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