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