Skip to main content

eclipse_core/
tools.rs

1//! Tool registry, dispatch and the built-in (gated) tools.
2//!
3//! Every tool is registered with a [`Policy`]. `Deny` tools are not advertised to the
4//! model and never run; `Ask` tools run only if the front-end's [`Approver`] agrees.
5
6use crate::config::{FetchHtml, Policy, ToolsConfig};
7use crate::plugins::{Hooks, Verdict};
8use crate::tools_defer::matches_pattern;
9use async_trait::async_trait;
10use serde::Serialize;
11use serde_json::{json, Value};
12use std::collections::BTreeMap;
13use std::ffi::OsString;
14use std::path::{Component, Path, PathBuf};
15use std::sync::Arc;
16use std::time::Duration;
17use tokio::io::{AsyncRead, AsyncReadExt};
18
19/// `~` and `/` are the two characters a JSON Pointer escapes; tool names avoid them today,
20/// but a name is a string and this keeps `$ref` honest for a plugin that does not.
21fn json_pointer_token(name: &str) -> String {
22    name.replace('~', "~0").replace('/', "~1")
23}
24
25#[derive(Debug, thiserror::Error)]
26pub enum ToolError {
27    #[error("invalid arguments: {0}")]
28    InvalidArgs(String),
29    #[error("{0}")]
30    Failed(String),
31    /// The gate has not answered (`#369`). Not something the model should read: `tool_call` — the
32    /// only route to a deferred tool — re-dispatches inside a tool, and its one channel back is an
33    /// error. [`ToolRegistry::dispatch_scoped`] turns this back into
34    /// [`ToolOutcome::awaiting`](ToolOutcome), so a nested call pauses the turn exactly like a
35    /// top-level one instead of collapsing into "failed" and letting the run carry on.
36    #[error("{0}")]
37    Deferred(String),
38}
39
40#[async_trait]
41pub trait Tool: Send + Sync {
42    fn name(&self) -> &str;
43    fn description(&self) -> &str;
44    /// JSON Schema for the arguments object.
45    fn parameters(&self) -> Value;
46    /// Human-readable one-liner shown when asking for approval.
47    fn describe_call(&self, args: &Value) -> String {
48        format!("{} {}", self.name(), args)
49    }
50    /// Whether this particular call is put to the [`Approver`] under `Policy::Ask`. Every call
51    /// is, unless a tool says otherwise: the answer is per call because one tool can have a
52    /// side-effect-free form (the `script` tool's listing) beside a form that runs code. `deny`
53    /// and `disabled` are not affected — they never run anything.
54    fn needs_approval(&self, _args: &Value) -> bool {
55        true
56    }
57    async fn call(&self, args: Value) -> Result<String, ToolError>;
58    /// [`call`](Self::call) for a tool that needs to know which run it is part of: who may be
59    /// asked, which session it belongs to, how many children the run has started. Almost no
60    /// tool does, so the default ignores the scope.
61    async fn call_scoped(&self, args: Value, _scope: &CallScope<'_>) -> Result<String, ToolError> {
62        self.call(args).await
63    }
64}
65
66/// What one run is, as far as a tool that starts children needs to know.
67#[derive(Default)]
68pub struct RunScope {
69    /// The session the run is writing to. A child session records it as its parent.
70    pub session: String,
71    /// The children this run has started so far.
72    pub children: crate::tools_delegate::ChildLedger,
73    /// The run's cancellation flag, so a tool that starts *another agent* can give it the same one.
74    /// A work that outlives the run that asked for it is exactly what cancellation is about.
75    pub cancel: crate::cancel::Cancel,
76}
77
78impl RunScope {
79    pub fn new(session: &str) -> Self {
80        Self {
81            session: session.to_string(),
82            children: crate::tools_delegate::ChildLedger::default(),
83            cancel: crate::cancel::Cancel::new(),
84        }
85    }
86
87    /// The same scope, carrying the run's cancellation flag.
88    pub fn cancellable(mut self, cancel: &crate::cancel::Cancel) -> Self {
89        self.cancel = cancel.clone();
90        self
91    }
92}
93
94/// The run a single tool call belongs to, the approver that call's policy was put to, and the
95/// registry the call arrived through.
96///
97/// The registry is here for `tool_call`, which is a router: it has to dispatch the tool it was
98/// given *through this funnel*, so that a deferred tool faces the same policy check, the same
99/// approval prompt and the same hooks as a call the model made directly. Handing the reference
100/// down from `dispatch_scoped` costs nothing and is honest about it — the alternative is a
101/// registry that owns a tool holding an `Arc` back to the registry, which is a reference cycle
102/// in the one place a mistake would leak every plugin.
103pub struct CallScope<'a> {
104    pub approver: &'a dyn Approver,
105    pub run: &'a RunScope,
106    pub registry: &'a ToolRegistry,
107    /// The id of the call this one belongs to, when it belongs to one (`#369`). `tool_call` is a
108    /// funnel: the call it re-dispatches *is* the call the answer is about, so the id travels with
109    /// it — a nested row is then matchable by `approvals::decision_for` on resume, which otherwise
110    /// looks for `""` and finds nothing. A tool that makes a call of its own leaves this `None`.
111    pub call_id: Option<&'a str>,
112}
113
114/// Decides whether a tool with `Policy::Ask` may run.
115///
116/// Three answers, because two is what makes an unanswered gate indistinguishable from `no`: a
117/// front-end that is not there (a scripted run, a closed dashboard) has to be able to say "nobody
118/// has answered" and have the loop stop rather than deny on the user's behalf. See
119/// [`crate::approvals`] for how that answer survives the process.
120#[async_trait]
121pub trait Approver: Send + Sync {
122    async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision;
123
124    /// The yes/no form, for callers that have no third answer to give. A `Defer` reads as "not
125    /// approved", which is the fail-closed direction — but a caller that means to pause a run has
126    /// to implement [`decide`](Self::decide) itself, because this loses the distinction.
127    async fn approve(&self, tool: &str, summary: &str) -> bool {
128        matches!(
129            self.decide(&crate::approvals::Pending::new(
130                "",
131                tool,
132                summary.to_string(),
133                String::new()
134            ))
135            .await,
136            crate::approvals::Decision::Allow
137        )
138    }
139}
140
141pub struct DenyAll;
142pub struct AllowAll;
143
144#[async_trait]
145impl Approver for DenyAll {
146    async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
147        crate::approvals::Decision::Deny("this run approves nothing".to_string())
148    }
149}
150
151#[async_trait]
152impl Approver for AllowAll {
153    async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
154        crate::approvals::Decision::Allow
155    }
156}
157
158/// Tool definition in the OpenAI `tools` array format.
159#[derive(Debug, Clone, Serialize, PartialEq)]
160pub struct ToolSpec {
161    #[serde(rename = "type")]
162    pub kind: &'static str,
163    pub function: ToolSpecFunction,
164}
165
166#[derive(Debug, Clone, Serialize, PartialEq)]
167pub struct ToolSpecFunction {
168    pub name: String,
169    pub description: String,
170    pub parameters: Value,
171}
172
173/// Who put this tool in the registry. Shown by `eclipse tools list`, in the panel and in the
174/// schema document's description of itself, because "which tool is this and who added it" is
175/// the first question when an extension misbehaves.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum ToolSource {
178    /// Compiled in, or registered by the runtime on the agent's behalf (the `memory` tool).
179    Builtin,
180    /// A `kind = "tool"` plugin. The name is the plugin directory's name.
181    Plugin(String),
182    /// A server `config.toml` declares under `[[mcp]]` (`#352`). The name is `mcp:<server>`, so the
183    /// label reads `config:mcp:<server>` — beside `plugin:mcp:<server>`, because which file the
184    /// entry lives in is exactly what this label is for.
185    Config(String),
186    /// A tool a skill provides. Nothing registers one: M4 skills are Markdown the model reads,
187    /// not code Eclipse runs, so the variant is kept for the listing and left unused.
188    Skill(String),
189}
190
191impl ToolSource {
192    /// `builtin`, `plugin:<name>`, `config:<name>` or `skill:<name>` — one spelling, everywhere.
193    pub fn label(&self) -> String {
194        match self {
195            Self::Builtin => "builtin".to_string(),
196            Self::Plugin(name) => format!("plugin:{name}"),
197            Self::Config(name) => format!("config:{name}"),
198            Self::Skill(name) => format!("skill:{name}"),
199        }
200    }
201}
202
203impl Serialize for ToolSource {
204    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
205        s.serialize_str(&self.label())
206    }
207}
208
209/// Everything known about one tool, in one place.
210///
211/// The model request ([`ToolSpec`]), `eclipse tools list`, `eclipse tools schema` and the tests
212/// all derive from this, so the four cannot disagree about what a tool is called, what it takes
213/// or who added it. `advertised` is the only field that is about this *configuration* rather
214/// than the tool: the descriptor still reports a denied tool, because an operator needs to see
215/// that it exists and why it is not offered.
216#[derive(Debug, Clone, Serialize, PartialEq)]
217pub struct ToolDescriptor {
218    pub name: String,
219    pub description: String,
220    /// JSON Schema for the arguments object.
221    pub parameters: Value,
222    pub policy: Policy,
223    pub source: ToolSource,
224    /// Whether the model is offered this tool. False for a policy of `deny`, for anything named
225    /// in `[tools] disabled`, and for anything deferred — the last of which is reachable through
226    /// `tool_call`, so [`deferred`](Self::deferred) is the field that says why.
227    pub advertised: bool,
228    /// Registered and callable, but withheld from the request to save its description's tokens.
229    pub deferred: bool,
230    /// Named in `[tools] disabled`: not offered and not callable at all. Kept apart from a
231    /// `deny` policy because the two are removed by different hands and a listing should say
232    /// which.
233    pub disabled: bool,
234}
235
236/// The `$id` of the document `eclipse tools schema` prints.
237pub const TOOL_SCHEMA_ID: &str = "urn:eclipse:tools";
238
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct ToolOutcome {
241    pub output: String,
242    pub is_error: bool,
243    /// The call could not even be attempted: an unknown tool, or arguments that are not JSON.
244    /// The model still reads `output`, and the loop counts these to spot a model that is
245    /// looping rather than working.
246    pub malformed: bool,
247    /// Nobody answered the approval gate, so the call did not run and must not be recorded as if
248    /// it had. The loop stops the turn and keeps the call as pending; a caller that ignores this
249    /// would show the model a result for work that never happened.
250    pub deferred: bool,
251}
252
253impl ToolOutcome {
254    fn ok(output: String) -> Self {
255        Self {
256            output,
257            is_error: false,
258            malformed: false,
259            deferred: false,
260        }
261    }
262    fn err(output: impl Into<String>) -> Self {
263        Self {
264            output: output.into(),
265            is_error: true,
266            malformed: false,
267            deferred: false,
268        }
269    }
270    /// A call that could not be attempted at all, as opposed to one that ran and failed.
271    pub(crate) fn unusable(output: impl Into<String>) -> Self {
272        Self {
273            output: output.into(),
274            is_error: true,
275            malformed: true,
276            deferred: false,
277        }
278    }
279    /// A call the gate has not answered: recorded, not run, not answered in the transcript.
280    pub(crate) fn awaiting(output: impl Into<String>) -> Self {
281        Self {
282            output: output.into(),
283            is_error: true,
284            malformed: false,
285            deferred: true,
286        }
287    }
288}
289
290struct Entry {
291    tool: Arc<dyn Tool>,
292    policy: Policy,
293    source: ToolSource,
294    /// Named in `[tools] disabled`: never advertised, never runs, whatever the policy says.
295    disabled: bool,
296    /// Named by `[tools] deferred`: registered and callable, but not described in the request.
297    /// Reachable through `tool_call`, which is the whole point.
298    deferred: bool,
299}
300
301pub struct ToolRegistry {
302    tools: BTreeMap<String, Entry>,
303    max_output_bytes: usize,
304    /// Plugin hooks run around every dispatch; empty unless plugins are enabled.
305    hooks: Hooks,
306    /// Policies for `tool_search`, `tool_describe` and `tool_call`, held until [`Self::defer`]
307    /// registers them — which it may never do, when nothing is deferred.
308    deferral: DeferralPolicies,
309}
310
311/// The three policies that belong to tools which may never be registered.
312#[derive(Debug, Clone, Copy)]
313struct DeferralPolicies {
314    search: Policy,
315    describe: Policy,
316    call: Policy,
317}
318
319impl Default for DeferralPolicies {
320    fn default() -> Self {
321        Self {
322            search: Policy::Allow,
323            describe: Policy::Allow,
324            call: Policy::Allow,
325        }
326    }
327}
328
329impl Default for ToolRegistry {
330    fn default() -> Self {
331        Self::new(32 * 1024)
332    }
333}
334
335impl ToolRegistry {
336    pub fn new(max_output_bytes: usize) -> Self {
337        Self {
338            tools: BTreeMap::new(),
339            max_output_bytes,
340            hooks: Hooks::default(),
341            deferral: DeferralPolicies::default(),
342        }
343    }
344
345    /// Take the deferral tools' policies from the config. Separate from `from_config_full`
346    /// because the policies are only *used* if something is deferred, which `defer` decides much
347    /// later — once plugin tools have names.
348    pub fn with_deferral_policies(mut self, cfg: &ToolsConfig) -> Self {
349        self.deferral = DeferralPolicies {
350            search: cfg.tool_search,
351            describe: cfg.tool_describe,
352            call: cfg.tool_call,
353        };
354        self
355    }
356
357    /// Attach plugin hooks to every tool call.
358    pub fn with_hooks(mut self, hooks: Hooks) -> Self {
359        self.hooks = hooks;
360        self
361    }
362
363    pub fn hooks(&self) -> &Hooks {
364        &self.hooks
365    }
366
367    /// The cap for what the model reads. Public because the runtime applies it *after* the loop
368    /// hooks — redaction has to see whole tokens (`#414`).
369    pub fn max_output_bytes(&self) -> usize {
370        self.max_output_bytes
371    }
372
373    /// Registry with the built-in tools, gated by `cfg` and confined to `workspace_root`.
374    pub fn from_config(cfg: &ToolsConfig, workspace_root: PathBuf) -> Self {
375        Self::from_config_with(cfg, workspace_root, Vec::new())
376    }
377
378    /// As [`Self::from_config`], and `shell` may also be given a `cwd` inside a skill's
379    /// directory, for the skills found under `skill_roots`.
380    pub fn from_config_with(
381        cfg: &ToolsConfig,
382        workspace_root: PathBuf,
383        skill_roots: Vec<crate::skills::Root>,
384    ) -> Self {
385        Self::from_config_full(cfg, workspace_root, skill_roots, None)
386    }
387
388    /// As [`Self::from_config_with`], and with a scripts directory: the `script` tool is
389    /// registered over it. `None` — no config directory could be worked out — means no
390    /// `script` tool, the same way there is no `skill_manage` without a directory to write.
391    pub fn from_config_full(
392        cfg: &ToolsConfig,
393        workspace_root: PathBuf,
394        skill_roots: Vec<crate::skills::Root>,
395        scripts_dir: Option<PathBuf>,
396    ) -> Self {
397        let root = std::fs::canonicalize(&workspace_root).unwrap_or(workspace_root);
398        let mut r = Self::new(cfg.max_output_bytes);
399        r.register(
400            Arc::new(ReadFile {
401                root: root.clone(),
402                max_bytes: cfg.max_output_bytes,
403            }),
404            cfg.read_file,
405        );
406        r.register(
407            Arc::new(crate::tools_search::SearchFiles::new(
408                root.clone(),
409                cfg.max_output_bytes,
410            )),
411            cfg.search_files,
412        );
413        r.register(
414            Arc::new(
415                WriteFile::new(root.clone(), scripts_dir.clone())
416                    .guard_bytes(cfg.rewrite_guard_bytes),
417            ),
418            cfg.write_file,
419        );
420        // `patch` edits a file `write_file` could have written, so it is built over the same
421        // roots rather than its own set of rules that could drift.
422        r.register(
423            Arc::new(crate::tools_patch::Patch::new(WriteFile::new(
424                root.clone(),
425                scripts_dir.clone(),
426            ))),
427            cfg.patch,
428        );
429        r.register(
430            Arc::new(Shell {
431                root: root.clone(),
432                skill_roots,
433                scripts_dir: scripts_dir.clone(),
434                sandbox: crate::sandbox::Sandbox::new(cfg, &root, scripts_dir.as_deref()),
435                timeout: Duration::from_secs(cfg.shell_timeout_secs),
436                allowlist: cfg.shell_allowlist.clone(),
437                max_bytes: cfg.max_output_bytes,
438                kill_grace: SHELL_KILL_GRACE,
439                ask: cfg.shell_ask,
440            }),
441            cfg.shell,
442        );
443        if let Some(dir) = scripts_dir {
444            // `script` and `execute_code` share a directory and a runner: one is a program that
445            // keeps its name, the other is code that does not.
446            r.register(
447                Arc::new(crate::tools_script::ScriptTool::new(
448                    dir.clone(),
449                    Duration::from_secs(cfg.shell_timeout_secs),
450                    cfg.max_output_bytes,
451                )),
452                cfg.script,
453            );
454            r.register(
455                Arc::new(crate::tools_exec::ExecuteCode::new(
456                    dir,
457                    root.clone(),
458                    Duration::from_secs(cfg.shell_timeout_secs),
459                    cfg.max_output_bytes,
460                    SHELL_KILL_GRACE,
461                )),
462                cfg.execute_code,
463            );
464        }
465        r.register(
466            Arc::new(
467                Fetch::new(
468                    Duration::from_secs(cfg.fetch_timeout_secs),
469                    cfg.max_output_bytes,
470                )
471                .with_html(cfg.fetch_html),
472            ),
473            cfg.fetch,
474        );
475        r.with_deferral_policies(cfg)
476    }
477
478    /// Register a built-in (or runtime-provided) tool.
479    pub fn register(&mut self, tool: Arc<dyn Tool>, policy: Policy) {
480        self.register_with_source(tool, policy, ToolSource::Builtin);
481    }
482
483    /// Register a tool and say who added it. Plugins use this so that `tools list` can point
484    /// at the directory to look at when something is wrong.
485    pub fn register_with_source(
486        &mut self,
487        tool: Arc<dyn Tool>,
488        policy: Policy,
489        source: ToolSource,
490    ) {
491        self.tools.insert(
492            tool.name().to_string(),
493            Entry {
494                tool,
495                policy,
496                source,
497                disabled: false,
498                deferred: false,
499            },
500        );
501    }
502
503    /// Remove tools named in `[tools] disabled`, returning the names that matched nothing.
504    ///
505    /// Called once after everything is registered — built-ins, plugin tools, the memory tool —
506    /// because a plugin tool can only be found after plugins load. The unknown names come back
507    /// instead of being ignored: a typo in this list is a tool the operator believes is off.
508    pub fn disable(&mut self, names: &[String]) -> Vec<String> {
509        let mut unknown = Vec::new();
510        for name in names {
511            match self.tools.get_mut(name) {
512                Some(entry) => entry.disabled = true,
513                None => unknown.push(name.clone()),
514            }
515        }
516        unknown
517    }
518
519    /// Withhold tools from the request without removing them: they stay registered and runnable,
520    /// and the three tools that reach them are registered here — but only if something was
521    /// actually deferred, because a config that defers nothing should not spend prompt tokens on
522    /// three tools with nothing to reach.
523    ///
524    /// Called once, after everything is registered, for the same reason as [`Self::disable`]:
525    /// a plugin's name is only known once plugins have loaded. Returns the patterns that matched
526    /// nothing, so a typo is reported rather than silently doing nothing.
527    ///
528    /// Defer by name or by **source** (`#351`).
529    ///
530    /// A pattern is matched against a tool's name and against its source label — `builtin`,
531    /// `plugin:<name>`, `plugin:mcp:<server>` — because that is the only way to say "every MCP
532    /// tool" without renaming them. MCP tools keep the name the server published (the `#373`
533    /// rule), so `mcp_*` would match nothing; `plugin:mcp:*` is the spelling that says what it
534    /// means, and it is the shipped default.
535    ///
536    /// A **source filter** that matches nothing is not a typo: `plugin:mcp:*` on a box with no MCP
537    /// server is a filter over an empty set, and warning on every run would train the reader to
538    /// ignore the warning. Source labels are the patterns that carry a `:` (`plugin:mcp:*`,
539    /// `plugin:greeter`); a plain name pattern that matches nothing — `note_*`, `shellish` — is
540    /// still a mistake in the file and is still reported.
541    pub fn defer(&mut self, patterns: &[String]) -> Vec<String> {
542        let mut unknown = Vec::new();
543        let mut deferred = Vec::new();
544        for pattern in patterns {
545            let matched: Vec<String> = self
546                .tools
547                .iter()
548                .filter(|(name, entry)| {
549                    matches_pattern(pattern, name)
550                        || matches_pattern(pattern, &entry.source.label())
551                })
552                .map(|(name, _)| name.clone())
553                .collect();
554            if matched.is_empty() && !pattern.contains(':') {
555                unknown.push(pattern.clone());
556            }
557            deferred.extend(matched);
558        }
559        for name in &deferred {
560            if let Some(entry) = self.tools.get_mut(name) {
561                entry.deferred = true;
562            }
563        }
564        if !deferred.is_empty() {
565            self.register_deferral_tools();
566        }
567        unknown
568    }
569
570    /// The three tools with which the model reaches a deferred one. Registered by [`Self::defer`]
571    /// only, and never themselves deferred: a tool the model cannot name is one it cannot search
572    /// for either.
573    fn register_deferral_tools(&mut self) {
574        for (tool, policy) in [
575            (
576                Arc::new(crate::tools_defer::ToolSearch) as Arc<dyn Tool>,
577                self.deferral_policy(crate::tools_defer::SEARCH),
578            ),
579            (
580                Arc::new(crate::tools_defer::ToolDescribe) as Arc<dyn Tool>,
581                self.deferral_policy(crate::tools_defer::DESCRIBE),
582            ),
583            (
584                Arc::new(crate::tools_defer::ToolCall) as Arc<dyn Tool>,
585                self.deferral_policy(crate::tools_defer::CALL),
586            ),
587        ] {
588            if !self.tools.contains_key(tool.name()) {
589                self.register(tool, policy);
590            }
591        }
592    }
593
594    /// The policy a deferral tool was configured with, defaulting to the `ToolsConfig` default
595    /// when the registry was built without one (tests, plugins that build their own).
596    fn deferral_policy(&self, name: &str) -> Policy {
597        match name {
598            crate::tools_defer::SEARCH => self.deferral.search,
599            crate::tools_defer::DESCRIBE => self.deferral.describe,
600            crate::tools_defer::CALL => self.deferral.call,
601            _ => Policy::Allow,
602        }
603    }
604
605    /// Every registered tool, advertised or not, in name order.
606    pub fn descriptors(&self) -> Vec<ToolDescriptor> {
607        self.tools
608            .iter()
609            .map(|(name, entry)| ToolDescriptor {
610                name: name.clone(),
611                description: entry.tool.description().to_string(),
612                parameters: entry.tool.parameters(),
613                policy: entry.policy,
614                source: entry.source.clone(),
615                advertised: !entry.disabled && entry.policy != Policy::Deny && !entry.deferred,
616                deferred: entry.deferred,
617                disabled: entry.disabled,
618            })
619            .collect()
620    }
621
622    /// Names the model is offered, in name order.
623    pub fn advertised_names(&self) -> Vec<String> {
624        self.descriptors()
625            .into_iter()
626            .filter(|d| d.advertised)
627            .map(|d| d.name)
628            .collect()
629    }
630
631    /// One JSON Schema document describing every tool call this registry allows.
632    ///
633    /// A call is `{"name": …, "arguments": {…}}`; `oneOf` gives one branch per *advertised*
634    /// tool, pinning `name` with `const` and validating `arguments` against the tool's
635    /// parameters schema in `$defs`. `$defs` carries every registered tool's schema, including
636    /// ones this configuration does not offer, so an external client can validate a call it
637    /// got hold of even after the policy changed.
638    pub fn schema_document(&self) -> Value {
639        let mut defs = serde_json::Map::new();
640        let mut branches = Vec::new();
641        for d in self.descriptors() {
642            let pointer = json_pointer_token(&d.name);
643            defs.insert(d.name.clone(), d.parameters.clone());
644            if !d.advertised {
645                continue;
646            }
647            branches.push(json!({
648                "type": "object",
649                "description": d.description,
650                "properties": {
651                    "name": { "const": d.name },
652                    "arguments": { "$ref": format!("#/$defs/{pointer}") },
653                },
654                "required": ["name", "arguments"],
655                "additionalProperties": false,
656            }));
657        }
658        json!({
659            "$schema": "https://json-schema.org/draft/2020-12/schema",
660            "$id": TOOL_SCHEMA_ID,
661            "title": "Eclipse tool calls",
662            "description": "One branch per tool the model is offered: `name` pins the tool and                             `arguments` is validated against its parameters schema in `$defs`.",
663            "oneOf": branches,
664            "$defs": defs,
665        })
666    }
667
668    pub fn names(&self) -> Vec<String> {
669        self.tools.keys().cloned().collect()
670    }
671
672    /// A copy of this registry holding **only** `names`, for an agent whose capabilities are
673    /// declared rather than subtracted (`#548`).
674    ///
675    /// The counterpart of [`without`](Self::without), and the direction that stays true: a
676    /// denylist is correct only until something new is registered — a plugin tool, an MCP server's
677    /// tool, a tool added next release — and every one of those arrives granted. A flare is
678    /// read-only, so what it holds is written down, and everything else is absent from its registry
679    /// and therefore unreachable through a `tool_call` bridge.
680    pub fn only(&self, names: &[&str]) -> ToolRegistry {
681        let mut out = ToolRegistry {
682            tools: BTreeMap::new(),
683            max_output_bytes: self.max_output_bytes,
684            hooks: self.hooks.clone(),
685            deferral: self.deferral,
686        };
687        for (name, entry) in &self.tools {
688            if !names.contains(&name.as_str()) {
689                continue;
690            }
691            out.tools.insert(
692                name.clone(),
693                Entry {
694                    tool: Arc::clone(&entry.tool),
695                    policy: entry.policy,
696                    source: entry.source.clone(),
697                    disabled: entry.disabled,
698                    deferred: entry.deferred,
699                },
700            );
701        }
702        out
703    }
704
705    /// A copy of this registry with `names` **removed**, for an agent that must not be able to
706    /// reach them at all (`#171`).
707    ///
708    /// Not [`disable`](Self::disable): a disabled tool is still registered, still dispatchable by
709    /// a `tool_call` that names it, and only withheld from the request. A flare is declared
710    /// read-only, so the write tools are not in its registry — the bridge cannot reach what is
711    /// not there, which is a claim a `duplicated policy` cannot make.
712    ///
713    /// The rest is kept as it is, policies included: what a flare may read is decided by the
714    /// parent's own configuration, not by a second set of rules.
715    pub fn without(&self, names: &[&str]) -> ToolRegistry {
716        let mut out = ToolRegistry {
717            tools: BTreeMap::new(),
718            max_output_bytes: self.max_output_bytes,
719            hooks: self.hooks.clone(),
720            deferral: self.deferral,
721        };
722        for (name, entry) in &self.tools {
723            if names.contains(&name.as_str()) {
724                continue;
725            }
726            out.tools.insert(
727                name.clone(),
728                Entry {
729                    tool: Arc::clone(&entry.tool),
730                    policy: entry.policy,
731                    source: entry.source.clone(),
732                    disabled: entry.disabled,
733                    deferred: entry.deferred,
734                },
735            );
736        }
737        // The three that reach a deferred tool are spending prompt tokens for a set that may now
738        // be empty — and a flare that removed the only deferred tool would be carrying a bridge to
739        // nowhere. Same rule [`Self::defer`] applies in the other direction.
740        if !out.tools.values().any(|e| e.deferred) {
741            for bridge in ["tool_search", "tool_describe", "tool_call"] {
742                out.tools.remove(bridge);
743            }
744        }
745        out
746    }
747
748    /// Specs for every tool the model is offered, derived from [`Self::descriptors`].
749    pub fn specs(&self) -> Vec<ToolSpec> {
750        self.descriptors()
751            .into_iter()
752            .filter(|d| d.advertised)
753            .map(|d| ToolSpec {
754                kind: "function",
755                function: ToolSpecFunction {
756                    name: d.name,
757                    description: d.description,
758                    parameters: d.parameters,
759                },
760            })
761            .collect()
762    }
763
764    /// Run a tool call as produced by a model. Never panics or errors: every failure
765    /// becomes an `is_error` outcome so it can be fed back to the model.
766    ///
767    /// Plugin hooks see `call_id: null` here: this form is for a caller that is not the
768    /// loop and has no model-issued call to name. The loop uses [`dispatch_call`].
769    pub async fn dispatch(
770        &self,
771        name: &str,
772        raw_args: &str,
773        approver: &dyn Approver,
774    ) -> ToolOutcome {
775        self.dispatch_call(name, raw_args, approver, None).await
776    }
777
778    /// The one-liner an approval prompt would show for this call, without asking anyone. Used by
779    /// the loop when it records a call nobody answered: the row it writes has to read like the
780    /// question a person would have been asked, months later in `eclipse approve --list`.
781    pub fn summary_of(&self, name: &str, raw_args: &str) -> String {
782        let Some(entry) = self.tools.get(name) else {
783            return format!("{name} {raw_args}");
784        };
785        let args = serde_json::from_str(raw_args).unwrap_or_else(|_| serde_json::json!({}));
786        entry.tool.describe_call(&args)
787    }
788
789    /// [`dispatch`](Self::dispatch), telling the plugin hooks which tool call this is. With
790    /// `[tools] concurrency` above 1 several calls are in flight at once and their
791    /// `before_tool` / `after_tool` payloads interleave, so the id is how a hook tells them
792    /// apart — and how an `after_tool` rewrite is matched to the call it belongs to.
793    pub async fn dispatch_call(
794        &self,
795        name: &str,
796        raw_args: &str,
797        approver: &dyn Approver,
798        call_id: Option<&str>,
799    ) -> ToolOutcome {
800        self.dispatch_scoped(name, raw_args, approver, call_id, &RunScope::default())
801            .await
802    }
803
804    /// [`dispatch_call`](Self::dispatch_call) for a call made by a run: `run` is that run's
805    /// scope, which a tool that starts children reads through [`Tool::call_scoped`].
806    pub async fn dispatch_scoped(
807        &self,
808        name: &str,
809        raw_args: &str,
810        approver: &dyn Approver,
811        call_id: Option<&str>,
812        run: &RunScope,
813    ) -> ToolOutcome {
814        let Some(entry) = self.tools.get(name) else {
815            return ToolOutcome::unusable(format!("unknown tool `{name}`"));
816        };
817        let args: Value = if raw_args.trim().is_empty() {
818            json!({})
819        } else {
820            match serde_json::from_str(raw_args) {
821                Ok(v) => v,
822                Err(e) => {
823                    return ToolOutcome::unusable(format!("arguments are not valid JSON: {e}"))
824                }
825            }
826        };
827        if entry.disabled {
828            return ToolOutcome::err(format!(
829                "tool `{name}` is disabled in the config (`[tools] disabled`)"
830            ));
831        }
832        if entry.policy == Policy::Deny {
833            return ToolOutcome::err(format!("tool `{name}` is disabled by policy"));
834        }
835        // Guards run before the approval prompt: a plugin that forbids the call must not
836        // first send the user a prompt for it, and a refusal is final.
837        if let Verdict::Deny(reason) = self.hooks.before(name, &args, call_id).await {
838            return self
839                .hooks
840                .after(name, &args, ToolOutcome::err(reason), call_id)
841                .await;
842        }
843        if entry.policy == Policy::Ask && entry.tool.needs_approval(&args) {
844            let summary = entry.tool.describe_call(&args);
845            let pending = crate::approvals::Pending::new(
846                call_id.unwrap_or_default(),
847                name,
848                summary.clone(),
849                raw_args.to_string(),
850            );
851            match approver.decide(&pending).await {
852                crate::approvals::Decision::Allow => {}
853                crate::approvals::Decision::Deny(reason) => {
854                    return ToolOutcome::err(format!(
855                        "the user declined to run `{name}`: {reason}"
856                    ));
857                }
858                crate::approvals::Decision::Defer => {
859                    // Not run, and not answered: the caller records the call and stops the turn.
860                    // Returning a normal result here would tell the model the tool ran or failed,
861                    // which is the one thing nobody knows yet.
862                    return ToolOutcome::awaiting(format!(
863                        "`{name}` is not approved yet; the call is waiting for an answer"
864                    ));
865                }
866            }
867        }
868        let scope = CallScope {
869            approver,
870            run,
871            registry: self,
872            call_id,
873        };
874        let outcome = match entry.tool.call_scoped(args.clone(), &scope).await {
875            Ok(out) => ToolOutcome::ok(out),
876            // `#369`: a call made through `tool_call` met a deferral and handed it back. The gate
877            // has not answered, so this is not a result for the model to read — it goes up as the
878            // same "waiting" outcome a top-level call produces, and the turn stops on it.
879            Err(ToolError::Deferred(message)) => ToolOutcome::awaiting(message),
880            Err(e) => ToolOutcome::err(e.to_string()),
881        };
882        // `#414`: **nothing here truncates.** The cap used to be applied right here, and the
883        // `redact-secrets` loop hook ran afterwards in the runtime — so a secret that ended at
884        // `max_output_bytes` was already cut in half when redaction looked at it, and a
885        // length-bounded pattern cannot match a token missing its tail: its prefix reached the
886        // transcript. The cap belongs to the caller now, after the loop hooks (see
887        // [`ToolRegistry::max_output_bytes`]); each tool bounds its own read, so the string
888        // between here and there is still bounded.
889        self.hooks.after(name, &args, outcome, call_id).await
890    }
891}
892
893/// Truncate to at most `max` bytes on a word boundary, noting the cut.
894///
895/// `#414`: a character boundary is not the same as a *token* boundary. A cutting point that landed
896/// inside a secret published half of it — `sk-abcdefgh` and no more — and no pattern catches that:
897/// the `sk-` rule wants twenty characters of key behind the prefix, so half a key reads as an
898/// error message and survives every redaction pass. So the cut backs up to the last separator
899/// inside a short window and drops the fragment with it. Losing one word out of a truncated output
900/// costs a reader nothing; losing the head of their key to a transcript costs them the key.
901pub fn truncate(mut s: String, max: usize) -> String {
902    if s.len() <= max {
903        return s;
904    }
905    let mut cut = max;
906    while !s.is_char_boundary(cut) {
907        cut -= 1;
908    }
909    let mut floor = cut.saturating_sub(200);
910    while !s.is_char_boundary(floor) {
911        floor += 1;
912    }
913    if let Some(at) = s[floor..cut]
914        .rfind(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ',' | ';' | '>' | '=' | '&'))
915    {
916        cut = floor + at;
917    }
918    s.truncate(cut);
919    s.push_str("\n[output truncated]");
920    s
921}
922
923pub(crate) fn str_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, ToolError> {
924    args.get(key)
925        .and_then(Value::as_str)
926        .ok_or_else(|| ToolError::InvalidArgs(format!("missing string field `{key}`")))
927}
928
929/// Write `content` beside `path` and rename it over, so a reader sees the old file or the new
930/// one and a crash leaves no half-written file. `patch` and `skill_manage` both edit in place;
931/// one implementation, so neither can be the one that truncates on a full disk.
932///
933/// `#374`: a rename does not carry over two things about the file it replaces.
934///
935/// **The mode.** The temp file was written with the umask's default and renamed into place, so
936/// patching an executable script left it `0644` — `./run.sh`, and anything on the scripts `PATH`,
937/// stopped working, silently, while the edit reported success. The mode belongs to the file, not to
938/// the write.
939///
940/// **The link.** `patch` edits the file it was pointed at. Writing through a symlink and leaving the
941/// link in place is what someone editing `link -> real` means; replacing the link with a regular file
942/// leaves `real` untouched, which is the opposite of what they asked for. So the target is resolved
943/// first and the link stays a link.
944pub(crate) fn replace_file(path: &Path, content: &str) -> Result<(), ToolError> {
945    let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
946    let mode = std::fs::metadata(&target).ok().map(|m| m.permissions());
947    let mut tmp = target.as_os_str().to_owned();
948    tmp.push(format!(".tmp{}", std::process::id()));
949    let tmp = PathBuf::from(tmp);
950    let wrote = std::fs::write(&tmp, content);
951    let wrote = match (wrote, mode) {
952        (Ok(()), Some(mode)) => std::fs::set_permissions(&tmp, mode),
953        (wrote, _) => wrote,
954    };
955    wrote
956        .and_then(|_| std::fs::rename(&tmp, &target))
957        .map_err(|e| {
958            let _ = std::fs::remove_file(&tmp);
959            ToolError::Failed(format!("cannot write {}: {e}", path.display()))
960        })
961}
962
963/// Lexically normalise (`.`/`..`) without touching the filesystem.
964fn normalize(p: &Path) -> PathBuf {
965    let mut out = PathBuf::new();
966    for c in p.components() {
967        match c {
968            Component::ParentDir => {
969                out.pop();
970            }
971            Component::CurDir => {}
972            other => out.push(other.as_os_str()),
973        }
974    }
975    out
976}
977
978/// Resolve `requested` against `root` and ensure the result, after following symlinks in
979/// its existing part, stays inside `root`. `root` must already be canonical.
980pub fn confine(root: &Path, requested: &str) -> Result<PathBuf, ToolError> {
981    let joined = normalize(&root.join(requested));
982    let mut existing = joined.as_path();
983    // `symlink_metadata` so a dangling symlink is resolved (and rejected if it points
984    // outside) instead of being skipped as a missing path that a write would follow.
985    while std::fs::symlink_metadata(existing).is_err() {
986        existing = existing
987            .parent()
988            .ok_or_else(|| ToolError::Failed("path has no existing ancestor".into()))?;
989    }
990    let canon = std::fs::canonicalize(existing)
991        .map_err(|e| ToolError::Failed(format!("cannot resolve path: {e}")))?;
992    if !canon.starts_with(root) {
993        return Err(ToolError::Failed(format!(
994            "path `{requested}` is outside the workspace"
995        )));
996    }
997    Ok(joined)
998}
999
1000pub struct ReadFile {
1001    root: PathBuf,
1002    max_bytes: usize,
1003}
1004
1005#[async_trait]
1006impl Tool for ReadFile {
1007    fn name(&self) -> &str {
1008        "read_file"
1009    }
1010    fn description(&self) -> &str {
1011        "Read a UTF-8 text file inside the workspace."
1012    }
1013    fn parameters(&self) -> Value {
1014        json!({"type":"object","properties":{"path":{"type":"string","description":"Path relative to the workspace"}},"required":["path"]})
1015    }
1016    fn describe_call(&self, args: &Value) -> String {
1017        format!("read file {}", args["path"].as_str().unwrap_or("?"))
1018    }
1019    async fn call(&self, args: Value) -> Result<String, ToolError> {
1020        let path = confine(&self.root, str_arg(&args, "path")?)?;
1021        let fail = |e: std::io::Error| ToolError::Failed(format!("{}: {e}", path.display()));
1022        // `#416`: `open(2)` on a FIFO with no writer blocks until somebody writes, so the check came
1023        // after the one call that could never return — the tool call and the turn hung, and a pool
1024        // thread went with them. `/dev/stdin` is only one spelling of that; a FIFO inside the
1025        // workspace is confined like any other path. Stat first, refuse what is not a regular file,
1026        // and open only what passed. (A file swapped between the two calls is a race this heuristic
1027        // does not try to win: the alternative is `O_NONBLOCK` and a read loop that means nothing to
1028        // this tool.)
1029        let meta = tokio::fs::metadata(&path).await.map_err(fail)?;
1030        if !meta.is_file() {
1031            return Err(ToolError::Failed(format!(
1032                "{}: not a regular file",
1033                path.display()
1034            )));
1035        }
1036        let file = tokio::fs::File::open(&path).await.map_err(fail)?;
1037        // Read one byte past the cap so the registry can tell the output was cut.
1038        let mut buf = Vec::new();
1039        file.take(self.max_bytes as u64 + 1)
1040            .read_to_end(&mut buf)
1041            .await
1042            .map_err(fail)?;
1043        // `#416`: the cap is a byte count, so the cut can land inside a character — and the old
1044        // code answered that with lossy text while a *smaller* binary file was an error. Same file,
1045        // same content, two answers depending on size: a big binary came back as garbage the model
1046        // then reasoned about. Now the rule is the file's, not the cut's: what is not UTF-8 is an
1047        // error, and the one exception is the character this tool cut in half, whose text is kept.
1048        let cut = buf.len() > self.max_bytes;
1049        match String::from_utf8(buf) {
1050            Ok(text) => Ok(text),
1051            Err(e) if cut && e.utf8_error().error_len().is_none() => {
1052                // The cut fell inside a character — `error_len() == None` means "input ended
1053                // mid-sequence", which is this tool's doing and not the file's. Keep the text and
1054                // leave one replacement character where the cut landed, so the string is still past
1055                // the cap and the registry marks it as cut rather than passing a silently shorter
1056                // file off as the whole one.
1057                let valid = e.utf8_error().valid_up_to();
1058                let mut bytes = e.into_bytes();
1059                bytes.truncate(valid);
1060                Ok(format!("{}\u{FFFD}", String::from_utf8_lossy(&bytes)))
1061            }
1062            Err(_) => Err(ToolError::Failed(format!(
1063                "{}: not valid UTF-8",
1064                path.display()
1065            ))),
1066        }
1067    }
1068}
1069
1070/// `write_file`: the workspace, and one more allowed root, the scripts directory.
1071///
1072/// The second root is the point of the `script` tool: a directory the agent is *meant* to
1073/// write into. It is the user's own config directory, so it is one extra place rather than a
1074/// way out of the workspace, and it is confined the same way — symlinks followed, `..` and
1075/// absolute paths resolved — against its own canonical form.
1076pub struct WriteFile {
1077    root: PathBuf,
1078    scripts: Option<PathBuf>,
1079    description: String,
1080    /// Beyond this many bytes, clobbering an existing file needs `force`. A rewrite sends the
1081    /// whole file as a tool-call argument, and that argument stays in the conversation for the
1082    /// rest of the session; a 44 KB file rewritten once is ~12k tokens of context forever. 0
1083    /// switches the guard off.
1084    guard_bytes: usize,
1085}
1086
1087impl WriteFile {
1088    pub(crate) fn new(root: PathBuf, scripts: Option<PathBuf>) -> Self {
1089        // The fence is named here, not only in the refusal. A model that cannot see where the
1090        // workspace is plans against the path it was asked for and finds out after it has already
1091        // spent the whole file on a call that will be refused.
1092        let description = match &scripts {
1093            None => format!(
1094                "Create or overwrite a text file inside the workspace ({}). A path outside it is \
1095refused, so a file that belongs elsewhere is written here and moved with `shell`. To change part \
1096of a file that already exists, use `patch`: a rewrite carries the whole file, and the whole file \
1097stays in the conversation afterwards.",
1098                root.display()
1099            ),
1100            Some(dir) => format!(
1101                "Create or overwrite a text file inside the workspace ({}), or inside the scripts \
1102directory ({}) which takes an absolute path. A path outside both is refused. A script written \
1103there is not executable until you run `chmod +x` on it with `shell`; see the `script` tool. To \
1104change part of a file that already exists, use `patch`: a rewrite carries the whole file, and the \
1105whole file stays in the conversation afterwards.",
1106                root.display(),
1107                dir.display()
1108            ),
1109        };
1110        Self {
1111            root,
1112            scripts,
1113            description,
1114            guard_bytes: 0,
1115        }
1116    }
1117
1118    /// Refuse to clobber an existing file **at least** `bytes` long unless the call says `force`.
1119    /// Configures the guard; `0` leaves `write_file` unguarded.
1120    ///
1121    /// The boundary is inclusive, which is the conservative reading of a safety limit: a file the
1122    /// size of the threshold is already the expensive rewrite this exists to stop. `0` disables it,
1123    /// and a creation is never a clobber.
1124    pub(crate) fn guard_bytes(mut self, bytes: usize) -> Self {
1125        self.guard_bytes = bytes;
1126        self
1127    }
1128
1129    /// `joined` (already normalised) relative to the scripts directory, when it lies lexically
1130    /// inside it. The directory may not exist yet, so this cannot ask the file system; the
1131    /// symlink check happens afterwards, against the directory as it then is.
1132    fn relative_to_scripts(&self, joined: &Path) -> Option<PathBuf> {
1133        let dir = normalize(self.scripts.as_deref()?);
1134        let canon = std::fs::canonicalize(&dir).ok();
1135        std::iter::once(dir)
1136            .chain(canon)
1137            .find_map(|d| joined.strip_prefix(d).ok().map(Path::to_path_buf))
1138    }
1139
1140    /// Where `requested` is to be written: inside the workspace, else inside the scripts
1141    /// directory, else refused with both roots named.
1142    pub(crate) fn resolve(&self, requested: &str) -> Result<PathBuf, ToolError> {
1143        let in_workspace = confine(&self.root, requested);
1144        let Some(scripts) = &self.scripts else {
1145            return in_workspace;
1146        };
1147        if let Ok(path) = in_workspace {
1148            return Ok(path);
1149        }
1150        let outside = || {
1151            ToolError::Failed(format!(
1152                "path `{requested}` is outside the workspace ({}) and outside the scripts \
1153directory ({})",
1154                self.root.display(),
1155                scripts.display()
1156            ))
1157        };
1158        let joined = normalize(&self.root.join(requested));
1159        let rest = self.relative_to_scripts(&joined).ok_or_else(outside)?;
1160        let rest = rest.to_str().ok_or_else(outside)?;
1161        std::fs::create_dir_all(scripts)
1162            .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
1163        let canon = std::fs::canonicalize(scripts)
1164            .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
1165        confine(&canon, rest).map_err(|_| outside())
1166    }
1167}
1168
1169#[async_trait]
1170impl Tool for WriteFile {
1171    fn name(&self) -> &str {
1172        "write_file"
1173    }
1174    fn description(&self) -> &str {
1175        &self.description
1176    }
1177    fn parameters(&self) -> Value {
1178        let path = match &self.scripts {
1179            Some(dir) => format!(
1180                "Path relative to the workspace ({}), or an absolute path inside the scripts \
1181directory ({})",
1182                self.root.display(),
1183                dir.display()
1184            ),
1185            None => format!("Path relative to the workspace ({})", self.root.display()),
1186        };
1187        json!({"type":"object","properties":{
1188            "path":{"type":"string","description":path},
1189            "content":{"type":"string"},
1190            "force":{"type":"boolean","description":"Replace an existing file even if it is large. A rewrite sends the whole file and it stays in the conversation; `patch` changes only the lines you name. Default false."}
1191        },"required":["path","content"]})
1192    }
1193    fn describe_call(&self, args: &Value) -> String {
1194        let path = args["path"].as_str().unwrap_or("?");
1195        let joined = normalize(&self.root.join(path));
1196        let in_scripts =
1197            !joined.starts_with(&self.root) && self.relative_to_scripts(&joined).is_some();
1198        format!(
1199            "write {} bytes to {path}{}",
1200            args["content"].as_str().map(str::len).unwrap_or(0),
1201            if in_scripts {
1202                " (scripts directory)"
1203            } else {
1204                ""
1205            }
1206        )
1207    }
1208    async fn call(&self, args: Value) -> Result<String, ToolError> {
1209        let content = str_arg(&args, "content")?;
1210        let path = self.resolve(str_arg(&args, "path")?)?;
1211        // A rewrite of a file that already exists is the expensive way to make a small change:
1212        // the whole file rides in this call's arguments and stays in the conversation afterwards.
1213        // Past the guard, the model has to mean it — `patch` for an edit, or `force` for a real
1214        // replacement — instead of quietly paying the whole file again.
1215        if self.guard_bytes > 0 && !args["force"].as_bool().unwrap_or(false) {
1216            if let Ok(meta) = tokio::fs::metadata(&path).await {
1217                let existing = meta.len() as usize;
1218                if existing >= self.guard_bytes {
1219                    let name = path
1220                        .file_name()
1221                        .map(|n| n.to_string_lossy().into_owned())
1222                        .unwrap_or_else(|| path.display().to_string());
1223                    return Err(ToolError::Failed(format!(
1224                        "refused: {name} already exists at {} bytes. Rewriting it means sending all \
1225{existing} bytes again, and they stay in the conversation for the rest of the session. Use \
1226`patch` for the lines you want to change — that carries only those lines — or call write_file \
1227again with `force: true` if the file really has to be replaced whole.",
1228                        existing
1229                    )));
1230                }
1231            }
1232        }
1233        if let Some(parent) = path.parent() {
1234            tokio::fs::create_dir_all(parent)
1235                .await
1236                .map_err(|e| ToolError::Failed(format!("{}: {e}", parent.display())))?;
1237        }
1238        tokio::fs::write(&path, content)
1239            .await
1240            .map_err(|e| ToolError::Failed(format!("{}: {e}", path.display())))?;
1241        Ok(format!(
1242            "wrote {} bytes to {}",
1243            content.len(),
1244            path.display()
1245        ))
1246    }
1247}
1248
1249pub struct Shell {
1250    root: PathBuf,
1251    /// Where skills are looked for when a `cwd` points outside the workspace.
1252    skill_roots: Vec<crate::skills::Root>,
1253    /// The scripts directory: a `cwd` may point into it, and the commands see it in
1254    /// `ECLIPSE_SCRIPTS_DIR` (and first on `PATH` unless an allowlist is set).
1255    scripts_dir: Option<PathBuf>,
1256    timeout: Duration,
1257    allowlist: Vec<String>,
1258    max_bytes: usize,
1259    /// Time between SIGTERM and SIGKILL when a timed-out command's process group is stopped.
1260    kill_grace: Duration,
1261    /// What the command may reach once it runs: nothing, a private PID namespace, or that plus a
1262    /// read-only filesystem. See [`crate::sandbox`].
1263    sandbox: crate::sandbox::Sandbox,
1264    /// Whether a person is asked about every command or only about the dangerous ones.
1265    ask: crate::config::ShellAsk,
1266}
1267
1268pub(crate) const SHELL_KILL_GRACE: Duration = Duration::from_secs(2);
1269
1270/// The shell runs in its own process group so a timeout can stop background
1271/// grandchildren too, not just the direct child.
1272#[cfg(unix)]
1273pub(crate) mod pgroup {
1274    use std::time::{Duration, Instant};
1275
1276    fn signal(pgid: u32, sig: libc::c_int) {
1277        if let Ok(pgid) = libc::pid_t::try_from(pgid) {
1278            // SAFETY: plain syscall; a negative pid addresses the whole process group.
1279            unsafe { libc::kill(-pgid, sig) };
1280        }
1281    }
1282
1283    /// One process, addressed by pid rather than by group.
1284    fn signal_pid(pid: u32, sig: libc::c_int) {
1285        if let Ok(pid) = libc::pid_t::try_from(pid) {
1286            // SAFETY: plain syscall. A pid that has been reused since the walk is a risk the caller
1287            // takes only while the child is still unreaped — see `Guard`.
1288            unsafe { libc::kill(pid, sig) };
1289        }
1290    }
1291
1292    /// Every process that descends from `root`, found through the `ppid` column of `/proc`.
1293    ///
1294    /// A child that calls `setsid` leaves the process group, and the group kill misses it. The
1295    /// parent link survives `setsid` (only a reparent to init breaks it), so the tree is the one
1296    /// thing that still names it. Deliberately shallow: no cgroups, no root, nothing to set up —
1297    /// and it says so in the docs rather than pretending.
1298    fn descendants(root: u32) -> Vec<u32> {
1299        let mut parent_of: Vec<(u32, u32)> = Vec::new();
1300        let Ok(entries) = std::fs::read_dir("/proc") else {
1301            return Vec::new();
1302        };
1303        for entry in entries.flatten() {
1304            let Some(pid) = entry
1305                .file_name()
1306                .to_str()
1307                .and_then(|s| s.parse::<u32>().ok())
1308            else {
1309                continue;
1310            };
1311            let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
1312                // Gone between the listing and the read: a process not worth reporting.
1313                continue;
1314            };
1315            // `pid (comm) state ppid …`, and `comm` may hold spaces and parentheses — so the fields
1316            // start after the *last* `)`.
1317            let Some((_, rest)) = stat.rsplit_once(')') else {
1318                continue;
1319            };
1320            let Some(ppid) = rest
1321                .split_whitespace()
1322                .nth(1)
1323                .and_then(|s| s.parse::<u32>().ok())
1324            else {
1325                continue;
1326            };
1327            parent_of.push((pid, ppid));
1328        }
1329        let mut out = Vec::new();
1330        let mut frontier = vec![root];
1331        while let Some(parent) = frontier.pop() {
1332            for (pid, ppid) in &parent_of {
1333                if *ppid == parent && !out.contains(pid) {
1334                    out.push(*pid);
1335                    frontier.push(*pid);
1336                }
1337            }
1338        }
1339        out
1340    }
1341
1342    /// SIGTERM, then SIGKILL, to the group *and* to every descendant still reachable by its parent
1343    /// link. The tree is walked before the first signal, because killing the parent is what makes a
1344    /// `setsid` grandchild unreachable.
1345    fn stop_tree(pgid: u32, sig: libc::c_int, tree: &[u32]) {
1346        signal(pgid, sig);
1347        for pid in tree {
1348            signal_pid(*pid, sig);
1349        }
1350    }
1351
1352    fn alive(pgid: u32) -> bool {
1353        let Ok(pgid) = libc::pid_t::try_from(pgid) else {
1354            return false;
1355        };
1356        // SAFETY: signal 0 only checks that the group exists.
1357        let rc = unsafe { libc::kill(-pgid, 0) };
1358        rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1359    }
1360
1361    /// SIGTERM the group, wait up to `grace` for it to disappear, then SIGKILL it.
1362    /// The direct child is reaped on the way so it does not linger as a zombie that
1363    /// would keep the group "alive".
1364    pub async fn terminate(child: &mut tokio::process::Child, pgid: u32, grace: Duration) {
1365        // Before any signal: a `setsid` grandchild is only reachable through its parent, so the
1366        // walk has to happen while the parent is still there to name it.
1367        let tree = descendants(pgid);
1368        stop_tree(pgid, libc::SIGTERM, &tree);
1369        let deadline = Instant::now() + grace;
1370        loop {
1371            let _ = child.try_wait();
1372            if !alive(pgid) && tree.iter().all(|pid| !alive_pid(*pid)) {
1373                return;
1374            }
1375            if Instant::now() >= deadline {
1376                break;
1377            }
1378            tokio::time::sleep(Duration::from_millis(20)).await;
1379        }
1380        // A descendant of a descendant may have appeared in the meantime; one more walk costs a
1381        // directory listing.
1382        let mut late = descendants(pgid);
1383        late.extend(tree);
1384        late.sort_unstable();
1385        late.dedup();
1386        stop_tree(pgid, libc::SIGKILL, &late);
1387        let _ = child.wait().await;
1388    }
1389
1390    /// Whether a single pid still exists. Used only for a pid this process has not reaped, so the
1391    /// id cannot have been handed out twice.
1392    fn alive_pid(pid: u32) -> bool {
1393        let Ok(pid) = libc::pid_t::try_from(pid) else {
1394            return false;
1395        };
1396        // SAFETY: signal 0 only checks that the process exists.
1397        let rc = unsafe { libc::kill(pid, 0) };
1398        rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1399    }
1400
1401    /// SIGKILL to the group and to every descendant reachable by its parent link, synchronously.
1402    ///
1403    /// For a `Drop` with no runtime to wait on: an MCP server is driven over plain blocking pipes
1404    /// (`#418`), and killing only its direct child left an `npx`/`sh -c` grandchild running — and
1405    /// holding the stdout pipe, so the reader thread stayed blocked on a connection nobody owned.
1406    pub(crate) fn kill_now(pgid: u32) {
1407        let tree = descendants(pgid);
1408        stop_tree(pgid, libc::SIGKILL, &tree);
1409    }
1410
1411    /// Kills the group if the run is cancelled (future dropped) before it finishes.
1412    pub struct Guard(Option<u32>);
1413
1414    impl Guard {
1415        pub fn new(pgid: Option<u32>) -> Self {
1416            Self(pgid)
1417        }
1418        pub fn disarm(&mut self) {
1419            self.0 = None;
1420        }
1421    }
1422
1423    impl Drop for Guard {
1424        /// A dropped future is a cancelled run: this is the only path that stops a child then, and
1425        /// it has no `.await` to work with — hence the synchronous walk.
1426        fn drop(&mut self) {
1427            if let Some(pgid) = self.0 {
1428                stop_tree(pgid, libc::SIGKILL, &descendants(pgid));
1429            }
1430        }
1431    }
1432}
1433
1434#[cfg(not(unix))]
1435mod pgroup {
1436    use std::time::Duration;
1437
1438    pub async fn terminate(child: &mut tokio::process::Child, _: u32, _: Duration) {
1439        let _ = child.kill().await;
1440    }
1441
1442    pub struct Guard;
1443
1444    impl Guard {
1445        pub fn new(_: Option<u32>) -> Self {
1446            Self
1447        }
1448        pub fn disarm(&mut self) {}
1449    }
1450}
1451
1452/// Read at most `cap` bytes, then drop the pipe so a flooding child gets SIGPIPE
1453/// instead of growing our memory.
1454///
1455/// The text lands in a buffer the caller also holds, not in the future's return value: `#368` — a
1456/// reader only ends at pipe EOF, and a background process the command started inherits the write
1457/// end, so the drain can outlive the call by hours. Publishing as it goes lets `finish` take what
1458/// has been read and let the reader go, instead of waiting for an EOF that is not coming.
1459pub(crate) struct Drain {
1460    buf: Arc<std::sync::Mutex<Vec<u8>>>,
1461    cap: usize,
1462    /// Set when the pipe was abandoned with more behind it, so the text says it is short.
1463    cut: Arc<std::sync::atomic::AtomicBool>,
1464    task: tokio::task::JoinHandle<()>,
1465}
1466
1467impl Drain {
1468    pub(crate) fn start<R: AsyncRead + Unpin + Send + 'static>(
1469        pipe: Option<R>,
1470        cap: usize,
1471    ) -> Self {
1472        let buf = Arc::new(std::sync::Mutex::new(Vec::new()));
1473        let cut = Arc::new(std::sync::atomic::AtomicBool::new(false));
1474        let task = tokio::spawn(drain_into(pipe, cap, buf.clone(), cut.clone()));
1475        Self {
1476            buf,
1477            cap,
1478            cut,
1479            task,
1480        }
1481    }
1482
1483    /// What has been read so far, and whether that is all of it.
1484    pub(crate) fn take(&self) -> (String, bool) {
1485        let buf = self
1486            .buf
1487            .lock()
1488            .unwrap_or_else(|poisoned| poisoned.into_inner());
1489        let short = self.cut.load(std::sync::atomic::Ordering::SeqCst) || buf.len() > self.cap;
1490        let text = String::from_utf8_lossy(&buf[..buf.len().min(self.cap)]).into_owned();
1491        (text, short)
1492    }
1493}
1494
1495impl Drop for Drain {
1496    /// A dropped caller is a cancelled run: the reader has nobody to publish to, and holding the
1497    /// pipe open would be the one thing `#368` is about.
1498    fn drop(&mut self) {
1499        self.task.abort();
1500    }
1501}
1502
1503/// [`Drain`] for a caller that wants the finished text and nothing in between — the plugin host,
1504/// which already bounds the whole run with its own timeout.
1505pub(crate) async fn read_capped<R: AsyncRead + Unpin + Send + 'static>(
1506    pipe: Option<R>,
1507    cap: usize,
1508) -> (String, bool) {
1509    let mut drain = Drain::start(pipe, cap);
1510    let _ = (&mut drain.task).await;
1511    drain.take()
1512}
1513
1514async fn drain_into<R: AsyncRead + Unpin>(
1515    pipe: Option<R>,
1516    cap: usize,
1517    buf: Arc<std::sync::Mutex<Vec<u8>>>,
1518    cut: Arc<std::sync::atomic::AtomicBool>,
1519) {
1520    let Some(mut pipe) = pipe else { return };
1521    let mut chunk = [0u8; 8192];
1522    loop {
1523        let room = (cap + 1).saturating_sub(buf.lock().map(|b| b.len()).unwrap_or(0));
1524        // Dropping the pipe is the point: a child that floods past the cap gets SIGPIPE rather than
1525        // an ever-growing buffer in this process.
1526        if room == 0 {
1527            cut.store(true, std::sync::atomic::Ordering::SeqCst);
1528            return;
1529        }
1530        let want = room.min(chunk.len());
1531        match pipe.read(&mut chunk[..want]).await {
1532            Ok(0) => return,
1533            Ok(n) => {
1534                if let Ok(mut buf) = buf.lock() {
1535                    buf.extend_from_slice(&chunk[..n]);
1536                }
1537            }
1538            Err(_) => return,
1539        }
1540    }
1541}
1542
1543const SHELL_META: &[char] = &[
1544    ';', '&', '|', '<', '>', '$', '`', '\n', '(', ')', '\\', '"', '\'', '*', '?',
1545];
1546
1547/// Whether a command text looks like it puts work in the background.
1548///
1549/// An approximation, and deliberately a cheap one: its only job is to decide whether to print
1550/// one sentence about containment. A false positive is a harmless note; a false negative is
1551/// silence about a server that is no longer running.
1552fn looks_backgrounded(command: &str) -> bool {
1553    if ["nohup", "setsid", "disown"]
1554        .iter()
1555        .any(|word| command.contains(word))
1556    {
1557        return true;
1558    }
1559    let bytes = command.as_bytes();
1560    for (i, &c) in bytes.iter().enumerate() {
1561        if c != b'&' {
1562            continue;
1563        }
1564        let next = bytes.get(i + 1).copied().unwrap_or(b' ');
1565        let prev = if i == 0 { b' ' } else { bytes[i - 1] };
1566        // `&&` joins, `&>` and `>&` are redirections; neither backgrounds anything.
1567        if next == b'&' || prev == b'&' || next == b'>' || prev == b'>' {
1568            continue;
1569        }
1570        return true;
1571    }
1572    false
1573}
1574
1575impl Shell {
1576    fn build_command(
1577        &self,
1578        command: &str,
1579        dir: &Path,
1580    ) -> Result<tokio::process::Command, ToolError> {
1581        let (program, args) = self.program_argv(command)?;
1582        let plan = self.sandbox.plan(&program, &args, dir)?;
1583        let mut c = tokio::process::Command::new(plan.program);
1584        c.args(plan.args);
1585        if let Some(dir) = &self.scripts_dir {
1586            c.env(crate::tools_script::ENV_SCRIPTS_DIR, dir);
1587            // With an allowlist, a script named after an allowed program would run in its
1588            // place, so the directory is offered by variable only.
1589            if self.allowlist.is_empty() {
1590                if let Some(path) = crate::tools_script::path_with(dir) {
1591                    c.env("PATH", path);
1592                }
1593            }
1594        }
1595        Ok(c)
1596    }
1597
1598    /// The intended command as (program, arguments), before anything is wrapped around it.
1599    fn program_argv(&self, command: &str) -> Result<(OsString, Vec<OsString>), ToolError> {
1600        if self.allowlist.is_empty() {
1601            return Ok((OsString::from("sh"), vec!["-c".into(), command.into()]));
1602        }
1603        if command.contains(SHELL_META) {
1604            return Err(ToolError::Failed(
1605                "shell syntax is not allowed when shell_allowlist is set".into(),
1606            ));
1607        }
1608        let mut parts = command.split_whitespace();
1609        let prog = parts
1610            .next()
1611            .ok_or_else(|| ToolError::InvalidArgs("empty command".into()))?;
1612        if !self.allowlist.iter().any(|a| a == prog) {
1613            return Err(ToolError::Failed(format!(
1614                "`{prog}` is not in shell_allowlist"
1615            )));
1616        }
1617        Ok((
1618            OsString::from(prog),
1619            parts.map(OsString::from).collect::<Vec<_>>(),
1620        ))
1621    }
1622
1623    /// The directory a command runs in: the workspace root by default, or the requested `cwd`
1624    /// when it resolves — symlinks followed — inside the workspace, inside the scripts
1625    /// directory or inside the directory of a skill that loads. Anything else is refused with
1626    /// what it resolved to.
1627    ///
1628    /// This is what lets a skill's own `bash scripts/backup.sh` work as written. It is not a
1629    /// sandbox: a command can still `cd` wherever the shell lets it, which is what the `ask`
1630    /// policy and `shell_allowlist` are for. What it keeps honest is the argument itself.
1631    fn working_dir(&self, requested: Option<&str>) -> Result<PathBuf, ToolError> {
1632        let Some(requested) = requested else {
1633            return Ok(self.root.clone());
1634        };
1635        let refuse = |why: String| ToolError::Failed(format!("cwd `{requested}` refused: {why}"));
1636        if requested.trim().is_empty() {
1637            return Err(refuse("it is empty".into()));
1638        }
1639        let resolved = std::fs::canonicalize(self.root.join(requested))
1640            .map_err(|e| refuse(format!("it cannot be resolved ({e})")))?;
1641        if !resolved.is_dir() {
1642            return Err(refuse(format!("{} is not a directory", resolved.display())));
1643        }
1644        if resolved.starts_with(&self.root) {
1645            return Ok(resolved);
1646        }
1647        let inside_scripts = self
1648            .scripts_dir
1649            .as_ref()
1650            .and_then(|dir| std::fs::canonicalize(dir).ok())
1651            .is_some_and(|dir| resolved.starts_with(dir));
1652        if inside_scripts {
1653            return Ok(resolved);
1654        }
1655        let report = crate::skills::discover(&self.skill_roots);
1656        let inside_a_skill = report.active().any(|(found, _)| {
1657            std::fs::canonicalize(&found.dir).is_ok_and(|dir| resolved.starts_with(dir))
1658        });
1659        if inside_a_skill {
1660            return Ok(resolved);
1661        }
1662        let scripts = self.scripts_dir.as_ref().map_or(String::new(), |dir| {
1663            format!(", outside the scripts directory ({})", dir.display())
1664        });
1665        Err(refuse(format!(
1666            "it resolves to {}, which is outside the workspace ({}){scripts} and outside every skill's directory",
1667            resolved.display(),
1668            self.root.display()
1669        )))
1670    }
1671
1672    /// A run under isolation cannot leave a daemon behind, which is the point — but it also
1673    /// means a deliberate `nohup server &` is stopped when the call returns. Saying so beats
1674    /// letting someone discover it, so a command that looks like it backgrounds something gets
1675    /// one sentence after its output.
1676    fn afterwards(&self, command: &str, out: String) -> String {
1677        if self.sandbox.degraded() {
1678            return format!(
1679                "{out}\n\n[shell_isolate = \"process\": bubblewrap (`bwrap`) is not on PATH, so this \
1680                 command ran uncontained — with your files, your network, and anything it started \
1681                 still running after it returned. Installing bubblewrap contains it.]"
1682            );
1683        }
1684        if !self.sandbox.is_on() || !looks_backgrounded(command) {
1685            return out;
1686        }
1687        format!(
1688            "{out}\n\n[shell_isolate = \"{}\": anything this command started in the background \
1689             was stopped when it returned, because the run's PID namespace dies with it. Set \
1690             [tools] shell_isolate = \"off\" for this profile if a process has to outlive the \
1691             call.]",
1692            self.sandbox.mode()
1693        )
1694    }
1695}
1696
1697#[async_trait]
1698impl Tool for Shell {
1699    fn name(&self) -> &str {
1700        "shell"
1701    }
1702    /// Only work that cannot be undone asks a person anything. `ls`, `cargo test`, a commit, a
1703    /// file written inside the workspace: those are the job, and a prompt for each of them trains
1704    /// the answer `y` that a `rm -rf` then arrives on top of. See [`crate::risk`] for the list.
1705    fn needs_approval(&self, args: &Value) -> bool {
1706        if self.ask == crate::config::ShellAsk::Always {
1707            return true;
1708        }
1709        match args["command"].as_str() {
1710            Some(command) => crate::risk::danger(command).is_some(),
1711            // A malformed call is the model's mistake, not a person's decision.
1712            None => false,
1713        }
1714    }
1715    fn description(&self) -> &str {
1716        "Run a command in the workspace directory and return its exit code, stdout and stderr. \
1717Pass `cwd` to run it somewhere else inside the workspace, inside the scripts directory, or \
1718inside a skill's own directory (to run that skill's `bash scripts/x.sh` as written); any other \
1719directory is refused. The scripts directory is first on `PATH` (unless a shell allowlist is set) \
1720and named in `ECLIPSE_SCRIPTS_DIR`, so a script there runs as a bare command."
1721    }
1722    fn parameters(&self) -> Value {
1723        json!({
1724            "type": "object",
1725            "properties": {
1726                "command": {"type": "string"},
1727                "cwd": {
1728                    "type": "string",
1729                    "description": "Directory to run in: relative to the workspace, or absolute. It must resolve inside the workspace, the scripts directory or a skill's directory."
1730                }
1731            },
1732            "required": ["command"]
1733        })
1734    }
1735    fn describe_call(&self, args: &Value) -> String {
1736        let command = args["command"].as_str().unwrap_or("?");
1737        match args["cwd"].as_str() {
1738            Some(cwd) => format!("run `{command}` in {cwd}"),
1739            None => format!("run `{command}`"),
1740        }
1741    }
1742    async fn call(&self, args: Value) -> Result<String, ToolError> {
1743        let command = str_arg(&args, "command")?;
1744        let cwd = match args.get("cwd") {
1745            None | Some(Value::Null) => None,
1746            Some(Value::String(s)) => Some(s.as_str()),
1747            Some(_) => return Err(ToolError::InvalidArgs("`cwd` must be a string".into())),
1748        };
1749        let dir = self.working_dir(cwd)?;
1750        let mut cmd = self.build_command(command, &dir)?;
1751        // The outer process needs a directory too: bubblewrap inherits it and then lands in the
1752        // one it was told to `--chdir` to.
1753        cmd.current_dir(&dir);
1754        let out = run_to_completion(cmd, self.timeout, self.max_bytes, self.kill_grace).await?;
1755        Ok(self.afterwards(command, out))
1756    }
1757}
1758
1759/// Start `cmd` with no stdin and piped output, in its own process group, and wait for it.
1760///
1761/// This is what `shell` and `script` have in common, so they keep the same guarantees by
1762/// being the same code: the run is bounded by `timeout`, a timeout stops the whole process
1763/// group (a background child cannot keep the run alive) and is reported as a timeout, output
1764/// is read up to `max_bytes` per stream and a flooding child is cut off, dropping the
1765/// future kills the group, and a child that exits is not waited on beyond a short grace even
1766/// when what it started still holds the output pipe (`DRAIN_GRACE`, `#368`).
1767/// Start a child built on demand, trying again when the kernel refuses the file for a moment.
1768///
1769/// `ETXTBSY` ("Text file busy") does not mean the file is wrong: it means someone still holds it
1770/// open for writing. In a program that writes a script and then runs it, the holder is usually a
1771/// child forked by another thread — the descriptor is inherited until that child execs. The
1772/// window is microseconds, so a fresh attempt is the right answer, not an error the person has to
1773/// interpret and work around.
1774pub(crate) async fn start_retrying<F>(mut build: F, max_bytes: usize) -> Result<Running, ToolError>
1775where
1776    F: FnMut() -> tokio::process::Command,
1777{
1778    let mut attempt = 0u32;
1779    loop {
1780        match start(build(), max_bytes) {
1781            Ok(running) => return Ok(running),
1782            Err(e) if attempt < 4 && is_text_busy(&e) => {
1783                attempt += 1;
1784                tokio::time::sleep(Duration::from_millis(1 << attempt)).await;
1785            }
1786            Err(e) => return Err(ToolError::Failed(crate::tools_script::start_error(&e))),
1787        }
1788    }
1789}
1790
1791#[cfg(unix)]
1792fn is_text_busy(e: &std::io::Error) -> bool {
1793    e.raw_os_error() == Some(libc::ETXTBSY)
1794}
1795
1796#[cfg(not(unix))]
1797fn is_text_busy(_: &std::io::Error) -> bool {
1798    false
1799}
1800
1801/// [`run_to_completion`] for a child that has to be built again if starting it is refused.
1802pub(crate) async fn run_built<F>(
1803    mut build: F,
1804    timeout: Duration,
1805    max_bytes: usize,
1806    kill_grace: Duration,
1807) -> Result<String, ToolError>
1808where
1809    F: FnMut() -> tokio::process::Command,
1810{
1811    let mut running = start_retrying(&mut build, max_bytes).await?;
1812    let status = match tokio::time::timeout(timeout, running.wait()).await {
1813        Ok(done) => done?,
1814        Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1815    };
1816    Ok(running.finish(status).await)
1817}
1818
1819pub(crate) async fn run_to_completion(
1820    cmd: tokio::process::Command,
1821    timeout: Duration,
1822    max_bytes: usize,
1823    kill_grace: Duration,
1824) -> Result<String, ToolError> {
1825    let mut running = spawn(cmd, max_bytes)?;
1826    let status = match tokio::time::timeout(timeout, running.wait()).await {
1827        Ok(done) => done?,
1828        Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1829    };
1830    Ok(running.finish(status).await)
1831}
1832
1833/// How long a finished child's pipes get to reach EOF before the drain is abandoned. A real drain
1834/// has nothing left to read once the child is reaped; only an inherited write end keeps it open.
1835const DRAIN_GRACE: Duration = Duration::from_millis(500);
1836
1837/// A child that has been started, with its output being drained.
1838///
1839/// Split out of [`run_to_completion`] so that the one place which decides what a child process
1840/// gets — no stdin, piped output, its own process group, killed when the future is dropped — is
1841/// also the one place the bridge in [`crate::tools_bridge`] starts from. It waits differently
1842/// (it also answers the child's tool calls), but it must not spawn differently.
1843pub(crate) struct Running {
1844    /// Declared before `child` on purpose: fields drop in declaration order, and `child` is
1845    /// `kill_on_drop`. If the child is killed first, a `setsid` grandchild is reparented to init and
1846    /// the guard's walk can no longer find it — the one case it exists for.
1847    guard: pgroup::Guard,
1848    pgid: Option<u32>,
1849    pub(crate) child: tokio::process::Child,
1850    out: Drain,
1851    err: Drain,
1852}
1853
1854pub(crate) fn spawn(cmd: tokio::process::Command, max_bytes: usize) -> Result<Running, ToolError> {
1855    start(cmd, max_bytes).map_err(|e| ToolError::Failed(crate::tools_script::start_error(&e)))
1856}
1857
1858/// [`spawn`] with the `io::Error` kept: "Text file busy" is a refusal that passes in a moment,
1859/// and a caller can only tell it apart from a real failure while the errno is still there.
1860pub(crate) fn start(
1861    mut cmd: tokio::process::Command,
1862    max_bytes: usize,
1863) -> std::io::Result<Running> {
1864    cmd.stdin(std::process::Stdio::null())
1865        .stdout(std::process::Stdio::piped())
1866        .stderr(std::process::Stdio::piped())
1867        .kill_on_drop(true);
1868    #[cfg(unix)]
1869    cmd.process_group(0);
1870    let mut child = cmd.spawn()?;
1871    let pgid = child.id();
1872    let guard = pgroup::Guard::new(pgid);
1873    let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
1874    // Readers are their own tasks so that a child filling one pipe cannot block on the other,
1875    // and so that a caller which waits some other way still drains both.
1876    let out = Drain::start(stdout, max_bytes);
1877    let err = Drain::start(stderr, max_bytes);
1878    Ok(Running {
1879        guard,
1880        pgid,
1881        child,
1882        out,
1883        err,
1884    })
1885}
1886
1887impl Running {
1888    pub(crate) async fn wait(&mut self) -> Result<std::process::ExitStatus, ToolError> {
1889        match self.child.wait().await {
1890            Ok(status) => {
1891                // Reaped: the pid — and so the group id — can be reused from here on.
1892                self.guard.disarm();
1893                Ok(status)
1894            }
1895            Err(e) => Err(ToolError::Failed(format!("failed to wait: {e}"))),
1896        }
1897    }
1898
1899    /// The timeout message, after stopping the whole group. `kill_grace` is honoured for the
1900    /// same reason as in a normal run: a child that ignores SIGTERM must not hold the turn.
1901    pub(crate) async fn timed_out(&mut self, timeout: Duration, kill_grace: Duration) -> ToolError {
1902        if let Some(pgid) = self.pgid {
1903            pgroup::terminate(&mut self.child, pgid, kill_grace).await;
1904        }
1905        // `terminate` reaped the child, so the group id is the kernel's to hand out again. The
1906        // guard must not fire on the way out: on a host with a small `pid_max` that kill reaches
1907        // whoever was given the id next.
1908        self.guard.disarm();
1909        ToolError::Failed(format!("timed out after {}s", timeout.as_secs()))
1910    }
1911
1912    /// The result text every process tool returns, in one spelling.
1913    ///
1914    /// `#368`: the drain ends at pipe EOF, which is when the *last* holder of the write end closes
1915    /// it — and a background process the command started inherits that end. `sh -c 'sleep 1000 &
1916    /// echo started'` exits in a millisecond, so `wait` returned, the guard was disarmed, and the
1917    /// turn then sat in this function for 1000 seconds. After the child is reaped a real drain has
1918    /// nothing left to read; whatever is still quiet after the grace is not this call's output, so
1919    /// it is taken as it stands and the reader is let go.
1920    pub(crate) async fn finish(mut self, status: std::process::ExitStatus) -> String {
1921        self.guard.disarm();
1922        let stalled = tokio::time::timeout(DRAIN_GRACE, async {
1923            let _ = (&mut self.out.task).await;
1924            let _ = (&mut self.err.task).await;
1925        })
1926        .await
1927        .is_err();
1928        if stalled {
1929            self.out.task.abort();
1930            self.err.task.abort();
1931        }
1932        let (out, out_cut) = self.out.take();
1933        let (err, err_cut) = self.err.take();
1934        let note = |cut| if cut { "\n[truncated]" } else { "" };
1935        let held = if stalled {
1936            "\n[a process the command started still holds its output pipe; this call did not wait \
1937             for it]"
1938        } else {
1939            ""
1940        };
1941        format!(
1942            "exit code: {}\nstdout:\n{out}{}\nstderr:\n{err}{}{held}",
1943            status.code().map_or("signal".into(), |c| c.to_string()),
1944            note(out_cut),
1945            note(err_cut),
1946        )
1947    }
1948}
1949
1950/// When converting HTML to text, read up to this many times `max_bytes` of markup so
1951/// that the text, which is much shorter than the source, can still fill the budget.
1952const HTML_READ_FACTOR: usize = 8;
1953
1954pub struct Fetch {
1955    timeout: Duration,
1956    max_bytes: usize,
1957    html: FetchHtml,
1958    /// Lets tests talk to a loopback mock server; never compiled into release builds.
1959    #[cfg(test)]
1960    allow_internal: bool,
1961}
1962
1963impl Fetch {
1964    pub fn new(timeout: Duration, max_bytes: usize) -> Self {
1965        Self {
1966            timeout,
1967            max_bytes,
1968            html: FetchHtml::Text,
1969            #[cfg(test)]
1970            allow_internal: false,
1971        }
1972    }
1973
1974    pub fn with_html(mut self, html: FetchHtml) -> Self {
1975        self.html = html;
1976        self
1977    }
1978
1979    fn reach(&self) -> crate::http::Reach {
1980        #[cfg(test)]
1981        if self.allow_internal {
1982            return crate::http::Reach::Anywhere;
1983        }
1984        crate::http::Reach::Public
1985    }
1986}
1987
1988#[async_trait]
1989impl Tool for Fetch {
1990    fn name(&self) -> &str {
1991        "fetch"
1992    }
1993    fn description(&self) -> &str {
1994        "HTTP GET a public http(s) URL and return the response body as text. HTML pages are \
1995         converted to approximate plain text unless `raw` is true. \
1996         Private, loopback and link-local hosts are blocked."
1997    }
1998    fn parameters(&self) -> Value {
1999        json!({"type":"object","properties":{
2000            "url":{"type":"string"},
2001            "raw":{"type":"boolean","description":"return HTML source instead of converted text"}
2002        },"required":["url"]})
2003    }
2004    fn describe_call(&self, args: &Value) -> String {
2005        format!("GET {}", args["url"].as_str().unwrap_or("?"))
2006    }
2007    async fn call(&self, args: Value) -> Result<String, ToolError> {
2008        let raw = str_arg(&args, "url")?;
2009        let url = reqwest::Url::parse(raw)
2010            .map_err(|e| ToolError::InvalidArgs(format!("invalid URL: {e}")))?;
2011        if !matches!(url.scheme(), "http" | "https") {
2012            return Err(ToolError::InvalidArgs(
2013                "only http(s) URLs are allowed".into(),
2014            ));
2015        }
2016        // Redirects are not followed: approval covered this URL only, so a redirect
2017        // target is reported and the model must ask (and be approved) again.
2018        let mut resp = crate::http::get(&url, self.timeout, self.reach(), &[])
2019            .await
2020            .map_err(ToolError::Failed)?;
2021        let status = resp.status();
2022        let location = resp
2023            .headers()
2024            .get(reqwest::header::LOCATION)
2025            .map(|v| format!("location: {}\n", String::from_utf8_lossy(v.as_bytes())))
2026            .unwrap_or_default();
2027        let content_type = resp
2028            .headers()
2029            .get(reqwest::header::CONTENT_TYPE)
2030            .and_then(|v| v.to_str().ok())
2031            .map(str::to_string);
2032        let want_raw = match args.get("raw").and_then(Value::as_bool) {
2033            Some(raw) => raw,
2034            None => self.html == FetchHtml::Raw,
2035        };
2036        // A declared HTML page gets a larger read budget because its text is far shorter
2037        // than its markup; anything else (including sniffed HTML) uses the normal cap.
2038        let declared_html = content_type
2039            .as_deref()
2040            .is_some_and(|c| c.to_ascii_lowercase().contains("html"));
2041        let limit = if declared_html && !want_raw {
2042            self.max_bytes.saturating_mul(HTML_READ_FACTOR)
2043        } else {
2044            self.max_bytes
2045        };
2046        let mut body = Vec::new();
2047        while let Some(chunk) = resp
2048            .chunk()
2049            .await
2050            .map_err(|e| ToolError::Failed(e.to_string()))?
2051        {
2052            body.extend_from_slice(&chunk);
2053            if body.len() > limit {
2054                break;
2055            }
2056        }
2057        let cut = body.len() > limit;
2058        body.truncate(limit);
2059        let text = String::from_utf8_lossy(&body).into_owned();
2060        let (note, text) = if !want_raw
2061            && crate::html::looks_like_html(content_type.as_deref(), &text)
2062        {
2063            (
2064                "note: HTML converted to approximate plain text (pass \"raw\": true for the source)\n",
2065                crate::html::to_text(&text),
2066            )
2067        } else {
2068            ("", text)
2069        };
2070        let marker = if cut {
2071            "\n[response body truncated]"
2072        } else {
2073            ""
2074        };
2075        Ok(format!(
2076            "status: {status}\n{location}{note}{}{marker}",
2077            truncate(text, self.max_bytes)
2078        ))
2079    }
2080}
2081
2082#[cfg(test)]
2083mod tests {
2084    use super::*;
2085    use crate::config::ShellIsolate;
2086    use std::sync::atomic::{AtomicUsize, Ordering};
2087
2088    struct Echo;
2089
2090    #[async_trait]
2091    impl Tool for Echo {
2092        fn name(&self) -> &str {
2093            "echo"
2094        }
2095        fn description(&self) -> &str {
2096            "echo"
2097        }
2098        fn parameters(&self) -> Value {
2099            json!({"type":"object"})
2100        }
2101        async fn call(&self, args: Value) -> Result<String, ToolError> {
2102            Ok(str_arg(&args, "text")?.to_string())
2103        }
2104    }
2105
2106    /// `#351`: a pattern is matched against a tool's name *and* its source, because an MCP tool
2107    /// keeps the name its server published and so cannot be deferred by name.
2108    #[test]
2109    fn a_pattern_matches_a_source_as_well_as_a_name() {
2110        let mut registry = ToolRegistry::new(4096);
2111        registry.register(Arc::new(Echo), Policy::Allow);
2112        registry.register_with_source(
2113            Arc::new(Other),
2114            Policy::Allow,
2115            ToolSource::Plugin("mcp:homeassistant".into()),
2116        );
2117        let unknown = registry.defer(&["plugin:mcp:*".to_string()]);
2118        assert!(unknown.is_empty(), "a wildcard that matches is not a typo");
2119        let described = registry.descriptors();
2120        let deferred: Vec<&str> = described
2121            .iter()
2122            .filter(|d| d.deferred)
2123            .map(|d| d.name.as_str())
2124            .collect();
2125        assert_eq!(deferred, ["other"], "the MCP tool, not the built-in");
2126        // Deferring registers the three that reach it, and only then.
2127        let names: Vec<String> = registry.names();
2128        assert!(names.iter().any(|n| n == "tool_search"), "{names:?}");
2129
2130        // A wildcard over a source that has no tools is a filter with an empty set, not a typo.
2131        let mut bare = ToolRegistry::new(4096);
2132        bare.register(Arc::new(Echo), Policy::Allow);
2133        assert!(bare.defer(&["plugin:mcp:*".to_string()]).is_empty());
2134        assert!(
2135            !bare.names().iter().any(|n| n == "tool_search"),
2136            "nothing deferred, nothing registered to reach it"
2137        );
2138        // A name pattern that matches nothing is still a typo, wildcard or not, and says so.
2139        assert_eq!(bare.defer(&["nosuchtool".to_string()]), ["nosuchtool"]);
2140        assert_eq!(bare.defer(&["note_*".to_string()]), ["note_*"]);
2141        // A source filter over nothing is not: that is the shipped default on a box with no MCP.
2142        assert!(bare.defer(&["plugin:nowhere:*".to_string()]).is_empty());
2143    }
2144
2145    /// `#171`: a flare's read-only toolset is made by taking tools **out**, so `tool_call` cannot
2146    /// reach one that a policy merely marked disabled.
2147    #[test]
2148    fn without_takes_a_tool_out_of_the_registry_rather_than_hiding_it() {
2149        let mut registry = ToolRegistry::new(4096);
2150        registry.register(Arc::new(Echo), Policy::Allow);
2151        registry.register(Arc::new(Other), Policy::Allow);
2152        registry.defer(&["other".to_string()]);
2153
2154        let read_only = registry.without(&["other"]);
2155        assert_eq!(read_only.names(), vec!["echo".to_string()]);
2156        // The parent is untouched: this is a copy, not a mutation of what the lead runs with.
2157        assert!(
2158            registry.names().iter().any(|n| n == "other"),
2159            "the lead kept the tool the flare was not given"
2160        );
2161        // A name that is not there is not an error — the list is a rule, not a lookup.
2162        assert_eq!(read_only.without(&["nosuchtool"]).names().len(), 1);
2163    }
2164
2165    struct Other;
2166
2167    #[async_trait]
2168    impl Tool for Other {
2169        fn name(&self) -> &str {
2170            "other"
2171        }
2172        fn description(&self) -> &str {
2173            "the other one"
2174        }
2175        fn parameters(&self) -> Value {
2176            json!({
2177                "type": "object",
2178                "properties": {"text": {"type": "string", "description": "what to say"}},
2179                "required": ["text"],
2180                "additionalProperties": false
2181            })
2182        }
2183        async fn call(&self, _: Value) -> Result<String, ToolError> {
2184            Ok("other".into())
2185        }
2186    }
2187
2188    /// A name JSON Pointers need to escape.
2189    struct Slashed;
2190
2191    #[async_trait]
2192    impl Tool for Slashed {
2193        fn name(&self) -> &str {
2194            "a/b~c"
2195        }
2196        fn description(&self) -> &str {
2197            "escaped"
2198        }
2199        fn parameters(&self) -> Value {
2200            json!({"type": "object", "properties": {}})
2201        }
2202        async fn call(&self, _: Value) -> Result<String, ToolError> {
2203            Ok(String::new())
2204        }
2205    }
2206
2207    struct CountingApprover(AtomicUsize, bool);
2208
2209    #[async_trait]
2210    impl Approver for CountingApprover {
2211        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
2212            self.0.fetch_add(1, Ordering::SeqCst);
2213            if self.1 {
2214                crate::approvals::Decision::Allow
2215            } else {
2216                crate::approvals::Decision::Deny("no".to_string())
2217            }
2218        }
2219    }
2220
2221    fn registry(policy: Policy) -> ToolRegistry {
2222        let mut r = ToolRegistry::new(64);
2223        r.register(Arc::new(Echo), policy);
2224        r
2225    }
2226
2227    /// What the model actually reads. `dispatch` hands the whole output on (`#414`: the redaction
2228    /// hook has to see whole tokens), and the runtime applies the cap afterwards, so a test about
2229    /// the cap takes the same step instead of expecting it from `dispatch`.
2230    fn model_output(r: &ToolRegistry, out: ToolOutcome) -> String {
2231        truncate(out.output, r.max_output_bytes())
2232    }
2233
2234    /// A deliberately small JSON Schema checker for the keywords this project emits.
2235    ///
2236    /// Written by hand rather than pulling in a validator: the point is not to be general, it
2237    /// is to catch the failure that actually hurts — a typo'd keyword (`requried`,
2238    /// `descrition`) that every model server silently ignores, leaving a tool whose arguments
2239    /// are unconstrained. A closed vocabulary turns those into a failing test.
2240    const KEYWORDS: &[&str] = &[
2241        "$schema",
2242        "$id",
2243        "$ref",
2244        "$defs",
2245        "$comment",
2246        "title",
2247        "description",
2248        "type",
2249        "properties",
2250        "required",
2251        "additionalProperties",
2252        "items",
2253        "enum",
2254        "const",
2255        "default",
2256        "oneOf",
2257        "anyOf",
2258        "allOf",
2259        "not",
2260        "minLength",
2261        "maxLength",
2262        "pattern",
2263        "format",
2264        "minimum",
2265        "maximum",
2266        "minItems",
2267        "maxItems",
2268        "uniqueItems",
2269        "examples",
2270        "deprecated",
2271    ];
2272
2273    fn check_schema(node: &Value, path: &str, problems: &mut Vec<String>) {
2274        match node {
2275            Value::Object(map) => {
2276                for (k, v) in map {
2277                    if k == "properties" || k == "$defs" {
2278                        // A map of *user-chosen* names, each holding a schema: only the
2279                        // values are schemas, so do not judge the keys here.
2280                        if let Value::Object(props) = v {
2281                            for (name, sub) in props {
2282                                check_schema(sub, &format!("{path}.{k}.{name}"), problems);
2283                            }
2284                        } else {
2285                            problems.push(format!("{path}.{k} is not an object"));
2286                        }
2287                        continue;
2288                    }
2289                    if !KEYWORDS.contains(&k.as_str()) {
2290                        problems.push(format!("{path}: unknown keyword `{k}`"));
2291                    }
2292                    check_schema(v, &format!("{path}.{k}"), problems);
2293                }
2294                if let Some(Value::Array(req)) = map.get("required") {
2295                    if let Some(Value::Object(props)) = map.get("properties") {
2296                        for r in req {
2297                            if let Some(name) = r.as_str() {
2298                                if !props.contains_key(name) {
2299                                    problems.push(format!(
2300                                        "{path}: `required` names `{name}`, which is not in `properties`"
2301                                    ));
2302                                }
2303                            }
2304                        }
2305                    }
2306                }
2307            }
2308            Value::Array(items) => {
2309                for (i, v) in items.iter().enumerate() {
2310                    check_schema(v, &format!("{path}[{i}]"), problems);
2311                }
2312            }
2313            Value::String(_) if path.ends_with(".$ref") => {}
2314            _ => {}
2315        }
2316    }
2317
2318    /// Resolve every `$ref` in the document, then check the vocabulary of everything it points
2319    /// at. Fails with a readable list rather than one assertion.
2320    fn assert_schema_is_sound(doc: &Value, defs: &serde_json::Map<String, Value>) {
2321        let mut problems = Vec::new();
2322        check_schema(doc, "$", &mut problems);
2323        let mut refs = Vec::new();
2324        fn collect_refs(node: &Value, out: &mut Vec<String>) {
2325            match node {
2326                Value::Object(map) => {
2327                    for (k, v) in map {
2328                        if k == "$ref" {
2329                            if let Some(r) = v.as_str() {
2330                                out.push(r.to_string());
2331                            }
2332                        }
2333                        collect_refs(v, out);
2334                    }
2335                }
2336                Value::Array(a) => a.iter().for_each(|v| collect_refs(v, out)),
2337                _ => {}
2338            }
2339        }
2340        collect_refs(doc, &mut refs);
2341        assert!(!refs.is_empty(), "the document refers to $defs");
2342        for r in &refs {
2343            let target = r
2344                .strip_prefix("#/$defs/")
2345                .unwrap_or_else(|| panic!("a $ref must point into $defs: {r}"));
2346            // A JSON Pointer escapes `~` as `~0` and `/` as `~1`; the key in `$defs` is the
2347            // raw name.
2348            let key = target.replace("~1", "/").replace("~0", "~");
2349            if !defs.contains_key(&key) {
2350                problems.push(format!("$ref {r} does not resolve"));
2351            }
2352        }
2353        assert!(problems.is_empty(), "{problems:#?}");
2354    }
2355
2356    #[test]
2357    fn every_tool_describes_itself_in_one_place() {
2358        let r = registry(Policy::Allow);
2359        let d = r.descriptors();
2360        assert_eq!(d.len(), 1);
2361        assert_eq!(d[0].name, "echo");
2362        assert_eq!(d[0].policy, Policy::Allow);
2363        assert_eq!(d[0].source, ToolSource::Builtin);
2364        assert!(d[0].advertised);
2365        // The model request and the listing cannot drift apart.
2366        assert_eq!(r.specs()[0].function.parameters, d[0].parameters);
2367        assert_eq!(r.specs()[0].function.description, d[0].description);
2368    }
2369
2370    #[test]
2371    fn provenance_says_which_plugin_offered_a_tool() {
2372        let mut r = ToolRegistry::new(64);
2373        r.register(Arc::new(Echo), Policy::Ask);
2374        assert_eq!(r.descriptors()[0].source.label(), "builtin");
2375        let mut r = ToolRegistry::new(64);
2376        r.register_with_source(
2377            Arc::new(Echo),
2378            Policy::Ask,
2379            ToolSource::Plugin("memory-bank".into()),
2380        );
2381        assert_eq!(r.descriptors()[0].source.label(), "plugin:memory-bank");
2382        let json = serde_json::to_value(r.descriptors()).unwrap();
2383        assert_eq!(json[0]["source"], "plugin:memory-bank");
2384    }
2385
2386    #[test]
2387    fn the_schema_document_describes_every_advertised_tool_and_only_those_branches() {
2388        let mut r = ToolRegistry::new(64);
2389        r.register(Arc::new(Echo), Policy::Allow);
2390        r.register_with_source(Arc::new(Other), Policy::Deny, ToolSource::Builtin);
2391        let doc = r.schema_document();
2392        assert_eq!(
2393            doc["$schema"],
2394            "https://json-schema.org/draft/2020-12/schema"
2395        );
2396        assert_eq!(doc["$id"], TOOL_SCHEMA_ID);
2397
2398        let defs = doc["$defs"].as_object().expect("$defs is an object");
2399        assert!(defs.contains_key("echo") && defs.contains_key("other"));
2400        assert_schema_is_sound(&doc, defs);
2401
2402        // A denied tool exists in $defs (its schema is still worth validating against) but is
2403        // not something a client may call, so it is not a branch.
2404        let branches = doc["oneOf"].as_array().expect("oneOf is an array");
2405        assert_eq!(branches.len(), 1, "{branches:#?}");
2406        assert_eq!(branches[0]["properties"]["name"]["const"], "echo");
2407        assert_eq!(
2408            branches[0]["properties"]["arguments"]["$ref"],
2409            "#/$defs/echo"
2410        );
2411    }
2412
2413    #[test]
2414    fn a_real_argument_object_validates_against_its_own_branch() {
2415        let mut r = ToolRegistry::new(64);
2416        r.register_with_source(Arc::new(Other), Policy::Allow, ToolSource::Builtin);
2417        let doc = r.schema_document();
2418        let defs = doc["$defs"].as_object().unwrap();
2419        assert_schema_is_sound(&doc, defs);
2420
2421        // Follow the branch the way a client would: name -> const, arguments -> $defs.
2422        let branch = &doc["oneOf"][0];
2423        let name = branch["properties"]["name"]["const"].as_str().unwrap();
2424        assert_eq!(name, "other");
2425        let target = branch["properties"]["arguments"]["$ref"]
2426            .as_str()
2427            .unwrap()
2428            .strip_prefix("#/$defs/")
2429            .unwrap();
2430        let schema = &defs[target];
2431        let required: Vec<&str> = schema["required"]
2432            .as_array()
2433            .unwrap()
2434            .iter()
2435            .filter_map(|v| v.as_str())
2436            .collect();
2437        assert_eq!(required, ["text"]);
2438        let args = json!({"text": "hi"});
2439        for key in &required {
2440            assert!(args.get(*key).is_some(), "missing {key}");
2441            let want = schema["properties"][*key]["type"].as_str().unwrap();
2442            assert_eq!(
2443                want,
2444                match &args[*key] {
2445                    Value::String(_) => "string",
2446                    Value::Number(_) => "number",
2447                    _ => "other",
2448                }
2449            );
2450        }
2451    }
2452
2453    #[tokio::test]
2454    async fn a_disabled_tool_is_not_offered_and_cannot_be_called() {
2455        let mut r = registry(Policy::Allow);
2456        assert_eq!(r.advertised_names(), ["echo"]);
2457        assert!(r.disable(&["echo".into()]).is_empty());
2458        assert!(r.specs().is_empty(), "not offered to the model");
2459        assert!(r.advertised_names().is_empty());
2460        // Still registered, so the listing can say it exists and why it is off.
2461        assert_eq!(r.descriptors().len(), 1);
2462        assert!(!r.descriptors()[0].advertised);
2463        assert_eq!(r.names(), ["echo"]);
2464        // A call that names it is refused, and the refusal names the reason, not the policy.
2465        let out = r.dispatch("echo", "{\"text\":\"x\"}", &AllowAll).await;
2466        assert!(out.is_error);
2467        assert!(out.output.contains("`[tools] disabled`"), "{}", out.output);
2468    }
2469
2470    #[test]
2471    fn disabling_overrides_an_allow_policy_and_reports_names_that_match_nothing() {
2472        let mut r = ToolRegistry::new(64);
2473        r.register(Arc::new(Echo), Policy::Allow);
2474        let unknown = r.disable(&["echo".into(), "nosuchtool".into()]);
2475        assert_eq!(unknown, ["nosuchtool"], "a typo is reported, not ignored");
2476        assert!(r.specs().is_empty());
2477        // Deny and disabled are different states, and say so differently.
2478        let mut r = ToolRegistry::new(64);
2479        r.register(Arc::new(Echo), Policy::Deny);
2480        assert!(!r.descriptors()[0].advertised);
2481        assert!(r.descriptors()[0].source == ToolSource::Builtin);
2482    }
2483
2484    #[test]
2485    fn a_tool_name_with_pointer_characters_still_produces_a_resolving_ref() {
2486        let mut r = ToolRegistry::new(64);
2487        r.register_with_source(Arc::new(Slashed), Policy::Allow, ToolSource::Builtin);
2488        let doc = r.schema_document();
2489        let defs = doc["$defs"].as_object().unwrap();
2490        assert_schema_is_sound(&doc, defs);
2491    }
2492
2493    /// `#414`: `dispatch` hands the whole output on. The cap is the caller's, applied after the
2494    /// loop hooks, because redaction that sees a string already cut at `max_output_bytes` cannot
2495    /// recognise a token that ends there — the `sk-` rule wants twenty characters behind the
2496    /// prefix, so half a key matches nothing. Every built-in tool bounds its own read, which is
2497    /// why this only bites for a tool that does not (an MCP or plugin tool, which is unbounded).
2498    #[tokio::test]
2499    async fn dispatch_does_not_cap_the_output_the_hooks_will_see() {
2500        let mut r = ToolRegistry::new(8);
2501        r.register(Arc::new(Echo), Policy::Allow);
2502        let long = "x".repeat(64);
2503        let out = r
2504            .dispatch("echo", &json!({"text": long}).to_string(), &AllowAll)
2505            .await;
2506        assert_eq!(
2507            out.output.len(),
2508            64,
2509            "the cap belongs to the caller, after the hooks: {:?}",
2510            out.output
2511        );
2512        // And the cap itself still works, on a word boundary, when the caller applies it.
2513        let cut = truncate(format!("{} tail", "y".repeat(20)), 8);
2514        assert!(
2515            cut.starts_with("yyyyyyy") && cut.ends_with("[output truncated]"),
2516            "{cut:?}"
2517        );
2518        assert!(
2519            !cut.contains("tail"),
2520            "and the fragment past the cut is gone"
2521        );
2522    }
2523
2524    #[tokio::test]
2525    async fn dispatch_runs_allowed_tool() {
2526        let out = registry(Policy::Allow)
2527            .dispatch("echo", r#"{"text":"hi"}"#, &DenyAll)
2528            .await;
2529        assert_eq!(out, ToolOutcome::ok("hi".into()));
2530    }
2531
2532    #[tokio::test]
2533    async fn dispatch_reports_unknown_tool_bad_json_and_bad_args() {
2534        let r = registry(Policy::Allow);
2535        assert!(r.dispatch("nope", "{}", &AllowAll).await.is_error);
2536        let bad = r.dispatch("echo", "{oops", &AllowAll).await;
2537        assert!(bad.is_error && bad.output.contains("not valid JSON"));
2538        let missing = r.dispatch("echo", "", &AllowAll).await;
2539        assert!(missing.is_error && missing.output.contains("`text`"));
2540    }
2541
2542    #[tokio::test]
2543    async fn deny_policy_blocks_and_hides_tool() {
2544        let r = registry(Policy::Deny);
2545        assert!(r.specs().is_empty());
2546        let out = r.dispatch("echo", r#"{"text":"x"}"#, &AllowAll).await;
2547        assert!(out.is_error && out.output.contains("disabled"));
2548    }
2549
2550    #[tokio::test]
2551    async fn ask_policy_consults_approver() {
2552        let r = registry(Policy::Ask);
2553        let yes = CountingApprover(AtomicUsize::new(0), true);
2554        assert!(!r.dispatch("echo", r#"{"text":"x"}"#, &yes).await.is_error);
2555        assert_eq!(yes.0.load(Ordering::SeqCst), 1);
2556        let no = CountingApprover(AtomicUsize::new(0), false);
2557        let out = r.dispatch("echo", r#"{"text":"x"}"#, &no).await;
2558        assert!(out.is_error && out.output.contains("declined"));
2559        assert_eq!(r.specs().len(), 1);
2560    }
2561
2562    #[tokio::test]
2563    async fn allow_policy_does_not_prompt() {
2564        let a = CountingApprover(AtomicUsize::new(0), false);
2565        registry(Policy::Allow)
2566            .dispatch("echo", r#"{"text":"x"}"#, &a)
2567            .await;
2568        assert_eq!(a.0.load(Ordering::SeqCst), 0);
2569    }
2570
2571    #[tokio::test]
2572    async fn output_is_truncated_on_char_boundary() {
2573        let r = registry(Policy::Allow);
2574        let out = r
2575            .dispatch(
2576                "echo",
2577                &json!({"text": "é".repeat(100)}).to_string(),
2578                &AllowAll,
2579            )
2580            .await;
2581        let out = model_output(&r, out);
2582        assert!(out.ends_with("[output truncated]"), "{out:?}");
2583        assert!(out.len() < 100);
2584    }
2585
2586    fn builtin(dir: &Path, tweak: impl FnOnce(&mut ToolsConfig)) -> ToolRegistry {
2587        let mut cfg = ToolsConfig {
2588            read_file: Policy::Allow,
2589            write_file: Policy::Allow,
2590            shell: Policy::Allow,
2591            fetch: Policy::Deny,
2592            ..ToolsConfig::default()
2593        };
2594        tweak(&mut cfg);
2595        ToolRegistry::from_config(&cfg, dir.to_path_buf())
2596    }
2597
2598    #[tokio::test]
2599    async fn builtin_defaults_are_gated() {
2600        let dir = tempfile::tempdir().unwrap();
2601        let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2602        assert_eq!(
2603            r.names(),
2604            [
2605                "fetch",
2606                "patch",
2607                "read_file",
2608                "search_files",
2609                "shell",
2610                "write_file"
2611            ]
2612        );
2613        // `echo hi` runs; a command that cannot be undone is the one a front-end is asked about.
2614        let out = r
2615            .dispatch("shell", r#"{"command":"rm -rf everything"}"#, &DenyAll)
2616            .await;
2617        assert!(out.is_error && out.output.contains("declined"));
2618        let out = r
2619            .dispatch("shell", r#"{"command":"echo hi"}"#, &DenyAll)
2620            .await;
2621        assert!(!out.is_error, "ordinary work is not gated: {}", out.output);
2622        // The file tools are confined, not gated: a write inside the workspace happens without a
2623        // question, and one outside it is refused by the tool itself.
2624        let out = r
2625            .dispatch("write_file", r#"{"path":"a","content":"b"}"#, &DenyAll)
2626            .await;
2627        assert!(!out.is_error, "{}", out.output);
2628        assert!(dir.path().join("a").exists());
2629        let out = r
2630            .dispatch(
2631                "write_file",
2632                r#"{"path":"/tmp/escape","content":"b"}"#,
2633                &DenyAll,
2634            )
2635            .await;
2636        assert!(
2637            out.is_error && out.output.contains("outside the workspace"),
2638            "{}",
2639            out.output
2640        );
2641    }
2642
2643    /// `search_files` is a read of the tree the file tools already confine: offered, never asked
2644    /// about, and refused — by the tool, not a prompt — when the path leaves the workspace.
2645    #[tokio::test]
2646    async fn search_files_is_offered_unasked_and_fenced_by_the_workspace() {
2647        let dir = tempfile::tempdir().unwrap();
2648        std::fs::create_dir_all(dir.path().join("src")).unwrap();
2649        std::fs::write(dir.path().join("src/a.rs"), "let needle = 1;\n").unwrap();
2650        let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2651
2652        let listed = r
2653            .descriptors()
2654            .into_iter()
2655            .find(|d| d.name == "search_files")
2656            .expect("the tool is registered");
2657        assert_eq!(listed.policy, Policy::Allow);
2658        assert!(listed.advertised);
2659
2660        let out = r
2661            .dispatch("search_files", r#"{"pattern":"needle"}"#, &DenyAll)
2662            .await;
2663        assert!(!out.is_error, "{}", out.output);
2664        assert!(out.output.contains("a.rs:1"), "{}", out.output);
2665
2666        let out = r
2667            .dispatch(
2668                "search_files",
2669                r#"{"pattern":"needle","path":".."}"#,
2670                &DenyAll,
2671            )
2672            .await;
2673        assert!(
2674            out.is_error && out.output.contains("outside the workspace"),
2675            "{}",
2676            out.output
2677        );
2678    }
2679
2680    #[tokio::test]
2681    async fn file_tools_round_trip_and_confine() {
2682        let dir = tempfile::tempdir().unwrap();
2683        let r = builtin(dir.path(), |_| {});
2684        let w = r
2685            .dispatch(
2686                "write_file",
2687                r#"{"path":"sub/a.txt","content":"hello"}"#,
2688                &DenyAll,
2689            )
2690            .await;
2691        assert!(!w.is_error, "{}", w.output);
2692        let rd = r
2693            .dispatch("read_file", r#"{"path":"sub/a.txt"}"#, &DenyAll)
2694            .await;
2695        assert_eq!(rd.output, "hello");
2696        for bad in ["../escape.txt", "/etc/passwd", "sub/../../x"] {
2697            let out = r
2698                .dispatch("read_file", &json!({"path": bad}).to_string(), &DenyAll)
2699                .await;
2700            assert!(
2701                out.is_error && out.output.contains("outside"),
2702                "{bad}: {}",
2703                out.output
2704            );
2705        }
2706        let out = r
2707            .dispatch(
2708                "write_file",
2709                r#"{"path":"../escape.txt","content":"x"}"#,
2710                &DenyAll,
2711            )
2712            .await;
2713        assert!(out.is_error);
2714    }
2715
2716    #[cfg(unix)]
2717    #[tokio::test]
2718    async fn symlink_escape_is_blocked() {
2719        let dir = tempfile::tempdir().unwrap();
2720        let outside = tempfile::tempdir().unwrap();
2721        std::fs::write(outside.path().join("secret"), "s").unwrap();
2722        std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
2723        let r = builtin(dir.path(), |_| {});
2724        let out = r
2725            .dispatch("read_file", r#"{"path":"link/secret"}"#, &DenyAll)
2726            .await;
2727        assert!(out.is_error && out.output.contains("outside"));
2728    }
2729
2730    #[cfg(unix)]
2731    #[tokio::test]
2732    async fn dangling_symlink_cannot_be_written_through() {
2733        let dir = tempfile::tempdir().unwrap();
2734        let outside = tempfile::tempdir().unwrap();
2735        let target = outside.path().join("created");
2736        std::os::unix::fs::symlink(&target, dir.path().join("evil")).unwrap();
2737        let r = builtin(dir.path(), |_| {});
2738        let out = r
2739            .dispatch("write_file", r#"{"path":"evil","content":"x"}"#, &DenyAll)
2740            .await;
2741        assert!(out.is_error, "{}", out.output);
2742        assert!(!target.exists());
2743    }
2744
2745    #[tokio::test]
2746    async fn read_file_is_bounded_and_regular_files_only() {
2747        let dir = tempfile::tempdir().unwrap();
2748        std::fs::write(dir.path().join("big.txt"), "é".repeat(1000)).unwrap();
2749        std::fs::create_dir(dir.path().join("d")).unwrap();
2750        let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2751        let out = r
2752            .dispatch("read_file", r#"{"path":"big.txt"}"#, &DenyAll)
2753            .await;
2754        let shown = model_output(&r, out);
2755        assert!(shown.ends_with("[output truncated]"), "{shown:?}");
2756        assert!(shown.len() < 100);
2757        let out = r.dispatch("read_file", r#"{"path":"d"}"#, &DenyAll).await;
2758        assert!(out.is_error && out.output.contains("not a regular"));
2759    }
2760
2761    /// `#416`: `open(2)` on a FIFO with no writer blocks until somebody writes — and the "not a
2762    /// regular file" check ran *after* the open, so it was never reached. The call hung, so did the
2763    /// turn, and a blocking-pool thread went with it. A workspace-local FIFO is confined like any
2764    /// other path, which is why this is reachable at all.
2765    #[cfg(unix)]
2766    #[tokio::test]
2767    async fn a_fifo_is_refused_instead_of_hanging_the_turn() {
2768        let dir = tempfile::tempdir().unwrap();
2769        assert!(std::process::Command::new("mkfifo")
2770            .arg(dir.path().join("pipe"))
2771            .status()
2772            .map(|s| s.success())
2773            .unwrap_or(false));
2774        let r = builtin(dir.path(), |_| {});
2775        let out = tokio::time::timeout(
2776            std::time::Duration::from_secs(3),
2777            r.dispatch("read_file", r#"{"path":"pipe"}"#, &DenyAll),
2778        )
2779        .await
2780        .expect("a FIFO must not block the read");
2781        assert!(out.is_error, "{}", out.output);
2782        assert!(out.output.contains("not a regular"), "{}", out.output);
2783    }
2784
2785    /// The other half of `#416`: the cap is a byte count, so a cut can land inside a character —
2786    /// and a binary file used to come back as lossy garbage when it was over the cap while the same
2787    /// content under the cap was an error.
2788    #[tokio::test]
2789    async fn a_binary_file_is_not_text_at_any_size() {
2790        let dir = tempfile::tempdir().unwrap();
2791        let mut binary = vec![0u8; 200];
2792        binary[10] = 0xff;
2793        std::fs::write(dir.path().join("small.bin"), &binary[..50]).unwrap();
2794        std::fs::write(dir.path().join("big.bin"), &binary).unwrap();
2795        // A text file whose cut falls inside the `é` in the middle of it.
2796        std::fs::write(dir.path().join("text.txt"), "aaéé".repeat(40)).unwrap();
2797        let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2798
2799        let out = r
2800            .dispatch("read_file", r#"{"path":"small.bin"}"#, &DenyAll)
2801            .await;
2802        assert!(
2803            out.is_error,
2804            "an under-cap binary is not text: {}",
2805            out.output
2806        );
2807        let out = r
2808            .dispatch("read_file", r#"{"path":"big.bin"}"#, &DenyAll)
2809            .await;
2810        assert!(
2811            out.is_error,
2812            "an over-cap binary is not text either: {}",
2813            out.output
2814        );
2815        // The cut landing mid-character is this tool's own doing, and that one is text.
2816        let out = r
2817            .dispatch("read_file", r#"{"path":"text.txt"}"#, &DenyAll)
2818            .await;
2819        assert!(!out.is_error, "{}", out.output);
2820        assert!(out.output.starts_with("aaé"), "{}", out.output);
2821    }
2822
2823    #[cfg(unix)]
2824    #[tokio::test]
2825    async fn shell_output_is_capped_and_flooding_child_stops() {
2826        let dir = tempfile::tempdir().unwrap();
2827        let r = builtin(dir.path(), |c| {
2828            c.max_output_bytes = 256;
2829            c.shell_timeout_secs = 10;
2830        });
2831        let out = r.dispatch("shell", r#"{"command":"yes"}"#, &DenyAll).await;
2832        assert!(!out.is_error, "{}", out.output);
2833        let shown = model_output(&r, out);
2834        assert!(
2835            shown.contains("[truncated]") || shown.contains("[output truncated]"),
2836            "{shown:?}"
2837        );
2838        assert!(shown.len() < 300, "{} bytes", shown.len());
2839    }
2840
2841    /// `#368`: a drain ends at pipe EOF, which is when the *last* holder of the write end closes it
2842    /// — and a background process the command started inherits that end. `sleep 5 & echo started`
2843    /// returns in a millisecond and then held the turn for five seconds, because `wait` saw the
2844    /// child go and the drain did not.
2845    #[cfg(unix)]
2846    #[tokio::test]
2847    async fn a_background_child_does_not_hold_the_turn() {
2848        let dir = tempfile::tempdir().unwrap();
2849        let r = builtin(dir.path(), |c| {
2850            c.max_output_bytes = 4096;
2851            c.shell_timeout_secs = 30;
2852            // `#368` needs the state the issue names: no PID namespace, so a background process
2853            // really does inherit the pipe. Under `process` the namespace closes it for us.
2854            c.shell_isolate = crate::config::ShellIsolate::Off;
2855        });
2856        let asked = std::time::Instant::now();
2857        let out = tokio::time::timeout(
2858            std::time::Duration::from_secs(3),
2859            r.dispatch("shell", r#"{"command":"sleep 5 & echo started"}"#, &DenyAll),
2860        )
2861        .await
2862        .expect("a background child must not hold the call — `#368`");
2863        assert!(!out.is_error, "{}", out.output);
2864        assert!(
2865            out.output.contains("started"),
2866            "what the child itself printed: {}",
2867            out.output
2868        );
2869        assert!(
2870            out.output.contains("still holds its output pipe"),
2871            "the result says why it stopped reading: {}",
2872            out.output
2873        );
2874        assert!(asked.elapsed() < std::time::Duration::from_secs(3));
2875    }
2876
2877    #[cfg(unix)]
2878    fn process_alive(pid: i32) -> bool {
2879        // One read, not two probes. `kill(pid, 0)` followed by a read of `/proc/<pid>/stat` gave a
2880        // false "still alive" whenever the kernel reaped the zombie in between: the existence
2881        // check had already said yes, the state read then failed, and `unwrap_or(false)` said
2882        // "not a zombie". The state character on its own answers the question, and a process with
2883        // no `/proc` entry is gone.
2884        std::fs::read_to_string(format!("/proc/{pid}/stat"))
2885            .ok()
2886            .and_then(|s| {
2887                s.rsplit(')')
2888                    .next()
2889                    .map(|state| !state.trim_start().starts_with(['Z', 'X']))
2890            })
2891            .unwrap_or(false)
2892    }
2893
2894    #[cfg(unix)]
2895    async fn timeout_kills_grandchild(command: &str, grace: Duration) {
2896        let dir = tempfile::tempdir().unwrap();
2897        let mut r = ToolRegistry::new(4096);
2898        r.register(
2899            Arc::new(Shell {
2900                root: std::fs::canonicalize(dir.path()).unwrap(),
2901                skill_roots: Vec::new(),
2902                scripts_dir: None,
2903                timeout: Duration::from_secs(1),
2904                allowlist: Vec::new(),
2905                max_bytes: 4096,
2906                kill_grace: grace,
2907                sandbox: crate::sandbox::Sandbox::off(),
2908                ask: crate::config::ShellAsk::Dangerous,
2909            }),
2910            Policy::Allow,
2911        );
2912        let started = std::time::Instant::now();
2913        let out = r
2914            .dispatch("shell", &json!({"command": command}).to_string(), &DenyAll)
2915            .await;
2916        assert!(
2917            out.is_error && out.output.contains("timed out"),
2918            "{}",
2919            out.output
2920        );
2921        let pid: i32 = std::fs::read_to_string(dir.path().join("child.pid"))
2922            .unwrap()
2923            .trim()
2924            .parse()
2925            .unwrap();
2926        for _ in 0..100 {
2927            if !process_alive(pid) {
2928                break;
2929            }
2930            tokio::time::sleep(Duration::from_millis(50)).await;
2931        }
2932        // When this fails it is worth knowing what the process actually was: a `sleep` still in
2933        // the group means the signal never reached it, a zombie means the group died and nobody
2934        // reaped it, a different programme means the pid belonged to someone else.
2935        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default();
2936        assert!(
2937            !process_alive(pid),
2938            "grandchild {pid} survived the timeout after {:.2}s; stat = {stat:?}",
2939            started.elapsed().as_secs_f32()
2940        );
2941        assert!(started.elapsed() < Duration::from_secs(8));
2942    }
2943
2944    #[cfg(unix)]
2945    #[tokio::test]
2946    async fn timeout_terminates_background_grandchild() {
2947        timeout_kills_grandchild(
2948            "sleep 300 & echo $! > child.pid; wait",
2949            Duration::from_secs(2),
2950        )
2951        .await;
2952    }
2953
2954    #[cfg(unix)]
2955    #[tokio::test]
2956    async fn timeout_terminates_a_grandchild_that_left_the_process_group() {
2957        // `setsid` is the escape the group kill cannot see: the process is in a session of its own,
2958        // so `kill(-pgid)` misses it. The parent link survives, which is what the tree walk uses.
2959        timeout_kills_grandchild(
2960            "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait",
2961            Duration::from_secs(2),
2962        )
2963        .await;
2964    }
2965
2966    #[cfg(unix)]
2967    #[tokio::test]
2968    async fn a_cancelled_run_kills_a_grandchild_that_left_the_process_group() {
2969        // Dropping the future is what cancellation does to a run in flight, and `Guard` is the only
2970        // thing that stops a child then. It has no `.await`, so a `setsid` grandchild has to be
2971        // found synchronously — inside `Drop`.
2972        let dir = tempfile::tempdir().unwrap();
2973        let mut r = ToolRegistry::new(4096);
2974        r.register(
2975            Arc::new(Shell {
2976                root: std::fs::canonicalize(dir.path()).unwrap(),
2977                skill_roots: Vec::new(),
2978                scripts_dir: None,
2979                timeout: Duration::from_secs(30),
2980                allowlist: Vec::new(),
2981                max_bytes: 4096,
2982                kill_grace: Duration::from_secs(2),
2983                sandbox: crate::sandbox::Sandbox::off(),
2984                ask: crate::config::ShellAsk::Dangerous,
2985            }),
2986            Policy::Allow,
2987        );
2988        let registry = Arc::new(r);
2989        let call = {
2990            let registry = Arc::clone(&registry);
2991            let args = json!({
2992                "command": "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait"
2993            })
2994            .to_string();
2995            tokio::spawn(async move { registry.dispatch("shell", &args, &DenyAll).await })
2996        };
2997        // The grandchild has to exist before the future is dropped, or the test proves nothing.
2998        let pid = wait_for_pid(&dir.path().join("child.pid")).await;
2999        call.abort();
3000        let _ = call.await;
3001        for _ in 0..100 {
3002            if !process_alive(pid) {
3003                break;
3004            }
3005            tokio::time::sleep(Duration::from_millis(50)).await;
3006        }
3007        assert!(
3008            !process_alive(pid),
3009            "grandchild {pid} survived the drop: {:#?}",
3010            std::fs::read_to_string(format!("/proc/{pid}/stat"))
3011        );
3012    }
3013
3014    /// The pid the script wrote, once it is there: a `setsid` launch is not instant.
3015    #[cfg(unix)]
3016    async fn wait_for_pid(path: &std::path::Path) -> i32 {
3017        for _ in 0..100 {
3018            if let Ok(text) = std::fs::read_to_string(path) {
3019                if let Ok(pid) = text.trim().parse::<i32>() {
3020                    return pid;
3021                }
3022            }
3023            tokio::time::sleep(Duration::from_millis(20)).await;
3024        }
3025        panic!("the script never wrote {}", path.display());
3026    }
3027
3028    #[cfg(unix)]
3029    #[tokio::test]
3030    async fn timeout_escalates_to_sigkill_when_sigterm_is_ignored() {
3031        timeout_kills_grandchild(
3032            "trap '' TERM; sleep 300 & echo $! > child.pid; wait",
3033            Duration::from_millis(300),
3034        )
3035        .await;
3036    }
3037
3038    #[cfg(unix)]
3039    #[tokio::test]
3040    async fn shell_runs_in_workspace_with_timeout_and_allowlist() {
3041        let dir = tempfile::tempdir().unwrap();
3042        let r = builtin(dir.path(), |c| c.shell_timeout_secs = 1);
3043        let out = r
3044            .dispatch("shell", r#"{"command":"echo hi; pwd"}"#, &DenyAll)
3045            .await;
3046        assert!(!out.is_error);
3047        assert!(out.output.contains("exit code: 0") && out.output.contains("hi"));
3048        let slow = r
3049            .dispatch("shell", r#"{"command":"sleep 5"}"#, &DenyAll)
3050            .await;
3051        assert!(slow.is_error && slow.output.contains("timed out"));
3052
3053        let r = builtin(dir.path(), |c| c.shell_allowlist = vec!["echo".into()]);
3054        let ok = r
3055            .dispatch("shell", r#"{"command":"echo a b"}"#, &DenyAll)
3056            .await;
3057        assert!(ok.output.contains("a b"), "{}", ok.output);
3058        for bad in ["ls", "echo hi; ls", "echo $(ls)"] {
3059            let out = r
3060                .dispatch("shell", &json!({"command": bad}).to_string(), &DenyAll)
3061                .await;
3062            assert!(out.is_error, "{bad}");
3063        }
3064    }
3065
3066    #[cfg(unix)]
3067    fn shell_with_skills(workspace: &Path, skills: &Path) -> ToolRegistry {
3068        let cfg = ToolsConfig {
3069            shell: Policy::Allow,
3070            ..ToolsConfig::default()
3071        };
3072        let roots = vec![crate::skills::Root {
3073            source: crate::skills::Source::Shared,
3074            dir: skills.to_path_buf(),
3075        }];
3076        ToolRegistry::from_config_with(&cfg, workspace.to_path_buf(), roots)
3077    }
3078
3079    #[cfg(unix)]
3080    async fn shell_in(r: &ToolRegistry, command: &str, cwd: &str) -> ToolOutcome {
3081        r.dispatch(
3082            "shell",
3083            &json!({"command": command, "cwd": cwd}).to_string(),
3084            &DenyAll,
3085        )
3086        .await
3087    }
3088
3089    #[cfg(unix)]
3090    #[tokio::test]
3091    async fn shell_cwd_is_accepted_inside_the_workspace_and_refused_elsewhere() {
3092        let tmp = tempfile::tempdir().unwrap();
3093        let workspace = tmp.path().join("ws");
3094        std::fs::create_dir_all(workspace.join("sub")).unwrap();
3095        std::fs::write(workspace.join("file.txt"), "x").unwrap();
3096        let outside = tmp.path().join("outside");
3097        std::fs::create_dir_all(&outside).unwrap();
3098        std::os::unix::fs::symlink(&outside, workspace.join("link")).unwrap();
3099        let r = shell_with_skills(&workspace, &tmp.path().join("skills"));
3100
3101        let out = shell_in(&r, "pwd", "sub").await;
3102        assert!(!out.is_error, "{}", out.output);
3103        assert!(out.output.contains("/ws/sub"), "{}", out.output);
3104        let absolute = workspace.join("sub").display().to_string();
3105        assert!(!shell_in(&r, "pwd", &absolute).await.is_error);
3106
3107        for (cwd, why) in [
3108            ("/etc", "outside the workspace"),
3109            ("..", "outside the workspace"),
3110            ("link", "outside the workspace"),
3111            ("missing", "cannot be resolved"),
3112            ("file.txt", "not a directory"),
3113            ("  ", "empty"),
3114        ] {
3115            let out = shell_in(&r, "pwd", cwd).await;
3116            assert!(out.is_error, "{cwd:?} should be refused: {}", out.output);
3117            assert!(
3118                out.output.contains(&format!("cwd `{cwd}` refused")),
3119                "names what was refused: {}",
3120                out.output
3121            );
3122            assert!(out.output.contains(why), "{cwd:?}, {why}: {}", out.output);
3123        }
3124    }
3125
3126    #[cfg(unix)]
3127    #[tokio::test]
3128    async fn a_skills_own_script_runs_from_its_directory_but_a_broken_skills_does_not() {
3129        let tmp = tempfile::tempdir().unwrap();
3130        let workspace = tmp.path().join("ws");
3131        std::fs::create_dir_all(&workspace).unwrap();
3132        let skills = tmp.path().join("skills");
3133        let good = skills.join("backup");
3134        std::fs::create_dir_all(good.join("scripts")).unwrap();
3135        std::fs::write(
3136            good.join("SKILL.md"),
3137            "---\nname: backup\n---\nRun `bash scripts/backup.sh`.\n",
3138        )
3139        .unwrap();
3140        std::fs::write(
3141            good.join("scripts/backup.sh"),
3142            "echo backed up from $(basename \"$PWD\")\n",
3143        )
3144        .unwrap();
3145        let broken = skills.join("broken");
3146        std::fs::create_dir_all(&broken).unwrap();
3147        std::fs::write(
3148            broken.join("SKILL.md"),
3149            "---\ndescription: no name\n---\nbody\n",
3150        )
3151        .unwrap();
3152        let r = shell_with_skills(&workspace, &skills);
3153
3154        let out = shell_in(&r, "bash scripts/backup.sh", &good.display().to_string()).await;
3155        assert!(!out.is_error, "{}", out.output);
3156        assert!(
3157            out.output.contains("backed up from backup"),
3158            "{}",
3159            out.output
3160        );
3161        let nested = good.join("scripts").display().to_string();
3162        assert!(!shell_in(&r, "pwd", &nested).await.is_error);
3163
3164        let out = shell_in(&r, "pwd", &skills.display().to_string()).await;
3165        assert!(
3166            out.is_error,
3167            "the skills directory is not a skill's directory"
3168        );
3169        let out = shell_in(&r, "pwd", &broken.display().to_string()).await;
3170        assert!(out.is_error, "{}", out.output);
3171        assert!(
3172            out.output.contains("outside every skill's directory"),
3173            "{}",
3174            out.output
3175        );
3176    }
3177
3178    #[cfg(unix)]
3179    fn shell_with_scripts(workspace: &Path, scripts: &Path, allowlist: &[&str]) -> ToolRegistry {
3180        let cfg = ToolsConfig {
3181            shell: Policy::Allow,
3182            shell_allowlist: allowlist.iter().map(|s| s.to_string()).collect(),
3183            ..ToolsConfig::default()
3184        };
3185        ToolRegistry::from_config_full(
3186            &cfg,
3187            workspace.to_path_buf(),
3188            Vec::new(),
3189            Some(scripts.to_path_buf()),
3190        )
3191    }
3192
3193    #[cfg(unix)]
3194    #[tokio::test]
3195    async fn shell_finds_a_script_as_a_bare_command_and_is_told_where_the_scripts_are() {
3196        use std::os::unix::fs::PermissionsExt;
3197        let tmp = tempfile::tempdir().unwrap();
3198        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3199        std::fs::create_dir_all(&workspace).unwrap();
3200        std::fs::create_dir_all(&scripts).unwrap();
3201        let script = scripts.join("hello-script");
3202        std::fs::write(&script, "#!/bin/sh\necho hello from $1\n").unwrap();
3203        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3204        // `#427`: a script named after a real command must not run in its place. `write_file` is
3205        // `allow`, so before this the scripts directory was first on `PATH` and this `date` would
3206        // have answered every later `shell` call in the session.
3207        let imposter = scripts.join("date");
3208        std::fs::write(&imposter, "#!/bin/sh\necho fake date\n").unwrap();
3209        std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3210        let r = shell_with_scripts(&workspace, &scripts, &[]);
3211
3212        let out = r
3213            .dispatch(
3214                "shell",
3215                &json!({"command": "hello-script world; date; echo dir=$ECLIPSE_SCRIPTS_DIR; \
3216                    echo last=${PATH##*:}"})
3217                .to_string(),
3218                &DenyAll,
3219            )
3220            .await;
3221        assert!(!out.is_error, "{}", out.output);
3222        let dir = scripts.display().to_string();
3223        assert!(out.output.contains("hello from world"), "{}", out.output);
3224        assert!(out.output.contains(&format!("dir={dir}")), "{}", out.output);
3225        assert!(
3226            out.output.contains(&format!("last={dir}")),
3227            "the scripts directory is on PATH, last: {}",
3228            out.output
3229        );
3230        assert!(
3231            !out.output.contains("fake date"),
3232            "a real command wins over a script of the same name: {}",
3233            out.output
3234        );
3235    }
3236
3237    #[cfg(unix)]
3238    #[tokio::test]
3239    async fn an_allowlisted_shell_does_not_let_a_script_take_the_place_of_a_program() {
3240        use std::os::unix::fs::PermissionsExt;
3241        let tmp = tempfile::tempdir().unwrap();
3242        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3243        std::fs::create_dir_all(&workspace).unwrap();
3244        std::fs::create_dir_all(&scripts).unwrap();
3245        let imposter = scripts.join("echo");
3246        std::fs::write(&imposter, "#!/bin/sh\necho imposter\n").unwrap();
3247        std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3248        let r = shell_with_scripts(&workspace, &scripts, &["echo", "env"]);
3249
3250        let out = r
3251            .dispatch("shell", r#"{"command":"echo real"}"#, &DenyAll)
3252            .await;
3253        assert!(
3254            out.output.contains("real") && !out.output.contains("imposter"),
3255            "{}",
3256            out.output
3257        );
3258        let out = r.dispatch("shell", r#"{"command":"env"}"#, &DenyAll).await;
3259        assert!(
3260            out.output
3261                .contains(&format!("ECLIPSE_SCRIPTS_DIR={}", scripts.display())),
3262            "{}",
3263            out.output
3264        );
3265    }
3266
3267    #[cfg(unix)]
3268    #[tokio::test]
3269    async fn shell_cwd_accepts_the_scripts_directory_and_the_refusal_names_it() {
3270        let tmp = tempfile::tempdir().unwrap();
3271        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3272        std::fs::create_dir_all(&workspace).unwrap();
3273        std::fs::create_dir_all(&scripts).unwrap();
3274        let r = shell_with_scripts(&workspace, &scripts, &[]);
3275
3276        let out = shell_in(&r, "pwd", &scripts.display().to_string()).await;
3277        assert!(!out.is_error, "{}", out.output);
3278        assert!(out.output.contains("/scripts"), "{}", out.output);
3279
3280        let out = shell_in(&r, "pwd", "/etc").await;
3281        assert!(
3282            out.is_error
3283                && out.output.contains("outside the workspace")
3284                && out.output.contains("outside the scripts directory")
3285                && out.output.contains("outside every skill's directory"),
3286            "{}",
3287            out.output
3288        );
3289    }
3290
3291    fn writer(workspace: &Path, scripts: &Path) -> ToolRegistry {
3292        let cfg = ToolsConfig {
3293            write_file: Policy::Allow,
3294            ..ToolsConfig::default()
3295        };
3296        ToolRegistry::from_config_full(
3297            &cfg,
3298            workspace.to_path_buf(),
3299            Vec::new(),
3300            Some(scripts.to_path_buf()),
3301        )
3302    }
3303
3304    async fn write_to(r: &ToolRegistry, path: &str) -> ToolOutcome {
3305        r.dispatch(
3306            "write_file",
3307            &json!({"path": path, "content": "#!/bin/sh\n"}).to_string(),
3308            &DenyAll,
3309        )
3310        .await
3311    }
3312
3313    #[tokio::test]
3314    async fn write_file_writes_in_the_scripts_directory_even_before_it_exists() {
3315        let tmp = tempfile::tempdir().unwrap();
3316        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("cfg/scripts"));
3317        std::fs::create_dir_all(&workspace).unwrap();
3318        let r = writer(&workspace, &scripts);
3319
3320        let target = scripts.join("backup.sh");
3321        let out = write_to(&r, &target.display().to_string()).await;
3322        assert!(!out.is_error, "{}", out.output);
3323        assert_eq!(std::fs::read_to_string(&target).unwrap(), "#!/bin/sh\n");
3324
3325        let out = write_to(&r, &format!("{}/sub/../again.sh", scripts.display())).await;
3326        assert!(!out.is_error, "{}", out.output);
3327        assert!(scripts.join("again.sh").is_file());
3328    }
3329
3330    #[tokio::test]
3331    async fn write_file_still_writes_in_the_workspace_when_scripts_are_configured() {
3332        let tmp = tempfile::tempdir().unwrap();
3333        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3334        std::fs::create_dir_all(&workspace).unwrap();
3335        let r = writer(&workspace, &scripts);
3336        let out = write_to(&r, "notes/a.txt").await;
3337        assert!(!out.is_error, "{}", out.output);
3338        assert!(workspace.join("notes/a.txt").is_file());
3339        assert!(!scripts.exists(), "a workspace write must not create it");
3340    }
3341
3342    /// The expensive mistake this guards against: the model rewrites a 50 KB file to change two
3343    /// lines, and the whole file becomes part of every request from then on. Past the guard it has
3344    /// to say `force`, and the refusal tells it the cheaper way.
3345    #[tokio::test]
3346    async fn a_big_file_is_not_clobbered_by_accident() {
3347        let dir = tempfile::tempdir().unwrap();
3348        let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(100);
3349
3350        let big = dir.path().join("index.html");
3351        std::fs::write(&big, "x".repeat(500)).unwrap();
3352
3353        let refused = tool
3354            .call(json!({"path": "index.html", "content": "tiny"}))
3355            .await
3356            .unwrap_err()
3357            .to_string();
3358        assert!(refused.contains("already exists at 500 bytes"), "{refused}");
3359        assert!(
3360            refused.contains("`patch`"),
3361            "it names the cheap path: {refused}"
3362        );
3363        assert!(
3364            refused.contains("force: true"),
3365            "and how to mean it: {refused}"
3366        );
3367        assert_eq!(
3368            std::fs::read_to_string(&big).unwrap().len(),
3369            500,
3370            "nothing was written"
3371        );
3372
3373        // Saying force writes it.
3374        tool.call(json!({"path": "index.html", "content": "tiny", "force": true}))
3375            .await
3376            .unwrap();
3377        assert_eq!(std::fs::read_to_string(&big).unwrap(), "tiny");
3378
3379        // Below the guard, a rewrite is just a write.
3380        let small = dir.path().join("notes.md");
3381        tool.call(json!({"path": "notes.md", "content": "one"}))
3382            .await
3383            .unwrap();
3384        tool.call(json!({"path": "notes.md", "content": "two"}))
3385            .await
3386            .unwrap();
3387        assert_eq!(std::fs::read_to_string(&small).unwrap(), "two");
3388
3389        // A fresh file of any size is a creation, not a clobber.
3390        tool.call(json!({"path": "fresh.html", "content": "y".repeat(400)}))
3391            .await
3392            .unwrap();
3393        assert!(dir.path().join("fresh.html").exists());
3394
3395        // 0 leaves the tool unguarded, for a profile that wants the old behaviour.
3396        let loose = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(0);
3397        loose
3398            .call(json!({"path": "index.html", "content": "free"}))
3399            .await
3400            .unwrap();
3401        assert_eq!(std::fs::read_to_string(&big).unwrap(), "free");
3402    }
3403
3404    /// The threshold is "at least", not "larger than": the boundary is the one part of a
3405    /// documented limit anyone will ever test, so it is pinned here rather than left to prose.
3406    #[tokio::test]
3407    async fn the_guard_refuses_at_the_threshold_not_only_above_it() {
3408        let dir = tempfile::tempdir().unwrap();
3409        let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(64);
3410
3411        // Exactly the threshold: refused.
3412        std::fs::write(dir.path().join("exact.txt"), "x".repeat(64)).unwrap();
3413        let refused = tool
3414            .call(json!({"path": "exact.txt", "content": "y"}))
3415            .await
3416            .unwrap_err()
3417            .to_string();
3418        assert!(refused.contains("already exists at 64 bytes"), "{refused}");
3419        assert_eq!(
3420            std::fs::read_to_string(dir.path().join("exact.txt"))
3421                .unwrap()
3422                .len(),
3423            64,
3424            "nothing was written"
3425        );
3426
3427        // One byte under: an ordinary rewrite.
3428        std::fs::write(dir.path().join("under.txt"), "x".repeat(63)).unwrap();
3429        tool.call(json!({"path": "under.txt", "content": "y"}))
3430            .await
3431            .unwrap();
3432        assert_eq!(
3433            std::fs::read_to_string(dir.path().join("under.txt")).unwrap(),
3434            "y"
3435        );
3436    }
3437
3438    #[cfg(unix)]
3439    #[tokio::test]
3440    async fn write_file_refuses_everywhere_else_and_names_both_roots() {
3441        let tmp = tempfile::tempdir().unwrap();
3442        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3443        let elsewhere = tmp.path().join("elsewhere");
3444        std::fs::create_dir_all(&workspace).unwrap();
3445        std::fs::create_dir_all(&scripts).unwrap();
3446        std::fs::create_dir_all(&elsewhere).unwrap();
3447        std::os::unix::fs::symlink(&elsewhere, scripts.join("link")).unwrap();
3448        let r = writer(&workspace, &scripts);
3449
3450        let sibling = format!("{}-other/x.sh", scripts.display());
3451        for requested in [
3452            "/etc/eclipse-test".to_string(),
3453            elsewhere.join("x.sh").display().to_string(),
3454            format!("{}/../escape.sh", scripts.display()),
3455            format!("{}/link/x.sh", scripts.display()),
3456            sibling,
3457        ] {
3458            let out = write_to(&r, &requested).await;
3459            assert!(out.is_error, "{requested} should be refused");
3460            assert!(
3461                out.output.contains(&workspace.display().to_string())
3462                    && out.output.contains(&scripts.display().to_string()),
3463                "{requested}: {}",
3464                out.output
3465            );
3466        }
3467        assert!(!elsewhere.join("x.sh").exists());
3468        assert!(!tmp.path().join("escape.sh").exists());
3469    }
3470
3471    #[test]
3472    fn the_approval_line_for_write_file_says_when_the_destination_is_the_scripts_directory() {
3473        let tmp = tempfile::tempdir().unwrap();
3474        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3475        let tool = WriteFile::new(workspace, Some(scripts.clone()));
3476        let line = tool.describe_call(
3477            &json!({"path": scripts.join("a.sh").display().to_string(), "content": "x"}),
3478        );
3479        assert!(line.ends_with("(scripts directory)"), "{line}");
3480        let line = tool.describe_call(&json!({"path": "a.txt", "content": "x"}));
3481        assert!(!line.contains("scripts"), "{line}");
3482    }
3483
3484    #[cfg(unix)]
3485    #[tokio::test]
3486    async fn shell_without_a_cwd_still_runs_in_the_workspace_root() {
3487        let tmp = tempfile::tempdir().unwrap();
3488        let r = shell_with_skills(tmp.path(), &tmp.path().join("skills"));
3489        let out = r.dispatch("shell", r#"{"command":"pwd"}"#, &DenyAll).await;
3490        let root = std::fs::canonicalize(tmp.path()).unwrap();
3491        assert!(
3492            out.output.contains(&root.display().to_string()),
3493            "{}",
3494            out.output
3495        );
3496        let out = r
3497            .dispatch("shell", r#"{"command":"pwd","cwd":7}"#, &DenyAll)
3498            .await;
3499        assert!(
3500            out.is_error && out.output.contains("`cwd` must be a string"),
3501            "{}",
3502            out.output
3503        );
3504    }
3505
3506    #[tokio::test]
3507    async fn fetch_rejects_non_http_schemes() {
3508        let dir = tempfile::tempdir().unwrap();
3509        let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3510        let out = r
3511            .dispatch("fetch", r#"{"url":"file:///etc/passwd"}"#, &DenyAll)
3512            .await;
3513        assert!(out.is_error && out.output.contains("http"));
3514    }
3515
3516    #[tokio::test]
3517    async fn fetch_blocks_internal_targets_before_connecting() {
3518        // A listener that must never be contacted.
3519        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3520        let port = listener.local_addr().unwrap().port();
3521        let dir = tempfile::tempdir().unwrap();
3522        let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3523        for url in [
3524            format!("http://127.0.0.1:{port}/"),
3525            format!("http://localhost:{port}/"),
3526            format!("http://svc.localhost:{port}/"),
3527            format!("http://[::1]:{port}/"),
3528            format!("http://[::ffff:127.0.0.1]:{port}/"),
3529            format!("http://2130706433:{port}/"),
3530            "http://169.254.169.254/latest/meta-data/".to_string(),
3531            "http://8.8.8.8/".to_string(),
3532        ] {
3533            let out = r
3534                .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3535                .await;
3536            assert!(
3537                out.is_error && out.output.contains("blocked"),
3538                "{url}: {}",
3539                out.output
3540            );
3541        }
3542        let accepted = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;
3543        assert!(accepted.is_err(), "blocked fetch connected anyway");
3544    }
3545
3546    #[tokio::test]
3547    async fn fetch_does_not_follow_redirects() {
3548        use tokio::io::{AsyncReadExt, AsyncWriteExt};
3549        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3550        let url = format!("http://{}/", listener.local_addr().unwrap());
3551        let server = tokio::spawn(async move {
3552            let (mut s, _) = listener.accept().await.unwrap();
3553            let mut buf = [0u8; 1024];
3554            let _ = s.read(&mut buf).await;
3555            s.write_all(
3556                b"HTTP/1.1 302 Found\r\nlocation: http://127.0.0.1:9/elsewhere\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
3557            )
3558            .await
3559            .unwrap();
3560        });
3561        let mut r = ToolRegistry::new(4096);
3562        r.register(
3563            Arc::new(Fetch {
3564                allow_internal: true,
3565                ..Fetch::new(Duration::from_secs(5), 4096)
3566            }),
3567            Policy::Allow,
3568        );
3569        let out = r
3570            .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3571            .await;
3572        server.await.unwrap();
3573        assert!(!out.is_error, "{}", out.output);
3574        assert!(
3575            out.output.contains("302")
3576                && out
3577                    .output
3578                    .contains("location: http://127.0.0.1:9/elsewhere")
3579        );
3580    }
3581
3582    /// Serves one response with the given headers/body and fetches it through the tool.
3583    async fn fetch_from_mock(
3584        headers: &'static str,
3585        body: &'static str,
3586        html: FetchHtml,
3587        args: Value,
3588    ) -> ToolOutcome {
3589        use tokio::io::{AsyncReadExt, AsyncWriteExt};
3590        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3591        let url = format!("http://{}/", listener.local_addr().unwrap());
3592        let server = tokio::spawn(async move {
3593            let (mut s, _) = listener.accept().await.unwrap();
3594            let mut buf = [0u8; 1024];
3595            let _ = s.read(&mut buf).await;
3596            let resp = format!(
3597                "HTTP/1.1 200 OK\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
3598                body.len()
3599            );
3600            s.write_all(resp.as_bytes()).await.unwrap();
3601        });
3602        let mut r = ToolRegistry::new(4096);
3603        r.register(
3604            Arc::new(
3605                Fetch {
3606                    allow_internal: true,
3607                    ..Fetch::new(Duration::from_secs(5), 4096)
3608                }
3609                .with_html(html),
3610            ),
3611            Policy::Allow,
3612        );
3613        let mut args = args;
3614        args["url"] = json!(url);
3615        let out = r.dispatch("fetch", &args.to_string(), &DenyAll).await;
3616        server.await.unwrap();
3617        out
3618    }
3619
3620    const PAGE: &str = "<!doctype html><html><head><title>T</title><script>evil()</script></head>\
3621        <body><h1>Hello</h1><p>one &amp; two</p></body></html>";
3622
3623    #[tokio::test]
3624    async fn fetch_converts_html_to_text_by_default() {
3625        let out = fetch_from_mock(
3626            "content-type: text/html; charset=utf-8\r\n",
3627            PAGE,
3628            FetchHtml::Text,
3629            json!({}),
3630        )
3631        .await;
3632        assert!(!out.is_error, "{}", out.output);
3633        assert!(out.output.starts_with("status: 200 OK\n"), "{}", out.output);
3634        assert!(
3635            out.output.contains("note: HTML converted"),
3636            "{}",
3637            out.output
3638        );
3639        assert!(
3640            out.output.ends_with("T\n\nHello\n\none & two"),
3641            "{}",
3642            out.output
3643        );
3644        assert!(!out.output.contains("<p>") && !out.output.contains("evil"));
3645
3646        // Also when the server sends no useful content type.
3647        let out = fetch_from_mock("", PAGE, FetchHtml::Text, json!({})).await;
3648        assert!(out.output.contains("Hello") && !out.output.contains("<h1>"));
3649    }
3650
3651    #[tokio::test]
3652    async fn fetch_can_return_raw_html_per_call_or_by_config() {
3653        let ct = "content-type: text/html\r\n";
3654        let out = fetch_from_mock(ct, PAGE, FetchHtml::Text, json!({"raw": true})).await;
3655        assert!(out.output.contains("<h1>Hello</h1>") && !out.output.contains("note: HTML"));
3656        let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({})).await;
3657        assert!(
3658            out.output.contains("<script>evil()</script>"),
3659            "{}",
3660            out.output
3661        );
3662        let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({"raw": false})).await;
3663        assert!(out.output.contains("note: HTML converted") && !out.output.contains("<h1>"));
3664    }
3665
3666    #[tokio::test]
3667    async fn fetch_leaves_non_html_bodies_alone() {
3668        let out = fetch_from_mock(
3669            "content-type: application/json\r\n",
3670            r#"{"html":"<p>x</p>"}"#,
3671            FetchHtml::Text,
3672            json!({}),
3673        )
3674        .await;
3675        assert!(
3676            out.output.ends_with(r#"{"html":"<p>x</p>"}"#),
3677            "{}",
3678            out.output
3679        );
3680        assert!(!out.output.contains("note:"));
3681    }
3682
3683    /// Whether bubblewrap is on this box. The tests below are the *behaviour* of isolation, so
3684    /// they mean nothing without the mechanism; a box without it skips them and the argv tests in
3685    /// `sandbox` still cover the shape.
3686    #[cfg(unix)]
3687    fn bwrap_present() -> bool {
3688        std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
3689            .any(|d| d.join("bwrap").is_file())
3690    }
3691
3692    /// A process whose command line contains `marker`, by way of `pgrep -f`.
3693    #[cfg(unix)]
3694    fn any_process(marker: &str) -> bool {
3695        std::process::Command::new("pgrep")
3696            .arg("-f")
3697            .arg(marker)
3698            .status()
3699            .map(|s| s.success())
3700            .unwrap_or(false)
3701    }
3702
3703    #[cfg(unix)]
3704    #[tokio::test]
3705    async fn isolation_stops_a_daemon_that_leaves_the_process_group() {
3706        if !bwrap_present() {
3707            return;
3708        }
3709        let dir = tempfile::tempdir().unwrap();
3710        let r = builtin(dir.path(), |c| c.shell_isolate = ShellIsolate::Process);
3711        let marker = "sleep 297.41";
3712        let started =
3713            json!({ "command": format!("setsid {marker} >/dev/null 2>&1 & echo ok") }).to_string();
3714        let out = r.dispatch("shell", &started, &DenyAll).await;
3715        assert!(!out.is_error, "{}", out.output);
3716        tokio::time::sleep(Duration::from_millis(500)).await;
3717        assert!(!any_process(marker), "a daemon outlived the run");
3718        // The run says so, rather than letting someone wonder where their server went.
3719        assert!(out.output.contains("shell_isolate"), "{}", out.output);
3720    }
3721
3722    #[cfg(unix)]
3723    #[tokio::test]
3724    async fn fs_mode_writes_inside_the_workspace_and_nowhere_else() {
3725        if !bwrap_present() {
3726            return;
3727        }
3728        let dir = tempfile::tempdir().unwrap();
3729        let r = builtin(dir.path(), |c| {
3730            c.shell_isolate = ShellIsolate::Fs;
3731            // This test is about mounts, not about the default hide list, which may well cover
3732            // the directory `tempfile` chose.
3733            c.shell_isolate_hide = Vec::new();
3734        });
3735        let command = "touch made-here && echo inside=$(test -f made-here && echo ok) \
3736                       etc=$(test -w /etc && echo writable || echo read-only) \
3737                       tmp=$(touch /tmp/x && echo writable || echo read-only)";
3738        let args = json!({ "command": command }).to_string();
3739        let out = r.dispatch("shell", &args, &DenyAll).await;
3740        assert!(!out.is_error, "{}", out.output);
3741        assert!(
3742            dir.path().join("made-here").exists(),
3743            "workspace write was lost"
3744        );
3745        assert!(out.output.contains("inside=ok"), "{}", out.output);
3746        assert!(out.output.contains("etc=read-only"), "{}", out.output);
3747        assert!(out.output.contains("tmp=writable"), "{}", out.output);
3748    }
3749
3750    #[cfg(unix)]
3751    #[tokio::test]
3752    async fn fs_mode_hides_a_path_even_inside_the_workspace() {
3753        if !bwrap_present() {
3754            return;
3755        }
3756        let dir = tempfile::tempdir().unwrap();
3757        std::fs::create_dir(dir.path().join("secret")).unwrap();
3758        std::fs::write(dir.path().join("secret/key"), "TOPSECRET").unwrap();
3759        let secret = dir.path().join("secret");
3760        let r = builtin(dir.path(), move |c| {
3761            c.shell_isolate = ShellIsolate::Fs;
3762            c.shell_isolate_hide = vec![secret];
3763        });
3764        let args = json!({ "command": "ls -A secret | wc -l" }).to_string();
3765        let out = r.dispatch("shell", &args, &DenyAll).await;
3766        assert!(!out.is_error, "{}", out.output);
3767        // `ls -A` of an emptied directory prints nothing, so the count is a bare `0`.
3768        assert!(out.output.contains("\n0\n"), "{}", out.output);
3769    }
3770
3771    #[cfg(unix)]
3772    #[tokio::test]
3773    async fn a_hide_that_would_erase_the_workspace_is_skipped_and_said_so() {
3774        if !bwrap_present() {
3775            return;
3776        }
3777        let dir = tempfile::tempdir().unwrap();
3778        // A workspace living inside something a profile hid: emptying the parent would delete
3779        // the run's own directory, so the hide is dropped — and named, rather than believed.
3780        let parent = dir.path().parent().unwrap().to_path_buf();
3781        let r = builtin(dir.path(), move |c| {
3782            c.shell_isolate = ShellIsolate::Fs;
3783            c.shell_isolate_hide = vec![parent];
3784        });
3785        let args = json!({ "command": "touch kept && ls -A | wc -l" }).to_string();
3786        let out = r.dispatch("shell", &args, &DenyAll).await;
3787        assert!(!out.is_error, "{}", out.output);
3788        assert!(
3789            dir.path().join("kept").exists(),
3790            "the workspace was erased: {}",
3791            out.output
3792        );
3793    }
3794
3795    #[test]
3796    fn specs_use_openai_function_format() {
3797        let v = serde_json::to_value(registry(Policy::Allow).specs()).unwrap();
3798        assert_eq!(v[0]["type"], "function");
3799        assert_eq!(v[0]["function"]["name"], "echo");
3800    }
3801
3802    /// `#374`: `patch` and `skill_manage` write beside the file and rename over it, and the rename
3803    /// brought the temp file's default mode with it — an executable script came back `0644`, so
3804    /// `./run.sh` and anything on the scripts `PATH` stopped running while the edit said success.
3805    #[cfg(unix)]
3806    #[test]
3807    fn replacing_a_file_keeps_its_mode() {
3808        use std::os::unix::fs::PermissionsExt;
3809        let dir = tempfile::tempdir().unwrap();
3810        let path = dir.path().join("run.sh");
3811        std::fs::write(&path, "#!/bin/sh\necho one\n").unwrap();
3812        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
3813
3814        replace_file(&path, "#!/bin/sh\necho two\n").expect("the edit lands");
3815
3816        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3817        assert_eq!(mode, 0o755, "an executable stays executable");
3818        assert_eq!(
3819            std::fs::read_to_string(&path).unwrap(),
3820            "#!/bin/sh\necho two\n"
3821        );
3822    }
3823
3824    /// The other half of `#374`: editing through a symlink used to replace the *link* with a regular
3825    /// file, leaving the real file untouched — the opposite of what "patch this path" means.
3826    #[cfg(unix)]
3827    #[test]
3828    fn replacing_through_a_symlink_edits_the_target_and_keeps_the_link() {
3829        let dir = tempfile::tempdir().unwrap();
3830        let real = dir.path().join("real.sh");
3831        let link = dir.path().join("link.sh");
3832        std::fs::write(&real, "old\n").unwrap();
3833        std::os::unix::fs::symlink(&real, &link).unwrap();
3834
3835        replace_file(&link, "new\n").expect("the edit lands");
3836
3837        let meta = std::fs::symlink_metadata(&link).unwrap();
3838        assert!(
3839            meta.file_type().is_symlink(),
3840            "the link is still a link, not a copy of the file"
3841        );
3842        assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n");
3843    }
3844}