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