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 without(&self, names: &[&str]) -> ToolRegistry {
683 let mut out = ToolRegistry {
684 tools: BTreeMap::new(),
685 max_output_bytes: self.max_output_bytes,
686 hooks: self.hooks.clone(),
687 deferral: self.deferral,
688 };
689 for (name, entry) in &self.tools {
690 if names.contains(&name.as_str()) {
691 continue;
692 }
693 out.tools.insert(
694 name.clone(),
695 Entry {
696 tool: Arc::clone(&entry.tool),
697 policy: entry.policy,
698 source: entry.source.clone(),
699 disabled: entry.disabled,
700 deferred: entry.deferred,
701 },
702 );
703 }
704 if !out.tools.values().any(|e| e.deferred) {
708 for bridge in ["tool_search", "tool_describe", "tool_call"] {
709 out.tools.remove(bridge);
710 }
711 }
712 out
713 }
714
715 pub fn specs(&self) -> Vec<ToolSpec> {
717 self.descriptors()
718 .into_iter()
719 .filter(|d| d.advertised)
720 .map(|d| ToolSpec {
721 kind: "function",
722 function: ToolSpecFunction {
723 name: d.name,
724 description: d.description,
725 parameters: d.parameters,
726 },
727 })
728 .collect()
729 }
730
731 pub async fn dispatch(
737 &self,
738 name: &str,
739 raw_args: &str,
740 approver: &dyn Approver,
741 ) -> ToolOutcome {
742 self.dispatch_call(name, raw_args, approver, None).await
743 }
744
745 pub fn summary_of(&self, name: &str, raw_args: &str) -> String {
749 let Some(entry) = self.tools.get(name) else {
750 return format!("{name} {raw_args}");
751 };
752 let args = serde_json::from_str(raw_args).unwrap_or_else(|_| serde_json::json!({}));
753 entry.tool.describe_call(&args)
754 }
755
756 pub async fn dispatch_call(
761 &self,
762 name: &str,
763 raw_args: &str,
764 approver: &dyn Approver,
765 call_id: Option<&str>,
766 ) -> ToolOutcome {
767 self.dispatch_scoped(name, raw_args, approver, call_id, &RunScope::default())
768 .await
769 }
770
771 pub async fn dispatch_scoped(
774 &self,
775 name: &str,
776 raw_args: &str,
777 approver: &dyn Approver,
778 call_id: Option<&str>,
779 run: &RunScope,
780 ) -> ToolOutcome {
781 let Some(entry) = self.tools.get(name) else {
782 return ToolOutcome::unusable(format!("unknown tool `{name}`"));
783 };
784 let args: Value = if raw_args.trim().is_empty() {
785 json!({})
786 } else {
787 match serde_json::from_str(raw_args) {
788 Ok(v) => v,
789 Err(e) => {
790 return ToolOutcome::unusable(format!("arguments are not valid JSON: {e}"))
791 }
792 }
793 };
794 if entry.disabled {
795 return ToolOutcome::err(format!(
796 "tool `{name}` is disabled in the config (`[tools] disabled`)"
797 ));
798 }
799 if entry.policy == Policy::Deny {
800 return ToolOutcome::err(format!("tool `{name}` is disabled by policy"));
801 }
802 if let Verdict::Deny(reason) = self.hooks.before(name, &args, call_id).await {
805 return self
806 .hooks
807 .after(name, &args, ToolOutcome::err(reason), call_id)
808 .await;
809 }
810 if entry.policy == Policy::Ask && entry.tool.needs_approval(&args) {
811 let summary = entry.tool.describe_call(&args);
812 let pending = crate::approvals::Pending::new(
813 call_id.unwrap_or_default(),
814 name,
815 summary.clone(),
816 raw_args.to_string(),
817 );
818 match approver.decide(&pending).await {
819 crate::approvals::Decision::Allow => {}
820 crate::approvals::Decision::Deny(reason) => {
821 return ToolOutcome::err(format!(
822 "the user declined to run `{name}`: {reason}"
823 ));
824 }
825 crate::approvals::Decision::Defer => {
826 return ToolOutcome::awaiting(format!(
830 "`{name}` is not approved yet; the call is waiting for an answer"
831 ));
832 }
833 }
834 }
835 let scope = CallScope {
836 approver,
837 run,
838 registry: self,
839 call_id,
840 };
841 let outcome = match entry.tool.call_scoped(args.clone(), &scope).await {
842 Ok(out) => ToolOutcome::ok(out),
843 Err(ToolError::Deferred(message)) => ToolOutcome::awaiting(message),
847 Err(e) => ToolOutcome::err(e.to_string()),
848 };
849 self.hooks.after(name, &args, outcome, call_id).await
857 }
858}
859
860pub fn truncate(mut s: String, max: usize) -> String {
869 if s.len() <= max {
870 return s;
871 }
872 let mut cut = max;
873 while !s.is_char_boundary(cut) {
874 cut -= 1;
875 }
876 let mut floor = cut.saturating_sub(200);
877 while !s.is_char_boundary(floor) {
878 floor += 1;
879 }
880 if let Some(at) = s[floor..cut]
881 .rfind(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ',' | ';' | '>' | '=' | '&'))
882 {
883 cut = floor + at;
884 }
885 s.truncate(cut);
886 s.push_str("\n[output truncated]");
887 s
888}
889
890pub(crate) fn str_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, ToolError> {
891 args.get(key)
892 .and_then(Value::as_str)
893 .ok_or_else(|| ToolError::InvalidArgs(format!("missing string field `{key}`")))
894}
895
896pub(crate) fn replace_file(path: &Path, content: &str) -> Result<(), ToolError> {
912 let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
913 let mode = std::fs::metadata(&target).ok().map(|m| m.permissions());
914 let mut tmp = target.as_os_str().to_owned();
915 tmp.push(format!(".tmp{}", std::process::id()));
916 let tmp = PathBuf::from(tmp);
917 let wrote = std::fs::write(&tmp, content);
918 let wrote = match (wrote, mode) {
919 (Ok(()), Some(mode)) => std::fs::set_permissions(&tmp, mode),
920 (wrote, _) => wrote,
921 };
922 wrote
923 .and_then(|_| std::fs::rename(&tmp, &target))
924 .map_err(|e| {
925 let _ = std::fs::remove_file(&tmp);
926 ToolError::Failed(format!("cannot write {}: {e}", path.display()))
927 })
928}
929
930fn normalize(p: &Path) -> PathBuf {
932 let mut out = PathBuf::new();
933 for c in p.components() {
934 match c {
935 Component::ParentDir => {
936 out.pop();
937 }
938 Component::CurDir => {}
939 other => out.push(other.as_os_str()),
940 }
941 }
942 out
943}
944
945pub fn confine(root: &Path, requested: &str) -> Result<PathBuf, ToolError> {
948 let joined = normalize(&root.join(requested));
949 let mut existing = joined.as_path();
950 while std::fs::symlink_metadata(existing).is_err() {
953 existing = existing
954 .parent()
955 .ok_or_else(|| ToolError::Failed("path has no existing ancestor".into()))?;
956 }
957 let canon = std::fs::canonicalize(existing)
958 .map_err(|e| ToolError::Failed(format!("cannot resolve path: {e}")))?;
959 if !canon.starts_with(root) {
960 return Err(ToolError::Failed(format!(
961 "path `{requested}` is outside the workspace"
962 )));
963 }
964 Ok(joined)
965}
966
967pub struct ReadFile {
968 root: PathBuf,
969 max_bytes: usize,
970}
971
972#[async_trait]
973impl Tool for ReadFile {
974 fn name(&self) -> &str {
975 "read_file"
976 }
977 fn description(&self) -> &str {
978 "Read a UTF-8 text file inside the workspace."
979 }
980 fn parameters(&self) -> Value {
981 json!({"type":"object","properties":{"path":{"type":"string","description":"Path relative to the workspace"}},"required":["path"]})
982 }
983 fn describe_call(&self, args: &Value) -> String {
984 format!("read file {}", args["path"].as_str().unwrap_or("?"))
985 }
986 async fn call(&self, args: Value) -> Result<String, ToolError> {
987 let path = confine(&self.root, str_arg(&args, "path")?)?;
988 let fail = |e: std::io::Error| ToolError::Failed(format!("{}: {e}", path.display()));
989 let meta = tokio::fs::metadata(&path).await.map_err(fail)?;
997 if !meta.is_file() {
998 return Err(ToolError::Failed(format!(
999 "{}: not a regular file",
1000 path.display()
1001 )));
1002 }
1003 let file = tokio::fs::File::open(&path).await.map_err(fail)?;
1004 let mut buf = Vec::new();
1006 file.take(self.max_bytes as u64 + 1)
1007 .read_to_end(&mut buf)
1008 .await
1009 .map_err(fail)?;
1010 let cut = buf.len() > self.max_bytes;
1016 match String::from_utf8(buf) {
1017 Ok(text) => Ok(text),
1018 Err(e) if cut && e.utf8_error().error_len().is_none() => {
1019 let valid = e.utf8_error().valid_up_to();
1025 let mut bytes = e.into_bytes();
1026 bytes.truncate(valid);
1027 Ok(format!("{}\u{FFFD}", String::from_utf8_lossy(&bytes)))
1028 }
1029 Err(_) => Err(ToolError::Failed(format!(
1030 "{}: not valid UTF-8",
1031 path.display()
1032 ))),
1033 }
1034 }
1035}
1036
1037pub struct WriteFile {
1044 root: PathBuf,
1045 scripts: Option<PathBuf>,
1046 description: String,
1047 guard_bytes: usize,
1052}
1053
1054impl WriteFile {
1055 pub(crate) fn new(root: PathBuf, scripts: Option<PathBuf>) -> Self {
1056 let description = match &scripts {
1060 None => format!(
1061 "Create or overwrite a text file inside the workspace ({}). A path outside it is \
1062refused, so a file that belongs elsewhere is written here and moved with `shell`. To change part \
1063of a file that already exists, use `patch`: a rewrite carries the whole file, and the whole file \
1064stays in the conversation afterwards.",
1065 root.display()
1066 ),
1067 Some(dir) => format!(
1068 "Create or overwrite a text file inside the workspace ({}), or inside the scripts \
1069directory ({}) which takes an absolute path. A path outside both is refused. A script written \
1070there is not executable until you run `chmod +x` on it with `shell`; see the `script` tool. To \
1071change part of a file that already exists, use `patch`: a rewrite carries the whole file, and the \
1072whole file stays in the conversation afterwards.",
1073 root.display(),
1074 dir.display()
1075 ),
1076 };
1077 Self {
1078 root,
1079 scripts,
1080 description,
1081 guard_bytes: 0,
1082 }
1083 }
1084
1085 pub(crate) fn guard_bytes(mut self, bytes: usize) -> Self {
1092 self.guard_bytes = bytes;
1093 self
1094 }
1095
1096 fn relative_to_scripts(&self, joined: &Path) -> Option<PathBuf> {
1100 let dir = normalize(self.scripts.as_deref()?);
1101 let canon = std::fs::canonicalize(&dir).ok();
1102 std::iter::once(dir)
1103 .chain(canon)
1104 .find_map(|d| joined.strip_prefix(d).ok().map(Path::to_path_buf))
1105 }
1106
1107 pub(crate) fn resolve(&self, requested: &str) -> Result<PathBuf, ToolError> {
1110 let in_workspace = confine(&self.root, requested);
1111 let Some(scripts) = &self.scripts else {
1112 return in_workspace;
1113 };
1114 if let Ok(path) = in_workspace {
1115 return Ok(path);
1116 }
1117 let outside = || {
1118 ToolError::Failed(format!(
1119 "path `{requested}` is outside the workspace ({}) and outside the scripts \
1120directory ({})",
1121 self.root.display(),
1122 scripts.display()
1123 ))
1124 };
1125 let joined = normalize(&self.root.join(requested));
1126 let rest = self.relative_to_scripts(&joined).ok_or_else(outside)?;
1127 let rest = rest.to_str().ok_or_else(outside)?;
1128 std::fs::create_dir_all(scripts)
1129 .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
1130 let canon = std::fs::canonicalize(scripts)
1131 .map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
1132 confine(&canon, rest).map_err(|_| outside())
1133 }
1134}
1135
1136#[async_trait]
1137impl Tool for WriteFile {
1138 fn name(&self) -> &str {
1139 "write_file"
1140 }
1141 fn description(&self) -> &str {
1142 &self.description
1143 }
1144 fn parameters(&self) -> Value {
1145 let path = match &self.scripts {
1146 Some(dir) => format!(
1147 "Path relative to the workspace ({}), or an absolute path inside the scripts \
1148directory ({})",
1149 self.root.display(),
1150 dir.display()
1151 ),
1152 None => format!("Path relative to the workspace ({})", self.root.display()),
1153 };
1154 json!({"type":"object","properties":{
1155 "path":{"type":"string","description":path},
1156 "content":{"type":"string"},
1157 "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."}
1158 },"required":["path","content"]})
1159 }
1160 fn describe_call(&self, args: &Value) -> String {
1161 let path = args["path"].as_str().unwrap_or("?");
1162 let joined = normalize(&self.root.join(path));
1163 let in_scripts =
1164 !joined.starts_with(&self.root) && self.relative_to_scripts(&joined).is_some();
1165 format!(
1166 "write {} bytes to {path}{}",
1167 args["content"].as_str().map(str::len).unwrap_or(0),
1168 if in_scripts {
1169 " (scripts directory)"
1170 } else {
1171 ""
1172 }
1173 )
1174 }
1175 async fn call(&self, args: Value) -> Result<String, ToolError> {
1176 let content = str_arg(&args, "content")?;
1177 let path = self.resolve(str_arg(&args, "path")?)?;
1178 if self.guard_bytes > 0 && !args["force"].as_bool().unwrap_or(false) {
1183 if let Ok(meta) = tokio::fs::metadata(&path).await {
1184 let existing = meta.len() as usize;
1185 if existing >= self.guard_bytes {
1186 let name = path
1187 .file_name()
1188 .map(|n| n.to_string_lossy().into_owned())
1189 .unwrap_or_else(|| path.display().to_string());
1190 return Err(ToolError::Failed(format!(
1191 "refused: {name} already exists at {} bytes. Rewriting it means sending all \
1192{existing} bytes again, and they stay in the conversation for the rest of the session. Use \
1193`patch` for the lines you want to change — that carries only those lines — or call write_file \
1194again with `force: true` if the file really has to be replaced whole.",
1195 existing
1196 )));
1197 }
1198 }
1199 }
1200 if let Some(parent) = path.parent() {
1201 tokio::fs::create_dir_all(parent)
1202 .await
1203 .map_err(|e| ToolError::Failed(format!("{}: {e}", parent.display())))?;
1204 }
1205 tokio::fs::write(&path, content)
1206 .await
1207 .map_err(|e| ToolError::Failed(format!("{}: {e}", path.display())))?;
1208 Ok(format!(
1209 "wrote {} bytes to {}",
1210 content.len(),
1211 path.display()
1212 ))
1213 }
1214}
1215
1216pub struct Shell {
1217 root: PathBuf,
1218 skill_roots: Vec<crate::skills::Root>,
1220 scripts_dir: Option<PathBuf>,
1223 timeout: Duration,
1224 allowlist: Vec<String>,
1225 max_bytes: usize,
1226 kill_grace: Duration,
1228 sandbox: crate::sandbox::Sandbox,
1231 ask: crate::config::ShellAsk,
1233}
1234
1235pub(crate) const SHELL_KILL_GRACE: Duration = Duration::from_secs(2);
1236
1237#[cfg(unix)]
1240pub(crate) mod pgroup {
1241 use std::time::{Duration, Instant};
1242
1243 fn signal(pgid: u32, sig: libc::c_int) {
1244 if let Ok(pgid) = libc::pid_t::try_from(pgid) {
1245 unsafe { libc::kill(-pgid, sig) };
1247 }
1248 }
1249
1250 fn signal_pid(pid: u32, sig: libc::c_int) {
1252 if let Ok(pid) = libc::pid_t::try_from(pid) {
1253 unsafe { libc::kill(pid, sig) };
1256 }
1257 }
1258
1259 fn descendants(root: u32) -> Vec<u32> {
1266 let mut parent_of: Vec<(u32, u32)> = Vec::new();
1267 let Ok(entries) = std::fs::read_dir("/proc") else {
1268 return Vec::new();
1269 };
1270 for entry in entries.flatten() {
1271 let Some(pid) = entry
1272 .file_name()
1273 .to_str()
1274 .and_then(|s| s.parse::<u32>().ok())
1275 else {
1276 continue;
1277 };
1278 let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
1279 continue;
1281 };
1282 let Some((_, rest)) = stat.rsplit_once(')') else {
1285 continue;
1286 };
1287 let Some(ppid) = rest
1288 .split_whitespace()
1289 .nth(1)
1290 .and_then(|s| s.parse::<u32>().ok())
1291 else {
1292 continue;
1293 };
1294 parent_of.push((pid, ppid));
1295 }
1296 let mut out = Vec::new();
1297 let mut frontier = vec![root];
1298 while let Some(parent) = frontier.pop() {
1299 for (pid, ppid) in &parent_of {
1300 if *ppid == parent && !out.contains(pid) {
1301 out.push(*pid);
1302 frontier.push(*pid);
1303 }
1304 }
1305 }
1306 out
1307 }
1308
1309 fn stop_tree(pgid: u32, sig: libc::c_int, tree: &[u32]) {
1313 signal(pgid, sig);
1314 for pid in tree {
1315 signal_pid(*pid, sig);
1316 }
1317 }
1318
1319 fn alive(pgid: u32) -> bool {
1320 let Ok(pgid) = libc::pid_t::try_from(pgid) else {
1321 return false;
1322 };
1323 let rc = unsafe { libc::kill(-pgid, 0) };
1325 rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1326 }
1327
1328 pub async fn terminate(child: &mut tokio::process::Child, pgid: u32, grace: Duration) {
1332 let tree = descendants(pgid);
1335 stop_tree(pgid, libc::SIGTERM, &tree);
1336 let deadline = Instant::now() + grace;
1337 loop {
1338 let _ = child.try_wait();
1339 if !alive(pgid) && tree.iter().all(|pid| !alive_pid(*pid)) {
1340 return;
1341 }
1342 if Instant::now() >= deadline {
1343 break;
1344 }
1345 tokio::time::sleep(Duration::from_millis(20)).await;
1346 }
1347 let mut late = descendants(pgid);
1350 late.extend(tree);
1351 late.sort_unstable();
1352 late.dedup();
1353 stop_tree(pgid, libc::SIGKILL, &late);
1354 let _ = child.wait().await;
1355 }
1356
1357 fn alive_pid(pid: u32) -> bool {
1360 let Ok(pid) = libc::pid_t::try_from(pid) else {
1361 return false;
1362 };
1363 let rc = unsafe { libc::kill(pid, 0) };
1365 rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1366 }
1367
1368 pub(crate) fn kill_now(pgid: u32) {
1374 let tree = descendants(pgid);
1375 stop_tree(pgid, libc::SIGKILL, &tree);
1376 }
1377
1378 pub struct Guard(Option<u32>);
1380
1381 impl Guard {
1382 pub fn new(pgid: Option<u32>) -> Self {
1383 Self(pgid)
1384 }
1385 pub fn disarm(&mut self) {
1386 self.0 = None;
1387 }
1388 }
1389
1390 impl Drop for Guard {
1391 fn drop(&mut self) {
1394 if let Some(pgid) = self.0 {
1395 stop_tree(pgid, libc::SIGKILL, &descendants(pgid));
1396 }
1397 }
1398 }
1399}
1400
1401#[cfg(not(unix))]
1402mod pgroup {
1403 use std::time::Duration;
1404
1405 pub async fn terminate(child: &mut tokio::process::Child, _: u32, _: Duration) {
1406 let _ = child.kill().await;
1407 }
1408
1409 pub struct Guard;
1410
1411 impl Guard {
1412 pub fn new(_: Option<u32>) -> Self {
1413 Self
1414 }
1415 pub fn disarm(&mut self) {}
1416 }
1417}
1418
1419pub(crate) struct Drain {
1427 buf: Arc<std::sync::Mutex<Vec<u8>>>,
1428 cap: usize,
1429 cut: Arc<std::sync::atomic::AtomicBool>,
1431 task: tokio::task::JoinHandle<()>,
1432}
1433
1434impl Drain {
1435 pub(crate) fn start<R: AsyncRead + Unpin + Send + 'static>(
1436 pipe: Option<R>,
1437 cap: usize,
1438 ) -> Self {
1439 let buf = Arc::new(std::sync::Mutex::new(Vec::new()));
1440 let cut = Arc::new(std::sync::atomic::AtomicBool::new(false));
1441 let task = tokio::spawn(drain_into(pipe, cap, buf.clone(), cut.clone()));
1442 Self {
1443 buf,
1444 cap,
1445 cut,
1446 task,
1447 }
1448 }
1449
1450 pub(crate) fn take(&self) -> (String, bool) {
1452 let buf = self
1453 .buf
1454 .lock()
1455 .unwrap_or_else(|poisoned| poisoned.into_inner());
1456 let short = self.cut.load(std::sync::atomic::Ordering::SeqCst) || buf.len() > self.cap;
1457 let text = String::from_utf8_lossy(&buf[..buf.len().min(self.cap)]).into_owned();
1458 (text, short)
1459 }
1460}
1461
1462impl Drop for Drain {
1463 fn drop(&mut self) {
1466 self.task.abort();
1467 }
1468}
1469
1470pub(crate) async fn read_capped<R: AsyncRead + Unpin + Send + 'static>(
1473 pipe: Option<R>,
1474 cap: usize,
1475) -> (String, bool) {
1476 let mut drain = Drain::start(pipe, cap);
1477 let _ = (&mut drain.task).await;
1478 drain.take()
1479}
1480
1481async fn drain_into<R: AsyncRead + Unpin>(
1482 pipe: Option<R>,
1483 cap: usize,
1484 buf: Arc<std::sync::Mutex<Vec<u8>>>,
1485 cut: Arc<std::sync::atomic::AtomicBool>,
1486) {
1487 let Some(mut pipe) = pipe else { return };
1488 let mut chunk = [0u8; 8192];
1489 loop {
1490 let room = (cap + 1).saturating_sub(buf.lock().map(|b| b.len()).unwrap_or(0));
1491 if room == 0 {
1494 cut.store(true, std::sync::atomic::Ordering::SeqCst);
1495 return;
1496 }
1497 let want = room.min(chunk.len());
1498 match pipe.read(&mut chunk[..want]).await {
1499 Ok(0) => return,
1500 Ok(n) => {
1501 if let Ok(mut buf) = buf.lock() {
1502 buf.extend_from_slice(&chunk[..n]);
1503 }
1504 }
1505 Err(_) => return,
1506 }
1507 }
1508}
1509
1510const SHELL_META: &[char] = &[
1511 ';', '&', '|', '<', '>', '$', '`', '\n', '(', ')', '\\', '"', '\'', '*', '?',
1512];
1513
1514fn looks_backgrounded(command: &str) -> bool {
1520 if ["nohup", "setsid", "disown"]
1521 .iter()
1522 .any(|word| command.contains(word))
1523 {
1524 return true;
1525 }
1526 let bytes = command.as_bytes();
1527 for (i, &c) in bytes.iter().enumerate() {
1528 if c != b'&' {
1529 continue;
1530 }
1531 let next = bytes.get(i + 1).copied().unwrap_or(b' ');
1532 let prev = if i == 0 { b' ' } else { bytes[i - 1] };
1533 if next == b'&' || prev == b'&' || next == b'>' || prev == b'>' {
1535 continue;
1536 }
1537 return true;
1538 }
1539 false
1540}
1541
1542impl Shell {
1543 fn build_command(
1544 &self,
1545 command: &str,
1546 dir: &Path,
1547 ) -> Result<tokio::process::Command, ToolError> {
1548 let (program, args) = self.program_argv(command)?;
1549 let plan = self.sandbox.plan(&program, &args, dir)?;
1550 let mut c = tokio::process::Command::new(plan.program);
1551 c.args(plan.args);
1552 if let Some(dir) = &self.scripts_dir {
1553 c.env(crate::tools_script::ENV_SCRIPTS_DIR, dir);
1554 if self.allowlist.is_empty() {
1557 if let Some(path) = crate::tools_script::path_with(dir) {
1558 c.env("PATH", path);
1559 }
1560 }
1561 }
1562 Ok(c)
1563 }
1564
1565 fn program_argv(&self, command: &str) -> Result<(OsString, Vec<OsString>), ToolError> {
1567 if self.allowlist.is_empty() {
1568 return Ok((OsString::from("sh"), vec!["-c".into(), command.into()]));
1569 }
1570 if command.contains(SHELL_META) {
1571 return Err(ToolError::Failed(
1572 "shell syntax is not allowed when shell_allowlist is set".into(),
1573 ));
1574 }
1575 let mut parts = command.split_whitespace();
1576 let prog = parts
1577 .next()
1578 .ok_or_else(|| ToolError::InvalidArgs("empty command".into()))?;
1579 if !self.allowlist.iter().any(|a| a == prog) {
1580 return Err(ToolError::Failed(format!(
1581 "`{prog}` is not in shell_allowlist"
1582 )));
1583 }
1584 Ok((
1585 OsString::from(prog),
1586 parts.map(OsString::from).collect::<Vec<_>>(),
1587 ))
1588 }
1589
1590 fn working_dir(&self, requested: Option<&str>) -> Result<PathBuf, ToolError> {
1599 let Some(requested) = requested else {
1600 return Ok(self.root.clone());
1601 };
1602 let refuse = |why: String| ToolError::Failed(format!("cwd `{requested}` refused: {why}"));
1603 if requested.trim().is_empty() {
1604 return Err(refuse("it is empty".into()));
1605 }
1606 let resolved = std::fs::canonicalize(self.root.join(requested))
1607 .map_err(|e| refuse(format!("it cannot be resolved ({e})")))?;
1608 if !resolved.is_dir() {
1609 return Err(refuse(format!("{} is not a directory", resolved.display())));
1610 }
1611 if resolved.starts_with(&self.root) {
1612 return Ok(resolved);
1613 }
1614 let inside_scripts = self
1615 .scripts_dir
1616 .as_ref()
1617 .and_then(|dir| std::fs::canonicalize(dir).ok())
1618 .is_some_and(|dir| resolved.starts_with(dir));
1619 if inside_scripts {
1620 return Ok(resolved);
1621 }
1622 let report = crate::skills::discover(&self.skill_roots);
1623 let inside_a_skill = report.active().any(|(found, _)| {
1624 std::fs::canonicalize(&found.dir).is_ok_and(|dir| resolved.starts_with(dir))
1625 });
1626 if inside_a_skill {
1627 return Ok(resolved);
1628 }
1629 let scripts = self.scripts_dir.as_ref().map_or(String::new(), |dir| {
1630 format!(", outside the scripts directory ({})", dir.display())
1631 });
1632 Err(refuse(format!(
1633 "it resolves to {}, which is outside the workspace ({}){scripts} and outside every skill's directory",
1634 resolved.display(),
1635 self.root.display()
1636 )))
1637 }
1638
1639 fn afterwards(&self, command: &str, out: String) -> String {
1644 if self.sandbox.degraded() {
1645 return format!(
1646 "{out}\n\n[shell_isolate = \"process\": bubblewrap (`bwrap`) is not on PATH, so this \
1647 command ran uncontained — with your files, your network, and anything it started \
1648 still running after it returned. Installing bubblewrap contains it.]"
1649 );
1650 }
1651 if !self.sandbox.is_on() || !looks_backgrounded(command) {
1652 return out;
1653 }
1654 format!(
1655 "{out}\n\n[shell_isolate = \"{}\": anything this command started in the background \
1656 was stopped when it returned, because the run's PID namespace dies with it. Set \
1657 [tools] shell_isolate = \"off\" for this profile if a process has to outlive the \
1658 call.]",
1659 self.sandbox.mode()
1660 )
1661 }
1662}
1663
1664#[async_trait]
1665impl Tool for Shell {
1666 fn name(&self) -> &str {
1667 "shell"
1668 }
1669 fn needs_approval(&self, args: &Value) -> bool {
1673 if self.ask == crate::config::ShellAsk::Always {
1674 return true;
1675 }
1676 match args["command"].as_str() {
1677 Some(command) => crate::risk::danger(command).is_some(),
1678 None => false,
1680 }
1681 }
1682 fn description(&self) -> &str {
1683 "Run a command in the workspace directory and return its exit code, stdout and stderr. \
1684Pass `cwd` to run it somewhere else inside the workspace, inside the scripts directory, or \
1685inside a skill's own directory (to run that skill's `bash scripts/x.sh` as written); any other \
1686directory is refused. The scripts directory is first on `PATH` (unless a shell allowlist is set) \
1687and named in `ECLIPSE_SCRIPTS_DIR`, so a script there runs as a bare command."
1688 }
1689 fn parameters(&self) -> Value {
1690 json!({
1691 "type": "object",
1692 "properties": {
1693 "command": {"type": "string"},
1694 "cwd": {
1695 "type": "string",
1696 "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."
1697 }
1698 },
1699 "required": ["command"]
1700 })
1701 }
1702 fn describe_call(&self, args: &Value) -> String {
1703 let command = args["command"].as_str().unwrap_or("?");
1704 match args["cwd"].as_str() {
1705 Some(cwd) => format!("run `{command}` in {cwd}"),
1706 None => format!("run `{command}`"),
1707 }
1708 }
1709 async fn call(&self, args: Value) -> Result<String, ToolError> {
1710 let command = str_arg(&args, "command")?;
1711 let cwd = match args.get("cwd") {
1712 None | Some(Value::Null) => None,
1713 Some(Value::String(s)) => Some(s.as_str()),
1714 Some(_) => return Err(ToolError::InvalidArgs("`cwd` must be a string".into())),
1715 };
1716 let dir = self.working_dir(cwd)?;
1717 let mut cmd = self.build_command(command, &dir)?;
1718 cmd.current_dir(&dir);
1721 let out = run_to_completion(cmd, self.timeout, self.max_bytes, self.kill_grace).await?;
1722 Ok(self.afterwards(command, out))
1723 }
1724}
1725
1726pub(crate) async fn start_retrying<F>(mut build: F, max_bytes: usize) -> Result<Running, ToolError>
1742where
1743 F: FnMut() -> tokio::process::Command,
1744{
1745 let mut attempt = 0u32;
1746 loop {
1747 match start(build(), max_bytes) {
1748 Ok(running) => return Ok(running),
1749 Err(e) if attempt < 4 && is_text_busy(&e) => {
1750 attempt += 1;
1751 tokio::time::sleep(Duration::from_millis(1 << attempt)).await;
1752 }
1753 Err(e) => return Err(ToolError::Failed(crate::tools_script::start_error(&e))),
1754 }
1755 }
1756}
1757
1758#[cfg(unix)]
1759fn is_text_busy(e: &std::io::Error) -> bool {
1760 e.raw_os_error() == Some(libc::ETXTBSY)
1761}
1762
1763#[cfg(not(unix))]
1764fn is_text_busy(_: &std::io::Error) -> bool {
1765 false
1766}
1767
1768pub(crate) async fn run_built<F>(
1770 mut build: F,
1771 timeout: Duration,
1772 max_bytes: usize,
1773 kill_grace: Duration,
1774) -> Result<String, ToolError>
1775where
1776 F: FnMut() -> tokio::process::Command,
1777{
1778 let mut running = start_retrying(&mut build, max_bytes).await?;
1779 let status = match tokio::time::timeout(timeout, running.wait()).await {
1780 Ok(done) => done?,
1781 Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1782 };
1783 Ok(running.finish(status).await)
1784}
1785
1786pub(crate) async fn run_to_completion(
1787 cmd: tokio::process::Command,
1788 timeout: Duration,
1789 max_bytes: usize,
1790 kill_grace: Duration,
1791) -> Result<String, ToolError> {
1792 let mut running = spawn(cmd, max_bytes)?;
1793 let status = match tokio::time::timeout(timeout, running.wait()).await {
1794 Ok(done) => done?,
1795 Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
1796 };
1797 Ok(running.finish(status).await)
1798}
1799
1800const DRAIN_GRACE: Duration = Duration::from_millis(500);
1803
1804pub(crate) struct Running {
1811 guard: pgroup::Guard,
1815 pgid: Option<u32>,
1816 pub(crate) child: tokio::process::Child,
1817 out: Drain,
1818 err: Drain,
1819}
1820
1821pub(crate) fn spawn(cmd: tokio::process::Command, max_bytes: usize) -> Result<Running, ToolError> {
1822 start(cmd, max_bytes).map_err(|e| ToolError::Failed(crate::tools_script::start_error(&e)))
1823}
1824
1825pub(crate) fn start(
1828 mut cmd: tokio::process::Command,
1829 max_bytes: usize,
1830) -> std::io::Result<Running> {
1831 cmd.stdin(std::process::Stdio::null())
1832 .stdout(std::process::Stdio::piped())
1833 .stderr(std::process::Stdio::piped())
1834 .kill_on_drop(true);
1835 #[cfg(unix)]
1836 cmd.process_group(0);
1837 let mut child = cmd.spawn()?;
1838 let pgid = child.id();
1839 let guard = pgroup::Guard::new(pgid);
1840 let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
1841 let out = Drain::start(stdout, max_bytes);
1844 let err = Drain::start(stderr, max_bytes);
1845 Ok(Running {
1846 guard,
1847 pgid,
1848 child,
1849 out,
1850 err,
1851 })
1852}
1853
1854impl Running {
1855 pub(crate) async fn wait(&mut self) -> Result<std::process::ExitStatus, ToolError> {
1856 match self.child.wait().await {
1857 Ok(status) => {
1858 self.guard.disarm();
1860 Ok(status)
1861 }
1862 Err(e) => Err(ToolError::Failed(format!("failed to wait: {e}"))),
1863 }
1864 }
1865
1866 pub(crate) async fn timed_out(&mut self, timeout: Duration, kill_grace: Duration) -> ToolError {
1869 if let Some(pgid) = self.pgid {
1870 pgroup::terminate(&mut self.child, pgid, kill_grace).await;
1871 }
1872 self.guard.disarm();
1876 ToolError::Failed(format!("timed out after {}s", timeout.as_secs()))
1877 }
1878
1879 pub(crate) async fn finish(mut self, status: std::process::ExitStatus) -> String {
1888 self.guard.disarm();
1889 let stalled = tokio::time::timeout(DRAIN_GRACE, async {
1890 let _ = (&mut self.out.task).await;
1891 let _ = (&mut self.err.task).await;
1892 })
1893 .await
1894 .is_err();
1895 if stalled {
1896 self.out.task.abort();
1897 self.err.task.abort();
1898 }
1899 let (out, out_cut) = self.out.take();
1900 let (err, err_cut) = self.err.take();
1901 let note = |cut| if cut { "\n[truncated]" } else { "" };
1902 let held = if stalled {
1903 "\n[a process the command started still holds its output pipe; this call did not wait \
1904 for it]"
1905 } else {
1906 ""
1907 };
1908 format!(
1909 "exit code: {}\nstdout:\n{out}{}\nstderr:\n{err}{}{held}",
1910 status.code().map_or("signal".into(), |c| c.to_string()),
1911 note(out_cut),
1912 note(err_cut),
1913 )
1914 }
1915}
1916
1917const HTML_READ_FACTOR: usize = 8;
1920
1921pub struct Fetch {
1922 timeout: Duration,
1923 max_bytes: usize,
1924 html: FetchHtml,
1925 #[cfg(test)]
1927 allow_internal: bool,
1928}
1929
1930impl Fetch {
1931 pub fn new(timeout: Duration, max_bytes: usize) -> Self {
1932 Self {
1933 timeout,
1934 max_bytes,
1935 html: FetchHtml::Text,
1936 #[cfg(test)]
1937 allow_internal: false,
1938 }
1939 }
1940
1941 pub fn with_html(mut self, html: FetchHtml) -> Self {
1942 self.html = html;
1943 self
1944 }
1945
1946 fn reach(&self) -> crate::http::Reach {
1947 #[cfg(test)]
1948 if self.allow_internal {
1949 return crate::http::Reach::Anywhere;
1950 }
1951 crate::http::Reach::Public
1952 }
1953}
1954
1955#[async_trait]
1956impl Tool for Fetch {
1957 fn name(&self) -> &str {
1958 "fetch"
1959 }
1960 fn description(&self) -> &str {
1961 "HTTP GET a public http(s) URL and return the response body as text. HTML pages are \
1962 converted to approximate plain text unless `raw` is true. \
1963 Private, loopback and link-local hosts are blocked."
1964 }
1965 fn parameters(&self) -> Value {
1966 json!({"type":"object","properties":{
1967 "url":{"type":"string"},
1968 "raw":{"type":"boolean","description":"return HTML source instead of converted text"}
1969 },"required":["url"]})
1970 }
1971 fn describe_call(&self, args: &Value) -> String {
1972 format!("GET {}", args["url"].as_str().unwrap_or("?"))
1973 }
1974 async fn call(&self, args: Value) -> Result<String, ToolError> {
1975 let raw = str_arg(&args, "url")?;
1976 let url = reqwest::Url::parse(raw)
1977 .map_err(|e| ToolError::InvalidArgs(format!("invalid URL: {e}")))?;
1978 if !matches!(url.scheme(), "http" | "https") {
1979 return Err(ToolError::InvalidArgs(
1980 "only http(s) URLs are allowed".into(),
1981 ));
1982 }
1983 let mut resp = crate::http::get(&url, self.timeout, self.reach(), &[])
1986 .await
1987 .map_err(ToolError::Failed)?;
1988 let status = resp.status();
1989 let location = resp
1990 .headers()
1991 .get(reqwest::header::LOCATION)
1992 .map(|v| format!("location: {}\n", String::from_utf8_lossy(v.as_bytes())))
1993 .unwrap_or_default();
1994 let content_type = resp
1995 .headers()
1996 .get(reqwest::header::CONTENT_TYPE)
1997 .and_then(|v| v.to_str().ok())
1998 .map(str::to_string);
1999 let want_raw = match args.get("raw").and_then(Value::as_bool) {
2000 Some(raw) => raw,
2001 None => self.html == FetchHtml::Raw,
2002 };
2003 let declared_html = content_type
2006 .as_deref()
2007 .is_some_and(|c| c.to_ascii_lowercase().contains("html"));
2008 let limit = if declared_html && !want_raw {
2009 self.max_bytes.saturating_mul(HTML_READ_FACTOR)
2010 } else {
2011 self.max_bytes
2012 };
2013 let mut body = Vec::new();
2014 while let Some(chunk) = resp
2015 .chunk()
2016 .await
2017 .map_err(|e| ToolError::Failed(e.to_string()))?
2018 {
2019 body.extend_from_slice(&chunk);
2020 if body.len() > limit {
2021 break;
2022 }
2023 }
2024 let cut = body.len() > limit;
2025 body.truncate(limit);
2026 let text = String::from_utf8_lossy(&body).into_owned();
2027 let (note, text) = if !want_raw
2028 && crate::html::looks_like_html(content_type.as_deref(), &text)
2029 {
2030 (
2031 "note: HTML converted to approximate plain text (pass \"raw\": true for the source)\n",
2032 crate::html::to_text(&text),
2033 )
2034 } else {
2035 ("", text)
2036 };
2037 let marker = if cut {
2038 "\n[response body truncated]"
2039 } else {
2040 ""
2041 };
2042 Ok(format!(
2043 "status: {status}\n{location}{note}{}{marker}",
2044 truncate(text, self.max_bytes)
2045 ))
2046 }
2047}
2048
2049#[cfg(test)]
2050mod tests {
2051 use super::*;
2052 use crate::config::ShellIsolate;
2053 use std::sync::atomic::{AtomicUsize, Ordering};
2054
2055 struct Echo;
2056
2057 #[async_trait]
2058 impl Tool for Echo {
2059 fn name(&self) -> &str {
2060 "echo"
2061 }
2062 fn description(&self) -> &str {
2063 "echo"
2064 }
2065 fn parameters(&self) -> Value {
2066 json!({"type":"object"})
2067 }
2068 async fn call(&self, args: Value) -> Result<String, ToolError> {
2069 Ok(str_arg(&args, "text")?.to_string())
2070 }
2071 }
2072
2073 #[test]
2076 fn a_pattern_matches_a_source_as_well_as_a_name() {
2077 let mut registry = ToolRegistry::new(4096);
2078 registry.register(Arc::new(Echo), Policy::Allow);
2079 registry.register_with_source(
2080 Arc::new(Other),
2081 Policy::Allow,
2082 ToolSource::Plugin("mcp:homeassistant".into()),
2083 );
2084 let unknown = registry.defer(&["plugin:mcp:*".to_string()]);
2085 assert!(unknown.is_empty(), "a wildcard that matches is not a typo");
2086 let described = registry.descriptors();
2087 let deferred: Vec<&str> = described
2088 .iter()
2089 .filter(|d| d.deferred)
2090 .map(|d| d.name.as_str())
2091 .collect();
2092 assert_eq!(deferred, ["other"], "the MCP tool, not the built-in");
2093 let names: Vec<String> = registry.names();
2095 assert!(names.iter().any(|n| n == "tool_search"), "{names:?}");
2096
2097 let mut bare = ToolRegistry::new(4096);
2099 bare.register(Arc::new(Echo), Policy::Allow);
2100 assert!(bare.defer(&["plugin:mcp:*".to_string()]).is_empty());
2101 assert!(
2102 !bare.names().iter().any(|n| n == "tool_search"),
2103 "nothing deferred, nothing registered to reach it"
2104 );
2105 assert_eq!(bare.defer(&["nosuchtool".to_string()]), ["nosuchtool"]);
2107 assert_eq!(bare.defer(&["note_*".to_string()]), ["note_*"]);
2108 assert!(bare.defer(&["plugin:nowhere:*".to_string()]).is_empty());
2110 }
2111
2112 #[test]
2115 fn without_takes_a_tool_out_of_the_registry_rather_than_hiding_it() {
2116 let mut registry = ToolRegistry::new(4096);
2117 registry.register(Arc::new(Echo), Policy::Allow);
2118 registry.register(Arc::new(Other), Policy::Allow);
2119 registry.defer(&["other".to_string()]);
2120
2121 let read_only = registry.without(&["other"]);
2122 assert_eq!(read_only.names(), vec!["echo".to_string()]);
2123 assert!(
2125 registry.names().iter().any(|n| n == "other"),
2126 "the lead kept the tool the flare was not given"
2127 );
2128 assert_eq!(read_only.without(&["nosuchtool"]).names().len(), 1);
2130 }
2131
2132 struct Other;
2133
2134 #[async_trait]
2135 impl Tool for Other {
2136 fn name(&self) -> &str {
2137 "other"
2138 }
2139 fn description(&self) -> &str {
2140 "the other one"
2141 }
2142 fn parameters(&self) -> Value {
2143 json!({
2144 "type": "object",
2145 "properties": {"text": {"type": "string", "description": "what to say"}},
2146 "required": ["text"],
2147 "additionalProperties": false
2148 })
2149 }
2150 async fn call(&self, _: Value) -> Result<String, ToolError> {
2151 Ok("other".into())
2152 }
2153 }
2154
2155 struct Slashed;
2157
2158 #[async_trait]
2159 impl Tool for Slashed {
2160 fn name(&self) -> &str {
2161 "a/b~c"
2162 }
2163 fn description(&self) -> &str {
2164 "escaped"
2165 }
2166 fn parameters(&self) -> Value {
2167 json!({"type": "object", "properties": {}})
2168 }
2169 async fn call(&self, _: Value) -> Result<String, ToolError> {
2170 Ok(String::new())
2171 }
2172 }
2173
2174 struct CountingApprover(AtomicUsize, bool);
2175
2176 #[async_trait]
2177 impl Approver for CountingApprover {
2178 async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
2179 self.0.fetch_add(1, Ordering::SeqCst);
2180 if self.1 {
2181 crate::approvals::Decision::Allow
2182 } else {
2183 crate::approvals::Decision::Deny("no".to_string())
2184 }
2185 }
2186 }
2187
2188 fn registry(policy: Policy) -> ToolRegistry {
2189 let mut r = ToolRegistry::new(64);
2190 r.register(Arc::new(Echo), policy);
2191 r
2192 }
2193
2194 fn model_output(r: &ToolRegistry, out: ToolOutcome) -> String {
2198 truncate(out.output, r.max_output_bytes())
2199 }
2200
2201 const KEYWORDS: &[&str] = &[
2208 "$schema",
2209 "$id",
2210 "$ref",
2211 "$defs",
2212 "$comment",
2213 "title",
2214 "description",
2215 "type",
2216 "properties",
2217 "required",
2218 "additionalProperties",
2219 "items",
2220 "enum",
2221 "const",
2222 "default",
2223 "oneOf",
2224 "anyOf",
2225 "allOf",
2226 "not",
2227 "minLength",
2228 "maxLength",
2229 "pattern",
2230 "format",
2231 "minimum",
2232 "maximum",
2233 "minItems",
2234 "maxItems",
2235 "uniqueItems",
2236 "examples",
2237 "deprecated",
2238 ];
2239
2240 fn check_schema(node: &Value, path: &str, problems: &mut Vec<String>) {
2241 match node {
2242 Value::Object(map) => {
2243 for (k, v) in map {
2244 if k == "properties" || k == "$defs" {
2245 if let Value::Object(props) = v {
2248 for (name, sub) in props {
2249 check_schema(sub, &format!("{path}.{k}.{name}"), problems);
2250 }
2251 } else {
2252 problems.push(format!("{path}.{k} is not an object"));
2253 }
2254 continue;
2255 }
2256 if !KEYWORDS.contains(&k.as_str()) {
2257 problems.push(format!("{path}: unknown keyword `{k}`"));
2258 }
2259 check_schema(v, &format!("{path}.{k}"), problems);
2260 }
2261 if let Some(Value::Array(req)) = map.get("required") {
2262 if let Some(Value::Object(props)) = map.get("properties") {
2263 for r in req {
2264 if let Some(name) = r.as_str() {
2265 if !props.contains_key(name) {
2266 problems.push(format!(
2267 "{path}: `required` names `{name}`, which is not in `properties`"
2268 ));
2269 }
2270 }
2271 }
2272 }
2273 }
2274 }
2275 Value::Array(items) => {
2276 for (i, v) in items.iter().enumerate() {
2277 check_schema(v, &format!("{path}[{i}]"), problems);
2278 }
2279 }
2280 Value::String(_) if path.ends_with(".$ref") => {}
2281 _ => {}
2282 }
2283 }
2284
2285 fn assert_schema_is_sound(doc: &Value, defs: &serde_json::Map<String, Value>) {
2288 let mut problems = Vec::new();
2289 check_schema(doc, "$", &mut problems);
2290 let mut refs = Vec::new();
2291 fn collect_refs(node: &Value, out: &mut Vec<String>) {
2292 match node {
2293 Value::Object(map) => {
2294 for (k, v) in map {
2295 if k == "$ref" {
2296 if let Some(r) = v.as_str() {
2297 out.push(r.to_string());
2298 }
2299 }
2300 collect_refs(v, out);
2301 }
2302 }
2303 Value::Array(a) => a.iter().for_each(|v| collect_refs(v, out)),
2304 _ => {}
2305 }
2306 }
2307 collect_refs(doc, &mut refs);
2308 assert!(!refs.is_empty(), "the document refers to $defs");
2309 for r in &refs {
2310 let target = r
2311 .strip_prefix("#/$defs/")
2312 .unwrap_or_else(|| panic!("a $ref must point into $defs: {r}"));
2313 let key = target.replace("~1", "/").replace("~0", "~");
2316 if !defs.contains_key(&key) {
2317 problems.push(format!("$ref {r} does not resolve"));
2318 }
2319 }
2320 assert!(problems.is_empty(), "{problems:#?}");
2321 }
2322
2323 #[test]
2324 fn every_tool_describes_itself_in_one_place() {
2325 let r = registry(Policy::Allow);
2326 let d = r.descriptors();
2327 assert_eq!(d.len(), 1);
2328 assert_eq!(d[0].name, "echo");
2329 assert_eq!(d[0].policy, Policy::Allow);
2330 assert_eq!(d[0].source, ToolSource::Builtin);
2331 assert!(d[0].advertised);
2332 assert_eq!(r.specs()[0].function.parameters, d[0].parameters);
2334 assert_eq!(r.specs()[0].function.description, d[0].description);
2335 }
2336
2337 #[test]
2338 fn provenance_says_which_plugin_offered_a_tool() {
2339 let mut r = ToolRegistry::new(64);
2340 r.register(Arc::new(Echo), Policy::Ask);
2341 assert_eq!(r.descriptors()[0].source.label(), "builtin");
2342 let mut r = ToolRegistry::new(64);
2343 r.register_with_source(
2344 Arc::new(Echo),
2345 Policy::Ask,
2346 ToolSource::Plugin("memory-bank".into()),
2347 );
2348 assert_eq!(r.descriptors()[0].source.label(), "plugin:memory-bank");
2349 let json = serde_json::to_value(r.descriptors()).unwrap();
2350 assert_eq!(json[0]["source"], "plugin:memory-bank");
2351 }
2352
2353 #[test]
2354 fn the_schema_document_describes_every_advertised_tool_and_only_those_branches() {
2355 let mut r = ToolRegistry::new(64);
2356 r.register(Arc::new(Echo), Policy::Allow);
2357 r.register_with_source(Arc::new(Other), Policy::Deny, ToolSource::Builtin);
2358 let doc = r.schema_document();
2359 assert_eq!(
2360 doc["$schema"],
2361 "https://json-schema.org/draft/2020-12/schema"
2362 );
2363 assert_eq!(doc["$id"], TOOL_SCHEMA_ID);
2364
2365 let defs = doc["$defs"].as_object().expect("$defs is an object");
2366 assert!(defs.contains_key("echo") && defs.contains_key("other"));
2367 assert_schema_is_sound(&doc, defs);
2368
2369 let branches = doc["oneOf"].as_array().expect("oneOf is an array");
2372 assert_eq!(branches.len(), 1, "{branches:#?}");
2373 assert_eq!(branches[0]["properties"]["name"]["const"], "echo");
2374 assert_eq!(
2375 branches[0]["properties"]["arguments"]["$ref"],
2376 "#/$defs/echo"
2377 );
2378 }
2379
2380 #[test]
2381 fn a_real_argument_object_validates_against_its_own_branch() {
2382 let mut r = ToolRegistry::new(64);
2383 r.register_with_source(Arc::new(Other), Policy::Allow, ToolSource::Builtin);
2384 let doc = r.schema_document();
2385 let defs = doc["$defs"].as_object().unwrap();
2386 assert_schema_is_sound(&doc, defs);
2387
2388 let branch = &doc["oneOf"][0];
2390 let name = branch["properties"]["name"]["const"].as_str().unwrap();
2391 assert_eq!(name, "other");
2392 let target = branch["properties"]["arguments"]["$ref"]
2393 .as_str()
2394 .unwrap()
2395 .strip_prefix("#/$defs/")
2396 .unwrap();
2397 let schema = &defs[target];
2398 let required: Vec<&str> = schema["required"]
2399 .as_array()
2400 .unwrap()
2401 .iter()
2402 .filter_map(|v| v.as_str())
2403 .collect();
2404 assert_eq!(required, ["text"]);
2405 let args = json!({"text": "hi"});
2406 for key in &required {
2407 assert!(args.get(*key).is_some(), "missing {key}");
2408 let want = schema["properties"][*key]["type"].as_str().unwrap();
2409 assert_eq!(
2410 want,
2411 match &args[*key] {
2412 Value::String(_) => "string",
2413 Value::Number(_) => "number",
2414 _ => "other",
2415 }
2416 );
2417 }
2418 }
2419
2420 #[tokio::test]
2421 async fn a_disabled_tool_is_not_offered_and_cannot_be_called() {
2422 let mut r = registry(Policy::Allow);
2423 assert_eq!(r.advertised_names(), ["echo"]);
2424 assert!(r.disable(&["echo".into()]).is_empty());
2425 assert!(r.specs().is_empty(), "not offered to the model");
2426 assert!(r.advertised_names().is_empty());
2427 assert_eq!(r.descriptors().len(), 1);
2429 assert!(!r.descriptors()[0].advertised);
2430 assert_eq!(r.names(), ["echo"]);
2431 let out = r.dispatch("echo", "{\"text\":\"x\"}", &AllowAll).await;
2433 assert!(out.is_error);
2434 assert!(out.output.contains("`[tools] disabled`"), "{}", out.output);
2435 }
2436
2437 #[test]
2438 fn disabling_overrides_an_allow_policy_and_reports_names_that_match_nothing() {
2439 let mut r = ToolRegistry::new(64);
2440 r.register(Arc::new(Echo), Policy::Allow);
2441 let unknown = r.disable(&["echo".into(), "nosuchtool".into()]);
2442 assert_eq!(unknown, ["nosuchtool"], "a typo is reported, not ignored");
2443 assert!(r.specs().is_empty());
2444 let mut r = ToolRegistry::new(64);
2446 r.register(Arc::new(Echo), Policy::Deny);
2447 assert!(!r.descriptors()[0].advertised);
2448 assert!(r.descriptors()[0].source == ToolSource::Builtin);
2449 }
2450
2451 #[test]
2452 fn a_tool_name_with_pointer_characters_still_produces_a_resolving_ref() {
2453 let mut r = ToolRegistry::new(64);
2454 r.register_with_source(Arc::new(Slashed), Policy::Allow, ToolSource::Builtin);
2455 let doc = r.schema_document();
2456 let defs = doc["$defs"].as_object().unwrap();
2457 assert_schema_is_sound(&doc, defs);
2458 }
2459
2460 #[tokio::test]
2466 async fn dispatch_does_not_cap_the_output_the_hooks_will_see() {
2467 let mut r = ToolRegistry::new(8);
2468 r.register(Arc::new(Echo), Policy::Allow);
2469 let long = "x".repeat(64);
2470 let out = r
2471 .dispatch("echo", &json!({"text": long}).to_string(), &AllowAll)
2472 .await;
2473 assert_eq!(
2474 out.output.len(),
2475 64,
2476 "the cap belongs to the caller, after the hooks: {:?}",
2477 out.output
2478 );
2479 let cut = truncate(format!("{} tail", "y".repeat(20)), 8);
2481 assert!(
2482 cut.starts_with("yyyyyyy") && cut.ends_with("[output truncated]"),
2483 "{cut:?}"
2484 );
2485 assert!(
2486 !cut.contains("tail"),
2487 "and the fragment past the cut is gone"
2488 );
2489 }
2490
2491 #[tokio::test]
2492 async fn dispatch_runs_allowed_tool() {
2493 let out = registry(Policy::Allow)
2494 .dispatch("echo", r#"{"text":"hi"}"#, &DenyAll)
2495 .await;
2496 assert_eq!(out, ToolOutcome::ok("hi".into()));
2497 }
2498
2499 #[tokio::test]
2500 async fn dispatch_reports_unknown_tool_bad_json_and_bad_args() {
2501 let r = registry(Policy::Allow);
2502 assert!(r.dispatch("nope", "{}", &AllowAll).await.is_error);
2503 let bad = r.dispatch("echo", "{oops", &AllowAll).await;
2504 assert!(bad.is_error && bad.output.contains("not valid JSON"));
2505 let missing = r.dispatch("echo", "", &AllowAll).await;
2506 assert!(missing.is_error && missing.output.contains("`text`"));
2507 }
2508
2509 #[tokio::test]
2510 async fn deny_policy_blocks_and_hides_tool() {
2511 let r = registry(Policy::Deny);
2512 assert!(r.specs().is_empty());
2513 let out = r.dispatch("echo", r#"{"text":"x"}"#, &AllowAll).await;
2514 assert!(out.is_error && out.output.contains("disabled"));
2515 }
2516
2517 #[tokio::test]
2518 async fn ask_policy_consults_approver() {
2519 let r = registry(Policy::Ask);
2520 let yes = CountingApprover(AtomicUsize::new(0), true);
2521 assert!(!r.dispatch("echo", r#"{"text":"x"}"#, &yes).await.is_error);
2522 assert_eq!(yes.0.load(Ordering::SeqCst), 1);
2523 let no = CountingApprover(AtomicUsize::new(0), false);
2524 let out = r.dispatch("echo", r#"{"text":"x"}"#, &no).await;
2525 assert!(out.is_error && out.output.contains("declined"));
2526 assert_eq!(r.specs().len(), 1);
2527 }
2528
2529 #[tokio::test]
2530 async fn allow_policy_does_not_prompt() {
2531 let a = CountingApprover(AtomicUsize::new(0), false);
2532 registry(Policy::Allow)
2533 .dispatch("echo", r#"{"text":"x"}"#, &a)
2534 .await;
2535 assert_eq!(a.0.load(Ordering::SeqCst), 0);
2536 }
2537
2538 #[tokio::test]
2539 async fn output_is_truncated_on_char_boundary() {
2540 let r = registry(Policy::Allow);
2541 let out = r
2542 .dispatch(
2543 "echo",
2544 &json!({"text": "é".repeat(100)}).to_string(),
2545 &AllowAll,
2546 )
2547 .await;
2548 let out = model_output(&r, out);
2549 assert!(out.ends_with("[output truncated]"), "{out:?}");
2550 assert!(out.len() < 100);
2551 }
2552
2553 fn builtin(dir: &Path, tweak: impl FnOnce(&mut ToolsConfig)) -> ToolRegistry {
2554 let mut cfg = ToolsConfig {
2555 read_file: Policy::Allow,
2556 write_file: Policy::Allow,
2557 shell: Policy::Allow,
2558 fetch: Policy::Deny,
2559 ..ToolsConfig::default()
2560 };
2561 tweak(&mut cfg);
2562 ToolRegistry::from_config(&cfg, dir.to_path_buf())
2563 }
2564
2565 #[tokio::test]
2566 async fn builtin_defaults_are_gated() {
2567 let dir = tempfile::tempdir().unwrap();
2568 let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2569 assert_eq!(
2570 r.names(),
2571 [
2572 "fetch",
2573 "patch",
2574 "read_file",
2575 "search_files",
2576 "shell",
2577 "write_file"
2578 ]
2579 );
2580 let out = r
2582 .dispatch("shell", r#"{"command":"rm -rf everything"}"#, &DenyAll)
2583 .await;
2584 assert!(out.is_error && out.output.contains("declined"));
2585 let out = r
2586 .dispatch("shell", r#"{"command":"echo hi"}"#, &DenyAll)
2587 .await;
2588 assert!(!out.is_error, "ordinary work is not gated: {}", out.output);
2589 let out = r
2592 .dispatch("write_file", r#"{"path":"a","content":"b"}"#, &DenyAll)
2593 .await;
2594 assert!(!out.is_error, "{}", out.output);
2595 assert!(dir.path().join("a").exists());
2596 let out = r
2597 .dispatch(
2598 "write_file",
2599 r#"{"path":"/tmp/escape","content":"b"}"#,
2600 &DenyAll,
2601 )
2602 .await;
2603 assert!(
2604 out.is_error && out.output.contains("outside the workspace"),
2605 "{}",
2606 out.output
2607 );
2608 }
2609
2610 #[tokio::test]
2613 async fn search_files_is_offered_unasked_and_fenced_by_the_workspace() {
2614 let dir = tempfile::tempdir().unwrap();
2615 std::fs::create_dir_all(dir.path().join("src")).unwrap();
2616 std::fs::write(dir.path().join("src/a.rs"), "let needle = 1;\n").unwrap();
2617 let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
2618
2619 let listed = r
2620 .descriptors()
2621 .into_iter()
2622 .find(|d| d.name == "search_files")
2623 .expect("the tool is registered");
2624 assert_eq!(listed.policy, Policy::Allow);
2625 assert!(listed.advertised);
2626
2627 let out = r
2628 .dispatch("search_files", r#"{"pattern":"needle"}"#, &DenyAll)
2629 .await;
2630 assert!(!out.is_error, "{}", out.output);
2631 assert!(out.output.contains("a.rs:1"), "{}", out.output);
2632
2633 let out = r
2634 .dispatch(
2635 "search_files",
2636 r#"{"pattern":"needle","path":".."}"#,
2637 &DenyAll,
2638 )
2639 .await;
2640 assert!(
2641 out.is_error && out.output.contains("outside the workspace"),
2642 "{}",
2643 out.output
2644 );
2645 }
2646
2647 #[tokio::test]
2648 async fn file_tools_round_trip_and_confine() {
2649 let dir = tempfile::tempdir().unwrap();
2650 let r = builtin(dir.path(), |_| {});
2651 let w = r
2652 .dispatch(
2653 "write_file",
2654 r#"{"path":"sub/a.txt","content":"hello"}"#,
2655 &DenyAll,
2656 )
2657 .await;
2658 assert!(!w.is_error, "{}", w.output);
2659 let rd = r
2660 .dispatch("read_file", r#"{"path":"sub/a.txt"}"#, &DenyAll)
2661 .await;
2662 assert_eq!(rd.output, "hello");
2663 for bad in ["../escape.txt", "/etc/passwd", "sub/../../x"] {
2664 let out = r
2665 .dispatch("read_file", &json!({"path": bad}).to_string(), &DenyAll)
2666 .await;
2667 assert!(
2668 out.is_error && out.output.contains("outside"),
2669 "{bad}: {}",
2670 out.output
2671 );
2672 }
2673 let out = r
2674 .dispatch(
2675 "write_file",
2676 r#"{"path":"../escape.txt","content":"x"}"#,
2677 &DenyAll,
2678 )
2679 .await;
2680 assert!(out.is_error);
2681 }
2682
2683 #[cfg(unix)]
2684 #[tokio::test]
2685 async fn symlink_escape_is_blocked() {
2686 let dir = tempfile::tempdir().unwrap();
2687 let outside = tempfile::tempdir().unwrap();
2688 std::fs::write(outside.path().join("secret"), "s").unwrap();
2689 std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
2690 let r = builtin(dir.path(), |_| {});
2691 let out = r
2692 .dispatch("read_file", r#"{"path":"link/secret"}"#, &DenyAll)
2693 .await;
2694 assert!(out.is_error && out.output.contains("outside"));
2695 }
2696
2697 #[cfg(unix)]
2698 #[tokio::test]
2699 async fn dangling_symlink_cannot_be_written_through() {
2700 let dir = tempfile::tempdir().unwrap();
2701 let outside = tempfile::tempdir().unwrap();
2702 let target = outside.path().join("created");
2703 std::os::unix::fs::symlink(&target, dir.path().join("evil")).unwrap();
2704 let r = builtin(dir.path(), |_| {});
2705 let out = r
2706 .dispatch("write_file", r#"{"path":"evil","content":"x"}"#, &DenyAll)
2707 .await;
2708 assert!(out.is_error, "{}", out.output);
2709 assert!(!target.exists());
2710 }
2711
2712 #[tokio::test]
2713 async fn read_file_is_bounded_and_regular_files_only() {
2714 let dir = tempfile::tempdir().unwrap();
2715 std::fs::write(dir.path().join("big.txt"), "é".repeat(1000)).unwrap();
2716 std::fs::create_dir(dir.path().join("d")).unwrap();
2717 let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2718 let out = r
2719 .dispatch("read_file", r#"{"path":"big.txt"}"#, &DenyAll)
2720 .await;
2721 let shown = model_output(&r, out);
2722 assert!(shown.ends_with("[output truncated]"), "{shown:?}");
2723 assert!(shown.len() < 100);
2724 let out = r.dispatch("read_file", r#"{"path":"d"}"#, &DenyAll).await;
2725 assert!(out.is_error && out.output.contains("not a regular"));
2726 }
2727
2728 #[cfg(unix)]
2733 #[tokio::test]
2734 async fn a_fifo_is_refused_instead_of_hanging_the_turn() {
2735 let dir = tempfile::tempdir().unwrap();
2736 assert!(std::process::Command::new("mkfifo")
2737 .arg(dir.path().join("pipe"))
2738 .status()
2739 .map(|s| s.success())
2740 .unwrap_or(false));
2741 let r = builtin(dir.path(), |_| {});
2742 let out = tokio::time::timeout(
2743 std::time::Duration::from_secs(3),
2744 r.dispatch("read_file", r#"{"path":"pipe"}"#, &DenyAll),
2745 )
2746 .await
2747 .expect("a FIFO must not block the read");
2748 assert!(out.is_error, "{}", out.output);
2749 assert!(out.output.contains("not a regular"), "{}", out.output);
2750 }
2751
2752 #[tokio::test]
2756 async fn a_binary_file_is_not_text_at_any_size() {
2757 let dir = tempfile::tempdir().unwrap();
2758 let mut binary = vec![0u8; 200];
2759 binary[10] = 0xff;
2760 std::fs::write(dir.path().join("small.bin"), &binary[..50]).unwrap();
2761 std::fs::write(dir.path().join("big.bin"), &binary).unwrap();
2762 std::fs::write(dir.path().join("text.txt"), "aaéé".repeat(40)).unwrap();
2764 let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
2765
2766 let out = r
2767 .dispatch("read_file", r#"{"path":"small.bin"}"#, &DenyAll)
2768 .await;
2769 assert!(
2770 out.is_error,
2771 "an under-cap binary is not text: {}",
2772 out.output
2773 );
2774 let out = r
2775 .dispatch("read_file", r#"{"path":"big.bin"}"#, &DenyAll)
2776 .await;
2777 assert!(
2778 out.is_error,
2779 "an over-cap binary is not text either: {}",
2780 out.output
2781 );
2782 let out = r
2784 .dispatch("read_file", r#"{"path":"text.txt"}"#, &DenyAll)
2785 .await;
2786 assert!(!out.is_error, "{}", out.output);
2787 assert!(out.output.starts_with("aaé"), "{}", out.output);
2788 }
2789
2790 #[cfg(unix)]
2791 #[tokio::test]
2792 async fn shell_output_is_capped_and_flooding_child_stops() {
2793 let dir = tempfile::tempdir().unwrap();
2794 let r = builtin(dir.path(), |c| {
2795 c.max_output_bytes = 256;
2796 c.shell_timeout_secs = 10;
2797 });
2798 let out = r.dispatch("shell", r#"{"command":"yes"}"#, &DenyAll).await;
2799 assert!(!out.is_error, "{}", out.output);
2800 let shown = model_output(&r, out);
2801 assert!(
2802 shown.contains("[truncated]") || shown.contains("[output truncated]"),
2803 "{shown:?}"
2804 );
2805 assert!(shown.len() < 300, "{} bytes", shown.len());
2806 }
2807
2808 #[cfg(unix)]
2813 #[tokio::test]
2814 async fn a_background_child_does_not_hold_the_turn() {
2815 let dir = tempfile::tempdir().unwrap();
2816 let r = builtin(dir.path(), |c| {
2817 c.max_output_bytes = 4096;
2818 c.shell_timeout_secs = 30;
2819 c.shell_isolate = crate::config::ShellIsolate::Off;
2822 });
2823 let asked = std::time::Instant::now();
2824 let out = tokio::time::timeout(
2825 std::time::Duration::from_secs(3),
2826 r.dispatch("shell", r#"{"command":"sleep 5 & echo started"}"#, &DenyAll),
2827 )
2828 .await
2829 .expect("a background child must not hold the call — `#368`");
2830 assert!(!out.is_error, "{}", out.output);
2831 assert!(
2832 out.output.contains("started"),
2833 "what the child itself printed: {}",
2834 out.output
2835 );
2836 assert!(
2837 out.output.contains("still holds its output pipe"),
2838 "the result says why it stopped reading: {}",
2839 out.output
2840 );
2841 assert!(asked.elapsed() < std::time::Duration::from_secs(3));
2842 }
2843
2844 #[cfg(unix)]
2845 fn process_alive(pid: i32) -> bool {
2846 std::fs::read_to_string(format!("/proc/{pid}/stat"))
2852 .ok()
2853 .and_then(|s| {
2854 s.rsplit(')')
2855 .next()
2856 .map(|state| !state.trim_start().starts_with(['Z', 'X']))
2857 })
2858 .unwrap_or(false)
2859 }
2860
2861 #[cfg(unix)]
2862 async fn timeout_kills_grandchild(command: &str, grace: Duration) {
2863 let dir = tempfile::tempdir().unwrap();
2864 let mut r = ToolRegistry::new(4096);
2865 r.register(
2866 Arc::new(Shell {
2867 root: std::fs::canonicalize(dir.path()).unwrap(),
2868 skill_roots: Vec::new(),
2869 scripts_dir: None,
2870 timeout: Duration::from_secs(1),
2871 allowlist: Vec::new(),
2872 max_bytes: 4096,
2873 kill_grace: grace,
2874 sandbox: crate::sandbox::Sandbox::off(),
2875 ask: crate::config::ShellAsk::Dangerous,
2876 }),
2877 Policy::Allow,
2878 );
2879 let started = std::time::Instant::now();
2880 let out = r
2881 .dispatch("shell", &json!({"command": command}).to_string(), &DenyAll)
2882 .await;
2883 assert!(
2884 out.is_error && out.output.contains("timed out"),
2885 "{}",
2886 out.output
2887 );
2888 let pid: i32 = std::fs::read_to_string(dir.path().join("child.pid"))
2889 .unwrap()
2890 .trim()
2891 .parse()
2892 .unwrap();
2893 for _ in 0..100 {
2894 if !process_alive(pid) {
2895 break;
2896 }
2897 tokio::time::sleep(Duration::from_millis(50)).await;
2898 }
2899 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default();
2903 assert!(
2904 !process_alive(pid),
2905 "grandchild {pid} survived the timeout after {:.2}s; stat = {stat:?}",
2906 started.elapsed().as_secs_f32()
2907 );
2908 assert!(started.elapsed() < Duration::from_secs(8));
2909 }
2910
2911 #[cfg(unix)]
2912 #[tokio::test]
2913 async fn timeout_terminates_background_grandchild() {
2914 timeout_kills_grandchild(
2915 "sleep 300 & echo $! > child.pid; wait",
2916 Duration::from_secs(2),
2917 )
2918 .await;
2919 }
2920
2921 #[cfg(unix)]
2922 #[tokio::test]
2923 async fn timeout_terminates_a_grandchild_that_left_the_process_group() {
2924 timeout_kills_grandchild(
2927 "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait",
2928 Duration::from_secs(2),
2929 )
2930 .await;
2931 }
2932
2933 #[cfg(unix)]
2934 #[tokio::test]
2935 async fn a_cancelled_run_kills_a_grandchild_that_left_the_process_group() {
2936 let dir = tempfile::tempdir().unwrap();
2940 let mut r = ToolRegistry::new(4096);
2941 r.register(
2942 Arc::new(Shell {
2943 root: std::fs::canonicalize(dir.path()).unwrap(),
2944 skill_roots: Vec::new(),
2945 scripts_dir: None,
2946 timeout: Duration::from_secs(30),
2947 allowlist: Vec::new(),
2948 max_bytes: 4096,
2949 kill_grace: Duration::from_secs(2),
2950 sandbox: crate::sandbox::Sandbox::off(),
2951 ask: crate::config::ShellAsk::Dangerous,
2952 }),
2953 Policy::Allow,
2954 );
2955 let registry = Arc::new(r);
2956 let call = {
2957 let registry = Arc::clone(®istry);
2958 let args = json!({
2959 "command": "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait"
2960 })
2961 .to_string();
2962 tokio::spawn(async move { registry.dispatch("shell", &args, &DenyAll).await })
2963 };
2964 let pid = wait_for_pid(&dir.path().join("child.pid")).await;
2966 call.abort();
2967 let _ = call.await;
2968 for _ in 0..100 {
2969 if !process_alive(pid) {
2970 break;
2971 }
2972 tokio::time::sleep(Duration::from_millis(50)).await;
2973 }
2974 assert!(
2975 !process_alive(pid),
2976 "grandchild {pid} survived the drop: {:#?}",
2977 std::fs::read_to_string(format!("/proc/{pid}/stat"))
2978 );
2979 }
2980
2981 #[cfg(unix)]
2983 async fn wait_for_pid(path: &std::path::Path) -> i32 {
2984 for _ in 0..100 {
2985 if let Ok(text) = std::fs::read_to_string(path) {
2986 if let Ok(pid) = text.trim().parse::<i32>() {
2987 return pid;
2988 }
2989 }
2990 tokio::time::sleep(Duration::from_millis(20)).await;
2991 }
2992 panic!("the script never wrote {}", path.display());
2993 }
2994
2995 #[cfg(unix)]
2996 #[tokio::test]
2997 async fn timeout_escalates_to_sigkill_when_sigterm_is_ignored() {
2998 timeout_kills_grandchild(
2999 "trap '' TERM; sleep 300 & echo $! > child.pid; wait",
3000 Duration::from_millis(300),
3001 )
3002 .await;
3003 }
3004
3005 #[cfg(unix)]
3006 #[tokio::test]
3007 async fn shell_runs_in_workspace_with_timeout_and_allowlist() {
3008 let dir = tempfile::tempdir().unwrap();
3009 let r = builtin(dir.path(), |c| c.shell_timeout_secs = 1);
3010 let out = r
3011 .dispatch("shell", r#"{"command":"echo hi; pwd"}"#, &DenyAll)
3012 .await;
3013 assert!(!out.is_error);
3014 assert!(out.output.contains("exit code: 0") && out.output.contains("hi"));
3015 let slow = r
3016 .dispatch("shell", r#"{"command":"sleep 5"}"#, &DenyAll)
3017 .await;
3018 assert!(slow.is_error && slow.output.contains("timed out"));
3019
3020 let r = builtin(dir.path(), |c| c.shell_allowlist = vec!["echo".into()]);
3021 let ok = r
3022 .dispatch("shell", r#"{"command":"echo a b"}"#, &DenyAll)
3023 .await;
3024 assert!(ok.output.contains("a b"), "{}", ok.output);
3025 for bad in ["ls", "echo hi; ls", "echo $(ls)"] {
3026 let out = r
3027 .dispatch("shell", &json!({"command": bad}).to_string(), &DenyAll)
3028 .await;
3029 assert!(out.is_error, "{bad}");
3030 }
3031 }
3032
3033 #[cfg(unix)]
3034 fn shell_with_skills(workspace: &Path, skills: &Path) -> ToolRegistry {
3035 let cfg = ToolsConfig {
3036 shell: Policy::Allow,
3037 ..ToolsConfig::default()
3038 };
3039 let roots = vec![crate::skills::Root {
3040 source: crate::skills::Source::Shared,
3041 dir: skills.to_path_buf(),
3042 }];
3043 ToolRegistry::from_config_with(&cfg, workspace.to_path_buf(), roots)
3044 }
3045
3046 #[cfg(unix)]
3047 async fn shell_in(r: &ToolRegistry, command: &str, cwd: &str) -> ToolOutcome {
3048 r.dispatch(
3049 "shell",
3050 &json!({"command": command, "cwd": cwd}).to_string(),
3051 &DenyAll,
3052 )
3053 .await
3054 }
3055
3056 #[cfg(unix)]
3057 #[tokio::test]
3058 async fn shell_cwd_is_accepted_inside_the_workspace_and_refused_elsewhere() {
3059 let tmp = tempfile::tempdir().unwrap();
3060 let workspace = tmp.path().join("ws");
3061 std::fs::create_dir_all(workspace.join("sub")).unwrap();
3062 std::fs::write(workspace.join("file.txt"), "x").unwrap();
3063 let outside = tmp.path().join("outside");
3064 std::fs::create_dir_all(&outside).unwrap();
3065 std::os::unix::fs::symlink(&outside, workspace.join("link")).unwrap();
3066 let r = shell_with_skills(&workspace, &tmp.path().join("skills"));
3067
3068 let out = shell_in(&r, "pwd", "sub").await;
3069 assert!(!out.is_error, "{}", out.output);
3070 assert!(out.output.contains("/ws/sub"), "{}", out.output);
3071 let absolute = workspace.join("sub").display().to_string();
3072 assert!(!shell_in(&r, "pwd", &absolute).await.is_error);
3073
3074 for (cwd, why) in [
3075 ("/etc", "outside the workspace"),
3076 ("..", "outside the workspace"),
3077 ("link", "outside the workspace"),
3078 ("missing", "cannot be resolved"),
3079 ("file.txt", "not a directory"),
3080 (" ", "empty"),
3081 ] {
3082 let out = shell_in(&r, "pwd", cwd).await;
3083 assert!(out.is_error, "{cwd:?} should be refused: {}", out.output);
3084 assert!(
3085 out.output.contains(&format!("cwd `{cwd}` refused")),
3086 "names what was refused: {}",
3087 out.output
3088 );
3089 assert!(out.output.contains(why), "{cwd:?}, {why}: {}", out.output);
3090 }
3091 }
3092
3093 #[cfg(unix)]
3094 #[tokio::test]
3095 async fn a_skills_own_script_runs_from_its_directory_but_a_broken_skills_does_not() {
3096 let tmp = tempfile::tempdir().unwrap();
3097 let workspace = tmp.path().join("ws");
3098 std::fs::create_dir_all(&workspace).unwrap();
3099 let skills = tmp.path().join("skills");
3100 let good = skills.join("backup");
3101 std::fs::create_dir_all(good.join("scripts")).unwrap();
3102 std::fs::write(
3103 good.join("SKILL.md"),
3104 "---\nname: backup\n---\nRun `bash scripts/backup.sh`.\n",
3105 )
3106 .unwrap();
3107 std::fs::write(
3108 good.join("scripts/backup.sh"),
3109 "echo backed up from $(basename \"$PWD\")\n",
3110 )
3111 .unwrap();
3112 let broken = skills.join("broken");
3113 std::fs::create_dir_all(&broken).unwrap();
3114 std::fs::write(
3115 broken.join("SKILL.md"),
3116 "---\ndescription: no name\n---\nbody\n",
3117 )
3118 .unwrap();
3119 let r = shell_with_skills(&workspace, &skills);
3120
3121 let out = shell_in(&r, "bash scripts/backup.sh", &good.display().to_string()).await;
3122 assert!(!out.is_error, "{}", out.output);
3123 assert!(
3124 out.output.contains("backed up from backup"),
3125 "{}",
3126 out.output
3127 );
3128 let nested = good.join("scripts").display().to_string();
3129 assert!(!shell_in(&r, "pwd", &nested).await.is_error);
3130
3131 let out = shell_in(&r, "pwd", &skills.display().to_string()).await;
3132 assert!(
3133 out.is_error,
3134 "the skills directory is not a skill's directory"
3135 );
3136 let out = shell_in(&r, "pwd", &broken.display().to_string()).await;
3137 assert!(out.is_error, "{}", out.output);
3138 assert!(
3139 out.output.contains("outside every skill's directory"),
3140 "{}",
3141 out.output
3142 );
3143 }
3144
3145 #[cfg(unix)]
3146 fn shell_with_scripts(workspace: &Path, scripts: &Path, allowlist: &[&str]) -> ToolRegistry {
3147 let cfg = ToolsConfig {
3148 shell: Policy::Allow,
3149 shell_allowlist: allowlist.iter().map(|s| s.to_string()).collect(),
3150 ..ToolsConfig::default()
3151 };
3152 ToolRegistry::from_config_full(
3153 &cfg,
3154 workspace.to_path_buf(),
3155 Vec::new(),
3156 Some(scripts.to_path_buf()),
3157 )
3158 }
3159
3160 #[cfg(unix)]
3161 #[tokio::test]
3162 async fn shell_finds_a_script_as_a_bare_command_and_is_told_where_the_scripts_are() {
3163 use std::os::unix::fs::PermissionsExt;
3164 let tmp = tempfile::tempdir().unwrap();
3165 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3166 std::fs::create_dir_all(&workspace).unwrap();
3167 std::fs::create_dir_all(&scripts).unwrap();
3168 let script = scripts.join("hello-script");
3169 std::fs::write(&script, "#!/bin/sh\necho hello from $1\n").unwrap();
3170 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3171 let imposter = scripts.join("date");
3175 std::fs::write(&imposter, "#!/bin/sh\necho fake date\n").unwrap();
3176 std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3177 let r = shell_with_scripts(&workspace, &scripts, &[]);
3178
3179 let out = r
3180 .dispatch(
3181 "shell",
3182 &json!({"command": "hello-script world; date; echo dir=$ECLIPSE_SCRIPTS_DIR; \
3183 echo last=${PATH##*:}"})
3184 .to_string(),
3185 &DenyAll,
3186 )
3187 .await;
3188 assert!(!out.is_error, "{}", out.output);
3189 let dir = scripts.display().to_string();
3190 assert!(out.output.contains("hello from world"), "{}", out.output);
3191 assert!(out.output.contains(&format!("dir={dir}")), "{}", out.output);
3192 assert!(
3193 out.output.contains(&format!("last={dir}")),
3194 "the scripts directory is on PATH, last: {}",
3195 out.output
3196 );
3197 assert!(
3198 !out.output.contains("fake date"),
3199 "a real command wins over a script of the same name: {}",
3200 out.output
3201 );
3202 }
3203
3204 #[cfg(unix)]
3205 #[tokio::test]
3206 async fn an_allowlisted_shell_does_not_let_a_script_take_the_place_of_a_program() {
3207 use std::os::unix::fs::PermissionsExt;
3208 let tmp = tempfile::tempdir().unwrap();
3209 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3210 std::fs::create_dir_all(&workspace).unwrap();
3211 std::fs::create_dir_all(&scripts).unwrap();
3212 let imposter = scripts.join("echo");
3213 std::fs::write(&imposter, "#!/bin/sh\necho imposter\n").unwrap();
3214 std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
3215 let r = shell_with_scripts(&workspace, &scripts, &["echo", "env"]);
3216
3217 let out = r
3218 .dispatch("shell", r#"{"command":"echo real"}"#, &DenyAll)
3219 .await;
3220 assert!(
3221 out.output.contains("real") && !out.output.contains("imposter"),
3222 "{}",
3223 out.output
3224 );
3225 let out = r.dispatch("shell", r#"{"command":"env"}"#, &DenyAll).await;
3226 assert!(
3227 out.output
3228 .contains(&format!("ECLIPSE_SCRIPTS_DIR={}", scripts.display())),
3229 "{}",
3230 out.output
3231 );
3232 }
3233
3234 #[cfg(unix)]
3235 #[tokio::test]
3236 async fn shell_cwd_accepts_the_scripts_directory_and_the_refusal_names_it() {
3237 let tmp = tempfile::tempdir().unwrap();
3238 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3239 std::fs::create_dir_all(&workspace).unwrap();
3240 std::fs::create_dir_all(&scripts).unwrap();
3241 let r = shell_with_scripts(&workspace, &scripts, &[]);
3242
3243 let out = shell_in(&r, "pwd", &scripts.display().to_string()).await;
3244 assert!(!out.is_error, "{}", out.output);
3245 assert!(out.output.contains("/scripts"), "{}", out.output);
3246
3247 let out = shell_in(&r, "pwd", "/etc").await;
3248 assert!(
3249 out.is_error
3250 && out.output.contains("outside the workspace")
3251 && out.output.contains("outside the scripts directory")
3252 && out.output.contains("outside every skill's directory"),
3253 "{}",
3254 out.output
3255 );
3256 }
3257
3258 fn writer(workspace: &Path, scripts: &Path) -> ToolRegistry {
3259 let cfg = ToolsConfig {
3260 write_file: Policy::Allow,
3261 ..ToolsConfig::default()
3262 };
3263 ToolRegistry::from_config_full(
3264 &cfg,
3265 workspace.to_path_buf(),
3266 Vec::new(),
3267 Some(scripts.to_path_buf()),
3268 )
3269 }
3270
3271 async fn write_to(r: &ToolRegistry, path: &str) -> ToolOutcome {
3272 r.dispatch(
3273 "write_file",
3274 &json!({"path": path, "content": "#!/bin/sh\n"}).to_string(),
3275 &DenyAll,
3276 )
3277 .await
3278 }
3279
3280 #[tokio::test]
3281 async fn write_file_writes_in_the_scripts_directory_even_before_it_exists() {
3282 let tmp = tempfile::tempdir().unwrap();
3283 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("cfg/scripts"));
3284 std::fs::create_dir_all(&workspace).unwrap();
3285 let r = writer(&workspace, &scripts);
3286
3287 let target = scripts.join("backup.sh");
3288 let out = write_to(&r, &target.display().to_string()).await;
3289 assert!(!out.is_error, "{}", out.output);
3290 assert_eq!(std::fs::read_to_string(&target).unwrap(), "#!/bin/sh\n");
3291
3292 let out = write_to(&r, &format!("{}/sub/../again.sh", scripts.display())).await;
3293 assert!(!out.is_error, "{}", out.output);
3294 assert!(scripts.join("again.sh").is_file());
3295 }
3296
3297 #[tokio::test]
3298 async fn write_file_still_writes_in_the_workspace_when_scripts_are_configured() {
3299 let tmp = tempfile::tempdir().unwrap();
3300 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3301 std::fs::create_dir_all(&workspace).unwrap();
3302 let r = writer(&workspace, &scripts);
3303 let out = write_to(&r, "notes/a.txt").await;
3304 assert!(!out.is_error, "{}", out.output);
3305 assert!(workspace.join("notes/a.txt").is_file());
3306 assert!(!scripts.exists(), "a workspace write must not create it");
3307 }
3308
3309 #[tokio::test]
3313 async fn a_big_file_is_not_clobbered_by_accident() {
3314 let dir = tempfile::tempdir().unwrap();
3315 let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(100);
3316
3317 let big = dir.path().join("index.html");
3318 std::fs::write(&big, "x".repeat(500)).unwrap();
3319
3320 let refused = tool
3321 .call(json!({"path": "index.html", "content": "tiny"}))
3322 .await
3323 .unwrap_err()
3324 .to_string();
3325 assert!(refused.contains("already exists at 500 bytes"), "{refused}");
3326 assert!(
3327 refused.contains("`patch`"),
3328 "it names the cheap path: {refused}"
3329 );
3330 assert!(
3331 refused.contains("force: true"),
3332 "and how to mean it: {refused}"
3333 );
3334 assert_eq!(
3335 std::fs::read_to_string(&big).unwrap().len(),
3336 500,
3337 "nothing was written"
3338 );
3339
3340 tool.call(json!({"path": "index.html", "content": "tiny", "force": true}))
3342 .await
3343 .unwrap();
3344 assert_eq!(std::fs::read_to_string(&big).unwrap(), "tiny");
3345
3346 let small = dir.path().join("notes.md");
3348 tool.call(json!({"path": "notes.md", "content": "one"}))
3349 .await
3350 .unwrap();
3351 tool.call(json!({"path": "notes.md", "content": "two"}))
3352 .await
3353 .unwrap();
3354 assert_eq!(std::fs::read_to_string(&small).unwrap(), "two");
3355
3356 tool.call(json!({"path": "fresh.html", "content": "y".repeat(400)}))
3358 .await
3359 .unwrap();
3360 assert!(dir.path().join("fresh.html").exists());
3361
3362 let loose = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(0);
3364 loose
3365 .call(json!({"path": "index.html", "content": "free"}))
3366 .await
3367 .unwrap();
3368 assert_eq!(std::fs::read_to_string(&big).unwrap(), "free");
3369 }
3370
3371 #[tokio::test]
3374 async fn the_guard_refuses_at_the_threshold_not_only_above_it() {
3375 let dir = tempfile::tempdir().unwrap();
3376 let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(64);
3377
3378 std::fs::write(dir.path().join("exact.txt"), "x".repeat(64)).unwrap();
3380 let refused = tool
3381 .call(json!({"path": "exact.txt", "content": "y"}))
3382 .await
3383 .unwrap_err()
3384 .to_string();
3385 assert!(refused.contains("already exists at 64 bytes"), "{refused}");
3386 assert_eq!(
3387 std::fs::read_to_string(dir.path().join("exact.txt"))
3388 .unwrap()
3389 .len(),
3390 64,
3391 "nothing was written"
3392 );
3393
3394 std::fs::write(dir.path().join("under.txt"), "x".repeat(63)).unwrap();
3396 tool.call(json!({"path": "under.txt", "content": "y"}))
3397 .await
3398 .unwrap();
3399 assert_eq!(
3400 std::fs::read_to_string(dir.path().join("under.txt")).unwrap(),
3401 "y"
3402 );
3403 }
3404
3405 #[cfg(unix)]
3406 #[tokio::test]
3407 async fn write_file_refuses_everywhere_else_and_names_both_roots() {
3408 let tmp = tempfile::tempdir().unwrap();
3409 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3410 let elsewhere = tmp.path().join("elsewhere");
3411 std::fs::create_dir_all(&workspace).unwrap();
3412 std::fs::create_dir_all(&scripts).unwrap();
3413 std::fs::create_dir_all(&elsewhere).unwrap();
3414 std::os::unix::fs::symlink(&elsewhere, scripts.join("link")).unwrap();
3415 let r = writer(&workspace, &scripts);
3416
3417 let sibling = format!("{}-other/x.sh", scripts.display());
3418 for requested in [
3419 "/etc/eclipse-test".to_string(),
3420 elsewhere.join("x.sh").display().to_string(),
3421 format!("{}/../escape.sh", scripts.display()),
3422 format!("{}/link/x.sh", scripts.display()),
3423 sibling,
3424 ] {
3425 let out = write_to(&r, &requested).await;
3426 assert!(out.is_error, "{requested} should be refused");
3427 assert!(
3428 out.output.contains(&workspace.display().to_string())
3429 && out.output.contains(&scripts.display().to_string()),
3430 "{requested}: {}",
3431 out.output
3432 );
3433 }
3434 assert!(!elsewhere.join("x.sh").exists());
3435 assert!(!tmp.path().join("escape.sh").exists());
3436 }
3437
3438 #[test]
3439 fn the_approval_line_for_write_file_says_when_the_destination_is_the_scripts_directory() {
3440 let tmp = tempfile::tempdir().unwrap();
3441 let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
3442 let tool = WriteFile::new(workspace, Some(scripts.clone()));
3443 let line = tool.describe_call(
3444 &json!({"path": scripts.join("a.sh").display().to_string(), "content": "x"}),
3445 );
3446 assert!(line.ends_with("(scripts directory)"), "{line}");
3447 let line = tool.describe_call(&json!({"path": "a.txt", "content": "x"}));
3448 assert!(!line.contains("scripts"), "{line}");
3449 }
3450
3451 #[cfg(unix)]
3452 #[tokio::test]
3453 async fn shell_without_a_cwd_still_runs_in_the_workspace_root() {
3454 let tmp = tempfile::tempdir().unwrap();
3455 let r = shell_with_skills(tmp.path(), &tmp.path().join("skills"));
3456 let out = r.dispatch("shell", r#"{"command":"pwd"}"#, &DenyAll).await;
3457 let root = std::fs::canonicalize(tmp.path()).unwrap();
3458 assert!(
3459 out.output.contains(&root.display().to_string()),
3460 "{}",
3461 out.output
3462 );
3463 let out = r
3464 .dispatch("shell", r#"{"command":"pwd","cwd":7}"#, &DenyAll)
3465 .await;
3466 assert!(
3467 out.is_error && out.output.contains("`cwd` must be a string"),
3468 "{}",
3469 out.output
3470 );
3471 }
3472
3473 #[tokio::test]
3474 async fn fetch_rejects_non_http_schemes() {
3475 let dir = tempfile::tempdir().unwrap();
3476 let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3477 let out = r
3478 .dispatch("fetch", r#"{"url":"file:///etc/passwd"}"#, &DenyAll)
3479 .await;
3480 assert!(out.is_error && out.output.contains("http"));
3481 }
3482
3483 #[tokio::test]
3484 async fn fetch_blocks_internal_targets_before_connecting() {
3485 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3487 let port = listener.local_addr().unwrap().port();
3488 let dir = tempfile::tempdir().unwrap();
3489 let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
3490 for url in [
3491 format!("http://127.0.0.1:{port}/"),
3492 format!("http://localhost:{port}/"),
3493 format!("http://svc.localhost:{port}/"),
3494 format!("http://[::1]:{port}/"),
3495 format!("http://[::ffff:127.0.0.1]:{port}/"),
3496 format!("http://2130706433:{port}/"),
3497 "http://169.254.169.254/latest/meta-data/".to_string(),
3498 "http://8.8.8.8/".to_string(),
3499 ] {
3500 let out = r
3501 .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3502 .await;
3503 assert!(
3504 out.is_error && out.output.contains("blocked"),
3505 "{url}: {}",
3506 out.output
3507 );
3508 }
3509 let accepted = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;
3510 assert!(accepted.is_err(), "blocked fetch connected anyway");
3511 }
3512
3513 #[tokio::test]
3514 async fn fetch_does_not_follow_redirects() {
3515 use tokio::io::{AsyncReadExt, AsyncWriteExt};
3516 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3517 let url = format!("http://{}/", listener.local_addr().unwrap());
3518 let server = tokio::spawn(async move {
3519 let (mut s, _) = listener.accept().await.unwrap();
3520 let mut buf = [0u8; 1024];
3521 let _ = s.read(&mut buf).await;
3522 s.write_all(
3523 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",
3524 )
3525 .await
3526 .unwrap();
3527 });
3528 let mut r = ToolRegistry::new(4096);
3529 r.register(
3530 Arc::new(Fetch {
3531 allow_internal: true,
3532 ..Fetch::new(Duration::from_secs(5), 4096)
3533 }),
3534 Policy::Allow,
3535 );
3536 let out = r
3537 .dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
3538 .await;
3539 server.await.unwrap();
3540 assert!(!out.is_error, "{}", out.output);
3541 assert!(
3542 out.output.contains("302")
3543 && out
3544 .output
3545 .contains("location: http://127.0.0.1:9/elsewhere")
3546 );
3547 }
3548
3549 async fn fetch_from_mock(
3551 headers: &'static str,
3552 body: &'static str,
3553 html: FetchHtml,
3554 args: Value,
3555 ) -> ToolOutcome {
3556 use tokio::io::{AsyncReadExt, AsyncWriteExt};
3557 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3558 let url = format!("http://{}/", listener.local_addr().unwrap());
3559 let server = tokio::spawn(async move {
3560 let (mut s, _) = listener.accept().await.unwrap();
3561 let mut buf = [0u8; 1024];
3562 let _ = s.read(&mut buf).await;
3563 let resp = format!(
3564 "HTTP/1.1 200 OK\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
3565 body.len()
3566 );
3567 s.write_all(resp.as_bytes()).await.unwrap();
3568 });
3569 let mut r = ToolRegistry::new(4096);
3570 r.register(
3571 Arc::new(
3572 Fetch {
3573 allow_internal: true,
3574 ..Fetch::new(Duration::from_secs(5), 4096)
3575 }
3576 .with_html(html),
3577 ),
3578 Policy::Allow,
3579 );
3580 let mut args = args;
3581 args["url"] = json!(url);
3582 let out = r.dispatch("fetch", &args.to_string(), &DenyAll).await;
3583 server.await.unwrap();
3584 out
3585 }
3586
3587 const PAGE: &str = "<!doctype html><html><head><title>T</title><script>evil()</script></head>\
3588 <body><h1>Hello</h1><p>one & two</p></body></html>";
3589
3590 #[tokio::test]
3591 async fn fetch_converts_html_to_text_by_default() {
3592 let out = fetch_from_mock(
3593 "content-type: text/html; charset=utf-8\r\n",
3594 PAGE,
3595 FetchHtml::Text,
3596 json!({}),
3597 )
3598 .await;
3599 assert!(!out.is_error, "{}", out.output);
3600 assert!(out.output.starts_with("status: 200 OK\n"), "{}", out.output);
3601 assert!(
3602 out.output.contains("note: HTML converted"),
3603 "{}",
3604 out.output
3605 );
3606 assert!(
3607 out.output.ends_with("T\n\nHello\n\none & two"),
3608 "{}",
3609 out.output
3610 );
3611 assert!(!out.output.contains("<p>") && !out.output.contains("evil"));
3612
3613 let out = fetch_from_mock("", PAGE, FetchHtml::Text, json!({})).await;
3615 assert!(out.output.contains("Hello") && !out.output.contains("<h1>"));
3616 }
3617
3618 #[tokio::test]
3619 async fn fetch_can_return_raw_html_per_call_or_by_config() {
3620 let ct = "content-type: text/html\r\n";
3621 let out = fetch_from_mock(ct, PAGE, FetchHtml::Text, json!({"raw": true})).await;
3622 assert!(out.output.contains("<h1>Hello</h1>") && !out.output.contains("note: HTML"));
3623 let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({})).await;
3624 assert!(
3625 out.output.contains("<script>evil()</script>"),
3626 "{}",
3627 out.output
3628 );
3629 let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({"raw": false})).await;
3630 assert!(out.output.contains("note: HTML converted") && !out.output.contains("<h1>"));
3631 }
3632
3633 #[tokio::test]
3634 async fn fetch_leaves_non_html_bodies_alone() {
3635 let out = fetch_from_mock(
3636 "content-type: application/json\r\n",
3637 r#"{"html":"<p>x</p>"}"#,
3638 FetchHtml::Text,
3639 json!({}),
3640 )
3641 .await;
3642 assert!(
3643 out.output.ends_with(r#"{"html":"<p>x</p>"}"#),
3644 "{}",
3645 out.output
3646 );
3647 assert!(!out.output.contains("note:"));
3648 }
3649
3650 #[cfg(unix)]
3654 fn bwrap_present() -> bool {
3655 std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
3656 .any(|d| d.join("bwrap").is_file())
3657 }
3658
3659 #[cfg(unix)]
3661 fn any_process(marker: &str) -> bool {
3662 std::process::Command::new("pgrep")
3663 .arg("-f")
3664 .arg(marker)
3665 .status()
3666 .map(|s| s.success())
3667 .unwrap_or(false)
3668 }
3669
3670 #[cfg(unix)]
3671 #[tokio::test]
3672 async fn isolation_stops_a_daemon_that_leaves_the_process_group() {
3673 if !bwrap_present() {
3674 return;
3675 }
3676 let dir = tempfile::tempdir().unwrap();
3677 let r = builtin(dir.path(), |c| c.shell_isolate = ShellIsolate::Process);
3678 let marker = "sleep 297.41";
3679 let started =
3680 json!({ "command": format!("setsid {marker} >/dev/null 2>&1 & echo ok") }).to_string();
3681 let out = r.dispatch("shell", &started, &DenyAll).await;
3682 assert!(!out.is_error, "{}", out.output);
3683 tokio::time::sleep(Duration::from_millis(500)).await;
3684 assert!(!any_process(marker), "a daemon outlived the run");
3685 assert!(out.output.contains("shell_isolate"), "{}", out.output);
3687 }
3688
3689 #[cfg(unix)]
3690 #[tokio::test]
3691 async fn fs_mode_writes_inside_the_workspace_and_nowhere_else() {
3692 if !bwrap_present() {
3693 return;
3694 }
3695 let dir = tempfile::tempdir().unwrap();
3696 let r = builtin(dir.path(), |c| {
3697 c.shell_isolate = ShellIsolate::Fs;
3698 c.shell_isolate_hide = Vec::new();
3701 });
3702 let command = "touch made-here && echo inside=$(test -f made-here && echo ok) \
3703 etc=$(test -w /etc && echo writable || echo read-only) \
3704 tmp=$(touch /tmp/x && echo writable || echo read-only)";
3705 let args = json!({ "command": command }).to_string();
3706 let out = r.dispatch("shell", &args, &DenyAll).await;
3707 assert!(!out.is_error, "{}", out.output);
3708 assert!(
3709 dir.path().join("made-here").exists(),
3710 "workspace write was lost"
3711 );
3712 assert!(out.output.contains("inside=ok"), "{}", out.output);
3713 assert!(out.output.contains("etc=read-only"), "{}", out.output);
3714 assert!(out.output.contains("tmp=writable"), "{}", out.output);
3715 }
3716
3717 #[cfg(unix)]
3718 #[tokio::test]
3719 async fn fs_mode_hides_a_path_even_inside_the_workspace() {
3720 if !bwrap_present() {
3721 return;
3722 }
3723 let dir = tempfile::tempdir().unwrap();
3724 std::fs::create_dir(dir.path().join("secret")).unwrap();
3725 std::fs::write(dir.path().join("secret/key"), "TOPSECRET").unwrap();
3726 let secret = dir.path().join("secret");
3727 let r = builtin(dir.path(), move |c| {
3728 c.shell_isolate = ShellIsolate::Fs;
3729 c.shell_isolate_hide = vec![secret];
3730 });
3731 let args = json!({ "command": "ls -A secret | wc -l" }).to_string();
3732 let out = r.dispatch("shell", &args, &DenyAll).await;
3733 assert!(!out.is_error, "{}", out.output);
3734 assert!(out.output.contains("\n0\n"), "{}", out.output);
3736 }
3737
3738 #[cfg(unix)]
3739 #[tokio::test]
3740 async fn a_hide_that_would_erase_the_workspace_is_skipped_and_said_so() {
3741 if !bwrap_present() {
3742 return;
3743 }
3744 let dir = tempfile::tempdir().unwrap();
3745 let parent = dir.path().parent().unwrap().to_path_buf();
3748 let r = builtin(dir.path(), move |c| {
3749 c.shell_isolate = ShellIsolate::Fs;
3750 c.shell_isolate_hide = vec![parent];
3751 });
3752 let args = json!({ "command": "touch kept && ls -A | wc -l" }).to_string();
3753 let out = r.dispatch("shell", &args, &DenyAll).await;
3754 assert!(!out.is_error, "{}", out.output);
3755 assert!(
3756 dir.path().join("kept").exists(),
3757 "the workspace was erased: {}",
3758 out.output
3759 );
3760 }
3761
3762 #[test]
3763 fn specs_use_openai_function_format() {
3764 let v = serde_json::to_value(registry(Policy::Allow).specs()).unwrap();
3765 assert_eq!(v[0]["type"], "function");
3766 assert_eq!(v[0]["function"]["name"], "echo");
3767 }
3768
3769 #[cfg(unix)]
3773 #[test]
3774 fn replacing_a_file_keeps_its_mode() {
3775 use std::os::unix::fs::PermissionsExt;
3776 let dir = tempfile::tempdir().unwrap();
3777 let path = dir.path().join("run.sh");
3778 std::fs::write(&path, "#!/bin/sh\necho one\n").unwrap();
3779 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
3780
3781 replace_file(&path, "#!/bin/sh\necho two\n").expect("the edit lands");
3782
3783 let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3784 assert_eq!(mode, 0o755, "an executable stays executable");
3785 assert_eq!(
3786 std::fs::read_to_string(&path).unwrap(),
3787 "#!/bin/sh\necho two\n"
3788 );
3789 }
3790
3791 #[cfg(unix)]
3794 #[test]
3795 fn replacing_through_a_symlink_edits_the_target_and_keeps_the_link() {
3796 let dir = tempfile::tempdir().unwrap();
3797 let real = dir.path().join("real.sh");
3798 let link = dir.path().join("link.sh");
3799 std::fs::write(&real, "old\n").unwrap();
3800 std::os::unix::fs::symlink(&real, &link).unwrap();
3801
3802 replace_file(&link, "new\n").expect("the edit lands");
3803
3804 let meta = std::fs::symlink_metadata(&link).unwrap();
3805 assert!(
3806 meta.file_type().is_symlink(),
3807 "the link is still a link, not a copy of the file"
3808 );
3809 assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n");
3810 }
3811}