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