Update virtual_fs.py

This commit is contained in:
2026-06-02 16:09:35 +00:00
parent 3b4d238f04
commit fd5af0ca2b
+23 -60
View File
@@ -1,76 +1,39 @@
"""
Virtual file system for the deep agent.
This module implements a simple in-memory file system that allows the agent to create
and modify files during its execution. At the end of the run the virtual files can
be dumped to the real file system.
Virtual file system used by the deep agent.
It stores files in memory and can be dumped to the real file system.
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import Dict, Iterable, Tuple
from typing import Dict, Optional
class VirtualFileSystem:
"""A minimal inmemory file system.
"""A simple inmemory file system.
The files are stored in a dictionary mapping a relative path to its content.
The content is stored as a string. The class provides methods for writing
files, reading files and dumping all files to a real directory.
Files are stored as a mapping from a relative path to its content.
"""
def __init__(self) -> None:
self._files: Dict[str, str] = {}
def __init__(self, base_dir: str = "virtual_fs"):
self.base_dir = Path(base_dir)
self.files: Dict[str, str] = {}
def write(self, path: str | Path, content: str) -> None:
"""Write *content* to *path*.
def write_file(self, path: str, content: str) -> None:
norm_path = Path(path).as_posix()
self.files[norm_path] = content
Parameters
----------
path:
The relative path of the file. ``Path`` objects are accepted for
convenience.
content:
The textual content to store.
"""
path = str(path).lstrip("./")
self._files[path] = content
def read_file(self, path: str) -> Optional[str]:
norm_path = Path(path).as_posix()
return self.files.get(norm_path)
def read(self, path: str | Path) -> str:
"""Return the content of *path*.
def list_files(self) -> Dict[str, str]:
return dict(self.files)
Raises
------
KeyError
If the file does not exist.
"""
path = str(path).lstrip("./")
return self._files[path]
def list_files(self) -> Iterable[Tuple[str, str]]:
"""Yield ``(path, content)`` for all stored files."""
for path, content in self._files.items():
yield path, content
def dump_to_disk(self, root: str | Path) -> None:
"""Write all virtual files to *root*.
Parameters
----------
root:
The directory on the real file system where the files should be
created.
"""
root = Path(root)
for path, content in self._files.items():
file_path = root / path
def dump_to_real_fs(self, real_root: str = "real_fs") -> None:
real_root_path = Path(real_root)
for rel_path, content in self.files.items():
file_path = real_root_path / rel_path
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text(content, encoding="utf-8")
def __repr__(self) -> str: # pragma: no cover
return f"VirtualFileSystem({len(self._files)} files)"
# Singleton instance used by the tools.
virtual_fs = VirtualFileSystem()
def __repr__(self) -> str:
return f"VirtualFileSystem(files={list(self.files.keys())})"