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