import asyncio
from boxlite import SimpleBox, BoxliteError
async def run_in_sandbox(command: str, *args: str) -> dict:
"""Run one command in an isolated sandbox and return a serializable result."""
try:
# auto_remove=True tears the box down on exit; image is required
async with SimpleBox(image="alpine:latest", auto_remove=True) as box:
result = await box.exec(command, *args, timeout=30.0)
# A non-zero exit code does NOT raise — return it as data
return {
"exit_code": result.exit_code,
"stdout": result.stdout,
"stderr": result.stderr,
}
except BoxliteError as exc:
# Wrapper-layer errors (e.g. ExecError) subclass BoxliteError
return {"error": str(exc)}
except RuntimeError as exc:
# Image pull failures and missing virtualization surface as RuntimeError
return {"error": f"runtime failure: {exc}"}
async def main() -> None:
print(await run_in_sandbox("echo", "hello from the box"))
if __name__ == "__main__":
asyncio.run(main())