Skip to content

Quickly sandbox your AI agent.

Python

feat: pure Python wheels for PyPI and HTTPS-only install

github-actions[bot]2b0d0f57d6fa
diff --git a/packages/contrib/quicksand-agent/quicksand_agent/__init__.py b/packages/contrib/quicksand-agent/quicksand_agent/__init__.py
index 6251fc4..3b9a6b6 100644
--- a/packages/contrib/quicksand-agent/quicksand_agent/__init__.py
+++ b/packages/contrib/quicksand-agent/quicksand_agent/__init__.py
@@ -23,10 +23,13 @@ class _AgentSandboxImageProvider:
from quicksand_core.qemu.image_resolver import ImageResolver
if not (IMAGES_DIR / "manifest.json").exists():
- raise FileNotFoundError(
- f"No bundled save found in {IMAGES_DIR}. "
- "The package may not have been built correctly."
- )
+ from quicksand_core._auto_install import auto_install_images
+
+ if not auto_install_images("quicksand-agent", IMAGES_DIR):
+ raise FileNotFoundError(
+ "No bundled save found. If you installed from PyPI, download images with:\n"
+ " quicksand install quicksand-agent"
+ )
return ImageResolver()._resolve_save(IMAGES_DIR)
diff --git a/packages/contrib/quicksand-alpine-desktop/quicksand_alpine_desktop/__init__.py b/packages/contrib/quicksand-alpine-desktop/quicksand_alpine_desktop/__init__.py
index 24a434f..2e108dd 100644
--- a/packages/contrib/quicksand-alpine-desktop/quicksand_alpine_desktop/__init__.py
+++ b/packages/contrib/quicksand-alpine-desktop/quicksand_alpine_desktop/__init__.py
@@ -48,10 +48,13 @@ class _AlpineDesktopImageProvider:
from quicksand_core.qemu.image_resolver import ImageResolver
if not (_IMAGES_DIR / "manifest.json").exists():
- raise FileNotFoundError(
- f"No bundled save found in {_IMAGES_DIR}. "
- "The package may not have been built correctly."
- )
+ from quicksand_core._auto_install import auto_install_images
+
+ if not auto_install_images("quicksand-alpine-desktop", _IMAGES_DIR):
+ raise FileNotFoundError(
+ "No bundled save found. If you installed from PyPI, download images with:\n"
+ " quicksand install quicksand-alpine-desktop"
+ )
return ImageResolver()._resolve_save(_IMAGES_DIR)
diff --git a/packages/contrib/quicksand-alpine/quicksand_alpine/__init__.py b/packages/contrib/quicksand-alpine/quicksand_alpine/__init__.py
index b49657a..e1fa245 100644
--- a/packages/contrib/quicksand-alpine/quicksand_alpine/__init__.py
+++ b/packages/contrib/quicksand-alpine/quicksand_alpine/__init__.py
@@ -69,6 +69,11 @@ def _get_image_artifacts(arch: str | None = None) -> ResolvedImage:
image_path = _IMAGES_DIR / f"alpine-{DISTRO_VERSION}.qcow2"
if not image_path.exists():
+ from quicksand_core._auto_install import auto_install_images
+
+ if auto_install_images("quicksand-alpine", _IMAGES_DIR):
+ return _get_image_artifacts(arch)
+
available = list(_IMAGES_DIR.glob("*.qcow2")) if _IMAGES_DIR.exists() else []
if available:
available_str = ", ".join(p.name for p in available)
@@ -86,8 +91,8 @@ def _get_image_artifacts(arch: str | None = None) -> ResolvedImage:
"Reinstall with: quicksand install quicksand-alpine"
)
raise FileNotFoundError(
- f"No Alpine images found in {_IMAGES_DIR}. "
- "The package may not have been built correctly."
+ "No Alpine images found. If you installed from PyPI, download images with:\n"
+ " quicksand install alpine"
)
return ResolvedImage(
diff --git a/packages/contrib/quicksand-cua/quicksand_cua/__init__.py b/packages/contrib/quicksand-cua/quicksand_cua/__init__.py
index 2e50161..e9fd1c3 100644
--- a/packages/contrib/quicksand-cua/quicksand_cua/__init__.py
+++ b/packages/contrib/quicksand-cua/quicksand_cua/__init__.py
@@ -23,10 +23,13 @@ class _CuaSandboxImageProvider:
from quicksand_core.qemu.image_resolver import ImageResolver
if not (IMAGES_DIR / "manifest.json").exists():
- raise FileNotFoundError(
- f"No bundled save found in {IMAGES_DIR}. "
- "The package may not have been built correctly."
- )
+ from quicksand_core._auto_install import auto_install_images
+
+ if not auto_install_images("quicksand-cua", IMAGES_DIR):
+ raise FileNotFoundError(
+ "No bundled save found. If you installed from PyPI, download images with:\n"
+ " quicksand install quicksand-cua"
+ )
return ImageResolver()._resolve_save(IMAGES_DIR)
diff --git a/packages/contrib/quicksand-ubuntu-desktop/quicksand_ubuntu_desktop/__init__.py b/packages/contrib/quicksand-ubuntu-desktop/quicksand_ubuntu_desktop/__init__.py
index 37c804f..ecfa4fe 100644
--- a/packages/contrib/quicksand-ubuntu-desktop/quicksand_ubuntu_desktop/__init__.py
+++ b/packages/contrib/quicksand-ubuntu-desktop/quicksand_ubuntu_desktop/__init__.py
@@ -48,10 +48,13 @@ class _UbuntuDesktopImageProvider:
from quicksand_core.qemu.image_resolver import ImageResolver
if not (_IMAGES_DIR / "manifest.json").exists():
- raise FileNotFoundError(
- f"No bundled save found in {_IMAGES_DIR}. "
- "The package may not have been built correctly."
- )
+ from quicksand_core._auto_install import auto_install_images
+
+ if not auto_install_images("quicksand-ubuntu-desktop", _IMAGES_DIR):
+ raise FileNotFoundError(
+ "No bundled save found. If you installed from PyPI, download images with:\n"
+ " quicksand install quicksand-ubuntu-desktop"
+ )
return ImageResolver()._resolve_save(_IMAGES_DIR)
diff --git a/packages/contrib/quicksand-ubuntu/quicksand_ubuntu/__init__.py b/packages/contrib/quicksand-ubuntu/quicksand_ubuntu/__init__.py
index 3cb862e..dc9d7a7 100644
--- a/packages/contrib/quicksand-ubuntu/quicksand_ubuntu/__init__.py
+++ b/packages/contrib/quicksand-ubuntu/quicksand_ubuntu/__init__.py
@@ -69,6 +69,11 @@ def _get_image_artifacts(arch: str | None = None) -> ResolvedImage:
image_path = _IMAGES_DIR / f"ubuntu-{DISTRO_VERSION}.qcow2"
if not image_path.exists():
+ from quicksand_core._auto_install import auto_install_images
+
+ if auto_install_images("quicksand-ubuntu", _IMAGES_DIR):
+ return _get_image_artifacts(arch)
+
available = list(_IMAGES_DIR.glob("*.qcow2")) if _IMAGES_DIR.exists() else []
if available:
available_str = ", ".join(p.name for p in available)
@@ -86,8 +91,8 @@ def _get_image_artifacts(arch: str | None = None) -> ResolvedImage:
"Reinstall with: quicksand install quicksand-ubuntu"
)
raise FileNotFoundError(
- f"No Ubuntu images found in {_IMAGES_DIR}. "
- "The package may not have been built correctly."
+ "No Ubuntu images found. If you installed from PyPI, download images with:\n"
+ " quicksand install ubuntu"
)
return ResolvedImage(
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/build_utils.py b/packages/dev/quicksand-image-tools/quicksand_image_tools/build_utils.py
index d74d595..3d0c7a4 100644
--- a/packages/dev/quicksand-image-tools/quicksand_image_tools/build_utils.py
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/build_utils.py
@@ -6,6 +6,7 @@ previously duplicated across every ``hatch_build.py`` in the monorepo.
from __future__ import annotations
+import os
import sysconfig
_X86_NAMES = {"x86_64", "amd64", "x64"}
@@ -43,6 +44,9 @@ def set_platform_wheel_tag(
"""
if target_name != "wheel" or version == "editable":
return False
+ if os.environ.get("QUICKSAND_PURE_WHEEL", "").strip() == "1":
+ build_data["pure_python"] = True
+ return False
native_arch = get_image_arch() # validates arch, raises on unsupported
build_data["pure_python"] = False
platform_tag = sysconfig.get_platform().replace("-", "_").replace(".", "_")
diff --git a/packages/quicksand-core/quicksand_core/_auto_install.py b/packages/quicksand-core/quicksand_core/_auto_install.py
new file mode 100644
index 0000000..cfe82a1
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/_auto_install.py
@@ -0,0 +1,185 @@
+"""Auto-install images from GitHub releases into site-packages.
+
+When ``QUICKSAND_AUTO_INSTALL`` is set to a truthy value, 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.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import shutil
+import tempfile
+import urllib.request
+import zipfile
+from importlib.metadata import version as _get_version
+from pathlib import Path
+
+logger = logging.getLogger("quicksand.auto_install")
+
+REPO = "microsoft/quicksand"
+_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:
+ """Download images from the fat wheel on GitHub into *images_dir*.
+
+ Only runs when ``QUICKSAND_AUTO_INSTALL`` is set to a truthy value.
+ 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).
+ """
+ val = os.environ.get("QUICKSAND_AUTO_INSTALL", "").strip().lower()
+ if val not in _TRUTHY:
+ return False
+
+ try:
+ ver = _get_version(package_name)
+ except Exception:
+ 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)
+ 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)
+
+
+# ---------------------------------------------------------------------------
+# Internal helpers
+# ---------------------------------------------------------------------------
+
+
+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
+
+
+def _pick_compatible_wheel(assets: list[dict]) -> str | None:
+ """Pick the best wheel URL for this platform from release assets."""
+ arch = _host_arch()
+ os_tag = _host_os_tag()
+
+ 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 arch in name and os_tag in name:
+ 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)
+ 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("/"):
+ 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
diff --git a/packages/quicksand/quicksand/cli/install.py b/packages/quicksand/quicksand/cli/install.py
index a0e6892..d3f9bbc 100644
--- a/packages/quicksand/quicksand/cli/install.py
+++ b/packages/quicksand/quicksand/cli/install.py
@@ -1,5 +1,9 @@
"""Install optional quicksand extras from GitHub releases.
+Downloads wheels from public GitHub releases using the REST API — no ``gh``
+CLI required. Authentication is optional: set ``GH_TOKEN`` or
+``GITHUB_TOKEN`` to avoid rate limits on private repos or heavy usage.
+
Programmatic API::
from quicksand import install
@@ -14,7 +18,6 @@ from __future__ import annotations
import argparse
import json
import platform
-import shutil
import subprocess
import sys
import tempfile
@@ -23,6 +26,7 @@ import urllib.request
from pathlib import Path
REPO = "microsoft/quicksand"
+_GITHUB_API = f"https://api.github.com/repos/{REPO}"
# Short aliases → actual package names on GitHub
ALIASES: dict[str, list[str]] = {
@@ -86,8 +90,8 @@ def install(*extras: str, arch: str | None = None) -> None:
Downloads cross-platform wheels for use with ``quicksand run --arch``.
Raises:
- RuntimeError: If ``gh`` CLI is missing or not authenticated, or
- if no matching wheels are found.
+ RuntimeError: If no matching wheels are found for the requested
+ packages.
Examples::
@@ -101,8 +105,6 @@ def install(*extras: str, arch: str | None = None) -> None:
if not extras:
raise ValueError("At least one extra name is required")
- _require_gh()
-
packages: list[str] = []
versions: dict[str, str | None] = {}
for raw in extras:
@@ -144,15 +146,6 @@ def register(subparsers: argparse._SubParsersAction) -> None:
def cmd(args: argparse.Namespace) -> int:
"""Install packages from GitHub releases."""
- if not shutil.which("gh"):
- print("Error: gh CLI not found. Install from https://cli.github.com/")
- 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")
- return 1
-
packages: list[str] = []
versions: dict[str, str | None] = {}
for raw in args.extras:
@@ -168,13 +161,11 @@ def cmd(args: argparse.Namespace) -> int:
# ── Implementation ────────────────────────────────────────────────────
-def _require_gh() -> None:
- """Check gh CLI is available and authenticated."""
- if not shutil.which("gh"):
- raise RuntimeError("gh CLI not found. Install from https://cli.github.com/")
- result = subprocess.run(["gh", "auth", "status"], capture_output=True, text=True)
- if result.returncode != 0:
- raise RuntimeError("gh CLI not authenticated. Run: gh auth login")
+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 _install_packages(
@@ -229,7 +220,7 @@ def _install_packages(
if not tag:
if pkg_name in packages:
print(f"Error: No compatible release found for {pkg_name}")
- print(f" Check releases: gh release list --repo {REPO}")
+ print(f" Check releases: https://github.com/{REPO}/releases")
return 1
continue # not a quicksand package, pip will resolve from PyPI
@@ -276,23 +267,18 @@ def _install_packages(
def _get_latest_release_tag(pkg_name: str) -> str | None:
"""Find the latest per-package release tag (e.g. quicksand-core/v0.3.4)."""
- result = subprocess.run(
- [
- "gh",
- "api",
- f"repos/{REPO}/git/matching-refs/tags/{pkg_name}/v",
- "--jq",
- '.[].ref | ltrimstr("refs/tags/")',
- ],
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
+ url = f"{_GITHUB_API}/git/matching-refs/tags/{pkg_name}/v"
+ try:
+ with urllib.request.urlopen(_github_request(url)) as resp:
+ refs = json.load(resp)
+ except Exception:
return None
tags = [
- t
- for t in result.stdout.strip().splitlines()
- if t and ".dev" not in t and not t.endswith("-base") and not t.endswith("-dev")
+ ref["ref"].removeprefix("refs/tags/")
+ for ref in refs
+ if not ref["ref"].endswith("-dev")
+ and ".dev" not in ref["ref"]
+ and not ref["ref"].endswith("-base")
]
return tags[-1] if tags else None
@@ -320,26 +306,20 @@ def _version_tuple(ver: str) -> tuple[int, ...]:
def _get_all_releases_with_dates() -> dict[str, str]:
"""Fetch every GitHub release in the repo → ``{tag_name: published_at}``."""
- result = subprocess.run(
- [
- "gh",
- "api",
- f"repos/{REPO}/releases",
- "--paginate",
- "--jq",
- ".[] | [.tag_name, .published_at] | @tsv",
- ],
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
- return {}
releases: dict[str, str] = {}
- for line in result.stdout.strip().splitlines():
- if "\t" not in line:
- continue
- tag, date = line.split("\t", 1)
- releases[tag] = date
+ page = 1
+ while True:
+ url = f"{_GITHUB_API}/releases?per_page=100&page={page}"
+ try:
+ with urllib.request.urlopen(_github_request(url)) as resp:
+ data = json.load(resp)
+ except Exception:
+ break
+ if not data:
+ break
+ for rel in data:
+ releases[rel["tag_name"]] = rel["published_at"]
+ page += 1
return releases
@@ -490,29 +470,26 @@ def _wheel_compatible_with_host(name: str) -> bool:
def _download_release_wheels(tag: str, dest_dir: Path) -> list[Path]:
"""Download host-compatible .whl assets from a GitHub release into dest_dir."""
- result = subprocess.run(
- ["gh", "api", f"repos/{REPO}/releases/tags/{tag}", "--jq", ".assets[] | {name, size, url}"],
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
+ url = f"{_GITHUB_API}/releases/tags/{tag}"
+ try:
+ with urllib.request.urlopen(_github_request(url)) as resp:
+ release = json.load(resp)
+ except Exception:
return []
- token = _get_gh_token()
downloaded: list[Path] = []
- for line in result.stdout.strip().splitlines():
- if not line:
- continue
- asset = json.loads(line)
- if not asset["name"].endswith(".whl"):
+ for asset in release.get("assets", []):
+ name = asset["name"]
+ if not name.endswith(".whl"):
continue
- if not _wheel_compatible_with_host(asset["name"]):
+ if not _wheel_compatible_with_host(name):
continue
- dest = dest_dir / asset["name"]
+ dest = dest_dir / name
if dest.exists():
continue
- print(f"Downloading {asset['name']}")
- _download_with_progress(asset["url"], dest, token, asset["size"])
+ print(f"Downloading {name}")
+ download_url = asset.get("browser_download_url", asset["url"])
+ _download_with_progress(download_url, dest, asset["size"])
downloaded.append(dest)
return downloaded
@@ -605,12 +582,6 @@ def _cleanup_incompatible_wheels(wheel_dir: Path) -> None:
whl.unlink()
-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)
@@ -621,10 +592,9 @@ def _format_size(size_bytes: int) -> str:
return f"{size:.1f}TB"
-def _download_with_progress(url: str, dest: Path, token: str, size: int) -> None:
+def _download_with_progress(url: str, dest: Path, size: int) -> None:
"""Download a file with progress bar."""
- req = urllib.request.Request(url)
- req.add_header("Authorization", f"Bearer {token}")
+ req = _github_request(url)
req.add_header("Accept", "application/octet-stream")
start_time = time.time()
diff --git a/uvr_hooks.py b/uvr_hooks.py
index 17774fb..b3c4f2e 100644
--- a/uvr_hooks.py
+++ b/uvr_hooks.py
@@ -5,7 +5,9 @@ from __future__ import annotations
import re
import shutil
import subprocess
+from collections import defaultdict
from pathlib import Path
+from typing import Any
from uv_release.types import Hooks as ReleaseHook
from uv_release.types import Plan
@@ -56,6 +58,100 @@ def _retag_wheels(dist: Path) -> None:
print(f" {whl.name} -> {new_name}")
+# Runner used to build pure (py3-none-any) wheels for PyPI.
+# Only one runner needs to do this since the output is platform-independent.
+_PURE_WHEEL_RUNNER: list[str] = ["self-hosted", "linux", "x64"]
+
+# PyPI per-file size limit.
+_PYPI_MAX_SIZE = 100 * 1024 * 1024 # 100 MB
+
+
+def _discover_contrib_packages() -> dict[str, str]:
+ """Return ``{dist_name: package_path}`` for contrib packages with custom build hooks."""
+ import tomllib
+
+ contrib: dict[str, str] = {}
+ for toml_path in sorted(Path("packages/contrib").glob("*/pyproject.toml")):
+ with open(toml_path, "rb") as f:
+ data = tomllib.load(f)
+ hooks = (
+ data.get("tool", {})
+ .get("hatch", {})
+ .get("build", {})
+ .get("targets", {})
+ .get("wheel", {})
+ .get("hooks", {})
+ )
+ if "custom" in hooks:
+ dist_name = data["project"]["name"].replace("-", "_")
+ contrib[dist_name] = str(toml_path.parent)
+ return contrib
+
+
+def _build_pure_wheels(dist: Path) -> None:
+ """Build ``py3-none-any`` wheels for contrib packages that have fat wheels in *dist*."""
+ import os
+
+ contrib = _discover_contrib_packages()
+ if not contrib:
+ return
+
+ env = {**os.environ, "QUICKSAND_PURE_WHEEL": "1"}
+ built: set[str] = set()
+ for whl in sorted(dist.glob("*.whl")):
+ name = whl.name.split("-")[0]
+ if name in contrib and name not in built:
+ built.add(name)
+ pkg_path = contrib[name]
+ print(f" Building pure wheel: {pkg_path}")
+ subprocess.run(
+ [
+ "uv",
+ "build",
+ pkg_path,
+ "--wheel",
+ "--out-dir",
+ str(dist),
+ "--find-links",
+ "deps",
+ "--find-links",
+ str(dist),
+ "--no-sources",
+ ],
+ env=env,
+ check=True,
+ )
+
+
+def _filter_wheels_for_pypi(dist: Path) -> None:
+ """Keep either fat or pure wheels per package based on the PyPI size limit.
+
+ For packages that have both platform-tagged (fat) and ``py3-none-any`` (pure)
+ variants: delete the fat wheels if any exceeds 100 MB, otherwise delete the
+ pure wheel so pip installs the platform-specific one.
+ """
+ packages: dict[str, list[Path]] = defaultdict(list)
+ for whl in dist.glob("*.whl"):
+ packages[whl.name.split("-")[0]].append(whl)
+
+ for _dist_name, wheels in packages.items():
+ pure = [w for w in wheels if "py3-none-any" in w.name]
+ fat = [w for w in wheels if "py3-none-any" not in w.name]
+ if not pure or not fat:
+ continue
+
+ oversized = any(w.stat().st_size > _PYPI_MAX_SIZE for w in fat)
+ if oversized:
+ for w in fat:
+ size_mb = w.stat().st_size / 1024 / 1024
+ print(f" Removing oversized wheel: {w.name} ({size_mb:.0f} MB)")
+ w.unlink()
+ else:
+ for w in pure:
+ print(f" Removing pure wheel (fat wheels are under 100 MB): {w.name}")
+ w.unlink()
+
+
# Packages whose changes require integration tests.
_TEST_PACKAGES = {
"quicksand",
@@ -215,6 +311,17 @@ class Hooks(ReleaseHook):
def pre_build(self) -> None:
"""No-op — gh install and image extraction handled by extract_dep_images."""
+ def pre_command(self, job_name: str, command: Any) -> None:
+ """Filter oversized wheels before the first PyPI publish command."""
+ if (
+ job_name == "publish"
+ and getattr(command, "type", None) == "publish_to_index"
+ and not getattr(self, "_pypi_filtered", False)
+ ):
+ self._pypi_filtered = True
+ print("Filtering oversized wheels for PyPI...")
+ _filter_wheels_for_pypi(Path("dist"))
+
def retag(self) -> None:
"""Retag platform-specific wheels for cross-OS distribution."""
import json
@@ -229,6 +336,10 @@ class Hooks(ReleaseHook):
print(f"Retagging wheels for cross-platform (runner: {runner})")
_retag_wheels(Path("dist"))
+ if runner == _PURE_WHEEL_RUNNER:
+ print("Building pure wheels for contrib packages...")
+ _build_pure_wheels(Path("dist"))
+
def post_build(self) -> None:
"""Local builds — delegate to retag."""
self.retag()