1use 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
19fn 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 #[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 fn parameters(&self) -> Value;
46 fn describe_call(&self, args: &Value) -> String {
48 format!("{} {}", self.name(), args)
49 }
50 fn needs_approval(&self, _args: &Value) -> bool {
55 true
56 }
57 async fn call(&self, args: Value) -> Result<String, ToolError>;
58 async fn call_scoped(&self, args: Value, _scope: &CallScope<'_>) -> Result<String, ToolError> {
62 self.call(args).await
63 }
64}
65
66#[derive(Default)]
68pub struct RunScope {
69 pub session: String,
71 pub children: crate::tools_delegate::ChildLedger,
73 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 pub fn cancellable(mut self, cancel: &crate::cancel::Cancel) -> Self {
89 self.cancel = cancel.clone();
90 self
91 }
92}
93
94pub struct CallScope<'a> {
104 pub approver: &'a dyn Approver,
105 pub run: &'a RunScope,
106 pub registry: &'a ToolRegistry,
107 pub call_id: Option<&'a str>,
112}
113
114#[async_trait]
121pub trait Approver: Send + Sync {
122 async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision;
123
124 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum ToolSource {
178 Builtin,
180 Plugin(String),
182 Config(String),
186 Skill(String),
189}
190
191impl ToolSource {
192 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#[derive(Debug, Clone, Serialize, PartialEq)]
217pub struct ToolDescriptor {
218 pub name: String,
219 pub description: String,
220 pub parameters: Value,
222 pub policy: Policy,
223 pub source: ToolSource,
224 pub advertised: bool,
228 pub deferred: bool,
230 pub disabled: bool,
234}
235
236pub 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 pub malformed: bool,
247 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 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 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 disabled: bool,
296 deferred: bool,
299}
300
301pub struct ToolRegistry {
302 tools: BTreeMap<String, Entry>,
303 max_output_bytes: usize,
304 hooks: Hooks,
306 deferral: DeferralPolicies,
309}
310
311#[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 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 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 pub fn max_output_bytes(&self) -> usize {
370 self.max_output_bytes
371 }
372
373 pub fn from_config(cfg: &ToolsConfig, workspace_root: PathBuf) -> Self {
375 Self::from_config_with(cfg, workspace_root, Vec::new())
376 }
377
378 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 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 r.register(
423 Arc::new(crate::tools_patch::Patch::new(WriteFile::new(
424 root.clone(),
425 scripts_dir.clone(),
426 ))),
427 cfg.patch,
428 );
429 r.register(
430 Arc::new(Shell {
431 root: root.clone(),
432 skill_roots,
433 scripts_dir: scripts_dir.clone(),
434 sandbox: crate::sandbox::Sandbox::new(cfg, &root, scripts_dir.as_deref()),
435 timeout: Duration::from_secs(cfg.shell_timeout_secs),
436 allowlist: cfg.shell_allowlist.clone(),
437 max_bytes: cfg.max_output_bytes,
438 kill_grace: SHELL_KILL_GRACE,
439 ask: cfg.shell_ask,
440 }),
441 cfg.shell,
442 );
443 if let Some(dir) = scripts_dir {
444 r.register(
447 Arc::new(crate::tools_script::ScriptTool::new(
448 dir.clone(),
449 Duration::from_secs(cfg.shell_timeout_secs),
450 cfg.max_output_bytes,
451 )),
452 cfg.script,
453 );
454 r.register(
455 Arc::new(crate::tools_exec::ExecuteCode::new(
456 dir,
457 root.clone(),
458 Duration::from_secs(cfg.shell_timeout_secs),
459 cfg.max_output_bytes,
460 SHELL_KILL_GRACE,
461 )),
462 cfg.execute_code,
463 );
464 }
465 r.register(
466 Arc::new(
467 Fetch::new(
468 Duration::from_secs(cfg.fetch_timeout_secs),
469 cfg.max_output_bytes,
470 )
471 .with_html(cfg.fetch_html),
472 ),
473 cfg.fetch,
474 );
475 r.with_deferral_policies(cfg)
476 }
477
478 pub fn register(&mut self, tool: Arc<dyn Tool>, policy: Policy) {
480 self.register_with_source(tool, policy, ToolSource::Builtin);
481 }
482
483 pub fn register_with_source(
486 &mut self,
487 tool: Arc<dyn Tool>,
488 policy: Policy,
489 source: ToolSource,
490 ) {
491 self.tools.insert(
492 tool.name().to_string(),
493 Entry {
494 tool,
495 policy,
496 source,
497 disabled: false,
498 deferred: false,
499 },
500 );
501 }
502
503 pub fn disable(&mut self, names: &[String]) -> Vec<String> {
509 let mut unknown = Vec::new();
510 for name in names {
511 match self.tools.get_mut(name) {
512 Some(entry) => entry.disabled = true,
513 None => unknown.push(name.clone()),
514 }
515 }
516 unknown
517 }
518
519 pub fn defer(&mut self, patterns: &[String]) -> Vec<String> {
542 let mut unknown = Vec::new();
543 let mut deferred = Vec::new();
544 for pattern in patterns {
545 let matched: Vec<String> = self
546 .tools
547 .iter()
548 .filter(|(name, entry)| {
549 matches_pattern(pattern, name)
550 || matches_pattern(pattern, &entry.source.label())
551 })
552 .map(|(name, _)| name.clone())
553 .collect();
554 if matched.is_empty() && !pattern.contains(':') {
555 unknown.push(pattern.clone());
556 }
557 deferred.extend(matched);
558 }
559 for name in &deferred {
560 if let Some(entry) = self.tools.get_mut(name) {
561 entry.deferred = true;
562 }
563 }
564 if !deferred.is_empty() {
565 self.register_deferral_tools();
566 }
567 unknown
568 }
569
570 fn register_deferral_tools(&mut self) {
574 for (tool, policy) in [
575 (
576 Arc::new(crate::tools_defer::ToolSearch) as Arc<dyn Tool>,
577 self.deferral_policy(crate::tools_defer::SEARCH),
578 ),
579 (
580 Arc::new(crate::tools_defer::ToolDescribe) as Arc<dyn Tool>,
581 self.deferral_policy(crate::tools_defer::DESCRIBE),
582 ),
583 (
584 Arc::new(crate::tools_defer::ToolCall) as Arc<dyn Tool>,
585 self.deferral_policy(crate::tools_defer::CALL),
586 ),
587 ] {
588 if !self.tools.contains_key(tool.name()) {
589 self.register(tool, policy);
590 }
591 }
592 }
593
594 fn deferral_policy(&self, name: &str) -> Policy {
597 match name {
598 crate::tools_defer::SEARCH => self.deferral.search,
599 crate::tools_defer::DESCRIBE => self.deferral.describe,
600 crate::tools_defer::CALL => self.deferral.call,
601 _ => Policy::Allow,
602 }
603 }
604
605 pub fn descriptors(&self) -> Vec<ToolDescriptor> {
607 self.tools
608 .iter()
609 .map(|(name, entry)| ToolDescriptor {
610 name: name.clone(),
611 description: entry.tool.description().to_string(),
612 parameters: entry.tool.parameters(),
613 policy: entry.policy,
614 source: entry.source.clone(),
615 advertised: !entry.disabled && entry.policy != Policy::Deny && !entry.deferred,
616 deferred: entry.deferred,
617 disabled: entry.disabled,
618 })
619 .collect()
620 }
621
622 pub fn advertised_names(&self) -> Vec<String> {
624 self.descriptors()
625 .into_iter()
626 .filter(|d| d.advertised)
627 .map(|d| d.name)
628 .collect()
629 }
630
631 pub fn schema_document(&self) -> Value {
639 let mut defs = serde_json::Map::new();
640 let mut branches = Vec::new();
641 for d in self.descriptors() {
642 let pointer = json_pointer_token(&d.name);
643 defs.insert(d.name.clone(), d.parameters.clone());
644 if !d.advertised {
645 continue;
646 }
647 branches.push(json!({
648 "type": "object",
649 "description": d.description,
650 "properties": {
651 "name": { "const": d.name },
652 "arguments": { "$ref": format!("#/$defs/{pointer}") },
653 },
654 "required": ["name", "arguments"],
655 "additionalProperties": false,
656 }));
657 }
658 json!({
659 "$schema": "https://json-schema.org/draft/2020-12/schema",
660 "$id": TOOL_SCHEMA_ID,
661 "title": "Eclipse tool calls",
662 "description": "One branch per tool the model is offered: `name` pins the tool and `arguments` is validated against its parameters schema in `$defs`.",
663 "oneOf": branches,
664 "$defs": defs,
665 })
666 }
667
668 pub fn names(&self) -> Vec<String> {
669 self.tools.keys().cloned().collect()
670 }
671
672 pub fn only(&self, names: &[&str]) -> ToolRegistry {
681 let mut out = ToolRegistry {
682 tools: BTreeMap::new(),
683 max_output_bytes: self.max_output_bytes,
684 hooks: self.hooks.clone(),
685 deferral: self.deferral,
686 };
687 for (name, entry) in &self.tools {
688 if !names.contains(&name.as_str()) {
689 continue;
690 }
691 out.tools.insert(
692 name.clone(),
693 Entry {
694 tool: Arc::clone(&entry.tool),
695 policy: entry.policy,
696 source: entry.source.clone(),
697 disabled: entry.disabled,
698 deferred: entry.deferred,
699 },
700 );
701 }
702 out
703 }
704
705 pub fn without(&self, names: &[&str]) -> ToolRegistry {
716 let mut out = ToolRegistry {
717 tools: BTreeMap::new(),
718 max_output_bytes: self.max_output_bytes,
719 hooks: self.hooks.clone(),
720 deferral: self.deferral,
721 };
722 for (name, entry) in &self.tools {
723 if names.contains(&name.as_str()) {
724 continue;
725 }
726 out.tools.insert(
727 name.clone(),
728 Entry {
729 tool: Arc::clone(&entry.tool),
730 policy: entry.policy,
731 source: entry.source.clone(),
732 disabled: entry.disabled,
733 deferred: entry.deferred,
734 },
735 );
736 }
737 if !out.tools.values().any(|e| e.deferred) {
741 for bridge in ["tool_search", "tool_describe", "tool_call"] {
742 out.tools.remove(bridge);
743 }
744 }
745 out
746 }
747
748 pub fn specs(&self) -> Vec<ToolSpec> {
750 self.descriptors()
751 .into_iter()
752 .filter(|d| d.advertised)
753 .map(|d| ToolSpec {
754 kind: "function",
755 function: ToolSpecFunction {
756 name: d.name,
757 description: d.description,
758 parameters: d.parameters,
759 },
760 })
761 .collect()
762 }
763
764 pub async fn dispatch(
770 &self,
771 name: &str,
772 raw_args: &str,
773 approver: &dyn Approver,
774 ) -> ToolOutcome {
775 self.dispatch_call(name, raw_args, approver, None).await
776 }
777
778 pub fn summary_of(&self, name: &str, raw_args: &str) -> String {
782 let Some(entry) = self.tools.get(name) else {
783 return format!("{name} {raw_args}");
784 };
785 let args = serde_json::from_str(raw_args).unwrap_or_else(|_| serde_json::json!({}));
786 entry.tool.describe_call(&args)
787 }
788
789 pub async fn dispatch_call(
794 &self,
795 name: &str,
796 raw_args: &str,
797 approver: &dyn Approver,
798 call_id: Option<&str>,
799 ) -> ToolOutcome {
800 self.dispatch_scoped(name, raw_args, approver, call_id, &RunScope::default())
801 .await
802 }
803
804 pub async fn dispatch_scoped(
807 &self,
808 name: &str,
809 raw_args: &str,
810 approver: &dyn Approver,
811 call_id: Option<&str>,
812 run: &RunScope,
813 ) -> ToolOutcome {
814 let Some(entry) = self.tools.get(name) else {
815 return ToolOutcome::unusable(format!("unknown tool `{name}`"));
816 };
817 let args: Value = if raw_args.trim().is_empty() {
818 json!({})
819 } else {
820 match serde_json::from_str(raw_args) {
821 Ok(v) => v,
822 Err(e) => {
823 return ToolOutcome::unusable(format!("arguments are not valid JSON: {e}"))
824 }
825 }
826 };
827 if entry.disabled {
828 return ToolOutcome::err(format!(
829 "tool `{name}` is disabled in the config (`[tools] disabled`)"
830 ));
831 }
832 if entry.policy == Policy::Deny {
833 return ToolOutcome::err(format!("tool `{name}` is disabled by policy"));
834 }
835 if let Verdict::Deny(reason) = self.hooks.before(name, &args, call_id).await {
838 return self
839 .hooks
840 .after(name, &args, ToolOutcome::err(reason), call_id)
841 .await;
842 }
843 if entry.policy == Policy::Ask && entry.tool.needs_approval(&args) {
844 let summary = entry.tool.describe_call(&args);
845 let pending = crate::approvals::Pending::new(
846 call_id.unwrap_or_default(),
847 name,
848 summary.clone(),
849 raw_args.to_string(),
850 );
851 match approver.decide(&pending).await {
852 crate::approvals::Decision::Allow => {}
853 crate::approvals::Decision::Deny(reason) => {
854 return ToolOutcome::err(format!(
855 "the user declined to run `{name}`: {reason}"
856 ));
857 }
858 crate::approvals::Decision::Defer => {
859 return ToolOutcome::awaiting(format!(
863 "`{name}` is not approved yet; the call is waiting for an answer"
864 ));
865 }
866 }
867 }
868 let scope = CallScope {
869 approver,
870 run,
871 registry: self,
872 call_id,
873 };
874 let outcome = match entry.tool.call_scoped(args.clone(), &scope).await {
875 Ok(out) => ToolOutcome::ok(out),
876 Err(ToolError::Deferred(message)) => ToolOutcome::awaiting(message),
880 Err(e) => ToolOutcome::err(e.to_string()),
881 };
882 self.hooks.after(name, &args, outcome, call_id).await
890 }
891}
892
893pub fn truncate(mut s: String, max: usize) -> String {
902 if s.len() <= max {
903 return s;
904 }
905 let mut cut = max;
906 while !s.is_char_boundary(cut) {
907 cut -= 1;
908 }
909 let mut floor = cut.saturating_sub(200);
910 while !s.is_char_boundary(floor) {
911 floor += 1;
912 }
913 if let Some(at) = s[floor..cut]
914 .rfind(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ',' | ';' | '>' | '=' | '&'))
915 {
916 cut = floor + at;
917 }
918 s.truncate(cut);
919 s.push_str("\n[output truncated]");
920 s
921}
922
923pub(crate) fn str_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, ToolError> {
924 args.get(key)
925 .and_then(Value::as_str)
926 .ok_or_else(|| ToolError::InvalidArgs(format!("missing string field `{key}`")))
927}
928
929pub(crate) fn replace_file(path: &Path, content: &str) -> Result<(), ToolError> {
945 let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
946 let mode = std::fs::metadata(&target).ok().map(|m| m.permissions());
947 let mut tmp = target.as_os_str().to_owned();
948 tmp.push(format!(".tmp{}", std::process::id()));
949 let tmp = PathBuf::from(tmp);
950 let wrote = std::fs::write(&tmp, content);
951 let wrote = match (wrote, mode) {
952 (Ok(()), Some(mode)) => std::fs::set_permissions(&tmp, mode),
953 (wrote, _) => wrote,
954 };
955 wrote
956 .and_then(|_| std::fs::rename(&tmp, &target))
957 .map_err(|e| {
958 let _ = std::fs::remove_file(&tmp);
959 ToolError::Failed(format!("cannot write {}: {e}", path.display()))
960 })
961}
962
963fn normalize(p: &Path) -> PathBuf {
965 let mut out = PathBuf::new();
966 for c in p.components() {
967 match c {
968 Component::ParentDir => {
969 out.pop();
970 }
971 Component::CurDir => {}
972 other => out.push(other.as_os_str()),
973 }
974 }
975 out
976}
977
978pub fn confine(root: &Path, requested: &str) -> Result<PathBuf, ToolError> {
981 let joined = normalize(&root.join(requested));
982 let mut existing = joined.as_path();
983 while std::fs::symlink_metadata(existing).is_err() {
986 existing = existing
987 .parent()
988 .ok_or_else(|| ToolError::Failed("path has no existing ancestor".into()))?;
989 }
990 let canon = std::fs::canonicalize(existing)
991 .map_err(|e| ToolError::Failed(format!("cannot resolve path: {e}")))?;
992 if !canon.starts_with(root) {
993 return Err(ToolError::Failed(format!(
994 "path `{requested}` is outside the workspace"
995 )));
996 }
997 Ok(joined)
998}
999
1000pub struct ReadFile {
1001 root: PathBuf,
1002 max_bytes: usize,
1003}
1004
1005#[async_trait]
1006impl Tool for ReadFile {
1007 fn name(&self) -> &str {
1008 "read_file"
1009 }
1010 fn description(&self) -> &str {
1011 "Read a UTF-8 text file inside the workspace."
1012 }
1013 fn parameters(&self) -> Value {
1014 json!({"type":"object","properties":{"path":{"type":"string","description":"Path relative to the workspace"}},"required":["path"]})
1015 }
1016 fn describe_call(&self, args: &Value) -> String {
1017 format!("read file {}", args["path"].as_str().unwrap_or("?"))
1018 }
1019 async fn call(&self, args: Value) -> Result<String, ToolError> {
1020 let path = confine(&self.root, str_arg(&args, "path")?)?;
1021 let fail = |e: std::io::Error| ToolError::Failed(format!("{}: {e}", path.display()));
1022 let meta = tokio::fs::metadata(&path).await.map_err(fail)?;
1030 if !meta.is_file() {
1031 return Err(ToolError::Failed(format!(
1032 "{}: not a regular file",
1033 path.display()
1034 )));
1035 }
1036 let file = tokio::fs::File::open(&path).await.map_err(fail)?;
1037 let mut buf = Vec::new();
1039 file.take(self.max_bytes as u64 + 1)
1040 .read_to_end(&mut buf)
1041 .await
1042 .map_err(fail)?;
1043 let cut = buf.len() > self.max_bytes;
1049 match String::from_utf8(buf) {
1050 Ok(text) => Ok(text),
1051 Err(e) if cut && e.utf8_error().error_len().is_none() => {
1052 let valid = e.utf8_error().valid_up_to();
1058 let mut bytes = e.into_bytes();
1059 bytes.truncate(valid);
1060 Ok(format!("{}\u{FFFD}", String::from_utf8_lossy(&bytes)))
1061 }
1062 Err(_) => Err(ToolError::Failed(format!(
1063 "{}: not valid UTF-8",
1064 path.display()
1065 ))),
1066 }
1067 }
1068}
1069
1070pub struct WriteFile {
1077 root: PathBuf,
1078 scripts: Option<PathBuf>,
1079 description: String,
1080 guard_bytes: usize,
1085}
1086
1087impl WriteFile {
1088 pub(crate) fn new(root: PathBuf, scripts: Option<PathBuf>) -> Self {
1089 let description = match &scripts {
1093 None => format!(
1094 "Create or overwrite a text file inside the workspace ({}). A path outside it is \
1095refused, so a file that belongs elsewhere is written here and moved with `shell`. To change part \
1096of a file that already exists, use `patch`: a rewrite carries the whole file, and the whole file \
1097stays in the conversation afterwards.",
1098 root.display()
1099 ),
1100 Some(dir) => format!(
1101 "Create or overwrite a text file inside the workspace ({}), or inside the scripts \
1102directory ({}) which takes an absolute path. A path outside both is refused. A script written \
1103there is not executable until you run `chmod +x` on it with `shell`; see the `script` tool. To \
1104change part of a file that already exists, use `patch`: a rewrite carries the whole file, and the \
1105whole file stays in the conversation afterwards.",
1106 root.display(),
1107 dir.display()
1108 ),
1109 };
1110 Self {
1111 root,
1112 scripts,
1113 description,
1114 guard_bytes: 0,
1115 }
1116 }
1117
1118 pub(crate) fn guard_bytes(mut self, bytes: usize) -> Self {
1125 self.guard_bytes = bytes;
1126 self
1127 }
1128
1129 fn relative_to_scripts(&self, joined: &Path) -> Option<PathBuf> {
1133 let dir = normalize(self.scripts.as_deref()?);
1134 let canon = std::fs::canonicalize(&dir).ok();
1135 std::iter::once(dir)
1136 .chain(canon)
1137 .find_map(|d| joined.strip_prefix(d).ok().map(Path::to_path_buf))
1138 }
1139
1140 pub(crate) fn resolve(&self, requested: &str) -> Result<PathBuf, ToolError> {
1143 let in_workspace = confine(&self.root, requested);
1144 let Some(scripts) = &self.scripts else {
1145 return in_workspace;
1146 };
1147 if let Ok(path) = in_workspace {
1148 return Ok(path);
1149 }
1150 let outside = || {
1151 ToolError::Failed(format!(
1152 "path `{requested}` is outside the workspace ({}) and outside the scripts \
1153directory ({})",
1154 self.root.display(),
1155 scripts.display()
1156 ))
1157 };
1158 let joined = normalize(&self.root.join(requested));
1159 let rest = self.relative_to_scripts(&joined).ok_or_else(outside)?;
1160 let rest = rest.to_str().ok_or_else(outside)?;
1161 std::fs::create_dir_all(scripts)
1162 .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
1163 let canon = std::fs::canonicalize(scripts)
1164 .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
1165 confine(&canon, rest).map_err(|_| outside())
1166 }
1167}
1168
1169#[async_trait]
1170impl Tool for WriteFile {
1171 fn name(&self) -> &str {
1172 "write_file"
1173 }
1174 fn description(&self) -> &str {
1175 &self.description
1176 }
1177 fn parameters(&self) -> Value {
1178 let path = match &self.scripts {
1179 Some(dir) => format!(
1180 "Path relative to the workspace ({}), or an absolute path inside the scripts \
1181directory ({})",
1182 self.root.display(),
1183 dir.display()
1184 ),
1185 None => format!("Path relative to the workspace ({})", self.root.display()),
1186 };
1187 json!({"type":"object","properties":{
1188 "path":{"type":"string","description":path},
1189 "content":{"type":"string"},
1190 "force":{"type":"boolean","description":"Replace an existing file even if it is large. A rewrite sends the whole file and it stays in the conversation; `patch` changes only the lines you name. Default false."}
1191 },"required":["path","content"]})
1192 }
1193 fn describe_call(&self, args: &Value) -> String {
1194 let path = args["path"].as_str().unwrap_or("?");
1195 let joined = normalize(&self.root.join(path));
1196 let in_scripts =
1197 !joined.starts_with(&self.root) && self.relative_to_scripts(&joined).is_some();
1198 format!(
1199 "write {} bytes to {path}{}",
1200 args["content"].as_str().map(str::len).unwrap_or(0),
1201 if in_scripts {
1202 " (scripts directory)"
1203 } else {
1204 ""
1205 }
1206 )
1207 }
1208 async fn call(&self, args: Value) -> Result<String, ToolError> {
1209 let content = str_arg(&args, "content")?;
1210 let path = self.resolve(str_arg(&args, "path")?)?;
1211 if self.guard_bytes > 0 && !args["force"].as_bool().unwrap_or(false) {
1216 if let Ok(meta) = tokio::fs::metadata(&path).await {
1217 let existing = meta.len() as usize;
1218 if existing >= self.guard_bytes {
1219 let name = path
1220 .file_name()
1221 .map(|n| n.to_string_lossy().into_owned())
1222 .unwrap_or_else(|| path.display().to_string());
1223 return Err(ToolError::Failed(format!(
1224 "refused: {name} already exists at {} bytes. Rewriting it means sending all \
1225{existing} bytes again, and they stay in the conversation for the rest of the session. Use \
1226`patch` for the lines you want to change — that carries only those lines — or call write_file \
1227again with `force: true` if the file really has to be replaced whole.",
1228 existing
1229 )));
1230 }
1231 }
1232 }
1233 if let Some(parent) = path.parent() {
1234 tokio::fs::create_dir_all(parent)
1235 .await
1236 .map_err(|e| ToolError::Failed(format!("{}: {e}", parent.display())))?;
1237 }
1238 tokio::fs::write(&path, content)
1239 .await
1240 .map_err(|e| ToolError::Failed(format!("{}: {e}", path.display())))?;
1241 Ok(format!(
1242 "wrote {} bytes to {}",
1243 content.len(),
1244 path.display()
1245 ))
1246 }
1247}
1248
1249pub struct Shell {
1250 root: PathBuf,
1251 skill_roots: Vec<crate::skills::Root>,
1253 scripts_dir: Option<PathBuf>,
1256 timeout: Duration,
1257 allowlist: Vec<String>,
1258 max_bytes: usize,
1259 kill_grace: Duration,
1261 sandbox: crate::sandbox::Sandbox,
1264 ask: crate::config::ShellAsk,
1266}
1267
1268pub(crate) const SHELL_KILL_GRACE: Duration = Duration::from_secs(2);
1269
1270#[cfg(unix)]
1273pub(crate) mod pgroup {
1274 use std::time::{Duration, Instant};
1275
1276 fn signal(pgid: u32, sig: libc::c_int) {
1277 if let Ok(pgid) = libc::pid_t::try_from(pgid) {
1278 unsafe { libc::kill(-pgid, sig) };
1280 }
1281 }
1282
1283 fn signal_pid(pid: u32, sig: libc::c_int) {
1285 if let Ok(pid) = libc::pid_t::try_from(pid) {
1286 unsafe { libc::kill(pid, sig) };
1289 }
1290 }
1291
1292 fn descendants(root: u32) -> Vec<u32> {
1299 let mut parent_of: Vec<(u32, u32)> = Vec::new();
1300 let Ok(entries) = std::fs::read_dir("/proc") else {
1301 return Vec::new();
1302 };
1303 for entry in entries.flatten() {
1304 let Some(pid) = entry
1305 .file_name()
1306 .to_str()
1307 .and_then(|s| s.parse::<u32>().ok())
1308 else {
1309 continue;
1310 };
1311 let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
1312 continue;
1314 };
1315 let Some((_, rest)) = stat.rsplit_once(')') else {
1318 continue;
1319 };
1320 let Some(ppid) = rest
1321 .split_whitespace()
1322 .nth(1)
1323 .and_then(|s| s.parse::<u32>().ok())
1324 else {
1325 continue;
1326 };
1327 parent_of.push((pid, ppid));
1328 }
1329 let mut out = Vec::new();
1330 let mut frontier = vec![root];
1331 while let Some(parent) = frontier.pop() {
1332 for (pid, ppid) in &parent_of {
1333 if *ppid == parent && !out.contains(pid) {
1334 out.push(*pid);
1335 frontier.push(*pid);
1336 }
1337 }
1338 }
1339 out
1340 }
1341
1342 fn stop_tree(pgid: u32, sig: libc::c_int, tree: &[u32]) {
1346 signal(pgid, sig);
1347 for pid in tree {
1348 signal_pid(*pid, sig);
1349 }
1350 }
1351
1352 fn alive(pgid: u32) -> bool {
1353 let Ok(pgid) = libc::pid_t::try_from(pgid) else {
1354 return false;
1355 };
1356 let rc = unsafe { libc::kill(-pgid, 0) };
1358 rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1359 }
1360
1361 pub async fn terminate(child: &mut tokio::process::Child, pgid: u32, grace: Duration) {
1365 let tree = descendants(pgid);
1368 stop_tree(pgid, libc::SIGTERM, &tree);
1369 let deadline = Instant::now() + grace;
1370 loop {
1371 let _ = child.try_wait();
1372 if !alive(pgid) && tree.iter().all(|pid| !alive_pid(*pid)) {
1373 return;
1374 }
1375 if Instant::now() >= deadline {
1376 break;
1377 }
1378 tokio::time::sleep(Duration::from_millis(20)).await;
1379 }
1380 let mut late = descendants(pgid);
1383 late.extend(tree);
1384 late.sort_unstable();
1385 late.dedup();
1386 stop_tree(pgid, libc::SIGKILL, &late);
1387 let _ = child.wait().await;
1388 }
1389
1390 fn alive_pid(pid: u32) -> bool {
1393 let Ok(pid) = libc::pid_t::try_from(pid) else {
1394 return false;
1395 };
1396 let rc = unsafe { libc::kill(pid, 0) };
1398 rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1399 }
1400
1401 pub(crate) fn kill_now(pgid: u32) {
1407 let tree = descendants(pgid);
1408 stop_tree(pgid, libc::SIGKILL, &tree);
1409 }
1410
1411 pub struct Guard(Option<u32>);
1413
1414 impl Guard {
1415 pub fn new(pgid: Option<u32>) -> Self {
1416 Self(pgid)
1417 }
1418 pub fn disarm(&mut self) {
1419 self.0 = None;
1420 }
1421 }
1422
1423 impl Drop for Guard {
1424 fn drop(&mut self) {
1427 if let Some(pgid) = self.0 {
1428 stop_tree(pgid, libc::SIGKILL, &descendants(pgid));
1429 }
1430 }
1431 }
1432}
1433
1434#[cfg(not(unix))]
1435mod pgroup {
1436 use std::time::Duration;
1437
1438 pub async fn terminate(child: &mut tokio::process::Child, _: u32, _: Duration) {
1439 let _ = child.kill().await;
1440 }
1441
1442 pub struct Guard;
1443
1444 impl Guard {
1445 pub fn new(_: Option<u32>) -> Self {
1446 Self
1447 }
1448 pub fn disarm(&mut self) {}
1449 }
1450}
1451
1452pub(crate) struct Drain {
1460 buf: Arc<std::sync::Mutex<Vec<u8>>>,
1461 cap: usize,
1462 cut: Arc<std::sync::atomic::AtomicBool>,
1464 task: tokio::task::JoinHandle<()>,
1465}
1466
1467impl Drain {
1468 pub(crate) fn start<R: AsyncRead + Unpin + Send + 'static>(
1469 pipe: Option<R>,
1470 cap: usize,
1471 ) -> Self {
1472 let buf = Arc::new(std::sync::Mutex::new(Vec::new()));
1473 let cut = Arc::new(std::sync::atomic::AtomicBool::new(false));
1474 let task = tokio::spawn(drain_into(pipe, cap, buf.clone(), cut.clone()));
1475 Self {
1476 buf,
1477 cap,
1478 cut,
1479 task,
1480 }
1481 }
1482
1483 pub(crate) fn take(&self) -> (String, bool) {
1485 let buf = self
1486 .buf
1487 .lock()
1488 .unwrap_or_else(|poisoned| poisoned.into_inner());
1489 let short = self.cut.load(std::sync::atomic::Ordering::SeqCst) || buf.len() > self.cap;
1490 let text = String::from_utf8_lossy(&buf[..buf.len().min(self.cap)]).into_owned();
1491 (text, short)
1492 }
1493}
1494
1495impl Drop for Drain {
1496 fn drop(&mut self) {
1499 self.task.abort();
1500 }
1501}
1502
1503pub(crate) async fn read_capped<R: AsyncRead + Unpin + Send + 'static>(
1506 pipe: Option<R>,
1507 cap: usize,
1508) -> (String, bool) {
1509 let mut drain = Drain::start(pipe, cap);
1510 let _ = (&mut drain.task).await;
1511 drain.take()
1512}
1513
1514async fn drain_into<R: AsyncRead + Unpin>(
1515 pipe: Option<R>,
1516 cap: usize,
1517 buf: Arc<std::sync::Mutex<Vec<u8>>>,
1518 cut: Arc<std::sync::atomic::AtomicBool>,
1519) {
1520 let Some(mut pipe) = pipe else { return };
1521 let mut chunk = [0u8; 8192];
1522 loop {
1523 let room = (cap + 1).saturating_sub(buf.lock().map(|b| b.len()).unwrap_or(0));
1524 if room == 0 {
1527 cut.store(true, std::sync::atomic::Ordering::SeqCst);
1528 return;
1529 }
1530 let want = room.min(chunk.len());
1531 match pipe.read(&mut chunk[..want]).await {
1532 Ok(0) => return,
1533 Ok(n) => {
1534 if let Ok(mut buf) = buf.lock() {
1535 buf.extend_from_slice(&chunk[..n]);
1536 }
1537 }
1538 Err(_) => return,
1539 }
1540 }
1541}
1542
1543const SHELL_META: &[char] = &[
1544 ';', '&', '|', '<', '>', '$', '`', '\n', '(', ')', '\\', '"', '\'', '*', '?',
1545];
1546
1547fn looks_backgrounded(command: &str) -> bool {
1553 if ["nohup", "setsid", "disown"]
1554 .iter()
1555 .any(|word| command.contains(word))
1556 {
1557 return true;
1558 }
1559 let bytes = command.as_bytes();
1560 for (i, &c) in bytes.iter().enumerate() {
1561 if c != b'&' {
1562 continue;
1563 }
1564 let next = bytes.get(i + 1).copied().unwrap_or(b' ');
1565 let prev = if i == 0 { b' ' } else { bytes[i - 1] };
1566 if next == b'&' || prev == b'&' || next == b'>' || prev == b'>' {
1568 continue;
1569 }
1570 return true;
1571 }
1572 false
1573}
1574
1575impl Shell {
1576 fn build_command(
1577 &self,
1578 command: &str,
1579 dir: &Path,
1580 ) -> Result<tokio::process::Command, ToolError> {
1581 let (program, args) = self.program_argv(command)?;
1582 let plan = self.sandbox.plan(&program, &args, dir)?;
1583 let mut c = tokio::process::Command::new(plan.program);
1584 c.args(plan.args);
1585 if let Some(dir) = &self.scripts_dir {
1586 c.env(crate::tools_script::ENV_SCRIPTS_DIR, dir);
1587 if self.allowlist.is_empty() {
1590 if let Some(path) = crate::tools_script::path_with(dir) {
1591 c.env("PATH", path);
1592 }
1593 }
1594 }
1595 Ok(c)
1596 }
1597
1598 fn program_argv(&self, command: &str) -> Result<(OsString, Vec<OsString>), ToolError> {
1600 if self.allowlist.is_empty() {
1601 return Ok((OsString::from("sh"), vec!["-c".into(), command.into()]));
1602 }
1603 if command.contains(SHELL_META) {
1604 return Err(ToolError::Failed(
1605 "shell syntax is not allowed when shell_allowlist is set".into(),
1606 ));
1607 }
1608 let mut parts = command.split_whitespace();
1609 let prog = parts
1610 .next()
1611 .ok_or_else(|| ToolError::InvalidArgs("empty command".into()))?;
1612 if !self.allowlist.iter().any(|a| a == prog) {
1613 return Err(ToolError::Failed(format!(
1614 "`{prog}` is not in shell_allowlist"
1615 )));
1616 }
1617 Ok((
1618 OsString::from(prog),
1619 parts.map(OsString::from).collect::<Vec<_>>(),
1620 ))
1621 }
1622
1623 fn working_dir(&self, requested: Option<&str>) -> Result<PathBuf, ToolError> {
1632 let Some(requested) = requested else {
1633 return Ok(self.root.clone());
1634 };
1635 let refuse = |why: String| ToolError::Failed(format!("cwd `{requested}` refused: {why}"));
1636 if requested.trim().is_empty() {
1637 return Err(refuse("it is empty".into()));
1638 }
1639 let resolved = std::fs::canonicalize(self.root.join(requested))
1640 .map_err(|e| refuse(format!("it cannot be resolved ({e})")))?;
1641 if !resolved.is_dir() {
1642 return Err(refuse(format!("{} is not a directory", resolved.display())));
1643 }
1644 if resolved.starts_with(&self.root) {
1645 return Ok(resolved);
1646 }
1647 let inside_scripts = self
1648 .scripts_dir
1649 .as_ref()
1650 .and_then(|dir| std::fs::canonicalize(dir).ok())
1651 .is_some_and(|dir| resolved.starts_with(dir));
1652 if inside_scripts {
1653 return Ok(resolved);
1654 }
1655 let report = crate::skills::discover(&self.skill_roots);
1656 let inside_a_skill = report.active().any(|(found, _)| {
1657 std::fs::canonicalize(&found.dir).is_ok_and(|dir| resolved.starts_with(dir))
1658 });
1659 if inside_a_skill {
1660 return Ok(resolved);
1661 }
1662 let scripts = self.scripts_dir.as_ref().map_or(String::new(), |dir| {
1663 format!(", outside the scripts directory ({})", dir.display())
1664 });
1665 Err(refuse(format!(
1666 "it resolves to {}, which is outside the workspace ({}){scripts} and outside every skill's directory",
1667 resolved.display(),
1668 self.root.display()
1669 )))
1670 }
1671
1672 fn afterwards(&self, command: &str, out: String) -> String {
1677 if self.sandbox.degraded() {
1678 return format!(
1679 "{out}\n\n[shell_isolate = \"process\": bubblewrap (`bwrap`) is not on PATH, so this \
1680 command ran uncontained — with your files, your network, and anything it started \
1681 still running after it returned. Installing bubblewrap contains it.]"
1682 );
1683 }
1684 if !self.sandbox.is_on() || !looks_backgrounded(command) {
1685 return out;
1686 }
1687 format!(
1688 "{out}\n\n[shell_isolate = \"{}\": anything this command started in the background \
1689 was stopped when it returned, because the run's PID namespace dies with it. Set \
1690 [tools] shell_isolate = \"off\" for this profile if a process has to outlive the \
1691 call.]",
1692 self.sandbox.mode()
1693 )
1694 }
1695}
1696
1697#[async_trait]
1698impl Tool for Shell {
1699 fn name(&self) -> &str {
1700 "shell"
1701 }
1702 fn needs_approval(&self, args: &Value) -> bool {
1706 if self.ask == crate::config::ShellAsk::Always {
1707 return true;
1708 }
1709 match args["command"].as_str() {
1710 Some(command) => crate::risk::danger(command).is_some(),
1711 None => false,
1713 }
1714 }
1715 fn description(&self) -> &str {
1716 "Run a command in the workspace directory and return its exit code, stdout and stderr. \
1717Pass `cwd` to run it somewhere else inside the workspace, inside the scripts directory, or \
1718inside a skill's own directory (to run that skill's `bash scripts/x.sh` as written); any other \
1719directory is refused. The scripts directory is first on `PATH` (unless a shell allowlist is set) \
1720and named in `ECLIPSE_SCRIPTS_DIR`, so a script there runs as a bare command."
1721 }
1722 fn parameters(&self) -> Value {
1723 json!({
1724 "type": "object",
1725 "properties": {
1726 "command": {"type": "string"},
1727 "cwd": {
1728 "type": "string",
1729 "description": "Directory to run in: relative to the workspace, or absolute. It must resolve inside the workspace, the scripts directory or a skill's directory."
1730 }
1731 },
1732 "required": ["command"]
1733 })
1734 }
1735 fn describe_call(&self, args: &Value) -> String {
1736 let command = args["command"].as_str().unwrap_or("?");
1737 match args["cwd"].as_str() {
1738 Some(cwd) => format!("run `{command}` in {cwd}"),
1739 None => format!("run `{command}`"),
1740 }
1741 }
1742 async fn call(&self, args: Value) -> Result<String, ToolError> {
1743 let command = str_arg(&args, "command")?;
1744 let cwd = match args.get("cwd") {
1745 None | Some(Value::Null) => None,
1746 Some(Value::String(s)) => Some(s.as_str()),
1747 Some(_) => return Err(ToolError::InvalidArgs("`cwd` must be a string".into())),
1748 };
1749 let dir = self.working_dir(cwd)?;
1750 let mut cmd = self.build_command(command, &dir)?;
1751 cmd.current_dir(&dir);
1754 let out = run_to_completion(cmd, self.timeout, self.max_bytes, self.kill_grace).await?;
1755 Ok(self.afterwards(command, out))
1756 }
1757}
1758
1759pub(crate) async fn start_retrying<F>(mut build: F, max_bytes: usize) -> Result<Running, ToolError>
1775where
1776 F: FnMut() -> tokio::process::Command,
1777{
1778 let mut attempt = 0u32;
1779 loop {
1780 match start(build(), max_bytes) {
1781 Ok(running) => return Ok(running),
1782 Err(e) if attempt < 4 && is_text_busy(&e) => {
1783 attempt += 1;
1784 tokio::time::sleep(Duration::from_millis(1 << attempt)).await;
1785 }
1786 Err(e) => return Err(ToolError::Failed(crate::tools_script::start_error(&e))),
1787 }
1788 }
1789}
1790
1791#[cfg(unix)]
1792fn is_text_busy(e: &std::io::Error) -> bool {
1793 e.raw_os_error() == Some(libc::ETXTBSY)
1794}
1795
1796#[cfg(not(unix))]
1797fn is_text_busy(_: &std::io::Error) -> bool {
1798 false
1799}
1800
1801pub(crate) async fn run_built<F>(
1803 mut build: F,
1804 timeout: Duration,
1805 max_bytes: usize,
1806 kill_grace: Duration,
1807) -> Result<String, ToolError>
1808where
1809 F: FnMut() -> tokio::process::Command,
1810{
1811 let mut running = start_retrying(&mut build, max_bytes).await?;
1812 let status = match tokio::time::timeout(timeout, running.wait()).await {
1813 Ok(done) => done?,
1814 Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1815 };
1816 Ok(running.finish(status).await)
1817}
1818
1819pub(crate) async fn run_to_completion(
1820 cmd: tokio::process::Command,
1821 timeout: Duration,
1822 max_bytes: usize,
1823 kill_grace: Duration,
1824) -> Result<String, ToolError> {
1825 let mut running = spawn(cmd, max_bytes)?;
1826 let status = match tokio::time::timeout(timeout, running.wait()).await {
1827 Ok(done) => done?,
1828 Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1829 };
1830 Ok(running.finish(status).await)
1831}
1832
1833const DRAIN_GRACE: Duration = Duration::from_millis(500);
1836
1837pub(crate) struct Running {
1844 guard: pgroup::Guard,
1848 pgid: Option<u32>,
1849 pub(crate) child: tokio::process::Child,
1850 out: Drain,
1851 err: Drain,
1852}
1853
1854pub(crate) fn spawn(cmd: tokio::process::Command, max_bytes: usize) -> Result<Running, ToolError> {
1855 start(cmd, max_bytes).map_err(|e| ToolError::Failed(crate::tools_script::start_error(&e)))
1856}
1857
1858pub(crate) fn start(
1861 mut cmd: tokio::process::Command,
1862 max_bytes: usize,
1863) -> std::io::Result<Running> {
1864 cmd.stdin(std::process::Stdio::null())
1865 .stdout(std::process::Stdio::piped())
1866 .stderr(std::process::Stdio::piped())
1867 .kill_on_drop(true);
1868 #[cfg(unix)]
1869 cmd.process_group(0);
1870 let mut child = cmd.spawn()?;
1871 let pgid = child.id();
1872 let guard = pgroup::Guard::new(pgid);
1873 let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
1874 let out = Drain::start(stdout, max_bytes);
1877 let err = Drain::start(stderr, max_bytes);
1878 Ok(Running {
1879 guard,
1880 pgid,
1881 child,
1882 out,
1883 err,
1884 })
1885}
1886
1887impl Running {
1888 pub(crate) async fn wait(&mut self) -> Result<std::process::ExitStatus, ToolError> {
1889 match self.child.wait().await {
1890 Ok(status) => {
1891 self.guard.disarm();
1893 Ok(status)
1894 }
1895 Err(e) => Err(ToolError::Failed(format!("failed to wait: {e}"))),
1896 }
1897 }
1898
1899 pub(crate) async fn timed_out(&mut self, timeout: Duration, kill_grace: Duration) -> ToolError {
1902 if let Some(pgid) = self.pgid {
1903 pgroup::terminate(&mut self.child, pgid, kill_grace).await;
1904 }
1905 self.guard.disarm();
1909 ToolError::Failed(format!("timed out after {}s", timeout.as_secs()))
1910 }
1911
1912 pub(crate) async fn finish(mut self, status: std::process::ExitStatus) -> String {
1921 self.guard.disarm();
1922 let stalled = tokio::time::timeout(DRAIN_GRACE, async {
1923 let _ = (&mut self.out.task).await;
1924 let _ = (&mut self.err.task).await;
1925 })
1926 .await
1927 .is_err();
1928 if stalled {
1929 self.out.task.abort();
1930 self.err.task.abort();
1931 }
1932 let (out, out_cut) = self.out.take();
1933 let (err, err_cut) = self.err.take();
1934 let note = |cut| if cut { "\n[truncated]" } else { "" };
1935 let held = if stalled {
1936 "\n[a process the command started still holds its output pipe; this call did not wait \
1937 for it]"
1938 } else {
1939 ""
1940 };
1941 format!(
1942 "exit code: {}\nstdout:\n{out}{}\nstderr:\n{err}{}{held}",
1943 status.code().map_or("signal".into(), |c| c.to_string()),
1944 note(out_cut),
1945 note(err_cut),
1946 )
1947 }
1948}
1949
1950const HTML_READ_FACTOR: usize = 8;
1953
1954pub struct Fetch {
1955 timeout: Duration,
1956 max_bytes: usize,
1957 html: FetchHtml,
1958 #[cfg(test)]
1960 allow_internal: bool,
1961}
1962
1963impl Fetch {
1964 pub fn new(timeout: Duration, max_bytes: usize) -> Self {
1965 Self {
1966 timeout,
1967 max_bytes,
1968 html: FetchHtml::Text,
1969 #[cfg(test)]
1970 allow_internal: false,
1971 }
1972 }
1973
1974 pub fn with_html(mut self, html: FetchHtml) -> Self {
1975 self.html = html;
1976 self
1977 }
1978
1979 fn reach(&self) -> crate::http::Reach {
1980 #[cfg(test)]
1981 if self.allow_internal {
1982 return crate::http::Reach::Anywhere;
1983 }
1984 crate::http::Reach::Public
1985 }
1986}
1987
1988#[async_trait]
1989impl Tool for Fetch {
1990 fn name(&self) -> &str {
1991 "fetch"
1992 }
1993 fn description(&self) -> &str {
1994 "HTTP GET a public http(s) URL and return the response body as text. HTML pages are \
1995 converted to approximate plain text unless `raw` is true. \
1996 Private, loopback and link-local hosts are blocked."
1997 }
1998 fn parameters(&self) -> Value {
1999 json!({"type":"object","properties":{
2000 "url":{"type":"string"},
2001 "raw":{"type":"boolean","description":"return HTML source instead of converted text"}
2002 },"required":["url"]})
2003 }
2004 fn describe_call(&self, args: &Value) -> String {
2005 format!("GET {}", args["url"].as_str().unwrap_or("?"))
2006 }
2007 async fn call(&self, args: Value) -> Result<String, ToolError> {
2008 let raw = str_arg(&args, "url")?;
2009 let url = reqwest::Url::parse(raw)
2010 .map_err(|e| ToolError::InvalidArgs(format!("invalid URL: {e}")))?;
2011 if !matches!(url.scheme(), "http" | "https") {
2012 return Err(ToolError::InvalidArgs(
2013 "only http(s) URLs are allowed".into(),
2014 ));
2015 }
2016 let mut resp = crate::http::get(&url, self.timeout, self.reach(), &[])
2019 .await
2020 .map_err(ToolError::Failed)?;
2021 let status = resp.status();
2022 let location = resp
2023 .headers()
2024 .get(reqwest::header::LOCATION)
2025 .map(|v| format!("location: {}\n", String::from_utf8_lossy(v.as_bytes())))
2026 .unwrap_or_default();
2027 let content_type = resp
2028 .headers()
2029 .get(reqwest::header::CONTENT_TYPE)
2030 .and_then(|v| v.to_str().ok())
2031 .map(str::to_string);
2032 let want_raw = match args.get("raw").and_then(Value::as_bool) {
2033 Some(raw) => raw,
2034 None => self.html == FetchHtml::Raw,
2035 };
2036 let declared_html = content_type
2039 .as_deref()
2040 .is_some_and(|c| c.to_ascii_lowercase().contains("html"));
2041 let limit = if declared_html && !want_raw {
2042 self.max_bytes.saturating_mul(HTML_READ_FACTOR)
2043 } else {
2044 self.max_bytes
2045 };
2046 let mut body = Vec::new();
2047 while let Some(chunk) = resp
2048 .chunk()
2049 .await
2050 .map_err(|e| ToolError::Failed(e.to_string()))?
2051 {
2052 body.extend_from_slice(&chunk);
2053 if body.len() > limit {
2054 break;
2055 }
2056 }
2057 let cut = body.len() > limit;
2058 body.truncate(limit);
2059 let text = String::from_utf8_lossy(&body).into_owned();
2060 let (note, text) = if !want_raw
2061 && crate::html::looks_like_html(content_type.as_deref(), &text)
2062 {
2063 (
2064 "note: HTML converted to approximate plain text (pass \"raw\": true for the source)\n",
2065 crate::html::to_text(&text),
2066 )
2067 } else {
2068 ("", text)
2069 };
2070 let marker = if cut {
2071 "\n[response body truncated]"
2072 } else {
2073 ""
2074 };
2075 Ok(format!(
2076 "status: {status}\n{location}{note}{}{marker}",
2077 truncate(text, self.max_bytes)
2078 ))
2079 }
2080}
2081
2082#[cfg(test)]
2083mod tests {
2084 use super::*;
2085 use crate::config::ShellIsolate;
2086 use std::sync::atomic::{AtomicUsize, Ordering};
2087
2088 struct Echo;
2089
2090 #[async_trait]
2091 impl Tool for Echo {
2092 fn name(&self) -> &str {
2093 "echo"
2094 }
2095 fn description(&self) -> &str {
2096 "echo"
2097 }
2098 fn parameters(&self) -> Value {
2099 json!({"type":"object"})
2100 }
2101 async fn call(&self, args: Value) -> Result<String, ToolError> {
2102 Ok(str_arg(&args, "text")?.to_string())
2103 }
2104 }
2105
2106 #[test]
2109 fn a_pattern_matches_a_source_as_well_as_a_name() {
2110 let mut registry = ToolRegistry::new(4096);
2111 registry.register(Arc::new(Echo), Policy::Allow);
2112 registry.register_with_source(
2113 Arc::new(Other),
2114 Policy::Allow,
2115 ToolSource::Plugin("mcp:homeassistant".into()),
2116 );
2117 let unknown = registry.defer(&["plugin:mcp:*".to_string()]);
2118 assert!(unknown.is_empty(), "a wildcard that matches is not a typo");
2119 let described = registry.descriptors();
2120 let deferred: Vec<&str> = described
2121 .iter()
2122 .filter(|d| d.deferred)
2123 .map(|d| d.name.as_str())
2124 .collect();
2125 assert_eq!(deferred, ["other"], "the MCP tool, not the built-in");
2126 let names: Vec<String> = registry.names();
2128 assert!(names.iter().any(|n| n == "tool_search"), "{names:?}");
2129
2130 let mut bare = ToolRegistry::new(4096);
2132 bare.register(Arc::new(Echo), Policy::Allow);
2133 assert!(bare.defer(&["plugin:mcp:*".to_string()]).is_empty());
2134 assert!(
2135 !bare.names().iter().any(|n| n == "tool_search"),
2136 "nothing deferred, nothing registered to reach it"
2137 );
2138 assert_eq!(bare.defer(&["nosuchtool".to_string()]), ["nosuchtool"]);
2140 assert_eq!(bare.defer(&["note_*".to_string()]), ["note_*"]);
2141 assert!(bare.defer(&["plugin:nowhere:*".to_string()]).is_empty());
2143 }
2144
2145 #[test]
2148 fn without_takes_a_tool_out_of_the_registry_rather_than_hiding_it() {
2149 let mut registry = ToolRegistry::new(4096);
2150 registry.register(Arc::new(Echo), Policy::Allow);
2151 registry.register(Arc::new(Other), Policy::Allow);
2152 registry.defer(&["other".to_string()]);
2153
2154 let read_only = registry.without(&["other"]);
2155 assert_eq!(read_only.names(), vec!["echo".to_string()]);
2156 assert!(
2158 registry.names().iter().any(|n| n == "other"),
2159 "the lead kept the tool the flare was not given"
2160 );
2161 assert_eq!(read_only.without(&["nosuchtool"]).names().len(), 1);
2163 }
2164
2165 struct Other;
2166
2167 #[async_trait]
2168 impl Tool for Other {
2169 fn name(&self) -> &str {
2170 "other"
2171 }
2172 fn description(&self) -> &str {
2173 "the other one"
2174 }
2175 fn parameters(&self) -> Value {
2176 json!({
2177 "type": "object",
2178 "properties": {"text": {"type": "string", "description": "what to say"}},
2179 "required": ["text"],
2180 "additionalProperties": false
2181 })
2182 }
2183 async fn call(&self, _: Value) -> Result<String, ToolError> {
2184 Ok("other".into())
2185 }
2186 }
2187
2188 struct Slashed;
2190
2191 #[async_trait]
2192 impl Tool for Slashed {
2193 fn name(&self) -> &str {
2194 "a/b~c"
2195 }
2196 fn description(&self) -> &str {
2197 "escaped"
2198 }
2199 fn parameters(&self) -> Value {
2200 json!({"type": "object", "properties": {}})
2201 }
2202 async fn call(&self, _: Value) -> Result<String, ToolError> {
2203 Ok(String::new())
2204 }
2205 }
2206
2207 struct CountingApprover(AtomicUsize, bool);
2208
2209 #[async_trait]
2210 impl Approver for CountingApprover {
2211 async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
2212 self.0.fetch_add(1, Ordering::SeqCst);
2213 if self.1 {
2214 crate::approvals::Decision::Allow
2215 } else {
2216 crate::approvals::Decision::Deny("no".to_string())
2217 }
2218 }
2219 }
2220
2221 fn registry(policy: Policy) -> ToolRegistry {
2222 let mut r = ToolRegistry::new(64);
2223 r.register(Arc::new(Echo), policy);
2224 r
2225 }
2226
2227 fn model_output(r: &ToolRegistry, out: ToolOutcome) -> String {
2231 truncate(out.output, r.max_output_bytes())
2232 }
2233
2234 const KEYWORDS: &[&str] = &[
2241 "$schema",
2242 "$id",
2243 "$ref",
2244 "$defs",
2245 "$comment",
2246 "title",
2247 "description",
2248 "type",
2249 "properties",
2250 "required",
2251 "additionalProperties",
2252 "items",
2253 "enum",
2254 "const",
2255 "default",
2256 "oneOf",
2257 "anyOf",
2258 "allOf",
2259 "not",
2260 "minLength",
2261 "maxLength",
2262 "pattern",
2263 "format",
2264 "minimum",
2265 "maximum",
2266 "minItems",
2267 "maxItems",
2268 "uniqueItems",
2269 "examples",
2270 "deprecated",
2271 ];
2272
2273 fn check_schema(node: &Value, path: &str, problems: &mut Vec<String>) {
2274 match node {
2275 Value::Object(map) => {
2276 for (k, v) in map {
2277 if k == "properties" || k == "$defs" {
2278 if let Value::Object(props) = v {
2281 for (name, sub) in props {
2282 check_schema(sub, &format!("{path}.{k}.{name}"), problems);
2283 }
2284 } else {
2285 problems.push(format!("{path}.{k} is not an object"));
2286 }
2287 continue;
2288 }
2289 if !KEYWORDS.contains(&k.as_str()) {
2290 problems.push(format!("{path}: unknown keyword `{k}`"));
2291 }
2292 check_schema(v, &format!("{path}.{k}"), problems);
2293 }
2294 if let Some(Value::Array(req)) = map.get("required") {
2295 if let Some(Value::Object(props)) = map.get("properties") {
2296 for r in req {
2297 if let Some(name) = r.as_str() {
2298 if !props.contains_key(name) {
2299 problems.push(format!(
2300 "{path}: `required` names `{name}`, which is not in `properties`"
2301 ));
2302 }
2303 }
2304 }
2305 }
2306 }
2307 }
2308 Value::Array(items) => {
2309 for (i, v) in items.iter().enumerate() {
2310 check_schema(v, &format!("{path}[{i}]"), problems);
2311 }
2312 }
2313 Value::String(_) if path.ends_with(".$ref") => {}
2314 _ => {}
2315 }
2316 }
2317
2318 fn assert_schema_is_sound(doc: &Value, defs: &serde_json::Map<String, Value>) {
2321 let mut problems = Vec::new();
2322 check_schema(doc, "$", &mut problems);
2323 let mut refs = Vec::new();
2324 fn collect_refs(node: &Value, out: &mut Vec<String>) {
2325 match node {
2326 Value::Object(map) => {
2327 for (k, v) in map {
2328 if k == "$ref" {
2329 if let Some(r) = v.as_str() {
2330 out.push(r.to_string());
2331 }
2332 }
2333 collect_refs(v, out);
2334 }
2335 }
2336 Value::Array(a) => a.iter().for_each(|v| collect_refs(v, out)),
2337 _ => {}
2338 }
2339 }
2340 collect_refs(doc, &mut refs);
2341 assert!(!refs.is_empty(), "the document refers to $defs");
2342 for r in &refs {
2343 let target = r
2344 .strip_prefix("#/$defs/")
2345 .unwrap_or_else(|| panic!("a $ref must point into $defs: {r}"));
2346 let key = target.replace("~1", "/").replace("~0", "~");
2349 if !defs.contains_key(&key) {
2350 problems.push(format!("$ref {r} does not resolve"));
2351 }
2352 }
2353 assert!(problems.is_empty(), "{problems:#?}");
2354 }
2355
2356 #[test]
2357 fn every_tool_describes_itself_in_one_place() {
2358 let r = registry(Policy::Allow);
2359 let d = r.descriptors();
2360 assert_eq!(d.len(), 1);
2361 assert_eq!(d[0].name, "echo");
2362 assert_eq!(d[0].policy, Policy::Allow);
2363 assert_eq!(d[0].source, ToolSource::Builtin);
2364 assert!(d[0].advertised);
2365 assert_eq!(r.specs()[0].function.parameters, d[0].parameters);
2367 assert_eq!(r.specs()[0].function.description, d[0].description);
2368 }
2369
2370 #[test]
2371 fn provenance_says_which_plugin_offered_a_tool() {
2372 let mut r = ToolRegistry::new(64);
2373 r.register(Arc::new(Echo), Policy::Ask);
2374 assert_eq!(r.descriptors()[0].source.label(), "builtin");
2375 let mut r = ToolRegistry::new(64);
2376 r.register_with_source(
2377 Arc::new(Echo),
2378 Policy::Ask,
2379 ToolSource::Plugin("memory-bank".into()),
2380 );
2381 assert_eq!(r.descriptors()[0].source.label(), "plugin:memory-bank");
2382 let json = serde_json::to_value(r.descriptors()).unwrap();
2383 assert_eq!(json[0]["source"], "plugin:memory-bank");
2384 }
2385
2386 #[test]
2387 fn the_schema_document_describes_every_advertised_tool_and_only_those_branches() {
2388 let mut r = ToolRegistry::new(64);
2389 r.register(Arc::new(Echo), Policy::Allow);
2390 r.register_with_source(Arc::new(Other), Policy::Deny, ToolSource::Builtin);
2391 let doc = r.schema_document();
2392 assert_eq!(
2393 doc["$schema"],
2394 "https://json-schema.org/draft/2020-12/schema"
2395 );
2396 assert_eq!(doc["$id"], TOOL_SCHEMA_ID);
2397
2398 let defs = doc["$defs"].as_object().expect("$defs is an object");
2399 assert!(defs.contains_key("echo") && defs.contains_key("other"));
2400 assert_schema_is_sound(&doc, defs);
2401
2402 let branches = doc["oneOf"].as_array().expect("oneOf is an array");
2405 assert_eq!(branches.len(), 1, "{branches:#?}");
2406 assert_eq!(branches[0]["properties"]["name"]["const"], "echo");
2407 assert_eq!(
2408 branches[0]["properties"]["arguments"]["$ref"],
2409 "#/$defs/echo"
2410 );
2411 }
2412
2413 #[test]
2414 fn a_real_argument_object_validates_against_its_own_branch() {
2415 let mut r = ToolRegistry::new(64);
2416 r.register_with_source(Arc::new(Other), Policy::Allow, ToolSource::Builtin);
2417 let doc = r.schema_document();
2418 let defs = doc["$defs"].as_object().unwrap();
2419 assert_schema_is_sound(&doc, defs);
2420
2421 let branch = &doc["oneOf"][0];
2423 let name = branch["properties"]["name"]["const"].as_str().unwrap();
2424 assert_eq!(name, "other");
2425 let target = branch["properties"]["arguments"]["$ref"]
2426 .as_str()
2427 .unwrap()
2428 .strip_prefix("#/$defs/")
2429 .unwrap();
2430 let schema = &defs[target];
2431 let required: Vec<&str> = schema["required"]
2432 .as_array()
2433 .unwrap()
2434 .iter()
2435 .filter_map(|v| v.as_str())
2436 .collect();
2437 assert_eq!(required, ["text"]);
2438 let args = json!({"text": "hi"});
2439 for key in &required {
2440 assert!(args.get(*key).is_some(), "missing {key}");
2441 let want = schema["properties"][*key]["type"].as_str().unwrap();
2442 assert_eq!(
2443 want,
2444 match &args[*key] {
2445 Value::String(_) => "string",
2446 Value::Number(_) => "number",
2447 _ => "other",
2448 }
2449 );
2450 }
2451 }
2452
2453 #[tokio::test]
2454 async fn a_disabled_tool_is_not_offered_and_cannot_be_called() {
2455 let mut r = registry(Policy::Allow);
2456 assert_eq!(r.advertised_names(), ["echo"]);
2457 assert!(r.disable(&["echo".into()]).is_empty());
2458 assert!(r.specs().is_empty(), "not offered to the model");
2459 assert!(r.advertised_names().is_empty());
2460 assert_eq!(r.descriptors().len(), 1);
2462 assert!(!r.descriptors()[0].advertised);
2463 assert_eq!(r.names(), ["echo"]);
2464 let out = r.dispatch("echo", "{\"text\":\"x\"}", &AllowAll).await;
2466 assert!(out.is_error);
2467 assert!(out.output.contains("`[tools] disabled`"), "{}", out.output);
2468 }
2469
2470 #[test]
2471 fn disabling_overrides_an_allow_policy_and_reports_names_that_match_nothing() {
2472 let mut r = ToolRegistry::new(64);
2473 r.register(Arc::new(Echo), Policy::Allow);
2474 let unknown = r.disable(&["echo".into(), "nosuchtool".into()]);
2475 assert_eq!(unknown, ["nosuchtool"], "a typo is reported, not ignored");
2476 assert!(r.specs().is_empty());
2477 let mut r = ToolRegistry::new(64);
2479 r.register(Arc::new(Echo), Policy::Deny);
2480 assert!(!r.descriptors()[0].advertised);
2481 assert!(r.descriptors()[0].source == ToolSource::Builtin);
2482 }
2483
2484 #[test]
2485 fn a_tool_name_with_pointer_characters_still_produces_a_resolving_ref() {
2486 let mut r = ToolRegistry::new(64);
2487 r.register_with_source(Arc::new(Slashed), Policy::Allow, ToolSource::Builtin);
2488 let doc = r.schema_document();
2489 let defs = doc["$defs"].as_object().unwrap();
2490 assert_schema_is_sound(&doc, defs);
2491 }
2492
2493 #[tokio::test]
2499 async fn dispatch_does_not_cap_the_output_the_hooks_will_see() {
2500 let mut r = ToolRegistry::new(8);
2501 r.register(Arc::new(Echo), Policy::Allow);
2502 let long = "x".repeat(64);
2503 let out = r
2504 .dispatch("echo", &json!({"text": long}).to_string(), &AllowAll)
2505 .await;
2506 assert_eq!(
2507 out.output.len(),
2508 64,
2509 "the cap belongs to the caller, after the hooks: {:?}",
2510 out.output
2511 );
2512 let cut = truncate(format!("{} tail", "y".repeat(20)), 8);
2514 assert!(
2515 cut.starts_with("yyyyyyy") && cut.ends_with("[output truncated]"),
2516 "{cut:?}"
2517 );
2518 assert!(
2519 !cut.contains("tail"),
2520 "and the fragment past the cut is gone"
2521 );
2522 }
2523
2524 #[tokio::test]
2525 async fn dispatch_runs_allowed_tool() {
2526 let out = registry(Policy::Allow)
2527 .dispatch("echo", r#"{"text":"hi"}"#, &DenyAll)
2528 .await;
2529 assert_eq!(out, ToolOutcome::ok("hi".into()));
2530 }
2531
2532 #[tokio::test]
2533 async fn dispatch_reports_unknown_tool_bad_json_and_bad_args() {
2534 let r = registry(Policy::Allow);
2535 assert!(r.dispatch("nope", "{}", &AllowAll).await.is_error);
2536 let bad = r.dispatch("echo", "{oops", &AllowAll).await;
2537 assert!(bad.is_error && bad.output.contains("not valid JSON"));
2538 let missing = r.dispatch("echo", "", &AllowAll).await;
2539 assert!(missing.is_error && missing.output.contains("`text`"));
2540 }
2541
2542 #[tokio::test]
2543 async fn deny_policy_blocks_and_hides_tool() {
2544 let r = registry(Policy::Deny);
2545 assert!(r.specs().is_empty());
2546 let out = r.dispatch("echo", r#"{"text":"x"}"#, &AllowAll).await;
2547 assert!(out.is_error && out.output.contains("disabled"));
2548 }
2549
2550 #[tokio::test]
2551 async fn ask_policy_consults_approver() {
2552 let r = registry(Policy::Ask);
2553 let yes = CountingApprover(AtomicUsize::new(0), true);
2554 assert!(!r.dispatch("echo", r#"{"text":"x"}"#, &yes).await.is_error);
2555 assert_eq!(yes.0.load(Ordering::SeqCst), 1);
2556 let no = CountingApprover(AtomicUsize::new(0), false);
2557 let out = r.dispatch("echo", r#"{"text":"x"}"#, &no).await;
2558 assert!(out.is_error && out.output.contains("declined"));
2559 assert_eq!(r.specs().len(), 1);
2560 }
2561
2562 #[tokio::test]
2563 async fn allow_policy_does_not_prompt() {
2564 let a = CountingApprover(AtomicUsize::new(0), false);
2565 registry(Policy::Allow)
2566 .dispatch("echo", r#"{"text":"x"}"#, &a)
2567 .await;
2568 assert_eq!(a.0.load(Ordering::SeqCst), 0);
2569 }
2570
2571 #[tokio::test]
2572 async fn output_is_truncated_on_char_boundary() {
2573 let r = registry(Policy::Allow);
2574 let out = r
2575 .dispatch(
2576 "echo",
2577 &json!({"text": "é".repeat(100)}).to_string(),
2578 &AllowAll,
2579 )
2580 .await;
2581 let out = model_output(&r, out);
2582 assert!(out.ends_with("[output truncated]"), "{out:?}");
2583 assert!(out.len() < 100);
2584 }
2585
2586 fn builtin(dir: &Path, tweak: impl FnOnce(&mut ToolsConfig)) -> ToolRegistry {
2587 let mut cfg = ToolsConfig {
2588 read_file: Policy::Allow,
2589 write_file: Policy::Allow,
2590 shell: Policy::Allow,
2591 fetch: Policy::Deny,
2592 ..ToolsConfig::default()
2593 };
2594 tweak(&mut cfg);
2595 ToolRegistry::from_config(&cfg, dir.to_path_buf())
2596 }
2597
2598 #[tokio::test]
2599 async fn builtin_defaults_are_gated() {
2600 let dir = tempfile::tempdir().unwrap();
2601 let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2602 assert_eq!(
2603 r.names(),
2604 [
2605 "fetch",
2606 "patch",
2607 "read_file",
2608 "search_files",
2609 "shell",
2610 "write_file"
2611 ]
2612 );
2613 let out = r
2615 .dispatch("shell", r#"{"command":"rm -rf everything"}"#, &DenyAll)
2616 .await;
2617 assert!(out.is_error && out.output.contains("declined"));
2618 let out = r
2619 .dispatch("shell", r#"{"command":"echo hi"}"#, &DenyAll)
2620 .await;
2621 assert!(!out.is_error, "ordinary work is not gated: {}", out.output);
2622 let out = r
2625 .dispatch("write_file", r#"{"path":"a","content":"b"}"#, &DenyAll)
2626 .await;
2627 assert!(!out.is_error, "{}", out.output);
2628 assert!(dir.path().join("a").exists());
2629 let out = r
2630 .dispatch(
2631 "write_file",
2632 r#"{"path":"/tmp/escape","content":"b"}"#,
2633 &DenyAll,
2634 )
2635 .await;
2636 assert!(
2637 out.is_error && out.output.contains("outside the workspace"),
2638 "{}",
2639 out.output
2640 );
2641 }
2642
2643 #[tokio::test]
2646 async fn search_files_is_offered_unasked_and_fenced_by_the_workspace() {
2647 let dir = tempfile::tempdir().unwrap();
2648 std::fs::create_dir_all(dir.path().join("src")).unwrap();
2649 std::fs::write(dir.path().join("src/a.rs"), "let needle = 1;\n").unwrap();
2650 let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2651
2652 let listed = r
2653 .descriptors()
2654 .into_iter()
2655 .find(|d| d.name == "search_files")
2656 .expect("the tool is registered");
2657 assert_eq!(listed.policy, Policy::Allow);
2658 assert!(listed.advertised);
2659
2660 let out = r
2661 .dispatch("search_files", r#"{"pattern":"needle"}"#, &DenyAll)
2662 .await;
2663 assert!(!out.is_error, "{}", out.output);
2664 assert!(out.output.contains("a.rs:1"), "{}", out.output);
2665
2666 let out = r
2667 .dispatch(
2668 "search_files",
2669 r#"{"pattern":"needle","path":".."}"#,
2670 &DenyAll,
2671 )
2672 .await;
2673 assert!(
2674 out.is_error && out.output.contains("outside the workspace"),
2675 "{}",
2676 out.output
2677 );
2678 }
2679
2680 #[tokio::test]
2681 async fn file_tools_round_trip_and_confine() {
2682 let dir = tempfile::tempdir().unwrap();
2683 let r = builtin(dir.path(), |_| {});
2684 let w = r
2685 .dispatch(
2686 "write_file",
2687 r#"{"path":"sub/a.txt","content":"hello"}"#,
2688 &DenyAll,
2689 )
2690 .await;
2691 assert!(!w.is_error, "{}", w.output);
2692 let rd = r
2693 .dispatch("read_file", r#"{"path":"sub/a.txt"}"#, &DenyAll)
2694 .await;
2695 assert_eq!(rd.output, "hello");
2696 for bad in ["../escape.txt", "/etc/passwd", "sub/../../x"] {
2697 let out = r
2698 .dispatch("read_file", &json!({"path": bad}).to_string(), &DenyAll)
2699 .await;
2700 assert!(
2701 out.is_error && out.output.contains("outside"),
2702 "{bad}: {}",
2703 out.output
2704 );
2705 }
2706 let out = r
2707 .dispatch(
2708 "write_file",
2709 r#"{"path":"../escape.txt","content":"x"}"#,
2710 &DenyAll,
2711 )
2712 .await;
2713 assert!(out.is_error);
2714 }
2715
2716 #[cfg(unix)]
2717 #[tokio::test]
2718 async fn symlink_escape_is_blocked() {
2719 let dir = tempfile::tempdir().unwrap();
2720 let outside = tempfile::tempdir().unwrap();
2721 std::fs::write(outside.path().join("secret"), "s").unwrap();
2722 std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
2723 let r = builtin(dir.path(), |_| {});
2724 let out = r
2725 .dispatch("read_file", r#"{"path":"link/secret"}"#, &DenyAll)
2726 .await;
2727 assert!(out.is_error && out.output.contains("outside"));
2728 }
2729
2730 #[cfg(unix)]
2731 #[tokio::test]
2732 async fn dangling_symlink_cannot_be_written_through() {
2733 let dir = tempfile::tempdir().unwrap();
2734 let outside = tempfile::tempdir().unwrap();
2735 let target = outside.path().join("created");
2736 std::os::unix::fs::symlink(&target, dir.path().join("evil")).unwrap();
2737 let r = builtin(dir.path(), |_| {});
2738 let out = r
2739 .dispatch("write_file", r#"{"path":"evil","content":"x"}"#, &DenyAll)
2740 .await;
2741 assert!(out.is_error, "{}", out.output);
2742 assert!(!target.exists());
2743 }
2744
2745 #[tokio::test]
2746 async fn read_file_is_bounded_and_regular_files_only() {
2747 let dir = tempfile::tempdir().unwrap();
2748 std::fs::write(dir.path().join("big.txt"), "é".repeat(1000)).unwrap();
2749 std::fs::create_dir(dir.path().join("d")).unwrap();
2750 let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2751 let out = r
2752 .dispatch("read_file", r#"{"path":"big.txt"}"#, &DenyAll)
2753 .await;
2754 let shown = model_output(&r, out);
2755 assert!(shown.ends_with("[output truncated]"), "{shown:?}");
2756 assert!(shown.len() < 100);
2757 let out = r.dispatch("read_file", r#"{"path":"d"}"#, &DenyAll).await;
2758 assert!(out.is_error && out.output.contains("not a regular"));
2759 }
2760
2761 #[cfg(unix)]
2766 #[tokio::test]
2767 async fn a_fifo_is_refused_instead_of_hanging_the_turn() {
2768 let dir = tempfile::tempdir().unwrap();
2769 assert!(std::process::Command::new("mkfifo")
2770 .arg(dir.path().join("pipe"))
2771 .status()
2772 .map(|s| s.success())
2773 .unwrap_or(false));
2774 let r = builtin(dir.path(), |_| {});
2775 let out = tokio::time::timeout(
2776 std::time::Duration::from_secs(3),
2777 r.dispatch("read_file", r#"{"path":"pipe"}"#, &DenyAll),
2778 )
2779 .await
2780 .expect("a FIFO must not block the read");
2781 assert!(out.is_error, "{}", out.output);
2782 assert!(out.output.contains("not a regular"), "{}", out.output);
2783 }
2784
2785 #[tokio::test]
2789 async fn a_binary_file_is_not_text_at_any_size() {
2790 let dir = tempfile::tempdir().unwrap();
2791 let mut binary = vec![0u8; 200];
2792 binary[10] = 0xff;
2793 std::fs::write(dir.path().join("small.bin"), &binary[..50]).unwrap();
2794 std::fs::write(dir.path().join("big.bin"), &binary).unwrap();
2795 std::fs::write(dir.path().join("text.txt"), "aaéé".repeat(40)).unwrap();
2797 let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2798
2799 let out = r
2800 .dispatch("read_file", r#"{"path":"small.bin"}"#, &DenyAll)
2801 .await;
2802 assert!(
2803 out.is_error,
2804 "an under-cap binary is not text: {}",
2805 out.output
2806 );
2807 let out = r
2808 .dispatch("read_file", r#"{"path":"big.bin"}"#, &DenyAll)
2809 .await;
2810 assert!(
2811 out.is_error,
2812 "an over-cap binary is not text either: {}",
2813 out.output
2814 );
2815 let out = r
2817 .dispatch("read_file", r#"{"path":"text.txt"}"#, &DenyAll)
2818 .await;
2819 assert!(!out.is_error, "{}", out.output);
2820 assert!(out.output.starts_with("aaé"), "{}", out.output);
2821 }
2822
2823 #[cfg(unix)]
2824 #[tokio::test]
2825 async fn shell_output_is_capped_and_flooding_child_stops() {
2826 let dir = tempfile::tempdir().unwrap();
2827 let r = builtin(dir.path(), |c| {
2828 c.max_output_bytes = 256;
2829 c.shell_timeout_secs = 10;
2830 });
2831 let out = r.dispatch("shell", r#"{"command":"yes"}"#, &DenyAll).await;
2832 assert!(!out.is_error, "{}", out.output);
2833 let shown = model_output(&r, out);
2834 assert!(
2835 shown.contains("[truncated]") || shown.contains("[output truncated]"),
2836 "{shown:?}"
2837 );
2838 assert!(shown.len() < 300, "{} bytes", shown.len());
2839 }
2840
2841 #[cfg(unix)]
2846 #[tokio::test]
2847 async fn a_background_child_does_not_hold_the_turn() {
2848 let dir = tempfile::tempdir().unwrap();
2849 let r = builtin(dir.path(), |c| {
2850 c.max_output_bytes = 4096;
2851 c.shell_timeout_secs = 30;
2852 c.shell_isolate = crate::config::ShellIsolate::Off;
2855 });
2856 let asked = std::time::Instant::now();
2857 let out = tokio::time::timeout(
2858 std::time::Duration::from_secs(3),
2859 r.dispatch("shell", r#"{"command":"sleep 5 & echo started"}"#, &DenyAll),
2860 )
2861 .await
2862 .expect("a background child must not hold the call — `#368`");
2863 assert!(!out.is_error, "{}", out.output);
2864 assert!(
2865 out.output.contains("started"),
2866 "what the child itself printed: {}",
2867 out.output
2868 );
2869 assert!(
2870 out.output.contains("still holds its output pipe"),
2871 "the result says why it stopped reading: {}",
2872 out.output
2873 );
2874 assert!(asked.elapsed() < std::time::Duration::from_secs(3));
2875 }
2876
2877 #[cfg(unix)]
2878 fn process_alive(pid: i32) -> bool {
2879 std::fs::read_to_string(format!("/proc/{pid}/stat"))
2885 .ok()
2886 .and_then(|s| {
2887 s.rsplit(')')
2888 .next()
2889 .map(|state| !state.trim_start().starts_with(['Z', 'X']))
2890 })
2891 .unwrap_or(false)
2892 }
2893
2894 #[cfg(unix)]
2895 async fn timeout_kills_grandchild(command: &str, grace: Duration) {
2896 let dir = tempfile::tempdir().unwrap();
2897 let mut r = ToolRegistry::new(4096);
2898 r.register(
2899 Arc::new(Shell {
2900 root: std::fs::canonicalize(dir.path()).unwrap(),
2901 skill_roots: Vec::new(),
2902 scripts_dir: None,
2903 timeout: Duration::from_secs(1),
2904 allowlist: Vec::new(),
2905 max_bytes: 4096,
2906 kill_grace: grace,
2907 sandbox: crate::sandbox::Sandbox::off(),
2908 ask: crate::config::ShellAsk::Dangerous,
2909 }),
2910 Policy::Allow,
2911 );
2912 let started = std::time::Instant::now();
2913 let out = r
2914 .dispatch("shell", &json!({"command": command}).to_string(), &DenyAll)
2915 .await;
2916 assert!(
2917 out.is_error && out.output.contains("timed out"),
2918 "{}",
2919 out.output
2920 );
2921 let pid: i32 = std::fs::read_to_string(dir.path().join("child.pid"))
2922 .unwrap()
2923 .trim()
2924 .parse()
2925 .unwrap();
2926 for _ in 0..100 {
2927 if !process_alive(pid) {
2928 break;
2929 }
2930 tokio::time::sleep(Duration::from_millis(50)).await;
2931 }
2932 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default();
2936 assert!(
2937 !process_alive(pid),
2938 "grandchild {pid} survived the timeout after {:.2}s; stat = {stat:?}",
2939 started.elapsed().as_secs_f32()
2940 );
2941 assert!(started.elapsed() < Duration::from_secs(8));
2942 }
2943
2944 #[cfg(unix)]
2945 #[tokio::test]
2946 async fn timeout_terminates_background_grandchild() {
2947 timeout_kills_grandchild(
2948 "sleep 300 & echo $! > child.pid; wait",
2949 Duration::from_secs(2),
2950 )
2951 .await;
2952 }
2953
2954 #[cfg(unix)]
2955 #[tokio::test]
2956 async fn timeout_terminates_a_grandchild_that_left_the_process_group() {
2957 timeout_kills_grandchild(
2960 "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait",
2961 Duration::from_secs(2),
2962 )
2963 .await;
2964 }
2965
2966 #[cfg(unix)]
2967 #[tokio::test]
2968 async fn a_cancelled_run_kills_a_grandchild_that_left_the_process_group() {
2969 let dir = tempfile::tempdir().unwrap();
2973 let mut r = ToolRegistry::new(4096);
2974 r.register(
2975 Arc::new(Shell {
2976 root: std::fs::canonicalize(dir.path()).unwrap(),
2977 skill_roots: Vec::new(),
2978 scripts_dir: None,
2979 timeout: Duration::from_secs(30),
2980 allowlist: Vec::new(),
2981 max_bytes: 4096,
2982 kill_grace: Duration::from_secs(2),
2983 sandbox: crate::sandbox::Sandbox::off(),
2984 ask: crate::config::ShellAsk::Dangerous,
2985 }),
2986 Policy::Allow,
2987 );
2988 let registry = Arc::new(r);
2989 let call = {
2990 let registry = Arc::clone(®istry);
2991 let args = json!({
2992 "command": "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait"
2993 })
2994 .to_string();
2995 tokio::spawn(async move { registry.dispatch("shell", &args, &DenyAll).await })
2996 };
2997 let pid = wait_for_pid(&dir.path().join("child.pid")).await;
2999 call.abort();
3000 let _ = call.await;
3001 for _ in 0..100 {
3002 if !process_alive(pid) {
3003 break;
3004 }
3005 tokio::time::sleep(Duration::from_millis(50)).await;
3006 }
3007 assert!(
3008 !process_alive(pid),
3009 "grandchild {pid} survived the drop: {:#?}",
3010 std::fs::read_to_string(format!("/proc/{pid}/stat"))
3011 );
3012 }
3013
3014 #[cfg(unix)]
3016 async fn wait_for_pid(path: &std::path::Path) -> i32 {
3017 for _ in 0..100 {
3018 if let Ok(text) = std::fs::read_to_string(path) {
3019 if let Ok(pid) = text.trim().parse::<i32>() {
3020 return pid;
3021 }
3022 }
3023 tokio::time::sleep(Duration::from_millis(20)).await;
3024 }
3025 panic!("the script never wrote {}", path.display());
3026 }
3027
3028 #[cfg(unix)]
3029 #[tokio::test]
3030 async fn timeout_escalates_to_sigkill_when_sigterm_is_ignored() {
3031 timeout_kills_grandchild(
3032 "trap '' TERM; sleep 300 & echo $! > child.pid; wait",
3033 Duration::from_millis(300),
3034 )
3035 .await;
3036 }
3037
3038 #[cfg(unix)]
3039 #[tokio::test]
3040 async fn shell_runs_in_workspace_with_timeout_and_allowlist() {
3041 let dir = tempfile::tempdir().unwrap();
3042 let r = builtin(dir.path(), |c| c.shell_timeout_secs = 1);
3043 let out = r
3044 .dispatch("shell", r#"{"command":"echo hi; pwd"}"#, &DenyAll)
3045 .await;
3046 assert!(!out.is_error);
3047 assert!(out.output.contains("exit code: 0") && out.output.contains("hi"));
3048 let slow = r
3049 .dispatch("shell", r#"{"command":"sleep 5"}"#, &DenyAll)
3050 .await;
3051 assert!(slow.is_error && slow.output.contains("timed out"));
3052
3053 let r = builtin(dir.path(), |c| c.shell_allowlist = vec!["echo".into()]);
3054 let ok = r
3055 .dispatch("shell", r#"{"command":"echo a b"}"#, &DenyAll)
3056 .await;
3057 assert!(ok.output.contains("a b"), "{}", ok.output);
3058 for bad in ["ls", "echo hi; ls", "echo $(ls)"] {
3059 let out = r
3060 .dispatch("shell", &json!({"command": bad}).to_string(), &DenyAll)
3061 .await;
3062 assert!(out.is_error, "{bad}");
3063 }
3064 }
3065
3066 #[cfg(unix)]
3067 fn shell_with_skills(workspace: &Path, skills: &Path) -> ToolRegistry {
3068 let cfg = ToolsConfig {
3069 shell: Policy::Allow,
3070 ..ToolsConfig::default()
3071 };
3072 let roots = vec![crate::skills::Root {
3073 source: crate::skills::Source::Shared,
3074 dir: skills.to_path_buf(),
3075 }];
3076 ToolRegistry::from_config_with(&cfg, workspace.to_path_buf(), roots)
3077 }
3078
3079 #[cfg(unix)]
3080 async fn shell_in(r: &ToolRegistry, command: &str, cwd: &str) -> ToolOutcome {
3081 r.dispatch(
3082 "shell",
3083 &json!({"command": command, "cwd": cwd}).to_string(),
3084 &DenyAll,
3085 )
3086 .await
3087 }
3088
3089 #[cfg(unix)]
3090 #[tokio::test]
3091 async fn shell_cwd_is_accepted_inside_the_workspace_and_refused_elsewhere() {
3092 let tmp = tempfile::tempdir().unwrap();
3093 let workspace = tmp.path().join("ws");
3094 std::fs::create_dir_all(workspace.join("sub")).unwrap();
3095 std::fs::write(workspace.join("file.txt"), "x").unwrap();
3096 let outside = tmp.path().join("outside");
3097 std::fs::create_dir_all(&outside).unwrap();
3098 std::os::unix::fs::symlink(&outside, workspace.join("link")).unwrap();
3099 let r = shell_with_skills(&workspace, &tmp.path().join("skills"));
3100
3101 let out = shell_in(&r, "pwd", "sub").await;
3102 assert!(!out.is_error, "{}", out.output);
3103 assert!(out.output.contains("/ws/sub"), "{}", out.output);
3104 let absolute = workspace.join("sub").display().to_string();
3105 assert!(!shell_in(&r, "pwd", &absolute).await.is_error);
3106
3107 for (cwd, why) in [
3108 ("/etc", "outside the workspace"),
3109 ("..", "outside the workspace"),
3110 ("link", "outside the workspace"),
3111 ("missing", "cannot be resolved"),
3112 ("file.txt", "not a directory"),
3113 (" ", "empty"),
3114 ] {
3115 let out = shell_in(&r, "pwd", cwd).await;
3116 assert!(out.is_error, "{cwd:?} should be refused: {}", out.output);
3117 assert!(
3118 out.output.contains(&format!("cwd `{cwd}` refused")),
3119 "names what was refused: {}",
3120 out.output
3121 );
3122 assert!(out.output.contains(why), "{cwd:?}, {why}: {}", out.output);
3123 }
3124 }
3125
3126 #[cfg(unix)]
3127 #[tokio::test]
3128 async fn a_skills_own_script_runs_from_its_directory_but_a_broken_skills_does_not() {
3129 let tmp = tempfile::tempdir().unwrap();
3130 let workspace = tmp.path().join("ws");
3131 std::fs::create_dir_all(&workspace).unwrap();
3132 let skills = tmp.path().join("skills");
3133 let good = skills.join("backup");
3134 std::fs::create_dir_all(good.join("scripts")).unwrap();
3135 std::fs::write(
3136 good.join("SKILL.md"),
3137 "---\nname: backup\n---\nRun `bash scripts/backup.sh`.\n",
3138 )
3139 .unwrap();
3140 std::fs::write(
3141 good.join("scripts/backup.sh"),
3142 "echo backed up from $(basename \"$PWD\")\n",
3143 )
3144 .unwrap();
3145 let broken = skills.join("broken");
3146 std::fs::create_dir_all(&broken).unwrap();
3147 std::fs::write(
3148 broken.join("SKILL.md"),
3149 "---\ndescription: no name\n---\nbody\n",
3150 )
3151 .unwrap();
3152 let r = shell_with_skills(&workspace, &skills);
3153
3154 let out = shell_in(&r, "bash scripts/backup.sh", &good.display().to_string()).await;
3155 assert!(!out.is_error, "{}", out.output);
3156 assert!(
3157 out.output.contains("backed up from backup"),
3158 "{}",
3159 out.output
3160 );
3161 let nested = good.join("scripts").display().to_string();
3162 assert!(!shell_in(&r, "pwd", &nested).await.is_error);
3163
3164 let out = shell_in(&r, "pwd", &skills.display().to_string()).await;
3165 assert!(
3166 out.is_error,
3167 "the skills directory is not a skill's directory"
3168 );
3169 let out = shell_in(&r, "pwd", &broken.display().to_string()).await;
3170 assert!(out.is_error, "{}", out.output);
3171 assert!(
3172 out.output.contains("outside every skill's directory"),
3173 "{}",
3174 out.output
3175 );
3176 }
3177
3178 #[cfg(unix)]
3179 fn shell_with_scripts(workspace: &Path, scripts: &Path, allowlist: &[&str]) -> ToolRegistry {
3180 let cfg = ToolsConfig {
3181 shell: Policy::Allow,
3182 shell_allowlist: allowlist.iter().map(|s| s.to_string()).collect(),
3183 ..ToolsConfig::default()
3184 };
3185 ToolRegistry::from_config_full(
3186 &cfg,
3187 workspace.to_path_buf(),
3188 Vec::new(),
3189 Some(scripts.to_path_buf()),
3190 )
3191 }
3192
3193 #[cfg(unix)]
3194 #[tokio::test]
3195 async fn shell_finds_a_script_as_a_bare_command_and_is_told_where_the_scripts_are() {
3196 use std::os::unix::fs::PermissionsExt;
3197 let tmp = tempfile::tempdir().unwrap();
3198 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3199 std::fs::create_dir_all(&workspace).unwrap();
3200 std::fs::create_dir_all(&scripts).unwrap();
3201 let script = scripts.join("hello-script");
3202 std::fs::write(&script, "#!/bin/sh\necho hello from $1\n").unwrap();
3203 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3204 let imposter = scripts.join("date");
3208 std::fs::write(&imposter, "#!/bin/sh\necho fake date\n").unwrap();
3209 std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3210 let r = shell_with_scripts(&workspace, &scripts, &[]);
3211
3212 let out = r
3213 .dispatch(
3214 "shell",
3215 &json!({"command": "hello-script world; date; echo dir=$ECLIPSE_SCRIPTS_DIR; \
3216 echo last=${PATH##*:}"})
3217 .to_string(),
3218 &DenyAll,
3219 )
3220 .await;
3221 assert!(!out.is_error, "{}", out.output);
3222 let dir = scripts.display().to_string();
3223 assert!(out.output.contains("hello from world"), "{}", out.output);
3224 assert!(out.output.contains(&format!("dir={dir}")), "{}", out.output);
3225 assert!(
3226 out.output.contains(&format!("last={dir}")),
3227 "the scripts directory is on PATH, last: {}",
3228 out.output
3229 );
3230 assert!(
3231 !out.output.contains("fake date"),
3232 "a real command wins over a script of the same name: {}",
3233 out.output
3234 );
3235 }
3236
3237 #[cfg(unix)]
3238 #[tokio::test]
3239 async fn an_allowlisted_shell_does_not_let_a_script_take_the_place_of_a_program() {
3240 use std::os::unix::fs::PermissionsExt;
3241 let tmp = tempfile::tempdir().unwrap();
3242 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3243 std::fs::create_dir_all(&workspace).unwrap();
3244 std::fs::create_dir_all(&scripts).unwrap();
3245 let imposter = scripts.join("echo");
3246 std::fs::write(&imposter, "#!/bin/sh\necho imposter\n").unwrap();
3247 std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3248 let r = shell_with_scripts(&workspace, &scripts, &["echo", "env"]);
3249
3250 let out = r
3251 .dispatch("shell", r#"{"command":"echo real"}"#, &DenyAll)
3252 .await;
3253 assert!(
3254 out.output.contains("real") && !out.output.contains("imposter"),
3255 "{}",
3256 out.output
3257 );
3258 let out = r.dispatch("shell", r#"{"command":"env"}"#, &DenyAll).await;
3259 assert!(
3260 out.output
3261 .contains(&format!("ECLIPSE_SCRIPTS_DIR={}", scripts.display())),
3262 "{}",
3263 out.output
3264 );
3265 }
3266
3267 #[cfg(unix)]
3268 #[tokio::test]
3269 async fn shell_cwd_accepts_the_scripts_directory_and_the_refusal_names_it() {
3270 let tmp = tempfile::tempdir().unwrap();
3271 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3272 std::fs::create_dir_all(&workspace).unwrap();
3273 std::fs::create_dir_all(&scripts).unwrap();
3274 let r = shell_with_scripts(&workspace, &scripts, &[]);
3275
3276 let out = shell_in(&r, "pwd", &scripts.display().to_string()).await;
3277 assert!(!out.is_error, "{}", out.output);
3278 assert!(out.output.contains("/scripts"), "{}", out.output);
3279
3280 let out = shell_in(&r, "pwd", "/etc").await;
3281 assert!(
3282 out.is_error
3283 && out.output.contains("outside the workspace")
3284 && out.output.contains("outside the scripts directory")
3285 && out.output.contains("outside every skill's directory"),
3286 "{}",
3287 out.output
3288 );
3289 }
3290
3291 fn writer(workspace: &Path, scripts: &Path) -> ToolRegistry {
3292 let cfg = ToolsConfig {
3293 write_file: Policy::Allow,
3294 ..ToolsConfig::default()
3295 };
3296 ToolRegistry::from_config_full(
3297 &cfg,
3298 workspace.to_path_buf(),
3299 Vec::new(),
3300 Some(scripts.to_path_buf()),
3301 )
3302 }
3303
3304 async fn write_to(r: &ToolRegistry, path: &str) -> ToolOutcome {
3305 r.dispatch(
3306 "write_file",
3307 &json!({"path": path, "content": "#!/bin/sh\n"}).to_string(),
3308 &DenyAll,
3309 )
3310 .await
3311 }
3312
3313 #[tokio::test]
3314 async fn write_file_writes_in_the_scripts_directory_even_before_it_exists() {
3315 let tmp = tempfile::tempdir().unwrap();
3316 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("cfg/scripts"));
3317 std::fs::create_dir_all(&workspace).unwrap();
3318 let r = writer(&workspace, &scripts);
3319
3320 let target = scripts.join("backup.sh");
3321 let out = write_to(&r, &target.display().to_string()).await;
3322 assert!(!out.is_error, "{}", out.output);
3323 assert_eq!(std::fs::read_to_string(&target).unwrap(), "#!/bin/sh\n");
3324
3325 let out = write_to(&r, &format!("{}/sub/../again.sh", scripts.display())).await;
3326 assert!(!out.is_error, "{}", out.output);
3327 assert!(scripts.join("again.sh").is_file());
3328 }
3329
3330 #[tokio::test]
3331 async fn write_file_still_writes_in_the_workspace_when_scripts_are_configured() {
3332 let tmp = tempfile::tempdir().unwrap();
3333 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3334 std::fs::create_dir_all(&workspace).unwrap();
3335 let r = writer(&workspace, &scripts);
3336 let out = write_to(&r, "notes/a.txt").await;
3337 assert!(!out.is_error, "{}", out.output);
3338 assert!(workspace.join("notes/a.txt").is_file());
3339 assert!(!scripts.exists(), "a workspace write must not create it");
3340 }
3341
3342 #[tokio::test]
3346 async fn a_big_file_is_not_clobbered_by_accident() {
3347 let dir = tempfile::tempdir().unwrap();
3348 let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(100);
3349
3350 let big = dir.path().join("index.html");
3351 std::fs::write(&big, "x".repeat(500)).unwrap();
3352
3353 let refused = tool
3354 .call(json!({"path": "index.html", "content": "tiny"}))
3355 .await
3356 .unwrap_err()
3357 .to_string();
3358 assert!(refused.contains("already exists at 500 bytes"), "{refused}");
3359 assert!(
3360 refused.contains("`patch`"),
3361 "it names the cheap path: {refused}"
3362 );
3363 assert!(
3364 refused.contains("force: true"),
3365 "and how to mean it: {refused}"
3366 );
3367 assert_eq!(
3368 std::fs::read_to_string(&big).unwrap().len(),
3369 500,
3370 "nothing was written"
3371 );
3372
3373 tool.call(json!({"path": "index.html", "content": "tiny", "force": true}))
3375 .await
3376 .unwrap();
3377 assert_eq!(std::fs::read_to_string(&big).unwrap(), "tiny");
3378
3379 let small = dir.path().join("notes.md");
3381 tool.call(json!({"path": "notes.md", "content": "one"}))
3382 .await
3383 .unwrap();
3384 tool.call(json!({"path": "notes.md", "content": "two"}))
3385 .await
3386 .unwrap();
3387 assert_eq!(std::fs::read_to_string(&small).unwrap(), "two");
3388
3389 tool.call(json!({"path": "fresh.html", "content": "y".repeat(400)}))
3391 .await
3392 .unwrap();
3393 assert!(dir.path().join("fresh.html").exists());
3394
3395 let loose = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(0);
3397 loose
3398 .call(json!({"path": "index.html", "content": "free"}))
3399 .await
3400 .unwrap();
3401 assert_eq!(std::fs::read_to_string(&big).unwrap(), "free");
3402 }
3403
3404 #[tokio::test]
3407 async fn the_guard_refuses_at_the_threshold_not_only_above_it() {
3408 let dir = tempfile::tempdir().unwrap();
3409 let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(64);
3410
3411 std::fs::write(dir.path().join("exact.txt"), "x".repeat(64)).unwrap();
3413 let refused = tool
3414 .call(json!({"path": "exact.txt", "content": "y"}))
3415 .await
3416 .unwrap_err()
3417 .to_string();
3418 assert!(refused.contains("already exists at 64 bytes"), "{refused}");
3419 assert_eq!(
3420 std::fs::read_to_string(dir.path().join("exact.txt"))
3421 .unwrap()
3422 .len(),
3423 64,
3424 "nothing was written"
3425 );
3426
3427 std::fs::write(dir.path().join("under.txt"), "x".repeat(63)).unwrap();
3429 tool.call(json!({"path": "under.txt", "content": "y"}))
3430 .await
3431 .unwrap();
3432 assert_eq!(
3433 std::fs::read_to_string(dir.path().join("under.txt")).unwrap(),
3434 "y"
3435 );
3436 }
3437
3438 #[cfg(unix)]
3439 #[tokio::test]
3440 async fn write_file_refuses_everywhere_else_and_names_both_roots() {
3441 let tmp = tempfile::tempdir().unwrap();
3442 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3443 let elsewhere = tmp.path().join("elsewhere");
3444 std::fs::create_dir_all(&workspace).unwrap();
3445 std::fs::create_dir_all(&scripts).unwrap();
3446 std::fs::create_dir_all(&elsewhere).unwrap();
3447 std::os::unix::fs::symlink(&elsewhere, scripts.join("link")).unwrap();
3448 let r = writer(&workspace, &scripts);
3449
3450 let sibling = format!("{}-other/x.sh", scripts.display());
3451 for requested in [
3452 "/etc/eclipse-test".to_string(),
3453 elsewhere.join("x.sh").display().to_string(),
3454 format!("{}/../escape.sh", scripts.display()),
3455 format!("{}/link/x.sh", scripts.display()),
3456 sibling,
3457 ] {
3458 let out = write_to(&r, &requested).await;
3459 assert!(out.is_error, "{requested} should be refused");
3460 assert!(
3461 out.output.contains(&workspace.display().to_string())
3462 && out.output.contains(&scripts.display().to_string()),
3463 "{requested}: {}",
3464 out.output
3465 );
3466 }
3467 assert!(!elsewhere.join("x.sh").exists());
3468 assert!(!tmp.path().join("escape.sh").exists());
3469 }
3470
3471 #[test]
3472 fn the_approval_line_for_write_file_says_when_the_destination_is_the_scripts_directory() {
3473 let tmp = tempfile::tempdir().unwrap();
3474 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3475 let tool = WriteFile::new(workspace, Some(scripts.clone()));
3476 let line = tool.describe_call(
3477 &json!({"path": scripts.join("a.sh").display().to_string(), "content": "x"}),
3478 );
3479 assert!(line.ends_with("(scripts directory)"), "{line}");
3480 let line = tool.describe_call(&json!({"path": "a.txt", "content": "x"}));
3481 assert!(!line.contains("scripts"), "{line}");
3482 }
3483
3484 #[cfg(unix)]
3485 #[tokio::test]
3486 async fn shell_without_a_cwd_still_runs_in_the_workspace_root() {
3487 let tmp = tempfile::tempdir().unwrap();
3488 let r = shell_with_skills(tmp.path(), &tmp.path().join("skills"));
3489 let out = r.dispatch("shell", r#"{"command":"pwd"}"#, &DenyAll).await;
3490 let root = std::fs::canonicalize(tmp.path()).unwrap();
3491 assert!(
3492 out.output.contains(&root.display().to_string()),
3493 "{}",
3494 out.output
3495 );
3496 let out = r
3497 .dispatch("shell", r#"{"command":"pwd","cwd":7}"#, &DenyAll)
3498 .await;
3499 assert!(
3500 out.is_error && out.output.contains("`cwd` must be a string"),
3501 "{}",
3502 out.output
3503 );
3504 }
3505
3506 #[tokio::test]
3507 async fn fetch_rejects_non_http_schemes() {
3508 let dir = tempfile::tempdir().unwrap();
3509 let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3510 let out = r
3511 .dispatch("fetch", r#"{"url":"file:///etc/passwd"}"#, &DenyAll)
3512 .await;
3513 assert!(out.is_error && out.output.contains("http"));
3514 }
3515
3516 #[tokio::test]
3517 async fn fetch_blocks_internal_targets_before_connecting() {
3518 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3520 let port = listener.local_addr().unwrap().port();
3521 let dir = tempfile::tempdir().unwrap();
3522 let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3523 for url in [
3524 format!("http://127.0.0.1:{port}/"),
3525 format!("http://localhost:{port}/"),
3526 format!("http://svc.localhost:{port}/"),
3527 format!("http://[::1]:{port}/"),
3528 format!("http://[::ffff:127.0.0.1]:{port}/"),
3529 format!("http://2130706433:{port}/"),
3530 "http://169.254.169.254/latest/meta-data/".to_string(),
3531 "http://8.8.8.8/".to_string(),
3532 ] {
3533 let out = r
3534 .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3535 .await;
3536 assert!(
3537 out.is_error && out.output.contains("blocked"),
3538 "{url}: {}",
3539 out.output
3540 );
3541 }
3542 let accepted = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;
3543 assert!(accepted.is_err(), "blocked fetch connected anyway");
3544 }
3545
3546 #[tokio::test]
3547 async fn fetch_does_not_follow_redirects() {
3548 use tokio::io::{AsyncReadExt, AsyncWriteExt};
3549 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3550 let url = format!("http://{}/", listener.local_addr().unwrap());
3551 let server = tokio::spawn(async move {
3552 let (mut s, _) = listener.accept().await.unwrap();
3553 let mut buf = [0u8; 1024];
3554 let _ = s.read(&mut buf).await;
3555 s.write_all(
3556 b"HTTP/1.1 302 Found\r\nlocation: http://127.0.0.1:9/elsewhere\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
3557 )
3558 .await
3559 .unwrap();
3560 });
3561 let mut r = ToolRegistry::new(4096);
3562 r.register(
3563 Arc::new(Fetch {
3564 allow_internal: true,
3565 ..Fetch::new(Duration::from_secs(5), 4096)
3566 }),
3567 Policy::Allow,
3568 );
3569 let out = r
3570 .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3571 .await;
3572 server.await.unwrap();
3573 assert!(!out.is_error, "{}", out.output);
3574 assert!(
3575 out.output.contains("302")
3576 && out
3577 .output
3578 .contains("location: http://127.0.0.1:9/elsewhere")
3579 );
3580 }
3581
3582 async fn fetch_from_mock(
3584 headers: &'static str,
3585 body: &'static str,
3586 html: FetchHtml,
3587 args: Value,
3588 ) -> ToolOutcome {
3589 use tokio::io::{AsyncReadExt, AsyncWriteExt};
3590 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3591 let url = format!("http://{}/", listener.local_addr().unwrap());
3592 let server = tokio::spawn(async move {
3593 let (mut s, _) = listener.accept().await.unwrap();
3594 let mut buf = [0u8; 1024];
3595 let _ = s.read(&mut buf).await;
3596 let resp = format!(
3597 "HTTP/1.1 200 OK\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
3598 body.len()
3599 );
3600 s.write_all(resp.as_bytes()).await.unwrap();
3601 });
3602 let mut r = ToolRegistry::new(4096);
3603 r.register(
3604 Arc::new(
3605 Fetch {
3606 allow_internal: true,
3607 ..Fetch::new(Duration::from_secs(5), 4096)
3608 }
3609 .with_html(html),
3610 ),
3611 Policy::Allow,
3612 );
3613 let mut args = args;
3614 args["url"] = json!(url);
3615 let out = r.dispatch("fetch", &args.to_string(), &DenyAll).await;
3616 server.await.unwrap();
3617 out
3618 }
3619
3620 const PAGE: &str = "<!doctype html><html><head><title>T</title><script>evil()</script></head>\
3621 <body><h1>Hello</h1><p>one & two</p></body></html>";
3622
3623 #[tokio::test]
3624 async fn fetch_converts_html_to_text_by_default() {
3625 let out = fetch_from_mock(
3626 "content-type: text/html; charset=utf-8\r\n",
3627 PAGE,
3628 FetchHtml::Text,
3629 json!({}),
3630 )
3631 .await;
3632 assert!(!out.is_error, "{}", out.output);
3633 assert!(out.output.starts_with("status: 200 OK\n"), "{}", out.output);
3634 assert!(
3635 out.output.contains("note: HTML converted"),
3636 "{}",
3637 out.output
3638 );
3639 assert!(
3640 out.output.ends_with("T\n\nHello\n\none & two"),
3641 "{}",
3642 out.output
3643 );
3644 assert!(!out.output.contains("<p>") && !out.output.contains("evil"));
3645
3646 let out = fetch_from_mock("", PAGE, FetchHtml::Text, json!({})).await;
3648 assert!(out.output.contains("Hello") && !out.output.contains("<h1>"));
3649 }
3650
3651 #[tokio::test]
3652 async fn fetch_can_return_raw_html_per_call_or_by_config() {
3653 let ct = "content-type: text/html\r\n";
3654 let out = fetch_from_mock(ct, PAGE, FetchHtml::Text, json!({"raw": true})).await;
3655 assert!(out.output.contains("<h1>Hello</h1>") && !out.output.contains("note: HTML"));
3656 let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({})).await;
3657 assert!(
3658 out.output.contains("<script>evil()</script>"),
3659 "{}",
3660 out.output
3661 );
3662 let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({"raw": false})).await;
3663 assert!(out.output.contains("note: HTML converted") && !out.output.contains("<h1>"));
3664 }
3665
3666 #[tokio::test]
3667 async fn fetch_leaves_non_html_bodies_alone() {
3668 let out = fetch_from_mock(
3669 "content-type: application/json\r\n",
3670 r#"{"html":"<p>x</p>"}"#,
3671 FetchHtml::Text,
3672 json!({}),
3673 )
3674 .await;
3675 assert!(
3676 out.output.ends_with(r#"{"html":"<p>x</p>"}"#),
3677 "{}",
3678 out.output
3679 );
3680 assert!(!out.output.contains("note:"));
3681 }
3682
3683 #[cfg(unix)]
3687 fn bwrap_present() -> bool {
3688 std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
3689 .any(|d| d.join("bwrap").is_file())
3690 }
3691
3692 #[cfg(unix)]
3694 fn any_process(marker: &str) -> bool {
3695 std::process::Command::new("pgrep")
3696 .arg("-f")
3697 .arg(marker)
3698 .status()
3699 .map(|s| s.success())
3700 .unwrap_or(false)
3701 }
3702
3703 #[cfg(unix)]
3704 #[tokio::test]
3705 async fn isolation_stops_a_daemon_that_leaves_the_process_group() {
3706 if !bwrap_present() {
3707 return;
3708 }
3709 let dir = tempfile::tempdir().unwrap();
3710 let r = builtin(dir.path(), |c| c.shell_isolate = ShellIsolate::Process);
3711 let marker = "sleep 297.41";
3712 let started =
3713 json!({ "command": format!("setsid {marker} >/dev/null 2>&1 & echo ok") }).to_string();
3714 let out = r.dispatch("shell", &started, &DenyAll).await;
3715 assert!(!out.is_error, "{}", out.output);
3716 tokio::time::sleep(Duration::from_millis(500)).await;
3717 assert!(!any_process(marker), "a daemon outlived the run");
3718 assert!(out.output.contains("shell_isolate"), "{}", out.output);
3720 }
3721
3722 #[cfg(unix)]
3723 #[tokio::test]
3724 async fn fs_mode_writes_inside_the_workspace_and_nowhere_else() {
3725 if !bwrap_present() {
3726 return;
3727 }
3728 let dir = tempfile::tempdir().unwrap();
3729 let r = builtin(dir.path(), |c| {
3730 c.shell_isolate = ShellIsolate::Fs;
3731 c.shell_isolate_hide = Vec::new();
3734 });
3735 let command = "touch made-here && echo inside=$(test -f made-here && echo ok) \
3736 etc=$(test -w /etc && echo writable || echo read-only) \
3737 tmp=$(touch /tmp/x && echo writable || echo read-only)";
3738 let args = json!({ "command": command }).to_string();
3739 let out = r.dispatch("shell", &args, &DenyAll).await;
3740 assert!(!out.is_error, "{}", out.output);
3741 assert!(
3742 dir.path().join("made-here").exists(),
3743 "workspace write was lost"
3744 );
3745 assert!(out.output.contains("inside=ok"), "{}", out.output);
3746 assert!(out.output.contains("etc=read-only"), "{}", out.output);
3747 assert!(out.output.contains("tmp=writable"), "{}", out.output);
3748 }
3749
3750 #[cfg(unix)]
3751 #[tokio::test]
3752 async fn fs_mode_hides_a_path_even_inside_the_workspace() {
3753 if !bwrap_present() {
3754 return;
3755 }
3756 let dir = tempfile::tempdir().unwrap();
3757 std::fs::create_dir(dir.path().join("secret")).unwrap();
3758 std::fs::write(dir.path().join("secret/key"), "TOPSECRET").unwrap();
3759 let secret = dir.path().join("secret");
3760 let r = builtin(dir.path(), move |c| {
3761 c.shell_isolate = ShellIsolate::Fs;
3762 c.shell_isolate_hide = vec![secret];
3763 });
3764 let args = json!({ "command": "ls -A secret | wc -l" }).to_string();
3765 let out = r.dispatch("shell", &args, &DenyAll).await;
3766 assert!(!out.is_error, "{}", out.output);
3767 assert!(out.output.contains("\n0\n"), "{}", out.output);
3769 }
3770
3771 #[cfg(unix)]
3772 #[tokio::test]
3773 async fn a_hide_that_would_erase_the_workspace_is_skipped_and_said_so() {
3774 if !bwrap_present() {
3775 return;
3776 }
3777 let dir = tempfile::tempdir().unwrap();
3778 let parent = dir.path().parent().unwrap().to_path_buf();
3781 let r = builtin(dir.path(), move |c| {
3782 c.shell_isolate = ShellIsolate::Fs;
3783 c.shell_isolate_hide = vec![parent];
3784 });
3785 let args = json!({ "command": "touch kept && ls -A | wc -l" }).to_string();
3786 let out = r.dispatch("shell", &args, &DenyAll).await;
3787 assert!(!out.is_error, "{}", out.output);
3788 assert!(
3789 dir.path().join("kept").exists(),
3790 "the workspace was erased: {}",
3791 out.output
3792 );
3793 }
3794
3795 #[test]
3796 fn specs_use_openai_function_format() {
3797 let v = serde_json::to_value(registry(Policy::Allow).specs()).unwrap();
3798 assert_eq!(v[0]["type"], "function");
3799 assert_eq!(v[0]["function"]["name"], "echo");
3800 }
3801
3802 #[cfg(unix)]
3806 #[test]
3807 fn replacing_a_file_keeps_its_mode() {
3808 use std::os::unix::fs::PermissionsExt;
3809 let dir = tempfile::tempdir().unwrap();
3810 let path = dir.path().join("run.sh");
3811 std::fs::write(&path, "#!/bin/sh\necho one\n").unwrap();
3812 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
3813
3814 replace_file(&path, "#!/bin/sh\necho two\n").expect("the edit lands");
3815
3816 let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3817 assert_eq!(mode, 0o755, "an executable stays executable");
3818 assert_eq!(
3819 std::fs::read_to_string(&path).unwrap(),
3820 "#!/bin/sh\necho two\n"
3821 );
3822 }
3823
3824 #[cfg(unix)]
3827 #[test]
3828 fn replacing_through_a_symlink_edits_the_target_and_keeps_the_link() {
3829 let dir = tempfile::tempdir().unwrap();
3830 let real = dir.path().join("real.sh");
3831 let link = dir.path().join("link.sh");
3832 std::fs::write(&real, "old\n").unwrap();
3833 std::os::unix::fs::symlink(&real, &link).unwrap();
3834
3835 replace_file(&link, "new\n").expect("the edit lands");
3836
3837 let meta = std::fs::symlink_metadata(&link).unwrap();
3838 assert!(
3839 meta.file_type().is_symlink(),
3840 "the link is still a link, not a copy of the file"
3841 );
3842 assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n");
3843 }
3844}