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 first 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 first on `PATH` (unless a shell allowlist is set) \
1731and named in `ECLIPSE_SCRIPTS_DIR`, so a script there runs as a bare command."
1732    }
1733    fn parameters(&self) -> Value {
1734        json!({
1735            "type": "object",
1736            "properties": {
1737                "command": {"type": "string"},
1738                "cwd": {
1739                    "type": "string",
1740                    "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."
1741                }
1742            },
1743            "required": ["command"]
1744        })
1745    }
1746    fn describe_call(&self, args: &Value) -> String {
1747        let command = args["command"].as_str().unwrap_or("?");
1748        match args["cwd"].as_str() {
1749            Some(cwd) => format!("run `{command}` in {cwd}"),
1750            None => format!("run `{command}`"),
1751        }
1752    }
1753    async fn call(&self, args: Value) -> Result<String, ToolError> {
1754        let command = str_arg(&args, "command")?;
1755        let cwd = match args.get("cwd") {
1756            None | Some(Value::Null) => None,
1757            Some(Value::String(s)) => Some(s.as_str()),
1758            Some(_) => return Err(ToolError::InvalidArgs("`cwd` must be a string".into())),
1759        };
1760        let dir = self.working_dir(cwd)?;
1761        let mut cmd = self.build_command(command, &dir)?;
1762        // The outer process needs a directory too: bubblewrap inherits it and then lands in the
1763        // one it was told to `--chdir` to.
1764        cmd.current_dir(&dir);
1765        let out = run_to_completion(cmd, self.timeout, self.max_bytes, self.kill_grace).await?;
1766        Ok(self.afterwards(command, out))
1767    }
1768}
1769
1770/// Start `cmd` with no stdin and piped output, in its own process group, and wait for it.
1771///
1772/// This is what `shell` and `script` have in common, so they keep the same guarantees by
1773/// being the same code: the run is bounded by `timeout`, a timeout stops the whole process
1774/// group (a background child cannot keep the run alive) and is reported as a timeout, output
1775/// is read up to `max_bytes` per stream and a flooding child is cut off, dropping the
1776/// future kills the group, and a child that exits is not waited on beyond a short grace even
1777/// when what it started still holds the output pipe (`DRAIN_GRACE`, `#368`).
1778/// Start a child built on demand, trying again when the kernel refuses the file for a moment.
1779///
1780/// `ETXTBSY` ("Text file busy") does not mean the file is wrong: it means someone still holds it
1781/// open for writing. In a program that writes a script and then runs it, the holder is usually a
1782/// child forked by another thread — the descriptor is inherited until that child execs. The
1783/// window is microseconds, so a fresh attempt is the right answer, not an error the person has to
1784/// interpret and work around.
1785pub(crate) async fn start_retrying<F>(mut build: F, max_bytes: usize) -> Result<Running, ToolError>
1786where
1787    F: FnMut() -> tokio::process::Command,
1788{
1789    let mut attempt = 0u32;
1790    loop {
1791        match start(build(), max_bytes) {
1792            Ok(running) => return Ok(running),
1793            Err(e) if attempt < 4 && is_text_busy(&e) => {
1794                attempt += 1;
1795                tokio::time::sleep(Duration::from_millis(1 << attempt)).await;
1796            }
1797            Err(e) => return Err(ToolError::Failed(crate::tools_script::start_error(&e))),
1798        }
1799    }
1800}
1801
1802#[cfg(unix)]
1803fn is_text_busy(e: &std::io::Error) -> bool {
1804    e.raw_os_error() == Some(libc::ETXTBSY)
1805}
1806
1807#[cfg(not(unix))]
1808fn is_text_busy(_: &std::io::Error) -> bool {
1809    false
1810}
1811
1812/// [`run_to_completion`] for a child that has to be built again if starting it is refused.
1813pub(crate) async fn run_built<F>(
1814    mut build: F,
1815    timeout: Duration,
1816    max_bytes: usize,
1817    kill_grace: Duration,
1818) -> Result<String, ToolError>
1819where
1820    F: FnMut() -> tokio::process::Command,
1821{
1822    let mut running = start_retrying(&mut build, max_bytes).await?;
1823    let status = match tokio::time::timeout(timeout, running.wait()).await {
1824        Ok(done) => done?,
1825        Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1826    };
1827    Ok(running.finish(status).await)
1828}
1829
1830pub(crate) async fn run_to_completion(
1831    cmd: tokio::process::Command,
1832    timeout: Duration,
1833    max_bytes: usize,
1834    kill_grace: Duration,
1835) -> Result<String, ToolError> {
1836    let mut running = spawn(cmd, max_bytes)?;
1837    let status = match tokio::time::timeout(timeout, running.wait()).await {
1838        Ok(done) => done?,
1839        Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1840    };
1841    Ok(running.finish(status).await)
1842}
1843
1844/// How long a finished child's pipes get to reach EOF before the drain is abandoned. A real drain
1845/// has nothing left to read once the child is reaped; only an inherited write end keeps it open.
1846const DRAIN_GRACE: Duration = Duration::from_millis(500);
1847
1848/// A child that has been started, with its output being drained.
1849///
1850/// Split out of [`run_to_completion`] so that the one place which decides what a child process
1851/// gets — no stdin, piped output, its own process group, killed when the future is dropped — is
1852/// also the one place the bridge in [`crate::tools_bridge`] starts from. It waits differently
1853/// (it also answers the child's tool calls), but it must not spawn differently.
1854pub(crate) struct Running {
1855    /// Declared before `child` on purpose: fields drop in declaration order, and `child` is
1856    /// `kill_on_drop`. If the child is killed first, a `setsid` grandchild is reparented to init and
1857    /// the guard's walk can no longer find it — the one case it exists for.
1858    guard: pgroup::Guard,
1859    pgid: Option<u32>,
1860    pub(crate) child: tokio::process::Child,
1861    out: Drain,
1862    err: Drain,
1863}
1864
1865pub(crate) fn spawn(cmd: tokio::process::Command, max_bytes: usize) -> Result<Running, ToolError> {
1866    start(cmd, max_bytes).map_err(|e| ToolError::Failed(crate::tools_script::start_error(&e)))
1867}
1868
1869/// [`spawn`] with the `io::Error` kept: "Text file busy" is a refusal that passes in a moment,
1870/// and a caller can only tell it apart from a real failure while the errno is still there.
1871pub(crate) fn start(
1872    mut cmd: tokio::process::Command,
1873    max_bytes: usize,
1874) -> std::io::Result<Running> {
1875    cmd.stdin(std::process::Stdio::null())
1876        .stdout(std::process::Stdio::piped())
1877        .stderr(std::process::Stdio::piped())
1878        .kill_on_drop(true);
1879    #[cfg(unix)]
1880    cmd.process_group(0);
1881    let mut child = cmd.spawn()?;
1882    let pgid = child.id();
1883    let guard = pgroup::Guard::new(pgid);
1884    let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
1885    // Readers are their own tasks so that a child filling one pipe cannot block on the other,
1886    // and so that a caller which waits some other way still drains both.
1887    let out = Drain::start(stdout, max_bytes);
1888    let err = Drain::start(stderr, max_bytes);
1889    Ok(Running {
1890        guard,
1891        pgid,
1892        child,
1893        out,
1894        err,
1895    })
1896}
1897
1898impl Running {
1899    pub(crate) async fn wait(&mut self) -> Result<std::process::ExitStatus, ToolError> {
1900        match self.child.wait().await {
1901            Ok(status) => {
1902                // Reaped: the pid — and so the group id — can be reused from here on.
1903                self.guard.disarm();
1904                Ok(status)
1905            }
1906            Err(e) => Err(ToolError::Failed(format!("failed to wait: {e}"))),
1907        }
1908    }
1909
1910    /// The timeout message, after stopping the whole group. `kill_grace` is honoured for the
1911    /// same reason as in a normal run: a child that ignores SIGTERM must not hold the turn.
1912    pub(crate) async fn timed_out(&mut self, timeout: Duration, kill_grace: Duration) -> ToolError {
1913        if let Some(pgid) = self.pgid {
1914            pgroup::terminate(&mut self.child, pgid, kill_grace).await;
1915        }
1916        // `terminate` reaped the child, so the group id is the kernel's to hand out again. The
1917        // guard must not fire on the way out: on a host with a small `pid_max` that kill reaches
1918        // whoever was given the id next.
1919        self.guard.disarm();
1920        ToolError::Failed(format!("timed out after {}s", timeout.as_secs()))
1921    }
1922
1923    /// The result text every process tool returns, in one spelling.
1924    ///
1925    /// `#368`: the drain ends at pipe EOF, which is when the *last* holder of the write end closes
1926    /// it — and a background process the command started inherits that end. `sh -c 'sleep 1000 &
1927    /// echo started'` exits in a millisecond, so `wait` returned, the guard was disarmed, and the
1928    /// turn then sat in this function for 1000 seconds. After the child is reaped a real drain has
1929    /// nothing left to read; whatever is still quiet after the grace is not this call's output, so
1930    /// it is taken as it stands and the reader is let go.
1931    pub(crate) async fn finish(mut self, status: std::process::ExitStatus) -> String {
1932        self.guard.disarm();
1933        let stalled = tokio::time::timeout(DRAIN_GRACE, async {
1934            let _ = (&mut self.out.task).await;
1935            let _ = (&mut self.err.task).await;
1936        })
1937        .await
1938        .is_err();
1939        if stalled {
1940            self.out.task.abort();
1941            self.err.task.abort();
1942        }
1943        let (out, out_cut) = self.out.take();
1944        let (err, err_cut) = self.err.take();
1945        let note = |cut| if cut { "\n[truncated]" } else { "" };
1946        let held = if stalled {
1947            "\n[a process the command started still holds its output pipe; this call did not wait \
1948             for it]"
1949        } else {
1950            ""
1951        };
1952        format!(
1953            "exit code: {}\nstdout:\n{out}{}\nstderr:\n{err}{}{held}",
1954            status.code().map_or("signal".into(), |c| c.to_string()),
1955            note(out_cut),
1956            note(err_cut),
1957        )
1958    }
1959}
1960
1961/// When converting HTML to text, read up to this many times `max_bytes` of markup so
1962/// that the text, which is much shorter than the source, can still fill the budget.
1963const HTML_READ_FACTOR: usize = 8;
1964
1965pub struct Fetch {
1966    timeout: Duration,
1967    max_bytes: usize,
1968    html: FetchHtml,
1969    /// Lets tests talk to a loopback mock server; never compiled into release builds.
1970    #[cfg(test)]
1971    allow_internal: bool,
1972}
1973
1974impl Fetch {
1975    pub fn new(timeout: Duration, max_bytes: usize) -> Self {
1976        Self {
1977            timeout,
1978            max_bytes,
1979            html: FetchHtml::Text,
1980            #[cfg(test)]
1981            allow_internal: false,
1982        }
1983    }
1984
1985    pub fn with_html(mut self, html: FetchHtml) -> Self {
1986        self.html = html;
1987        self
1988    }
1989
1990    fn reach(&self) -> crate::http::Reach {
1991        #[cfg(test)]
1992        if self.allow_internal {
1993            return crate::http::Reach::Anywhere;
1994        }
1995        crate::http::Reach::Public
1996    }
1997}
1998
1999#[async_trait]
2000impl Tool for Fetch {
2001    fn name(&self) -> &str {
2002        "fetch"
2003    }
2004    fn description(&self) -> &str {
2005        "HTTP GET a public http(s) URL and return the response body as text. HTML pages are \
2006         converted to approximate plain text unless `raw` is true. \
2007         Private, loopback and link-local hosts are blocked."
2008    }
2009    fn parameters(&self) -> Value {
2010        json!({"type":"object","properties":{
2011            "url":{"type":"string"},
2012            "raw":{"type":"boolean","description":"return HTML source instead of converted text"}
2013        },"required":["url"]})
2014    }
2015    fn describe_call(&self, args: &Value) -> String {
2016        format!("GET {}", args["url"].as_str().unwrap_or("?"))
2017    }
2018    async fn call(&self, args: Value) -> Result<String, ToolError> {
2019        let raw = str_arg(&args, "url")?;
2020        let url = reqwest::Url::parse(raw)
2021            .map_err(|e| ToolError::InvalidArgs(format!("invalid URL: {e}")))?;
2022        if !matches!(url.scheme(), "http" | "https") {
2023            return Err(ToolError::InvalidArgs(
2024                "only http(s) URLs are allowed".into(),
2025            ));
2026        }
2027        // Redirects are not followed: approval covered this URL only, so a redirect
2028        // target is reported and the model must ask (and be approved) again.
2029        let mut resp = crate::http::get(&url, self.timeout, self.reach(), &[])
2030            .await
2031            .map_err(ToolError::Failed)?;
2032        let status = resp.status();
2033        let location = resp
2034            .headers()
2035            .get(reqwest::header::LOCATION)
2036            .map(|v| format!("location: {}\n", String::from_utf8_lossy(v.as_bytes())))
2037            .unwrap_or_default();
2038        let content_type = resp
2039            .headers()
2040            .get(reqwest::header::CONTENT_TYPE)
2041            .and_then(|v| v.to_str().ok())
2042            .map(str::to_string);
2043        let want_raw = match args.get("raw").and_then(Value::as_bool) {
2044            Some(raw) => raw,
2045            None => self.html == FetchHtml::Raw,
2046        };
2047        // A declared HTML page gets a larger read budget because its text is far shorter
2048        // than its markup; anything else (including sniffed HTML) uses the normal cap.
2049        let declared_html = content_type
2050            .as_deref()
2051            .is_some_and(|c| c.to_ascii_lowercase().contains("html"));
2052        let limit = if declared_html && !want_raw {
2053            self.max_bytes.saturating_mul(HTML_READ_FACTOR)
2054        } else {
2055            self.max_bytes
2056        };
2057        let mut body = Vec::new();
2058        while let Some(chunk) = resp
2059            .chunk()
2060            .await
2061            .map_err(|e| ToolError::Failed(e.to_string()))?
2062        {
2063            body.extend_from_slice(&chunk);
2064            if body.len() > limit {
2065                break;
2066            }
2067        }
2068        let cut = body.len() > limit;
2069        body.truncate(limit);
2070        let text = String::from_utf8_lossy(&body).into_owned();
2071        let (note, text) = if !want_raw
2072            && crate::html::looks_like_html(content_type.as_deref(), &text)
2073        {
2074            (
2075                "note: HTML converted to approximate plain text (pass \"raw\": true for the source)\n",
2076                crate::html::to_text(&text),
2077            )
2078        } else {
2079            ("", text)
2080        };
2081        let marker = if cut {
2082            "\n[response body truncated]"
2083        } else {
2084            ""
2085        };
2086        Ok(format!(
2087            "status: {status}\n{location}{note}{}{marker}",
2088            truncate(text, self.max_bytes)
2089        ))
2090    }
2091}
2092
2093#[cfg(test)]
2094mod tests {
2095    use super::*;
2096    use crate::config::ShellIsolate;
2097    use std::sync::atomic::{AtomicUsize, Ordering};
2098
2099    struct Echo;
2100
2101    #[async_trait]
2102    impl Tool for Echo {
2103        fn name(&self) -> &str {
2104            "echo"
2105        }
2106        fn description(&self) -> &str {
2107            "echo"
2108        }
2109        fn parameters(&self) -> Value {
2110            json!({"type":"object"})
2111        }
2112        async fn call(&self, args: Value) -> Result<String, ToolError> {
2113            Ok(str_arg(&args, "text")?.to_string())
2114        }
2115    }
2116
2117    /// `#351`: a pattern is matched against a tool's name *and* its source, because an MCP tool
2118    /// keeps the name its server published and so cannot be deferred by name.
2119    #[test]
2120    fn a_pattern_matches_a_source_as_well_as_a_name() {
2121        let mut registry = ToolRegistry::new(4096);
2122        registry.register(Arc::new(Echo), Policy::Allow);
2123        registry.register_with_source(
2124            Arc::new(Other),
2125            Policy::Allow,
2126            ToolSource::Plugin("mcp:homeassistant".into()),
2127        );
2128        let unknown = registry.defer(&["plugin:mcp:*".to_string()]);
2129        assert!(unknown.is_empty(), "a wildcard that matches is not a typo");
2130        let described = registry.descriptors();
2131        let deferred: Vec<&str> = described
2132            .iter()
2133            .filter(|d| d.deferred)
2134            .map(|d| d.name.as_str())
2135            .collect();
2136        assert_eq!(deferred, ["other"], "the MCP tool, not the built-in");
2137        // Deferring registers the three that reach it, and only then.
2138        let names: Vec<String> = registry.names();
2139        assert!(names.iter().any(|n| n == "tool_search"), "{names:?}");
2140
2141        // A wildcard over a source that has no tools is a filter with an empty set, not a typo.
2142        let mut bare = ToolRegistry::new(4096);
2143        bare.register(Arc::new(Echo), Policy::Allow);
2144        assert!(bare.defer(&["plugin:mcp:*".to_string()]).is_empty());
2145        assert!(
2146            !bare.names().iter().any(|n| n == "tool_search"),
2147            "nothing deferred, nothing registered to reach it"
2148        );
2149        // A name pattern that matches nothing is still a typo, wildcard or not, and says so.
2150        assert_eq!(bare.defer(&["nosuchtool".to_string()]), ["nosuchtool"]);
2151        assert_eq!(bare.defer(&["note_*".to_string()]), ["note_*"]);
2152        // A source filter over nothing is not: that is the shipped default on a box with no MCP.
2153        assert!(bare.defer(&["plugin:nowhere:*".to_string()]).is_empty());
2154    }
2155
2156    /// `#171`: a flare's read-only toolset is made by taking tools **out**, so `tool_call` cannot
2157    /// reach one that a policy merely marked disabled.
2158    #[test]
2159    fn without_takes_a_tool_out_of_the_registry_rather_than_hiding_it() {
2160        let mut registry = ToolRegistry::new(4096);
2161        registry.register(Arc::new(Echo), Policy::Allow);
2162        registry.register(Arc::new(Other), Policy::Allow);
2163        registry.defer(&["other".to_string()]);
2164
2165        let read_only = registry.without(&["other"]);
2166        assert_eq!(read_only.names(), vec!["echo".to_string()]);
2167        // The parent is untouched: this is a copy, not a mutation of what the lead runs with.
2168        assert!(
2169            registry.names().iter().any(|n| n == "other"),
2170            "the lead kept the tool the flare was not given"
2171        );
2172        // A name that is not there is not an error — the list is a rule, not a lookup.
2173        assert_eq!(read_only.without(&["nosuchtool"]).names().len(), 1);
2174    }
2175
2176    struct Other;
2177
2178    #[async_trait]
2179    impl Tool for Other {
2180        fn name(&self) -> &str {
2181            "other"
2182        }
2183        fn description(&self) -> &str {
2184            "the other one"
2185        }
2186        fn parameters(&self) -> Value {
2187            json!({
2188                "type": "object",
2189                "properties": {"text": {"type": "string", "description": "what to say"}},
2190                "required": ["text"],
2191                "additionalProperties": false
2192            })
2193        }
2194        async fn call(&self, _: Value) -> Result<String, ToolError> {
2195            Ok("other".into())
2196        }
2197    }
2198
2199    /// A name JSON Pointers need to escape.
2200    struct Slashed;
2201
2202    #[async_trait]
2203    impl Tool for Slashed {
2204        fn name(&self) -> &str {
2205            "a/b~c"
2206        }
2207        fn description(&self) -> &str {
2208            "escaped"
2209        }
2210        fn parameters(&self) -> Value {
2211            json!({"type": "object", "properties": {}})
2212        }
2213        async fn call(&self, _: Value) -> Result<String, ToolError> {
2214            Ok(String::new())
2215        }
2216    }
2217
2218    struct CountingApprover(AtomicUsize, bool);
2219
2220    #[async_trait]
2221    impl Approver for CountingApprover {
2222        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
2223            self.0.fetch_add(1, Ordering::SeqCst);
2224            if self.1 {
2225                crate::approvals::Decision::Allow
2226            } else {
2227                crate::approvals::Decision::Deny("no".to_string())
2228            }
2229        }
2230    }
2231
2232    fn registry(policy: Policy) -> ToolRegistry {
2233        let mut r = ToolRegistry::new(64);
2234        r.register(Arc::new(Echo), policy);
2235        r
2236    }
2237
2238    /// What the model actually reads. `dispatch` hands the whole output on (`#414`: the redaction
2239    /// hook has to see whole tokens), and the runtime applies the cap afterwards, so a test about
2240    /// the cap takes the same step instead of expecting it from `dispatch`.
2241    fn model_output(r: &ToolRegistry, out: ToolOutcome) -> String {
2242        truncate(out.output, r.max_output_bytes())
2243    }
2244
2245    /// A deliberately small JSON Schema checker for the keywords this project emits.
2246    ///
2247    /// Written by hand rather than pulling in a validator: the point is not to be general, it
2248    /// is to catch the failure that actually hurts — a typo'd keyword (`requried`,
2249    /// `descrition`) that every model server silently ignores, leaving a tool whose arguments
2250    /// are unconstrained. A closed vocabulary turns those into a failing test.
2251    const KEYWORDS: &[&str] = &[
2252        "$schema",
2253        "$id",
2254        "$ref",
2255        "$defs",
2256        "$comment",
2257        "title",
2258        "description",
2259        "type",
2260        "properties",
2261        "required",
2262        "additionalProperties",
2263        "items",
2264        "enum",
2265        "const",
2266        "default",
2267        "oneOf",
2268        "anyOf",
2269        "allOf",
2270        "not",
2271        "minLength",
2272        "maxLength",
2273        "pattern",
2274        "format",
2275        "minimum",
2276        "maximum",
2277        "minItems",
2278        "maxItems",
2279        "uniqueItems",
2280        "examples",
2281        "deprecated",
2282    ];
2283
2284    fn check_schema(node: &Value, path: &str, problems: &mut Vec<String>) {
2285        match node {
2286            Value::Object(map) => {
2287                for (k, v) in map {
2288                    if k == "properties" || k == "$defs" {
2289                        // A map of *user-chosen* names, each holding a schema: only the
2290                        // values are schemas, so do not judge the keys here.
2291                        if let Value::Object(props) = v {
2292                            for (name, sub) in props {
2293                                check_schema(sub, &format!("{path}.{k}.{name}"), problems);
2294                            }
2295                        } else {
2296                            problems.push(format!("{path}.{k} is not an object"));
2297                        }
2298                        continue;
2299                    }
2300                    if !KEYWORDS.contains(&k.as_str()) {
2301                        problems.push(format!("{path}: unknown keyword `{k}`"));
2302                    }
2303                    check_schema(v, &format!("{path}.{k}"), problems);
2304                }
2305                if let Some(Value::Array(req)) = map.get("required") {
2306                    if let Some(Value::Object(props)) = map.get("properties") {
2307                        for r in req {
2308                            if let Some(name) = r.as_str() {
2309                                if !props.contains_key(name) {
2310                                    problems.push(format!(
2311                                        "{path}: `required` names `{name}`, which is not in `properties`"
2312                                    ));
2313                                }
2314                            }
2315                        }
2316                    }
2317                }
2318            }
2319            Value::Array(items) => {
2320                for (i, v) in items.iter().enumerate() {
2321                    check_schema(v, &format!("{path}[{i}]"), problems);
2322                }
2323            }
2324            Value::String(_) if path.ends_with(".$ref") => {}
2325            _ => {}
2326        }
2327    }
2328
2329    /// Resolve every `$ref` in the document, then check the vocabulary of everything it points
2330    /// at. Fails with a readable list rather than one assertion.
2331    fn assert_schema_is_sound(doc: &Value, defs: &serde_json::Map<String, Value>) {
2332        let mut problems = Vec::new();
2333        check_schema(doc, "$", &mut problems);
2334        let mut refs = Vec::new();
2335        fn collect_refs(node: &Value, out: &mut Vec<String>) {
2336            match node {
2337                Value::Object(map) => {
2338                    for (k, v) in map {
2339                        if k == "$ref" {
2340                            if let Some(r) = v.as_str() {
2341                                out.push(r.to_string());
2342                            }
2343                        }
2344                        collect_refs(v, out);
2345                    }
2346                }
2347                Value::Array(a) => a.iter().for_each(|v| collect_refs(v, out)),
2348                _ => {}
2349            }
2350        }
2351        collect_refs(doc, &mut refs);
2352        assert!(!refs.is_empty(), "the document refers to $defs");
2353        for r in &refs {
2354            let target = r
2355                .strip_prefix("#/$defs/")
2356                .unwrap_or_else(|| panic!("a $ref must point into $defs: {r}"));
2357            // A JSON Pointer escapes `~` as `~0` and `/` as `~1`; the key in `$defs` is the
2358            // raw name.
2359            let key = target.replace("~1", "/").replace("~0", "~");
2360            if !defs.contains_key(&key) {
2361                problems.push(format!("$ref {r} does not resolve"));
2362            }
2363        }
2364        assert!(problems.is_empty(), "{problems:#?}");
2365    }
2366
2367    #[test]
2368    fn every_tool_describes_itself_in_one_place() {
2369        let r = registry(Policy::Allow);
2370        let d = r.descriptors();
2371        assert_eq!(d.len(), 1);
2372        assert_eq!(d[0].name, "echo");
2373        assert_eq!(d[0].policy, Policy::Allow);
2374        assert_eq!(d[0].source, ToolSource::Builtin);
2375        assert!(d[0].advertised);
2376        // The model request and the listing cannot drift apart.
2377        assert_eq!(r.specs()[0].function.parameters, d[0].parameters);
2378        assert_eq!(r.specs()[0].function.description, d[0].description);
2379    }
2380
2381    #[test]
2382    fn provenance_says_which_plugin_offered_a_tool() {
2383        let mut r = ToolRegistry::new(64);
2384        r.register(Arc::new(Echo), Policy::Ask);
2385        assert_eq!(r.descriptors()[0].source.label(), "builtin");
2386        let mut r = ToolRegistry::new(64);
2387        r.register_with_source(
2388            Arc::new(Echo),
2389            Policy::Ask,
2390            ToolSource::Plugin("memory-bank".into()),
2391        );
2392        assert_eq!(r.descriptors()[0].source.label(), "plugin:memory-bank");
2393        let json = serde_json::to_value(r.descriptors()).unwrap();
2394        assert_eq!(json[0]["source"], "plugin:memory-bank");
2395    }
2396
2397    #[test]
2398    fn the_schema_document_describes_every_advertised_tool_and_only_those_branches() {
2399        let mut r = ToolRegistry::new(64);
2400        r.register(Arc::new(Echo), Policy::Allow);
2401        r.register_with_source(Arc::new(Other), Policy::Deny, ToolSource::Builtin);
2402        let doc = r.schema_document();
2403        assert_eq!(
2404            doc["$schema"],
2405            "https://json-schema.org/draft/2020-12/schema"
2406        );
2407        assert_eq!(doc["$id"], TOOL_SCHEMA_ID);
2408
2409        let defs = doc["$defs"].as_object().expect("$defs is an object");
2410        assert!(defs.contains_key("echo") && defs.contains_key("other"));
2411        assert_schema_is_sound(&doc, defs);
2412
2413        // A denied tool exists in $defs (its schema is still worth validating against) but is
2414        // not something a client may call, so it is not a branch.
2415        let branches = doc["oneOf"].as_array().expect("oneOf is an array");
2416        assert_eq!(branches.len(), 1, "{branches:#?}");
2417        assert_eq!(branches[0]["properties"]["name"]["const"], "echo");
2418        assert_eq!(
2419            branches[0]["properties"]["arguments"]["$ref"],
2420            "#/$defs/echo"
2421        );
2422    }
2423
2424    #[test]
2425    fn a_real_argument_object_validates_against_its_own_branch() {
2426        let mut r = ToolRegistry::new(64);
2427        r.register_with_source(Arc::new(Other), Policy::Allow, ToolSource::Builtin);
2428        let doc = r.schema_document();
2429        let defs = doc["$defs"].as_object().unwrap();
2430        assert_schema_is_sound(&doc, defs);
2431
2432        // Follow the branch the way a client would: name -> const, arguments -> $defs.
2433        let branch = &doc["oneOf"][0];
2434        let name = branch["properties"]["name"]["const"].as_str().unwrap();
2435        assert_eq!(name, "other");
2436        let target = branch["properties"]["arguments"]["$ref"]
2437            .as_str()
2438            .unwrap()
2439            .strip_prefix("#/$defs/")
2440            .unwrap();
2441        let schema = &defs[target];
2442        let required: Vec<&str> = schema["required"]
2443            .as_array()
2444            .unwrap()
2445            .iter()
2446            .filter_map(|v| v.as_str())
2447            .collect();
2448        assert_eq!(required, ["text"]);
2449        let args = json!({"text": "hi"});
2450        for key in &required {
2451            assert!(args.get(*key).is_some(), "missing {key}");
2452            let want = schema["properties"][*key]["type"].as_str().unwrap();
2453            assert_eq!(
2454                want,
2455                match &args[*key] {
2456                    Value::String(_) => "string",
2457                    Value::Number(_) => "number",
2458                    _ => "other",
2459                }
2460            );
2461        }
2462    }
2463
2464    #[tokio::test]
2465    async fn a_disabled_tool_is_not_offered_and_cannot_be_called() {
2466        let mut r = registry(Policy::Allow);
2467        assert_eq!(r.advertised_names(), ["echo"]);
2468        assert!(r.disable(&["echo".into()]).is_empty());
2469        assert!(r.specs().is_empty(), "not offered to the model");
2470        assert!(r.advertised_names().is_empty());
2471        // Still registered, so the listing can say it exists and why it is off.
2472        assert_eq!(r.descriptors().len(), 1);
2473        assert!(!r.descriptors()[0].advertised);
2474        assert_eq!(r.names(), ["echo"]);
2475        // A call that names it is refused, and the refusal names the reason, not the policy.
2476        let out = r.dispatch("echo", "{\"text\":\"x\"}", &AllowAll).await;
2477        assert!(out.is_error);
2478        assert!(out.output.contains("`[tools] disabled`"), "{}", out.output);
2479    }
2480
2481    #[test]
2482    fn disabling_overrides_an_allow_policy_and_reports_names_that_match_nothing() {
2483        let mut r = ToolRegistry::new(64);
2484        r.register(Arc::new(Echo), Policy::Allow);
2485        let unknown = r.disable(&["echo".into(), "nosuchtool".into()]);
2486        assert_eq!(unknown, ["nosuchtool"], "a typo is reported, not ignored");
2487        assert!(r.specs().is_empty());
2488        // Deny and disabled are different states, and say so differently.
2489        let mut r = ToolRegistry::new(64);
2490        r.register(Arc::new(Echo), Policy::Deny);
2491        assert!(!r.descriptors()[0].advertised);
2492        assert!(r.descriptors()[0].source == ToolSource::Builtin);
2493    }
2494
2495    #[test]
2496    fn a_tool_name_with_pointer_characters_still_produces_a_resolving_ref() {
2497        let mut r = ToolRegistry::new(64);
2498        r.register_with_source(Arc::new(Slashed), Policy::Allow, ToolSource::Builtin);
2499        let doc = r.schema_document();
2500        let defs = doc["$defs"].as_object().unwrap();
2501        assert_schema_is_sound(&doc, defs);
2502    }
2503
2504    /// `#414`: `dispatch` hands the whole output on. The cap is the caller's, applied after the
2505    /// loop hooks, because redaction that sees a string already cut at `max_output_bytes` cannot
2506    /// recognise a token that ends there — the `sk-` rule wants twenty characters behind the
2507    /// prefix, so half a key matches nothing. Every built-in tool bounds its own read, which is
2508    /// why this only bites for a tool that does not (an MCP or plugin tool, which is unbounded).
2509    #[tokio::test]
2510    async fn dispatch_does_not_cap_the_output_the_hooks_will_see() {
2511        let mut r = ToolRegistry::new(8);
2512        r.register(Arc::new(Echo), Policy::Allow);
2513        let long = "x".repeat(64);
2514        let out = r
2515            .dispatch("echo", &json!({"text": long}).to_string(), &AllowAll)
2516            .await;
2517        assert_eq!(
2518            out.output.len(),
2519            64,
2520            "the cap belongs to the caller, after the hooks: {:?}",
2521            out.output
2522        );
2523        // And the cap itself still works, on a word boundary, when the caller applies it.
2524        let cut = truncate(format!("{} tail", "y".repeat(20)), 8);
2525        assert!(
2526            cut.starts_with("yyyyyyy") && cut.ends_with("[output truncated]"),
2527            "{cut:?}"
2528        );
2529        assert!(
2530            !cut.contains("tail"),
2531            "and the fragment past the cut is gone"
2532        );
2533    }
2534
2535    #[tokio::test]
2536    async fn dispatch_runs_allowed_tool() {
2537        let out = registry(Policy::Allow)
2538            .dispatch("echo", r#"{"text":"hi"}"#, &DenyAll)
2539            .await;
2540        assert_eq!(out, ToolOutcome::ok("hi".into()));
2541    }
2542
2543    #[tokio::test]
2544    async fn dispatch_reports_unknown_tool_bad_json_and_bad_args() {
2545        let r = registry(Policy::Allow);
2546        assert!(r.dispatch("nope", "{}", &AllowAll).await.is_error);
2547        let bad = r.dispatch("echo", "{oops", &AllowAll).await;
2548        assert!(bad.is_error && bad.output.contains("not valid JSON"));
2549        let missing = r.dispatch("echo", "", &AllowAll).await;
2550        assert!(missing.is_error && missing.output.contains("`text`"));
2551    }
2552
2553    #[tokio::test]
2554    async fn deny_policy_blocks_and_hides_tool() {
2555        let r = registry(Policy::Deny);
2556        assert!(r.specs().is_empty());
2557        let out = r.dispatch("echo", r#"{"text":"x"}"#, &AllowAll).await;
2558        assert!(out.is_error && out.output.contains("disabled"));
2559    }
2560
2561    #[tokio::test]
2562    async fn ask_policy_consults_approver() {
2563        let r = registry(Policy::Ask);
2564        let yes = CountingApprover(AtomicUsize::new(0), true);
2565        assert!(!r.dispatch("echo", r#"{"text":"x"}"#, &yes).await.is_error);
2566        assert_eq!(yes.0.load(Ordering::SeqCst), 1);
2567        let no = CountingApprover(AtomicUsize::new(0), false);
2568        let out = r.dispatch("echo", r#"{"text":"x"}"#, &no).await;
2569        assert!(out.is_error && out.output.contains("declined"));
2570        assert_eq!(r.specs().len(), 1);
2571    }
2572
2573    #[tokio::test]
2574    async fn allow_policy_does_not_prompt() {
2575        let a = CountingApprover(AtomicUsize::new(0), false);
2576        registry(Policy::Allow)
2577            .dispatch("echo", r#"{"text":"x"}"#, &a)
2578            .await;
2579        assert_eq!(a.0.load(Ordering::SeqCst), 0);
2580    }
2581
2582    #[tokio::test]
2583    async fn output_is_truncated_on_char_boundary() {
2584        let r = registry(Policy::Allow);
2585        let out = r
2586            .dispatch(
2587                "echo",
2588                &json!({"text": "é".repeat(100)}).to_string(),
2589                &AllowAll,
2590            )
2591            .await;
2592        let out = model_output(&r, out);
2593        assert!(out.ends_with("[output truncated]"), "{out:?}");
2594        assert!(out.len() < 100);
2595    }
2596
2597    fn builtin(dir: &Path, tweak: impl FnOnce(&mut ToolsConfig)) -> ToolRegistry {
2598        let mut cfg = ToolsConfig {
2599            read_file: Policy::Allow,
2600            write_file: Policy::Allow,
2601            shell: Policy::Allow,
2602            fetch: Policy::Deny,
2603            ..ToolsConfig::default()
2604        };
2605        tweak(&mut cfg);
2606        ToolRegistry::from_config(&cfg, dir.to_path_buf())
2607    }
2608
2609    #[tokio::test]
2610    async fn builtin_defaults_are_gated() {
2611        let dir = tempfile::tempdir().unwrap();
2612        let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2613        assert_eq!(
2614            r.names(),
2615            [
2616                "fetch",
2617                "patch",
2618                "read_file",
2619                "search_files",
2620                "shell",
2621                "write_file"
2622            ]
2623        );
2624        // `echo hi` runs; a command that cannot be undone is the one a front-end is asked about.
2625        let out = r
2626            .dispatch("shell", r#"{"command":"rm -rf everything"}"#, &DenyAll)
2627            .await;
2628        assert!(out.is_error && out.output.contains("declined"));
2629        let out = r
2630            .dispatch("shell", r#"{"command":"echo hi"}"#, &DenyAll)
2631            .await;
2632        assert!(!out.is_error, "ordinary work is not gated: {}", out.output);
2633        // The file tools are confined, not gated: a write inside the workspace happens without a
2634        // question, and one outside it is refused by the tool itself.
2635        let out = r
2636            .dispatch("write_file", r#"{"path":"a","content":"b"}"#, &DenyAll)
2637            .await;
2638        assert!(!out.is_error, "{}", out.output);
2639        assert!(dir.path().join("a").exists());
2640        let out = r
2641            .dispatch(
2642                "write_file",
2643                r#"{"path":"/tmp/escape","content":"b"}"#,
2644                &DenyAll,
2645            )
2646            .await;
2647        assert!(
2648            out.is_error && out.output.contains("outside the workspace"),
2649            "{}",
2650            out.output
2651        );
2652    }
2653
2654    /// `search_files` is a read of the tree the file tools already confine: offered, never asked
2655    /// about, and refused — by the tool, not a prompt — when the path leaves the workspace.
2656    #[tokio::test]
2657    async fn search_files_is_offered_unasked_and_fenced_by_the_workspace() {
2658        let dir = tempfile::tempdir().unwrap();
2659        std::fs::create_dir_all(dir.path().join("src")).unwrap();
2660        std::fs::write(dir.path().join("src/a.rs"), "let needle = 1;\n").unwrap();
2661        let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2662
2663        let listed = r
2664            .descriptors()
2665            .into_iter()
2666            .find(|d| d.name == "search_files")
2667            .expect("the tool is registered");
2668        assert_eq!(listed.policy, Policy::Allow);
2669        assert!(listed.advertised);
2670
2671        let out = r
2672            .dispatch("search_files", r#"{"pattern":"needle"}"#, &DenyAll)
2673            .await;
2674        assert!(!out.is_error, "{}", out.output);
2675        assert!(out.output.contains("a.rs:1"), "{}", out.output);
2676
2677        let out = r
2678            .dispatch(
2679                "search_files",
2680                r#"{"pattern":"needle","path":".."}"#,
2681                &DenyAll,
2682            )
2683            .await;
2684        assert!(
2685            out.is_error && out.output.contains("outside the workspace"),
2686            "{}",
2687            out.output
2688        );
2689    }
2690
2691    #[tokio::test]
2692    async fn file_tools_round_trip_and_confine() {
2693        let dir = tempfile::tempdir().unwrap();
2694        let r = builtin(dir.path(), |_| {});
2695        let w = r
2696            .dispatch(
2697                "write_file",
2698                r#"{"path":"sub/a.txt","content":"hello"}"#,
2699                &DenyAll,
2700            )
2701            .await;
2702        assert!(!w.is_error, "{}", w.output);
2703        let rd = r
2704            .dispatch("read_file", r#"{"path":"sub/a.txt"}"#, &DenyAll)
2705            .await;
2706        assert_eq!(rd.output, "hello");
2707        for bad in ["../escape.txt", "/etc/passwd", "sub/../../x"] {
2708            let out = r
2709                .dispatch("read_file", &json!({"path": bad}).to_string(), &DenyAll)
2710                .await;
2711            assert!(
2712                out.is_error && out.output.contains("outside"),
2713                "{bad}: {}",
2714                out.output
2715            );
2716        }
2717        let out = r
2718            .dispatch(
2719                "write_file",
2720                r#"{"path":"../escape.txt","content":"x"}"#,
2721                &DenyAll,
2722            )
2723            .await;
2724        assert!(out.is_error);
2725    }
2726
2727    #[cfg(unix)]
2728    #[tokio::test]
2729    async fn symlink_escape_is_blocked() {
2730        let dir = tempfile::tempdir().unwrap();
2731        let outside = tempfile::tempdir().unwrap();
2732        std::fs::write(outside.path().join("secret"), "s").unwrap();
2733        std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
2734        let r = builtin(dir.path(), |_| {});
2735        let out = r
2736            .dispatch("read_file", r#"{"path":"link/secret"}"#, &DenyAll)
2737            .await;
2738        assert!(out.is_error && out.output.contains("outside"));
2739    }
2740
2741    #[cfg(unix)]
2742    #[tokio::test]
2743    async fn dangling_symlink_cannot_be_written_through() {
2744        let dir = tempfile::tempdir().unwrap();
2745        let outside = tempfile::tempdir().unwrap();
2746        let target = outside.path().join("created");
2747        std::os::unix::fs::symlink(&target, dir.path().join("evil")).unwrap();
2748        let r = builtin(dir.path(), |_| {});
2749        let out = r
2750            .dispatch("write_file", r#"{"path":"evil","content":"x"}"#, &DenyAll)
2751            .await;
2752        assert!(out.is_error, "{}", out.output);
2753        assert!(!target.exists());
2754    }
2755
2756    #[tokio::test]
2757    async fn read_file_is_bounded_and_regular_files_only() {
2758        let dir = tempfile::tempdir().unwrap();
2759        std::fs::write(dir.path().join("big.txt"), "é".repeat(1000)).unwrap();
2760        std::fs::create_dir(dir.path().join("d")).unwrap();
2761        let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2762        let out = r
2763            .dispatch("read_file", r#"{"path":"big.txt"}"#, &DenyAll)
2764            .await;
2765        let shown = model_output(&r, out);
2766        assert!(shown.ends_with("[output truncated]"), "{shown:?}");
2767        assert!(shown.len() < 100);
2768        let out = r.dispatch("read_file", r#"{"path":"d"}"#, &DenyAll).await;
2769        assert!(out.is_error && out.output.contains("not a regular"));
2770    }
2771
2772    /// `#416`: `open(2)` on a FIFO with no writer blocks until somebody writes — and the "not a
2773    /// regular file" check ran *after* the open, so it was never reached. The call hung, so did the
2774    /// turn, and a blocking-pool thread went with it. A workspace-local FIFO is confined like any
2775    /// other path, which is why this is reachable at all.
2776    #[cfg(unix)]
2777    #[tokio::test]
2778    async fn a_fifo_is_refused_instead_of_hanging_the_turn() {
2779        let dir = tempfile::tempdir().unwrap();
2780        assert!(std::process::Command::new("mkfifo")
2781            .arg(dir.path().join("pipe"))
2782            .status()
2783            .map(|s| s.success())
2784            .unwrap_or(false));
2785        let r = builtin(dir.path(), |_| {});
2786        let out = tokio::time::timeout(
2787            std::time::Duration::from_secs(3),
2788            r.dispatch("read_file", r#"{"path":"pipe"}"#, &DenyAll),
2789        )
2790        .await
2791        .expect("a FIFO must not block the read");
2792        assert!(out.is_error, "{}", out.output);
2793        assert!(out.output.contains("not a regular"), "{}", out.output);
2794    }
2795
2796    /// The other half of `#416`: the cap is a byte count, so a cut can land inside a character —
2797    /// and a binary file used to come back as lossy garbage when it was over the cap while the same
2798    /// content under the cap was an error.
2799    #[tokio::test]
2800    async fn a_binary_file_is_not_text_at_any_size() {
2801        let dir = tempfile::tempdir().unwrap();
2802        let mut binary = vec![0u8; 200];
2803        binary[10] = 0xff;
2804        std::fs::write(dir.path().join("small.bin"), &binary[..50]).unwrap();
2805        std::fs::write(dir.path().join("big.bin"), &binary).unwrap();
2806        // A text file whose cut falls inside the `é` in the middle of it.
2807        std::fs::write(dir.path().join("text.txt"), "aaéé".repeat(40)).unwrap();
2808        let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2809
2810        let out = r
2811            .dispatch("read_file", r#"{"path":"small.bin"}"#, &DenyAll)
2812            .await;
2813        assert!(
2814            out.is_error,
2815            "an under-cap binary is not text: {}",
2816            out.output
2817        );
2818        let out = r
2819            .dispatch("read_file", r#"{"path":"big.bin"}"#, &DenyAll)
2820            .await;
2821        assert!(
2822            out.is_error,
2823            "an over-cap binary is not text either: {}",
2824            out.output
2825        );
2826        // The cut landing mid-character is this tool's own doing, and that one is text.
2827        let out = r
2828            .dispatch("read_file", r#"{"path":"text.txt"}"#, &DenyAll)
2829            .await;
2830        assert!(!out.is_error, "{}", out.output);
2831        assert!(out.output.starts_with("aaé"), "{}", out.output);
2832    }
2833
2834    #[cfg(unix)]
2835    #[tokio::test]
2836    async fn shell_output_is_capped_and_flooding_child_stops() {
2837        let dir = tempfile::tempdir().unwrap();
2838        let r = builtin(dir.path(), |c| {
2839            c.max_output_bytes = 256;
2840            c.shell_timeout_secs = 10;
2841        });
2842        let out = r.dispatch("shell", r#"{"command":"yes"}"#, &DenyAll).await;
2843        assert!(!out.is_error, "{}", out.output);
2844        let shown = model_output(&r, out);
2845        assert!(
2846            shown.contains("[truncated]") || shown.contains("[output truncated]"),
2847            "{shown:?}"
2848        );
2849        assert!(shown.len() < 300, "{} bytes", shown.len());
2850    }
2851
2852    /// `#368`: a drain ends at pipe EOF, which is when the *last* holder of the write end closes it
2853    /// — and a background process the command started inherits that end. `sleep 5 & echo started`
2854    /// returns in a millisecond and then held the turn for five seconds, because `wait` saw the
2855    /// child go and the drain did not.
2856    #[cfg(unix)]
2857    #[tokio::test]
2858    async fn a_background_child_does_not_hold_the_turn() {
2859        let dir = tempfile::tempdir().unwrap();
2860        let r = builtin(dir.path(), |c| {
2861            c.max_output_bytes = 4096;
2862            c.shell_timeout_secs = 30;
2863            // `#368` needs the state the issue names: no PID namespace, so a background process
2864            // really does inherit the pipe. Under `process` the namespace closes it for us.
2865            c.shell_isolate = crate::config::ShellIsolate::Off;
2866        });
2867        let asked = std::time::Instant::now();
2868        let out = tokio::time::timeout(
2869            std::time::Duration::from_secs(3),
2870            r.dispatch("shell", r#"{"command":"sleep 5 & echo started"}"#, &DenyAll),
2871        )
2872        .await
2873        .expect("a background child must not hold the call — `#368`");
2874        assert!(!out.is_error, "{}", out.output);
2875        assert!(
2876            out.output.contains("started"),
2877            "what the child itself printed: {}",
2878            out.output
2879        );
2880        assert!(
2881            out.output.contains("still holds its output pipe"),
2882            "the result says why it stopped reading: {}",
2883            out.output
2884        );
2885        assert!(asked.elapsed() < std::time::Duration::from_secs(3));
2886    }
2887
2888    #[cfg(unix)]
2889    fn process_alive(pid: i32) -> bool {
2890        // One read, not two probes. `kill(pid, 0)` followed by a read of `/proc/<pid>/stat` gave a
2891        // false "still alive" whenever the kernel reaped the zombie in between: the existence
2892        // check had already said yes, the state read then failed, and `unwrap_or(false)` said
2893        // "not a zombie". The state character on its own answers the question, and a process with
2894        // no `/proc` entry is gone.
2895        std::fs::read_to_string(format!("/proc/{pid}/stat"))
2896            .ok()
2897            .and_then(|s| {
2898                s.rsplit(')')
2899                    .next()
2900                    .map(|state| !state.trim_start().starts_with(['Z', 'X']))
2901            })
2902            .unwrap_or(false)
2903    }
2904
2905    #[cfg(unix)]
2906    async fn timeout_kills_grandchild(command: &str, grace: Duration) {
2907        let dir = tempfile::tempdir().unwrap();
2908        let mut r = ToolRegistry::new(4096);
2909        r.register(
2910            Arc::new(Shell {
2911                root: std::fs::canonicalize(dir.path()).unwrap(),
2912                skill_roots: Vec::new(),
2913                scripts_dir: None,
2914                timeout: Duration::from_secs(1),
2915                allowlist: Vec::new(),
2916                max_bytes: 4096,
2917                kill_grace: grace,
2918                sandbox: crate::sandbox::Sandbox::off(),
2919                ask: crate::config::ShellAsk::Dangerous,
2920            }),
2921            Policy::Allow,
2922        );
2923        let started = std::time::Instant::now();
2924        let out = r
2925            .dispatch("shell", &json!({"command": command}).to_string(), &DenyAll)
2926            .await;
2927        assert!(
2928            out.is_error && out.output.contains("timed out"),
2929            "{}",
2930            out.output
2931        );
2932        let pid: i32 = std::fs::read_to_string(dir.path().join("child.pid"))
2933            .unwrap()
2934            .trim()
2935            .parse()
2936            .unwrap();
2937        for _ in 0..100 {
2938            if !process_alive(pid) {
2939                break;
2940            }
2941            tokio::time::sleep(Duration::from_millis(50)).await;
2942        }
2943        // When this fails it is worth knowing what the process actually was: a `sleep` still in
2944        // the group means the signal never reached it, a zombie means the group died and nobody
2945        // reaped it, a different programme means the pid belonged to someone else.
2946        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default();
2947        assert!(
2948            !process_alive(pid),
2949            "grandchild {pid} survived the timeout after {:.2}s; stat = {stat:?}",
2950            started.elapsed().as_secs_f32()
2951        );
2952        assert!(started.elapsed() < Duration::from_secs(8));
2953    }
2954
2955    #[cfg(unix)]
2956    #[tokio::test]
2957    async fn timeout_terminates_background_grandchild() {
2958        timeout_kills_grandchild(
2959            "sleep 300 & echo $! > child.pid; wait",
2960            Duration::from_secs(2),
2961        )
2962        .await;
2963    }
2964
2965    #[cfg(unix)]
2966    #[tokio::test]
2967    async fn timeout_terminates_a_grandchild_that_left_the_process_group() {
2968        // `setsid` is the escape the group kill cannot see: the process is in a session of its own,
2969        // so `kill(-pgid)` misses it. The parent link survives, which is what the tree walk uses.
2970        timeout_kills_grandchild(
2971            "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait",
2972            Duration::from_secs(2),
2973        )
2974        .await;
2975    }
2976
2977    #[cfg(unix)]
2978    #[tokio::test]
2979    async fn a_cancelled_run_kills_a_grandchild_that_left_the_process_group() {
2980        // Dropping the future is what cancellation does to a run in flight, and `Guard` is the only
2981        // thing that stops a child then. It has no `.await`, so a `setsid` grandchild has to be
2982        // found synchronously — inside `Drop`.
2983        let dir = tempfile::tempdir().unwrap();
2984        let mut r = ToolRegistry::new(4096);
2985        r.register(
2986            Arc::new(Shell {
2987                root: std::fs::canonicalize(dir.path()).unwrap(),
2988                skill_roots: Vec::new(),
2989                scripts_dir: None,
2990                timeout: Duration::from_secs(30),
2991                allowlist: Vec::new(),
2992                max_bytes: 4096,
2993                kill_grace: Duration::from_secs(2),
2994                sandbox: crate::sandbox::Sandbox::off(),
2995                ask: crate::config::ShellAsk::Dangerous,
2996            }),
2997            Policy::Allow,
2998        );
2999        let registry = Arc::new(r);
3000        let call = {
3001            let registry = Arc::clone(&registry);
3002            let args = json!({
3003                "command": "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait"
3004            })
3005            .to_string();
3006            tokio::spawn(async move { registry.dispatch("shell", &args, &DenyAll).await })
3007        };
3008        // The grandchild has to exist before the future is dropped, or the test proves nothing.
3009        let pid = wait_for_pid(&dir.path().join("child.pid")).await;
3010        call.abort();
3011        let _ = call.await;
3012        for _ in 0..100 {
3013            if !process_alive(pid) {
3014                break;
3015            }
3016            tokio::time::sleep(Duration::from_millis(50)).await;
3017        }
3018        assert!(
3019            !process_alive(pid),
3020            "grandchild {pid} survived the drop: {:#?}",
3021            std::fs::read_to_string(format!("/proc/{pid}/stat"))
3022        );
3023    }
3024
3025    /// The pid the script wrote, once it is there: a `setsid` launch is not instant.
3026    #[cfg(unix)]
3027    async fn wait_for_pid(path: &std::path::Path) -> i32 {
3028        for _ in 0..100 {
3029            if let Ok(text) = std::fs::read_to_string(path) {
3030                if let Ok(pid) = text.trim().parse::<i32>() {
3031                    return pid;
3032                }
3033            }
3034            tokio::time::sleep(Duration::from_millis(20)).await;
3035        }
3036        panic!("the script never wrote {}", path.display());
3037    }
3038
3039    #[cfg(unix)]
3040    #[tokio::test]
3041    async fn timeout_escalates_to_sigkill_when_sigterm_is_ignored() {
3042        timeout_kills_grandchild(
3043            "trap '' TERM; sleep 300 & echo $! > child.pid; wait",
3044            Duration::from_millis(300),
3045        )
3046        .await;
3047    }
3048
3049    #[cfg(unix)]
3050    #[tokio::test]
3051    async fn shell_runs_in_workspace_with_timeout_and_allowlist() {
3052        let dir = tempfile::tempdir().unwrap();
3053        let r = builtin(dir.path(), |c| c.shell_timeout_secs = 1);
3054        let out = r
3055            .dispatch("shell", r#"{"command":"echo hi; pwd"}"#, &DenyAll)
3056            .await;
3057        assert!(!out.is_error);
3058        assert!(out.output.contains("exit code: 0") && out.output.contains("hi"));
3059        let slow = r
3060            .dispatch("shell", r#"{"command":"sleep 5"}"#, &DenyAll)
3061            .await;
3062        assert!(slow.is_error && slow.output.contains("timed out"));
3063
3064        let r = builtin(dir.path(), |c| c.shell_allowlist = vec!["echo".into()]);
3065        let ok = r
3066            .dispatch("shell", r#"{"command":"echo a b"}"#, &DenyAll)
3067            .await;
3068        assert!(ok.output.contains("a b"), "{}", ok.output);
3069        for bad in ["ls", "echo hi; ls", "echo $(ls)"] {
3070            let out = r
3071                .dispatch("shell", &json!({"command": bad}).to_string(), &DenyAll)
3072                .await;
3073            assert!(out.is_error, "{bad}");
3074        }
3075    }
3076
3077    #[cfg(unix)]
3078    fn shell_with_skills(workspace: &Path, skills: &Path) -> ToolRegistry {
3079        let cfg = ToolsConfig {
3080            shell: Policy::Allow,
3081            ..ToolsConfig::default()
3082        };
3083        let roots = vec![crate::skills::Root {
3084            source: crate::skills::Source::Shared,
3085            dir: skills.to_path_buf(),
3086        }];
3087        ToolRegistry::from_config_with(&cfg, workspace.to_path_buf(), roots)
3088    }
3089
3090    #[cfg(unix)]
3091    async fn shell_in(r: &ToolRegistry, command: &str, cwd: &str) -> ToolOutcome {
3092        r.dispatch(
3093            "shell",
3094            &json!({"command": command, "cwd": cwd}).to_string(),
3095            &DenyAll,
3096        )
3097        .await
3098    }
3099
3100    #[cfg(unix)]
3101    #[tokio::test]
3102    async fn shell_cwd_is_accepted_inside_the_workspace_and_refused_elsewhere() {
3103        let tmp = tempfile::tempdir().unwrap();
3104        let workspace = tmp.path().join("ws");
3105        std::fs::create_dir_all(workspace.join("sub")).unwrap();
3106        std::fs::write(workspace.join("file.txt"), "x").unwrap();
3107        let outside = tmp.path().join("outside");
3108        std::fs::create_dir_all(&outside).unwrap();
3109        std::os::unix::fs::symlink(&outside, workspace.join("link")).unwrap();
3110        let r = shell_with_skills(&workspace, &tmp.path().join("skills"));
3111
3112        let out = shell_in(&r, "pwd", "sub").await;
3113        assert!(!out.is_error, "{}", out.output);
3114        assert!(out.output.contains("/ws/sub"), "{}", out.output);
3115        let absolute = workspace.join("sub").display().to_string();
3116        assert!(!shell_in(&r, "pwd", &absolute).await.is_error);
3117
3118        for (cwd, why) in [
3119            ("/etc", "outside the workspace"),
3120            ("..", "outside the workspace"),
3121            ("link", "outside the workspace"),
3122            ("missing", "cannot be resolved"),
3123            ("file.txt", "not a directory"),
3124            ("  ", "empty"),
3125        ] {
3126            let out = shell_in(&r, "pwd", cwd).await;
3127            assert!(out.is_error, "{cwd:?} should be refused: {}", out.output);
3128            assert!(
3129                out.output.contains(&format!("cwd `{cwd}` refused")),
3130                "names what was refused: {}",
3131                out.output
3132            );
3133            assert!(out.output.contains(why), "{cwd:?}, {why}: {}", out.output);
3134        }
3135    }
3136
3137    #[cfg(unix)]
3138    #[tokio::test]
3139    async fn a_skills_own_script_runs_from_its_directory_but_a_broken_skills_does_not() {
3140        let tmp = tempfile::tempdir().unwrap();
3141        let workspace = tmp.path().join("ws");
3142        std::fs::create_dir_all(&workspace).unwrap();
3143        let skills = tmp.path().join("skills");
3144        let good = skills.join("backup");
3145        std::fs::create_dir_all(good.join("scripts")).unwrap();
3146        std::fs::write(
3147            good.join("SKILL.md"),
3148            "---\nname: backup\n---\nRun `bash scripts/backup.sh`.\n",
3149        )
3150        .unwrap();
3151        std::fs::write(
3152            good.join("scripts/backup.sh"),
3153            "echo backed up from $(basename \"$PWD\")\n",
3154        )
3155        .unwrap();
3156        let broken = skills.join("broken");
3157        std::fs::create_dir_all(&broken).unwrap();
3158        std::fs::write(
3159            broken.join("SKILL.md"),
3160            "---\ndescription: no name\n---\nbody\n",
3161        )
3162        .unwrap();
3163        let r = shell_with_skills(&workspace, &skills);
3164
3165        let out = shell_in(&r, "bash scripts/backup.sh", &good.display().to_string()).await;
3166        assert!(!out.is_error, "{}", out.output);
3167        assert!(
3168            out.output.contains("backed up from backup"),
3169            "{}",
3170            out.output
3171        );
3172        let nested = good.join("scripts").display().to_string();
3173        assert!(!shell_in(&r, "pwd", &nested).await.is_error);
3174
3175        let out = shell_in(&r, "pwd", &skills.display().to_string()).await;
3176        assert!(
3177            out.is_error,
3178            "the skills directory is not a skill's directory"
3179        );
3180        let out = shell_in(&r, "pwd", &broken.display().to_string()).await;
3181        assert!(out.is_error, "{}", out.output);
3182        assert!(
3183            out.output.contains("outside every skill's directory"),
3184            "{}",
3185            out.output
3186        );
3187    }
3188
3189    #[cfg(unix)]
3190    fn shell_with_scripts(workspace: &Path, scripts: &Path, allowlist: &[&str]) -> ToolRegistry {
3191        let cfg = ToolsConfig {
3192            shell: Policy::Allow,
3193            shell_allowlist: allowlist.iter().map(|s| s.to_string()).collect(),
3194            ..ToolsConfig::default()
3195        };
3196        ToolRegistry::from_config_full(
3197            &cfg,
3198            workspace.to_path_buf(),
3199            Vec::new(),
3200            Some(scripts.to_path_buf()),
3201        )
3202    }
3203
3204    #[cfg(unix)]
3205    #[tokio::test]
3206    async fn shell_finds_a_script_as_a_bare_command_and_is_told_where_the_scripts_are() {
3207        use std::os::unix::fs::PermissionsExt;
3208        let tmp = tempfile::tempdir().unwrap();
3209        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3210        std::fs::create_dir_all(&workspace).unwrap();
3211        std::fs::create_dir_all(&scripts).unwrap();
3212        let script = scripts.join("hello-script");
3213        std::fs::write(&script, "#!/bin/sh\necho hello from $1\n").unwrap();
3214        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3215        // `#427`: a script named after a real command must not run in its place. `write_file` is
3216        // `allow`, so before this the scripts directory was first on `PATH` and this `date` would
3217        // have answered every later `shell` call in the session.
3218        let imposter = scripts.join("date");
3219        std::fs::write(&imposter, "#!/bin/sh\necho fake date\n").unwrap();
3220        std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3221        let r = shell_with_scripts(&workspace, &scripts, &[]);
3222
3223        let out = r
3224            .dispatch(
3225                "shell",
3226                &json!({"command": "hello-script world; date; echo dir=$ECLIPSE_SCRIPTS_DIR; \
3227                    echo last=${PATH##*:}"})
3228                .to_string(),
3229                &DenyAll,
3230            )
3231            .await;
3232        assert!(!out.is_error, "{}", out.output);
3233        let dir = scripts.display().to_string();
3234        assert!(out.output.contains("hello from world"), "{}", out.output);
3235        assert!(out.output.contains(&format!("dir={dir}")), "{}", out.output);
3236        assert!(
3237            out.output.contains(&format!("last={dir}")),
3238            "the scripts directory is on PATH, last: {}",
3239            out.output
3240        );
3241        assert!(
3242            !out.output.contains("fake date"),
3243            "a real command wins over a script of the same name: {}",
3244            out.output
3245        );
3246    }
3247
3248    #[cfg(unix)]
3249    #[tokio::test]
3250    async fn an_allowlisted_shell_does_not_let_a_script_take_the_place_of_a_program() {
3251        use std::os::unix::fs::PermissionsExt;
3252        let tmp = tempfile::tempdir().unwrap();
3253        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3254        std::fs::create_dir_all(&workspace).unwrap();
3255        std::fs::create_dir_all(&scripts).unwrap();
3256        let imposter = scripts.join("echo");
3257        std::fs::write(&imposter, "#!/bin/sh\necho imposter\n").unwrap();
3258        std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3259        let r = shell_with_scripts(&workspace, &scripts, &["echo", "env"]);
3260
3261        let out = r
3262            .dispatch("shell", r#"{"command":"echo real"}"#, &DenyAll)
3263            .await;
3264        assert!(
3265            out.output.contains("real") && !out.output.contains("imposter"),
3266            "{}",
3267            out.output
3268        );
3269        let out = r.dispatch("shell", r#"{"command":"env"}"#, &DenyAll).await;
3270        assert!(
3271            out.output
3272                .contains(&format!("ECLIPSE_SCRIPTS_DIR={}", scripts.display())),
3273            "{}",
3274            out.output
3275        );
3276    }
3277
3278    #[cfg(unix)]
3279    #[tokio::test]
3280    async fn shell_cwd_accepts_the_scripts_directory_and_the_refusal_names_it() {
3281        let tmp = tempfile::tempdir().unwrap();
3282        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3283        std::fs::create_dir_all(&workspace).unwrap();
3284        std::fs::create_dir_all(&scripts).unwrap();
3285        let r = shell_with_scripts(&workspace, &scripts, &[]);
3286
3287        let out = shell_in(&r, "pwd", &scripts.display().to_string()).await;
3288        assert!(!out.is_error, "{}", out.output);
3289        assert!(out.output.contains("/scripts"), "{}", out.output);
3290
3291        let out = shell_in(&r, "pwd", "/etc").await;
3292        assert!(
3293            out.is_error
3294                && out.output.contains("outside the workspace")
3295                && out.output.contains("outside the scripts directory")
3296                && out.output.contains("outside every skill's directory"),
3297            "{}",
3298            out.output
3299        );
3300    }
3301
3302    fn writer(workspace: &Path, scripts: &Path) -> ToolRegistry {
3303        let cfg = ToolsConfig {
3304            write_file: Policy::Allow,
3305            ..ToolsConfig::default()
3306        };
3307        ToolRegistry::from_config_full(
3308            &cfg,
3309            workspace.to_path_buf(),
3310            Vec::new(),
3311            Some(scripts.to_path_buf()),
3312        )
3313    }
3314
3315    async fn write_to(r: &ToolRegistry, path: &str) -> ToolOutcome {
3316        r.dispatch(
3317            "write_file",
3318            &json!({"path": path, "content": "#!/bin/sh\n"}).to_string(),
3319            &DenyAll,
3320        )
3321        .await
3322    }
3323
3324    #[tokio::test]
3325    async fn write_file_writes_in_the_scripts_directory_even_before_it_exists() {
3326        let tmp = tempfile::tempdir().unwrap();
3327        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("cfg/scripts"));
3328        std::fs::create_dir_all(&workspace).unwrap();
3329        let r = writer(&workspace, &scripts);
3330
3331        let target = scripts.join("backup.sh");
3332        let out = write_to(&r, &target.display().to_string()).await;
3333        assert!(!out.is_error, "{}", out.output);
3334        assert_eq!(std::fs::read_to_string(&target).unwrap(), "#!/bin/sh\n");
3335
3336        let out = write_to(&r, &format!("{}/sub/../again.sh", scripts.display())).await;
3337        assert!(!out.is_error, "{}", out.output);
3338        assert!(scripts.join("again.sh").is_file());
3339    }
3340
3341    #[tokio::test]
3342    async fn write_file_still_writes_in_the_workspace_when_scripts_are_configured() {
3343        let tmp = tempfile::tempdir().unwrap();
3344        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3345        std::fs::create_dir_all(&workspace).unwrap();
3346        let r = writer(&workspace, &scripts);
3347        let out = write_to(&r, "notes/a.txt").await;
3348        assert!(!out.is_error, "{}", out.output);
3349        assert!(workspace.join("notes/a.txt").is_file());
3350        assert!(!scripts.exists(), "a workspace write must not create it");
3351    }
3352
3353    /// The expensive mistake this guards against: the model rewrites a 50 KB file to change two
3354    /// lines, and the whole file becomes part of every request from then on. Past the guard it has
3355    /// to say `force`, and the refusal tells it the cheaper way.
3356    #[tokio::test]
3357    async fn a_big_file_is_not_clobbered_by_accident() {
3358        let dir = tempfile::tempdir().unwrap();
3359        let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(100);
3360
3361        let big = dir.path().join("index.html");
3362        std::fs::write(&big, "x".repeat(500)).unwrap();
3363
3364        let refused = tool
3365            .call(json!({"path": "index.html", "content": "tiny"}))
3366            .await
3367            .unwrap_err()
3368            .to_string();
3369        assert!(refused.contains("already exists at 500 bytes"), "{refused}");
3370        assert!(
3371            refused.contains("`patch`"),
3372            "it names the cheap path: {refused}"
3373        );
3374        assert!(
3375            refused.contains("force: true"),
3376            "and how to mean it: {refused}"
3377        );
3378        assert_eq!(
3379            std::fs::read_to_string(&big).unwrap().len(),
3380            500,
3381            "nothing was written"
3382        );
3383
3384        // Saying force writes it.
3385        tool.call(json!({"path": "index.html", "content": "tiny", "force": true}))
3386            .await
3387            .unwrap();
3388        assert_eq!(std::fs::read_to_string(&big).unwrap(), "tiny");
3389
3390        // Below the guard, a rewrite is just a write.
3391        let small = dir.path().join("notes.md");
3392        tool.call(json!({"path": "notes.md", "content": "one"}))
3393            .await
3394            .unwrap();
3395        tool.call(json!({"path": "notes.md", "content": "two"}))
3396            .await
3397            .unwrap();
3398        assert_eq!(std::fs::read_to_string(&small).unwrap(), "two");
3399
3400        // A fresh file of any size is a creation, not a clobber.
3401        tool.call(json!({"path": "fresh.html", "content": "y".repeat(400)}))
3402            .await
3403            .unwrap();
3404        assert!(dir.path().join("fresh.html").exists());
3405
3406        // 0 leaves the tool unguarded, for a profile that wants the old behaviour.
3407        let loose = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(0);
3408        loose
3409            .call(json!({"path": "index.html", "content": "free"}))
3410            .await
3411            .unwrap();
3412        assert_eq!(std::fs::read_to_string(&big).unwrap(), "free");
3413    }
3414
3415    /// The threshold is "at least", not "larger than": the boundary is the one part of a
3416    /// documented limit anyone will ever test, so it is pinned here rather than left to prose.
3417    #[tokio::test]
3418    async fn the_guard_refuses_at_the_threshold_not_only_above_it() {
3419        let dir = tempfile::tempdir().unwrap();
3420        let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(64);
3421
3422        // Exactly the threshold: refused.
3423        std::fs::write(dir.path().join("exact.txt"), "x".repeat(64)).unwrap();
3424        let refused = tool
3425            .call(json!({"path": "exact.txt", "content": "y"}))
3426            .await
3427            .unwrap_err()
3428            .to_string();
3429        assert!(refused.contains("already exists at 64 bytes"), "{refused}");
3430        assert_eq!(
3431            std::fs::read_to_string(dir.path().join("exact.txt"))
3432                .unwrap()
3433                .len(),
3434            64,
3435            "nothing was written"
3436        );
3437
3438        // One byte under: an ordinary rewrite.
3439        std::fs::write(dir.path().join("under.txt"), "x".repeat(63)).unwrap();
3440        tool.call(json!({"path": "under.txt", "content": "y"}))
3441            .await
3442            .unwrap();
3443        assert_eq!(
3444            std::fs::read_to_string(dir.path().join("under.txt")).unwrap(),
3445            "y"
3446        );
3447    }
3448
3449    #[cfg(unix)]
3450    #[tokio::test]
3451    async fn write_file_refuses_everywhere_else_and_names_both_roots() {
3452        let tmp = tempfile::tempdir().unwrap();
3453        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3454        let elsewhere = tmp.path().join("elsewhere");
3455        std::fs::create_dir_all(&workspace).unwrap();
3456        std::fs::create_dir_all(&scripts).unwrap();
3457        std::fs::create_dir_all(&elsewhere).unwrap();
3458        std::os::unix::fs::symlink(&elsewhere, scripts.join("link")).unwrap();
3459        let r = writer(&workspace, &scripts);
3460
3461        let sibling = format!("{}-other/x.sh", scripts.display());
3462        for requested in [
3463            "/etc/eclipse-test".to_string(),
3464            elsewhere.join("x.sh").display().to_string(),
3465            format!("{}/../escape.sh", scripts.display()),
3466            format!("{}/link/x.sh", scripts.display()),
3467            sibling,
3468        ] {
3469            let out = write_to(&r, &requested).await;
3470            assert!(out.is_error, "{requested} should be refused");
3471            assert!(
3472                out.output.contains(&workspace.display().to_string())
3473                    && out.output.contains(&scripts.display().to_string()),
3474                "{requested}: {}",
3475                out.output
3476            );
3477        }
3478        assert!(!elsewhere.join("x.sh").exists());
3479        assert!(!tmp.path().join("escape.sh").exists());
3480    }
3481
3482    #[test]
3483    fn the_approval_line_for_write_file_says_when_the_destination_is_the_scripts_directory() {
3484        let tmp = tempfile::tempdir().unwrap();
3485        let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3486        let tool = WriteFile::new(workspace, Some(scripts.clone()));
3487        let line = tool.describe_call(
3488            &json!({"path": scripts.join("a.sh").display().to_string(), "content": "x"}),
3489        );
3490        assert!(line.ends_with("(scripts directory)"), "{line}");
3491        let line = tool.describe_call(&json!({"path": "a.txt", "content": "x"}));
3492        assert!(!line.contains("scripts"), "{line}");
3493    }
3494
3495    #[cfg(unix)]
3496    #[tokio::test]
3497    async fn shell_without_a_cwd_still_runs_in_the_workspace_root() {
3498        let tmp = tempfile::tempdir().unwrap();
3499        let r = shell_with_skills(tmp.path(), &tmp.path().join("skills"));
3500        let out = r.dispatch("shell", r#"{"command":"pwd"}"#, &DenyAll).await;
3501        let root = std::fs::canonicalize(tmp.path()).unwrap();
3502        assert!(
3503            out.output.contains(&root.display().to_string()),
3504            "{}",
3505            out.output
3506        );
3507        let out = r
3508            .dispatch("shell", r#"{"command":"pwd","cwd":7}"#, &DenyAll)
3509            .await;
3510        assert!(
3511            out.is_error && out.output.contains("`cwd` must be a string"),
3512            "{}",
3513            out.output
3514        );
3515    }
3516
3517    #[tokio::test]
3518    async fn fetch_rejects_non_http_schemes() {
3519        let dir = tempfile::tempdir().unwrap();
3520        let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3521        let out = r
3522            .dispatch("fetch", r#"{"url":"file:///etc/passwd"}"#, &DenyAll)
3523            .await;
3524        assert!(out.is_error && out.output.contains("http"));
3525    }
3526
3527    #[tokio::test]
3528    async fn fetch_blocks_internal_targets_before_connecting() {
3529        // A listener that must never be contacted.
3530        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3531        let port = listener.local_addr().unwrap().port();
3532        let dir = tempfile::tempdir().unwrap();
3533        let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3534        for url in [
3535            format!("http://127.0.0.1:{port}/"),
3536            format!("http://localhost:{port}/"),
3537            format!("http://svc.localhost:{port}/"),
3538            format!("http://[::1]:{port}/"),
3539            format!("http://[::ffff:127.0.0.1]:{port}/"),
3540            format!("http://2130706433:{port}/"),
3541            "http://169.254.169.254/latest/meta-data/".to_string(),
3542            "http://8.8.8.8/".to_string(),
3543        ] {
3544            let out = r
3545                .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3546                .await;
3547            assert!(
3548                out.is_error && out.output.contains("blocked"),
3549                "{url}: {}",
3550                out.output
3551            );
3552        }
3553        let accepted = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;
3554        assert!(accepted.is_err(), "blocked fetch connected anyway");
3555    }
3556
3557    #[tokio::test]
3558    async fn fetch_does_not_follow_redirects() {
3559        use tokio::io::{AsyncReadExt, AsyncWriteExt};
3560        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3561        let url = format!("http://{}/", listener.local_addr().unwrap());
3562        let server = tokio::spawn(async move {
3563            let (mut s, _) = listener.accept().await.unwrap();
3564            let mut buf = [0u8; 1024];
3565            let _ = s.read(&mut buf).await;
3566            s.write_all(
3567                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",
3568            )
3569            .await
3570            .unwrap();
3571        });
3572        let mut r = ToolRegistry::new(4096);
3573        r.register(
3574            Arc::new(Fetch {
3575                allow_internal: true,
3576                ..Fetch::new(Duration::from_secs(5), 4096)
3577            }),
3578            Policy::Allow,
3579        );
3580        let out = r
3581            .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3582            .await;
3583        server.await.unwrap();
3584        assert!(!out.is_error, "{}", out.output);
3585        assert!(
3586            out.output.contains("302")
3587                && out
3588                    .output
3589                    .contains("location: http://127.0.0.1:9/elsewhere")
3590        );
3591    }
3592
3593    /// Serves one response with the given headers/body and fetches it through the tool.
3594    async fn fetch_from_mock(
3595        headers: &'static str,
3596        body: &'static str,
3597        html: FetchHtml,
3598        args: Value,
3599    ) -> ToolOutcome {
3600        use tokio::io::{AsyncReadExt, AsyncWriteExt};
3601        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3602        let url = format!("http://{}/", listener.local_addr().unwrap());
3603        let server = tokio::spawn(async move {
3604            let (mut s, _) = listener.accept().await.unwrap();
3605            let mut buf = [0u8; 1024];
3606            let _ = s.read(&mut buf).await;
3607            let resp = format!(
3608                "HTTP/1.1 200 OK\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
3609                body.len()
3610            );
3611            s.write_all(resp.as_bytes()).await.unwrap();
3612        });
3613        let mut r = ToolRegistry::new(4096);
3614        r.register(
3615            Arc::new(
3616                Fetch {
3617                    allow_internal: true,
3618                    ..Fetch::new(Duration::from_secs(5), 4096)
3619                }
3620                .with_html(html),
3621            ),
3622            Policy::Allow,
3623        );
3624        let mut args = args;
3625        args["url"] = json!(url);
3626        let out = r.dispatch("fetch", &args.to_string(), &DenyAll).await;
3627        server.await.unwrap();
3628        out
3629    }
3630
3631    const PAGE: &str = "<!doctype html><html><head><title>T</title><script>evil()</script></head>\
3632        <body><h1>Hello</h1><p>one &amp; two</p></body></html>";
3633
3634    #[tokio::test]
3635    async fn fetch_converts_html_to_text_by_default() {
3636        let out = fetch_from_mock(
3637            "content-type: text/html; charset=utf-8\r\n",
3638            PAGE,
3639            FetchHtml::Text,
3640            json!({}),
3641        )
3642        .await;
3643        assert!(!out.is_error, "{}", out.output);
3644        assert!(out.output.starts_with("status: 200 OK\n"), "{}", out.output);
3645        assert!(
3646            out.output.contains("note: HTML converted"),
3647            "{}",
3648            out.output
3649        );
3650        assert!(
3651            out.output.ends_with("T\n\nHello\n\none & two"),
3652            "{}",
3653            out.output
3654        );
3655        assert!(!out.output.contains("<p>") && !out.output.contains("evil"));
3656
3657        // Also when the server sends no useful content type.
3658        let out = fetch_from_mock("", PAGE, FetchHtml::Text, json!({})).await;
3659        assert!(out.output.contains("Hello") && !out.output.contains("<h1>"));
3660    }
3661
3662    #[tokio::test]
3663    async fn fetch_can_return_raw_html_per_call_or_by_config() {
3664        let ct = "content-type: text/html\r\n";
3665        let out = fetch_from_mock(ct, PAGE, FetchHtml::Text, json!({"raw": true})).await;
3666        assert!(out.output.contains("<h1>Hello</h1>") && !out.output.contains("note: HTML"));
3667        let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({})).await;
3668        assert!(
3669            out.output.contains("<script>evil()</script>"),
3670            "{}",
3671            out.output
3672        );
3673        let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({"raw": false})).await;
3674        assert!(out.output.contains("note: HTML converted") && !out.output.contains("<h1>"));
3675    }
3676
3677    #[tokio::test]
3678    async fn fetch_leaves_non_html_bodies_alone() {
3679        let out = fetch_from_mock(
3680            "content-type: application/json\r\n",
3681            r#"{"html":"<p>x</p>"}"#,
3682            FetchHtml::Text,
3683            json!({}),
3684        )
3685        .await;
3686        assert!(
3687            out.output.ends_with(r#"{"html":"<p>x</p>"}"#),
3688            "{}",
3689            out.output
3690        );
3691        assert!(!out.output.contains("note:"));
3692    }
3693
3694    /// Whether bubblewrap is on this box. The tests below are the *behaviour* of isolation, so
3695    /// they mean nothing without the mechanism; a box without it skips them and the argv tests in
3696    /// `sandbox` still cover the shape.
3697    #[cfg(unix)]
3698    fn bwrap_present() -> bool {
3699        std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
3700            .any(|d| d.join("bwrap").is_file())
3701    }
3702
3703    /// A process whose command line contains `marker`, by way of `pgrep -f`.
3704    #[cfg(unix)]
3705    fn any_process(marker: &str) -> bool {
3706        std::process::Command::new("pgrep")
3707            .arg("-f")
3708            .arg(marker)
3709            .status()
3710            .map(|s| s.success())
3711            .unwrap_or(false)
3712    }
3713
3714    #[cfg(unix)]
3715    #[tokio::test]
3716    async fn isolation_stops_a_daemon_that_leaves_the_process_group() {
3717        if !bwrap_present() {
3718            return;
3719        }
3720        let dir = tempfile::tempdir().unwrap();
3721        let r = builtin(dir.path(), |c| c.shell_isolate = ShellIsolate::Process);
3722        let marker = "sleep 297.41";
3723        let started =
3724            json!({ "command": format!("setsid {marker} >/dev/null 2>&1 & echo ok") }).to_string();
3725        let out = r.dispatch("shell", &started, &DenyAll).await;
3726        assert!(!out.is_error, "{}", out.output);
3727        tokio::time::sleep(Duration::from_millis(500)).await;
3728        assert!(!any_process(marker), "a daemon outlived the run");
3729        // The run says so, rather than letting someone wonder where their server went.
3730        assert!(out.output.contains("shell_isolate"), "{}", out.output);
3731    }
3732
3733    #[cfg(unix)]
3734    #[tokio::test]
3735    async fn fs_mode_writes_inside_the_workspace_and_nowhere_else() {
3736        if !bwrap_present() {
3737            return;
3738        }
3739        let dir = tempfile::tempdir().unwrap();
3740        let r = builtin(dir.path(), |c| {
3741            c.shell_isolate = ShellIsolate::Fs;
3742            // This test is about mounts, not about the default hide list, which may well cover
3743            // the directory `tempfile` chose.
3744            c.shell_isolate_hide = Vec::new();
3745        });
3746        let command = "touch made-here && echo inside=$(test -f made-here && echo ok) \
3747                       etc=$(test -w /etc && echo writable || echo read-only) \
3748                       tmp=$(touch /tmp/x && echo writable || echo read-only)";
3749        let args = json!({ "command": command }).to_string();
3750        let out = r.dispatch("shell", &args, &DenyAll).await;
3751        assert!(!out.is_error, "{}", out.output);
3752        assert!(
3753            dir.path().join("made-here").exists(),
3754            "workspace write was lost"
3755        );
3756        assert!(out.output.contains("inside=ok"), "{}", out.output);
3757        assert!(out.output.contains("etc=read-only"), "{}", out.output);
3758        assert!(out.output.contains("tmp=writable"), "{}", out.output);
3759    }
3760
3761    #[cfg(unix)]
3762    #[tokio::test]
3763    async fn fs_mode_hides_a_path_even_inside_the_workspace() {
3764        if !bwrap_present() {
3765            return;
3766        }
3767        let dir = tempfile::tempdir().unwrap();
3768        std::fs::create_dir(dir.path().join("secret")).unwrap();
3769        std::fs::write(dir.path().join("secret/key"), "TOPSECRET").unwrap();
3770        let secret = dir.path().join("secret");
3771        let r = builtin(dir.path(), move |c| {
3772            c.shell_isolate = ShellIsolate::Fs;
3773            c.shell_isolate_hide = vec![secret];
3774        });
3775        let args = json!({ "command": "ls -A secret | wc -l" }).to_string();
3776        let out = r.dispatch("shell", &args, &DenyAll).await;
3777        assert!(!out.is_error, "{}", out.output);
3778        // `ls -A` of an emptied directory prints nothing, so the count is a bare `0`.
3779        assert!(out.output.contains("\n0\n"), "{}", out.output);
3780    }
3781
3782    #[cfg(unix)]
3783    #[tokio::test]
3784    async fn a_hide_that_would_erase_the_workspace_is_skipped_and_said_so() {
3785        if !bwrap_present() {
3786            return;
3787        }
3788        let dir = tempfile::tempdir().unwrap();
3789        // A workspace living inside something a profile hid: emptying the parent would delete
3790        // the run's own directory, so the hide is dropped — and named, rather than believed.
3791        let parent = dir.path().parent().unwrap().to_path_buf();
3792        let r = builtin(dir.path(), move |c| {
3793            c.shell_isolate = ShellIsolate::Fs;
3794            c.shell_isolate_hide = vec![parent];
3795        });
3796        let args = json!({ "command": "touch kept && ls -A | wc -l" }).to_string();
3797        let out = r.dispatch("shell", &args, &DenyAll).await;
3798        assert!(!out.is_error, "{}", out.output);
3799        assert!(
3800            dir.path().join("kept").exists(),
3801            "the workspace was erased: {}",
3802            out.output
3803        );
3804    }
3805
3806    #[test]
3807    fn specs_use_openai_function_format() {
3808        let v = serde_json::to_value(registry(Policy::Allow).specs()).unwrap();
3809        assert_eq!(v[0]["type"], "function");
3810        assert_eq!(v[0]["function"]["name"], "echo");
3811    }
3812
3813    /// `#374`: `patch` and `skill_manage` write beside the file and rename over it, and the rename
3814    /// brought the temp file's default mode with it — an executable script came back `0644`, so
3815    /// `./run.sh` and anything on the scripts `PATH` stopped running while the edit said success.
3816    #[cfg(unix)]
3817    #[test]
3818    fn replacing_a_file_keeps_its_mode() {
3819        use std::os::unix::fs::PermissionsExt;
3820        let dir = tempfile::tempdir().unwrap();
3821        let path = dir.path().join("run.sh");
3822        std::fs::write(&path, "#!/bin/sh\necho one\n").unwrap();
3823        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
3824
3825        replace_file(&path, "#!/bin/sh\necho two\n").expect("the edit lands");
3826
3827        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3828        assert_eq!(mode, 0o755, "an executable stays executable");
3829        assert_eq!(
3830            std::fs::read_to_string(&path).unwrap(),
3831            "#!/bin/sh\necho two\n"
3832        );
3833    }
3834
3835    /// The other half of `#374`: editing through a symlink used to replace the *link* with a regular
3836    /// file, leaving the real file untouched — the opposite of what "patch this path" means.
3837    #[cfg(unix)]
3838    #[test]
3839    fn replacing_through_a_symlink_edits_the_target_and_keeps_the_link() {
3840        let dir = tempfile::tempdir().unwrap();
3841        let real = dir.path().join("real.sh");
3842        let link = dir.path().join("link.sh");
3843        std::fs::write(&real, "old\n").unwrap();
3844        std::os::unix::fs::symlink(&real, &link).unwrap();
3845
3846        replace_file(&link, "new\n").expect("the edit lands");
3847
3848        let meta = std::fs::symlink_metadata(&link).unwrap();
3849        assert!(
3850            meta.file_type().is_symlink(),
3851            "the link is still a link, not a copy of the file"
3852        );
3853        assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n");
3854    }
3855}