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