1#![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#[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#[derive(Debug, Clone, PartialEq)]
48pub struct ToolSpec {
49 pub name: String,
51 pub description: String,
52 pub parameters: Value,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub enum Access {
59 Read,
61 Write,
63 Network,
65 Execute,
67}
68
69pub struct ToolContext<'a> {
71 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 turn: Option<&'a str>,
84}
85
86#[derive(Debug, Clone, Default, PartialEq, Eq)]
90pub struct EnvPlan {
91 pub container: Option<bool>,
94 pub project: Option<bool>,
97 pub image: Option<String>,
99 pub providers: Option<EnvProviders>,
102}
103
104#[derive(Debug, Clone, Default, PartialEq, Eq)]
106pub struct EnvProviders {
107 pub off: Vec<String>,
109 pub external: Vec<CommandEnv>,
111}
112
113#[derive(Debug, Clone, Default, PartialEq, Eq)]
117pub struct CommandEnv {
118 pub id: String,
120 pub label: String,
122 pub detect: Vec<String>,
123 pub inputs: Vec<String>,
125 pub program: PathBuf,
126 pub args: Vec<String>,
127 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 #[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 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 #[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 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 #[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 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 #[must_use]
184 pub fn with_env(mut self, plan: &'a EnvPlan) -> Self {
185 self.env = Some(plan);
186 self
187 }
188
189 pub fn env(&self) -> EnvPlan {
191 self.env.cloned().unwrap_or_default()
192 }
193
194 #[must_use]
196 pub fn with_asker(mut self, asker: &'a dyn Asker) -> Self {
197 self.asker = Some(asker);
198 self
199 }
200
201 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 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 #[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 #[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 #[must_use]
243 pub fn with_journal(mut self, journal: &'a Journal) -> Self {
244 self.journal = Some(journal);
245 self
246 }
247
248 pub fn journal(&self) -> Option<&'a Journal> {
252 self.journal
253 }
254
255 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 pub fn cancel_flag(&self) -> &AtomicBool {
268 self.cancel
269 }
270}
271
272#[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#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct Question {
286 pub title: String,
288 pub text: String,
290 pub warning: Option<String>,
292 pub access: Access,
295 pub always_ask: bool,
297}
298
299#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub enum Answer {
302 Yes,
304 No,
306 AutoYes,
308 AutoNo,
310}
311
312impl Answer {
313 pub fn allowed(self) -> bool {
314 matches!(self, Self::Yes | Self::AutoYes)
315 }
316
317 pub fn by_user(self) -> bool {
319 matches!(self, Self::Yes | Self::No)
320 }
321}
322
323pub trait Asker: Send + Sync {
325 fn ask(&self, q: &Question) -> Answer;
326
327 fn ask_user(&self, q: &UserQuestion) -> UserReply {
330 let _ = q;
331 UserReply::NoOne
332 }
333}
334
335#[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#[derive(Debug, Clone, PartialEq, Eq)]
346pub enum UserReply {
347 Answered(String),
349 Skipped,
351 NoOne,
353}
354
355pub trait EnvControl: Send + Sync {
359 fn describe(&self, ws: &Path, plan: &EnvPlan) -> byob_protocol::WorkspaceEnv;
361 fn apply(&self, ws: &Path, action: &byob_protocol::EnvAction) -> Result<String, String>;
363 fn support(&self) -> byob_protocol::EnvSupport;
365 fn check_containers(&self) -> Result<String, String>;
367 fn forget(&self, ws: &Path) -> Result<String, String>;
370}
371
372#[derive(Debug, Clone, Default, PartialEq)]
374pub struct ToolOutput {
375 pub text: String,
376 pub failed: bool,
378 pub changes: Vec<FileChange>,
379 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 fn title(&self, args: &Value) -> String;
399
400 fn pending_title(&self, _args: &Value) -> String {
403 format!("Run {}", self.spec().name)
404 }
405
406 fn preview(&self, args: &Value, _workspace: &Path) -> Option<Preview> {
409 Some(preview::args(args))
410 }
411
412 fn access(&self, args: &Value) -> Access;
414
415 fn always_ask(&self, _args: &Value) -> Option<String> {
419 None
420 }
421
422 fn card(&self, _args: &Value) -> Option<Card> {
425 None
426 }
427
428 fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput;
430
431 fn concurrent(&self) -> bool {
435 false
436 }
437
438 fn repeatable(&self, _args: &Value) -> bool {
441 false
442 }
443}
444
445pub 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#[derive(Default, Clone)]
452pub struct Registry {
453 tools: BTreeMap<String, Arc<dyn Tool>>,
454}
455
456impl Registry {
457 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 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
484pub fn register_builtins(reg: &mut Registry) {
488 register_builtins_with(reg, &ArtifactTypes::builtin());
489}
490
491pub 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
510pub 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}