1pub mod delegate;
10pub mod exec;
11pub mod files;
12pub mod memory;
13#[cfg(feature = "agent86ui")]
14pub mod render_ui;
15pub mod sandbox;
16pub mod search;
17pub mod secret;
18pub mod skills;
19pub mod web;
20
21use crate::types::{ToolCall, ToolResult, ToolSpec};
22use sandbox::Executor;
23use serde_json::{json, Map, Value};
24use std::path::{Component, Path, PathBuf};
25use std::sync::{Arc, RwLock};
26use std::time::Duration;
27
28pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum ToolError {
34 InvalidArguments(Vec<String>),
36 Raised { exception: String, message: String },
38}
39
40impl ToolError {
41 fn raised(exception: &str, message: impl Into<String>) -> Self {
42 Self::Raised {
43 exception: exception.to_owned(),
44 message: message.into(),
45 }
46 }
47
48 pub fn editor(message: impl Into<String>) -> Self {
50 Self::raised("OSError", message)
51 }
52
53 pub fn io(error: &std::io::Error) -> Self {
55 let exception = match error.kind() {
56 std::io::ErrorKind::NotFound => "FileNotFoundError",
57 std::io::ErrorKind::PermissionDenied => "PermissionError",
58 std::io::ErrorKind::IsADirectory => "IsADirectoryError",
59 std::io::ErrorKind::NotADirectory => "NotADirectoryError",
60 _ => "OSError",
61 };
62 Self::raised(exception, error.to_string())
63 }
64}
65
66pub trait Tool: Send + Sync {
68 fn name(&self) -> &str;
69 fn description(&self) -> &str;
70
71 fn side_effecting(&self) -> bool {
73 false
74 }
75
76 fn parallel_safe(&self) -> bool {
79 true
80 }
81
82 fn expands_secrets(&self) -> bool {
87 false
88 }
89
90 fn parameters(&self) -> Value;
92
93 fn preview(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
97 None
98 }
99
100 fn guarded_target(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
106 None
107 }
108
109 fn change(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<FileChange> {
115 None
116 }
117
118 fn preview_lexer(&self) -> Option<&'static str> {
121 None
122 }
123
124 fn execute(
126 &self,
127 args: &Map<String, Value>,
128 ctx: &ToolContext,
129 ) -> Result<ToolResult, ToolError>;
130
131 fn spec(&self) -> ToolSpec {
133 ToolSpec {
134 name: self.name().to_owned(),
135 description: self.description().to_owned(),
136 parameters: self.parameters(),
137 side_effecting: self.side_effecting(),
138 }
139 }
140
141 fn run(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
143 let mut result = match self.execute(&call.arguments, ctx) {
144 Ok(result) => result,
145 Err(ToolError::InvalidArguments(errors)) => failure(
146 self.name(),
147 format!(
148 "Invalid arguments for '{}': {}",
149 self.name(),
150 errors.join("; ")
151 ),
152 ),
153 Err(ToolError::Raised { exception, message }) => {
154 failure(self.name(), format!("{exception}: {message}"))
155 }
156 };
157 if result.call_id.is_empty() {
158 result.call_id = call.id.clone();
159 }
160 if result.name.is_empty() {
161 result.name = self.name().to_owned();
162 }
163 result
164 }
165}
166
167pub const MAX_CHANGE_TEXT_BYTES: usize = 256 * 1024;
170
171#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct FileChange {
178 pub path: String,
180 pub old_text: Option<String>,
182 pub new_text: String,
183 pub line: Option<usize>,
185}
186
187impl FileChange {
188 pub fn capped(target: &Path, old_text: Option<&str>, new_text: &str) -> Option<Self> {
190 let over = |text: &str| text.len() > MAX_CHANGE_TEXT_BYTES;
191 if over(new_text) || old_text.is_some_and(over) {
192 return None;
193 }
194 Some(Self {
195 path: display_path(target),
196 old_text: old_text.map(str::to_owned),
197 new_text: new_text.to_owned(),
198 line: first_changed_line(old_text, new_text),
199 })
200 }
201
202 pub fn redacted(mut self, secrets: &crate::vault::SecretVault) -> Self {
204 if !secrets.is_empty() {
205 self.path = secrets.redact(&self.path);
206 self.old_text = self.old_text.map(|text| secrets.redact(&text));
207 self.new_text = secrets.redact(&self.new_text);
208 }
209 self
210 }
211
212 pub fn record(&self, metadata: &mut Map<String, Value>) {
214 metadata.insert("abs_path".to_owned(), json!(self.path));
215 metadata.insert("old_text".to_owned(), json!(self.old_text));
216 metadata.insert("new_text".to_owned(), json!(self.new_text));
217 metadata.insert("line".to_owned(), json!(self.line));
218 }
219
220 pub fn record_write(
224 target: &Path,
225 old_text: Option<&str>,
226 new_text: &str,
227 metadata: &mut Map<String, Value>,
228 ) {
229 match Self::capped(target, old_text, new_text) {
230 Some(change) => change.record(metadata),
231 None => {
232 metadata.insert("abs_path".to_owned(), json!(display_path(target)));
233 metadata.insert(
234 "line".to_owned(),
235 json!(first_changed_line(old_text, new_text)),
236 );
237 }
238 }
239 }
240
241 pub fn from_metadata(metadata: &Map<String, Value>) -> Option<Self> {
243 Some(Self {
244 path: metadata.get("abs_path")?.as_str()?.to_owned(),
245 old_text: match metadata.get("old_text")? {
246 Value::Null => None,
247 value => Some(value.as_str()?.to_owned()),
248 },
249 new_text: metadata.get("new_text")?.as_str()?.to_owned(),
250 line: metadata
251 .get("line")
252 .and_then(Value::as_u64)
253 .and_then(|line| usize::try_from(line).ok()),
254 })
255 }
256}
257
258pub fn first_changed_line(old: Option<&str>, new: &str) -> Option<usize> {
261 let Some(old) = old else {
262 return Some(1);
263 };
264 if old == new {
265 return None;
266 }
267 let mut old_lines = old.split('\n');
268 let mut new_lines = new.split('\n');
269 let mut line: usize = 1;
270 loop {
271 match (old_lines.next(), new_lines.next()) {
272 (Some(a), Some(b)) if a == b => line += 1,
273 (Some(_), None) => return Some(line.saturating_sub(1).max(1)),
275 _ => return Some(line),
276 }
277 }
278}
279
280pub fn success(name: &str, content: String) -> ToolResult {
282 ToolResult {
283 call_id: String::new(),
284 name: name.to_owned(),
285 ok: true,
286 content,
287 error: None,
288 metadata: Map::new(),
289 }
290}
291
292pub fn failure(name: &str, error: String) -> ToolResult {
294 ToolResult {
295 call_id: String::new(),
296 name: name.to_owned(),
297 ok: false,
298 content: String::new(),
299 error: Some(error),
300 metadata: Map::new(),
301 }
302}
303
304pub struct Arguments<'a> {
308 args: &'a Map<String, Value>,
309 errors: Vec<String>,
310}
311
312impl<'a> Arguments<'a> {
313 pub fn new(args: &'a Map<String, Value>) -> Self {
314 Self {
315 args,
316 errors: Vec::new(),
317 }
318 }
319
320 pub fn string(&mut self, field: &str, default: Option<&str>) -> String {
322 match (self.args.get(field), default) {
323 (Some(Value::String(value)), _) => value.clone(),
324 (Some(_), _) => {
325 self.errors
326 .push(format!("{field}: Input should be a valid string"));
327 String::new()
328 }
329 (None, Some(default)) => default.to_owned(),
330 (None, None) => {
331 self.errors.push(format!("{field}: Field required"));
332 String::new()
333 }
334 }
335 }
336
337 pub fn optional_string(&mut self, field: &str) -> Option<String> {
339 match self.args.get(field) {
340 None | Some(Value::Null) => None,
341 Some(Value::String(value)) => Some(value.clone()),
342 Some(_) => {
343 self.errors
344 .push(format!("{field}: Input should be a valid string"));
345 None
346 }
347 }
348 }
349
350 pub fn string_list(&mut self, field: &str) -> Vec<String> {
353 match self.args.get(field) {
354 None | Some(Value::Null) => Vec::new(),
355 Some(Value::Array(items)) => {
356 let mut values = Vec::new();
357 for (index, item) in items.iter().enumerate() {
358 match item {
359 Value::String(text) => values.push(text.clone()),
360 _ => self
361 .errors
362 .push(format!("{field}.{index}: Input should be a valid string")),
363 }
364 }
365 values
366 }
367 Some(_) => {
368 self.errors
369 .push(format!("{field}: Input should be a valid list"));
370 Vec::new()
371 }
372 }
373 }
374
375 pub fn string_alias(&mut self, names: &[&str]) -> String {
378 match names.iter().find(|name| self.args.contains_key(**name)) {
379 Some(name) => self.string(name, None),
380 None => {
381 self.errors.push(format!("{}: Field required", names[0]));
382 String::new()
383 }
384 }
385 }
386
387 pub fn boolean(&mut self, field: &str, default: bool) -> bool {
390 const PLAIN: &str = "Input should be a valid boolean";
391 const UNINTERPRETABLE: &str = "Input should be a valid boolean, unable to interpret input";
392 let parsed = match self.args.get(field) {
393 None => return default,
394 Some(Value::Bool(flag)) => Ok(*flag),
395 Some(Value::Number(number)) => {
396 let value = number.as_f64().unwrap_or(f64::NAN);
397 if value == 0.0 {
398 Ok(false)
399 } else if value == 1.0 {
400 Ok(true)
401 } else if number.is_f64() && value.fract() != 0.0 {
402 Err(PLAIN)
403 } else {
404 Err(UNINTERPRETABLE)
405 }
406 }
407 Some(Value::String(text)) => match text.to_lowercase().as_str() {
408 "0" | "off" | "f" | "false" | "n" | "no" => Ok(false),
409 "1" | "on" | "t" | "true" | "y" | "yes" => Ok(true),
410 _ => Err(UNINTERPRETABLE),
411 },
412 Some(_) => Err(PLAIN),
413 };
414 parsed.unwrap_or_else(|message| {
415 self.errors.push(format!("{field}: {message}"));
416 default
417 })
418 }
419
420 pub fn string_map(&mut self, field: &str) -> Map<String, Value> {
423 match self.args.get(field) {
424 None => Map::new(),
425 Some(Value::Object(map)) => {
426 for (key, value) in map {
427 if !value.is_string() {
428 self.errors
429 .push(format!("{field}.{key}: Input should be a valid string"));
430 }
431 }
432 map.clone()
433 }
434 Some(_) => {
435 self.errors
436 .push(format!("{field}: Input should be a valid dictionary"));
437 Map::new()
438 }
439 }
440 }
441
442 pub fn integer(&mut self, field: &str, default: i64) -> i64 {
446 const PLAIN: &str = "Input should be a valid integer";
447 const UNPARSABLE: &str =
448 "Input should be a valid integer, unable to parse string as an integer";
449 let parsed = match self.args.get(field) {
450 None => return default,
451 Some(Value::Bool(flag)) => Ok(i64::from(*flag)),
452 Some(Value::Number(number)) => match (number.as_i64(), number.as_u64()) {
453 (Some(value), _) => Ok(value),
454 (None, Some(_)) => Ok(i64::MAX),
455 (None, None) => {
456 let value = number.as_f64().unwrap_or(f64::NAN);
457 if value.fract() != 0.0 {
458 Err("Input should be a valid integer, got a number with a fractional part")
459 } else if value.abs() > i64::MAX as f64 {
460 Err("Unable to parse input string as an integer, exceeded maximum size")
461 } else {
462 Ok(value as i64)
463 }
464 }
465 },
466 Some(Value::String(text)) => parse_python_int(text).ok_or(UNPARSABLE),
467 Some(_) => Err(PLAIN),
468 };
469 parsed.unwrap_or_else(|message| {
470 self.errors.push(format!("{field}: {message}"));
471 default
472 })
473 }
474
475 pub fn bounded_integer(&mut self, field: &str, default: i64, min: i64, max: i64) -> i64 {
478 let before = self.errors.len();
479 let value = self.integer(field, default);
480 if self.errors.len() > before {
481 return default;
482 }
483 if value < min {
484 self.errors.push(format!(
485 "{field}: Input should be greater than or equal to {min}"
486 ));
487 default
488 } else if value > max {
489 self.errors.push(format!(
490 "{field}: Input should be less than or equal to {max}"
491 ));
492 default
493 } else {
494 value
495 }
496 }
497
498 pub fn choice(&mut self, field: &str, choices: &[&str]) -> String {
500 match self.args.get(field) {
501 Some(Value::String(value)) if choices.contains(&value.as_str()) => value.clone(),
502 None => {
503 self.errors.push(format!("{field}: Field required"));
504 String::new()
505 }
506 Some(_) => {
507 let quoted: Vec<String> =
508 choices.iter().map(|choice| format!("'{choice}'")).collect();
509 let listed = match quoted.split_last() {
510 Some((last, rest)) if !rest.is_empty() => {
511 format!("{} or {last}", rest.join(", "))
512 }
513 _ => quoted.concat(),
514 };
515 self.errors
516 .push(format!("{field}: Input should be {listed}"));
517 String::new()
518 }
519 }
520 }
521
522 pub fn finish(self) -> Result<(), ToolError> {
524 if self.errors.is_empty() {
525 Ok(())
526 } else {
527 Err(ToolError::InvalidArguments(self.errors))
528 }
529 }
530}
531
532fn parse_python_int(text: &str) -> Option<i64> {
534 let text = text.trim();
535 let text = match text.split_once('.') {
537 Some((whole, zeros)) if !zeros.is_empty() && zeros.bytes().all(|b| b == b'0') => whole,
538 Some(_) => return None,
539 None => text,
540 };
541 let (negative, digits) = match text.as_bytes().first() {
542 Some(b'-') => (true, &text[1..]),
543 Some(b'+') => (false, &text[1..]),
544 _ => (false, text),
545 };
546 if digits.is_empty()
548 || digits.starts_with('_')
549 || digits.ends_with('_')
550 || digits.contains("__")
551 || !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')
552 {
553 return None;
554 }
555 let mut value: i64 = 0;
556 for digit in digits.bytes().filter(u8::is_ascii_digit) {
557 value = value
558 .saturating_mul(10)
559 .saturating_add(i64::from(digit - b'0'));
560 }
561 Some(if negative {
562 value.saturating_neg()
563 } else {
564 value
565 })
566}
567
568#[derive(Debug, Clone, PartialEq, Eq)]
570pub struct SandboxPolicy {
571 workspace: PathBuf,
573 allow_paths: Vec<PathBuf>,
577 guarded_roots: Vec<PathBuf>,
580 pub max_output_chars: usize,
581 pub timeout: Duration,
583 pub env_passthrough: Vec<String>,
585 pub network: bool,
587}
588
589impl SandboxPolicy {
590 pub fn new(workspace: &Path) -> std::io::Result<Self> {
592 Ok(Self {
593 workspace: std::fs::canonicalize(workspace)?,
594 allow_paths: Vec::new(),
595 guarded_roots: Vec::new(),
596 max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
597 timeout: Duration::from_secs(30),
598 env_passthrough: Vec::new(),
599 network: true,
600 })
601 }
602
603 pub fn workspace(&self) -> &Path {
604 &self.workspace
605 }
606
607 pub fn rerooted(&self, root: &Path, keep: Vec<PathBuf>) -> std::io::Result<Self> {
612 let mut policy = self.clone();
613 policy.workspace = std::fs::canonicalize(root)?;
614 let allowed = std::mem::take(&mut policy.allow_paths);
615 policy.allow(allowed.into_iter().chain(keep));
616 Ok(policy)
617 }
618
619 pub fn allow(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
622 for root in roots {
623 if !root.starts_with(&self.workspace) && !self.allow_paths.contains(&root) {
624 self.allow_paths.push(root);
625 }
626 }
627 }
628
629 pub fn guard(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
633 for root in roots {
634 let root = resolve(&root);
635 if !self.guarded_roots.contains(&root) {
636 self.guarded_roots.push(root);
637 }
638 }
639 }
640
641 pub fn guarded(&self, target: &Path) -> bool {
653 if self
654 .allow_paths
655 .iter()
656 .chain(&self.guarded_roots)
657 .any(|root| target.starts_with(root))
658 {
659 return true;
660 }
661 let Ok(inside) = target.strip_prefix(&self.workspace) else {
662 return false;
663 };
664 let names: Vec<String> = inside
665 .components()
666 .take(2)
667 .filter_map(|component| match component {
668 Component::Normal(name) => Some(
669 name.to_string_lossy()
670 .trim_end_matches(['.', ' '])
671 .to_ascii_lowercase(),
672 ),
673 _ => None,
674 })
675 .collect();
676 match names.as_slice() {
677 [first, ..] if first == ".agent86" => true,
678 [first, second] => first == ".claude" && second == "skills",
679 _ => false,
680 }
681 }
682
683 pub fn resolve_within(&self, path: &str) -> Result<PathBuf, ToolError> {
688 let candidate = resolve(&self.workspace.join(path));
689 let inside = std::iter::once(&self.workspace)
690 .chain(&self.allow_paths)
691 .any(|root| candidate.starts_with(root));
692 if inside {
693 Ok(candidate)
694 } else {
695 Err(ToolError::raised(
696 "PolicyError",
697 format!(
698 "Path '{path}' resolves outside the workspace jail ({}).",
699 display_path(&self.workspace)
700 ),
701 ))
702 }
703 }
704
705 pub fn root_of(&self, path: &Path) -> Option<&Path> {
709 std::iter::once(&self.workspace)
710 .chain(&self.allow_paths)
711 .find(|root| path.starts_with(root))
712 .map(PathBuf::as_path)
713 }
714
715 pub fn require_network(&self) -> Result<(), ToolError> {
717 if self.network {
718 Ok(())
719 } else {
720 Err(ToolError::raised(
721 "PolicyError",
722 "Network access is disabled by the sandbox policy.",
723 ))
724 }
725 }
726
727 pub fn truncate(&self, text: String) -> String {
729 let length = text.chars().count();
730 if length <= self.max_output_chars {
731 return text;
732 }
733 let kept: String = text.chars().take(self.max_output_chars).collect();
734 format!(
735 "{kept}\n... [truncated {} bytes]",
736 length - self.max_output_chars
737 )
738 }
739}
740
741fn resolve(path: &Path) -> PathBuf {
753 resolve_following(path, 0)
754}
755
756const MAX_LINKS: usize = 40;
758
759fn resolve_following(path: &Path, links: usize) -> PathBuf {
760 let mut resolved = PathBuf::new();
761 for component in path.components() {
762 match component {
763 Component::Prefix(_) | Component::RootDir => resolved.push(component),
764 Component::CurDir => {}
765 Component::ParentDir => {
766 resolved.pop();
767 }
768 Component::Normal(part) => {
769 resolved.push(part);
770 if let Ok(real) = std::fs::canonicalize(&resolved) {
771 resolved = real;
772 } else if links < MAX_LINKS {
773 if let Ok(target) = std::fs::read_link(&resolved) {
774 let base = resolved.parent().map(Path::to_path_buf).unwrap_or_default();
775 resolved = resolve_following(&base.join(target), links + 1);
776 }
777 }
778 }
779 }
780 }
781 resolved
782}
783
784fn redact_value(value: &mut Value, ctx: &ToolContext) {
786 match value {
787 Value::String(text) => *text = ctx.secrets.redact(text),
788 Value::Array(items) => items.iter_mut().for_each(|item| redact_value(item, ctx)),
789 Value::Object(map) => map.values_mut().for_each(|item| redact_value(item, ctx)),
790 _ => {}
791 }
792}
793
794pub fn plain_path(path: &Path) -> PathBuf {
798 PathBuf::from(display_path(path))
799}
800
801pub fn display_path(path: &Path) -> String {
803 let text = path.display().to_string();
804 if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
805 format!(r"\\{rest}")
806 } else if let Some(rest) = text.strip_prefix(r"\\?\") {
807 rest.to_owned()
808 } else {
809 text
810 }
811}
812
813pub trait EditorFiles: Send + Sync + std::fmt::Debug {
819 fn read_text(&self, path: &Path) -> Option<String>;
823
824 fn write_text(&self, path: &Path, content: &str) -> Option<Result<(), String>>;
828}
829
830#[derive(Debug, Clone)]
832pub struct ToolContext {
833 pub policy: SandboxPolicy,
834 pub executor: Executor,
836 pub web: web::WebSettings,
838 pub memory: Option<crate::session::SessionStore>,
840 pub skills: Arc<crate::skills::Skills>,
842 active_skill: Arc<std::sync::Mutex<Option<Arc<crate::skills::Skill>>>>,
845 pub secrets: crate::vault::SecretVault,
848 pub editor: Option<Arc<dyn EditorFiles>>,
851 pub specialties: Arc<crate::agents_def::Specialties>,
853 pub scope: Option<Arc<ToolScope>>,
857 pub can_delegate: bool,
861 pub fanout: Option<Arc<crate::subagent::FanOut>>,
865 pub fresh_clients: bool,
868 pub worktree: Option<Arc<crate::worktree::Worktree>>,
871 pub card: Option<Arc<crate::subagent::Card>>,
874 pub subagent: Option<Arc<crate::subagent::SubagentRun>>,
877 #[cfg(feature = "agent86ui")]
881 pub ui: Option<Arc<crate::agent86ui::UiSession>>,
882}
883
884#[derive(Debug, Clone, Default, PartialEq, Eq)]
889pub struct ToolScope {
890 pub label: String,
892 pub only: Option<Vec<String>>,
894 pub except: Vec<String>,
896 pub approval: Option<crate::types::ApprovalMode>,
898 pub confirm: Vec<String>,
900 pub preloaded: Vec<String>,
902 pub isolated: bool,
905}
906
907impl ToolScope {
908 pub fn allows(&self, name: &str) -> bool {
909 let named = self
910 .only
911 .as_ref()
912 .is_some_and(|only| only.iter().any(|tool| tool == name));
913 if self.isolated && name.starts_with("mcp__") && !named {
914 return false;
915 }
916 (self.only.is_none() || named) && !self.except.iter().any(|tool| tool == name)
917 }
918
919 pub fn within(mut self, outer: Option<&ToolScope>) -> Self {
921 let Some(outer) = outer else {
922 return self;
923 };
924 self.only = match (self.only.take(), &outer.only) {
925 (Some(mine), Some(theirs)) => Some(
926 mine.into_iter()
927 .filter(|tool| theirs.contains(tool))
928 .collect(),
929 ),
930 (Some(mine), None) => Some(mine),
931 (None, theirs) => theirs.clone(),
932 };
933 for tool in &outer.except {
934 if !self.except.contains(tool) {
935 self.except.push(tool.clone());
936 }
937 }
938 self.approval = stricter(self.approval, outer.approval);
939 self.isolated |= outer.isolated;
940 for tool in &outer.confirm {
941 if !self.confirm.contains(tool) {
942 self.confirm.push(tool.clone());
943 }
944 }
945 self
946 }
947}
948
949pub fn stricter(
951 a: Option<crate::types::ApprovalMode>,
952 b: Option<crate::types::ApprovalMode>,
953) -> Option<crate::types::ApprovalMode> {
954 use crate::types::ApprovalMode::{Ask, Auto, Deny};
955 let rank = |mode| match mode {
956 Deny => 2,
957 Ask => 1,
958 Auto => 0,
959 };
960 match (a, b) {
961 (Some(a), Some(b)) => Some(if rank(a) >= rank(b) { a } else { b }),
962 (a, None) => a,
963 (None, b) => b,
964 }
965}
966
967impl ToolContext {
968 pub fn new(workspace: &Path) -> std::io::Result<Self> {
970 Ok(Self {
971 policy: SandboxPolicy::new(workspace)?,
972 executor: Executor::Subprocess,
973 web: web::WebSettings::default(),
974 memory: None,
975 skills: Arc::default(),
976 active_skill: Arc::default(),
977 secrets: crate::vault::SecretVault::default(),
978 editor: None,
979 specialties: Arc::default(),
980 scope: None,
981 can_delegate: false,
982 fanout: None,
983 fresh_clients: false,
984 worktree: None,
985 card: None,
986 subagent: None,
987 #[cfg(feature = "agent86ui")]
988 ui: None,
989 })
990 }
991
992 fn active(&self) -> std::sync::MutexGuard<'_, Option<Arc<crate::skills::Skill>>> {
993 self.active_skill
994 .lock()
995 .unwrap_or_else(std::sync::PoisonError::into_inner)
996 }
997
998 pub fn activate_skill(&self, skill: &Arc<crate::skills::Skill>) {
1000 *self.active() = Some(Arc::clone(skill));
1001 }
1002
1003 pub fn clear_skill(&self) {
1005 *self.active() = None;
1006 }
1007
1008 pub fn fork(&self) -> Self {
1012 let mut forked = self.clone();
1013 forked.active_skill = Arc::new(std::sync::Mutex::new(self.active_skill()));
1014 #[cfg(feature = "agent86ui")]
1015 {
1016 forked.ui = None;
1017 }
1018 forked
1019 }
1020
1021 pub fn active_skill(&self) -> Option<Arc<crate::skills::Skill>> {
1022 self.active().clone()
1023 }
1024
1025 pub fn scope_allows(&self, name: &str) -> bool {
1027 self.scope.as_deref().is_none_or(|scope| scope.allows(name))
1028 }
1029
1030 pub fn allowed_tool(&self, name: &str) -> bool {
1034 if !self.scope_allows(name) {
1037 return false;
1038 }
1039 match self.active().as_deref() {
1040 Some(skill) if !skill.allowed_tools.is_empty() => {
1041 name == "use_skill" || skill.allowed_tools.iter().any(|tool| tool == name)
1042 }
1043 _ => true,
1044 }
1045 }
1046}
1047
1048#[derive(Default, Clone)]
1054pub struct ToolRegistry {
1055 inner: Arc<RwLock<RegistryInner>>,
1056}
1057
1058#[derive(Default)]
1059struct RegistryInner {
1060 tools: Vec<Arc<dyn Tool>>,
1062 collisions: Vec<String>,
1064}
1065
1066impl ToolRegistry {
1067 pub fn new() -> Self {
1068 Self::default()
1069 }
1070
1071 fn read(&self) -> std::sync::RwLockReadGuard<'_, RegistryInner> {
1072 self.inner
1073 .read()
1074 .unwrap_or_else(|poisoned| poisoned.into_inner())
1075 }
1076
1077 fn write(&self) -> std::sync::RwLockWriteGuard<'_, RegistryInner> {
1078 self.inner
1079 .write()
1080 .unwrap_or_else(|poisoned| poisoned.into_inner())
1081 }
1082
1083 pub fn register(&self, tool: Box<dyn Tool>) -> Result<(), String> {
1084 let mut inner = self.write();
1085 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1086 return Err(format!("Tool '{}' is already registered.", tool.name()));
1087 }
1088 inner.tools.push(Arc::from(tool));
1089 Ok(())
1090 }
1091
1092 pub fn try_register(&self, tool: Arc<dyn Tool>) -> bool {
1095 let mut inner = self.write();
1096 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1097 inner.collisions.push(tool.name().to_owned());
1098 return false;
1099 }
1100 inner.tools.push(tool);
1101 true
1102 }
1103
1104 pub fn register_shared(&self, tool: Arc<dyn Tool>) -> bool {
1109 let mut inner = self.write();
1110 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1111 return false;
1112 }
1113 inner.tools.push(tool);
1114 true
1115 }
1116
1117 pub fn unregister_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1118 let mut inner = self.write();
1119 let before = inner.tools.len();
1120 inner.tools.retain(|known| !same_tool(known, tool));
1121 inner.tools.len() != before
1122 }
1123
1124 pub fn contains_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1126 self.read().tools.iter().any(|known| same_tool(known, tool))
1127 }
1128
1129 pub fn collisions(&self) -> Vec<String> {
1131 self.read().collisions.clone()
1132 }
1133
1134 pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
1135 self.read()
1136 .tools
1137 .iter()
1138 .find(|tool| tool.name() == name)
1139 .cloned()
1140 }
1141
1142 pub fn names(&self) -> Vec<String> {
1144 let mut names: Vec<String> = self
1145 .read()
1146 .tools
1147 .iter()
1148 .map(|tool| tool.name().to_owned())
1149 .collect();
1150 names.sort_unstable();
1151 names
1152 }
1153
1154 pub fn specs(&self) -> Vec<ToolSpec> {
1156 let tools: Vec<Arc<dyn Tool>> = self.read().tools.clone();
1157 tools.iter().map(|tool| tool.spec()).collect()
1158 }
1159
1160 pub fn dispatch(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1167 let mut result = self.dispatch_unredacted(call, ctx);
1168 if !ctx.secrets.is_empty() {
1169 result.content = ctx.secrets.redact(&result.content);
1170 result.error = result.error.map(|error| ctx.secrets.redact(&error));
1171 for value in result.metadata.values_mut() {
1174 redact_value(value, ctx);
1175 }
1176 }
1177 result
1178 }
1179
1180 fn dispatch_unredacted(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1181 match self.get(&call.name) {
1182 Some(_) if !ctx.scope_allows(&call.name) => scope_refusal(call, ctx),
1183 Some(_) if !ctx.allowed_tool(&call.name) => skill_refusal(call, ctx),
1184 Some(tool) => match with_secrets(tool.as_ref(), call, ctx) {
1185 Ok(call) => {
1186 let (call, repaired) = repaired_call(tool.as_ref(), call);
1187 let mut result = tool.run(&call, ctx);
1188 if !result.ok {
1189 if let Some(hint) = unparsed_json_hint(&tool.parameters(), &call.arguments)
1190 {
1191 let error = result.error.get_or_insert_with(String::new);
1192 error.push('\n');
1193 error.push_str(&hint);
1194 }
1195 }
1196 if !repaired.is_empty() {
1197 result
1198 .metadata
1199 .insert(ARGS_REPAIRED_KEY.to_owned(), json!(repaired));
1200 }
1201 result
1202 }
1203 Err(error) => ToolResult {
1204 call_id: call.id.clone(),
1205 ..failure(&call.name, error)
1206 },
1207 },
1208 None => ToolResult {
1209 call_id: call.id.clone(),
1210 ..failure(
1211 &call.name,
1212 format!(
1213 "Unknown tool '{}'. Available: {}.",
1214 call.name,
1215 self.names().join(", ")
1216 ),
1217 )
1218 },
1219 }
1220 }
1221}
1222
1223pub fn with_secrets<'a>(
1227 tool: &dyn Tool,
1228 call: &'a ToolCall,
1229 ctx: &ToolContext,
1230) -> Result<std::borrow::Cow<'a, ToolCall>, String> {
1231 if !tool.expands_secrets() {
1232 return Ok(std::borrow::Cow::Borrowed(call));
1233 }
1234 let Value::Object(arguments) = ctx
1235 .secrets
1236 .expand_value(&Value::Object(call.arguments.clone()))?
1237 else {
1238 unreachable!("an object expands to an object")
1239 };
1240 Ok(std::borrow::Cow::Owned(ToolCall {
1241 arguments,
1242 ..call.clone()
1243 }))
1244}
1245
1246pub const ARGS_REPAIRED_KEY: &str = "args_repaired";
1249
1250fn repaired_call<'a>(
1253 tool: &dyn Tool,
1254 call: std::borrow::Cow<'a, ToolCall>,
1255) -> (std::borrow::Cow<'a, ToolCall>, Vec<String>) {
1256 let Some((arguments, repaired)) = repair_arguments(&tool.parameters(), &call.arguments) else {
1257 return (call, Vec::new());
1258 };
1259 let call = ToolCall {
1260 arguments,
1261 ..call.into_owned()
1262 };
1263 (std::borrow::Cow::Owned(call), repaired)
1264}
1265
1266pub fn repair_arguments(
1277 schema: &Value,
1278 arguments: &Map<String, Value>,
1279) -> Option<(Map<String, Value>, Vec<String>)> {
1280 let properties = schema.get("properties")?.as_object()?;
1281 let mut repaired_arguments = arguments.clone();
1282 let mut repaired = Vec::new();
1283 for (name, value) in arguments {
1284 let (Value::String(text), Some(property)) = (value, properties.get(name)) else {
1285 continue;
1286 };
1287 let accepted = accepted_types(property);
1288 if accepted.contains(&"string") {
1289 continue;
1290 }
1291 let Ok(parsed) = serde_json::from_str::<Value>(text.trim()) else {
1292 continue;
1293 };
1294 let kind = match parsed {
1295 Value::Array(_) => "array",
1296 Value::Object(_) => "object",
1297 _ => continue,
1298 };
1299 if accepted.contains(&kind) {
1300 repaired_arguments.insert(name.clone(), parsed);
1301 repaired.push(name.clone());
1302 }
1303 }
1304 (!repaired.is_empty()).then_some((repaired_arguments, repaired))
1305}
1306
1307pub fn unparsed_json_hint(schema: &Value, arguments: &Map<String, Value>) -> Option<String> {
1314 let properties = schema.get("properties")?.as_object()?;
1315 let hints: Vec<String> = arguments
1316 .iter()
1317 .filter_map(|(name, value)| {
1318 let text = value.as_str()?.trim();
1319 let accepted = accepted_types(properties.get(name)?);
1320 let wanted = match text.chars().next()? {
1321 '[' if accepted.contains(&"array") => "array",
1322 '{' if accepted.contains(&"object") => "object",
1323 _ => return None,
1324 };
1325 if accepted.contains(&"string") {
1326 return None;
1327 }
1328 let error = serde_json::from_str::<Value>(text).err()?;
1329 Some(format!(
1330 "'{name}' was sent as a string holding JSON that does not parse ({error}). \
1331 Send it as a JSON {wanted} itself, not inside a string, and check that \
1332 every bracket and brace closes in order."
1333 ))
1334 })
1335 .collect();
1336 (!hints.is_empty()).then(|| hints.join("\n"))
1337}
1338
1339fn accepted_types(property: &Value) -> Vec<&str> {
1342 let mut types = Vec::new();
1343 match property.get("type") {
1344 Some(Value::String(kind)) => types.push(kind.as_str()),
1345 Some(Value::Array(kinds)) => types.extend(kinds.iter().filter_map(Value::as_str)),
1346 _ => {}
1347 }
1348 for key in ["anyOf", "oneOf"] {
1349 if let Some(branches) = property.get(key).and_then(Value::as_array) {
1350 for branch in branches {
1351 types.extend(accepted_types(branch));
1352 }
1353 }
1354 }
1355 types
1356}
1357
1358pub fn scope_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1361 let label = ctx
1362 .scope
1363 .as_deref()
1364 .map_or("", |scope| scope.label.as_str());
1365 ToolResult {
1366 call_id: call.id.clone(),
1367 ..failure(
1368 &call.name,
1369 format!(
1370 "Tool '{}' is not permitted for the '{label}' sub-agent. Use only the tools you \
1371 were given.",
1372 call.name
1373 ),
1374 )
1375 }
1376}
1377
1378fn skill_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1381 let skill = ctx.active_skill();
1382 let (name, allowed) = skill
1383 .as_deref()
1384 .map(|skill| (skill.name.as_str(), skill.allowed_tools.join(", ")))
1385 .unwrap_or_default();
1386 ToolResult {
1387 call_id: call.id.clone(),
1388 ..failure(
1389 &call.name,
1390 format!(
1391 "Tool '{}' is not permitted while the skill '{name}' is active. That skill's \
1392 allowed-tools are: {allowed}. Use one of those, or finish with the skill first.",
1393 call.name
1394 ),
1395 )
1396 }
1397}
1398
1399fn same_tool(a: &Arc<dyn Tool>, b: &Arc<dyn Tool>) -> bool {
1400 std::ptr::eq(Arc::as_ptr(a).cast::<()>(), Arc::as_ptr(b).cast::<()>())
1401}
1402
1403pub fn default_registry(
1409 with_memory: bool,
1410 with_skills: bool,
1411 with_delegate: bool,
1412 with_secrets: bool,
1413) -> ToolRegistry {
1414 let registry = builtin_registry();
1415 for tool in [
1416 Box::new(search::SearchFilesTool) as Box<dyn Tool>,
1417 Box::new(search::FindFilesTool),
1418 ] {
1419 registry
1420 .register(tool)
1421 .expect("search tool names are unique");
1422 }
1423 if with_memory {
1424 for tool in [
1425 Box::new(memory::RememberTool) as Box<dyn Tool>,
1426 Box::new(memory::RecallTool),
1427 ] {
1428 registry
1429 .register(tool)
1430 .expect("memory tool names are unique");
1431 }
1432 }
1433 if with_skills {
1434 registry
1435 .register(Box::new(skills::UseSkillTool))
1436 .expect("use_skill is unique");
1437 }
1438 if with_delegate {
1439 registry
1440 .register(Box::new(delegate::DelegateTool))
1441 .expect("delegate is unique");
1442 }
1443 if with_secrets {
1444 registry
1445 .register(Box::new(secret::RequestSecretTool))
1446 .expect("request_secret is unique");
1447 }
1448 registry
1449}
1450
1451pub fn builtin_registry() -> ToolRegistry {
1453 let registry = ToolRegistry::new();
1454 for tool in [
1455 Box::new(files::ReadFileTool) as Box<dyn Tool>,
1456 Box::new(files::WriteFileTool),
1457 Box::new(files::EditFileTool),
1458 Box::new(files::ListDirTool),
1459 Box::new(exec::RunCommandTool),
1460 Box::new(exec::PythonExecTool),
1461 Box::new(web::WebFetchTool),
1462 ] {
1463 registry
1464 .register(tool)
1465 .expect("built-in tool names are unique");
1466 }
1467 registry
1468}