1pub mod ask_user;
10pub mod delegate;
11pub mod exec;
12pub mod files;
13pub mod memory;
14#[cfg(feature = "agent86ui")]
15pub mod render_ui;
16pub mod sandbox;
17pub mod search;
18pub mod secret;
19pub mod skills;
20pub mod web;
21
22use crate::types::{ToolCall, ToolResult, ToolSpec};
23use sandbox::Executor;
24use serde_json::{json, Map, Value};
25use std::path::{Component, Path, PathBuf};
26use std::sync::{Arc, RwLock};
27use std::time::Duration;
28
29pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum ToolError {
35 InvalidArguments(Vec<String>),
37 Raised { exception: String, message: String },
39}
40
41impl ToolError {
42 fn raised(exception: &str, message: impl Into<String>) -> Self {
43 Self::Raised {
44 exception: exception.to_owned(),
45 message: message.into(),
46 }
47 }
48
49 pub fn editor(message: impl Into<String>) -> Self {
51 Self::raised("OSError", message)
52 }
53
54 pub fn io(error: &std::io::Error) -> Self {
56 let exception = match error.kind() {
57 std::io::ErrorKind::NotFound => "FileNotFoundError",
58 std::io::ErrorKind::PermissionDenied => "PermissionError",
59 std::io::ErrorKind::IsADirectory => "IsADirectoryError",
60 std::io::ErrorKind::NotADirectory => "NotADirectoryError",
61 _ => "OSError",
62 };
63 Self::raised(exception, error.to_string())
64 }
65}
66
67pub trait Tool: Send + Sync {
69 fn name(&self) -> &str;
70 fn description(&self) -> &str;
71
72 fn side_effecting(&self) -> bool {
74 false
75 }
76
77 fn parallel_safe(&self) -> bool {
80 true
81 }
82
83 fn expands_secrets(&self) -> bool {
88 false
89 }
90
91 fn retry_hint(&self) -> Option<&str> {
96 None
97 }
98
99 fn parameters(&self) -> Value;
101
102 fn preview(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
106 None
107 }
108
109 fn guarded_target(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
115 None
116 }
117
118 fn change(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<FileChange> {
124 None
125 }
126
127 fn preview_lexer(&self) -> Option<&'static str> {
130 None
131 }
132
133 fn execute(
135 &self,
136 args: &Map<String, Value>,
137 ctx: &ToolContext,
138 ) -> Result<ToolResult, ToolError>;
139
140 fn spec(&self) -> ToolSpec {
142 ToolSpec {
143 name: self.name().to_owned(),
144 description: self.description().to_owned(),
145 parameters: self.parameters(),
146 side_effecting: self.side_effecting(),
147 }
148 }
149
150 fn run(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
152 let mut result = match self.execute(&call.arguments, ctx) {
153 Ok(result) => result,
154 Err(ToolError::InvalidArguments(errors)) => failure(
155 self.name(),
156 format!(
157 "Invalid arguments for '{}': {}",
158 self.name(),
159 errors.join("; ")
160 ),
161 ),
162 Err(ToolError::Raised { exception, message }) => {
163 failure(self.name(), format!("{exception}: {message}"))
164 }
165 };
166 if result.call_id.is_empty() {
167 result.call_id = call.id.clone();
168 }
169 if result.name.is_empty() {
170 result.name = self.name().to_owned();
171 }
172 result
173 }
174}
175
176pub const MAX_CHANGE_TEXT_BYTES: usize = 256 * 1024;
179
180#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct FileChange {
187 pub path: String,
189 pub old_text: Option<String>,
191 pub new_text: String,
192 pub line: Option<usize>,
194}
195
196impl FileChange {
197 pub fn capped(target: &Path, old_text: Option<&str>, new_text: &str) -> Option<Self> {
199 let over = |text: &str| text.len() > MAX_CHANGE_TEXT_BYTES;
200 if over(new_text) || old_text.is_some_and(over) {
201 return None;
202 }
203 Some(Self {
204 path: display_path(target),
205 old_text: old_text.map(str::to_owned),
206 new_text: new_text.to_owned(),
207 line: first_changed_line(old_text, new_text),
208 })
209 }
210
211 pub fn redacted(mut self, secrets: &crate::vault::SecretVault) -> Self {
213 if !secrets.is_empty() {
214 self.path = secrets.redact(&self.path);
215 self.old_text = self.old_text.map(|text| secrets.redact(&text));
216 self.new_text = secrets.redact(&self.new_text);
217 }
218 self
219 }
220
221 pub fn record(&self, metadata: &mut Map<String, Value>) {
223 metadata.insert("abs_path".to_owned(), json!(self.path));
224 metadata.insert("old_text".to_owned(), json!(self.old_text));
225 metadata.insert("new_text".to_owned(), json!(self.new_text));
226 metadata.insert("line".to_owned(), json!(self.line));
227 }
228
229 pub fn record_write(
233 target: &Path,
234 old_text: Option<&str>,
235 new_text: &str,
236 metadata: &mut Map<String, Value>,
237 ) {
238 match Self::capped(target, old_text, new_text) {
239 Some(change) => change.record(metadata),
240 None => {
241 metadata.insert("abs_path".to_owned(), json!(display_path(target)));
242 metadata.insert(
243 "line".to_owned(),
244 json!(first_changed_line(old_text, new_text)),
245 );
246 }
247 }
248 }
249
250 pub fn from_metadata(metadata: &Map<String, Value>) -> Option<Self> {
252 Some(Self {
253 path: metadata.get("abs_path")?.as_str()?.to_owned(),
254 old_text: match metadata.get("old_text")? {
255 Value::Null => None,
256 value => Some(value.as_str()?.to_owned()),
257 },
258 new_text: metadata.get("new_text")?.as_str()?.to_owned(),
259 line: metadata
260 .get("line")
261 .and_then(Value::as_u64)
262 .and_then(|line| usize::try_from(line).ok()),
263 })
264 }
265}
266
267pub fn first_changed_line(old: Option<&str>, new: &str) -> Option<usize> {
270 let Some(old) = old else {
271 return Some(1);
272 };
273 if old == new {
274 return None;
275 }
276 let mut old_lines = old.split('\n');
277 let mut new_lines = new.split('\n');
278 let mut line: usize = 1;
279 loop {
280 match (old_lines.next(), new_lines.next()) {
281 (Some(a), Some(b)) if a == b => line += 1,
282 (Some(_), None) => return Some(line.saturating_sub(1).max(1)),
284 _ => return Some(line),
285 }
286 }
287}
288
289pub fn success(name: &str, content: String) -> ToolResult {
291 ToolResult {
292 call_id: String::new(),
293 name: name.to_owned(),
294 ok: true,
295 content,
296 error: None,
297 metadata: Map::new(),
298 }
299}
300
301pub fn failure(name: &str, error: String) -> ToolResult {
303 ToolResult {
304 call_id: String::new(),
305 name: name.to_owned(),
306 ok: false,
307 content: String::new(),
308 error: Some(error),
309 metadata: Map::new(),
310 }
311}
312
313pub struct Arguments<'a> {
317 args: &'a Map<String, Value>,
318 errors: Vec<String>,
319}
320
321impl<'a> Arguments<'a> {
322 pub fn new(args: &'a Map<String, Value>) -> Self {
323 Self {
324 args,
325 errors: Vec::new(),
326 }
327 }
328
329 pub fn string(&mut self, field: &str, default: Option<&str>) -> String {
331 match (self.args.get(field), default) {
332 (Some(Value::String(value)), _) => value.clone(),
333 (Some(_), _) => {
334 self.errors
335 .push(format!("{field}: Input should be a valid string"));
336 String::new()
337 }
338 (None, Some(default)) => default.to_owned(),
339 (None, None) => {
340 self.errors.push(format!("{field}: Field required"));
341 String::new()
342 }
343 }
344 }
345
346 pub fn optional_string(&mut self, field: &str) -> Option<String> {
348 match self.args.get(field) {
349 None | Some(Value::Null) => None,
350 Some(Value::String(value)) => Some(value.clone()),
351 Some(_) => {
352 self.errors
353 .push(format!("{field}: Input should be a valid string"));
354 None
355 }
356 }
357 }
358
359 pub fn string_list(&mut self, field: &str) -> Vec<String> {
362 match self.args.get(field) {
363 None | Some(Value::Null) => Vec::new(),
364 Some(Value::Array(items)) => {
365 let mut values = Vec::new();
366 for (index, item) in items.iter().enumerate() {
367 match item {
368 Value::String(text) => values.push(text.clone()),
369 _ => self
370 .errors
371 .push(format!("{field}.{index}: Input should be a valid string")),
372 }
373 }
374 values
375 }
376 Some(_) => {
377 self.errors
378 .push(format!("{field}: Input should be a valid list"));
379 Vec::new()
380 }
381 }
382 }
383
384 pub fn string_alias(&mut self, names: &[&str]) -> String {
387 match names.iter().find(|name| self.args.contains_key(**name)) {
388 Some(name) => self.string(name, None),
389 None => {
390 self.errors.push(format!("{}: Field required", names[0]));
391 String::new()
392 }
393 }
394 }
395
396 pub fn boolean(&mut self, field: &str, default: bool) -> bool {
399 const PLAIN: &str = "Input should be a valid boolean";
400 const UNINTERPRETABLE: &str = "Input should be a valid boolean, unable to interpret input";
401 let parsed = match self.args.get(field) {
402 None => return default,
403 Some(Value::Bool(flag)) => Ok(*flag),
404 Some(Value::Number(number)) => {
405 let value = number.as_f64().unwrap_or(f64::NAN);
406 if value == 0.0 {
407 Ok(false)
408 } else if value == 1.0 {
409 Ok(true)
410 } else if number.is_f64() && value.fract() != 0.0 {
411 Err(PLAIN)
412 } else {
413 Err(UNINTERPRETABLE)
414 }
415 }
416 Some(Value::String(text)) => match text.to_lowercase().as_str() {
417 "0" | "off" | "f" | "false" | "n" | "no" => Ok(false),
418 "1" | "on" | "t" | "true" | "y" | "yes" => Ok(true),
419 _ => Err(UNINTERPRETABLE),
420 },
421 Some(_) => Err(PLAIN),
422 };
423 parsed.unwrap_or_else(|message| {
424 self.errors.push(format!("{field}: {message}"));
425 default
426 })
427 }
428
429 pub fn string_map(&mut self, field: &str) -> Map<String, Value> {
432 match self.args.get(field) {
433 None => Map::new(),
434 Some(Value::Object(map)) => {
435 for (key, value) in map {
436 if !value.is_string() {
437 self.errors
438 .push(format!("{field}.{key}: Input should be a valid string"));
439 }
440 }
441 map.clone()
442 }
443 Some(_) => {
444 self.errors
445 .push(format!("{field}: Input should be a valid dictionary"));
446 Map::new()
447 }
448 }
449 }
450
451 pub fn integer(&mut self, field: &str, default: i64) -> i64 {
455 const PLAIN: &str = "Input should be a valid integer";
456 const UNPARSABLE: &str =
457 "Input should be a valid integer, unable to parse string as an integer";
458 let parsed = match self.args.get(field) {
459 None => return default,
460 Some(Value::Bool(flag)) => Ok(i64::from(*flag)),
461 Some(Value::Number(number)) => match (number.as_i64(), number.as_u64()) {
462 (Some(value), _) => Ok(value),
463 (None, Some(_)) => Ok(i64::MAX),
464 (None, None) => {
465 let value = number.as_f64().unwrap_or(f64::NAN);
466 if value.fract() != 0.0 {
467 Err("Input should be a valid integer, got a number with a fractional part")
468 } else if value.abs() > i64::MAX as f64 {
469 Err("Unable to parse input string as an integer, exceeded maximum size")
470 } else {
471 Ok(value as i64)
472 }
473 }
474 },
475 Some(Value::String(text)) => parse_python_int(text).ok_or(UNPARSABLE),
476 Some(_) => Err(PLAIN),
477 };
478 parsed.unwrap_or_else(|message| {
479 self.errors.push(format!("{field}: {message}"));
480 default
481 })
482 }
483
484 pub fn bounded_integer(&mut self, field: &str, default: i64, min: i64, max: i64) -> i64 {
487 let before = self.errors.len();
488 let value = self.integer(field, default);
489 if self.errors.len() > before {
490 return default;
491 }
492 if value < min {
493 self.errors.push(format!(
494 "{field}: Input should be greater than or equal to {min}"
495 ));
496 default
497 } else if value > max {
498 self.errors.push(format!(
499 "{field}: Input should be less than or equal to {max}"
500 ));
501 default
502 } else {
503 value
504 }
505 }
506
507 pub fn choice(&mut self, field: &str, choices: &[&str]) -> String {
509 match self.args.get(field) {
510 Some(Value::String(value)) if choices.contains(&value.as_str()) => value.clone(),
511 None => {
512 self.errors.push(format!("{field}: Field required"));
513 String::new()
514 }
515 Some(_) => {
516 let quoted: Vec<String> =
517 choices.iter().map(|choice| format!("'{choice}'")).collect();
518 let listed = match quoted.split_last() {
519 Some((last, rest)) if !rest.is_empty() => {
520 format!("{} or {last}", rest.join(", "))
521 }
522 _ => quoted.concat(),
523 };
524 self.errors
525 .push(format!("{field}: Input should be {listed}"));
526 String::new()
527 }
528 }
529 }
530
531 pub fn finish(self) -> Result<(), ToolError> {
533 if self.errors.is_empty() {
534 Ok(())
535 } else {
536 Err(ToolError::InvalidArguments(self.errors))
537 }
538 }
539}
540
541fn parse_python_int(text: &str) -> Option<i64> {
543 let text = text.trim();
544 let text = match text.split_once('.') {
546 Some((whole, zeros)) if !zeros.is_empty() && zeros.bytes().all(|b| b == b'0') => whole,
547 Some(_) => return None,
548 None => text,
549 };
550 let (negative, digits) = match text.as_bytes().first() {
551 Some(b'-') => (true, &text[1..]),
552 Some(b'+') => (false, &text[1..]),
553 _ => (false, text),
554 };
555 if digits.is_empty()
557 || digits.starts_with('_')
558 || digits.ends_with('_')
559 || digits.contains("__")
560 || !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')
561 {
562 return None;
563 }
564 let mut value: i64 = 0;
565 for digit in digits.bytes().filter(u8::is_ascii_digit) {
566 value = value
567 .saturating_mul(10)
568 .saturating_add(i64::from(digit - b'0'));
569 }
570 Some(if negative {
571 value.saturating_neg()
572 } else {
573 value
574 })
575}
576
577#[derive(Debug, Clone, PartialEq, Eq)]
579pub struct SandboxPolicy {
580 workspace: PathBuf,
582 allow_paths: Vec<PathBuf>,
586 guarded_roots: Vec<PathBuf>,
589 pub max_output_chars: usize,
590 pub timeout: Duration,
592 pub env_passthrough: Vec<String>,
594 pub network: bool,
596}
597
598impl SandboxPolicy {
599 pub fn new(workspace: &Path) -> std::io::Result<Self> {
601 Ok(Self {
602 workspace: std::fs::canonicalize(workspace)?,
603 allow_paths: Vec::new(),
604 guarded_roots: Vec::new(),
605 max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
606 timeout: Duration::from_secs(30),
607 env_passthrough: Vec::new(),
608 network: true,
609 })
610 }
611
612 pub fn workspace(&self) -> &Path {
613 &self.workspace
614 }
615
616 pub fn rerooted(&self, root: &Path, keep: Vec<PathBuf>) -> std::io::Result<Self> {
621 let mut policy = self.clone();
622 policy.workspace = std::fs::canonicalize(root)?;
623 let allowed = std::mem::take(&mut policy.allow_paths);
624 policy.allow(allowed.into_iter().chain(keep));
625 Ok(policy)
626 }
627
628 pub fn allow(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
631 for root in roots {
632 if !root.starts_with(&self.workspace) && !self.allow_paths.contains(&root) {
633 self.allow_paths.push(root);
634 }
635 }
636 }
637
638 pub fn guard(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
642 for root in roots {
643 let root = resolve(&root);
644 if !self.guarded_roots.contains(&root) {
645 self.guarded_roots.push(root);
646 }
647 }
648 }
649
650 pub fn guarded(&self, target: &Path) -> bool {
662 if self
663 .allow_paths
664 .iter()
665 .chain(&self.guarded_roots)
666 .any(|root| target.starts_with(root))
667 {
668 return true;
669 }
670 let Ok(inside) = target.strip_prefix(&self.workspace) else {
671 return false;
672 };
673 let names: Vec<String> = inside
674 .components()
675 .take(2)
676 .filter_map(|component| match component {
677 Component::Normal(name) => Some(
678 name.to_string_lossy()
679 .trim_end_matches(['.', ' '])
680 .to_ascii_lowercase(),
681 ),
682 _ => None,
683 })
684 .collect();
685 match names.as_slice() {
686 [first, ..] if first == ".agent86" => true,
687 [first, second] => first == ".claude" && second == "skills",
688 _ => false,
689 }
690 }
691
692 pub fn resolve_within(&self, path: &str) -> Result<PathBuf, ToolError> {
697 let candidate = resolve(&self.workspace.join(path));
698 let inside = std::iter::once(&self.workspace)
699 .chain(&self.allow_paths)
700 .any(|root| candidate.starts_with(root));
701 if inside {
702 Ok(candidate)
703 } else {
704 Err(ToolError::raised(
705 "PolicyError",
706 format!(
707 "Path '{path}' resolves outside the workspace jail ({}).",
708 display_path(&self.workspace)
709 ),
710 ))
711 }
712 }
713
714 pub fn root_of(&self, path: &Path) -> Option<&Path> {
718 std::iter::once(&self.workspace)
719 .chain(&self.allow_paths)
720 .find(|root| path.starts_with(root))
721 .map(PathBuf::as_path)
722 }
723
724 pub fn require_network(&self) -> Result<(), ToolError> {
726 if self.network {
727 Ok(())
728 } else {
729 Err(ToolError::raised(
730 "PolicyError",
731 "Network access is disabled by the sandbox policy.",
732 ))
733 }
734 }
735
736 pub fn truncate(&self, text: String) -> String {
738 let length = text.chars().count();
739 if length <= self.max_output_chars {
740 return text;
741 }
742 let kept: String = text.chars().take(self.max_output_chars).collect();
743 format!(
744 "{kept}\n... [truncated {} bytes]",
745 length - self.max_output_chars
746 )
747 }
748}
749
750fn resolve(path: &Path) -> PathBuf {
762 resolve_following(path, 0)
763}
764
765const MAX_LINKS: usize = 40;
767
768fn resolve_following(path: &Path, links: usize) -> PathBuf {
769 let mut resolved = PathBuf::new();
770 for component in path.components() {
771 match component {
772 Component::Prefix(_) | Component::RootDir => resolved.push(component),
773 Component::CurDir => {}
774 Component::ParentDir => {
775 resolved.pop();
776 }
777 Component::Normal(part) => {
778 resolved.push(part);
779 if let Ok(real) = std::fs::canonicalize(&resolved) {
780 resolved = real;
781 } else if links < MAX_LINKS {
782 if let Ok(target) = std::fs::read_link(&resolved) {
783 let base = resolved.parent().map(Path::to_path_buf).unwrap_or_default();
784 resolved = resolve_following(&base.join(target), links + 1);
785 }
786 }
787 }
788 }
789 }
790 resolved
791}
792
793fn redact_value(value: &mut Value, ctx: &ToolContext) {
795 match value {
796 Value::String(text) => *text = ctx.secrets.redact(text),
797 Value::Array(items) => items.iter_mut().for_each(|item| redact_value(item, ctx)),
798 Value::Object(map) => map.values_mut().for_each(|item| redact_value(item, ctx)),
799 _ => {}
800 }
801}
802
803pub fn plain_path(path: &Path) -> PathBuf {
807 PathBuf::from(display_path(path))
808}
809
810pub fn display_path(path: &Path) -> String {
812 let text = path.display().to_string();
813 if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
814 format!(r"\\{rest}")
815 } else if let Some(rest) = text.strip_prefix(r"\\?\") {
816 rest.to_owned()
817 } else {
818 text
819 }
820}
821
822pub trait EditorFiles: Send + Sync + std::fmt::Debug {
828 fn read_text(&self, path: &Path) -> Option<String>;
832
833 fn write_text(&self, path: &Path, content: &str) -> Option<Result<(), String>>;
837}
838
839#[derive(Debug, Clone)]
841pub struct ToolContext {
842 pub policy: SandboxPolicy,
843 pub executor: Executor,
845 pub web: web::WebSettings,
847 pub memory: Option<crate::session::SessionStore>,
849 pub skills: Arc<crate::skills::Skills>,
851 active_skill: Arc<std::sync::Mutex<Option<Arc<crate::skills::Skill>>>>,
854 pub secrets: crate::vault::SecretVault,
857 pub editor: Option<Arc<dyn EditorFiles>>,
860 pub specialties: Arc<crate::agents_def::Specialties>,
862 pub scope: Option<Arc<ToolScope>>,
866 pub can_delegate: bool,
870 pub fanout: Option<Arc<crate::subagent::FanOut>>,
874 pub fresh_clients: bool,
877 pub worktree: Option<Arc<crate::worktree::Worktree>>,
880 pub card: Option<Arc<crate::subagent::Card>>,
883 pub subagent: Option<Arc<crate::subagent::SubagentRun>>,
886 pub asker: crate::ask::Asker,
890 #[cfg(feature = "agent86ui")]
894 pub ui: Option<Arc<crate::agent86ui::UiSession>>,
895}
896
897#[derive(Debug, Clone, Default, PartialEq, Eq)]
902pub struct ToolScope {
903 pub label: String,
905 pub only: Option<Vec<String>>,
907 pub except: Vec<String>,
909 pub approval: Option<crate::types::ApprovalMode>,
911 pub confirm: Vec<String>,
913 pub preloaded: Vec<String>,
915 pub isolated: bool,
918}
919
920impl ToolScope {
921 pub fn allows(&self, name: &str) -> bool {
922 let named = self
923 .only
924 .as_ref()
925 .is_some_and(|only| only.iter().any(|tool| tool == name));
926 if self.isolated && name.starts_with("mcp__") && !named {
927 return false;
928 }
929 (self.only.is_none() || named) && !self.except.iter().any(|tool| tool == name)
930 }
931
932 pub fn within(mut self, outer: Option<&ToolScope>) -> Self {
934 let Some(outer) = outer else {
935 return self;
936 };
937 self.only = match (self.only.take(), &outer.only) {
938 (Some(mine), Some(theirs)) => Some(
939 mine.into_iter()
940 .filter(|tool| theirs.contains(tool))
941 .collect(),
942 ),
943 (Some(mine), None) => Some(mine),
944 (None, theirs) => theirs.clone(),
945 };
946 for tool in &outer.except {
947 if !self.except.contains(tool) {
948 self.except.push(tool.clone());
949 }
950 }
951 self.approval = stricter(self.approval, outer.approval);
952 self.isolated |= outer.isolated;
953 for tool in &outer.confirm {
954 if !self.confirm.contains(tool) {
955 self.confirm.push(tool.clone());
956 }
957 }
958 self
959 }
960}
961
962pub fn stricter(
964 a: Option<crate::types::ApprovalMode>,
965 b: Option<crate::types::ApprovalMode>,
966) -> Option<crate::types::ApprovalMode> {
967 use crate::types::ApprovalMode::{Ask, Auto, Deny};
968 let rank = |mode| match mode {
969 Deny => 2,
970 Ask => 1,
971 Auto => 0,
972 };
973 match (a, b) {
974 (Some(a), Some(b)) => Some(if rank(a) >= rank(b) { a } else { b }),
975 (a, None) => a,
976 (None, b) => b,
977 }
978}
979
980impl ToolContext {
981 pub fn new(workspace: &Path) -> std::io::Result<Self> {
983 Ok(Self {
984 policy: SandboxPolicy::new(workspace)?,
985 executor: Executor::Subprocess,
986 web: web::WebSettings::default(),
987 memory: None,
988 skills: Arc::default(),
989 active_skill: Arc::default(),
990 secrets: crate::vault::SecretVault::default(),
991 editor: None,
992 specialties: Arc::default(),
993 scope: None,
994 can_delegate: false,
995 fanout: None,
996 fresh_clients: false,
997 worktree: None,
998 card: None,
999 subagent: None,
1000 asker: crate::ask::Asker::default(),
1001 #[cfg(feature = "agent86ui")]
1002 ui: None,
1003 })
1004 }
1005
1006 fn active(&self) -> std::sync::MutexGuard<'_, Option<Arc<crate::skills::Skill>>> {
1007 self.active_skill
1008 .lock()
1009 .unwrap_or_else(std::sync::PoisonError::into_inner)
1010 }
1011
1012 pub fn activate_skill(&self, skill: &Arc<crate::skills::Skill>) {
1014 *self.active() = Some(Arc::clone(skill));
1015 }
1016
1017 pub fn clear_skill(&self) {
1019 *self.active() = None;
1020 }
1021
1022 pub fn fork(&self) -> Self {
1027 let mut forked = self.clone();
1028 forked.active_skill = Arc::new(std::sync::Mutex::new(self.active_skill()));
1029 forked.asker = crate::ask::Asker::default();
1030 #[cfg(feature = "agent86ui")]
1031 {
1032 forked.ui = None;
1033 }
1034 forked
1035 }
1036
1037 pub fn active_skill(&self) -> Option<Arc<crate::skills::Skill>> {
1038 self.active().clone()
1039 }
1040
1041 pub fn scope_allows(&self, name: &str) -> bool {
1043 self.scope.as_deref().is_none_or(|scope| scope.allows(name))
1044 }
1045
1046 pub fn allowed_tool(&self, name: &str) -> bool {
1050 if !self.scope_allows(name) {
1053 return false;
1054 }
1055 match self.active().as_deref() {
1056 Some(skill) if !skill.allowed_tools.is_empty() => {
1057 name == "use_skill" || skill.allowed_tools.iter().any(|tool| tool == name)
1058 }
1059 _ => true,
1060 }
1061 }
1062}
1063
1064#[derive(Default, Clone)]
1070pub struct ToolRegistry {
1071 inner: Arc<RwLock<RegistryInner>>,
1072}
1073
1074#[derive(Default)]
1075struct RegistryInner {
1076 tools: Vec<Arc<dyn Tool>>,
1078 collisions: Vec<String>,
1080}
1081
1082impl ToolRegistry {
1083 pub fn new() -> Self {
1084 Self::default()
1085 }
1086
1087 fn read(&self) -> std::sync::RwLockReadGuard<'_, RegistryInner> {
1088 self.inner
1089 .read()
1090 .unwrap_or_else(|poisoned| poisoned.into_inner())
1091 }
1092
1093 fn write(&self) -> std::sync::RwLockWriteGuard<'_, RegistryInner> {
1094 self.inner
1095 .write()
1096 .unwrap_or_else(|poisoned| poisoned.into_inner())
1097 }
1098
1099 pub fn register(&self, tool: Box<dyn Tool>) -> Result<(), String> {
1100 let mut inner = self.write();
1101 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1102 return Err(format!("Tool '{}' is already registered.", tool.name()));
1103 }
1104 inner.tools.push(Arc::from(tool));
1105 Ok(())
1106 }
1107
1108 pub fn try_register(&self, tool: Arc<dyn Tool>) -> bool {
1111 let mut inner = self.write();
1112 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1113 inner.collisions.push(tool.name().to_owned());
1114 return false;
1115 }
1116 inner.tools.push(tool);
1117 true
1118 }
1119
1120 pub fn register_shared(&self, tool: Arc<dyn Tool>) -> bool {
1125 let mut inner = self.write();
1126 if inner.tools.iter().any(|known| known.name() == tool.name()) {
1127 return false;
1128 }
1129 inner.tools.push(tool);
1130 true
1131 }
1132
1133 pub fn unregister_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1134 let mut inner = self.write();
1135 let before = inner.tools.len();
1136 inner.tools.retain(|known| !same_tool(known, tool));
1137 inner.tools.len() != before
1138 }
1139
1140 pub fn contains_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1142 self.read().tools.iter().any(|known| same_tool(known, tool))
1143 }
1144
1145 pub fn collisions(&self) -> Vec<String> {
1147 self.read().collisions.clone()
1148 }
1149
1150 pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
1151 self.read()
1152 .tools
1153 .iter()
1154 .find(|tool| tool.name() == name)
1155 .cloned()
1156 }
1157
1158 pub fn names(&self) -> Vec<String> {
1160 let mut names: Vec<String> = self
1161 .read()
1162 .tools
1163 .iter()
1164 .map(|tool| tool.name().to_owned())
1165 .collect();
1166 names.sort_unstable();
1167 names
1168 }
1169
1170 pub fn specs(&self) -> Vec<ToolSpec> {
1172 let tools: Vec<Arc<dyn Tool>> = self.read().tools.clone();
1173 tools.iter().map(|tool| tool.spec()).collect()
1174 }
1175
1176 pub fn dispatch(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1183 let mut result = self.dispatch_unredacted(call, ctx);
1184 if !ctx.secrets.is_empty() {
1185 result.content = ctx.secrets.redact(&result.content);
1186 result.error = result.error.map(|error| ctx.secrets.redact(&error));
1187 for value in result.metadata.values_mut() {
1190 redact_value(value, ctx);
1191 }
1192 }
1193 result
1194 }
1195
1196 fn dispatch_unredacted(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1197 match self.get(&call.name) {
1198 Some(_) if !ctx.scope_allows(&call.name) => scope_refusal(call, ctx),
1199 Some(_) if !ctx.allowed_tool(&call.name) => skill_refusal(call, ctx),
1200 Some(tool) => match with_secrets(tool.as_ref(), call, ctx) {
1201 Ok(call) => {
1202 let (call, repaired) = repaired_call(tool.as_ref(), call);
1203 let mut result = tool.run(&call, ctx);
1204 if !result.ok {
1205 if let Some(hint) = unparsed_json_hint(&tool.parameters(), &call.arguments)
1206 {
1207 let error = result.error.get_or_insert_with(String::new);
1208 error.push('\n');
1209 error.push_str(&hint);
1210 }
1211 }
1212 if !repaired.is_empty() {
1213 result
1214 .metadata
1215 .insert(ARGS_REPAIRED_KEY.to_owned(), json!(repaired));
1216 }
1217 result
1218 }
1219 Err(error) => ToolResult {
1220 call_id: call.id.clone(),
1221 ..failure(&call.name, error)
1222 },
1223 },
1224 None => ToolResult {
1225 call_id: call.id.clone(),
1226 ..failure(
1227 &call.name,
1228 format!(
1229 "Unknown tool '{}'. Available: {}.",
1230 call.name,
1231 self.names().join(", ")
1232 ),
1233 )
1234 },
1235 }
1236 }
1237}
1238
1239pub fn with_secrets<'a>(
1243 tool: &dyn Tool,
1244 call: &'a ToolCall,
1245 ctx: &ToolContext,
1246) -> Result<std::borrow::Cow<'a, ToolCall>, String> {
1247 if !tool.expands_secrets() {
1248 return Ok(std::borrow::Cow::Borrowed(call));
1249 }
1250 let Value::Object(arguments) = ctx
1251 .secrets
1252 .expand_value(&Value::Object(call.arguments.clone()))?
1253 else {
1254 unreachable!("an object expands to an object")
1255 };
1256 Ok(std::borrow::Cow::Owned(ToolCall {
1257 arguments,
1258 ..call.clone()
1259 }))
1260}
1261
1262pub const ARGS_REPAIRED_KEY: &str = "args_repaired";
1265
1266fn repaired_call<'a>(
1269 tool: &dyn Tool,
1270 call: std::borrow::Cow<'a, ToolCall>,
1271) -> (std::borrow::Cow<'a, ToolCall>, Vec<String>) {
1272 let Some((arguments, repaired)) = repair_arguments(&tool.parameters(), &call.arguments) else {
1273 return (call, Vec::new());
1274 };
1275 let call = ToolCall {
1276 arguments,
1277 ..call.into_owned()
1278 };
1279 (std::borrow::Cow::Owned(call), repaired)
1280}
1281
1282pub fn repair_arguments(
1293 schema: &Value,
1294 arguments: &Map<String, Value>,
1295) -> Option<(Map<String, Value>, Vec<String>)> {
1296 let properties = schema.get("properties")?.as_object()?;
1297 let mut repaired_arguments = arguments.clone();
1298 let mut repaired = Vec::new();
1299 for (name, value) in arguments {
1300 let (Value::String(text), Some(property)) = (value, properties.get(name)) else {
1301 continue;
1302 };
1303 let accepted = accepted_types(property);
1304 if accepted.contains(&"string") {
1305 continue;
1306 }
1307 let Ok(parsed) = serde_json::from_str::<Value>(text.trim()) else {
1308 continue;
1309 };
1310 let kind = match parsed {
1311 Value::Array(_) => "array",
1312 Value::Object(_) => "object",
1313 _ => continue,
1314 };
1315 if accepted.contains(&kind) {
1316 repaired_arguments.insert(name.clone(), parsed);
1317 repaired.push(name.clone());
1318 }
1319 }
1320 (!repaired.is_empty()).then_some((repaired_arguments, repaired))
1321}
1322
1323pub fn unparsed_json_hint(schema: &Value, arguments: &Map<String, Value>) -> Option<String> {
1330 let properties = schema.get("properties")?.as_object()?;
1331 let hints: Vec<String> = arguments
1332 .iter()
1333 .filter_map(|(name, value)| {
1334 let text = value.as_str()?.trim();
1335 let accepted = accepted_types(properties.get(name)?);
1336 let wanted = match text.chars().next()? {
1337 '[' if accepted.contains(&"array") => "array",
1338 '{' if accepted.contains(&"object") => "object",
1339 _ => return None,
1340 };
1341 if accepted.contains(&"string") {
1342 return None;
1343 }
1344 let error = serde_json::from_str::<Value>(text).err()?;
1345 Some(format!(
1346 "'{name}' was sent as a string holding JSON that does not parse ({error}). \
1347 Send it as a JSON {wanted} itself, not inside a string, and check that \
1348 every bracket and brace closes in order."
1349 ))
1350 })
1351 .collect();
1352 (!hints.is_empty()).then(|| hints.join("\n"))
1353}
1354
1355fn accepted_types(property: &Value) -> Vec<&str> {
1358 let mut types = Vec::new();
1359 match property.get("type") {
1360 Some(Value::String(kind)) => types.push(kind.as_str()),
1361 Some(Value::Array(kinds)) => types.extend(kinds.iter().filter_map(Value::as_str)),
1362 _ => {}
1363 }
1364 for key in ["anyOf", "oneOf"] {
1365 if let Some(branches) = property.get(key).and_then(Value::as_array) {
1366 for branch in branches {
1367 types.extend(accepted_types(branch));
1368 }
1369 }
1370 }
1371 types
1372}
1373
1374pub fn scope_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1377 let label = ctx
1378 .scope
1379 .as_deref()
1380 .map_or("", |scope| scope.label.as_str());
1381 ToolResult {
1382 call_id: call.id.clone(),
1383 ..failure(
1384 &call.name,
1385 format!(
1386 "Tool '{}' is not permitted for the '{label}' sub-agent. Use only the tools you \
1387 were given.",
1388 call.name
1389 ),
1390 )
1391 }
1392}
1393
1394fn skill_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1397 let skill = ctx.active_skill();
1398 let (name, allowed) = skill
1399 .as_deref()
1400 .map(|skill| (skill.name.as_str(), skill.allowed_tools.join(", ")))
1401 .unwrap_or_default();
1402 ToolResult {
1403 call_id: call.id.clone(),
1404 ..failure(
1405 &call.name,
1406 format!(
1407 "Tool '{}' is not permitted while the skill '{name}' is active. That skill's \
1408 allowed-tools are: {allowed}. Use one of those, or finish with the skill first.",
1409 call.name
1410 ),
1411 )
1412 }
1413}
1414
1415fn same_tool(a: &Arc<dyn Tool>, b: &Arc<dyn Tool>) -> bool {
1416 std::ptr::eq(Arc::as_ptr(a).cast::<()>(), Arc::as_ptr(b).cast::<()>())
1417}
1418
1419pub fn default_registry(
1425 with_memory: bool,
1426 with_skills: bool,
1427 with_delegate: bool,
1428 with_secrets: bool,
1429) -> ToolRegistry {
1430 let registry = builtin_registry();
1431 for tool in [
1432 Box::new(search::SearchFilesTool) as Box<dyn Tool>,
1433 Box::new(search::FindFilesTool),
1434 ] {
1435 registry
1436 .register(tool)
1437 .expect("search tool names are unique");
1438 }
1439 if with_memory {
1440 for tool in [
1441 Box::new(memory::RememberTool) as Box<dyn Tool>,
1442 Box::new(memory::RecallTool),
1443 ] {
1444 registry
1445 .register(tool)
1446 .expect("memory tool names are unique");
1447 }
1448 }
1449 if with_skills {
1450 registry
1451 .register(Box::new(skills::UseSkillTool))
1452 .expect("use_skill is unique");
1453 }
1454 if with_delegate {
1455 registry
1456 .register(Box::new(delegate::DelegateTool))
1457 .expect("delegate is unique");
1458 }
1459 if with_secrets {
1460 registry
1461 .register(Box::new(secret::RequestSecretTool))
1462 .expect("request_secret is unique");
1463 }
1464 registry
1465}
1466
1467pub fn builtin_registry() -> ToolRegistry {
1469 let registry = ToolRegistry::new();
1470 for tool in [
1471 Box::new(files::ReadFileTool) as Box<dyn Tool>,
1472 Box::new(files::WriteFileTool),
1473 Box::new(files::EditFileTool),
1474 Box::new(files::ListDirTool),
1475 Box::new(exec::RunCommandTool),
1476 Box::new(exec::PythonExecTool),
1477 Box::new(web::WebFetchTool),
1478 ] {
1479 registry
1480 .register(tool)
1481 .expect("built-in tool names are unique");
1482 }
1483 registry
1484}