Skip to main content

byob_tools/
lib.rs

1//! The tool interface. Everything the model can call — built-in file tools, plugin
2//! skills, Python tools, MCP server tools — implements [`Tool`] and is collected in a
3//! [`Registry`]. The agent loop (`byob-agent`) owns calling them, the permission gate, and
4//! approvals; tools only describe themselves and do the work.
5//!
6//! Tools are synchronous and run on the turn's worker thread. Long-running tools should
7//! poll [`ToolContext::cancelled`].
8#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
9
10pub mod artifact;
11pub mod artifact_types;
12pub mod chart;
13pub mod edits;
14mod fs;
15pub mod images;
16pub mod plan;
17pub mod preview;
18pub mod sandbox;
19pub mod undo;
20
21pub use artifact::{CreateArtifact, ReadArtifact, UpdateArtifact};
22pub use artifact_types::{ArtifactHooks, ArtifactType, ArtifactTypes};
23pub use chart::MakeChart;
24pub use fs::{DEFAULT_TRASH_DIR, DeleteFile, EditFile, ListFiles, LookAtImage, MoveFile, MoveFiles, ReadFile, SearchFiles, WriteFile};
25pub use plan::{AskUser, UpdatePlan};
26pub use preview::Preview;
27pub use undo::{Journal, UndoOp};
28
29use std::collections::BTreeMap;
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32use std::sync::atomic::{AtomicBool, Ordering};
33
34use serde::de::DeserializeOwned;
35use serde_json::Value;
36
37/// What the model sees: name, description, JSON Schema for the arguments.
38#[derive(Debug, Clone, PartialEq)]
39pub struct ToolSpec {
40    /// `[a-zA-Z0-9_-]{1,64}` — the constraint OpenAI-compatible servers enforce.
41    pub name: String,
42    pub description: String,
43    /// JSON Schema object describing the arguments.
44    pub parameters: Value,
45}
46
47/// What a call does, for the permission gate. Ordered from least to most dangerous.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub enum Access {
50    /// Reads inside the workspace only.
51    Read,
52    /// Creates, modifies, moves or deletes files.
53    Write,
54    /// Talks to the network.
55    Network,
56    /// Runs code or external programs.
57    Execute,
58}
59
60/// Per-call environment provided by the agent.
61pub struct ToolContext<'a> {
62    /// Root folder the tool may touch. File tools must refuse paths outside it.
63    pub workspace: &'a Path,
64    cancel: &'a AtomicBool,
65    journal: Option<&'a Journal>,
66    chat: Option<&'a str>,
67    asker: Option<&'a dyn Asker>,
68    env: Option<&'a EnvPlan>,
69    host: Option<&'a (dyn std::any::Any + Sync)>,
70    views: Option<&'a std::sync::Mutex<Vec<byob_protocol::View>>>,
71    images: Option<&'a std::sync::Mutex<Vec<String>>>,
72    /// The request (turn) this call is part of: saves of one artifact within it make one
73    /// version ([`crate::artifact::SaveBytes::turn`]).
74    turn: Option<&'a str>,
75}
76
77/// Where a chat's commands run, as its workspace and chat settings decide (the engine
78/// resolves them; see `byob_types::config`). The default leaves everything to the answers
79/// the user gave for the folder (asked once).
80#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct EnvPlan {
82    /// In the workspace's container (`Some(true)`), on this machine (`Some(false)`), or as
83    /// the user answered for the folder (`None`). Chosen in the settings, so never asked.
84    pub container: Option<bool>,
85    /// Load the folder's project environment (flake.nix, …) without asking (`Some(true)`),
86    /// never (`Some(false)`), or as answered (`None`).
87    pub project: Option<bool>,
88    /// The container's image; `None`: the folder's devcontainer.json, else the default.
89    pub image: Option<String>,
90    /// The environment providers the chat's plugins switch on (`None`: every one byob has;
91    /// see `byob_exec::env::EnvProvider`).
92    pub providers: Option<EnvProviders>,
93}
94
95/// Which workspace environment providers a chat uses.
96#[derive(Debug, Clone, Default, PartialEq, Eq)]
97pub struct EnvProviders {
98    /// Registered providers left out, by id (byob's own: `nix`, `pixi`, `mise`, `container`).
99    pub off: Vec<String>,
100    /// Command providers plugins declare (`environments` in a manifest).
101    pub external: Vec<CommandEnv>,
102}
103
104/// A plugin's environment provider: when the workspace has one of `detect`, run `program`
105/// with `args` in it (sandboxed, with network) and read the environment it prints as JSON
106/// (`{"PATH": "...", "NAME": "value"}`, or pixi's `{"environment_variables": {...}}`).
107#[derive(Debug, Clone, Default, PartialEq, Eq)]
108pub struct CommandEnv {
109    /// Unique among providers (names the cache file): `<plugin>-<id>`.
110    pub id: String,
111    /// For messages: "conda environment".
112    pub label: String,
113    pub detect: Vec<String>,
114    /// Files whose contents key the cache (besides `detect`).
115    pub inputs: Vec<String>,
116    pub program: PathBuf,
117    pub args: Vec<String>,
118    /// The plugin's folder (readable by the run).
119    pub dir: PathBuf,
120}
121
122impl<'a> ToolContext<'a> {
123    pub fn new(workspace: &'a Path, cancel: &'a AtomicBool) -> Self {
124        Self { workspace, cancel, journal: None, chat: None, asker: None, env: None, host: None, views: None, images: None, turn: None }
125    }
126
127    /// Where [`ToolContext::attach_view`] puts views (the engine's turn: on the call's step).
128    #[must_use]
129    pub fn with_views(mut self, views: &'a std::sync::Mutex<Vec<byob_protocol::View>>) -> Self {
130        self.views = Some(views);
131        self
132    }
133
134    /// Show `view` on this call's step (e.g. an MCP App). `false` if nobody takes views.
135    pub fn attach_view(&self, view: byob_protocol::View) -> bool {
136        let Some(v) = self.views else { return false };
137        v.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(view);
138        true
139    }
140
141    /// Where [`ToolContext::show_image`] puts images (the engine's turn).
142    #[must_use]
143    pub fn with_images(mut self, images: &'a std::sync::Mutex<Vec<String>>) -> Self {
144        self.images = Some(images);
145        self
146    }
147
148    /// Show the model an image (a `data:image/...;base64,` URL, already downscaled) with
149    /// this call's result. The turn hands it to the chat's model if that can see, else asks
150    /// the `vision` model role about it (the call's `question` argument) and adds the answer
151    /// to the result. Only this turn sees it; later turns see the result text alone.
152    /// `false` if nobody takes images.
153    pub fn show_image(&self, url: String) -> bool {
154        let Some(i) = self.images else { return false };
155        i.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(url);
156        true
157    }
158
159    /// What the program running the tool offers beyond this context (the engine's turn
160    /// offers a handle to start child turns; see `byob_agent`'s `delegate`). Tools that need
161    /// it look it up by type with [`ToolContext::host`].
162    #[must_use]
163    pub fn with_host(mut self, host: &'a (dyn std::any::Any + Sync)) -> Self {
164        self.host = Some(host);
165        self
166    }
167
168    /// The host capability of type `T`, if the caller offered one.
169    pub fn host<T: 'static>(&self) -> Option<&'a T> {
170        self.host.and_then(|h| (h as &dyn std::any::Any).downcast_ref::<T>())
171    }
172
173    /// Run commands where `plan` says (see [`EnvPlan`]).
174    #[must_use]
175    pub fn with_env(mut self, plan: &'a EnvPlan) -> Self {
176        self.env = Some(plan);
177        self
178    }
179
180    /// Where this chat's commands run (the default when the engine didn't say).
181    pub fn env(&self) -> EnvPlan {
182        self.env.cloned().unwrap_or_default()
183    }
184
185    /// Let the tool ask the user questions while it runs (see [`ToolContext::ask`]).
186    #[must_use]
187    pub fn with_asker(mut self, asker: &'a dyn Asker) -> Self {
188        self.asker = Some(asker);
189        self
190    }
191
192    /// Ask the user `q` (an approval card), blocking until answered. Without anyone to ask
193    /// (no asker: tests, direct calls) the answer is [`Answer::AutoNo`].
194    pub fn ask(&self, q: &Question) -> Answer {
195        if self.cancelled() {
196            return Answer::AutoNo;
197        }
198        self.asker.map_or(Answer::AutoNo, |a| a.ask(q))
199    }
200
201    /// Ask the user `q` on a question card, blocking until they answer (see
202    /// [`Asker::ask_user`]). [`UserReply::NoOne`] without an asker.
203    pub fn ask_user(&self, q: &UserQuestion) -> UserReply {
204        if self.cancelled() {
205            return UserReply::NoOne;
206        }
207        self.asker.map_or(UserReply::NoOne, |a| a.ask_user(q))
208    }
209
210    /// The chat this call runs in (artifacts belong to a chat).
211    #[must_use]
212    pub fn with_chat(mut self, chat: &'a str) -> Self {
213        self.chat = Some(chat);
214        self
215    }
216
217    pub fn chat(&self) -> Option<&'a str> {
218        self.chat
219    }
220
221    /// Part of request (turn) `turn`.
222    #[must_use]
223    pub fn with_turn(mut self, turn: &'a str) -> Self {
224        self.turn = Some(turn);
225        self
226    }
227
228    pub fn turn(&self) -> Option<&'a str> {
229        self.turn
230    }
231
232    /// Record undo information for this call's file changes in `journal`.
233    #[must_use]
234    pub fn with_journal(mut self, journal: &'a Journal) -> Self {
235        self.journal = Some(journal);
236        self
237    }
238
239    /// The turn's undo journal, if it keeps one. Tools that change files record an
240    /// [`UndoOp`] per change, and back up a file with [`Journal::backup`] before
241    /// overwriting it.
242    pub fn journal(&self) -> Option<&'a Journal> {
243        self.journal
244    }
245
246    /// Shorthand: record `op` if there is a journal.
247    pub fn record(&self, op: UndoOp) {
248        if let Some(j) = self.journal {
249            j.record(op);
250        }
251    }
252
253    pub fn cancelled(&self) -> bool {
254        self.cancel.load(Ordering::Relaxed)
255    }
256
257    /// The turn's cancel flag, for APIs that poll it themselves (e.g. MCP calls).
258    pub fn cancel_flag(&self) -> &AtomicBool {
259        self.cancel
260    }
261}
262
263/// A file-system effect of a call, reported for the UI and the undo journal.
264#[derive(Debug, Clone, PartialEq, Eq)]
265pub enum FileChange {
266    Created(PathBuf),
267    Modified(PathBuf),
268    Deleted(PathBuf),
269    Moved { from: PathBuf, to: PathBuf },
270}
271
272/// A question a tool asks the user while it runs, e.g. "Load this workspace's Nix dev
273/// shell?". Shown as an approval card with only Allow and Deny: the tool remembers the
274/// answer itself, so "always allow" grants don't apply.
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct Question {
277    /// Phrased like a pending title: "Load the workspace's Nix dev shell (flake.nix)".
278    pub title: String,
279    /// What saying yes means, for the card (a few short lines).
280    pub text: String,
281    /// Shown prominently, e.g. "installs system-wide".
282    pub warning: Option<String>,
283    /// Decides who answers: the permission policy for this level may answer for the user
284    /// (e.g. `--auto-approve`), unless [`Question::always_ask`].
285    pub access: Access,
286    /// Only a person may say yes: not the policy, not `--auto-approve`.
287    pub always_ask: bool,
288}
289
290/// The answer to a [`Question`].
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum Answer {
293    /// A person said yes.
294    Yes,
295    /// A person said no.
296    No,
297    /// The policy allowed it without asking (`--auto-approve`).
298    AutoYes,
299    /// Nobody was asked: the policy refused, the turn stopped, or there's no one to ask.
300    AutoNo,
301}
302
303impl Answer {
304    pub fn allowed(self) -> bool {
305        matches!(self, Self::Yes | Self::AutoYes)
306    }
307
308    /// A person answered (worth remembering).
309    pub fn by_user(self) -> bool {
310        matches!(self, Self::Yes | Self::No)
311    }
312}
313
314/// Puts a [`Question`] to the user; the agent provides one per call.
315pub trait Asker: Send + Sync {
316    fn ask(&self, q: &Question) -> Answer;
317
318    /// Put a [`UserQuestion`] to the user (a question card), blocking until answered.
319    /// Only a person answers it. The default: nobody to ask.
320    fn ask_user(&self, q: &UserQuestion) -> UserReply {
321        let _ = q;
322        UserReply::NoOne
323    }
324}
325
326/// A question the model asks the user (`ask_user`): a card with the options as buttons and,
327/// with `free_text`, a field for their own answer.
328#[derive(Debug, Clone, PartialEq, Eq)]
329pub struct UserQuestion {
330    pub question: String,
331    pub options: Vec<String>,
332    pub free_text: bool,
333}
334
335/// The answer to a [`UserQuestion`].
336#[derive(Debug, Clone, PartialEq, Eq)]
337pub enum UserReply {
338    /// The option picked or the text typed.
339    Answered(String),
340    /// The user closed the card without answering.
341    Skipped,
342    /// Nobody answered: the turn stopped, or there is no one to ask.
343    NoOne,
344}
345
346/// Workspace environment settings the engine shows to clients and lets them change
347/// (provided by the code-running tools, `byob-exec`). Calls may block for a while
348/// (stopping a container): the engine makes them off its own thread.
349pub trait EnvControl: Send + Sync {
350    /// The settings and state of workspace `ws`, whose settings say `plan`.
351    fn describe(&self, ws: &Path, plan: &EnvPlan) -> byob_protocol::WorkspaceEnv;
352    /// Change them; returns what happened, for the user.
353    fn apply(&self, ws: &Path, action: &byob_protocol::EnvAction) -> Result<String, String>;
354    /// What this machine offers (Nix, a container runtime). Cheap.
355    fn support(&self) -> byob_protocol::EnvSupport;
356    /// Whether the container runtime answers; the error says what to do. May take seconds.
357    fn check_containers(&self) -> Result<String, String>;
358    /// Forget everything byob keeps for `ws` outside the folder: its answers, installed
359    /// packages and container. The folder itself is never touched. May take seconds.
360    fn forget(&self, ws: &Path) -> Result<String, String>;
361}
362
363/// Result of a call. `text` goes back to the model; keep it bounded.
364#[derive(Debug, Clone, Default, PartialEq)]
365pub struct ToolOutput {
366    pub text: String,
367    /// The call failed; `text` explains why (the model sees it and can recover).
368    pub failed: bool,
369    pub changes: Vec<FileChange>,
370    /// Images for the model to look at (`data:` URLs, see [`images::for_model`]). They go to
371    /// the model after the round's tool results, in a message of their own.
372    pub images: Vec<String>,
373}
374
375impl ToolOutput {
376    pub fn ok(text: impl Into<String>) -> Self {
377        Self { text: text.into(), ..Default::default() }
378    }
379
380    pub fn err(text: impl Into<String>) -> Self {
381        Self { text: text.into(), failed: true, ..Default::default() }
382    }
383}
384
385pub trait Tool: Send + Sync {
386    fn spec(&self) -> ToolSpec;
387
388    /// Short human title for the finished call, e.g. "Wrote notes.md". `args` is untrusted.
389    fn title(&self, args: &Value) -> String;
390
391    /// Title for the call before and while it runs, and on approval cards, e.g.
392    /// "Write notes.md". Defaults to "Run <tool name>".
393    fn pending_title(&self, _args: &Value) -> String {
394        format!("Run {}", self.spec().name)
395    }
396
397    /// A readable account of what the call would do, for approval cards: e.g. a diff for a
398    /// file write. Reads only, no side effects; bounded. Defaults to the key arguments.
399    fn preview(&self, args: &Value, _workspace: &Path) -> Option<Preview> {
400        Some(preview::args(args))
401    }
402
403    /// What this call would do; drives the permission gate. Must not have side effects.
404    fn access(&self, args: &Value) -> Access;
405
406    /// `Some(warning)` if this call must be approved by a person every time: no policy,
407    /// "always allow" grant or `--auto-approve` lets it run (e.g. installing system-wide).
408    /// The warning is shown on the approval card.
409    fn always_ask(&self, _args: &Value) -> Option<String> {
410        None
411    }
412
413    /// Do it. `args` is untrusted model output: validate everything, never panic.
414    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput;
415
416    /// Calls of this tool start before the other calls of the same round and run side by
417    /// side, each on a thread of its own (results still go back in call order). For tools
418    /// that mostly wait, like `delegate`.
419    fn concurrent(&self) -> bool {
420        false
421    }
422
423    /// The same call can mean something new each time, so the turn's repeat guard ("you
424    /// already called this") lets it through: reads of state that changes, or undo.
425    fn repeatable(&self, _args: &Value) -> bool {
426        false
427    }
428}
429
430/// Parse tool arguments into a typed struct, with a model-readable error.
431pub fn parse_args<T: DeserializeOwned>(args: &Value) -> Result<T, String> {
432    serde_json::from_value(args.clone()).map_err(|e| format!("invalid arguments: {e}"))
433}
434
435/// Tools available to a turn, by name.
436#[derive(Default, Clone)]
437pub struct Registry {
438    tools: BTreeMap<String, Arc<dyn Tool>>,
439}
440
441impl Registry {
442    /// Add a tool. A later tool with the same name replaces the earlier one.
443    pub fn register(&mut self, tool: Arc<dyn Tool>) {
444        self.tools.insert(tool.spec().name, tool);
445    }
446
447    pub fn get(&self, name: &str) -> Option<&Arc<dyn Tool>> {
448        self.tools.get(name)
449    }
450
451    /// Take a tool out (a native tool whose plugin is off).
452    pub fn remove(&mut self, name: &str) -> Option<Arc<dyn Tool>> {
453        self.tools.remove(name)
454    }
455
456    pub fn specs(&self) -> Vec<ToolSpec> {
457        self.tools.values().map(|t| t.spec()).collect()
458    }
459
460    pub fn len(&self) -> usize {
461        self.tools.len()
462    }
463
464    pub fn is_empty(&self) -> bool {
465        self.tools.is_empty()
466    }
467}
468
469/// Add the built-in file tools (`list_files`, `read_file`, `search_files`, `write_file`,
470/// `edit_file`, `move_file`, `move_files`, `delete_file`), `make_chart` and the artifact tools (for byob's own
471/// artifact types). Deleted files go to [`DEFAULT_TRASH_DIR`].
472pub fn register_builtins(reg: &mut Registry) {
473    register_builtins_with(reg, &ArtifactTypes::builtin());
474}
475
476/// [`register_builtins`], with the artifact tools using `types` (the engine's registry).
477pub fn register_builtins_with(reg: &mut Registry, types: &ArtifactTypes) {
478    reg.register(Arc::new(ListFiles));
479    reg.register(Arc::new(ReadFile));
480    reg.register(Arc::new(SearchFiles));
481    reg.register(Arc::new(LookAtImage));
482    reg.register(Arc::new(WriteFile));
483    reg.register(Arc::new(EditFile));
484    reg.register(Arc::new(MoveFile));
485    reg.register(Arc::new(MoveFiles));
486    reg.register(Arc::new(DeleteFile::default()));
487    reg.register(Arc::new(MakeChart));
488    reg.register(Arc::new(CreateArtifact { types: types.clone() }));
489    reg.register(Arc::new(UpdateArtifact { types: types.clone() }));
490    reg.register(Arc::new(ReadArtifact { types: types.clone() }));
491    reg.register(Arc::new(UpdatePlan));
492    reg.register(Arc::new(AskUser));
493}
494
495/// A registry with just the built-in file tools.
496pub fn builtin() -> Registry {
497    let mut reg = Registry::default();
498    register_builtins(&mut reg);
499    reg
500}
501
502#[cfg(test)]
503mod tests {
504    use super::*;
505
506    struct Echo;
507
508    impl Tool for Echo {
509        fn spec(&self) -> ToolSpec {
510            ToolSpec {
511                name: "echo".into(),
512                description: "Echo text".into(),
513                parameters: serde_json::json!({"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}),
514            }
515        }
516        fn title(&self, _args: &Value) -> String {
517            "Echo".into()
518        }
519        fn access(&self, _args: &Value) -> Access {
520            Access::Read
521        }
522        fn run(&self, args: &Value, _ctx: &ToolContext<'_>) -> ToolOutput {
523            #[derive(serde::Deserialize)]
524            struct Args {
525                text: String,
526            }
527            match parse_args::<Args>(args) {
528                Ok(a) => ToolOutput::ok(a.text),
529                Err(e) => ToolOutput::err(e),
530            }
531        }
532    }
533
534    #[test]
535    fn registry_dispatch_and_bad_args() {
536        let mut reg = Registry::default();
537        reg.register(Arc::new(Echo));
538        let cancel = AtomicBool::new(false);
539        let ctx = ToolContext::new(Path::new("/tmp"), &cancel);
540        let tool = reg.get("echo").unwrap();
541        assert_eq!(tool.run(&serde_json::json!({"text":"hi"}), &ctx), ToolOutput::ok("hi"));
542        assert!(tool.run(&serde_json::json!({"nope":1}), &ctx).failed);
543        assert_eq!(reg.specs().len(), 1);
544    }
545
546    #[test]
547    fn builtins_are_valid() {
548        let reg = builtin();
549        assert_eq!(reg.len(), 15);
550        for spec in reg.specs() {
551            assert!(spec.name.len() <= 64 && spec.name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'));
552            assert_eq!(spec.parameters["type"], "object");
553            let tool = reg.get(&spec.name).unwrap();
554            let expected = if matches!(
555                spec.name.as_str(),
556                "list_files"
557                    | "read_file"
558                    | "search_files"
559                    | "look_at_image"
560                    | "make_chart"
561                    | "create_artifact"
562                    | "update_artifact"
563                    | "read_artifact"
564                    | "update_plan"
565                    | "ask_user"
566            ) {
567                Access::Read
568            } else {
569                Access::Write
570            };
571            assert_eq!(tool.access(&serde_json::json!({})), expected, "{}", spec.name);
572        }
573    }
574
575    #[test]
576    fn default_pending_title_and_preview() {
577        assert_eq!(Echo.pending_title(&serde_json::json!({})), "Run echo");
578        let p = Echo.preview(&serde_json::json!({"text": "hi"}), Path::new("/tmp"));
579        assert_eq!(p, Some(Preview::Args { fields: vec![("text".into(), "hi".into())], code: None, more: 0 }));
580    }
581
582    #[test]
583    fn access_is_ordered_by_danger() {
584        assert!(Access::Read < Access::Write && Access::Write < Access::Network && Access::Network < Access::Execute);
585    }
586}