Spaces:
Runtime error

ammo-card / workspace.py
Expanded-Repetition's picture
Upload 17 files
2b4b6d8 verified
Raw History Blame Contribute Delete
14.1 kB
from __future__ import annotations
import os
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from datetime import datetime
from pathlib import Path, PurePosixPath
APP_DIR = Path(__file__).resolve().parent.parent
WORKSPACE_ROOT = APP_DIR / "workspace"
WORKSPACE_ROOT.mkdir(parents=True, exist_ok=True)
MAX_READ_BYTES = 30_000
MAX_WRITE_BYTES = 100_000
MAX_ZIP_MEMBERS = 200
MAX_ZIP_TOTAL_BYTES = 15_000_000
ALLOWED_SUFFIXES = {
".txt", ".md", ".py", ".json", ".yaml", ".yml", ".html", ".css", ".js",
".ts", ".tsx", ".jsx", ".toml", ".ini", ".log", ".sql", ".sh", ".xml",
".rst", ".java", ".kt", ".go", ".rs", ".c", ".h", ".cpp", ".hpp", ".cs",
".php", ".rb", ".swift"
}
FORBIDDEN_NAMES = {".env", ".env.local", ".env.production", "id_rsa", "id_ed25519", "credentials.json"}
def _is_sensitive(path: Path) -> bool:
if path.name.lower() in FORBIDDEN_NAMES:
return True
if path.suffix.lower() in {".pem", ".key", ".p12", ".pfx", ".sqlite", ".sqlite3", ".db"}:
return True
return any(part.lower() in {".git", ".ssh", ".aws", ".config", ".secrets"} for part in path.parts)
def resolve_workspace_path(relative: str = ".", *, allow_directory: bool = True) -> Path:
rel = (relative or ".").strip()
candidate_rel = PurePosixPath(rel.replace("\\", "/"))
if candidate_rel.is_absolute() or ".." in candidate_rel.parts or "\x00" in rel:
raise ValueError("المسار يجب أن يكون نسبياً داخل workspace، ولا يسمح بـ .. أو المسارات المطلقة.")
if any(part.startswith(".") and part != ".amo_backups" for part in candidate_rel.parts if part not in {".", ".."}):
raise ValueError("المسارات المخفية محجوبة افتراضياً لحماية الإعدادات والأسرار.")
root = WORKSPACE_ROOT.resolve()
target = (root / Path(*candidate_rel.parts)).resolve()
if target != root and root not in target.parents:
raise ValueError("تم رفض مسار يخرج خارج مساحة العمل.")
# Reject direct symlink traversal even when its target happens to remain inside root.
cursor = root
for part in candidate_rel.parts:
if part in {".", ""}:
continue
cursor = cursor / part
if cursor.is_symlink():
raise ValueError("المسارات الرمزية محجوبة داخل مساحة العمل.")
if _is_sensitive(target):
raise ValueError("تم حجب ملف حساس أو إعداد خاص.")
if not allow_directory and target.suffix.lower() not in ALLOWED_SUFFIXES:
raise ValueError(f"امتداد الملف غير مسموح: {target.suffix}")
return target
def list_workspace(path: str = ".") -> str:
target = resolve_workspace_path(path, allow_directory=True)
if not target.exists():
return f"المسار غير موجود: {path}"
if not target.is_dir():
return f"ليس مجلداً: {path}"
rows = []
for item in sorted(target.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower())):
if item.name == ".amo_backups" or item.name.startswith(".") or _is_sensitive(item):
continue
suffix = "/" if item.is_dir() else ""
size = "" if item.is_dir() else f" ({item.stat().st_size} bytes)"
rows.append(f"{item.name}{suffix}{size}")
if len(rows) >= 150:
rows.append("… جرى تحديد القائمة إلى 150 عنصراً")
break
return "المجلد فارغ." if not rows else "\n".join(rows)
def read_workspace_file(path: str) -> str:
target = resolve_workspace_path(path, allow_directory=False)
if not target.exists() or not target.is_file():
return f"الملف غير موجود: {path}"
if target.stat().st_size > MAX_READ_BYTES:
return f"الملف أكبر من حد القراءة {MAX_READ_BYTES} bytes؛ اقرأه على أجزاء أو صغّر الملف."
try:
return target.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return f"تعذرت قراءة الملف: {type(exc).__name__}: {exc}"
def write_workspace_file(path: str, content: str) -> str:
target = resolve_workspace_path(path, allow_directory=False)
content = content or ""
if len(content.encode("utf-8")) > MAX_WRITE_BYTES:
return f"رفض الكتابة: الحد الأقصى {MAX_WRITE_BYTES} bytes لكل ملف."
target.parent.mkdir(parents=True, exist_ok=True)
# Revalidate after creating parent directories.
target = resolve_workspace_path(path, allow_directory=False)
backup_note = ""
if target.exists():
if not target.is_file():
return "رفض الكتابة: الهدف ليس ملفاً عادياً."
backup_dir = WORKSPACE_ROOT / ".amo_backups"
backup_dir.mkdir(exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
backup_name = (str(Path(path)).replace("/", "__").replace("\\", "__") + f".{stamp}.bak")
shutil.copy2(target, backup_dir / backup_name)
backup_note = f" النسخة السابقة محفوظة في .amo_backups/{backup_name}."
temp = target.with_name(target.name + ".amo-tmp")
temp.write_text(content, encoding="utf-8")
os.replace(temp, target)
return f"تم حفظ {path} ({len(content.encode('utf-8'))} bytes)." + backup_note
def import_workspace_zip(zip_path: str) -> tuple[int, int, list[str]]:
"""Extract only source/text files after rejecting traversal and oversized members."""
src = Path(zip_path)
written, total, errors = 0, 0, []
if not src.exists() or src.suffix.lower() != ".zip":
return 0, 0, ["اختر ملف ZIP صالحاً."]
try:
with zipfile.ZipFile(src) as zf:
members = [m for m in zf.infolist() if not m.is_dir()][:MAX_ZIP_MEMBERS]
for info in members:
pure = PurePosixPath(info.filename)
if pure.is_absolute() or ".." in pure.parts or not pure.parts:
errors.append(f"تخطي مسار غير آمن: {info.filename[:120]}")
continue
path = Path(*pure.parts)
if _is_sensitive(path) or path.suffix.lower() not in ALLOWED_SUFFIXES:
continue
if info.file_size > MAX_WRITE_BYTES:
errors.append(f"تخطي ملف كبير: {info.filename}")
continue
total += info.file_size
if total > MAX_ZIP_TOTAL_BYTES:
errors.append("توقف الاستيراد عند حد 15MB الإجمالي.")
break
try:
text = zf.read(info).decode("utf-8", errors="replace")
result = write_workspace_file(str(path), text)
if result.startswith("تم حفظ"):
written += 1
else:
errors.append(f"{info.filename}: {result}")
except Exception as exc:
errors.append(f"{info.filename}: {type(exc).__name__}: {exc}")
except (OSError, zipfile.BadZipFile) as exc:
errors.append(f"تعذر فتح ZIP: {type(exc).__name__}: {exc}")
return written, total, errors
def compile_workspace_python(path: str = ".") -> str:
target = resolve_workspace_path(path, allow_directory=True)
if not target.exists():
return f"المسار غير موجود: {path}"
files = [target] if target.is_file() and target.suffix.lower() == ".py" else list(target.rglob("*.py")) if target.is_dir() else []
files = [p for p in files if not _is_sensitive(p) and ".amo_backups" not in p.parts][:300]
if not files:
return "لم يتم العثور على ملفات Python مسموحة ضمن المسار."
errors, passed = [], 0
for file in files:
try:
if file.is_symlink() or WORKSPACE_ROOT.resolve() not in file.resolve().parents:
continue
source = file.read_text(encoding="utf-8", errors="replace")
compile(source, str(file.relative_to(WORKSPACE_ROOT)), "exec")
passed += 1
except SyntaxError as exc:
errors.append(f"{file.relative_to(WORKSPACE_ROOT)}:{exc.lineno}: {exc.msg}")
except OSError as exc:
errors.append(f"{file.name}: {exc}")
report = f"فحص الصياغة: نجح {passed} من {len(files)} ملف/ملفات."
if errors:
report += "\n" + "\n".join(errors[:30])
return report
def _test_process_limits():
try:
import resource
resource.setrlimit(resource.RLIMIT_CPU, (15, 15))
resource.setrlimit(resource.RLIMIT_FSIZE, (10_000_000, 10_000_000))
resource.setrlimit(resource.RLIMIT_NOFILE, (48, 48))
if hasattr(resource, "RLIMIT_CORE"):
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
except Exception:
pass
def run_workspace_unittests(path: str = ".", timeout_seconds: int = 20) -> str:
"""Explicitly requested test execution. Limited process, but not a hardened VM."""
target = resolve_workspace_path(path, allow_directory=True)
if not target.exists() or not target.is_dir():
return "مسار الاختبارات يجب أن يكون مجلداً موجوداً داخل مساحة العمل."
test_files = list(target.rglob("test*.py"))[:200]
if not test_files:
return "لم أعثر على ملفات test*.py. أضف اختبارات unittest ثم أعد المحاولة."
runner = (
"import os, sys, unittest\n"
f"root = {str(WORKSPACE_ROOT.resolve())!r}\n"
f"start = {str(target.resolve())!r}\n"
"sys.path.insert(0, root)\n"
"suite = unittest.defaultTestLoader.discover(start_dir=start, top_level_dir=root)\n"
"result = unittest.TextTestRunner(verbosity=2).run(suite)\n"
"raise SystemExit(0 if result.wasSuccessful() and result.testsRun > 0 else 1)\n"
)
env = {"PATH": os.environ.get("PATH", ""), "HOME": tempfile.gettempdir(), "PYTHONIOENCODING": "utf-8", "PYTHONHASHSEED": "0"}
start_time = time.monotonic()
try:
proc = subprocess.run(
[sys.executable, "-I", "-c", runner], cwd=str(WORKSPACE_ROOT), env=env,
stdin=subprocess.DEVNULL, capture_output=True, text=True,
timeout=max(3, min(int(timeout_seconds), 25)),
preexec_fn=_test_process_limits if os.name == "posix" else None,
)
output = (proc.stdout + "\n" + proc.stderr).strip()
return f"رمز الخروج: {proc.returncode} · الزمن: {time.monotonic()-start_time:.1f}s\n{output[:7000]}"
except subprocess.TimeoutExpired:
return f"تجاوزت الاختبارات {timeout_seconds} ثانية وأُوقفت."
except Exception as exc:
return f"تعذر تشغيل الاختبارات: {type(exc).__name__}: {exc}"
def linux_safe_task(task: str) -> str:
"""Run a small fixed allow-list of Linux diagnostics without arbitrary shell input."""
task = (task or "").strip()
root = WORKSPACE_ROOT.resolve()
commands = {
"python_version": [sys.executable, "--version"],
"linux_info": ["uname", "-a"],
"disk_usage": ["df", "-h", str(root)],
"installed_packages": [sys.executable, "-m", "pip", "list", "--format=columns"],
}
if task not in commands:
return "مهمة Linux غير مسموحة. استخدم أحد المعرفات: python_version, linux_info, disk_usage, installed_packages."
env = {"PATH": os.environ.get("PATH", ""), "HOME": tempfile.gettempdir(), "PYTHONIOENCODING": "utf-8", "PYTHONHASHSEED": "0"}
start_time = time.monotonic()
try:
result = subprocess.run(
commands[task], cwd=str(root), env=env, stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=10, check=False,
preexec_fn=_test_process_limits if os.name == "posix" else None,
)
output = (result.stdout + "\n" + result.stderr).strip()
return f"مهمة Linux `{task}` · exit={result.returncode} · {time.monotonic()-start_time:.1f}s\n{output[:5000]}"
except Exception as exc:
return f"فشل فحص Linux: {type(exc).__name__}: {exc}"
def dispatch_tool(name: str, arguments: dict, *, allow_writes: bool, allow_tests: bool) -> str:
if name == "linux_safe_task":
return linux_safe_task(str(arguments.get("task", "")))
if name == "workspace_list":
return list_workspace(str(arguments.get("path", ".")))
if name == "workspace_read":
return read_workspace_file(str(arguments.get("path", "")))
if name == "workspace_write":
if not allow_writes:
return "مرفوض: المستخدم لم يفعّل السماح بكتابة الملفات في هذه المهمة."
rel = PurePosixPath(str(arguments.get("path", "")).replace("\\", "/"))
if "tests" in rel.parts or rel.name.startswith("test_") or rel.name.endswith("_test.py"):
return "مرفوض: الوكيل لا يغيّر ملفات الاختبارات تلقائياً؛ اطلب تغييرها يدوياً عند الحاجة."
return write_workspace_file(str(arguments.get("path", "")), str(arguments.get("content", "")))
if name == "workspace_check_python":
mode = str(arguments.get("mode", "compile"))
path = str(arguments.get("path", "."))
if mode == "compile":
return compile_workspace_python(path)
if mode == "unittest":
if not allow_tests:
return "مرفوض: تشغيل الاختبارات يحتاج تفعيل إذن تشغيل الاختبارات لهذه المهمة."
return run_workspace_unittests(path)
return "وضع فحص غير معروف؛ استخدم compile أو unittest."
return f"أداة غير متاحة: {name}"