Spaces:
Sleeping
Sleeping
Create agent/fs.py
Browse files- agent/fs.py +62 -0
agent/fs.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
BASE_DIR = "/workspace/agent"
|
| 4 |
+
|
| 5 |
+
def safe_path(path: str) -> str:
|
| 6 |
+
full = os.path.abspath(os.path.join(BASE_DIR, path))
|
| 7 |
+
if not full.startswith(BASE_DIR):
|
| 8 |
+
raise PermissionError("Access denied")
|
| 9 |
+
return full
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def init_workspace():
|
| 13 |
+
os.makedirs(safe_path("projects"), exist_ok=True)
|
| 14 |
+
os.makedirs(safe_path("temp"), exist_ok=True)
|
| 15 |
+
os.makedirs(safe_path("logs"), exist_ok=True)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def list_projects():
|
| 19 |
+
base = safe_path("projects")
|
| 20 |
+
return [
|
| 21 |
+
d for d in os.listdir(base)
|
| 22 |
+
if os.path.isdir(os.path.join(base, d))
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def create_project(name):
|
| 27 |
+
path = safe_path(f"projects/{name}")
|
| 28 |
+
os.makedirs(path, exist_ok=True)
|
| 29 |
+
return {"created": name}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def read_file(path, start=0, limit=2000):
|
| 33 |
+
file_path = safe_path(path)
|
| 34 |
+
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 35 |
+
f.seek(start)
|
| 36 |
+
return f.read(limit)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def write_file(path, content):
|
| 40 |
+
file_path = safe_path(path)
|
| 41 |
+
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
| 42 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 43 |
+
f.write(content)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def append_file(path, content):
|
| 47 |
+
file_path = safe_path(path)
|
| 48 |
+
with open(file_path, "a", encoding="utf-8") as f:
|
| 49 |
+
f.write(content)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def tree(path="projects", depth=2):
|
| 53 |
+
root = safe_path(path)
|
| 54 |
+
result = {}
|
| 55 |
+
|
| 56 |
+
for base, dirs, files in os.walk(root):
|
| 57 |
+
level = base.replace(root, "").count(os.sep)
|
| 58 |
+
if level >= depth:
|
| 59 |
+
continue
|
| 60 |
+
result[base.replace(BASE_DIR, "")] = files
|
| 61 |
+
|
| 62 |
+
return result
|