feat(v0.3): add workspace snapshot and restore

Context:
- Agent workflows need files written in one run to exist in the next without a gVisor backend.
- Tar the sandbox workspace (minus the entry script) and restore it when snapshot_id is sent.

Test Plan:
- docker compose run --rm test
- tests/test_api.py::test_snapshot_restore_keeps_workspace_file
- tests/test_api.py::test_unknown_snapshot_returns_400

Additional Notes:
- Snapshots live under AGENTBOX_SNAPSHOT_DIR (default /tmp/agentbox-snapshots). Isolation is still subprocess.
This commit is contained in:
Yash Shah
2026-08-19 01:07:54 +05:30
parent 3ef07d2fe9
commit 67495fc374
11 changed files with 109 additions and 10 deletions
+5
View File
@@ -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
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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.
+1 -1
View File
@@ -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"
+1 -1
View File
@@ -1,3 +1,3 @@
"""Self-hosted code execution sandbox for AI agents."""
__version__ = "0.2.0"
__version__ = "0.3.0"
+12 -1
View File
@@ -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,
)
+1
View File
@@ -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"
+23 -4
View File
@@ -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")):
+30
View File
@@ -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)
+6
View File
@@ -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()
+27
View File
@@ -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