pub mod delegate;
pub mod exec;
pub mod files;
pub mod memory;
#[cfg(feature = "agent86ui")]
pub mod render_ui;
pub mod sandbox;
pub mod search;
pub mod secret;
pub mod skills;
pub mod web;
use crate::types::{ToolCall, ToolResult, ToolSpec};
use sandbox::Executor;
use serde_json::{json, Map, Value};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolError {
InvalidArguments(Vec<String>),
Raised { exception: String, message: String },
}
impl ToolError {
fn raised(exception: &str, message: impl Into<String>) -> Self {
Self::Raised {
exception: exception.to_owned(),
message: message.into(),
}
}
pub fn editor(message: impl Into<String>) -> Self {
Self::raised("OSError", message)
}
pub fn io(error: &std::io::Error) -> Self {
let exception = match error.kind() {
std::io::ErrorKind::NotFound => "FileNotFoundError",
std::io::ErrorKind::PermissionDenied => "PermissionError",
std::io::ErrorKind::IsADirectory => "IsADirectoryError",
std::io::ErrorKind::NotADirectory => "NotADirectoryError",
_ => "OSError",
};
Self::raised(exception, error.to_string())
}
}
pub trait Tool: Send + Sync {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn side_effecting(&self) -> bool {
false
}
fn parallel_safe(&self) -> bool {
true
}
fn expands_secrets(&self) -> bool {
false
}
fn parameters(&self) -> Value;
fn preview(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
None
}
fn guarded_target(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
None
}
fn change(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<FileChange> {
None
}
fn preview_lexer(&self) -> Option<&'static str> {
None
}
fn execute(
&self,
args: &Map<String, Value>,
ctx: &ToolContext,
) -> Result<ToolResult, ToolError>;
fn spec(&self) -> ToolSpec {
ToolSpec {
name: self.name().to_owned(),
description: self.description().to_owned(),
parameters: self.parameters(),
side_effecting: self.side_effecting(),
}
}
fn run(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
let mut result = match self.execute(&call.arguments, ctx) {
Ok(result) => result,
Err(ToolError::InvalidArguments(errors)) => failure(
self.name(),
format!(
"Invalid arguments for '{}': {}",
self.name(),
errors.join("; ")
),
),
Err(ToolError::Raised { exception, message }) => {
failure(self.name(), format!("{exception}: {message}"))
}
};
if result.call_id.is_empty() {
result.call_id = call.id.clone();
}
if result.name.is_empty() {
result.name = self.name().to_owned();
}
result
}
}
pub const MAX_CHANGE_TEXT_BYTES: usize = 256 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileChange {
pub path: String,
pub old_text: Option<String>,
pub new_text: String,
pub line: Option<usize>,
}
impl FileChange {
pub fn capped(target: &Path, old_text: Option<&str>, new_text: &str) -> Option<Self> {
let over = |text: &str| text.len() > MAX_CHANGE_TEXT_BYTES;
if over(new_text) || old_text.is_some_and(over) {
return None;
}
Some(Self {
path: display_path(target),
old_text: old_text.map(str::to_owned),
new_text: new_text.to_owned(),
line: first_changed_line(old_text, new_text),
})
}
pub fn redacted(mut self, secrets: &crate::vault::SecretVault) -> Self {
if !secrets.is_empty() {
self.path = secrets.redact(&self.path);
self.old_text = self.old_text.map(|text| secrets.redact(&text));
self.new_text = secrets.redact(&self.new_text);
}
self
}
pub fn record(&self, metadata: &mut Map<String, Value>) {
metadata.insert("abs_path".to_owned(), json!(self.path));
metadata.insert("old_text".to_owned(), json!(self.old_text));
metadata.insert("new_text".to_owned(), json!(self.new_text));
metadata.insert("line".to_owned(), json!(self.line));
}
pub fn record_write(
target: &Path,
old_text: Option<&str>,
new_text: &str,
metadata: &mut Map<String, Value>,
) {
match Self::capped(target, old_text, new_text) {
Some(change) => change.record(metadata),
None => {
metadata.insert("abs_path".to_owned(), json!(display_path(target)));
metadata.insert(
"line".to_owned(),
json!(first_changed_line(old_text, new_text)),
);
}
}
}
pub fn from_metadata(metadata: &Map<String, Value>) -> Option<Self> {
Some(Self {
path: metadata.get("abs_path")?.as_str()?.to_owned(),
old_text: match metadata.get("old_text")? {
Value::Null => None,
value => Some(value.as_str()?.to_owned()),
},
new_text: metadata.get("new_text")?.as_str()?.to_owned(),
line: metadata
.get("line")
.and_then(Value::as_u64)
.and_then(|line| usize::try_from(line).ok()),
})
}
}
pub fn first_changed_line(old: Option<&str>, new: &str) -> Option<usize> {
let Some(old) = old else {
return Some(1);
};
if old == new {
return None;
}
let mut old_lines = old.split('\n');
let mut new_lines = new.split('\n');
let mut line: usize = 1;
loop {
match (old_lines.next(), new_lines.next()) {
(Some(a), Some(b)) if a == b => line += 1,
(Some(_), None) => return Some(line.saturating_sub(1).max(1)),
_ => return Some(line),
}
}
}
pub fn success(name: &str, content: String) -> ToolResult {
ToolResult {
call_id: String::new(),
name: name.to_owned(),
ok: true,
content,
error: None,
metadata: Map::new(),
}
}
pub fn failure(name: &str, error: String) -> ToolResult {
ToolResult {
call_id: String::new(),
name: name.to_owned(),
ok: false,
content: String::new(),
error: Some(error),
metadata: Map::new(),
}
}
pub struct Arguments<'a> {
args: &'a Map<String, Value>,
errors: Vec<String>,
}
impl<'a> Arguments<'a> {
pub fn new(args: &'a Map<String, Value>) -> Self {
Self {
args,
errors: Vec::new(),
}
}
pub fn string(&mut self, field: &str, default: Option<&str>) -> String {
match (self.args.get(field), default) {
(Some(Value::String(value)), _) => value.clone(),
(Some(_), _) => {
self.errors
.push(format!("{field}: Input should be a valid string"));
String::new()
}
(None, Some(default)) => default.to_owned(),
(None, None) => {
self.errors.push(format!("{field}: Field required"));
String::new()
}
}
}
pub fn optional_string(&mut self, field: &str) -> Option<String> {
match self.args.get(field) {
None | Some(Value::Null) => None,
Some(Value::String(value)) => Some(value.clone()),
Some(_) => {
self.errors
.push(format!("{field}: Input should be a valid string"));
None
}
}
}
pub fn string_list(&mut self, field: &str) -> Vec<String> {
match self.args.get(field) {
None | Some(Value::Null) => Vec::new(),
Some(Value::Array(items)) => {
let mut values = Vec::new();
for (index, item) in items.iter().enumerate() {
match item {
Value::String(text) => values.push(text.clone()),
_ => self
.errors
.push(format!("{field}.{index}: Input should be a valid string")),
}
}
values
}
Some(_) => {
self.errors
.push(format!("{field}: Input should be a valid list"));
Vec::new()
}
}
}
pub fn string_alias(&mut self, names: &[&str]) -> String {
match names.iter().find(|name| self.args.contains_key(**name)) {
Some(name) => self.string(name, None),
None => {
self.errors.push(format!("{}: Field required", names[0]));
String::new()
}
}
}
pub fn boolean(&mut self, field: &str, default: bool) -> bool {
const PLAIN: &str = "Input should be a valid boolean";
const UNINTERPRETABLE: &str = "Input should be a valid boolean, unable to interpret input";
let parsed = match self.args.get(field) {
None => return default,
Some(Value::Bool(flag)) => Ok(*flag),
Some(Value::Number(number)) => {
let value = number.as_f64().unwrap_or(f64::NAN);
if value == 0.0 {
Ok(false)
} else if value == 1.0 {
Ok(true)
} else if number.is_f64() && value.fract() != 0.0 {
Err(PLAIN)
} else {
Err(UNINTERPRETABLE)
}
}
Some(Value::String(text)) => match text.to_lowercase().as_str() {
"0" | "off" | "f" | "false" | "n" | "no" => Ok(false),
"1" | "on" | "t" | "true" | "y" | "yes" => Ok(true),
_ => Err(UNINTERPRETABLE),
},
Some(_) => Err(PLAIN),
};
parsed.unwrap_or_else(|message| {
self.errors.push(format!("{field}: {message}"));
default
})
}
pub fn string_map(&mut self, field: &str) -> Map<String, Value> {
match self.args.get(field) {
None => Map::new(),
Some(Value::Object(map)) => {
for (key, value) in map {
if !value.is_string() {
self.errors
.push(format!("{field}.{key}: Input should be a valid string"));
}
}
map.clone()
}
Some(_) => {
self.errors
.push(format!("{field}: Input should be a valid dictionary"));
Map::new()
}
}
}
pub fn integer(&mut self, field: &str, default: i64) -> i64 {
const PLAIN: &str = "Input should be a valid integer";
const UNPARSABLE: &str =
"Input should be a valid integer, unable to parse string as an integer";
let parsed = match self.args.get(field) {
None => return default,
Some(Value::Bool(flag)) => Ok(i64::from(*flag)),
Some(Value::Number(number)) => match (number.as_i64(), number.as_u64()) {
(Some(value), _) => Ok(value),
(None, Some(_)) => Ok(i64::MAX),
(None, None) => {
let value = number.as_f64().unwrap_or(f64::NAN);
if value.fract() != 0.0 {
Err("Input should be a valid integer, got a number with a fractional part")
} else if value.abs() > i64::MAX as f64 {
Err("Unable to parse input string as an integer, exceeded maximum size")
} else {
Ok(value as i64)
}
}
},
Some(Value::String(text)) => parse_python_int(text).ok_or(UNPARSABLE),
Some(_) => Err(PLAIN),
};
parsed.unwrap_or_else(|message| {
self.errors.push(format!("{field}: {message}"));
default
})
}
pub fn bounded_integer(&mut self, field: &str, default: i64, min: i64, max: i64) -> i64 {
let before = self.errors.len();
let value = self.integer(field, default);
if self.errors.len() > before {
return default;
}
if value < min {
self.errors.push(format!(
"{field}: Input should be greater than or equal to {min}"
));
default
} else if value > max {
self.errors.push(format!(
"{field}: Input should be less than or equal to {max}"
));
default
} else {
value
}
}
pub fn choice(&mut self, field: &str, choices: &[&str]) -> String {
match self.args.get(field) {
Some(Value::String(value)) if choices.contains(&value.as_str()) => value.clone(),
None => {
self.errors.push(format!("{field}: Field required"));
String::new()
}
Some(_) => {
let quoted: Vec<String> =
choices.iter().map(|choice| format!("'{choice}'")).collect();
let listed = match quoted.split_last() {
Some((last, rest)) if !rest.is_empty() => {
format!("{} or {last}", rest.join(", "))
}
_ => quoted.concat(),
};
self.errors
.push(format!("{field}: Input should be {listed}"));
String::new()
}
}
}
pub fn finish(self) -> Result<(), ToolError> {
if self.errors.is_empty() {
Ok(())
} else {
Err(ToolError::InvalidArguments(self.errors))
}
}
}
fn parse_python_int(text: &str) -> Option<i64> {
let text = text.trim();
let text = match text.split_once('.') {
Some((whole, zeros)) if !zeros.is_empty() && zeros.bytes().all(|b| b == b'0') => whole,
Some(_) => return None,
None => text,
};
let (negative, digits) = match text.as_bytes().first() {
Some(b'-') => (true, &text[1..]),
Some(b'+') => (false, &text[1..]),
_ => (false, text),
};
if digits.is_empty()
|| digits.starts_with('_')
|| digits.ends_with('_')
|| digits.contains("__")
|| !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')
{
return None;
}
let mut value: i64 = 0;
for digit in digits.bytes().filter(u8::is_ascii_digit) {
value = value
.saturating_mul(10)
.saturating_add(i64::from(digit - b'0'));
}
Some(if negative {
value.saturating_neg()
} else {
value
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SandboxPolicy {
workspace: PathBuf,
allow_paths: Vec<PathBuf>,
guarded_roots: Vec<PathBuf>,
pub max_output_chars: usize,
pub timeout: Duration,
pub env_passthrough: Vec<String>,
pub network: bool,
}
impl SandboxPolicy {
pub fn new(workspace: &Path) -> std::io::Result<Self> {
Ok(Self {
workspace: std::fs::canonicalize(workspace)?,
allow_paths: Vec::new(),
guarded_roots: Vec::new(),
max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
timeout: Duration::from_secs(30),
env_passthrough: Vec::new(),
network: true,
})
}
pub fn workspace(&self) -> &Path {
&self.workspace
}
pub fn rerooted(&self, root: &Path, keep: Vec<PathBuf>) -> std::io::Result<Self> {
let mut policy = self.clone();
policy.workspace = std::fs::canonicalize(root)?;
let allowed = std::mem::take(&mut policy.allow_paths);
policy.allow(allowed.into_iter().chain(keep));
Ok(policy)
}
pub fn allow(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
for root in roots {
if !root.starts_with(&self.workspace) && !self.allow_paths.contains(&root) {
self.allow_paths.push(root);
}
}
}
pub fn guard(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
for root in roots {
let root = resolve(&root);
if !self.guarded_roots.contains(&root) {
self.guarded_roots.push(root);
}
}
}
pub fn guarded(&self, target: &Path) -> bool {
if self
.allow_paths
.iter()
.chain(&self.guarded_roots)
.any(|root| target.starts_with(root))
{
return true;
}
let Ok(inside) = target.strip_prefix(&self.workspace) else {
return false;
};
let names: Vec<String> = inside
.components()
.take(2)
.filter_map(|component| match component {
Component::Normal(name) => Some(
name.to_string_lossy()
.trim_end_matches(['.', ' '])
.to_ascii_lowercase(),
),
_ => None,
})
.collect();
match names.as_slice() {
[first, ..] if first == ".agent86" => true,
[first, second] => first == ".claude" && second == "skills",
_ => false,
}
}
pub fn resolve_within(&self, path: &str) -> Result<PathBuf, ToolError> {
let candidate = resolve(&self.workspace.join(path));
let inside = std::iter::once(&self.workspace)
.chain(&self.allow_paths)
.any(|root| candidate.starts_with(root));
if inside {
Ok(candidate)
} else {
Err(ToolError::raised(
"PolicyError",
format!(
"Path '{path}' resolves outside the workspace jail ({}).",
display_path(&self.workspace)
),
))
}
}
pub fn root_of(&self, path: &Path) -> Option<&Path> {
std::iter::once(&self.workspace)
.chain(&self.allow_paths)
.find(|root| path.starts_with(root))
.map(PathBuf::as_path)
}
pub fn require_network(&self) -> Result<(), ToolError> {
if self.network {
Ok(())
} else {
Err(ToolError::raised(
"PolicyError",
"Network access is disabled by the sandbox policy.",
))
}
}
pub fn truncate(&self, text: String) -> String {
let length = text.chars().count();
if length <= self.max_output_chars {
return text;
}
let kept: String = text.chars().take(self.max_output_chars).collect();
format!(
"{kept}\n... [truncated {} bytes]",
length - self.max_output_chars
)
}
}
fn resolve(path: &Path) -> PathBuf {
resolve_following(path, 0)
}
const MAX_LINKS: usize = 40;
fn resolve_following(path: &Path, links: usize) -> PathBuf {
let mut resolved = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) | Component::RootDir => resolved.push(component),
Component::CurDir => {}
Component::ParentDir => {
resolved.pop();
}
Component::Normal(part) => {
resolved.push(part);
if let Ok(real) = std::fs::canonicalize(&resolved) {
resolved = real;
} else if links < MAX_LINKS {
if let Ok(target) = std::fs::read_link(&resolved) {
let base = resolved.parent().map(Path::to_path_buf).unwrap_or_default();
resolved = resolve_following(&base.join(target), links + 1);
}
}
}
}
}
resolved
}
fn redact_value(value: &mut Value, ctx: &ToolContext) {
match value {
Value::String(text) => *text = ctx.secrets.redact(text),
Value::Array(items) => items.iter_mut().for_each(|item| redact_value(item, ctx)),
Value::Object(map) => map.values_mut().for_each(|item| redact_value(item, ctx)),
_ => {}
}
}
pub fn plain_path(path: &Path) -> PathBuf {
PathBuf::from(display_path(path))
}
pub fn display_path(path: &Path) -> String {
let text = path.display().to_string();
if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
format!(r"\\{rest}")
} else if let Some(rest) = text.strip_prefix(r"\\?\") {
rest.to_owned()
} else {
text
}
}
pub trait EditorFiles: Send + Sync + std::fmt::Debug {
fn read_text(&self, path: &Path) -> Option<String>;
fn write_text(&self, path: &Path, content: &str) -> Option<Result<(), String>>;
}
#[derive(Debug, Clone)]
pub struct ToolContext {
pub policy: SandboxPolicy,
pub executor: Executor,
pub web: web::WebSettings,
pub memory: Option<crate::session::SessionStore>,
pub skills: Arc<crate::skills::Skills>,
active_skill: Arc<std::sync::Mutex<Option<Arc<crate::skills::Skill>>>>,
pub secrets: crate::vault::SecretVault,
pub editor: Option<Arc<dyn EditorFiles>>,
pub specialties: Arc<crate::agents_def::Specialties>,
pub scope: Option<Arc<ToolScope>>,
pub can_delegate: bool,
pub fanout: Option<Arc<crate::subagent::FanOut>>,
pub fresh_clients: bool,
pub worktree: Option<Arc<crate::worktree::Worktree>>,
pub card: Option<Arc<crate::subagent::Card>>,
pub subagent: Option<Arc<crate::subagent::SubagentRun>>,
#[cfg(feature = "agent86ui")]
pub ui: Option<Arc<crate::agent86ui::UiSession>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolScope {
pub label: String,
pub only: Option<Vec<String>>,
pub except: Vec<String>,
pub approval: Option<crate::types::ApprovalMode>,
pub confirm: Vec<String>,
pub preloaded: Vec<String>,
pub isolated: bool,
}
impl ToolScope {
pub fn allows(&self, name: &str) -> bool {
let named = self
.only
.as_ref()
.is_some_and(|only| only.iter().any(|tool| tool == name));
if self.isolated && name.starts_with("mcp__") && !named {
return false;
}
(self.only.is_none() || named) && !self.except.iter().any(|tool| tool == name)
}
pub fn within(mut self, outer: Option<&ToolScope>) -> Self {
let Some(outer) = outer else {
return self;
};
self.only = match (self.only.take(), &outer.only) {
(Some(mine), Some(theirs)) => Some(
mine.into_iter()
.filter(|tool| theirs.contains(tool))
.collect(),
),
(Some(mine), None) => Some(mine),
(None, theirs) => theirs.clone(),
};
for tool in &outer.except {
if !self.except.contains(tool) {
self.except.push(tool.clone());
}
}
self.approval = stricter(self.approval, outer.approval);
self.isolated |= outer.isolated;
for tool in &outer.confirm {
if !self.confirm.contains(tool) {
self.confirm.push(tool.clone());
}
}
self
}
}
pub fn stricter(
a: Option<crate::types::ApprovalMode>,
b: Option<crate::types::ApprovalMode>,
) -> Option<crate::types::ApprovalMode> {
use crate::types::ApprovalMode::{Ask, Auto, Deny};
let rank = |mode| match mode {
Deny => 2,
Ask => 1,
Auto => 0,
};
match (a, b) {
(Some(a), Some(b)) => Some(if rank(a) >= rank(b) { a } else { b }),
(a, None) => a,
(None, b) => b,
}
}
impl ToolContext {
pub fn new(workspace: &Path) -> std::io::Result<Self> {
Ok(Self {
policy: SandboxPolicy::new(workspace)?,
executor: Executor::Subprocess,
web: web::WebSettings::default(),
memory: None,
skills: Arc::default(),
active_skill: Arc::default(),
secrets: crate::vault::SecretVault::default(),
editor: None,
specialties: Arc::default(),
scope: None,
can_delegate: false,
fanout: None,
fresh_clients: false,
worktree: None,
card: None,
subagent: None,
#[cfg(feature = "agent86ui")]
ui: None,
})
}
fn active(&self) -> std::sync::MutexGuard<'_, Option<Arc<crate::skills::Skill>>> {
self.active_skill
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn activate_skill(&self, skill: &Arc<crate::skills::Skill>) {
*self.active() = Some(Arc::clone(skill));
}
pub fn clear_skill(&self) {
*self.active() = None;
}
pub fn fork(&self) -> Self {
let mut forked = self.clone();
forked.active_skill = Arc::new(std::sync::Mutex::new(self.active_skill()));
#[cfg(feature = "agent86ui")]
{
forked.ui = None;
}
forked
}
pub fn active_skill(&self) -> Option<Arc<crate::skills::Skill>> {
self.active().clone()
}
pub fn scope_allows(&self, name: &str) -> bool {
self.scope.as_deref().is_none_or(|scope| scope.allows(name))
}
pub fn allowed_tool(&self, name: &str) -> bool {
if !self.scope_allows(name) {
return false;
}
match self.active().as_deref() {
Some(skill) if !skill.allowed_tools.is_empty() => {
name == "use_skill" || skill.allowed_tools.iter().any(|tool| tool == name)
}
_ => true,
}
}
}
#[derive(Default, Clone)]
pub struct ToolRegistry {
inner: Arc<RwLock<RegistryInner>>,
}
#[derive(Default)]
struct RegistryInner {
tools: Vec<Arc<dyn Tool>>,
collisions: Vec<String>,
}
impl ToolRegistry {
pub fn new() -> Self {
Self::default()
}
fn read(&self) -> std::sync::RwLockReadGuard<'_, RegistryInner> {
self.inner
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn write(&self) -> std::sync::RwLockWriteGuard<'_, RegistryInner> {
self.inner
.write()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn register(&self, tool: Box<dyn Tool>) -> Result<(), String> {
let mut inner = self.write();
if inner.tools.iter().any(|known| known.name() == tool.name()) {
return Err(format!("Tool '{}' is already registered.", tool.name()));
}
inner.tools.push(Arc::from(tool));
Ok(())
}
pub fn try_register(&self, tool: Arc<dyn Tool>) -> bool {
let mut inner = self.write();
if inner.tools.iter().any(|known| known.name() == tool.name()) {
inner.collisions.push(tool.name().to_owned());
return false;
}
inner.tools.push(tool);
true
}
pub fn register_shared(&self, tool: Arc<dyn Tool>) -> bool {
let mut inner = self.write();
if inner.tools.iter().any(|known| known.name() == tool.name()) {
return false;
}
inner.tools.push(tool);
true
}
pub fn unregister_tool(&self, tool: &Arc<dyn Tool>) -> bool {
let mut inner = self.write();
let before = inner.tools.len();
inner.tools.retain(|known| !same_tool(known, tool));
inner.tools.len() != before
}
pub fn contains_tool(&self, tool: &Arc<dyn Tool>) -> bool {
self.read().tools.iter().any(|known| same_tool(known, tool))
}
pub fn collisions(&self) -> Vec<String> {
self.read().collisions.clone()
}
pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
self.read()
.tools
.iter()
.find(|tool| tool.name() == name)
.cloned()
}
pub fn names(&self) -> Vec<String> {
let mut names: Vec<String> = self
.read()
.tools
.iter()
.map(|tool| tool.name().to_owned())
.collect();
names.sort_unstable();
names
}
pub fn specs(&self) -> Vec<ToolSpec> {
let tools: Vec<Arc<dyn Tool>> = self.read().tools.clone();
tools.iter().map(|tool| tool.spec()).collect()
}
pub fn dispatch(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
let mut result = self.dispatch_unredacted(call, ctx);
if !ctx.secrets.is_empty() {
result.content = ctx.secrets.redact(&result.content);
result.error = result.error.map(|error| ctx.secrets.redact(&error));
for value in result.metadata.values_mut() {
redact_value(value, ctx);
}
}
result
}
fn dispatch_unredacted(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
match self.get(&call.name) {
Some(_) if !ctx.scope_allows(&call.name) => scope_refusal(call, ctx),
Some(_) if !ctx.allowed_tool(&call.name) => skill_refusal(call, ctx),
Some(tool) => match with_secrets(tool.as_ref(), call, ctx) {
Ok(call) => {
let (call, repaired) = repaired_call(tool.as_ref(), call);
let mut result = tool.run(&call, ctx);
if !result.ok {
if let Some(hint) = unparsed_json_hint(&tool.parameters(), &call.arguments)
{
let error = result.error.get_or_insert_with(String::new);
error.push('\n');
error.push_str(&hint);
}
}
if !repaired.is_empty() {
result
.metadata
.insert(ARGS_REPAIRED_KEY.to_owned(), json!(repaired));
}
result
}
Err(error) => ToolResult {
call_id: call.id.clone(),
..failure(&call.name, error)
},
},
None => ToolResult {
call_id: call.id.clone(),
..failure(
&call.name,
format!(
"Unknown tool '{}'. Available: {}.",
call.name,
self.names().join(", ")
),
)
},
}
}
}
pub fn with_secrets<'a>(
tool: &dyn Tool,
call: &'a ToolCall,
ctx: &ToolContext,
) -> Result<std::borrow::Cow<'a, ToolCall>, String> {
if !tool.expands_secrets() {
return Ok(std::borrow::Cow::Borrowed(call));
}
let Value::Object(arguments) = ctx
.secrets
.expand_value(&Value::Object(call.arguments.clone()))?
else {
unreachable!("an object expands to an object")
};
Ok(std::borrow::Cow::Owned(ToolCall {
arguments,
..call.clone()
}))
}
pub const ARGS_REPAIRED_KEY: &str = "args_repaired";
fn repaired_call<'a>(
tool: &dyn Tool,
call: std::borrow::Cow<'a, ToolCall>,
) -> (std::borrow::Cow<'a, ToolCall>, Vec<String>) {
let Some((arguments, repaired)) = repair_arguments(&tool.parameters(), &call.arguments) else {
return (call, Vec::new());
};
let call = ToolCall {
arguments,
..call.into_owned()
};
(std::borrow::Cow::Owned(call), repaired)
}
pub fn repair_arguments(
schema: &Value,
arguments: &Map<String, Value>,
) -> Option<(Map<String, Value>, Vec<String>)> {
let properties = schema.get("properties")?.as_object()?;
let mut repaired_arguments = arguments.clone();
let mut repaired = Vec::new();
for (name, value) in arguments {
let (Value::String(text), Some(property)) = (value, properties.get(name)) else {
continue;
};
let accepted = accepted_types(property);
if accepted.contains(&"string") {
continue;
}
let Ok(parsed) = serde_json::from_str::<Value>(text.trim()) else {
continue;
};
let kind = match parsed {
Value::Array(_) => "array",
Value::Object(_) => "object",
_ => continue,
};
if accepted.contains(&kind) {
repaired_arguments.insert(name.clone(), parsed);
repaired.push(name.clone());
}
}
(!repaired.is_empty()).then_some((repaired_arguments, repaired))
}
pub fn unparsed_json_hint(schema: &Value, arguments: &Map<String, Value>) -> Option<String> {
let properties = schema.get("properties")?.as_object()?;
let hints: Vec<String> = arguments
.iter()
.filter_map(|(name, value)| {
let text = value.as_str()?.trim();
let accepted = accepted_types(properties.get(name)?);
let wanted = match text.chars().next()? {
'[' if accepted.contains(&"array") => "array",
'{' if accepted.contains(&"object") => "object",
_ => return None,
};
if accepted.contains(&"string") {
return None;
}
let error = serde_json::from_str::<Value>(text).err()?;
Some(format!(
"'{name}' was sent as a string holding JSON that does not parse ({error}). \
Send it as a JSON {wanted} itself, not inside a string, and check that \
every bracket and brace closes in order."
))
})
.collect();
(!hints.is_empty()).then(|| hints.join("\n"))
}
fn accepted_types(property: &Value) -> Vec<&str> {
let mut types = Vec::new();
match property.get("type") {
Some(Value::String(kind)) => types.push(kind.as_str()),
Some(Value::Array(kinds)) => types.extend(kinds.iter().filter_map(Value::as_str)),
_ => {}
}
for key in ["anyOf", "oneOf"] {
if let Some(branches) = property.get(key).and_then(Value::as_array) {
for branch in branches {
types.extend(accepted_types(branch));
}
}
}
types
}
pub fn scope_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
let label = ctx
.scope
.as_deref()
.map_or("", |scope| scope.label.as_str());
ToolResult {
call_id: call.id.clone(),
..failure(
&call.name,
format!(
"Tool '{}' is not permitted for the '{label}' sub-agent. Use only the tools you \
were given.",
call.name
),
)
}
}
fn skill_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
let skill = ctx.active_skill();
let (name, allowed) = skill
.as_deref()
.map(|skill| (skill.name.as_str(), skill.allowed_tools.join(", ")))
.unwrap_or_default();
ToolResult {
call_id: call.id.clone(),
..failure(
&call.name,
format!(
"Tool '{}' is not permitted while the skill '{name}' is active. That skill's \
allowed-tools are: {allowed}. Use one of those, or finish with the skill first.",
call.name
),
)
}
}
fn same_tool(a: &Arc<dyn Tool>, b: &Arc<dyn Tool>) -> bool {
std::ptr::eq(Arc::as_ptr(a).cast::<()>(), Arc::as_ptr(b).cast::<()>())
}
pub fn default_registry(
with_memory: bool,
with_skills: bool,
with_delegate: bool,
with_secrets: bool,
) -> ToolRegistry {
let registry = builtin_registry();
for tool in [
Box::new(search::SearchFilesTool) as Box<dyn Tool>,
Box::new(search::FindFilesTool),
] {
registry
.register(tool)
.expect("search tool names are unique");
}
if with_memory {
for tool in [
Box::new(memory::RememberTool) as Box<dyn Tool>,
Box::new(memory::RecallTool),
] {
registry
.register(tool)
.expect("memory tool names are unique");
}
}
if with_skills {
registry
.register(Box::new(skills::UseSkillTool))
.expect("use_skill is unique");
}
if with_delegate {
registry
.register(Box::new(delegate::DelegateTool))
.expect("delegate is unique");
}
if with_secrets {
registry
.register(Box::new(secret::RequestSecretTool))
.expect("request_secret is unique");
}
registry
}
pub fn builtin_registry() -> ToolRegistry {
let registry = ToolRegistry::new();
for tool in [
Box::new(files::ReadFileTool) as Box<dyn Tool>,
Box::new(files::WriteFileTool),
Box::new(files::EditFileTool),
Box::new(files::ListDirTool),
Box::new(exec::RunCommandTool),
Box::new(exec::PythonExecTool),
Box::new(web::WebFetchTool),
] {
registry
.register(tool)
.expect("built-in tool names are unique");
}
registry
}