1pub mod delegate;
10pub mod exec;
11pub mod files;
12pub mod memory;
13pub mod sandbox;
14pub mod search;
15pub mod secret;
16pub mod skills;
17pub mod web;
18
19use crate::types::{ToolCall, ToolResult, ToolSpec};
20use sandbox::Executor;
21use serde_json::{json, Map, Value};
22use std::path::{Component, Path, PathBuf};
23use std::sync::{Arc, RwLock};
24use std::time::Duration;
25
26pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum ToolError {
32 InvalidArguments(Vec<String>),
34 Raised { exception: String, message: String },
36}
37
38impl ToolError {
39 fn raised(exception: &str, message: impl Into<String>) -> Self {
40 Self::Raised {
41 exception: exception.to_owned(),
42 message: message.into(),
43 }
44 }
45
46 pub fn editor(message: impl Into<String>) -> Self {
48 Self::raised("OSError", message)
49 }
50
51 pub fn io(error: &std::io::Error) -> Self {
53 let exception = match error.kind() {
54 std::io::ErrorKind::NotFound => "FileNotFoundError",
55 std::io::ErrorKind::PermissionDenied => "PermissionError",
56 std::io::ErrorKind::IsADirectory => "IsADirectoryError",
57 std::io::ErrorKind::NotADirectory => "NotADirectoryError",
58 _ => "OSError",
59 };
60 Self::raised(exception, error.to_string())
61 }
62}
63
64pub trait Tool: Send + Sync {
66 fn name(&self) -> &str;
67 fn description(&self) -> &str;
68
69 fn side_effecting(&self) -> bool {
71 false
72 }
73
74 fn parallel_safe(&self) -> bool {
77 true
78 }
79
80 fn expands_secrets(&self) -> bool {
85 false
86 }
87
88 fn parameters(&self) -> Value;
90
91 fn preview(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
95 None
96 }
97
98 fn guarded_target(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
104 None
105 }
106
107 fn change(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<FileChange> {
113 None
114 }
115
116 fn preview_lexer(&self) -> Option<&'static str> {
119 None
120 }
121
122 fn execute(
124 &self,
125 args: &Map<String, Value>,
126 ctx: &ToolContext,
127 ) -> Result<ToolResult, ToolError>;
128
129 fn spec(&self) -> ToolSpec {
131 ToolSpec {
132 name: self.name().to_owned(),
133 description: self.description().to_owned(),
134 parameters: self.parameters(),
135 side_effecting: self.side_effecting(),
136 }
137 }
138
139 fn run(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
141 let mut result = match self.execute(&call.arguments, ctx) {
142 Ok(result) => result,
143 Err(ToolError::InvalidArguments(errors)) => failure(
144 self.name(),
145 format!(
146 "Invalid arguments for '{}': {}",
147 self.name(),
148 errors.join("; ")
149 ),
150 ),
151 Err(ToolError::Raised { exception, message }) => {
152 failure(self.name(), format!("{exception}: {message}"))
153 }
154 };
155 if result.call_id.is_empty() {
156 result.call_id = call.id.clone();
157 }
158 if result.name.is_empty() {
159 result.name = self.name().to_owned();
160 }
161 result
162 }
163}
164
165pub const MAX_CHANGE_TEXT_BYTES: usize = 256 * 1024;
168
169#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct FileChange {
176 pub path: String,
178 pub old_text: Option<String>,
180 pub new_text: String,
181 pub line: Option<usize>,
183}
184
185impl FileChange {
186 pub fn capped(target: &Path, old_text: Option<&str>, new_text: &str) -> Option<Self> {
188 let over = |text: &str| text.len() > MAX_CHANGE_TEXT_BYTES;
189 if over(new_text) || old_text.is_some_and(over) {
190 return None;
191 }
192 Some(Self {
193 path: display_path(target),
194 old_text: old_text.map(str::to_owned),
195 new_text: new_text.to_owned(),
196 line: first_changed_line(old_text, new_text),
197 })
198 }
199
200 pub fn redacted(mut self, secrets: &crate::vault::SecretVault) -> Self {
202 if !secrets.is_empty() {
203 self.path = secrets.redact(&self.path);
204 self.old_text = self.old_text.map(|text| secrets.redact(&text));
205 self.new_text = secrets.redact(&self.new_text);
206 }
207 self
208 }
209
210 pub fn record(&self, metadata: &mut Map<String, Value>) {
212 metadata.insert("abs_path".to_owned(), json!(self.path));
213 metadata.insert("old_text".to_owned(), json!(self.old_text));
214 metadata.insert("new_text".to_owned(), json!(self.new_text));
215 metadata.insert("line".to_owned(), json!(self.line));
216 }
217
218 pub fn record_write(
222 target: &Path,
223 old_text: Option<&str>,
224 new_text: &str,
225 metadata: &mut Map<String, Value>,
226 ) {
227 match Self::capped(target, old_text, new_text) {
228 Some(change) => change.record(metadata),
229 None => {
230 metadata.insert("abs_path".to_owned(), json!(display_path(target)));
231 metadata.insert(
232 "line".to_owned(),
233 json!(first_changed_line(old_text, new_text)),
234 );
235 }
236 }
237 }
238
239 pub fn from_metadata(metadata: &Map<String, Value>) -> Option<Self> {
241 Some(Self {
242 path: metadata.get("abs_path")?.as_str()?.to_owned(),
243 old_text: match metadata.get("old_text")? {
244 Value::Null => None,
245 value => Some(value.as_str()?.to_owned()),
246 },
247 new_text: metadata.get("new_text")?.as_str()?.to_owned(),
248 line: metadata
249 .get("line")
250 .and_then(Value::as_u64)
251 .and_then(|line| usize::try_from(line).ok()),
252 })
253 }
254}
255
256pub fn first_changed_line(old: Option<&str>, new: &str) -> Option<usize> {
259 let Some(old) = old else {
260 return Some(1);
261 };
262 if old == new {
263 return None;
264 }
265 let mut old_lines = old.split('\n');
266 let mut new_lines = new.split('\n');
267 let mut line: usize = 1;
268 loop {
269 match (old_lines.next(), new_lines.next()) {
270 (Some(a), Some(b)) if a == b => line += 1,
271 (Some(_), None) => return Some(line.saturating_sub(1).max(1)),
273 _ => return Some(line),
274 }
275 }
276}
277
278pub fn success(name: &str, content: String) -> ToolResult {
280 ToolResult {
281 call_id: String::new(),
282 name: name.to_owned(),
283 ok: true,
284 content,
285 error: None,
286 metadata: Map::new(),
287 }
288}
289
290pub fn failure(name: &str, error: String) -> ToolResult {
292 ToolResult {
293 call_id: String::new(),
294 name: name.to_owned(),
295 ok: false,
296 content: String::new(),
297 error: Some(error),
298 metadata: Map::new(),
299 }
300}
301
302pub struct Arguments<'a> {
306 args: &'a Map<String, Value>,
307 errors: Vec<String>,
308}
309
310impl<'a> Arguments<'a> {
311 pub fn new(args: &'a Map<String, Value>) -> Self {
312 Self {
313 args,
314 errors: Vec::new(),
315 }
316 }
317
318 pub fn string(&mut self, field: &str, default: Option<&str>) -> String {
320 match (self.args.get(field), default) {
321 (Some(Value::String(value)), _) => value.clone(),
322 (Some(_), _) => {
323 self.errors
324 .push(format!("{field}: Input should be a valid string"));
325 String::new()
326 }
327 (None, Some(default)) => default.to_owned(),
328 (None, None) => {
329 self.errors.push(format!("{field}: Field required"));
330 String::new()
331 }
332 }
333 }
334
335 pub fn optional_string(&mut self, field: &str) -> Option<String> {
337 match self.args.get(field) {
338 None | Some(Value::Null) => None,
339 Some(Value::String(value)) => Some(value.clone()),
340 Some(_) => {
341 self.errors
342 .push(format!("{field}: Input should be a valid string"));
343 None
344 }
345 }
346 }
347
348 pub fn string_list(&mut self, field: &str) -> Vec<String> {
351 match self.args.get(field) {
352 None | Some(Value::Null) => Vec::new(),
353 Some(Value::Array(items)) => {
354 let mut values = Vec::new();
355 for (index, item) in items.iter().enumerate() {
356 match item {
357 Value::String(text) => values.push(text.clone()),
358 _ => self
359 .errors
360 .push(format!("{field}.{index}: Input should be a valid string")),
361 }
362 }
363 values
364 }
365 Some(_) => {
366 self.errors
367 .push(format!("{field}: Input should be a valid list"));
368 Vec::new()
369 }
370 }
371 }
372
373 pub fn string_alias(&mut self, names: &[&str]) -> String {
376 match names.iter().find(|name| self.args.contains_key(**name)) {
377 Some(name) => self.string(name, None),
378 None => {
379 self.errors.push(format!("{}: Field required", names[0]));
380 String::new()
381 }
382 }
383 }
384
385 pub fn boolean(&mut self, field: &str, default: bool) -> bool {
388 const PLAIN: &str = "Input should be a valid boolean";
389 const UNINTERPRETABLE: &str = "Input should be a valid boolean, unable to interpret input";
390 let parsed = match self.args.get(field) {
391 None => return default,
392 Some(Value::Bool(flag)) => Ok(*flag),
393 Some(Value::Number(number)) => {
394 let value = number.as_f64().unwrap_or(f64::NAN);
395 if value == 0.0 {
396 Ok(false)
397 } else if value == 1.0 {
398 Ok(true)
399 } else if number.is_f64() && value.fract() != 0.0 {
400 Err(PLAIN)
401 } else {
402 Err(UNINTERPRETABLE)
403 }
404 }
405 Some(Value::String(text)) => match text.to_lowercase().as_str() {
406 "0" | "off" | "f" | "false" | "n" | "no" => Ok(false),
407 "1" | "on" | "t" | "true" | "y" | "yes" => Ok(true),
408 _ => Err(UNINTERPRETABLE),
409 },
410 Some(_) => Err(PLAIN),
411 };
412 parsed.unwrap_or_else(|message| {
413 self.errors.push(format!("{field}: {message}"));
414 default
415 })
416 }
417
418 pub fn string_map(&mut self, field: &str) -> Map<String, Value> {
421 match self.args.get(field) {
422 None => Map::new(),
423 Some(Value::Object(map)) => {
424 for (key, value) in map {
425 if !value.is_string() {
426 self.errors
427 .push(format!("{field}.{key}: Input should be a valid string"));
428 }
429 }
430 map.clone()
431 }
432 Some(_) => {
433 self.errors
434 .push(format!("{field}: Input should be a valid dictionary"));
435 Map::new()
436 }
437 }
438 }
439
440 pub fn integer(&mut self, field: &str, default: i64) -> i64 {
444 const PLAIN: &str = "Input should be a valid integer";
445 const UNPARSABLE: &str =
446 "Input should be a valid integer, unable to parse string as an integer";
447 let parsed = match self.args.get(field) {
448 None => return default,
449 Some(Value::Bool(flag)) => Ok(i64::from(*flag)),
450 Some(Value::Number(number)) => match (number.as_i64(), number.as_u64()) {
451 (Some(value), _) => Ok(value),
452 (None, Some(_)) => Ok(i64::MAX),
453 (None, None) => {
454 let value = number.as_f64().unwrap_or(f64::NAN);
455 if value.fract() != 0.0 {
456 Err("Input should be a valid integer, got a number with a fractional part")
457 } else if value.abs() > i64::MAX as f64 {
458 Err("Unable to parse input string as an integer, exceeded maximum size")
459 } else {
460 Ok(value as i64)
461 }
462 }
463 },
464 Some(Value::String(text)) => parse_python_int(text).ok_or(UNPARSABLE),
465 Some(_) => Err(PLAIN),
466 };
467 parsed.unwrap_or_else(|message| {
468 self.errors.push(format!("{field}: {message}"));
469 default
470 })
471 }
472
473 pub fn bounded_integer(&mut self, field: &str, default: i64, min: i64, max: i64) -> i64 {
476 let before = self.errors.len();
477 let value = self.integer(field, default);
478 if self.errors.len() > before {
479 return default;
480 }
481 if value < min {
482 self.errors.push(format!(
483 "{field}: Input should be greater than or equal to {min}"
484 ));
485 default
486 } else if value > max {
487 self.errors.push(format!(
488 "{field}: Input should be less than or equal to {max}"
489 ));
490 default
491 } else {
492 value
493 }
494 }
495
496 pub fn choice(&mut self, field: &str, choices: &[&str]) -> String {
498 match self.args.get(field) {
499 Some(Value::String(value)) if choices.contains(&value.as_str()) => value.clone(),
500 None => {
501 self.errors.push(format!("{field}: Field required"));
502 String::new()
503 }
504 Some(_) => {
505 let quoted: Vec<String> =
506 choices.iter().map(|choice| format!("'{choice}'")).collect();
507 let listed = match quoted.split_last() {
508 Some((last, rest)) if !rest.is_empty() => {
509 format!("{} or {last}", rest.join(", "))
510 }
511 _ => quoted.concat(),
512 };
513 self.errors
514 .push(format!("{field}: Input should be {listed}"));
515 String::new()
516 }
517 }
518 }
519
520 pub fn finish(self) -> Result<(), ToolError> {
522 if self.errors.is_empty() {
523 Ok(())
524 } else {
525 Err(ToolError::InvalidArguments(self.errors))
526 }
527 }
528}
529
530fn parse_python_int(text: &str) -> Option<i64> {
532 let text = text.trim();
533 let text = match text.split_once('.') {
535 Some((whole, zeros)) if !zeros.is_empty() && zeros.bytes().all(|b| b == b'0') => whole,
536 Some(_) => return None,
537 None => text,
538 };
539 let (negative, digits) = match text.as_bytes().first() {
540 Some(b'-') => (true, &text[1..]),
541 Some(b'+') => (false, &text[1..]),
542 _ => (false, text),
543 };
544 if digits.is_empty()
546 || digits.starts_with('_')
547 || digits.ends_with('_')
548 || digits.contains("__")
549 || !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')
550 {
551 return None;
552 }
553 let mut value: i64 = 0;
554 for digit in digits.bytes().filter(u8::is_ascii_digit) {
555 value = value
556 .saturating_mul(10)
557 .saturating_add(i64::from(digit - b'0'));
558 }
559 Some(if negative {
560 value.saturating_neg()
561 } else {
562 value
563 })
564}
565
566#[derive(Debug, Clone, PartialEq, Eq)]
568pub struct SandboxPolicy {
569 workspace: PathBuf,
571 allow_paths: Vec<PathBuf>,
575 guarded_roots: Vec<PathBuf>,
578 pub max_output_chars: usize,
579 pub timeout: Duration,
581 pub env_passthrough: Vec<String>,
583 pub network: bool,
585}
586
587impl SandboxPolicy {
588 pub fn new(workspace: &Path) -> std::io::Result<Self> {
590 Ok(Self {
591 workspace: std::fs::canonicalize(workspace)?,
592 allow_paths: Vec::new(),
593 guarded_roots: Vec::new(),
594 max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
595 timeout: Duration::from_secs(30),
596 env_passthrough: Vec::new(),
597 network: true,
598 })
599 }
600
601 pub fn workspace(&self) -> &Path {
602 &self.workspace
603 }
604
605 pub fn rerooted(&self, root: &Path, keep: Vec<PathBuf>) -> std::io::Result<Self> {
610 let mut policy = self.clone();
611 policy.workspace = std::fs::canonicalize(root)?;
612 let allowed = std::mem::take(&mut policy.allow_paths);
613 policy.allow(allowed.into_iter().chain(keep));
614 Ok(policy)
615 }
616
617 pub fn allow(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
620 for root in roots {
621 if !root.starts_with(&self.workspace) && !self.allow_paths.contains(&root) {
622 self.allow_paths.push(root);
623 }
624 }
625 }
626
627 pub fn guard(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
631 for root in roots {
632 let root = resolve(&root);
633 if !self.guarded_roots.contains(&root) {
634 self.guarded_roots.push(root);
635 }
636 }
637 }
638
639 pub fn guarded(&self, target: &Path) -> bool {
651 if self
652 .allow_paths
653 .iter()
654 .chain(&self.guarded_roots)
655 .any(|root| target.starts_with(root))
656 {
657 return true;
658 }
659 let Ok(inside) = target.strip_prefix(&self.workspace) else {
660 return false;
661 };
662 let names: Vec<String> = inside
663 .components()
664 .take(2)
665 .filter_map(|component| match component {
666 Component::Normal(name) => Some(
667 name.to_string_lossy()
668 .trim_end_matches(['.', ' '])
669 .to_ascii_lowercase(),
670 ),
671 _ => None,
672 })
673 .collect();
674 match names.as_slice() {
675 [first, ..] if first == ".agent86" => true,
676 [first, second] => first == ".claude" && second == "skills",
677 _ => false,
678 }
679 }
680
681 pub fn resolve_within(&self, path: &str) -> Result<PathBuf, ToolError> {
686 let candidate = resolve(&self.workspace.join(path));
687 let inside = std::iter::once(&self.workspace)
688 .chain(&self.allow_paths)
689 .any(|root| candidate.starts_with(root));
690 if inside {
691 Ok(candidate)
692 } else {
693 Err(ToolError::raised(
694 "PolicyError",
695 format!(
696 "Path '{path}' resolves outside the workspace jail ({}).",
697 display_path(&self.workspace)
698 ),
699 ))
700 }
701 }
702
703 pub fn root_of(&self, path: &Path) -> Option<&Path> {
707 std::iter::once(&self.workspace)
708 .chain(&self.allow_paths)
709 .find(|root| path.starts_with(root))
710 .map(PathBuf::as_path)
711 }
712
713 pub fn require_network(&self) -> Result<(), ToolError> {
715 if self.network {
716 Ok(())
717 } else {
718 Err(ToolError::raised(
719 "PolicyError",
720 "Network access is disabled by the sandbox policy.",
721 ))
722 }
723 }
724
725 pub fn truncate(&self, text: String) -> String {
727 let length = text.chars().count();
728 if length <= self.max_output_chars {
729 return text;
730 }
731 let kept: String = text.chars().take(self.max_output_chars).collect();
732 format!(
733 "{kept}\n... [truncated {} bytes]",
734 length - self.max_output_chars
735 )
736 }
737}
738
739fn resolve(path: &Path) -> PathBuf {
751 resolve_following(path, 0)
752}
753
754const MAX_LINKS: usize = 40;
756
757fn resolve_following(path: &Path, links: usize) -> PathBuf {
758 let mut resolved = PathBuf::new();
759 for component in path.components() {
760 match component {
761 Component::Prefix(_) | Component::RootDir => resolved.push(component),
762 Component::CurDir => {}
763 Component::ParentDir => {
764 resolved.pop();
765 }
766 Component::Normal(part) => {
767 resolved.push(part);
768 if let Ok(real) = std::fs::canonicalize(&resolved) {
769 resolved = real;
770 } else if links < MAX_LINKS {
771 if let Ok(target) = std::fs::read_link(&resolved) {
772 let base = resolved.parent().map(Path::to_path_buf).unwrap_or_default();
773 resolved = resolve_following(&base.join(target), links + 1);
774 }
775 }
776 }
777 }
778 }
779 resolved
780}
781
782fn redact_value(value: &mut Value, ctx: &ToolContext) {
784 match value {
785 Value::String(text) => *text = ctx.secrets.redact(text),
786 Value::Array(items) => items.iter_mut().for_each(|item| redact_value(item, ctx)),
787 Value::Object(map) => map.values_mut().for_each(|item| redact_value(item, ctx)),
788 _ => {}
789 }
790}
791
792pub fn plain_path(path: &Path) -> PathBuf {
796 PathBuf::from(display_path(path))
797}
798
799pub fn display_path(path: &Path) -> String {
801 let text = path.display().to_string();
802 if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
803 format!(r"\\{rest}")
804 } else if let Some(rest) = text.strip_prefix(r"\\?\") {
805 rest.to_owned()
806 } else {
807 text
808 }
809}
810
811pub trait EditorFiles: Send + Sync + std::fmt::Debug {
817 fn read_text(&self, path: &Path) -> Option<String>;
821
822 fn write_text(&self, path: &Path, content: &str) -> Option<Result<(), String>>;
826}
827
828#[derive(Debug, Clone)]
830pub struct ToolContext {
831 pub policy: SandboxPolicy,
832 pub executor: Executor,
834 pub web: web::WebSettings,
836 pub memory: Option<crate::session::SessionStore>,
838 pub skills: Arc<crate::skills::Skills>,
840 active_skill: Arc<std::sync::Mutex<Option<Arc<crate::skills::Skill>>>>,
843 pub secrets: crate::vault::SecretVault,
846 pub editor: Option<Arc<dyn EditorFiles>>,
849 pub specialties: Arc<crate::agents_def::Specialties>,
851 pub scope: Option<Arc<ToolScope>>,
855 pub can_delegate: bool,
859 pub fanout: Option<Arc<crate::subagent::FanOut>>,
863 pub fresh_clients: bool,
866 pub worktree: Option<Arc<crate::worktree::Worktree>>,
869 pub card: Option<Arc<crate::subagent::Card>>,
872 pub subagent: Option<Arc<crate::subagent::SubagentRun>>,
875}
876
877#[derive(Debug, Clone, Default, PartialEq, Eq)]
882pub struct ToolScope {
883 pub label: String,
885 pub only: Option<Vec<String>>,
887 pub except: Vec<String>,
889 pub approval: Option<crate::types::ApprovalMode>,
891 pub confirm: Vec<String>,
893 pub preloaded: Vec<String>,
895 pub isolated: bool,
898}
899
900impl ToolScope {
901 pub fn allows(&self, name: &str) -> bool {
902 let named = self
903 .only
904 .as_ref()
905 .is_some_and(|only| only.iter().any(|tool| tool == name));
906 if self.isolated && name.starts_with("mcp__") && !named {
907 return false;
908 }
909 (self.only.is_none() || named) && !self.except.iter().any(|tool| tool == name)
910 }
911
912 pub fn within(mut self, outer: Option<&ToolScope>) -> Self {
914 let Some(outer) = outer else {
915 return self;
916 };
917 self.only = match (self.only.take(), &outer.only) {
918 (Some(mine), Some(theirs)) => Some(
919 mine.into_iter()
920 .filter(|tool| theirs.contains(tool))
921 .collect(),
922 ),
923 (Some(mine), None) => Some(mine),
924 (None, theirs) => theirs.clone(),
925 };
926 for tool in &outer.except {
927 if !self.except.contains(tool) {
928 self.except.push(tool.clone());
929 }
930 }
931 self.approval = stricter(self.approval, outer.approval);
932 self.isolated |= outer.isolated;
933 for tool in &outer.confirm {
934 if !self.confirm.contains(tool) {
935 self.confirm.push(tool.clone());
936 }
937 }
938 self
939 }
940}
941
942pub fn stricter(
944 a: Option<crate::types::ApprovalMode>,
945 b: Option<crate::types::ApprovalMode>,
946) -> Option<crate::types::ApprovalMode> {
947 use crate::types::ApprovalMode::{Ask, Auto, Deny};
948 let rank = |mode| match mode {
949 Deny => 2,
950 Ask => 1,
951 Auto => 0,
952 };
953 match (a, b) {
954 (Some(a), Some(b)) => Some(if rank(a) >= rank(b) { a } else { b }),
955 (a, None) => a,
956 (None, b) => b,
957 }
958}
959
960impl ToolContext {
961 pub fn new(workspace: &Path) -> std::io::Result<Self> {
963 Ok(Self {
964 policy: SandboxPolicy::new(workspace)?,
965 executor: Executor::Subprocess,
966 web: web::WebSettings::default(),
967 memory: None,
968 skills: Arc::default(),
969 active_skill: Arc::default(),
970 secrets: crate::vault::SecretVault::default(),
971 editor: None,
972 specialties: Arc::default(),
973 scope: None,
974 can_delegate: false,
975 fanout: None,
976 fresh_clients: false,
977 worktree: None,
978 card: None,
979 subagent: None,
980 })
981 }
982
983 fn active(&self) -> std::sync::MutexGuard<'_, Option<Arc<crate::skills::Skill>>> {
984 self.active_skill
985 .lock()
986 .unwrap_or_else(std::sync::PoisonError::into_inner)
987 }
988
989 pub fn activate_skill(&self, skill: &Arc<crate::skills::Skill>) {
991 *self.active() = Some(Arc::clone(skill));
992 }
993
994 pub fn clear_skill(&self) {
996 *self.active() = None;
997 }
998
999 pub fn fork(&self) -> Self {
1002 let mut forked = self.clone();
1003 forked.active_skill = Arc::new(std::sync::Mutex::new(self.active_skill()));
1004 forked
1005 }
1006
1007 pub fn active_skill(&self) -> Option<Arc<crate::skills::Skill>> {
1008 self.active().clone()
1009 }
1010
1011 pub fn scope_allows(&self, name: &str) -> bool {
1013 self.scope.as_deref().is_none_or(|scope| scope.allows(name))
1014 }
1015
1016 pub fn allowed_tool(&self, name: &str) -> bool {
1020 if !self.scope_allows(name) {
1023 return false;
1024 }
1025 match self.active().as_deref() {
1026 Some(skill) if !skill.allowed_tools.is_empty() => {
1027 name == "use_skill" || skill.allowed_tools.iter().any(|tool| tool == name)
1028 }
1029 _ => true,
1030 }
1031 }
1032}
1033
1034#[derive(Default, Clone)]
1040pub struct ToolRegistry {
1041 inner: Arc<RwLock<RegistryInner>>,
1042}
1043
1044#[derive(Default)]
1045struct RegistryInner {
1046 tools: Vec<Arc<dyn Tool>>,
1048 collisions: Vec<String>,
1050}
1051
1052impl ToolRegistry {
1053 pub fn new() -> Self {
1054 Self::default()
1055 }
1056
1057 fn read(&self) -> std::sync::RwLockReadGuard<'_, RegistryInner> {
1058 self.inner
1059 .read()
1060 .unwrap_or_else(|poisoned| poisoned.into_inner())
1061 }
1062
1063 fn write(&self) -> std::sync::RwLockWriteGuard<'_, RegistryInner> {
1064 self.inner
1065 .write()
1066 .unwrap_or_else(|poisoned| poisoned.into_inner())
1067 }
1068
1069 pub fn register(&self, tool: Box<dyn Tool>) -> Result<(), String> {
1070 let mut inner = self.write();
1071 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1072 return Err(format!("Tool '{}' is already registered.", tool.name()));
1073 }
1074 inner.tools.push(Arc::from(tool));
1075 Ok(())
1076 }
1077
1078 pub fn try_register(&self, tool: Arc<dyn Tool>) -> bool {
1081 let mut inner = self.write();
1082 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1083 inner.collisions.push(tool.name().to_owned());
1084 return false;
1085 }
1086 inner.tools.push(tool);
1087 true
1088 }
1089
1090 pub fn register_shared(&self, tool: Arc<dyn Tool>) -> bool {
1095 let mut inner = self.write();
1096 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1097 return false;
1098 }
1099 inner.tools.push(tool);
1100 true
1101 }
1102
1103 pub fn unregister_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1104 let mut inner = self.write();
1105 let before = inner.tools.len();
1106 inner.tools.retain(|known| !same_tool(known, tool));
1107 inner.tools.len() != before
1108 }
1109
1110 pub fn contains_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1112 self.read().tools.iter().any(|known| same_tool(known, tool))
1113 }
1114
1115 pub fn collisions(&self) -> Vec<String> {
1117 self.read().collisions.clone()
1118 }
1119
1120 pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
1121 self.read()
1122 .tools
1123 .iter()
1124 .find(|tool| tool.name() == name)
1125 .cloned()
1126 }
1127
1128 pub fn names(&self) -> Vec<String> {
1130 let mut names: Vec<String> = self
1131 .read()
1132 .tools
1133 .iter()
1134 .map(|tool| tool.name().to_owned())
1135 .collect();
1136 names.sort_unstable();
1137 names
1138 }
1139
1140 pub fn specs(&self) -> Vec<ToolSpec> {
1142 let tools: Vec<Arc<dyn Tool>> = self.read().tools.clone();
1143 tools.iter().map(|tool| tool.spec()).collect()
1144 }
1145
1146 pub fn dispatch(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1153 let mut result = self.dispatch_unredacted(call, ctx);
1154 if !ctx.secrets.is_empty() {
1155 result.content = ctx.secrets.redact(&result.content);
1156 result.error = result.error.map(|error| ctx.secrets.redact(&error));
1157 for value in result.metadata.values_mut() {
1160 redact_value(value, ctx);
1161 }
1162 }
1163 result
1164 }
1165
1166 fn dispatch_unredacted(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1167 match self.get(&call.name) {
1168 Some(_) if !ctx.scope_allows(&call.name) => scope_refusal(call, ctx),
1169 Some(_) if !ctx.allowed_tool(&call.name) => skill_refusal(call, ctx),
1170 Some(tool) => match with_secrets(tool.as_ref(), call, ctx) {
1171 Ok(call) => {
1172 let (call, repaired) = repaired_call(tool.as_ref(), call);
1173 let mut result = tool.run(&call, ctx);
1174 if !repaired.is_empty() {
1175 result
1176 .metadata
1177 .insert(ARGS_REPAIRED_KEY.to_owned(), json!(repaired));
1178 }
1179 result
1180 }
1181 Err(error) => ToolResult {
1182 call_id: call.id.clone(),
1183 ..failure(&call.name, error)
1184 },
1185 },
1186 None => ToolResult {
1187 call_id: call.id.clone(),
1188 ..failure(
1189 &call.name,
1190 format!(
1191 "Unknown tool '{}'. Available: {}.",
1192 call.name,
1193 self.names().join(", ")
1194 ),
1195 )
1196 },
1197 }
1198 }
1199}
1200
1201pub fn with_secrets<'a>(
1205 tool: &dyn Tool,
1206 call: &'a ToolCall,
1207 ctx: &ToolContext,
1208) -> Result<std::borrow::Cow<'a, ToolCall>, String> {
1209 if !tool.expands_secrets() {
1210 return Ok(std::borrow::Cow::Borrowed(call));
1211 }
1212 let Value::Object(arguments) = ctx
1213 .secrets
1214 .expand_value(&Value::Object(call.arguments.clone()))?
1215 else {
1216 unreachable!("an object expands to an object")
1217 };
1218 Ok(std::borrow::Cow::Owned(ToolCall {
1219 arguments,
1220 ..call.clone()
1221 }))
1222}
1223
1224pub const ARGS_REPAIRED_KEY: &str = "args_repaired";
1227
1228fn repaired_call<'a>(
1231 tool: &dyn Tool,
1232 call: std::borrow::Cow<'a, ToolCall>,
1233) -> (std::borrow::Cow<'a, ToolCall>, Vec<String>) {
1234 let Some((arguments, repaired)) = repair_arguments(&tool.parameters(), &call.arguments) else {
1235 return (call, Vec::new());
1236 };
1237 let call = ToolCall {
1238 arguments,
1239 ..call.into_owned()
1240 };
1241 (std::borrow::Cow::Owned(call), repaired)
1242}
1243
1244pub fn repair_arguments(
1255 schema: &Value,
1256 arguments: &Map<String, Value>,
1257) -> Option<(Map<String, Value>, Vec<String>)> {
1258 let properties = schema.get("properties")?.as_object()?;
1259 let mut repaired_arguments = arguments.clone();
1260 let mut repaired = Vec::new();
1261 for (name, value) in arguments {
1262 let (Value::String(text), Some(property)) = (value, properties.get(name)) else {
1263 continue;
1264 };
1265 let accepted = accepted_types(property);
1266 if accepted.contains(&"string") {
1267 continue;
1268 }
1269 let Ok(parsed) = serde_json::from_str::<Value>(text.trim()) else {
1270 continue;
1271 };
1272 let kind = match parsed {
1273 Value::Array(_) => "array",
1274 Value::Object(_) => "object",
1275 _ => continue,
1276 };
1277 if accepted.contains(&kind) {
1278 repaired_arguments.insert(name.clone(), parsed);
1279 repaired.push(name.clone());
1280 }
1281 }
1282 (!repaired.is_empty()).then_some((repaired_arguments, repaired))
1283}
1284
1285fn accepted_types(property: &Value) -> Vec<&str> {
1288 let mut types = Vec::new();
1289 match property.get("type") {
1290 Some(Value::String(kind)) => types.push(kind.as_str()),
1291 Some(Value::Array(kinds)) => types.extend(kinds.iter().filter_map(Value::as_str)),
1292 _ => {}
1293 }
1294 for key in ["anyOf", "oneOf"] {
1295 if let Some(branches) = property.get(key).and_then(Value::as_array) {
1296 for branch in branches {
1297 types.extend(accepted_types(branch));
1298 }
1299 }
1300 }
1301 types
1302}
1303
1304pub fn scope_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1307 let label = ctx
1308 .scope
1309 .as_deref()
1310 .map_or("", |scope| scope.label.as_str());
1311 ToolResult {
1312 call_id: call.id.clone(),
1313 ..failure(
1314 &call.name,
1315 format!(
1316 "Tool '{}' is not permitted for the '{label}' sub-agent. Use only the tools you \
1317 were given.",
1318 call.name
1319 ),
1320 )
1321 }
1322}
1323
1324fn skill_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1327 let skill = ctx.active_skill();
1328 let (name, allowed) = skill
1329 .as_deref()
1330 .map(|skill| (skill.name.as_str(), skill.allowed_tools.join(", ")))
1331 .unwrap_or_default();
1332 ToolResult {
1333 call_id: call.id.clone(),
1334 ..failure(
1335 &call.name,
1336 format!(
1337 "Tool '{}' is not permitted while the skill '{name}' is active. That skill's \
1338 allowed-tools are: {allowed}. Use one of those, or finish with the skill first.",
1339 call.name
1340 ),
1341 )
1342 }
1343}
1344
1345fn same_tool(a: &Arc<dyn Tool>, b: &Arc<dyn Tool>) -> bool {
1346 std::ptr::eq(Arc::as_ptr(a).cast::<()>(), Arc::as_ptr(b).cast::<()>())
1347}
1348
1349pub fn default_registry(
1355 with_memory: bool,
1356 with_skills: bool,
1357 with_delegate: bool,
1358 with_secrets: bool,
1359) -> ToolRegistry {
1360 let registry = builtin_registry();
1361 for tool in [
1362 Box::new(search::SearchFilesTool) as Box<dyn Tool>,
1363 Box::new(search::FindFilesTool),
1364 ] {
1365 registry
1366 .register(tool)
1367 .expect("search tool names are unique");
1368 }
1369 if with_memory {
1370 for tool in [
1371 Box::new(memory::RememberTool) as Box<dyn Tool>,
1372 Box::new(memory::RecallTool),
1373 ] {
1374 registry
1375 .register(tool)
1376 .expect("memory tool names are unique");
1377 }
1378 }
1379 if with_skills {
1380 registry
1381 .register(Box::new(skills::UseSkillTool))
1382 .expect("use_skill is unique");
1383 }
1384 if with_delegate {
1385 registry
1386 .register(Box::new(delegate::DelegateTool))
1387 .expect("delegate is unique");
1388 }
1389 if with_secrets {
1390 registry
1391 .register(Box::new(secret::RequestSecretTool))
1392 .expect("request_secret is unique");
1393 }
1394 registry
1395}
1396
1397pub fn builtin_registry() -> ToolRegistry {
1399 let registry = ToolRegistry::new();
1400 for tool in [
1401 Box::new(files::ReadFileTool) as Box<dyn Tool>,
1402 Box::new(files::WriteFileTool),
1403 Box::new(files::EditFileTool),
1404 Box::new(files::ListDirTool),
1405 Box::new(exec::RunCommandTool),
1406 Box::new(exec::PythonExecTool),
1407 Box::new(web::WebFetchTool),
1408 ] {
1409 registry
1410 .register(tool)
1411 .expect("built-in tool names are unique");
1412 }
1413 registry
1414}