Skip to main content

aidaemon_tools/
lib.rs

1//! # aidaemon-tools (experimental)
2//!
3//! A small default tool set for [`aidaemon_core`] agents, built on lessons
4//! from agent-computer interfaces (SWE-agent, Claude Code, Aider): few
5//! non-overlapping tools, bounded output, actionable errors, and validation
6//! before mutation.
7//!
8//! | Tool | Name | Annotations |
9//! |---|---|---|
10//! | [`ReadFile`] | `read_file` | read-only |
11//! | [`WriteFile`] | `write_file` | write (idempotent) |
12//! | [`EditFile`] | `edit_file` | write |
13//! | [`Glob`] | `glob` | read-only |
14//! | [`Grep`] | `grep` | read-only |
15//! | [`Shell`] | `shell` | destructive |
16//! | [`WebFetch`] | `web_fetch` | read-only |
17//! | [`Checklist`] | `track_requirements` | write (agent state only) |
18//!
19//! Every file tool is confined to a [`Workspace`]. The shell runs through a
20//! [`Sandbox`]; containment (sandboxing) lives there, while approval
21//! stays a policy concern for [`aidaemon_core::Hook`]s. No tool contains
22//! approval logic.
23//!
24//! ```no_run
25//! use aidaemon_tools::{default_tools, Checklist, Workspace};
26//! # fn demo(provider: impl aidaemon_core::Provider + 'static) -> Result<(), Box<dyn std::error::Error>> {
27//! let workspace = Workspace::new("./my-project")?;
28//! let (checklist, gate) = Checklist::with_gate();
29//! let mut builder = aidaemon_core::Agent::builder("coder").allow_unguarded()
30//!     .model("some-model")
31//!     .provider(provider)
32//!     .tool(checklist)
33//!     .hook(gate);
34//! for tool in default_tools(workspace) {
35//!     builder = builder.tool_arc(tool);
36//! }
37//! let agent = builder.build()?;
38//! # let _ = agent; Ok(()) }
39//! ```
40
41use std::sync::Arc;
42
43use aidaemon_core::Tool;
44
45pub mod backend;
46pub mod background_deliverable;
47pub mod backoff;
48pub mod check_environment;
49mod checklist;
50#[cfg(feature = "checkpoints")]
51pub mod checkpoints;
52pub mod cli_agent_flags;
53pub mod command_effects;
54pub mod command_risk;
55pub mod config_file;
56pub mod daemon_guard;
57pub mod duration_format;
58mod exec;
59pub mod execution;
60pub mod file_delivery;
61mod fs;
62pub mod fs_utils;
63pub mod git_guard;
64pub mod http_request;
65pub mod internal_markers;
66pub mod local_backend;
67pub mod local_sites;
68pub mod outcome;
69pub mod owner_answers;
70pub mod path_class;
71pub mod permission_bypass;
72pub mod platform_shell;
73pub mod process_control;
74pub mod result_spill;
75pub mod sanitize;
76mod search;
77mod search_files;
78#[cfg(test)]
79mod search_files_tests;
80pub mod semantics;
81pub mod services;
82mod shell;
83pub mod shown;
84pub mod status;
85pub mod stt_setup;
86pub mod system;
87#[cfg(any(test, feature = "testing"))]
88pub mod testing;
89pub mod text;
90pub mod tls;
91mod util;
92pub mod web;
93pub mod web_search;
94mod workspace;
95
96#[cfg(test)]
97mod testutil;
98
99pub use backend::{
100    BackendDirEntry, BackendFileType, BackendKind, BackendMetadata, BackendPath, CommandSpec,
101    ExecutionBackend, ExecutionOutput, ExecutionRequest, LexicalPaths, ProcessHandle,
102    SpawnedProcess, WriteMode, shell_quote,
103};
104pub use checklist::{Checklist, ChecklistGate, ChecklistItem, ChecklistState, ItemStatus};
105pub use exec::{
106    BubblewrapSandbox, BubblewrapScope, CommandOutput, DockerSandbox, ExecError, HOME_SECRET_PATHS,
107    LocalSandbox, SANDBOX_ENV, Sandbox, SandboxCommand, SandboxKind, SandboxSelection,
108    SeatbeltSandbox, TerminalConfinement, best_available_sandbox, default_deny_read,
109    home_secret_paths, sandbox_preference_from_env, select_sandbox,
110};
111pub use fs::{
112    DEFAULT_IGNORE_DIRS, EditFile, FilePolicy, HostFilePolicy, HostFilePolicySettings,
113    MAX_READ_CHARS, ProtectedPathGuard, ReadFile, ToolText, WorkspaceBackend, WorkspaceFilePolicy,
114    WriteFile, format_with_line_numbers, render_read_file_output, render_read_file_output_within,
115};
116pub use outcome::{
117    CallValidator, KernelAdapter, NothingSentError, OutcomeRunner, OutcomeTool, TargetNotFound,
118    ToolTimedOut, failed_without_effect, timed_out,
119};
120pub use path_class::PathClassifier;
121pub use search::{Glob, Grep};
122pub use search_files::SearchFiles;
123pub use shell::{DEFAULT_ENV_ALLOWLIST, Shell};
124pub use util::sniff_image_mime;
125pub use web::{NetworkGuard, WebFetch};
126pub use workspace::{PathError, Workspace};
127
128/// The standard set: `read_file`, `write_file`, `edit_file`, `glob`, `grep`,
129/// `shell` (with [`best_available_sandbox`]: bubblewrap on Linux, seatbelt
130/// on macOS) and `web_fetch`.
131///
132/// `track_requirements` is not included because it is only useful together
133/// with its stop hook; add both with [`Checklist::with_gate`].
134pub fn default_tools(workspace: Workspace) -> Vec<Arc<dyn Tool>> {
135    default_tools_with_sandbox(workspace, best_available_sandbox())
136}
137
138/// [`default_tools`] with the shell on an explicit backend, for example
139/// `SandboxKind::Local.backend()` to run commands on the host on purpose.
140pub fn default_tools_with_sandbox(
141    workspace: Workspace,
142    sandbox: Arc<dyn Sandbox>,
143) -> Vec<Arc<dyn Tool>> {
144    vec![
145        Arc::new(ReadFile::new(workspace.clone())),
146        Arc::new(WriteFile::new(workspace.clone())),
147        Arc::new(EditFile::new(workspace.clone())),
148        Arc::new(Glob::new(workspace.clone())),
149        Arc::new(Grep::new(workspace.clone())),
150        Arc::new(Shell::new(workspace, sandbox)),
151        Arc::new(WebFetch::new()),
152    ]
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn default_set_has_strict_unique_specs() {
161        let (_d, ws) = testutil::ws();
162        let tools = default_tools(ws);
163        let mut names: Vec<String> = tools.iter().map(|t| t.spec().name).collect();
164        names.push(Checklist::default().spec().name);
165        let mut sorted = names.clone();
166        sorted.sort();
167        sorted.dedup();
168        assert_eq!(sorted.len(), names.len());
169        for tool in tools
170            .iter()
171            .cloned()
172            .chain([Arc::new(Checklist::default()) as Arc<dyn Tool>])
173        {
174            let spec = tool.spec();
175            assert!(!spec.description.is_empty(), "{}", spec.name);
176            assert_eq!(spec.parameters["type"], "object", "{}", spec.name);
177            assert_eq!(
178                spec.parameters["additionalProperties"],
179                serde_json::json!(false),
180                "{}",
181                spec.name
182            );
183            // Every required key is a declared property.
184            for key in spec.parameters["required"].as_array().unwrap() {
185                assert!(
186                    spec.parameters["properties"]
187                        .get(key.as_str().unwrap())
188                        .is_some(),
189                    "{}: {key}",
190                    spec.name
191                );
192            }
193        }
194        let read_only: Vec<bool> = tools.iter().map(|t| t.annotations().read_only).collect();
195        assert_eq!(read_only, [true, false, false, true, true, false, true]);
196    }
197}