77 lines
2.2 KiB
Python
77 lines
2.2 KiB
Python
"""
|
||
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.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from pathlib import Path
|
||
from typing import Dict, Iterable, Tuple
|
||
|
||
|
||
class VirtualFileSystem:
|
||
"""A minimal in‑memory 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.
|
||
"""
|
||
|
||
def __init__(self) -> None:
|
||
self._files: Dict[str, str] = {}
|
||
|
||
def write(self, path: str | Path, content: str) -> None:
|
||
"""Write *content* to *path*.
|
||
|
||
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(self, path: str | Path) -> str:
|
||
"""Return the content of *path*.
|
||
|
||
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
|
||
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()
|