1use async_trait::async_trait;
24use std::sync::Arc;
25
26use crate::error::{AgentLoopError, Result};
27use crate::session_file::{FileInfo, FileStat, GrepMatch, InitialFile, SessionFile};
28use crate::traits::SessionFileSystem;
29use crate::typed_id::SessionId;
30
31pub const WORKSPACE_MOUNT: &str = crate::session_path::WORKSPACE_PREFIX;
36
37#[derive(Clone)]
39struct Mount {
40 mount_point: String,
43 backend: Arc<dyn SessionFileSystem>,
45 backend_root: String,
47 primary_workspace: bool,
52}
53
54#[derive(Clone)]
55struct ResolvedMount {
56 mount_point: String,
57 backend: Arc<dyn SessionFileSystem>,
58 backend_root: String,
59 backend_path: String,
60 primary_workspace: bool,
61}
62
63pub struct MountFs {
66 mounts: Vec<Mount>,
69 primary: Arc<dyn SessionFileSystem>,
71 cwd: String,
75}
76
77impl MountFs {
78 pub fn new(workspace: Arc<dyn SessionFileSystem>) -> Self {
84 let mounts = vec![
85 Mount {
86 mount_point: "/".to_string(),
87 backend: workspace.clone(),
88 backend_root: "/".to_string(),
89 primary_workspace: true,
90 },
91 Mount {
92 mount_point: WORKSPACE_MOUNT.to_string(),
93 backend: workspace.clone(),
94 backend_root: "/".to_string(),
95 primary_workspace: true,
96 },
97 ];
98 let mut fs = Self {
99 mounts,
100 primary: workspace,
101 cwd: WORKSPACE_MOUNT.to_string(),
102 };
103 fs.sort_mounts();
104 fs
105 }
106
107 pub fn wrap(workspace: Arc<dyn SessionFileSystem>) -> Arc<dyn SessionFileSystem> {
109 Arc::new(Self::new(workspace))
110 }
111
112 pub fn wrap_if_needed(workspace: Arc<dyn SessionFileSystem>) -> Arc<dyn SessionFileSystem> {
117 if workspace.is_mount_resolver() {
118 workspace
119 } else {
120 Self::wrap(workspace)
121 }
122 }
123
124 pub fn with_mount(
127 mut self,
128 mount_point: impl Into<String>,
129 backend: Arc<dyn SessionFileSystem>,
130 backend_root: impl Into<String>,
131 ) -> Self {
132 self.mounts.push(Mount {
133 mount_point: normalize_virtual(&mount_point.into(), "/"),
134 backend,
135 backend_root: normalize_virtual(&backend_root.into(), "/"),
136 primary_workspace: false,
137 });
138 self.sort_mounts();
139 self
140 }
141
142 pub fn cwd(&self) -> String {
144 self.cwd.clone()
145 }
146
147 fn sort_mounts(&mut self) {
148 self.mounts
150 .sort_by_key(|m| std::cmp::Reverse(m.mount_point.len()));
151 }
152
153 fn resolve(&self, input: &str) -> Result<ResolvedMount> {
159 reject_additional_root_traversal(input, &self.cwd)?;
160 let virtual_path = normalize_virtual(input, &self.cwd());
161 for mount in &self.mounts {
162 if let Some(rest) = mount_suffix(&mount.mount_point, &virtual_path) {
163 return Ok(ResolvedMount {
164 mount_point: mount.mount_point.clone(),
165 backend: mount.backend.clone(),
166 backend_root: mount.backend_root.clone(),
167 backend_path: join_backend_path(&mount.backend_root, &rest),
168 primary_workspace: mount.primary_workspace,
169 });
170 }
171 }
172 Ok(ResolvedMount {
175 mount_point: "/".to_string(),
176 backend: self.primary.clone(),
177 backend_root: "/".to_string(),
178 backend_path: virtual_path,
179 primary_workspace: true,
180 })
181 }
182
183 fn grep_mounts(&self) -> Vec<ResolvedMount> {
184 let mut out: Vec<ResolvedMount> = Vec::new();
185 for mount in self.mounts.iter().rev() {
186 if out.iter().any(|existing| {
187 Arc::ptr_eq(&existing.backend, &mount.backend)
188 && existing.backend_root == mount.backend_root
189 }) {
190 continue;
191 }
192 out.push(ResolvedMount {
193 mount_point: mount.mount_point.clone(),
194 backend: mount.backend.clone(),
195 backend_root: mount.backend_root.clone(),
196 backend_path: mount.backend_root.clone(),
197 primary_workspace: mount.primary_workspace,
198 });
199 }
200 out
201 }
202}
203
204impl ResolvedMount {
205 fn map_session_file(&self, mut file: SessionFile) -> SessionFile {
206 file.path = self.to_virtual_output_path(&file.path);
207 file.name = FileInfo::name_from_path(&file.path);
208 file
209 }
210
211 fn map_file_info(&self, mut info: FileInfo) -> FileInfo {
212 info.path = self.to_virtual_output_path(&info.path);
213 info.name = FileInfo::name_from_path(&info.path);
214 info
215 }
216
217 fn map_file_stat(&self, mut stat: FileStat) -> FileStat {
218 stat.path = self.to_virtual_output_path(&stat.path);
219 stat.name = FileInfo::name_from_path(&stat.path);
220 stat
221 }
222
223 fn map_grep_match(&self, mut grep_match: GrepMatch) -> GrepMatch {
224 grep_match.path = self.to_virtual_output_path(&grep_match.path);
225 grep_match
226 }
227
228 fn to_virtual_output_path(&self, backend_path: &str) -> String {
229 if self.primary_workspace {
230 return normalize_virtual(backend_path, "/");
231 }
232 let normalized = normalize_virtual(backend_path, "/");
233 let rest = mount_suffix(&self.backend_root, &normalized).unwrap_or(normalized);
234 join_backend_path(&self.mount_point, &rest)
235 }
236}
237
238fn normalize_virtual(input: &str, cwd: &str) -> String {
241 let combined = if input.starts_with('/') {
242 input.to_string()
243 } else {
244 format!("{}/{}", cwd.trim_end_matches('/'), input)
245 };
246 let mut stack: Vec<&str> = Vec::new();
247 for segment in combined.split('/') {
248 match segment {
249 "" | "." => {}
250 ".." => {
251 stack.pop();
252 }
253 other => stack.push(other),
254 }
255 }
256 if stack.is_empty() {
257 "/".to_string()
258 } else {
259 format!("/{}", stack.join("/"))
260 }
261}
262
263fn reject_additional_root_traversal(input: &str, cwd: &str) -> Result<()> {
264 let combined = if input.starts_with('/') {
265 input.to_string()
266 } else {
267 format!("{}/{}", cwd.trim_end_matches('/'), input)
268 };
269 let segments: Vec<&str> = combined
270 .split('/')
271 .filter(|segment| !segment.is_empty())
272 .collect();
273 for window_start in 0..segments.len().saturating_sub(2) {
274 if segments[window_start] == "workspace" && segments[window_start + 1] == "roots" {
275 let root_name_idx = window_start + 2;
276 if segments[root_name_idx].is_empty() {
277 continue;
278 }
279 if segments
280 .iter()
281 .skip(root_name_idx + 1)
282 .any(|segment| *segment == "..")
283 {
284 return Err(AgentLoopError::tool(format!(
285 "path traversal rejected: {input}"
286 )));
287 }
288 }
289 }
290 Ok(())
291}
292
293fn mount_suffix(mount_point: &str, virtual_path: &str) -> Option<String> {
297 if mount_point == "/" {
298 return Some(virtual_path.to_string());
300 }
301 if virtual_path == mount_point {
302 return Some("/".to_string());
303 }
304 virtual_path
305 .strip_prefix(mount_point)
306 .filter(|rest| rest.starts_with('/'))
307 .map(|rest| rest.to_string())
308}
309
310fn join_backend_path(backend_root: &str, rest: &str) -> String {
312 if backend_root == "/" {
313 return rest.to_string();
314 }
315 if rest == "/" {
316 return backend_root.to_string();
317 }
318 format!("{backend_root}{rest}")
319}
320
321#[async_trait]
322impl SessionFileSystem for MountFs {
323 fn display_root(&self) -> String {
324 self.primary.display_root()
325 }
326
327 fn is_mount_resolver(&self) -> bool {
328 true
329 }
330
331 fn resolve_path(&self, input: &str) -> String {
332 let virtual_path = normalize_virtual(input, &self.cwd());
337 match self.resolve(&virtual_path) {
338 Ok(resolved) if resolved.primary_workspace => {
339 resolved.backend.display_path(&resolved.backend_path)
340 }
341 _ => virtual_path,
342 }
343 }
344
345 fn display_path(&self, path: &str) -> String {
346 let virtual_path = normalize_virtual(path, "/");
347 match self.resolve(&virtual_path) {
348 Ok(resolved) if resolved.primary_workspace => {
349 resolved.backend.display_path(&resolved.backend_path)
350 }
351 _ => virtual_path,
352 }
353 }
354
355 async fn read_file(&self, session_id: SessionId, path: &str) -> Result<Option<SessionFile>> {
356 let resolved = self.resolve(path)?;
357 Ok(resolved
358 .backend
359 .read_file(session_id, &resolved.backend_path)
360 .await?
361 .map(|file| resolved.map_session_file(file)))
362 }
363
364 async fn write_file(
365 &self,
366 session_id: SessionId,
367 path: &str,
368 content: &str,
369 encoding: &str,
370 ) -> Result<SessionFile> {
371 let resolved = self.resolve(path)?;
372 Ok(resolved.map_session_file(
373 resolved
374 .backend
375 .write_file(session_id, &resolved.backend_path, content, encoding)
376 .await?,
377 ))
378 }
379
380 async fn write_file_if_content_matches(
381 &self,
382 session_id: SessionId,
383 path: &str,
384 expected_content: &str,
385 expected_encoding: &str,
386 content: &str,
387 encoding: &str,
388 ) -> Result<Option<SessionFile>> {
389 let resolved = self.resolve(path)?;
390 Ok(resolved
391 .backend
392 .write_file_if_content_matches(
393 session_id,
394 &resolved.backend_path,
395 expected_content,
396 expected_encoding,
397 content,
398 encoding,
399 )
400 .await?
401 .map(|file| resolved.map_session_file(file)))
402 }
403
404 async fn delete_file(
405 &self,
406 session_id: SessionId,
407 path: &str,
408 recursive: bool,
409 ) -> Result<bool> {
410 let resolved = self.resolve(path)?;
411 resolved
412 .backend
413 .delete_file(session_id, &resolved.backend_path, recursive)
414 .await
415 }
416
417 async fn list_directory(&self, session_id: SessionId, path: &str) -> Result<Vec<FileInfo>> {
418 let resolved = self.resolve(path)?;
419 Ok(resolved
420 .backend
421 .list_directory(session_id, &resolved.backend_path)
422 .await?
423 .into_iter()
424 .map(|info| resolved.map_file_info(info))
425 .collect())
426 }
427
428 async fn stat_file(&self, session_id: SessionId, path: &str) -> Result<Option<FileStat>> {
429 let resolved = self.resolve(path)?;
430 Ok(resolved
431 .backend
432 .stat_file(session_id, &resolved.backend_path)
433 .await?
434 .map(|stat| resolved.map_file_stat(stat)))
435 }
436
437 async fn grep_files(
438 &self,
439 session_id: SessionId,
440 pattern: &str,
441 path_pattern: Option<&str>,
442 ) -> Result<Vec<GrepMatch>> {
443 match path_pattern {
444 Some(pp) => {
445 let resolved = self.resolve(pp)?;
446 Ok(resolved
447 .backend
448 .grep_files(session_id, pattern, Some(&resolved.backend_path))
449 .await?
450 .into_iter()
451 .map(|grep_match| resolved.map_grep_match(grep_match))
452 .collect())
453 }
454 None => {
455 let mut matches = Vec::new();
456 for resolved in self.grep_mounts() {
457 matches.extend(
458 resolved
459 .backend
460 .grep_files(session_id, pattern, Some(&resolved.backend_path))
461 .await?
462 .into_iter()
463 .map(|grep_match| resolved.map_grep_match(grep_match)),
464 );
465 }
466 matches.sort_by(|a, b| {
467 a.path
468 .cmp(&b.path)
469 .then(a.line_number.cmp(&b.line_number))
470 .then(a.line.cmp(&b.line))
471 });
472 Ok(matches)
473 }
474 }
475 }
476
477 async fn create_directory(&self, session_id: SessionId, path: &str) -> Result<FileInfo> {
478 let resolved = self.resolve(path)?;
479 Ok(resolved.map_file_info(
480 resolved
481 .backend
482 .create_directory(session_id, &resolved.backend_path)
483 .await?,
484 ))
485 }
486
487 async fn seed_initial_file(&self, session_id: SessionId, file: &InitialFile) -> Result<()> {
488 let resolved = self.resolve(&file.path)?;
489 let seeded = InitialFile {
490 path: resolved.backend_path,
491 content: file.content.clone(),
492 encoding: file.encoding.clone(),
493 is_readonly: file.is_readonly,
494 };
495 resolved
496 .backend
497 .seed_initial_file(session_id, &seeded)
498 .await
499 }
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505
506 fn sid() -> SessionId {
507 SessionId::from_seed(1)
508 }
509
510 #[derive(Default)]
513 struct FlatStore {
514 files: std::sync::Mutex<std::collections::HashMap<String, String>>,
515 }
516
517 #[async_trait]
518 impl SessionFileSystem for FlatStore {
519 fn is_mount_resolver(&self) -> bool {
520 false
521 }
522
523 async fn read_file(&self, sid: SessionId, path: &str) -> Result<Option<SessionFile>> {
524 let files = self.files.lock().unwrap();
525 Ok(files.get(path).map(|content| SessionFile {
526 id: uuid::Uuid::nil(),
527 session_id: sid.uuid(),
528 path: path.to_string(),
529 name: path.rsplit('/').next().unwrap_or("").to_string(),
530 content: Some(content.clone()),
531 encoding: "text".to_string(),
532 is_directory: false,
533 is_readonly: false,
534 size_bytes: content.len() as i64,
535 created_at: chrono::Utc::now(),
536 updated_at: chrono::Utc::now(),
537 }))
538 }
539 async fn write_file(
540 &self,
541 sid: SessionId,
542 path: &str,
543 content: &str,
544 encoding: &str,
545 ) -> Result<SessionFile> {
546 self.files
547 .lock()
548 .unwrap()
549 .insert(path.to_string(), content.to_string());
550 Ok(SessionFile {
551 id: uuid::Uuid::nil(),
552 session_id: sid.uuid(),
553 path: path.to_string(),
554 name: path.rsplit('/').next().unwrap_or("").to_string(),
555 content: Some(content.to_string()),
556 encoding: encoding.to_string(),
557 is_directory: false,
558 is_readonly: false,
559 size_bytes: content.len() as i64,
560 created_at: chrono::Utc::now(),
561 updated_at: chrono::Utc::now(),
562 })
563 }
564 async fn delete_file(&self, _: SessionId, path: &str, _: bool) -> Result<bool> {
565 Ok(self.files.lock().unwrap().remove(path).is_some())
566 }
567 async fn list_directory(&self, _: SessionId, _: &str) -> Result<Vec<FileInfo>> {
568 Ok(vec![])
569 }
570 async fn stat_file(&self, _: SessionId, path: &str) -> Result<Option<FileStat>> {
571 let files = self.files.lock().unwrap();
572 Ok(files.get(path).map(|content| FileStat {
573 path: path.to_string(),
574 name: path.rsplit('/').next().unwrap_or("").to_string(),
575 is_directory: false,
576 is_readonly: false,
577 size_bytes: content.len() as i64,
578 created_at: chrono::Utc::now(),
579 updated_at: chrono::Utc::now(),
580 }))
581 }
582 async fn grep_files(
583 &self,
584 _: SessionId,
585 pattern: &str,
586 path_pattern: Option<&str>,
587 ) -> Result<Vec<GrepMatch>> {
588 let files = self.files.lock().unwrap();
589 let mut matches = Vec::new();
590 for (path, content) in files.iter() {
591 if let Some(filter) = path_pattern
592 && !path.contains(filter)
593 {
594 continue;
595 }
596 for (idx, line) in content.lines().enumerate() {
597 if line.contains(pattern) {
598 matches.push(GrepMatch {
599 path: path.clone(),
600 line_number: idx + 1,
601 line: line.to_string(),
602 });
603 }
604 }
605 }
606 Ok(matches)
607 }
608 async fn create_directory(&self, sid: SessionId, path: &str) -> Result<FileInfo> {
609 Ok(FileInfo {
610 id: uuid::Uuid::nil(),
611 session_id: sid.uuid(),
612 name: path.rsplit('/').next().unwrap_or("").to_string(),
613 path: path.to_string(),
614 is_directory: true,
615 is_readonly: false,
616 size_bytes: 0,
617 created_at: chrono::Utc::now(),
618 updated_at: chrono::Utc::now(),
619 })
620 }
621 }
622
623 #[test]
624 fn normalize_resolves_relative_against_cwd() {
625 assert_eq!(
626 normalize_virtual("foo/bar", "/workspace"),
627 "/workspace/foo/bar"
628 );
629 assert_eq!(normalize_virtual("/foo", "/workspace"), "/foo");
630 assert_eq!(normalize_virtual("a/../b", "/workspace"), "/workspace/b");
631 assert_eq!(normalize_virtual("../../x", "/workspace"), "/x");
632 assert_eq!(normalize_virtual(".", "/workspace"), "/workspace");
633 assert_eq!(normalize_virtual("/", "/workspace"), "/");
634 }
635
636 #[tokio::test]
637 async fn workspace_and_root_address_the_same_file() {
638 let backend: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
639 let fs = MountFs::new(backend);
640
641 fs.write_file(sid(), "/workspace/src/lib.rs", "X", "text")
643 .await
644 .unwrap();
645 let via_root = fs.read_file(sid(), "/src/lib.rs").await.unwrap().unwrap();
646 assert_eq!(via_root.content.as_deref(), Some("X"));
647 assert_eq!(via_root.path, "/src/lib.rs");
649 }
650
651 #[tokio::test]
652 async fn relative_paths_resolve_against_cwd() {
653 let backend: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
654 let fs = MountFs::new(backend);
655 assert_eq!(fs.cwd(), "/workspace");
656
657 fs.write_file(sid(), "notes.md", "hi", "text")
658 .await
659 .unwrap();
660 let read = fs.read_file(sid(), "/notes.md").await.unwrap().unwrap();
662 assert_eq!(read.content.as_deref(), Some("hi"));
663 }
664
665 #[tokio::test]
666 async fn legacy_subtree_paths_pass_through_root_mount() {
667 let backend: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
668 let fs = MountFs::new(backend);
669 fs.write_file(sid(), "/outputs/call.stdout", "out", "text")
671 .await
672 .unwrap();
673 let read = fs
674 .read_file(sid(), "/workspace/outputs/call.stdout")
675 .await
676 .unwrap()
677 .unwrap();
678 assert_eq!(read.content.as_deref(), Some("out"));
679 }
680
681 #[test]
682 fn display_uses_the_primary_backends_identity() {
683 let backend: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
684 let fs = MountFs::new(backend);
685 assert_eq!(fs.display_root(), "/workspace");
686 assert_eq!(fs.display_path("/src/lib.rs"), "/workspace/src/lib.rs");
687 assert_eq!(fs.display_path("/"), "/workspace");
688 assert_eq!(fs.resolve_path("src/lib.rs"), "/workspace/src/lib.rs");
689 }
690
691 #[tokio::test]
692 async fn additional_mount_routes_to_its_backend() {
693 let workspace: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
694 let volume: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
695 let fs = MountFs::new(workspace).with_mount("/data", volume.clone(), "/");
696
697 fs.write_file(sid(), "/data/report.csv", "1,2,3", "text")
698 .await
699 .unwrap();
700 let from_volume = volume
702 .read_file(sid(), "/report.csv")
703 .await
704 .unwrap()
705 .unwrap();
706 assert_eq!(from_volume.content.as_deref(), Some("1,2,3"));
707 }
708
709 #[tokio::test]
710 async fn additional_mount_outputs_use_virtual_paths() {
711 let workspace: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
712 let volume: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
713 let fs = MountFs::new(workspace).with_mount("/workspace/roots/backend", volume, "/");
714
715 let written = fs
716 .write_file(
717 sid(),
718 "/workspace/roots/backend/Cargo.toml",
719 "name = \"backend\"",
720 "text",
721 )
722 .await
723 .unwrap();
724 assert_eq!(written.path, "/workspace/roots/backend/Cargo.toml");
725
726 let stat = fs
727 .stat_file(sid(), "/workspace/roots/backend/Cargo.toml")
728 .await
729 .unwrap()
730 .unwrap();
731 assert_eq!(stat.path, "/workspace/roots/backend/Cargo.toml");
732 assert_eq!(
733 fs.display_path(&stat.path),
734 "/workspace/roots/backend/Cargo.toml"
735 );
736 assert_eq!(
737 fs.resolve_path("/workspace/roots/backend/Cargo.toml"),
738 "/workspace/roots/backend/Cargo.toml"
739 );
740 }
741
742 #[tokio::test]
743 async fn grep_without_path_searches_all_mounts() {
744 let workspace: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
745 let volume: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
746 let fs = MountFs::new(workspace).with_mount("/workspace/roots/backend", volume, "/");
747
748 fs.write_file(sid(), "/workspace/README.md", "needle primary", "text")
749 .await
750 .unwrap();
751 fs.write_file(
752 sid(),
753 "/workspace/roots/backend/Cargo.toml",
754 "needle backend",
755 "text",
756 )
757 .await
758 .unwrap();
759
760 let matches = fs.grep_files(sid(), "needle", None).await.unwrap();
761 let paths: Vec<_> = matches.into_iter().map(|m| m.path).collect();
762 assert_eq!(
763 paths,
764 vec![
765 "/README.md".to_string(),
766 "/workspace/roots/backend/Cargo.toml".to_string()
767 ]
768 );
769 }
770
771 #[test]
772 fn mount_fs_identifies_as_resolver() {
773 let workspace: Arc<dyn SessionFileSystem> = Arc::new(FlatStore::default());
774 let fs = MountFs::wrap(workspace);
775 assert!(fs.is_mount_resolver());
776 let again = MountFs::wrap_if_needed(fs.clone());
777 assert!(Arc::ptr_eq(&fs, &again));
778 }
779}