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;
13#[cfg(feature = "agent86ui")]
14pub mod render_ui;
15pub mod sandbox;
16pub mod search;
17pub mod secret;
18pub mod skills;
19pub mod web;
20
21use crate::types::{ToolCall, ToolResult, ToolSpec};
22use sandbox::Executor;
23use serde_json::{json, Map, Value};
24use std::path::{Component, Path, PathBuf};
25use std::sync::{Arc, RwLock};
26use std::time::Duration;
27
28/// Default cap on a tool's output, in characters (Python's `max_output_bytes`).
29pub const DEFAULT_MAX_OUTPUT_CHARS: usize = 100_000;
30
31/// Why a tool call failed before producing a result.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum ToolError {
34    /// Argument validation failed; each entry is `"<field>: <message>"`.
35    InvalidArguments(Vec<String>),
36    /// What Python reports as an exception escaping `execute`: `"<Exception>: <message>"`.
37    Raised { exception: String, message: String },
38}
39
40impl ToolError {
41    fn raised(exception: &str, message: impl Into<String>) -> Self {
42        Self::Raised {
43            exception: exception.to_owned(),
44            message: message.into(),
45        }
46    }
47
48    /// The editor refused or could not answer a file request (beyond Python).
49    pub fn editor(message: impl Into<String>) -> Self {
50        Self::raised("OSError", message)
51    }
52
53    /// Map an I/O error onto the Python exception class it would raise.
54    pub fn io(error: &std::io::Error) -> Self {
55        let exception = match error.kind() {
56            std::io::ErrorKind::NotFound => "FileNotFoundError",
57            std::io::ErrorKind::PermissionDenied => "PermissionError",
58            std::io::ErrorKind::IsADirectory => "IsADirectoryError",
59            std::io::ErrorKind::NotADirectory => "NotADirectoryError",
60            _ => "OSError",
61        };
62        Self::raised(exception, error.to_string())
63    }
64}
65
66/// A tool the model can call.
67pub trait Tool: Send + Sync {
68    fn name(&self) -> &str;
69    fn description(&self) -> &str;
70
71    /// True if invoking the tool causes an external side effect (gated by approvals).
72    fn side_effecting(&self) -> bool {
73        false
74    }
75
76    /// False for a tool that must not share a parallel batch even though it is
77    /// read-only, such as one that can reach the approval prompt.
78    fn parallel_safe(&self) -> bool {
79        true
80    }
81
82    /// Beyond Python: whether `${secret:NAME}` in this tool's string arguments is
83    /// replaced by the user's secret when it runs (`crate::vault`). Only for tools
84    /// that put a value where the user can see and approve it (a file write), never
85    /// one that would carry it onto a command line or to a server.
86    fn expands_secrets(&self) -> bool {
87        false
88    }
89
90    /// The JSON Schema of the arguments, exactly as Python's pydantic models advertise it.
91    fn parameters(&self) -> Value;
92
93    /// What this call would do, shown in the approval prompt before it runs (a
94    /// unified diff for a file write). Receives the raw, unvalidated arguments and
95    /// must never fail; `None` means the argument summary says it all.
96    fn preview(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
97        None
98    }
99
100    /// Beyond Python: the path this call would write if it is agent86's own
101    /// configuration or skills ([`SandboxPolicy::guarded`]), as the model gave it.
102    /// Such a write changes what agent86 runs from then on, so the approval gate
103    /// asks about it even in `auto` mode, and declines it with nobody to ask.
104    /// Receives the raw arguments and must never fail.
105    fn guarded_target(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<String> {
106        None
107    }
108
109    /// Beyond Python: the file text this call would change, before and after, for a
110    /// surface that shows a reviewable diff (an editor over ACP). Receives the raw
111    /// arguments (already expanded, for a tool that [`Tool::expands_secrets`]) and
112    /// must never fail; `None` when the call would not change a text file, or when
113    /// either side is over [`MAX_CHANGE_TEXT_BYTES`].
114    fn change(&self, _args: &Map<String, Value>, _ctx: &ToolContext) -> Option<FileChange> {
115        None
116    }
117
118    /// What [`Tool::preview`] is written in (`diff`, `bash`, `python`), as Python's
119    /// `preview_lexer`, so the interface can colour it.
120    fn preview_lexer(&self) -> Option<&'static str> {
121        None
122    }
123
124    /// Run the tool. `ToolResult::call_id` may be left empty; [`Tool::run`] fills it in.
125    fn execute(
126        &self,
127        args: &Map<String, Value>,
128        ctx: &ToolContext,
129    ) -> Result<ToolResult, ToolError>;
130
131    /// Advertise this tool to the model.
132    fn spec(&self) -> ToolSpec {
133        ToolSpec {
134            name: self.name().to_owned(),
135            description: self.description().to_owned(),
136            parameters: self.parameters(),
137            side_effecting: self.side_effecting(),
138        }
139    }
140
141    /// Execute `call`, translating every failure into a structured result.
142    fn run(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
143        let mut result = match self.execute(&call.arguments, ctx) {
144            Ok(result) => result,
145            Err(ToolError::InvalidArguments(errors)) => failure(
146                self.name(),
147                format!(
148                    "Invalid arguments for '{}': {}",
149                    self.name(),
150                    errors.join("; ")
151                ),
152            ),
153            Err(ToolError::Raised { exception, message }) => {
154                failure(self.name(), format!("{exception}: {message}"))
155            }
156        };
157        if result.call_id.is_empty() {
158            result.call_id = call.id.clone();
159        }
160        if result.name.is_empty() {
161            result.name = self.name().to_owned();
162        }
163        result
164    }
165}
166
167/// Beyond Python: the most text, in bytes, a [`FileChange`] keeps on either side.
168/// Above it only the unified diff is kept, as before.
169pub const MAX_CHANGE_TEXT_BYTES: usize = 256 * 1024;
170
171/// Beyond Python: a text file's contents before and after a write, for an editor to
172/// show as a diff (ACP's `diff` content). `write_file` and `edit_file` put one in
173/// their result's metadata (`abs_path`, `old_text`, `new_text`, `line`) and give one
174/// for the approval ([`Tool::change`]); `dispatch` and `build_preview` redact it, so
175/// an expanded `${secret:NAME}` comes back as its placeholder.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct FileChange {
178    /// Absolute, jail-resolved, without Windows' `\\?\` prefix.
179    pub path: String,
180    /// `None` for a new file.
181    pub old_text: Option<String>,
182    pub new_text: String,
183    /// The first changed line, 1-based; `None` when nothing changes.
184    pub line: Option<usize>,
185}
186
187impl FileChange {
188    /// The change, unless either side is over [`MAX_CHANGE_TEXT_BYTES`].
189    pub fn capped(target: &Path, old_text: Option<&str>, new_text: &str) -> Option<Self> {
190        let over = |text: &str| text.len() > MAX_CHANGE_TEXT_BYTES;
191        if over(new_text) || old_text.is_some_and(over) {
192            return None;
193        }
194        Some(Self {
195            path: display_path(target),
196            old_text: old_text.map(str::to_owned),
197            new_text: new_text.to_owned(),
198            line: first_changed_line(old_text, new_text),
199        })
200    }
201
202    /// The change with every vault value replaced by its placeholder.
203    pub fn redacted(mut self, secrets: &crate::vault::SecretVault) -> Self {
204        if !secrets.is_empty() {
205            self.path = secrets.redact(&self.path);
206            self.old_text = self.old_text.map(|text| secrets.redact(&text));
207            self.new_text = secrets.redact(&self.new_text);
208        }
209        self
210    }
211
212    /// Put this change into a result's metadata.
213    pub fn record(&self, metadata: &mut Map<String, Value>) {
214        metadata.insert("abs_path".to_owned(), json!(self.path));
215        metadata.insert("old_text".to_owned(), json!(self.old_text));
216        metadata.insert("new_text".to_owned(), json!(self.new_text));
217        metadata.insert("line".to_owned(), json!(self.line));
218    }
219
220    /// Record a write of `target` from `old_text` to `new_text` in a result's
221    /// metadata: the whole change under the cap, else only where it is
222    /// (`abs_path` and `line`), beside the unified diff the tool keeps anyway.
223    pub fn record_write(
224        target: &Path,
225        old_text: Option<&str>,
226        new_text: &str,
227        metadata: &mut Map<String, Value>,
228    ) {
229        match Self::capped(target, old_text, new_text) {
230            Some(change) => change.record(metadata),
231            None => {
232                metadata.insert("abs_path".to_owned(), json!(display_path(target)));
233                metadata.insert(
234                    "line".to_owned(),
235                    json!(first_changed_line(old_text, new_text)),
236                );
237            }
238        }
239    }
240
241    /// The change a result's metadata records, if it holds one.
242    pub fn from_metadata(metadata: &Map<String, Value>) -> Option<Self> {
243        Some(Self {
244            path: metadata.get("abs_path")?.as_str()?.to_owned(),
245            old_text: match metadata.get("old_text")? {
246                Value::Null => None,
247                value => Some(value.as_str()?.to_owned()),
248            },
249            new_text: metadata.get("new_text")?.as_str()?.to_owned(),
250            line: metadata
251                .get("line")
252                .and_then(Value::as_u64)
253                .and_then(|line| usize::try_from(line).ok()),
254        })
255    }
256}
257
258/// The first line, 1-based, where `new` differs from `old` (line 1 for a new file),
259/// or `None` when they are the same.
260pub fn first_changed_line(old: Option<&str>, new: &str) -> Option<usize> {
261    let Some(old) = old else {
262        return Some(1);
263    };
264    if old == new {
265        return None;
266    }
267    let mut old_lines = old.split('\n');
268    let mut new_lines = new.split('\n');
269    let mut line: usize = 1;
270    loop {
271        match (old_lines.next(), new_lines.next()) {
272            (Some(a), Some(b)) if a == b => line += 1,
273            // A change at the very end (lines removed) is shown at the last line left.
274            (Some(_), None) => return Some(line.saturating_sub(1).max(1)),
275            _ => return Some(line),
276        }
277    }
278}
279
280/// A successful result with `content`.
281pub fn success(name: &str, content: String) -> ToolResult {
282    ToolResult {
283        call_id: String::new(),
284        name: name.to_owned(),
285        ok: true,
286        content,
287        error: None,
288        metadata: Map::new(),
289    }
290}
291
292/// A failed result with `error`.
293pub fn failure(name: &str, error: String) -> ToolResult {
294    ToolResult {
295        call_id: String::new(),
296        name: name.to_owned(),
297        ok: false,
298        content: String::new(),
299        error: Some(error),
300        metadata: Map::new(),
301    }
302}
303
304/// Validates tool arguments with pydantic's semantics and messages.
305///
306/// Unknown keys are ignored, as pydantic does by default.
307pub struct Arguments<'a> {
308    args: &'a Map<String, Value>,
309    errors: Vec<String>,
310}
311
312impl<'a> Arguments<'a> {
313    pub fn new(args: &'a Map<String, Value>) -> Self {
314        Self {
315            args,
316            errors: Vec::new(),
317        }
318    }
319
320    /// A string field; `default` makes it optional.
321    pub fn string(&mut self, field: &str, default: Option<&str>) -> String {
322        match (self.args.get(field), default) {
323            (Some(Value::String(value)), _) => value.clone(),
324            (Some(_), _) => {
325                self.errors
326                    .push(format!("{field}: Input should be a valid string"));
327                String::new()
328            }
329            (None, Some(default)) => default.to_owned(),
330            (None, None) => {
331                self.errors.push(format!("{field}: Field required"));
332                String::new()
333            }
334        }
335    }
336
337    /// An `Optional[str]` field (default `None`); `null` reads as absent.
338    pub fn optional_string(&mut self, field: &str) -> Option<String> {
339        match self.args.get(field) {
340            None | Some(Value::Null) => None,
341            Some(Value::String(value)) => Some(value.clone()),
342            Some(_) => {
343                self.errors
344                    .push(format!("{field}: Input should be a valid string"));
345                None
346            }
347        }
348    }
349
350    /// A `list[str]` field (default `[]`), each bad item reported under its index,
351    /// as pydantic does.
352    pub fn string_list(&mut self, field: &str) -> Vec<String> {
353        match self.args.get(field) {
354            None | Some(Value::Null) => Vec::new(),
355            Some(Value::Array(items)) => {
356                let mut values = Vec::new();
357                for (index, item) in items.iter().enumerate() {
358                    match item {
359                        Value::String(text) => values.push(text.clone()),
360                        _ => self
361                            .errors
362                            .push(format!("{field}.{index}: Input should be a valid string")),
363                    }
364                }
365                values
366            }
367            Some(_) => {
368                self.errors
369                    .push(format!("{field}: Input should be a valid list"));
370                Vec::new()
371            }
372        }
373    }
374
375    /// A string field accepted under any of `names` (pydantic's `AliasChoices`);
376    /// the first name present wins, and errors name the first choice.
377    pub fn string_alias(&mut self, names: &[&str]) -> String {
378        match names.iter().find(|name| self.args.contains_key(**name)) {
379            Some(name) => self.string(name, None),
380            None => {
381                self.errors.push(format!("{}: Field required", names[0]));
382                String::new()
383            }
384        }
385    }
386
387    /// A boolean field with pydantic's lax parsing: `true`/`false`, `0`/`1`, and
388    /// strings such as `"yes"`, `"off"`, or `"t"` in any case.
389    pub fn boolean(&mut self, field: &str, default: bool) -> bool {
390        const PLAIN: &str = "Input should be a valid boolean";
391        const UNINTERPRETABLE: &str = "Input should be a valid boolean, unable to interpret input";
392        let parsed = match self.args.get(field) {
393            None => return default,
394            Some(Value::Bool(flag)) => Ok(*flag),
395            Some(Value::Number(number)) => {
396                let value = number.as_f64().unwrap_or(f64::NAN);
397                if value == 0.0 {
398                    Ok(false)
399                } else if value == 1.0 {
400                    Ok(true)
401                } else if number.is_f64() && value.fract() != 0.0 {
402                    Err(PLAIN)
403                } else {
404                    Err(UNINTERPRETABLE)
405                }
406            }
407            Some(Value::String(text)) => match text.to_lowercase().as_str() {
408                "0" | "off" | "f" | "false" | "n" | "no" => Ok(false),
409                "1" | "on" | "t" | "true" | "y" | "yes" => Ok(true),
410                _ => Err(UNINTERPRETABLE),
411            },
412            Some(_) => Err(PLAIN),
413        };
414        parsed.unwrap_or_else(|message| {
415            self.errors.push(format!("{field}: {message}"));
416            default
417        })
418    }
419
420    /// An optional `dict[str, str]` field (default `{}`), each bad value reported
421    /// under its own key, as pydantic does.
422    pub fn string_map(&mut self, field: &str) -> Map<String, Value> {
423        match self.args.get(field) {
424            None => Map::new(),
425            Some(Value::Object(map)) => {
426                for (key, value) in map {
427                    if !value.is_string() {
428                        self.errors
429                            .push(format!("{field}.{key}: Input should be a valid string"));
430                    }
431                }
432                map.clone()
433            }
434            Some(_) => {
435                self.errors
436                    .push(format!("{field}: Input should be a valid dictionary"));
437                Map::new()
438            }
439        }
440    }
441
442    /// An `int` field with pydantic's lax parsing: integers, whole floats, booleans
443    /// (as 0 and 1), and strings of digits (with a sign, single underscores between
444    /// digits, surrounding whitespace, and a `.0` tail). Out-of-range values saturate.
445    pub fn integer(&mut self, field: &str, default: i64) -> i64 {
446        const PLAIN: &str = "Input should be a valid integer";
447        const UNPARSABLE: &str =
448            "Input should be a valid integer, unable to parse string as an integer";
449        let parsed = match self.args.get(field) {
450            None => return default,
451            Some(Value::Bool(flag)) => Ok(i64::from(*flag)),
452            Some(Value::Number(number)) => match (number.as_i64(), number.as_u64()) {
453                (Some(value), _) => Ok(value),
454                (None, Some(_)) => Ok(i64::MAX),
455                (None, None) => {
456                    let value = number.as_f64().unwrap_or(f64::NAN);
457                    if value.fract() != 0.0 {
458                        Err("Input should be a valid integer, got a number with a fractional part")
459                    } else if value.abs() > i64::MAX as f64 {
460                        Err("Unable to parse input string as an integer, exceeded maximum size")
461                    } else {
462                        Ok(value as i64)
463                    }
464                }
465            },
466            Some(Value::String(text)) => parse_python_int(text).ok_or(UNPARSABLE),
467            Some(_) => Err(PLAIN),
468        };
469        parsed.unwrap_or_else(|message| {
470            self.errors.push(format!("{field}: {message}"));
471            default
472        })
473    }
474
475    /// An `int` field constrained to `min..=max`, as pydantic's `Field(ge=, le=)`
476    /// reports a value outside it.
477    pub fn bounded_integer(&mut self, field: &str, default: i64, min: i64, max: i64) -> i64 {
478        let before = self.errors.len();
479        let value = self.integer(field, default);
480        if self.errors.len() > before {
481            return default;
482        }
483        if value < min {
484            self.errors.push(format!(
485                "{field}: Input should be greater than or equal to {min}"
486            ));
487            default
488        } else if value > max {
489            self.errors.push(format!(
490                "{field}: Input should be less than or equal to {max}"
491            ));
492            default
493        } else {
494            value
495        }
496    }
497
498    /// A required `Literal[...]` string field.
499    pub fn choice(&mut self, field: &str, choices: &[&str]) -> String {
500        match self.args.get(field) {
501            Some(Value::String(value)) if choices.contains(&value.as_str()) => value.clone(),
502            None => {
503                self.errors.push(format!("{field}: Field required"));
504                String::new()
505            }
506            Some(_) => {
507                let quoted: Vec<String> =
508                    choices.iter().map(|choice| format!("'{choice}'")).collect();
509                let listed = match quoted.split_last() {
510                    Some((last, rest)) if !rest.is_empty() => {
511                        format!("{} or {last}", rest.join(", "))
512                    }
513                    _ => quoted.concat(),
514                };
515                self.errors
516                    .push(format!("{field}: Input should be {listed}"));
517                String::new()
518            }
519        }
520    }
521
522    /// `Err` with every collected error, or `Ok` when all fields were valid.
523    pub fn finish(self) -> Result<(), ToolError> {
524        if self.errors.is_empty() {
525            Ok(())
526        } else {
527            Err(ToolError::InvalidArguments(self.errors))
528        }
529    }
530}
531
532/// A string pydantic's lax mode accepts as an `int`, saturating out of range.
533fn parse_python_int(text: &str) -> Option<i64> {
534    let text = text.trim();
535    // A whole number written with a zero fraction ("7.0", "7.00") counts.
536    let text = match text.split_once('.') {
537        Some((whole, zeros)) if !zeros.is_empty() && zeros.bytes().all(|b| b == b'0') => whole,
538        Some(_) => return None,
539        None => text,
540    };
541    let (negative, digits) = match text.as_bytes().first() {
542        Some(b'-') => (true, &text[1..]),
543        Some(b'+') => (false, &text[1..]),
544        _ => (false, text),
545    };
546    // Digits with single underscores between them, as Python's `int()`.
547    if digits.is_empty()
548        || digits.starts_with('_')
549        || digits.ends_with('_')
550        || digits.contains("__")
551        || !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')
552    {
553        return None;
554    }
555    let mut value: i64 = 0;
556    for digit in digits.bytes().filter(u8::is_ascii_digit) {
557        value = value
558            .saturating_mul(10)
559            .saturating_add(i64::from(digit - b'0'));
560    }
561    Some(if negative {
562        value.saturating_neg()
563    } else {
564        value
565    })
566}
567
568/// Constraints applied to every tool execution.
569#[derive(Debug, Clone, PartialEq, Eq)]
570pub struct SandboxPolicy {
571    /// The workspace root, fully resolved.
572    workspace: PathBuf,
573    /// Further roots tools may reach: the skill directories, so a skill's bundled
574    /// files can be read. (The jail has no read/write split, as in Python; a write
575    /// there still passes the approval gate.)
576    allow_paths: Vec<PathBuf>,
577    /// Beyond Python: further roots that hold agent86's own files (the user's
578    /// `~/.agent86`), for [`SandboxPolicy::guarded`]. They add nothing to the jail.
579    guarded_roots: Vec<PathBuf>,
580    pub max_output_chars: usize,
581    /// How long one sandboxed process may run before its tree is killed.
582    pub timeout: Duration,
583    /// Extra environment variable names forwarded into tool processes.
584    pub env_passthrough: Vec<String>,
585    /// Whether network access is allowed (`web_fetch`).
586    pub network: bool,
587}
588
589impl SandboxPolicy {
590    /// A policy jailed to `workspace`, which must exist.
591    pub fn new(workspace: &Path) -> std::io::Result<Self> {
592        Ok(Self {
593            workspace: std::fs::canonicalize(workspace)?,
594            allow_paths: Vec::new(),
595            guarded_roots: Vec::new(),
596            max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
597            timeout: Duration::from_secs(30),
598            env_passthrough: Vec::new(),
599            network: true,
600        })
601    }
602
603    pub fn workspace(&self) -> &Path {
604        &self.workspace
605    }
606
607    /// This policy jailed to `root` instead (a git worktree, beyond Python), with its
608    /// guards, timeout, output cap, passthrough, and network kept, the roots it
609    /// already allowed, and `keep` (roots inside the old workspace that must stay
610    /// reachable at their real path, such as a project's skill directories).
611    pub fn rerooted(&self, root: &Path, keep: Vec<PathBuf>) -> std::io::Result<Self> {
612        let mut policy = self.clone();
613        policy.workspace = std::fs::canonicalize(root)?;
614        let allowed = std::mem::take(&mut policy.allow_paths);
615        policy.allow(allowed.into_iter().chain(keep));
616        Ok(policy)
617    }
618
619    /// Let tools also reach `roots` (already resolved), leaving out any inside the
620    /// workspace, as Python's `default_policy` does with the skill roots.
621    pub fn allow(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
622        for root in roots {
623            if !root.starts_with(&self.workspace) && !self.allow_paths.contains(&root) {
624                self.allow_paths.push(root);
625            }
626        }
627    }
628
629    /// Also count `roots` as agent86's own files for [`SandboxPolicy::guarded`],
630    /// resolved as the jail resolves paths, so a workspace inside one (or equal to
631    /// it) is covered. The jail itself is unchanged.
632    pub fn guard(&mut self, roots: impl IntoIterator<Item = PathBuf>) {
633        for root in roots {
634            let root = resolve(&root);
635            if !self.guarded_roots.contains(&root) {
636                self.guarded_roots.push(root);
637            }
638        }
639    }
640
641    /// Beyond Python: whether `target` (as [`SandboxPolicy::resolve_within`] gave it)
642    /// is agent86's own configuration or skills: the workspace's `.agent86/` or
643    /// `.claude/skills/`, a skill root outside the workspace (such as
644    /// `~/.agent86/skills`, which every project loads), or a root given to
645    /// [`SandboxPolicy::guard`] (the user's `~/.agent86`, so running in that very
646    /// directory still guards its `config.toml`). What is written there runs, or is
647    /// read as instructions, from then on.
648    ///
649    /// Names are compared as Windows and macOS do (ignoring ASCII case, and on
650    /// Windows the trailing dots and spaces it drops), so `.AGENT86./` is caught
651    /// too; on Linux that only asks about a little more than it must.
652    pub fn guarded(&self, target: &Path) -> bool {
653        if self
654            .allow_paths
655            .iter()
656            .chain(&self.guarded_roots)
657            .any(|root| target.starts_with(root))
658        {
659            return true;
660        }
661        let Ok(inside) = target.strip_prefix(&self.workspace) else {
662            return false;
663        };
664        let names: Vec<String> = inside
665            .components()
666            .take(2)
667            .filter_map(|component| match component {
668                Component::Normal(name) => Some(
669                    name.to_string_lossy()
670                        .trim_end_matches(['.', ' '])
671                        .to_ascii_lowercase(),
672                ),
673                _ => None,
674            })
675            .collect();
676        match names.as_slice() {
677            [first, ..] if first == ".agent86" => true,
678            [first, second] => first == ".claude" && second == "skills",
679            _ => false,
680        }
681    }
682
683    /// Resolve `path` (relative to the workspace) and enforce the jail.
684    ///
685    /// Resolution follows symlinks the way Python's `Path.resolve()` does, so a
686    /// link inside the workspace that points outside it is refused.
687    pub fn resolve_within(&self, path: &str) -> Result<PathBuf, ToolError> {
688        let candidate = resolve(&self.workspace.join(path));
689        let inside = std::iter::once(&self.workspace)
690            .chain(&self.allow_paths)
691            .any(|root| candidate.starts_with(root));
692        if inside {
693            Ok(candidate)
694        } else {
695            Err(ToolError::raised(
696                "PolicyError",
697                format!(
698                    "Path '{path}' resolves outside the workspace jail ({}).",
699                    display_path(&self.workspace)
700                ),
701            ))
702        }
703    }
704
705    /// The jail root `path` (as [`SandboxPolicy::resolve_within`] gave it) lies
706    /// under: the workspace, or the allowed root holding it. The search tools keep
707    /// a walk inside the root it started in (beyond Python).
708    pub fn root_of(&self, path: &Path) -> Option<&Path> {
709        std::iter::once(&self.workspace)
710            .chain(&self.allow_paths)
711            .find(|root| path.starts_with(root))
712            .map(PathBuf::as_path)
713    }
714
715    /// Fail unless network access is allowed.
716    pub fn require_network(&self) -> Result<(), ToolError> {
717        if self.network {
718            Ok(())
719        } else {
720            Err(ToolError::raised(
721                "PolicyError",
722                "Network access is disabled by the sandbox policy.",
723            ))
724        }
725    }
726
727    /// Cap `text` at the output limit, saying how much was dropped.
728    pub fn truncate(&self, text: String) -> String {
729        let length = text.chars().count();
730        if length <= self.max_output_chars {
731            return text;
732        }
733        let kept: String = text.chars().take(self.max_output_chars).collect();
734        format!(
735            "{kept}\n... [truncated {} bytes]",
736            length - self.max_output_chars
737        )
738    }
739}
740
741/// Make `path` absolute and canonical, like Python's non-strict `Path.resolve()`.
742///
743/// Each existing prefix is canonicalized (following symlinks) before the next
744/// component is applied, so `..` acts on the real location; components past the
745/// last existing directory are appended lexically.
746///
747/// A symlink whose target does not exist (yet) is followed too, as Python's
748/// `Path.resolve()` follows it: `canonicalize` fails on it, and keeping the link's
749/// own path would let `notes -> ~/.ssh/authorized_keys` pass the jail while a
750/// write through it lands outside. Links are followed at most [`MAX_LINKS`] deep,
751/// past which the OS refuses the path anyway.
752fn resolve(path: &Path) -> PathBuf {
753    resolve_following(path, 0)
754}
755
756/// How many dangling symlinks [`resolve`] follows in a chain, as Linux's limit.
757const MAX_LINKS: usize = 40;
758
759fn resolve_following(path: &Path, links: usize) -> PathBuf {
760    let mut resolved = PathBuf::new();
761    for component in path.components() {
762        match component {
763            Component::Prefix(_) | Component::RootDir => resolved.push(component),
764            Component::CurDir => {}
765            Component::ParentDir => {
766                resolved.pop();
767            }
768            Component::Normal(part) => {
769                resolved.push(part);
770                if let Ok(real) = std::fs::canonicalize(&resolved) {
771                    resolved = real;
772                } else if links < MAX_LINKS {
773                    if let Ok(target) = std::fs::read_link(&resolved) {
774                        let base = resolved.parent().map(Path::to_path_buf).unwrap_or_default();
775                        resolved = resolve_following(&base.join(target), links + 1);
776                    }
777                }
778            }
779        }
780    }
781    resolved
782}
783
784/// Every string in `value`, however deep, with the user's secrets taken out.
785fn redact_value(value: &mut Value, ctx: &ToolContext) {
786    match value {
787        Value::String(text) => *text = ctx.secrets.redact(text),
788        Value::Array(items) => items.iter_mut().for_each(|item| redact_value(item, ctx)),
789        Value::Object(map) => map.values_mut().for_each(|item| redact_value(item, ctx)),
790        _ => {}
791    }
792}
793
794/// `path` without Windows' `\\?\` verbatim prefix, for handing to other programs:
795/// `cmd.exe` refuses a verbatim working directory and falls back to the Windows
796/// directory, so child processes must get the plain form.
797pub fn plain_path(path: &Path) -> PathBuf {
798    PathBuf::from(display_path(path))
799}
800
801/// A path for messages, without Windows' `\\?\` verbatim prefix.
802pub fn display_path(path: &Path) -> String {
803    let text = path.display().to_string();
804    if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
805        format!(r"\\{rest}")
806    } else if let Some(rest) = text.strip_prefix(r"\\?\") {
807        rest.to_owned()
808    } else {
809        text
810    }
811}
812
813/// Where the editor driving the agent keeps its files (beyond Python; the ACP
814/// server installs it). The file tools read and write text through it when it is
815/// set, so they see unsaved buffers and the editor sees what the agent wrote; with
816/// none, they use the disk exactly as before. Paths are absolute and inside the
817/// workspace: the tools resolve them through the jail first.
818pub trait EditorFiles: Send + Sync + std::fmt::Debug {
819    /// The editor's text of `path`, or `None` when it has none to give (the editor
820    /// does not offer reads, does not know the file, or did not answer): the tool
821    /// then reads the disk.
822    fn read_text(&self, path: &Path) -> Option<String>;
823
824    /// Write `content` through the editor. `None` means the editor does not offer
825    /// writes, so the tool writes the disk; `Some(Err)` is the editor refusing, which
826    /// fails the call rather than writing around it.
827    fn write_text(&self, path: &Path, content: &str) -> Option<Result<(), String>>;
828}
829
830/// Ambient state handed to every tool at execution time.
831#[derive(Debug, Clone)]
832pub struct ToolContext {
833    pub policy: SandboxPolicy,
834    /// Where commands and Python snippets run.
835    pub executor: Executor,
836    /// `web_fetch` settings.
837    pub web: web::WebSettings,
838    /// Long-term memory for `remember` and `recall`; `None` when memory is off.
839    pub memory: Option<crate::session::SessionStore>,
840    /// The discovered skills, for `use_skill`.
841    pub skills: Arc<crate::skills::Skills>,
842    /// The skill `use_skill` activated this turn, whose `allowed-tools` restrict
843    /// what may run. Shared by clones of the context.
844    active_skill: Arc<std::sync::Mutex<Option<Arc<crate::skills::Skill>>>>,
845    /// Secrets the user entered (beyond Python): set in tool processes' environment,
846    /// and redacted from every result. Shared by clones and sub-agent forks.
847    pub secrets: crate::vault::SecretVault,
848    /// The editor's files, when an editor drives the agent. Shared by clones and
849    /// sub-agent forks.
850    pub editor: Option<Arc<dyn EditorFiles>>,
851    /// The specialist sub-agents (beyond Python), for `delegate` and `use_skill`.
852    pub specialties: Arc<crate::agents_def::Specialties>,
853    /// What narrows this context (beyond Python): the specialty it runs, or one it
854    /// was delegated from. Set once when a sub-agent is spawned (or for `run
855    /// --agent`), never by the model, and checked with the active skill's list.
856    pub scope: Option<Arc<ToolScope>>,
857    /// Whether a `use_skill` hand-off to a specialty could be made from here: the
858    /// harness delegates, `delegate` is offered at this depth, and this context may
859    /// call it. Set by the harness.
860    pub can_delegate: bool,
861    /// The fan-out this context's sub-agent belongs to (beyond Python): siblings
862    /// running at once share its spend and its stop. Inherited by forks, so a
863    /// sibling's own delegations stop with it.
864    pub fanout: Option<Arc<crate::subagent::FanOut>>,
865    /// On a fan-out thread: every sub-agent here calls a provider copy with an
866    /// HTTP client of its own ([`crate::provider::Provider::fresh`]).
867    pub fresh_clients: bool,
868    /// The git worktree this context is jailed to, when a specialty runs isolated;
869    /// a delegation from inside asking for isolation is served by the same one.
870    pub worktree: Option<Arc<crate::worktree::Worktree>>,
871    /// The card a sub-agent's progress is reported on (beyond Python): the
872    /// top-level delegation's, which nested runs share.
873    pub card: Option<Arc<crate::subagent::Card>>,
874    /// The sub-agent run this context belongs to (beyond Python), with its progress,
875    /// so a question it asks can say who asks. Set when a sub-agent is spawned.
876    pub subagent: Option<Arc<crate::subagent::SubagentRun>>,
877    /// The renderer the embedder declared (beyond Python; ADR 0005), for
878    /// `render_ui`: its catalogs and the surfaces drawn. Shared by clones;
879    /// sub-agent forks have none, since only the main loop draws.
880    #[cfg(feature = "agent86ui")]
881    pub ui: Option<Arc<crate::agent86ui::UiSession>>,
882}
883
884/// What a specialist sub-agent may do (beyond Python): its tools, approval mode,
885/// and always-asked tools, already narrowed by whoever delegated to it. Authority
886/// only narrows: a nested delegation intersects the lists, keeps the stricter
887/// mode, and unites the always-asked tools.
888#[derive(Debug, Clone, Default, PartialEq, Eq)]
889pub struct ToolScope {
890    /// Who runs under it, for refusals and approval prompts: the specialty's name.
891    pub label: String,
892    /// Only these tools, when set.
893    pub only: Option<Vec<String>>,
894    /// Never these (a specialty with no `tools` line inherits all but `delegate`).
895    pub except: Vec<String>,
896    /// Applies only when stricter than the session's mode.
897    pub approval: Option<crate::types::ApprovalMode>,
898    /// Asked about in every mode but `deny`.
899    pub confirm: Vec<String>,
900    /// The skills preloaded into it, so `use_skill` does not hand one back to it.
901    pub preloaded: Vec<String>,
902    /// Runs in a git worktree: MCP tools, which act outside the jail, are allowed
903    /// only when `only` names them.
904    pub isolated: bool,
905}
906
907impl ToolScope {
908    pub fn allows(&self, name: &str) -> bool {
909        let named = self
910            .only
911            .as_ref()
912            .is_some_and(|only| only.iter().any(|tool| tool == name));
913        if self.isolated && name.starts_with("mcp__") && !named {
914            return false;
915        }
916        (self.only.is_none() || named) && !self.except.iter().any(|tool| tool == name)
917    }
918
919    /// This scope narrowed by `outer`, the caller's.
920    pub fn within(mut self, outer: Option<&ToolScope>) -> Self {
921        let Some(outer) = outer else {
922            return self;
923        };
924        self.only = match (self.only.take(), &outer.only) {
925            (Some(mine), Some(theirs)) => Some(
926                mine.into_iter()
927                    .filter(|tool| theirs.contains(tool))
928                    .collect(),
929            ),
930            (Some(mine), None) => Some(mine),
931            (None, theirs) => theirs.clone(),
932        };
933        for tool in &outer.except {
934            if !self.except.contains(tool) {
935                self.except.push(tool.clone());
936            }
937        }
938        self.approval = stricter(self.approval, outer.approval);
939        self.isolated |= outer.isolated;
940        for tool in &outer.confirm {
941            if !self.confirm.contains(tool) {
942                self.confirm.push(tool.clone());
943            }
944        }
945        self
946    }
947}
948
949/// The stricter of two modes (`deny`, then `ask`, then `auto`); `None` imposes nothing.
950pub fn stricter(
951    a: Option<crate::types::ApprovalMode>,
952    b: Option<crate::types::ApprovalMode>,
953) -> Option<crate::types::ApprovalMode> {
954    use crate::types::ApprovalMode::{Ask, Auto, Deny};
955    let rank = |mode| match mode {
956        Deny => 2,
957        Ask => 1,
958        Auto => 0,
959    };
960    match (a, b) {
961        (Some(a), Some(b)) => Some(if rank(a) >= rank(b) { a } else { b }),
962        (a, None) => a,
963        (None, b) => b,
964    }
965}
966
967impl ToolContext {
968    /// A context jailed to `workspace`.
969    pub fn new(workspace: &Path) -> std::io::Result<Self> {
970        Ok(Self {
971            policy: SandboxPolicy::new(workspace)?,
972            executor: Executor::Subprocess,
973            web: web::WebSettings::default(),
974            memory: None,
975            skills: Arc::default(),
976            active_skill: Arc::default(),
977            secrets: crate::vault::SecretVault::default(),
978            editor: None,
979            specialties: Arc::default(),
980            scope: None,
981            can_delegate: false,
982            fanout: None,
983            fresh_clients: false,
984            worktree: None,
985            card: None,
986            subagent: None,
987            #[cfg(feature = "agent86ui")]
988            ui: None,
989        })
990    }
991
992    fn active(&self) -> std::sync::MutexGuard<'_, Option<Arc<crate::skills::Skill>>> {
993        self.active_skill
994            .lock()
995            .unwrap_or_else(std::sync::PoisonError::into_inner)
996    }
997
998    /// Make `skill` the active one, replacing (never stacking on) any other.
999    pub fn activate_skill(&self, skill: &Arc<crate::skills::Skill>) {
1000        *self.active() = Some(Arc::clone(skill));
1001    }
1002
1003    /// Lift the active skill's restriction, as the end of a turn does.
1004    pub fn clear_skill(&self) {
1005        *self.active() = None;
1006    }
1007
1008    /// A copy for a sub-agent: the same tools and jail, and its own active skill,
1009    /// starting as this context's, so what it activates restricts only itself.
1010    /// It draws no UI: only the main loop has the renderer.
1011    pub fn fork(&self) -> Self {
1012        let mut forked = self.clone();
1013        forked.active_skill = Arc::new(std::sync::Mutex::new(self.active_skill()));
1014        #[cfg(feature = "agent86ui")]
1015        {
1016            forked.ui = None;
1017        }
1018        forked
1019    }
1020
1021    pub fn active_skill(&self) -> Option<Arc<crate::skills::Skill>> {
1022        self.active().clone()
1023    }
1024
1025    /// Whether the specialty this context runs under (if any) permits `name`.
1026    pub fn scope_allows(&self, name: &str) -> bool {
1027        self.scope.as_deref().is_none_or(|scope| scope.allows(name))
1028    }
1029
1030    /// Whether `name` may be called now, given the active skill's `allowed-tools`.
1031    /// `use_skill` always may: it is how the model switches skills, and a skill
1032    /// that forgot to list it would otherwise be a one-way door.
1033    pub fn allowed_tool(&self, name: &str) -> bool {
1034        // A specialty's own list is not lifted for `use_skill`: it is set at spawn
1035        // and the model cannot change it.
1036        if !self.scope_allows(name) {
1037            return false;
1038        }
1039        match self.active().as_deref() {
1040            Some(skill) if !skill.allowed_tools.is_empty() => {
1041                name == "use_skill" || skill.allowed_tools.iter().any(|tool| tool == name)
1042            }
1043            _ => true,
1044        }
1045    }
1046}
1047
1048/// Holds every available tool, exposes their specs, and dispatches calls.
1049///
1050/// Cloning shares the same tools: the MCP manager keeps a clone so it can take a
1051/// dropped server's tools out, and put them back on reconnect, while the agent
1052/// loop is using the registry, as Python's lock-guarded `ToolRegistry` allows.
1053#[derive(Default, Clone)]
1054pub struct ToolRegistry {
1055    inner: Arc<RwLock<RegistryInner>>,
1056}
1057
1058#[derive(Default)]
1059struct RegistryInner {
1060    /// In registration order, which is the order specs are advertised in.
1061    tools: Vec<Arc<dyn Tool>>,
1062    /// Names dropped by [`ToolRegistry::try_register`] because something already owned them.
1063    collisions: Vec<String>,
1064}
1065
1066impl ToolRegistry {
1067    pub fn new() -> Self {
1068        Self::default()
1069    }
1070
1071    fn read(&self) -> std::sync::RwLockReadGuard<'_, RegistryInner> {
1072        self.inner
1073            .read()
1074            .unwrap_or_else(|poisoned| poisoned.into_inner())
1075    }
1076
1077    fn write(&self) -> std::sync::RwLockWriteGuard<'_, RegistryInner> {
1078        self.inner
1079            .write()
1080            .unwrap_or_else(|poisoned| poisoned.into_inner())
1081    }
1082
1083    pub fn register(&self, tool: Box<dyn Tool>) -> Result<(), String> {
1084        let mut inner = self.write();
1085        if inner.tools.iter().any(|known| known.name() == tool.name()) {
1086            return Err(format!("Tool '{}' is already registered.", tool.name()));
1087        }
1088        inner.tools.push(Arc::from(tool));
1089        Ok(())
1090    }
1091
1092    /// Register `tool` unless its name is taken, recording the clash if it is. The
1093    /// lenient path for mounting MCP tools, where one collision must not abort the run.
1094    pub fn try_register(&self, tool: Arc<dyn Tool>) -> bool {
1095        let mut inner = self.write();
1096        if inner.tools.iter().any(|known| known.name() == tool.name()) {
1097            inner.collisions.push(tool.name().to_owned());
1098            return false;
1099        }
1100        inner.tools.push(tool);
1101        true
1102    }
1103
1104    /// Remove `tool` only if it is the object registered under its name, so a dropped
1105    /// MCP tool that lost a name collision never takes the winner out with it.
1106    /// Register a shared tool unless its name is taken, without recording a
1107    /// collision: for a change the user asked for, which reports its own.
1108    pub fn register_shared(&self, tool: Arc<dyn Tool>) -> bool {
1109        let mut inner = self.write();
1110        if inner.tools.iter().any(|known| known.name() == tool.name()) {
1111            return false;
1112        }
1113        inner.tools.push(tool);
1114        true
1115    }
1116
1117    pub fn unregister_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1118        let mut inner = self.write();
1119        let before = inner.tools.len();
1120        inner.tools.retain(|known| !same_tool(known, tool));
1121        inner.tools.len() != before
1122    }
1123
1124    /// Is this exact tool object registered (not merely one with the same name)?
1125    pub fn contains_tool(&self, tool: &Arc<dyn Tool>) -> bool {
1126        self.read().tools.iter().any(|known| same_tool(known, tool))
1127    }
1128
1129    /// Names [`ToolRegistry::try_register`] refused, in the order they were refused.
1130    pub fn collisions(&self) -> Vec<String> {
1131        self.read().collisions.clone()
1132    }
1133
1134    pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
1135        self.read()
1136            .tools
1137            .iter()
1138            .find(|tool| tool.name() == name)
1139            .cloned()
1140    }
1141
1142    /// Tool names, sorted.
1143    pub fn names(&self) -> Vec<String> {
1144        let mut names: Vec<String> = self
1145            .read()
1146            .tools
1147            .iter()
1148            .map(|tool| tool.name().to_owned())
1149            .collect();
1150        names.sort_unstable();
1151        names
1152    }
1153
1154    /// Specs in registration order.
1155    pub fn specs(&self) -> Vec<ToolSpec> {
1156        let tools: Vec<Arc<dyn Tool>> = self.read().tools.clone();
1157        tools.iter().map(|tool| tool.spec()).collect()
1158    }
1159
1160    /// Run `call`. The lock is released before the tool runs, so a long call never
1161    /// blocks the MCP manager from updating the registry.
1162    ///
1163    /// Every result passes through here, from the loop, its parallel reads, and
1164    /// sub-agents, so this is where a secret the user entered is taken out of what a
1165    /// tool returns, before the model, the transcript, or the trace sees it.
1166    pub fn dispatch(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1167        let mut result = self.dispatch_unredacted(call, ctx);
1168        if !ctx.secrets.is_empty() {
1169            result.content = ctx.secrets.redact(&result.content);
1170            result.error = result.error.map(|error| ctx.secrets.redact(&error));
1171            // The metadata is kept too (the session's steps, the transcript), and a
1172            // file tool's diff in it comes from the expanded arguments.
1173            for value in result.metadata.values_mut() {
1174                redact_value(value, ctx);
1175            }
1176        }
1177        result
1178    }
1179
1180    fn dispatch_unredacted(&self, call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1181        match self.get(&call.name) {
1182            Some(_) if !ctx.scope_allows(&call.name) => scope_refusal(call, ctx),
1183            Some(_) if !ctx.allowed_tool(&call.name) => skill_refusal(call, ctx),
1184            Some(tool) => match with_secrets(tool.as_ref(), call, ctx) {
1185                Ok(call) => {
1186                    let (call, repaired) = repaired_call(tool.as_ref(), call);
1187                    let mut result = tool.run(&call, ctx);
1188                    if !repaired.is_empty() {
1189                        result
1190                            .metadata
1191                            .insert(ARGS_REPAIRED_KEY.to_owned(), json!(repaired));
1192                    }
1193                    result
1194                }
1195                Err(error) => ToolResult {
1196                    call_id: call.id.clone(),
1197                    ..failure(&call.name, error)
1198                },
1199            },
1200            None => ToolResult {
1201                call_id: call.id.clone(),
1202                ..failure(
1203                    &call.name,
1204                    format!(
1205                        "Unknown tool '{}'. Available: {}.",
1206                        call.name,
1207                        self.names().join(", ")
1208                    ),
1209                )
1210            },
1211        }
1212    }
1213}
1214
1215/// `call` as `tool` runs it: with `${secret:NAME}` in its arguments replaced by the
1216/// values, for a tool that [`Tool::expands_secrets`], or unchanged. The call the
1217/// loop keeps (history, trace, approval summary) is never the expanded one.
1218pub fn with_secrets<'a>(
1219    tool: &dyn Tool,
1220    call: &'a ToolCall,
1221    ctx: &ToolContext,
1222) -> Result<std::borrow::Cow<'a, ToolCall>, String> {
1223    if !tool.expands_secrets() {
1224        return Ok(std::borrow::Cow::Borrowed(call));
1225    }
1226    let Value::Object(arguments) = ctx
1227        .secrets
1228        .expand_value(&Value::Object(call.arguments.clone()))?
1229    else {
1230        unreachable!("an object expands to an object")
1231    };
1232    Ok(std::borrow::Cow::Owned(ToolCall {
1233        arguments,
1234        ..call.clone()
1235    }))
1236}
1237
1238/// The `ToolResult::metadata` key under which [`ToolRegistry::dispatch`] lists the
1239/// parameters it repaired, so the loop can record a `tool_args_repaired` event.
1240pub const ARGS_REPAIRED_KEY: &str = "args_repaired";
1241
1242/// `call` with its JSON-string arguments repaired against `tool`'s schema, and the
1243/// names of the parameters repaired. The call the loop keeps is never this one.
1244fn repaired_call<'a>(
1245    tool: &dyn Tool,
1246    call: std::borrow::Cow<'a, ToolCall>,
1247) -> (std::borrow::Cow<'a, ToolCall>, Vec<String>) {
1248    let Some((arguments, repaired)) = repair_arguments(&tool.parameters(), &call.arguments) else {
1249        return (call, Vec::new());
1250    };
1251    let call = ToolCall {
1252        arguments,
1253        ..call.into_owned()
1254    };
1255    (std::borrow::Cow::Owned(call), repaired)
1256}
1257
1258/// Beyond Python: models sometimes send an array or an object argument as a JSON
1259/// string (`"[\"markdown\"]"` where the schema wants `["markdown"]`), which the
1260/// tool then rejects and the turn loses a step. When a parameter's schema accepts
1261/// an array or an object but not a string, and the model sent a string that parses
1262/// as JSON of that kind, the parsed value is used. Anything else is left alone, so
1263/// the error the model gets for it is unchanged, and a string parameter that
1264/// happens to hold JSON is never touched.
1265///
1266/// `None` when nothing needed repair, else the repaired arguments and the names of
1267/// the parameters that were.
1268pub fn repair_arguments(
1269    schema: &Value,
1270    arguments: &Map<String, Value>,
1271) -> Option<(Map<String, Value>, Vec<String>)> {
1272    let properties = schema.get("properties")?.as_object()?;
1273    let mut repaired_arguments = arguments.clone();
1274    let mut repaired = Vec::new();
1275    for (name, value) in arguments {
1276        let (Value::String(text), Some(property)) = (value, properties.get(name)) else {
1277            continue;
1278        };
1279        let accepted = accepted_types(property);
1280        if accepted.contains(&"string") {
1281            continue;
1282        }
1283        let Ok(parsed) = serde_json::from_str::<Value>(text.trim()) else {
1284            continue;
1285        };
1286        let kind = match parsed {
1287            Value::Array(_) => "array",
1288            Value::Object(_) => "object",
1289            _ => continue,
1290        };
1291        if accepted.contains(&kind) {
1292            repaired_arguments.insert(name.clone(), parsed);
1293            repaired.push(name.clone());
1294        }
1295    }
1296    (!repaired.is_empty()).then_some((repaired_arguments, repaired))
1297}
1298
1299/// The JSON types a property schema accepts: its `type` (a name or a list), and
1300/// those of its `anyOf`/`oneOf` branches (pydantic writes `Optional[list]` that way).
1301fn accepted_types(property: &Value) -> Vec<&str> {
1302    let mut types = Vec::new();
1303    match property.get("type") {
1304        Some(Value::String(kind)) => types.push(kind.as_str()),
1305        Some(Value::Array(kinds)) => types.extend(kinds.iter().filter_map(Value::as_str)),
1306        _ => {}
1307    }
1308    for key in ["anyOf", "oneOf"] {
1309        if let Some(branches) = property.get(key).and_then(Value::as_array) {
1310            for branch in branches {
1311                types.extend(accepted_types(branch));
1312            }
1313        }
1314    }
1315    types
1316}
1317
1318/// The answer to a call outside the running specialty's tools, naming what it
1319/// may use so the model can re-plan.
1320pub fn scope_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1321    let label = ctx
1322        .scope
1323        .as_deref()
1324        .map_or("", |scope| scope.label.as_str());
1325    ToolResult {
1326        call_id: call.id.clone(),
1327        ..failure(
1328            &call.name,
1329            format!(
1330                "Tool '{}' is not permitted for the '{label}' sub-agent. Use only the tools you \
1331                 were given.",
1332                call.name
1333            ),
1334        )
1335    }
1336}
1337
1338/// The answer to a call the active skill's `allowed-tools` forbid, naming the
1339/// skill and its list so the model can re-plan rather than retry.
1340fn skill_refusal(call: &ToolCall, ctx: &ToolContext) -> ToolResult {
1341    let skill = ctx.active_skill();
1342    let (name, allowed) = skill
1343        .as_deref()
1344        .map(|skill| (skill.name.as_str(), skill.allowed_tools.join(", ")))
1345        .unwrap_or_default();
1346    ToolResult {
1347        call_id: call.id.clone(),
1348        ..failure(
1349            &call.name,
1350            format!(
1351                "Tool '{}' is not permitted while the skill '{name}' is active. That skill's \
1352                 allowed-tools are: {allowed}. Use one of those, or finish with the skill first.",
1353                call.name
1354            ),
1355        )
1356    }
1357}
1358
1359fn same_tool(a: &Arc<dyn Tool>, b: &Arc<dyn Tool>) -> bool {
1360    std::ptr::eq(Arc::as_ptr(a).cast::<()>(), Arc::as_ptr(b).cast::<()>())
1361}
1362
1363/// Python's built-in tools, then, beyond Python, the read-only search tools
1364/// (`search_files`, `find_files`), then `remember` and `recall` when memory is on,
1365/// `use_skill` when a skill was found, and `delegate` when `[agents]` is on, in
1366/// Python's registration order (`default_registry`). Last, beyond Python,
1367/// `request_secret` when someone is there to answer it (`with_secrets`).
1368pub fn default_registry(
1369    with_memory: bool,
1370    with_skills: bool,
1371    with_delegate: bool,
1372    with_secrets: bool,
1373) -> ToolRegistry {
1374    let registry = builtin_registry();
1375    for tool in [
1376        Box::new(search::SearchFilesTool) as Box<dyn Tool>,
1377        Box::new(search::FindFilesTool),
1378    ] {
1379        registry
1380            .register(tool)
1381            .expect("search tool names are unique");
1382    }
1383    if with_memory {
1384        for tool in [
1385            Box::new(memory::RememberTool) as Box<dyn Tool>,
1386            Box::new(memory::RecallTool),
1387        ] {
1388            registry
1389                .register(tool)
1390                .expect("memory tool names are unique");
1391        }
1392    }
1393    if with_skills {
1394        registry
1395            .register(Box::new(skills::UseSkillTool))
1396            .expect("use_skill is unique");
1397    }
1398    if with_delegate {
1399        registry
1400            .register(Box::new(delegate::DelegateTool))
1401            .expect("delegate is unique");
1402    }
1403    if with_secrets {
1404        registry
1405            .register(Box::new(secret::RequestSecretTool))
1406            .expect("request_secret is unique");
1407    }
1408    registry
1409}
1410
1411/// Python's built-in tools, in its registration order.
1412pub fn builtin_registry() -> ToolRegistry {
1413    let registry = ToolRegistry::new();
1414    for tool in [
1415        Box::new(files::ReadFileTool) as Box<dyn Tool>,
1416        Box::new(files::WriteFileTool),
1417        Box::new(files::EditFileTool),
1418        Box::new(files::ListDirTool),
1419        Box::new(exec::RunCommandTool),
1420        Box::new(exec::PythonExecTool),
1421        Box::new(web::WebFetchTool),
1422    ] {
1423        registry
1424            .register(tool)
1425            .expect("built-in tool names are unique");
1426    }
1427    registry
1428}