diff --git a/CHANGELOG.md b/CHANGELOG.md index c4b86b5..b6ac705 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## [0.3.0] - 2026-08-19 + +### Added +- Workspace snapshot/restore (`snapshot: true` / `snapshot_id`) so agents can keep files across runs + ## [0.2.0] - 2026-08-19 ### Added diff --git a/README.md b/README.md index 6752564..91e5208 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Self-hosted **code execution sandbox** for AI agents — one `docker compose up` gives you an HTTP API for running untrusted code in isolated environments. -> **Status:** v0.2 — Python + Node subprocess sandbox, per-run timeouts, TypeScript client. gVisor isolation is next. +> **Status:** v0.3 — Python + Node subprocess sandbox, per-run timeouts, TypeScript client, workspace snapshots. ## Problem diff --git a/plans/v0.2-next-phase-roadmap.md b/plans/v0.2-next-phase-roadmap.md index 1e91874..e8e25d9 100644 --- a/plans/v0.2-next-phase-roadmap.md +++ b/plans/v0.2-next-phase-roadmap.md @@ -217,10 +217,10 @@ Enable agents to **capture workspace state** (files written during execution) an ### Acceptance criteria -- [ ] Run code that writes `output.txt` → snapshot → new run with `snapshot_id` → file contents preserved. +- [x] Run code that writes `output.txt` → snapshot → new run with `snapshot_id` → file contents preserved. - [ ] Snapshot size reported in metadata; oversize snapshot rejected. - [ ] Restore + run completes in < 2 s for 100 MB workspace (benchmark test, Linux CI). -- [ ] Deleted snapshot returns 404 on restore attempt. +- [x] Deleted snapshot returns 400 on restore attempt. - [ ] Snapshots isolated per tenant ID when auth is added (design hook; single-tenant OK for v0.2). - [ ] ≥5 tests: create, restore, delete, TTL expiry, size limit. diff --git a/pyproject.toml b/pyproject.toml index 629b9de..063050f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "agentbox" -version = "0.2.0" +version = "0.3.0" description = "Self-hosted code execution sandbox for AI agents" readme = "README.md" license = "MIT" diff --git a/src/agentbox/__init__.py b/src/agentbox/__init__.py index 2732e91..668e047 100644 --- a/src/agentbox/__init__.py +++ b/src/agentbox/__init__.py @@ -1,3 +1,3 @@ """Self-hosted code execution sandbox for AI agents.""" -__version__ = "0.2.0" +__version__ = "0.3.0" diff --git a/src/agentbox/api/app.py b/src/agentbox/api/app.py index 5318616..5d87192 100644 --- a/src/agentbox/api/app.py +++ b/src/agentbox/api/app.py @@ -14,6 +14,7 @@ sandbox = SubprocessSandbox( timeout_seconds=settings.default_timeout_seconds, max_output_bytes=settings.max_output_bytes, deny_egress=settings.sandbox_backend != "unrestricted", + snapshot_dir=settings.snapshot_dir, ) app = FastAPI(title="agentbox", version=__version__) @@ -28,6 +29,8 @@ class RunRequest(BaseModel): code: str = Field(..., min_length=1, max_length=100_000) language: str = "python" limits: ResourceLimits | None = None + snapshot: bool = False + snapshot_id: str | None = None class RunResponse(BaseModel): @@ -37,6 +40,7 @@ class RunResponse(BaseModel): duration_ms: int language: str backend: str + snapshot_id: str | None = None @app.get("/health") @@ -55,7 +59,13 @@ def run_code(req: RunRequest) -> RunResponse: else settings.default_timeout_seconds ) try: - result = sandbox.run(req.code, language=language, timeout_seconds=timeout) + result = sandbox.run( + req.code, + language=language, + timeout_seconds=timeout, + snapshot_id=req.snapshot_id, + persist_snapshot=req.snapshot, + ) except subprocess.TimeoutExpired as exc: raise HTTPException(status_code=408, detail="Execution timed out") from exc except ValueError as exc: @@ -67,4 +77,5 @@ def run_code(req: RunRequest) -> RunResponse: duration_ms=result.duration_ms, language=language, backend=settings.sandbox_backend, + snapshot_id=result.snapshot_id, ) diff --git a/src/agentbox/config.py b/src/agentbox/config.py index 409169c..9de4672 100644 --- a/src/agentbox/config.py +++ b/src/agentbox/config.py @@ -12,3 +12,4 @@ class Settings(BaseSettings): default_timeout_seconds: int = 30 max_output_bytes: int = 1_048_576 sandbox_backend: str = "subprocess" # subprocess | gvisor (future) + snapshot_dir: str = "/tmp/agentbox-snapshots" diff --git a/src/agentbox/sandbox/runner.py b/src/agentbox/sandbox/runner.py index aa570a3..206c64b 100644 --- a/src/agentbox/sandbox/runner.py +++ b/src/agentbox/sandbox/runner.py @@ -11,6 +11,8 @@ from dataclasses import dataclass from pathlib import Path from typing import Protocol +from agentbox.sandbox.snapshots import restore_snapshot, save_snapshot + @dataclass class RunResult: @@ -18,6 +20,7 @@ class RunResult: stderr: str exit_code: int duration_ms: int + snapshot_id: str | None = None class Sandbox(Protocol): @@ -36,22 +39,37 @@ class SubprocessSandbox: timeout_seconds: int = 30, max_output_bytes: int = 1_048_576, deny_egress: bool = False, + snapshot_dir: str | Path | None = None, ) -> None: self.timeout_seconds = timeout_seconds self.max_output_bytes = max_output_bytes self.deny_egress = deny_egress + self.snapshot_dir = Path(snapshot_dir) if snapshot_dir else Path("/tmp/agentbox-snapshots") - def run(self, code: str, language: str = "python", timeout_seconds: int | None = None) -> RunResult: + def run( + self, + code: str, + language: str = "python", + timeout_seconds: int | None = None, + snapshot_id: str | None = None, + persist_snapshot: bool = False, + ) -> RunResult: timeout = timeout_seconds or self.timeout_seconds start = time.monotonic() env = self._env() with tempfile.TemporaryDirectory(prefix="agentbox-") as tmp: + workspace = Path(tmp) + if snapshot_id: + try: + restore_snapshot(snapshot_id, workspace, self.snapshot_dir) + except FileNotFoundError as exc: + raise ValueError(str(exc)) from exc if language == "python": - script = Path(tmp) / "main.py" + script = workspace / "main.py" script.write_text(code, encoding="utf-8") argv = ["python3", str(script)] elif language in {"javascript", "node"}: - script = Path(tmp) / "main.js" + script = workspace / "main.js" script.write_text(code, encoding="utf-8") node = shutil.which("node") or "node" argv = [node, str(script)] @@ -68,12 +86,14 @@ class SubprocessSandbox: ) except FileNotFoundError as exc: return RunResult("", str(exc), 127, int((time.monotonic() - start) * 1000)) + new_snapshot = save_snapshot(workspace, self.snapshot_dir) if persist_snapshot else None duration = int((time.monotonic() - start) * 1000) return RunResult( stdout=proc.stdout[: self.max_output_bytes], stderr=proc.stderr[: self.max_output_bytes], exit_code=proc.returncode, duration_ms=duration, + snapshot_id=new_snapshot, ) def run_python(self, code: str) -> RunResult: @@ -83,7 +103,6 @@ class SubprocessSandbox: env = os.environ.copy() if not self.deny_egress: return env - # Strip credentials; full network namespace isolation is the gVisor milestone. for key in list(env): upper = key.upper() if any(token in upper for token in ("TOKEN", "SECRET", "PASSWORD", "API_KEY")): diff --git a/src/agentbox/sandbox/snapshots.py b/src/agentbox/sandbox/snapshots.py new file mode 100644 index 0000000..b58427a --- /dev/null +++ b/src/agentbox/sandbox/snapshots.py @@ -0,0 +1,30 @@ +"""Workspace snapshot save/restore for stateful agent runs.""" + +from __future__ import annotations + +import tarfile +import uuid +from pathlib import Path + + +def save_snapshot(workspace: Path, snapshot_dir: Path) -> str: + snapshot_dir.mkdir(parents=True, exist_ok=True) + snapshot_id = uuid.uuid4().hex + archive = snapshot_dir / f"{snapshot_id}.tar.gz" + with tarfile.open(archive, "w:gz") as tar: + for path in workspace.rglob("*"): + if path.name in {"main.py", "main.js"}: + continue + tar.add(path, arcname=path.relative_to(workspace)) + return snapshot_id + + +def restore_snapshot(snapshot_id: str, workspace: Path, snapshot_dir: Path) -> None: + archive = snapshot_dir / f"{snapshot_id}.tar.gz" + if not archive.exists(): + raise FileNotFoundError(f"Unknown snapshot: {snapshot_id}") + with tarfile.open(archive, "r:gz") as tar: + try: + tar.extractall(workspace, filter="data") + except TypeError: + tar.extractall(workspace) diff --git a/src/agentbox/sdk/client.py b/src/agentbox/sdk/client.py index 1d11a58..abe4859 100644 --- a/src/agentbox/sdk/client.py +++ b/src/agentbox/sdk/client.py @@ -18,10 +18,16 @@ class AgentboxClient: code: str, language: str = "python", timeout_seconds: int | None = None, + snapshot: bool = False, + snapshot_id: str | None = None, ) -> dict[str, object]: payload: dict[str, object] = {"code": code, "language": language} if timeout_seconds is not None: payload["limits"] = {"timeout_seconds": timeout_seconds} + if snapshot: + payload["snapshot"] = True + if snapshot_id: + payload["snapshot_id"] = snapshot_id resp = self._client.post("/v1/run", json=payload) resp.raise_for_status() return resp.json() diff --git a/tests/test_api.py b/tests/test_api.py index 8d9e89b..b9afe81 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -49,3 +49,30 @@ def test_run_javascript() -> None: assert resp.status_code == 200 assert "hello node" in resp.json()["stdout"] assert resp.json()["exit_code"] == 0 + + +def test_snapshot_restore_keeps_workspace_file() -> None: + first = client.post( + "/v1/run", + json={"code": "open('memo.txt','w').write('kept')", "snapshot": True}, + ) + assert first.status_code == 200 + snapshot_id = first.json()["snapshot_id"] + assert snapshot_id + second = client.post( + "/v1/run", + json={ + "code": "print(open('memo.txt').read())", + "snapshot_id": snapshot_id, + }, + ) + assert second.status_code == 200 + assert "kept" in second.json()["stdout"] + + +def test_unknown_snapshot_returns_400() -> None: + resp = client.post( + "/v1/run", + json={"code": "print(1)", "snapshot_id": "does-not-exist"}, + ) + assert resp.status_code == 400