Quickly sandbox your AI agent.
Python
refactor(cli): drop dead subcommands and add `quicksand list`
Tyler Payne72384c0cbb9e
diff --git a/docs/under-the-hood/index.md b/docs/under-the-hood/index.mdindex b2b2462..35a0663 100644--- a/docs/under-the-hood/index.md+++ b/docs/under-the-hood/index.md@@ -506,7 +506,7 @@ Image packages register via `quicksand.images` entry points:ubuntu = "quicksand_ubuntu:ImageProvider"```-The `quicksand images list` CLI and image resolution logic use these entry points to discover available images dynamically. `ImageProvider` is a `typing.Protocol` that returns a `ResolvedImage` (with fields: `name`, `chain`, `kernel`, `initrd`, `guest_arch`). The `chain` is the full disk chain from base image to topmost overlay, where `chain[0]` is the root base qcow2 and `chain[1:]` are overlay layers in bottom-to-top order.+Image resolution uses these entry points to discover available images dynamically. `ImageProvider` is a `typing.Protocol` that returns a `ResolvedImage` (with fields: `name`, `chain`, `kernel`, `initrd`, `guest_arch`). The `chain` is the full disk chain from base image to topmost overlay, where `chain[0]` is the root base qcow2 and `chain[1:]` are overlay layers in bottom-to-top order.### Image Bundle Format (.quicksand)diff --git a/docs/user-guide/01-installation.md b/docs/user-guide/01-installation.mdindex 75197ce..1cd5d96 100644--- a/docs/user-guide/01-installation.md+++ b/docs/user-guide/01-installation.md@@ -66,10 +66,6 @@ Alpine is smaller and boots faster. Ubuntu has a larger package ecosystem. Deskt## Verify the installation-```bash-quicksand images list # Shows installed images-```-```pythonimport asynciofrom quicksand import Sandboxdiff --git a/packages/quicksand/quicksand/cli/__init__.py b/packages/quicksand/quicksand/cli/__init__.pyindex ea7a869..5587f89 100644--- a/packages/quicksand/quicksand/cli/__init__.py+++ b/packages/quicksand/quicksand/cli/__init__.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport argparseimport sys-from . import clean, dev, install, qemu, release_save, run, uninstall+from . import clean, dev, install, list_extras, qemu, run, uninstalldef main() -> int:@@ -20,8 +20,8 @@ def main() -> int:run.register(subparsers)install.register(subparsers)uninstall.register(subparsers)+ list_extras.register(subparsers)clean.register(subparsers)- release_save.register(subparsers)qemu.register(subparsers)dev.register(subparsers)@@ -37,8 +37,8 @@ def main() -> int:return install.cmd(args)elif args.command == "uninstall":return uninstall.cmd(args)- elif args.command == "release":- return release_save.cmd(args)+ elif args.command == "list":+ return list_extras.cmd(args)elif args.command == "qemu":return qemu.cmd(args)elif args.command == "clean":diff --git a/packages/quicksand/quicksand/cli/dev.py b/packages/quicksand/quicksand/cli/dev.pyindex 7a16a51..d3ab621 100644--- a/packages/quicksand/quicksand/cli/dev.py+++ b/packages/quicksand/quicksand/cli/dev.py@@ -1,8 +1,4 @@-"""Development tools for building images and packages.--Routes scaffold commands to their respective packages and delegates-everything else to quicksand-image-tools.-"""+"""Development tools for building images and packages."""from __future__ import annotations@@ -15,7 +11,7 @@ def register(subparsers: argparse._SubParsersAction) -> None:"""Register the dev subcommand."""parser = subparsers.add_parser("dev",- help="Development tools for building images and packages (requires quicksand[dev])",+ help="Development tools for building images and packages",)dev_sub = parser.add_subparsers(dest="dev_command")@@ -32,45 +28,15 @@ def register(subparsers: argparse._SubParsersAction) -> None:base_parser.add_argument("name", help="Package name (e.g. quicksand-mylinux)")base_parser.add_argument("--output-dir", type=Path, default=None, help="Output directory")- # Catch-all for image-tools commands (init, build-base, build-image, etc.)- dev_sub.add_parser(- "image-tools",- help="Run quicksand-image-tools commands",- add_help=False,- prefix_chars="\x00", # disable prefix parsing so all args pass through- ).add_argument("image_tools_args", nargs=argparse.REMAINDER)---def _check_dev_installed() -> bool:- """Check if quicksand[dev] is installed, print help if not."""- try:- import quicksand_image_tools # noqa: F401-- return True- except ImportError:- print(- "Error: quicksand[dev] is not installed.\n\n"- "Install with:\n"- " pip install 'quicksand[dev]'\n"- " # or: uv pip install 'quicksand[dev]'",- file=sys.stderr,- )- return False+ parser.set_defaults(_dev_parser=parser)def cmd(args: argparse.Namespace) -> int:"""Route dev subcommands."""if args.dev_command == "scaffold":return _cmd_scaffold(args)- if args.dev_command == "image-tools":- return _cmd_image_tools(args)- # No subcommand — show help- if not _check_dev_installed():- return 1- from quicksand_image_tools.cli import main as dev_main-- sys.argv = ["quicksand dev", "--help"]- return dev_main()+ args._dev_parser.print_help()+ return 0def _cmd_scaffold(args: argparse.Namespace) -> int:@@ -112,13 +78,3 @@ def _cmd_scaffold(args: argparse.Namespace) -> int:# No scaffold type — show helpprint("Usage: quicksand dev scaffold {overlay,base} ...", file=sys.stderr)return 1---def _cmd_image_tools(args: argparse.Namespace) -> int:- """Delegate to quicksand-image-tools."""- if not _check_dev_installed():- return 1- from quicksand_image_tools.cli import main as dev_main-- sys.argv = ["quicksand-image-tools", *args.image_tools_args]- return dev_main()diff --git a/packages/quicksand/quicksand/cli/images.py b/packages/quicksand/quicksand/cli/images.pydeleted file mode 100644index 4b5dffd..0000000--- a/packages/quicksand/quicksand/cli/images.py+++ /dev/null@@ -1,192 +0,0 @@-"""Image management commands."""--from __future__ import annotations--import argparse-import sys-from importlib.metadata import entry_points-from pathlib import Path---def register(subparsers: argparse._SubParsersAction) -> None:- """Register the images subcommand."""- parser = subparsers.add_parser(- "images",- help="Image management commands",- )- images_sub = parser.add_subparsers(dest="images_command", required=True)- images_sub.add_parser("list", help="List installed base images")-- install_parser = images_sub.add_parser(- "install",- help="Install a base image",- )- install_parser.add_argument(- "name",- help="Image name to install (e.g. ubuntu-desktop)",- )- install_parser.add_argument(- "--arch",- choices=["arm64", "amd64"],- default=None,- help="Target architecture (auto-detected from host if not specified)",- )- install_parser.add_argument(- "--output",- metavar="PATH",- type=Path,- default=None,- help="Override the output path for the installed image",- )- install_parser.add_argument(- "--force",- action="store_true",- help="Re-install even if the image already exists",- )---def cmd(args: argparse.Namespace) -> int:- """Run an image management command."""- if args.images_command == "list":- return cmd_list()- if args.images_command == "install":- return cmd_install(args)- return 1---def cmd_list() -> int:- """List installed base images."""- images: list[dict] = []-- # Discover images via quicksand.images entry points- eps = entry_points(group="quicksand.images")- for ep in eps:- try:- provider = ep.load()- except Exception:- continue-- # Resolve path using the package's get_image_path() if available- try:- pkg = ep.value.split(":")[0]- import importlib-- mod = importlib.import_module(pkg)- image_path = Path(mod.get_image_path())- version = getattr(mod, "DISTRO_VERSION", getattr(mod, "__version__", ""))- if image_path.exists():- images.append(- {- "name": provider.name,- "version": version,- "path": image_path,- "size": _format_size(image_path.stat().st_size),- }- )- except (FileNotFoundError, AttributeError, ImportError):- pass-- if not images:- print("No images installed.", file=sys.stderr)- print(- "Install with: pip install 'quick-sandbox[alpine-desktop]'"- " or 'quick-sandbox[ubuntu-desktop]'",- file=sys.stderr,- )- return 1-- for img in images:- print(f"{img['name']:20} {img['version']:6} {img['path']} ({img['size']})")-- return 0---def cmd_install(args: argparse.Namespace) -> int:- """Install a base image by name."""- name: str = args.name- arch: str | None = args.arch- output: Path | None = args.output- force: bool = args.force-- # Find the package that provides this image name via entry points- eps = entry_points(group="quicksand.images")- for ep in eps:- try:- provider = ep.load()- except Exception:- continue-- if provider.name != name:- continue-- # Found — now call install_image() from the package- pkg_name = ep.value.split(":")[0]- try:- import importlib-- mod = importlib.import_module(pkg_name)- except ImportError:- print(- f"Error: package {pkg_name!r} is installed but could not be imported.",- file=sys.stderr,- )- return 1-- if not hasattr(mod, "install_image"):- print(- f"Error: {name!r} does not support installation via `quicksand images install`.\n"- "Use `quicksand install {name}` to install the pre-built wheel instead.",- file=sys.stderr,- )- return 1-- # Check if already installed- if not force:- try:- existing = mod.get_image_path(arch)- print(f"Image already installed: {existing}")- print("Use --force to reinstall.")- return 0- except FileNotFoundError:- pass-- print(f"Installing {name} image...")- if arch:- print(f" Architecture: {arch}")-- def progress(message: str, current: int, total: int) -> None:- if total > 0:- pct = int(current / total * 100)- print(f" [{pct:3d}%] {message}")- else:- print(f" {message}")-- try:- result_path = mod.install_image(- output_path=output,- arch=arch,- progress_callback=progress,- )- print(f"\nInstalled: {result_path}")- return 0- except Exception as e:- print(f"\nError: {e}", file=sys.stderr)- return 1-- print(- f"Error: no image named {name!r} found.\n"- "Available images (from installed quicksand.images entry points):\n"- + "\n".join(f" {ep.name}" for ep in entry_points(group="quicksand.images")),- file=sys.stderr,- )- return 1---def _format_size(size_bytes: int) -> str:- """Format size in human-readable format."""- size = float(size_bytes)- for unit in ["B", "KB", "MB", "GB"]:- if size < 1024:- return f"{size:.0f} {unit}"- size /= 1024- return f"{size:.0f} TB"diff --git a/packages/quicksand/quicksand/cli/list_extras.py b/packages/quicksand/quicksand/cli/list_extras.pynew file mode 100644index 0000000..c92729f--- /dev/null+++ b/packages/quicksand/quicksand/cli/list_extras.py@@ -0,0 +1,67 @@+"""List installed quicksand extras."""++from __future__ import annotations++import argparse+from importlib.metadata import PackageNotFoundError, version++from .install import ALIASES+++def register(subparsers: argparse._SubParsersAction) -> None:+ """Register the list subcommand."""+ parser = subparsers.add_parser(+ "list",+ help="List installed quicksand extras",+ )+ parser.add_argument(+ "--all",+ action="store_true",+ help="Also show extras that are not installed",+ )+++def cmd(args: argparse.Namespace) -> int:+ """Print installed quicksand extras."""+ try:+ qs_ver = version("quick-sandbox")+ except PackageNotFoundError:+ qs_ver = "(not installed)"+ print(f"quicksand {qs_ver}")+ print()++ width = max(len(alias) for alias in ALIASES)+ any_installed = False++ for alias, pkgs in ALIASES.items():+ pkg_versions = [(pkg, _pkg_version(pkg)) for pkg in pkgs]+ installed = [(p, v) for p, v in pkg_versions if v is not None]++ if not installed:+ if args.all:+ print(f" {alias:<{width}} (not installed)")+ continue++ any_installed = True+ if len(pkg_versions) == 1:+ print(f" {alias:<{width}} {pkg_versions[0][0]} {pkg_versions[0][1]}")+ else:+ print(f" {alias:<{width}} {pkg_versions[0][0]} {_fmt_ver(pkg_versions[0][1])}")+ for pkg, ver in pkg_versions[1:]:+ print(f" {' ' * width} {pkg} {_fmt_ver(ver)}")++ if not any_installed and not args.all:+ print(" (no extras installed — use `quicksand install` to add some)")++ return 0+++def _pkg_version(pkg: str) -> str | None:+ try:+ return version(pkg)+ except PackageNotFoundError:+ return None+++def _fmt_ver(ver: str | None) -> str:+ return ver if ver is not None else "(not installed)"diff --git a/packages/quicksand/quicksand/cli/release_save.py b/packages/quicksand/quicksand/cli/release_save.pydeleted file mode 100644index bac0e54..0000000--- a/packages/quicksand/quicksand/cli/release_save.py+++ /dev/null@@ -1,275 +0,0 @@-"""Release a sandbox save to GitHub."""--from __future__ import annotations--import argparse-import shutil-import subprocess-import sys-import tarfile-import tempfile-import time-import urllib.request-from pathlib import Path-from urllib.error import HTTPError--REPO = "microsoft/quicksand"-GLOBAL_SAVES_DIR = Path.home() / ".quicksand" / "sandboxes"---def register(subparsers: argparse._SubParsersAction) -> None:- """Register the release subcommand."""- parser = subparsers.add_parser(- "release",- help="Publish a sandbox save to GitHub releases",- )- parser.add_argument(- "name",- help="Save name (from .quicksand/sandboxes/) or path to save file",- )- parser.add_argument(- "--tag",- help="Custom release tag (default: <name>)",- )- parser.add_argument(- "--title",- help="Release title (default: 'Sandbox: <name>')",- )- parser.add_argument(- "--notes",- default="",- help="Release notes",- )- parser.add_argument(- "--repo",- default=REPO,- help=f"GitHub repo (default: {REPO})",- )---_SAVE_EXTS = (".tar.gz", ".tar")---def _resolve_save(name: str) -> Path | None:- """Resolve a save name to an existing save path.-- Precedence:- 1. Literal path (if contains / or has a save extension)- 2. Directory, .tar.gz, .tar in project-local sandboxes- 3. Directory, .tar.gz, .tar in user-global sandboxes- """- if "/" in name or "\\" in name or any(name.endswith(ext) for ext in _SAVE_EXTS):- p = Path(name)- return p if p.exists() else None-- suffixes = ["", *_SAVE_EXTS]- for base_dir in [Path.cwd() / ".quicksand" / "sandboxes", GLOBAL_SAVES_DIR]:- for suffix in suffixes:- candidate = base_dir / f"{name}{suffix}"- if candidate.exists():- return candidate-- return None---def _get_gh_token() -> str:- """Get GitHub token from gh CLI."""- result = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, check=True)- return result.stdout.strip()---def _format_size(size_bytes: int) -> str:- """Format size in bytes to human readable string."""- size = float(size_bytes)- for unit in ["B", "KB", "MB", "GB"]:- if size < 1024:- return f"{size:.1f}{unit}"- size /= 1024- return f"{size:.1f}TB"---def _get_release_id(tag: str, repo: str) -> int | None:- """Get release ID by tag, or None if not found."""- result = subprocess.run(- ["gh", "api", f"repos/{repo}/releases/tags/{tag}", "--jq", ".id"],- capture_output=True,- text=True,- )- if result.returncode != 0:- return None- return int(result.stdout.strip())---def _upload_with_progress(tar_path: Path, release_id: int, repo: str, token: str) -> bool:- """Upload a file to a GitHub release with a progress bar."""- file_size = tar_path.stat().st_size- file_name = tar_path.name- upload_url = (- f"https://uploads.github.com/repos/{repo}/releases/{release_id}/assets?name={file_name}"- )-- # Read the file and upload with progress- start_time = time.time()- uploaded = 0-- class ProgressReader:- """File-like wrapper that prints progress on read()."""-- def __init__(self, fp, total: int):- self._fp = fp- self._total = total-- def read(self, n: int = -1) -> bytes:- nonlocal uploaded- data = self._fp.read(n)- if data:- uploaded += len(data)- elapsed = time.time() - start_time- speed = uploaded / elapsed if elapsed > 0 else 0- percent = (uploaded / self._total * 100) if self._total > 0 else 0- bar_width = 30- filled = int(bar_width * uploaded / self._total) if self._total > 0 else 0- bar = "#" * filled + "-" * (bar_width - filled)- sys.stdout.write(- f"\r {bar} {percent:5.1f}% "- f"{_format_size(uploaded)}/{_format_size(self._total)} "- f"({_format_size(int(speed))}/s)"- )- sys.stdout.flush()- return data-- def __len__(self) -> int:- return self._total-- with open(tar_path, "rb") as f:- reader = ProgressReader(f, file_size)- req = urllib.request.Request(upload_url, data=reader, method="POST")- req.add_header("Authorization", f"Bearer {token}")- req.add_header("Content-Type", "application/octet-stream")- req.add_header("Content-Length", str(file_size))-- try:- urllib.request.urlopen(req)- sys.stdout.write("\n")- return True- except HTTPError as e:- sys.stdout.write("\n")- print(f"Upload failed: {e.code} {e.reason}", file=sys.stderr)- body = e.read().decode(errors="replace")- if body:- print(f" {body[:200]}", file=sys.stderr)- return False---def cmd(args: argparse.Namespace) -> int:- """Publish a sandbox save as a GitHub release."""- name = args.name- save_path = _resolve_save(name)-- if "/" in name or "\\" in name or any(name.endswith(ext) for ext in _SAVE_EXTS):- release_name = Path(name).stem- if release_name.endswith(".tar"):- release_name = release_name[:-4]- else:- release_name = name-- if save_path is None:- print(f"Save not found: {name}", file=sys.stderr)- return 1-- # Check gh CLI- if not shutil.which("gh"):- print("Error: gh CLI not found. Install from https://cli.github.com/", file=sys.stderr)- return 1-- result = subprocess.run(["gh", "auth", "status"], capture_output=True, text=True)- if result.returncode != 0:- print("Error: gh CLI not authenticated. Run: gh auth login", file=sys.stderr)- return 1-- # If save is a directory, pack it into a temp .tar.gz for upload- tmp_tar: Path | None = None- if save_path.is_dir():- print("Packing save directory...")- tmp_dir = Path(tempfile.mkdtemp(prefix="quicksand-release-"))- tmp_tar = tmp_dir / f"{release_name}.tar.gz"- with tarfile.open(tmp_tar, "w:gz") as tar:- for item in save_path.iterdir():- tar.add(item, arcname=item.name)- upload_path = tmp_tar- else:- upload_path = save_path-- tag = args.tag or release_name- title = args.title or f"Sandbox: {release_name}"- repo = args.repo- size_mb = upload_path.stat().st_size / 1024 / 1024-- print(f"Publishing {upload_path.name} ({size_mb:.1f} MB)")- print(f" Repo: {repo}")- print(f" Tag: {tag}")- print()-- token = _get_gh_token()-- # Ensure release exists- release_id = _get_release_id(tag, repo)- if release_id is None:- print(f"Creating release '{tag}'...")- result = subprocess.run(- [- "gh",- "release",- "create",- tag,- "--repo",- repo,- "--title",- title,- "--notes",- args.notes or f"Pre-configured sandbox environment: {release_name}",- ],- capture_output=True,- text=True,- )- if result.returncode != 0:- print(f"Error: Failed to create release: {result.stderr}", file=sys.stderr)- return 1- release_id = _get_release_id(tag, repo)- if release_id is None:- print("Error: Release created but could not fetch ID.", file=sys.stderr)- return 1-- # Delete existing asset with same name (for --clobber behavior)- existing = subprocess.run(- [- "gh",- "api",- f"repos/{repo}/releases/{release_id}/assets",- "--jq",- f'.[] | select(.name == "{upload_path.name}") | .id',- ],- capture_output=True,- text=True,- )- if existing.returncode == 0 and existing.stdout.strip():- asset_id = existing.stdout.strip()- print("Replacing existing asset...")- subprocess.run(- ["gh", "api", "-X", "DELETE", f"repos/{repo}/releases/assets/{asset_id}"],- capture_output=True,- )-- # Upload with progress- print(f"Uploading {upload_path.name}")- success = _upload_with_progress(upload_path, release_id, repo, token)-- # Clean up temp tar- if tmp_tar is not None:- shutil.rmtree(tmp_tar.parent, ignore_errors=True)-- if not success:- return 1-- print(f"\nPublished! Install with: quicksand install {release_name}")- return 0