Skip to main content

agent86_core/tools/
mod.rs

1//! The tool layer, ported from Python's `tools/base.py`, `tools/registry.py`, and
2//! `tools/sandbox/policy.py`.
3//!
4//! A tool validates the model's arguments before anything runs. Invalid
5//! arguments, policy violations, and I/O failures all come back as a
6//! [`ToolResult`] with `ok = false` that the model can correct itself from;
7//! nothing a tool does can crash the agent loop.
8
9pub 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
26/// Default cap on a tool's output, in characters (Python's `max_output_bytes`).
27pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;
28
29/// Why a tool call failed before producing a result.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum ToolError {
32    /// Argument validation failed; each entry is `"<field>: <message>"`.
33    InvalidArguments(Vec<String>),
34    /// What Python reports as an exception escaping `execute`: `"<Exception>: <message>"`.
35    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    /// The editor refused or could not answer a file request (beyond Python).
47    pub fn editor(message: impl Into<String>) -> Self {
48        Self::raised("OSError", message)
49    }
50
51    /// Map an I/O error onto the Python exception class it would raise.
52    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
64/// A tool the model can call.
65pub trait Tool: Send + Sync {
66    fn name(&self) -> &str;
67    fn description(&self) -> &str;
68
69    /// True if invoking the tool causes an external side effect (gated by approvals).
70    fn side_effecting(&self) -> bool {
71        false
72    }
73
74    /// False for a tool that must not share a parallel batch even though it is
75    /// read-only, such as one that can reach the approval prompt.
76    fn parallel_safe(&self) -> bool {
77        true
78    }
79
80    /// Beyond Python: whether `${secret:NAME}` in this tool's string arguments is
81    /// replaced by the user's secret when it runs (`crate::vault`). Only for tools
82    /// that put a value where the user can see and approve it (a file write), never
83    /// one that would carry it onto a command line or to a server.
84    fn expands_secrets(&self) -> bool {
85        false
86    }
87
88    /// The JSON Schema of the arguments, exactly as Python's pydantic models advertise it.
89    fn parameters(&self) -> Value;
90
91    /// What this call would do, shown in the approval prompt before it runs (a
92    /// unified diff for a file write). Receives the raw, unvalidated arguments and
93    /// must never fail; `None` means the argument summary says it all.
94    fn preview(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
95        None
96    }
97
98    /// Beyond Python: the path this call would write if it is agent86's own
99    /// configuration or skills ([`SandboxPolicy::guarded`]), as the model gave it.
100    /// Such a write changes what agent86 runs from then on, so the approval gate
101    /// asks about it even in `auto` mode, and declines it with nobody to ask.
102    /// Receives the raw arguments and must never fail.
103    fn guarded_target(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
104        None
105    }
106
107    /// Beyond Python: the file text this call would change, before and after, for a
108    /// surface that shows a reviewable diff (an editor over ACP). Receives the raw
109    /// arguments (already expanded, for a tool that [`Tool::expands_secrets`]) and
110    /// must never fail; `None` when the call would not change a text file, or when
111    /// either side is over [`MAX_CHANGE_TEXT_BYTES`].
112    fn change(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<FileChange> {
113        None
114    }
115
116    /// What [`Tool::preview`] is written in (`diff`, `bash`, `python`), as Python's
117    /// `preview_lexer`, so the interface can colour it.
118    fn preview_lexer(&self) -> Option<&'static str> {
119        None
120    }
121
122    /// Run the tool. `ToolResult::call_id` may be left empty; [`Tool::run`] fills it in.
123    fn execute(
124        &self,
125        args: &Map<String, Value>,
126        ctx: &ToolContext,
127    ) -> Result<ToolResult, ToolError>;
128
129    /// Advertise this tool to the model.
130    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    /// Execute `call`, translating every failure into a structured result.
140    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
165/// Beyond Python: the most text, in bytes, a [`FileChange`] keeps on either side.
166/// Above it only the unified diff is kept, as before.
167pub const MAX_CHANGE_TEXT_BYTES: usize = 256 * 1024;
168
169/// Beyond Python: a text file's contents before and after a write, for an editor to
170/// show as a diff (ACP's `diff` content). `write_file` and `edit_file` put one in
171/// their result's metadata (`abs_path`, `old_text`, `new_text`, `line`) and give one
172/// for the approval ([`Tool::change`]); `dispatch` and `build_preview` redact it, so
173/// an expanded `${secret:NAME}` comes back as its placeholder.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct FileChange {
176    /// Absolute, jail-resolved, without Windows' `\\?\` prefix.
177    pub path: String,
178    /// `None` for a new file.
179    pub old_text: Option<String>,
180    pub new_text: String,
181    /// The first changed line, 1-based; `None` when nothing changes.
182    pub line: Option<usize>,
183}
184
185impl FileChange {
186    /// The change, unless either side is over [`MAX_CHANGE_TEXT_BYTES`].
187    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    /// The change with every vault value replaced by its placeholder.
201    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    /// Put this change into a result's metadata.
211    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    /// Record a write of `target` from `old_text` to `new_text` in a result's
219    /// metadata: the whole change under the cap, else only where it is
220    /// (`abs_path` and `line`), beside the unified diff the tool keeps anyway.
221    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    /// The change a result's metadata records, if it holds one.
240    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
256/// The first line, 1-based, where `new` differs from `old` (line 1 for a new file),
257/// or `None` when they are the same.
258pub 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            // A change at the very end (lines removed) is shown at the last line left.
272            (Some(_), None) => return Some(line.saturating_sub(1).max(1)),
273            _ => return Some(line),
274        }
275    }
276}
277
278/// A successful result with `content`.
279pub 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
290/// A failed result with `error`.
291pub 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
302/// Validates tool arguments with pydantic's semantics and messages.
303///
304/// Unknown keys are ignored, as pydantic does by default.
305pub 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    /// A string field; `default` makes it optional.
319    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    /// An `Optional[str]` field (default `None`); `null` reads as absent.
336    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    /// A `list[str]` field (default `[]`), each bad item reported under its index,
349    /// as pydantic does.
350    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    /// A string field accepted under any of `names` (pydantic's `AliasChoices`);
374    /// the first name present wins, and errors name the first choice.
375    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    /// A boolean field with pydantic's lax parsing: `true`/`false`, `0`/`1`, and
386    /// strings such as `"yes"`, `"off"`, or `"t"` in any case.
387    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    /// An optional `dict[str, str]` field (default `{}`), each bad value reported
419    /// under its own key, as pydantic does.
420    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    /// An `int` field with pydantic's lax parsing: integers, whole floats, booleans
441    /// (as 0 and 1), and strings of digits (with a sign, single underscores between
442    /// digits, surrounding whitespace, and a `.0` tail). Out-of-range values saturate.
443    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    /// An `int` field constrained to `min..=max`, as pydantic's `Field(ge=, le=)`
474    /// reports a value outside it.
475    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    /// A required `Literal[...]` string field.
497    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    /// `Err` with every collected error, or `Ok` when all fields were valid.
521    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
530/// A string pydantic's lax mode accepts as an `int`, saturating out of range.
531fn parse_python_int(text: &str) -> Option<i64> {
532    let text = text.trim();
533    // A whole number written with a zero fraction ("7.0", "7.00") counts.
534    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    // Digits with single underscores between them, as Python's `int()`.
545    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/// Constraints applied to every tool execution.
567#[derive(Debug, Clone, PartialEq, Eq)]
568pub struct SandboxPolicy {
569    /// The workspace root, fully resolved.
570    workspace: PathBuf,
571    /// Further roots tools may reach: the skill directories, so a skill's bundled
572    /// files can be read. (The jail has no read/write split, as in Python; a write
573    /// there still passes the approval gate.)
574    allow_paths: Vec<PathBuf>,
575    /// Beyond Python: further roots that hold agent86's own files (the user's
576    /// `~/.agent86`), for [`SandboxPolicy::guarded`]. They add nothing to the jail.
577    guarded_roots: Vec<PathBuf>,
578    pub max_output_chars: usize,
579    /// How long one sandboxed process may run before its tree is killed.
580    pub timeout: Duration,
581    /// Extra environment variable names forwarded into tool processes.
582    pub env_passthrough: Vec<String>,
583    /// Whether network access is allowed (`web_fetch`).
584    pub network: bool,
585}
586
587impl SandboxPolicy {
588    /// A policy jailed to `workspace`, which must exist.
589    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    /// This policy jailed to `root` instead (a git worktree, beyond Python), with its
606    /// guards, timeout, output cap, passthrough, and network kept, the roots it
607    /// already allowed, and `keep` (roots inside the old workspace that must stay
608    /// reachable at their real path, such as a project's skill directories).
609    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    /// Let tools also reach `roots` (already resolved), leaving out any inside the
618    /// workspace, as Python's `default_policy` does with the skill roots.
619    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    /// Also count `roots` as agent86's own files for [`SandboxPolicy::guarded`],
628    /// resolved as the jail resolves paths, so a workspace inside one (or equal to
629    /// it) is covered. The jail itself is unchanged.
630    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    /// Beyond Python: whether `target` (as [`SandboxPolicy::resolve_within`] gave it)
640    /// is agent86's own configuration or skills: the workspace's `.agent86/` or
641    /// `.claude/skills/`, a skill root outside the workspace (such as
642    /// `~/.agent86/skills`, which every project loads), or a root given to
643    /// [`SandboxPolicy::guard`] (the user's `~/.agent86`, so running in that very
644    /// directory still guards its `config.toml`). What is written there runs, or is
645    /// read as instructions, from then on.
646    ///
647    /// Names are compared as Windows and macOS do (ignoring ASCII case, and on
648    /// Windows the trailing dots and spaces it drops), so `.AGENT86./` is caught
649    /// too; on Linux that only asks about a little more than it must.
650    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    /// Resolve `path` (relative to the workspace) and enforce the jail.
682    ///
683    /// Resolution follows symlinks the way Python's `Path.resolve()` does, so a
684    /// link inside the workspace that points outside it is refused.
685    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    /// The jail root `path` (as [`SandboxPolicy::resolve_within`] gave it) lies
704    /// under: the workspace, or the allowed root holding it. The search tools keep
705    /// a walk inside the root it started in (beyond Python).
706    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    /// Fail unless network access is allowed.
714    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    /// Cap `text` at the output limit, saying how much was dropped.
726    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
739/// Make `path` absolute and canonical, like Python's non-strict `Path.resolve()`.
740///
741/// Each existing prefix is canonicalized (following symlinks) before the next
742/// component is applied, so `..` acts on the real location; components past the
743/// last existing directory are appended lexically.
744///
745/// A symlink whose target does not exist (yet) is followed too, as Python's
746/// `Path.resolve()` follows it: `canonicalize` fails on it, and keeping the link's
747/// own path would let `notes -> ~/.ssh/authorized_keys` pass the jail while a
748/// write through it lands outside. Links are followed at most [`MAX_LINKS`] deep,
749/// past which the OS refuses the path anyway.
750fn resolve(path: &Path) -> PathBuf {
751    resolve_following(path, 0)
752}
753
754/// How many dangling symlinks [`resolve`] follows in a chain, as Linux's limit.
755const 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
782/// Every string in `value`, however deep, with the user's secrets taken out.
783fn 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
792/// `path` without Windows' `\\?\` verbatim prefix, for handing to other programs:
793/// `cmd.exe` refuses a verbatim working directory and falls back to the Windows
794/// directory, so child processes must get the plain form.
795pub fn plain_path(path: &Path) -> PathBuf {
796    PathBuf::from(display_path(path))
797}
798
799/// A path for messages, without Windows' `\\?\` verbatim prefix.
800pub 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
811/// Where the editor driving the agent keeps its files (beyond Python; the ACP
812/// server installs it). The file tools read and write text through it when it is
813/// set, so they see unsaved buffers and the editor sees what the agent wrote; with
814/// none, they use the disk exactly as before. Paths are absolute and inside the
815/// workspace: the tools resolve them through the jail first.
816pub trait EditorFiles: Send + Sync + std::fmt::Debug {
817    /// The editor's text of `path`, or `None` when it has none to give (the editor
818    /// does not offer reads, does not know the file, or did not answer): the tool
819    /// then reads the disk.
820    fn read_text(&self, path: &Path) -> Option<String>;
821
822    /// Write `content` through the editor. `None` means the editor does not offer
823    /// writes, so the tool writes the disk; `Some(Err)` is the editor refusing, which
824    /// fails the call rather than writing around it.
825    fn write_text(&self, path: &Path, content: &str) -> Option<Result<(), String>>;
826}
827
828/// Ambient state handed to every tool at execution time.
829#[derive(Debug, Clone)]
830pub struct ToolContext {
831    pub policy: SandboxPolicy,
832    /// Where commands and Python snippets run.
833    pub executor: Executor,
834    /// `web_fetch` settings.
835    pub web: web::WebSettings,
836    /// Long-term memory for `remember` and `recall`; `None` when memory is off.
837    pub memory: Option<crate::session::SessionStore>,
838    /// The discovered skills, for `use_skill`.
839    pub skills: Arc<crate::skills::Skills>,
840    /// The skill `use_skill` activated this turn, whose `allowed-tools` restrict
841    /// what may run. Shared by clones of the context.
842    active_skill: Arc<std::sync::Mutex<Option<Arc<crate::skills::Skill>>>>,
843    /// Secrets the user entered (beyond Python): set in tool processes' environment,
844    /// and redacted from every result. Shared by clones and sub-agent forks.
845    pub secrets: crate::vault::SecretVault,
846    /// The editor's files, when an editor drives the agent. Shared by clones and
847    /// sub-agent forks.
848    pub editor: Option<Arc<dyn EditorFiles>>,
849    /// The specialist sub-agents (beyond Python), for `delegate` and `use_skill`.
850    pub specialties: Arc<crate::agents_def::Specialties>,
851    /// What narrows this context (beyond Python): the specialty it runs, or one it
852    /// was delegated from. Set once when a sub-agent is spawned (or for `run
853    /// --agent`), never by the model, and checked with the active skill's list.
854    pub scope: Option<Arc<ToolScope>>,
855    /// Whether a `use_skill` hand-off to a specialty could be made from here: the
856    /// harness delegates, `delegate` is offered at this depth, and this context may
857    /// call it. Set by the harness.
858    pub can_delegate: bool,
859    /// The fan-out this context's sub-agent belongs to (beyond Python): siblings
860    /// running at once share its spend and its stop. Inherited by forks, so a
861    /// sibling's own delegations stop with it.
862    pub fanout: Option<Arc<crate::subagent::FanOut>>,
863    /// On a fan-out thread: every sub-agent here calls a provider copy with an
864    /// HTTP client of its own ([`crate::provider::Provider::fresh`]).
865    pub fresh_clients: bool,
866    /// The git worktree this context is jailed to, when a specialty runs isolated;
867    /// a delegation from inside asking for isolation is served by the same one.
868    pub worktree: Option<Arc<crate::worktree::Worktree>>,
869    /// The card a sub-agent's progress is reported on (beyond Python): the
870    /// top-level delegation's, which nested runs share.
871    pub card: Option<Arc<crate::subagent::Card>>,
872    /// The sub-agent run this context belongs to (beyond Python), with its progress,
873    /// so a question it asks can say who asks. Set when a sub-agent is spawned.
874    pub subagent: Option<Arc<crate::subagent::SubagentRun>>,
875}
876
877/// What a specialist sub-agent may do (beyond Python): its tools, approval mode,
878/// and always-asked tools, already narrowed by whoever delegated to it. Authority
879/// only narrows: a nested delegation intersects the lists, keeps the stricter
880/// mode, and unites the always-asked tools.
881#[derive(Debug, Clone, Default, PartialEq, Eq)]
882pub struct ToolScope {
883    /// Who runs under it, for refusals and approval prompts: the specialty's name.
884    pub label: String,
885    /// Only these tools, when set.
886    pub only: Option<Vec<String>>,
887    /// Never these (a specialty with no `tools` line inherits all but `delegate`).
888    pub except: Vec<String>,
889    /// Applies only when stricter than the session's mode.
890    pub approval: Option<crate::types::ApprovalMode>,
891    /// Asked about in every mode but `deny`.
892    pub confirm: Vec<String>,
893    /// The skills preloaded into it, so `use_skill` does not hand one back to it.
894    pub preloaded: Vec<String>,
895    /// Runs in a git worktree: MCP tools, which act outside the jail, are allowed
896    /// only when `only` names them.
897    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    /// This scope narrowed by `outer`, the caller's.
913    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
942/// The stricter of two modes (`deny`, then `ask`, then `auto`); `None` imposes nothing.
943pub 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    /// A context jailed to `workspace`.
962    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    /// Make `skill` the active one, replacing (never stacking on) any other.
990    pub fn activate_skill(&self, skill: &Arc<crate::skills::Skill>) {
991        *self.active() = Some(Arc::clone(skill));
992    }
993
994    /// Lift the active skill's restriction, as the end of a turn does.
995    pub fn clear_skill(&self) {
996        *self.active() = None;
997    }
998
999    /// A copy for a sub-agent: the same tools and jail, and its own active skill,
1000    /// starting as this context's, so what it activates restricts only itself.
1001    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    /// Whether the specialty this context runs under (if any) permits `name`.
1012    pub fn scope_allows(&self, name: &str) -> bool {
1013        self.scope.as_deref().is_none_or(|scope| scope.allows(name))
1014    }
1015
1016    /// Whether `name` may be called now, given the active skill's `allowed-tools`.
1017    /// `use_skill` always may: it is how the model switches skills, and a skill
1018    /// that forgot to list it would otherwise be a one-way door.
1019    pub fn allowed_tool(&self, name: &str) -> bool {
1020        // A specialty's own list is not lifted for `use_skill`: it is set at spawn
1021        // and the model cannot change it.
1022        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/// Holds every available tool, exposes their specs, and dispatches calls.
1035///
1036/// Cloning shares the same tools: the MCP manager keeps a clone so it can take a
1037/// dropped server's tools out, and put them back on reconnect, while the agent
1038/// loop is using the registry, as Python's lock-guarded `ToolRegistry` allows.
1039#[derive(Default, Clone)]
1040pub struct ToolRegistry {
1041    inner: Arc<RwLock<RegistryInner>>,
1042}
1043
1044#[derive(Default)]
1045struct RegistryInner {
1046    /// In registration order, which is the order specs are advertised in.
1047    tools: Vec<Arc<dyn Tool>>,
1048    /// Names dropped by [`ToolRegistry::try_register`] because something already owned them.
1049    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    /// Register `tool` unless its name is taken, recording the clash if it is. The
1079    /// lenient path for mounting MCP tools, where one collision must not abort the run.
1080    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    /// Remove `tool` only if it is the object registered under its name, so a dropped
1091    /// MCP tool that lost a name collision never takes the winner out with it.
1092    /// Register a shared tool unless its name is taken, without recording a
1093    /// collision: for a change the user asked for, which reports its own.
1094    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    /// Is this exact tool object registered (not merely one with the same name)?
1111    pub fn contains_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1112        self.read().tools.iter().any(|known| same_tool(known, tool))
1113    }
1114
1115    /// Names [`ToolRegistry::try_register`] refused, in the order they were refused.
1116    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    /// Tool names, sorted.
1129    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    /// Specs in registration order.
1141    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    /// Run `call`. The lock is released before the tool runs, so a long call never
1147    /// blocks the MCP manager from updating the registry.
1148    ///
1149    /// Every result passes through here, from the loop, its parallel reads, and
1150    /// sub-agents, so this is where a secret the user entered is taken out of what a
1151    /// tool returns, before the model, the transcript, or the trace sees it.
1152    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            // The metadata is kept too (the session's steps, the transcript), and a
1158            // file tool's diff in it comes from the expanded arguments.
1159            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
1201/// `call` as `tool` runs it: with `${secret:NAME}` in its arguments replaced by the
1202/// values, for a tool that [`Tool::expands_secrets`], or unchanged. The call the
1203/// loop keeps (history, trace, approval summary) is never the expanded one.
1204pub 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
1224/// The `ToolResult::metadata` key under which [`ToolRegistry::dispatch`] lists the
1225/// parameters it repaired, so the loop can record a `tool_args_repaired` event.
1226pub const ARGS_REPAIRED_KEY: &str = "args_repaired";
1227
1228/// `call` with its JSON-string arguments repaired against `tool`'s schema, and the
1229/// names of the parameters repaired. The call the loop keeps is never this one.
1230fn 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
1244/// Beyond Python: models sometimes send an array or an object argument as a JSON
1245/// string (`"[\"markdown\"]"` where the schema wants `["markdown"]`), which the
1246/// tool then rejects and the turn loses a step. When a parameter's schema accepts
1247/// an array or an object but not a string, and the model sent a string that parses
1248/// as JSON of that kind, the parsed value is used. Anything else is left alone, so
1249/// the error the model gets for it is unchanged, and a string parameter that
1250/// happens to hold JSON is never touched.
1251///
1252/// `None` when nothing needed repair, else the repaired arguments and the names of
1253/// the parameters that were.
1254pub 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
1285/// The JSON types a property schema accepts: its `type` (a name or a list), and
1286/// those of its `anyOf`/`oneOf` branches (pydantic writes `Optional[list]` that way).
1287fn 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
1304/// The answer to a call outside the running specialty's tools, naming what it
1305/// may use so the model can re-plan.
1306pub 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
1324/// The answer to a call the active skill's `allowed-tools` forbid, naming the
1325/// skill and its list so the model can re-plan rather than retry.
1326fn 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
1349/// Python's built-in tools, then, beyond Python, the read-only search tools
1350/// (`search_files`, `find_files`), then `remember` and `recall` when memory is on,
1351/// `use_skill` when a skill was found, and `delegate` when `[agents]` is on, in
1352/// Python's registration order (`default_registry`). Last, beyond Python,
1353/// `request_secret` when someone is there to answer it (`with_secrets`).
1354pub 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
1397/// Python's built-in tools, in its registration order.
1398pub 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}