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
41// Feature unification only (cargo-hakari); keeps the unused-dependency lint quiet.
42use workspace_hack as _;
43
44use std::sync::Arc;
45
46use aidaemon_core::Tool;
47
48pub mod backend;
49pub mod background_deliverable;
50pub mod backoff;
51pub mod check_environment;
52mod checklist;
53#[cfg(feature = "checkpoints")]
54pub mod checkpoints;
55pub mod cli_agent_flags;
56pub mod command_effects;
57pub mod command_risk;
58pub mod config_file;
59pub mod daemon_guard;
60pub mod duration_format;
61mod exec;
62pub mod execution;
63pub mod file_delivery;
64mod fs;
65pub mod fs_utils;
66pub mod git_guard;
67pub mod http_request;
68pub mod internal_markers;
69pub mod local_backend;
70pub mod local_sites;
71pub mod outcome;
72pub mod owner_answers;
73pub mod path_class;
74pub mod permission_bypass;
75pub mod platform_shell;
76pub mod process_control;
77pub mod result_spill;
78pub mod sanitize;
79mod search;
80mod search_files;
81#[cfg(test)]
82mod search_files_tests;
83pub mod semantics;
84pub mod services;
85mod shell;
86pub mod shown;
87#[cfg(feature = "sqlite")]
88pub mod sqlite_schema;
89pub mod status;
90pub mod stt_setup;
91pub mod system;
92#[cfg(any(test, feature = "testing"))]
93pub mod testing;
94pub mod text;
95pub mod tls;
96mod util;
97pub mod web;
98pub mod web_search;
99mod workspace;
100
101#[cfg(test)]
102mod testutil;
103
104pub use backend::{
105    BackendDirEntry, BackendFileType, BackendKind, BackendMetadata, BackendPath, CommandSpec,
106    ExecutionBackend, ExecutionOutput, ExecutionRequest, LexicalPaths, ProcessHandle,
107    SpawnedProcess, WriteMode, shell_quote,
108};
109pub use checklist::{Checklist, ChecklistGate, ChecklistItem, ChecklistState, ItemStatus};
110pub use exec::{
111    BubblewrapSandbox, BubblewrapScope, CommandOutput, DockerSandbox, ExecError, HOME_SECRET_PATHS,
112    LocalSandbox, SANDBOX_ENV, Sandbox, SandboxCommand, SandboxKind, SandboxSelection,
113    SeatbeltSandbox, TerminalConfinement, best_available_sandbox, default_deny_read,
114    home_secret_paths, sandbox_preference_from_env, select_sandbox,
115};
116pub use fs::{
117    DEFAULT_IGNORE_DIRS, EditFile, FilePolicy, HostFilePolicy, HostFilePolicySettings,
118    MAX_READ_CHARS, ProtectedPathGuard, ReadFile, ToolText, WorkspaceBackend, WorkspaceFilePolicy,
119    WriteFile, format_with_line_numbers, render_read_file_output, render_read_file_output_within,
120};
121pub use outcome::{
122    CallValidator, KernelAdapter, NothingSentError, OutcomeRunner, OutcomeTool, TargetNotFound,
123    ToolTimedOut, failed_without_effect, timed_out,
124};
125pub use path_class::PathClassifier;
126pub use search::{Glob, Grep};
127pub use search_files::SearchFiles;
128pub use shell::{DEFAULT_ENV_ALLOWLIST, Shell};
129pub use util::sniff_image_mime;
130pub use web::{NetworkGuard, WebFetch};
131pub use workspace::{PathError, Workspace};
132
133/// The standard set: `read_file`, `write_file`, `edit_file`, `glob`, `grep`,
134/// `shell` (with [`best_available_sandbox`]: bubblewrap on Linux, seatbelt
135/// on macOS) and `web_fetch`.
136///
137/// `track_requirements` is not included because it is only useful together
138/// with its stop hook; add both with [`Checklist::with_gate`].
139pub fn default_tools(workspace: Workspace) -> Vec<Arc<dyn Tool>> {
140    default_tools_with_sandbox(workspace, best_available_sandbox())
141}
142
143/// [`default_tools`] with the shell on an explicit backend, for example
144/// `SandboxKind::Local.backend()` to run commands on the host on purpose.
145pub fn default_tools_with_sandbox(
146    workspace: Workspace,
147    sandbox: Arc<dyn Sandbox>,
148) -> Vec<Arc<dyn Tool>> {
149    vec![
150        Arc::new(ReadFile::new(workspace.clone())),
151        Arc::new(WriteFile::new(workspace.clone())),
152        Arc::new(EditFile::new(workspace.clone())),
153        Arc::new(Glob::new(workspace.clone())),
154        Arc::new(Grep::new(workspace.clone())),
155        Arc::new(Shell::new(workspace, sandbox)),
156        Arc::new(WebFetch::new()),
157    ]
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn default_set_has_strict_unique_specs() {
166        let (_d, ws) = testutil::ws();
167        let tools = default_tools(ws);
168        let mut names: Vec<String> = tools.iter().map(|t| t.spec().name).collect();
169        names.push(Checklist::default().spec().name);
170        let mut sorted = names.clone();
171        sorted.sort();
172        sorted.dedup();
173        assert_eq!(sorted.len(), names.len());
174        for tool in tools
175            .iter()
176            .cloned()
177            .chain([Arc::new(Checklist::default()) as Arc<dyn Tool>])
178        {
179            let spec = tool.spec();
180            assert!(!spec.description.is_empty(), "{}", spec.name);
181            assert_eq!(spec.parameters["type"], "object", "{}", spec.name);
182            assert_eq!(
183                spec.parameters["additionalProperties"],
184                serde_json::json!(false),
185                "{}",
186                spec.name
187            );
188            // Every required key is a declared property.
189            for key in spec.parameters["required"].as_array().unwrap() {
190                assert!(
191                    spec.parameters["properties"]
192                        .get(key.as_str().unwrap())
193                        .is_some(),
194                    "{}: {key}",
195                    spec.name
196                );
197            }
198        }
199        let read_only: Vec<bool> = tools.iter().map(|t| t.annotations().read_only).collect();
200        assert_eq!(read_only, [true, false, false, true, true, false, true]);
201    }
202}