Skip to content

Quickly sandbox your AI agent.

Python

refactor: auto-install via pip + simple index, share index URLs

Tyler Payne1d49632a58b8
diff --git a/packages/quicksand-core/quicksand_core/_auto_install.py b/packages/quicksand-core/quicksand_core/_auto_install.py
index 0af9de5..88b1537 100644
--- a/packages/quicksand-core/quicksand_core/_auto_install.py
+++ b/packages/quicksand-core/quicksand_core/_auto_install.py
@@ -1,54 +1,50 @@
-"""Auto-install images from GitHub releases into site-packages.
+"""Auto-fetch fat-wheel images from the quicksand simple index.
-Contrib packages can call :func:`auto_install_images` to download the fat
-wheel from GitHub Releases and extract image files directly into the
-installed package's ``images/`` directory — no pip reinstall needed.
+When a contrib package is installed from PyPI as a pure-Python stub (the
+fat wheel exceeded PyPI's 100 MB cap), this module re-runs ``pip install``
+against the quicksand simple index — which serves every wheel from every
+per-package GitHub release — to upgrade the install to the platform-specific
+fat wheel carrying the actual images.
Enabled by default; set ``QUICKSAND_AUTO_INSTALL=0`` to opt out.
"""
from __future__ import annotations
-import json
import logging
import os
-import shutil
-import tempfile
-import urllib.request
-import zipfile
+import subprocess
+import sys
from importlib.metadata import version as _get_version
from pathlib import Path
+from ._index import QUICKSAND_INDEX_URL
+
logger = logging.getLogger("quicksand.auto_install")
-REPO = "microsoft/quicksand"
-_FALSY = {"0", "false", "no", "off"}
+_TRUTHY = {"1", "true", "yes", "on"}
-# File extensions and paths that are image artifacts inside a wheel.
-_IMAGE_GLOBS = ("*.qcow2", "*.kernel", "*.initrd", "manifest.json")
+def auto_install_images(package_name: str, images_dir: Path) -> bool:
+ """Re-install *package_name* against the quicksand simple index.
-def auto_install_images(
- package_name: str,
- images_dir: Path,
- arch: str | None = None,
-) -> bool:
- """Download images from the fat wheel on GitHub into *images_dir*.
+ The package is assumed to already be installed (typically as a PyPI
+ pure-Python stub with no images). This re-runs pip against the simple
+ index, which serves the fat wheel from the matching per-package GitHub
+ release; pip drops the images into the package's site-packages dir.
Enabled by default; set ``QUICKSAND_AUTO_INSTALL=0`` to opt out.
- Returns ``True`` if images were successfully extracted.
Args:
package_name: PyPI package name (e.g. ``"quicksand-ubuntu"``).
- images_dir: Destination directory for extracted images
- (typically the package's ``images/`` folder in site-packages).
- arch: Target arch (``"amd64"``/``"x86_64"``/``"arm64"``/``"aarch64"``).
- When ``None``, picks the wheel matching the host arch and OS.
- When set, picks any wheel for the target arch (cross-arch image
- install — image content is OS-agnostic when extracted).
+ images_dir: Expected images directory — used only to verify that
+ the reinstall actually placed images.
+
+ Returns:
+ True if ``manifest.json`` is present in *images_dir* afterwards.
"""
- val = os.environ.get("QUICKSAND_AUTO_INSTALL", "").strip().lower()
- if val in _FALSY:
+ val = os.environ.get("QUICKSAND_AUTO_INSTALL", "1").strip().lower()
+ if val not in _TRUTHY:
return False
try:
@@ -57,159 +53,28 @@ def auto_install_images(
logger.debug("Could not determine version for %s", package_name)
return False
- tag = f"{package_name}/v{ver}"
- logger.info("Auto-installing images for %s (tag: %s) ...", package_name, tag)
-
- assets = _get_release_assets(tag)
- if not assets:
- logger.warning("No GitHub release found for tag %s", tag)
- return False
-
- wheel_url = _pick_compatible_wheel(assets, arch=arch)
- if not wheel_url:
- logger.warning("No compatible wheel found in release %s", tag)
- return False
-
- return _download_and_extract_images(wheel_url, images_dir)
-
+ logger.info("Re-installing %s==%s from quicksand simple index ...", package_name, ver)
-# ---------------------------------------------------------------------------
-# Internal helpers
-# ---------------------------------------------------------------------------
+ pip_args = [
+ sys.executable,
+ "-m",
+ "pip",
+ "install",
+ "--force-reinstall",
+ "--no-deps",
+ "--index-url",
+ QUICKSAND_INDEX_URL,
+ f"{package_name}=={ver}",
+ ]
-
-def _github_request(url: str) -> urllib.request.Request:
- """Build a GitHub API request."""
- req = urllib.request.Request(url)
- req.add_header("Accept", "application/vnd.github+json")
- return req
-
-
-def _get_release_assets(tag: str) -> list[dict]:
- """Fetch the asset list for a GitHub release by tag name."""
- url = f"https://api.github.com/repos/{REPO}/releases/tags/{tag}"
try:
- with urllib.request.urlopen(_github_request(url)) as resp:
- data = json.load(resp)
- return data.get("assets", [])
- except Exception:
- logger.debug("Failed to fetch release %s", tag, exc_info=True)
- return []
-
-
-def _host_arch() -> str:
- """Return the host architecture tag substring (``x86_64`` or ``arm64``)."""
- import platform
-
- machine = platform.machine().lower()
- if machine in ("aarch64", "arm64"):
- return "arm64"
- return "x86_64"
-
-
-def _host_os_tag() -> str:
- """Return a substring that must appear in a compatible wheel filename."""
- import platform
-
- system = platform.system().lower()
- if system == "darwin":
- return "macosx"
- if system == "linux":
- return "linux"
- if system == "windows":
- return "win"
- return system
-
-
-_ARCH_ALIASES: dict[str, tuple[str, ...]] = {
- "x86_64": ("x86_64", "amd64"),
- "amd64": ("x86_64", "amd64"),
- "arm64": ("arm64", "aarch64"),
- "aarch64": ("arm64", "aarch64"),
-}
-
-
-def _pick_compatible_wheel(assets: list[dict], arch: str | None = None) -> str | None:
- """Pick the best wheel URL for the host (or *arch*) from release assets.
-
- Without *arch*: returns the wheel matching both host arch and host OS.
- With *arch*: returns any non-pure wheel whose name contains the target
- arch tag — image content is OS-agnostic once extracted, so a foreign-OS
- wheel works for cross-arch image installs.
- """
- if arch is None:
- target_archs = (_host_arch(),)
- require_os = _host_os_tag()
- else:
- target_archs = _ARCH_ALIASES.get(arch.lower(), (arch.lower(),))
- require_os = None
-
- for asset in assets:
- name = asset.get("name", "")
- if not name.endswith(".whl"):
- continue
- if "py3-none-any" in name:
- continue # skip pure wheels
- if not any(a in name for a in target_archs):
- continue
- if require_os is not None and require_os not in name:
- continue
- return asset.get("browser_download_url") or asset.get("url")
- return None
-
-
-def _download_and_extract_images(wheel_url: str, images_dir: Path) -> bool:
- """Download a wheel and extract image files into *images_dir*."""
- images_dir.mkdir(parents=True, exist_ok=True)
- tmp_path: Path | None = None
-
- try:
- with tempfile.NamedTemporaryFile(suffix=".whl", delete=False) as tmp:
- tmp_path = Path(tmp.name)
-
- logger.info("Downloading %s ...", wheel_url.rsplit("/", 1)[-1])
- req = _github_request(wheel_url)
- req.add_header("Accept", "application/octet-stream")
- with urllib.request.urlopen(req) as resp, open(tmp_path, "wb") as out:
- shutil.copyfileobj(resp, out)
-
- extracted = 0
- with zipfile.ZipFile(tmp_path) as zf:
- for entry in zf.namelist():
- if not _is_image_file(entry):
- continue
- # Flatten: images/foo.qcow2 → images_dir/foo.qcow2
- # Handle nested: images/overlays/001.qcow2 → images_dir/overlays/001.qcow2
- parts = Path(entry).parts
- # Find the "images" segment and keep everything after it
- try:
- idx = parts.index("images")
- except ValueError:
- continue
- rel = Path(*parts[idx + 1 :]) if len(parts) > idx + 1 else Path(parts[-1])
- dest = images_dir / rel
- dest.parent.mkdir(parents=True, exist_ok=True)
- with zf.open(entry) as src, open(dest, "wb") as dst:
- shutil.copyfileobj(src, dst)
- extracted += 1
-
- logger.info("Extracted %d image file(s) to %s", extracted, images_dir)
- return extracted > 0
- except Exception:
- logger.warning("Failed to download/extract images", exc_info=True)
+ result = subprocess.run(pip_args, check=False)
+ except OSError:
+ logger.warning("Failed to invoke pip", exc_info=True)
return False
- finally:
- if tmp_path is not None:
- tmp_path.unlink(missing_ok=True)
-
-def _is_image_file(entry: str) -> bool:
- """Check if a zip entry is an image artifact."""
- if entry.endswith("/"):
+ if result.returncode != 0:
+ logger.warning("pip install failed (exit %s)", result.returncode)
return False
- name = entry.rsplit("/", 1)[-1]
- for glob in _IMAGE_GLOBS:
- pattern = glob.lstrip("*")
- if name.endswith(pattern) or name == glob:
- return True
- return False
+
+ return (images_dir / "manifest.json").exists()
diff --git a/packages/quicksand-core/quicksand_core/_index.py b/packages/quicksand-core/quicksand_core/_index.py
new file mode 100644
index 0000000..c3ca820
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/_index.py
@@ -0,0 +1,15 @@
+"""Package index URLs used by ``quicksand install`` and auto-install.
+
+Single source of truth so the CLI and the fat-wheel fallback agree on
+where wheels live.
+"""
+
+from __future__ import annotations
+
+# PEP 503 simple index generated from the per-package GitHub Releases and
+# served via the quicksand GitHub Pages site.
+QUICKSAND_INDEX_URL = "https://microsoft.github.io/quicksand/simple/"
+
+# Public PyPI — used as a fallback for transitive dependencies that aren't
+# quicksand packages (pydantic, anyio, …).
+PYPI_INDEX_URL = "https://pypi.org/simple/"
diff --git a/packages/quicksand/quicksand/cli/install.py b/packages/quicksand/quicksand/cli/install.py
index c5053d1..fa7996b 100644
--- a/packages/quicksand/quicksand/cli/install.py
+++ b/packages/quicksand/quicksand/cli/install.py
@@ -26,6 +26,7 @@ import subprocess
import sys
from packaging.requirements import Requirement
+from quicksand_core._index import PYPI_INDEX_URL, QUICKSAND_INDEX_URL
# Short aliases → actual project names on the simple index / PyPI.
ALIASES: dict[str, list[str]] = {
@@ -39,12 +40,6 @@ ALIASES: dict[str, list[str]] = {
"dev": ["quicksand-image-tools", "quicksand-overlay-scaffold", "quicksand-base-scaffold"],
}
-# PEP 503 simple index served from the quicksand GitHub Pages site, listing
-# every wheel attached to every per-package GitHub release. Falling back to
-# PyPI keeps transitive dependencies (``pydantic``, ``anyio``, …) resolvable.
-QUICKSAND_INDEX_URL = "https://microsoft.github.io/quicksand/simple/"
-PYPI_INDEX_URL = "https://pypi.org/simple/"
-
# ── Helpers ───────────────────────────────────────────────────────────