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;
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#[derive(Debug, Clone, PartialEq)]
39pub struct ToolSpec {
40 pub name: String,
42 pub description: String,
43 pub parameters: Value,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub enum Access {
50 Read,
52 Write,
54 Network,
56 Execute,
58}
59
60pub struct ToolContext<'a> {
62 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 turn: Option<&'a str>,
75}
76
77#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct EnvPlan {
82 pub container: Option<bool>,
85 pub project: Option<bool>,
88 pub image: Option<String>,
90 pub providers: Option<EnvProviders>,
93}
94
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
97pub struct EnvProviders {
98 pub off: Vec<String>,
100 pub external: Vec<CommandEnv>,
102}
103
104#[derive(Debug, Clone, Default, PartialEq, Eq)]
108pub struct CommandEnv {
109 pub id: String,
111 pub label: String,
113 pub detect: Vec<String>,
114 pub inputs: Vec<String>,
116 pub program: PathBuf,
117 pub args: Vec<String>,
118 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 #[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 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 #[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 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 #[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 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 #[must_use]
175 pub fn with_env(mut self, plan: &'a EnvPlan) -> Self {
176 self.env = Some(plan);
177 self
178 }
179
180 pub fn env(&self) -> EnvPlan {
182 self.env.cloned().unwrap_or_default()
183 }
184
185 #[must_use]
187 pub fn with_asker(mut self, asker: &'a dyn Asker) -> Self {
188 self.asker = Some(asker);
189 self
190 }
191
192 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 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 #[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 #[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 #[must_use]
234 pub fn with_journal(mut self, journal: &'a Journal) -> Self {
235 self.journal = Some(journal);
236 self
237 }
238
239 pub fn journal(&self) -> Option<&'a Journal> {
243 self.journal
244 }
245
246 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 pub fn cancel_flag(&self) -> &AtomicBool {
259 self.cancel
260 }
261}
262
263#[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#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct Question {
277 pub title: String,
279 pub text: String,
281 pub warning: Option<String>,
283 pub access: Access,
286 pub always_ask: bool,
288}
289
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum Answer {
293 Yes,
295 No,
297 AutoYes,
299 AutoNo,
301}
302
303impl Answer {
304 pub fn allowed(self) -> bool {
305 matches!(self, Self::Yes | Self::AutoYes)
306 }
307
308 pub fn by_user(self) -> bool {
310 matches!(self, Self::Yes | Self::No)
311 }
312}
313
314pub trait Asker: Send + Sync {
316 fn ask(&self, q: &Question) -> Answer;
317
318 fn ask_user(&self, q: &UserQuestion) -> UserReply {
321 let _ = q;
322 UserReply::NoOne
323 }
324}
325
326#[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#[derive(Debug, Clone, PartialEq, Eq)]
337pub enum UserReply {
338 Answered(String),
340 Skipped,
342 NoOne,
344}
345
346pub trait EnvControl: Send + Sync {
350 fn describe(&self, ws: &Path, plan: &EnvPlan) -> byob_protocol::WorkspaceEnv;
352 fn apply(&self, ws: &Path, action: &byob_protocol::EnvAction) -> Result<String, String>;
354 fn support(&self) -> byob_protocol::EnvSupport;
356 fn check_containers(&self) -> Result<String, String>;
358 fn forget(&self, ws: &Path) -> Result<String, String>;
361}
362
363#[derive(Debug, Clone, Default, PartialEq)]
365pub struct ToolOutput {
366 pub text: String,
367 pub failed: bool,
369 pub changes: Vec<FileChange>,
370 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 fn title(&self, args: &Value) -> String;
390
391 fn pending_title(&self, _args: &Value) -> String {
394 format!("Run {}", self.spec().name)
395 }
396
397 fn preview(&self, args: &Value, _workspace: &Path) -> Option<Preview> {
400 Some(preview::args(args))
401 }
402
403 fn access(&self, args: &Value) -> Access;
405
406 fn always_ask(&self, _args: &Value) -> Option<String> {
410 None
411 }
412
413 fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput;
415
416 fn concurrent(&self) -> bool {
420 false
421 }
422
423 fn repeatable(&self, _args: &Value) -> bool {
426 false
427 }
428}
429
430pub 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#[derive(Default, Clone)]
437pub struct Registry {
438 tools: BTreeMap<String, Arc<dyn Tool>>,
439}
440
441impl Registry {
442 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 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
469pub fn register_builtins(reg: &mut Registry) {
473 register_builtins_with(reg, &ArtifactTypes::builtin());
474}
475
476pub 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
495pub 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}