Skip to content

Quickly sandbox your AI agent.

Python

Initial commit

Tyler Paynef89196a56f90
diff --git a/.claude/skills/new-base-image/SKILL.md b/.claude/skills/new-base-image/SKILL.md
new file mode 100644
index 0000000..dc36281
--- /dev/null
+++ b/.claude/skills/new-base-image/SKILL.md
@@ -0,0 +1,149 @@
+---
+name: new-base-image
+description: >
+ How to create base image packages that bundle a VM image built from a Dockerfile.
+ Use when creating a new distro base like quicksand-ubuntu or quicksand-alpine,
+ scaffolding a base image, or modifying Dockerfiles for base image builds.
+---
+
+# Creating Base Image Packages
+
+Base image packages (like `quicksand-ubuntu`, `quicksand-alpine`) bundle a VM image built from a Dockerfile.
+
+## Quick Start
+
+Use the scaffolding tool:
+
+```bash
+quicksand dev scaffold base quicksand-{distro}
+```
+
+This creates `quicksand-{distro}/` from the base image template and renames everything. Then customize the Dockerfile and build with `uv build`.
+
+## Package Structure
+
+```
+quicksand-{distro}/
+├── pyproject.toml
+├── hatch_build.py # Builds image during `uv build`
+├── README.md
+└── quicksand_{distro}/
+ ├── __init__.py # Python API
+ ├── images/ # Built images (git-ignored)
+ └── docker/
+ ├── Dockerfile
+ ├── quicksand-sudoers
+ ├── hostname
+ └── [init configs]
+```
+
+The guest agent source is copied into `docker/agent/` automatically at build time by `quicksand-image-tools`.
+
+## Dockerfile Requirements
+
+Every base image MUST include:
+
+### 1. Kernel + Initramfs
+```dockerfile
+# Ubuntu
+RUN apt-get install -y linux-image-virtual \
+ && KVER=$(ls /lib/modules/ | head -1) \
+ && apt-get install -y initramfs-tools \
+ && update-initramfs -c -k ${KVER}
+
+# Alpine
+RUN apk add --no-cache linux-virt
+```
+
+### 2. Init System
+```dockerfile
+# Ubuntu (systemd)
+RUN apt-get install -y systemd systemd-sysv
+
+# Alpine (OpenRC)
+RUN apk add --no-cache openrc busybox-openrc
+```
+
+### 3. 9p Modules, User, Networking, Agent
+```dockerfile
+# 9p for host file sharing
+RUN echo "9p" >> /etc/modules && echo "9pnet" >> /etc/modules && echo "9pnet_virtio" >> /etc/modules
+
+# quicksand user with passwordless sudo
+RUN useradd -m -s /bin/bash quicksand
+COPY quicksand-sudoers /etc/sudoers.d/quicksand
+
+# Rust agent via multi-stage build
+FROM rust:bookworm AS agent-builder
+WORKDIR /build
+COPY agent/Cargo.toml agent/Cargo.lock* ./
+COPY agent/src ./src
+RUN cargo build --release && strip /build/target/release/quicksand-guest-agent
+
+# In final stage:
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/
+
+# DHCP networking + CMD
+CMD ["/sbin/init"]
+```
+
+For Alpine, use `rust:alpine` with `musl-dev` for static linking.
+
+## Python API (__init__.py)
+
+Reference: `packages/quicksand-ubuntu/quicksand_ubuntu/__init__.py`
+
+Must export:
+- `image` — `_ImageProvider` instance (registered as `quicksand.images` entry point)
+- `{Distro}Sandbox` — `Sandbox` subclass with default image kwarg
+
+## pyproject.toml
+
+```toml
+[project]
+name = "quicksand-{distro}"
+version = "0.1.0"
+dependencies = ["quicksand-core"]
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_{distro}"]
+artifacts = [
+ "quicksand_{distro}/images/*.qcow2",
+ "quicksand_{distro}/images/*.kernel",
+ "quicksand_{distro}/images/*.initrd",
+ "quicksand_{distro}/docker/*",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[project.entry-points."quicksand.images"]
+{distro} = "quicksand_{distro}:image"
+```
+
+## hatch_build.py
+
+Reference: `packages/quicksand-ubuntu/hatch_build.py`
+
+The build hook detects architecture, sets platform-specific wheel tags, and builds the Docker image if the qcow2 doesn't exist yet.
+
+## Release
+
+The release pipeline automatically discovers base image packages via `provider.type = "base"` on the `quicksand.images` entry point. No manual registration needed.
+
+## Testing
+
+```bash
+uv build --package quicksand-{distro}
+```
+
+```python
+from quicksand_{distro} import {Distro}Sandbox
+
+async with {Distro}Sandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+```
diff --git a/.claude/skills/new-overlay-image/SKILL.md b/.claude/skills/new-overlay-image/SKILL.md
new file mode 100644
index 0000000..44174dc
--- /dev/null
+++ b/.claude/skills/new-overlay-image/SKILL.md
@@ -0,0 +1,148 @@
+---
+name: new-overlay-image
+description: >
+ How to create overlay image packages that layer on top of base images.
+ Use when creating a new overlay package like aif-agent-sandbox, scaffolding
+ an overlay, or modifying hatch_build.py for overlay builds.
+---
+
+# Creating Overlay Image Packages
+
+Overlay packages (like `aif-agent-sandbox`) boot a base VM, install software, and save the result as an overlay. They're faster to create than base images and layer on top of existing base images.
+
+## Quick Start
+
+Use the scaffold tool:
+
+```bash
+quicksand dev scaffold overlay my-overlay-package --base ubuntu
+```
+
+This creates `my-overlay-package/` from the overlay template and renames everything. Then edit the `_setup()` function in `hatch_build.py`.
+
+## Package Structure
+
+```
+{name}/
+├── pyproject.toml
+├── hatch_build.py # Boots VM, runs setup, saves overlay
+├── README.md
+└── {module_name}/
+ ├── __init__.py # ImageProvider entry point
+ ├── sandbox.py # Optional: custom Sandbox subclass
+ └── images/ # Built overlay save (git-ignored)
+ ├── manifest.json
+ └── overlays/*.qcow2
+```
+
+## How It Works
+
+During `uv build`, the `hatch_build.py` hook:
+1. Boots a base VM (default: Ubuntu) with full network access
+2. Runs `_setup(shell)` — your install commands
+3. Saves the VM state as a compressed overlay
+4. Packages the overlay into the wheel
+
+## hatch_build.py
+
+Reference: `packages/contrib/aif-agent-sandbox/hatch_build.py`
+
+The key function to edit:
+
+```python
+async def _setup(shell: Shell) -> None:
+ """Install steps for your overlay."""
+ await shell("apt-get update", timeout=120)
+ await shell("apt-get install -y your-packages", timeout=300)
+ await shell("pip install your-python-deps", timeout=300)
+```
+
+The `shell` callable runs commands inside the VM, streams output, and raises on failure. Use `timeout=` for slow commands.
+
+The build hook also:
+- Sets `pure_python = False` and platform-specific wheel tags
+- Skips rebuild if `images/manifest.json` already exists
+- Uses `UbuntuSandboxConfig` with 4G memory, 4 CPUs, full network, 10G disk
+
+## Python API (__init__.py)
+
+Reference: `packages/contrib/aif-agent-sandbox/aif_agent_sandbox/__init__.py`
+
+Must export:
+- `image` — `_ImageProvider` instance that resolves the bundled save via `ImageResolver()._resolve_save(IMAGES_DIR)`
+
+## pyproject.toml
+
+```toml
+[project]
+name = "{name}"
+version = "0.1.0"
+dependencies = [
+ "quicksand-core>=0.6.0",
+ "quicksand-ubuntu>=0.5.0",
+]
+
+[build-system]
+requires = ["hatchling", "quicksand-core", "quicksand-ubuntu", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["{module_name}"]
+artifacts = [
+ "{module_name}/images/manifest.json",
+ "{module_name}/images/overlays/*.qcow2",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[project.entry-points."quicksand.images"]
+{name} = "{module_name}:image"
+
+[tool.uv.sources]
+quicksand-core = { workspace = true }
+quicksand-ubuntu = { workspace = true }
+```
+
+## Release
+
+Add the package to `_shared.py:OVERLAY_PACKAGES` so the release pipeline:
+- Builds it per-architecture after base images complete
+- Extracts base images from build artifacts before building
+- Sets up KVM (best-effort) for VM acceleration
+
+## Building
+
+```bash
+# First build (boots VM, runs setup, saves overlay — takes a few minutes)
+uv build --package {name}
+
+# Subsequent builds (reuses cached overlay)
+uv build --package {name}
+```
+
+To force rebuild, delete the images directory:
+```bash
+rm -rf packages/contrib/{name}/{module_name}/images/
+uv build --package {name}
+```
+
+## Testing
+
+```bash
+uv run quicksand run {name}
+```
+
+```python
+from quicksand_core import Sandbox
+
+async with Sandbox(image="{name}") as sb:
+ result = await sb.execute("your-command")
+ print(result.stdout)
+```
+
+## Changing the Base Image
+
+By default overlays use Ubuntu. To use Alpine or another base:
+1. Change the import in `hatch_build.py` from `quicksand_ubuntu` to your base
+2. Update `pyproject.toml` dependencies and build-system requires
+3. Update `_setup()` commands for the new distro (e.g., `apk add` instead of `apt-get install`)
diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md
new file mode 100644
index 0000000..751ea4f
--- /dev/null
+++ b/.claude/skills/release/SKILL.md
@@ -0,0 +1,209 @@
+---
+name: release
+description: Release packages to GitHub via uvr. Use when user says "release", "publish packages", "cut a release", or wants to publish new package versions.
+disable-model-invocation: true
+---
+
+# Releasing Packages
+
+Prerequisites: `uvr` (`uv tool install uv-release-monorepo`) and `gh`.
+
+For first-time setup, scaffold the workflow with `uvr workflow init` (see `references/cmd-init.md`). To install the Claude skills into your project, see `references/cmd-skill-init.md`.
+
+If the project has existing CI checks (tests, linting, etc.) that aren't yet wired into the release workflow, see `references/custom-jobs.md` before your first release.
+
+## 1. Branch
+
+You must not be on main. If you are, create a release branch and switch to it.
+
+The working tree must be clean. Run `git status`. If dirty, ask the user whether to stash, commit, or abort.
+
+## 2. Preview Changes
+
+```bash
+uvr release
+```
+
+This prints the plan and prompts `Dispatch release? [y/N]`. Decline (`N`) to preview without dispatching. See `references/cmd-release.md` for all flags.
+
+Present the output to the user. For each changed package, show:
+- The package name and its new version
+- Why it changed (summarize the relevant commits)
+
+Ask the user whether any packages need a minor bump instead of patch. Patch is the default — bump minor for new features, new public API, or breaking changes:
+
+```bash
+uv version --bump minor --directory packages/<package-name>
+```
+
+## 3. Review
+
+For each changed package, verify its public API against its docs:
+
+1. Read the current public API
+2. Check each item on this list:
+ - Do the package's docstrings accurately reflect the exported types and internal functionality? Audit natural language descriptions, argument lists, returns notes, code examples, and references.
+ - Do all docs (READMEs, docs/, etc) accurately reflect the public API and internal functionality of the package? Audit natural language descriptions, code examples, and references.
+3. Fix any discrepancies before continuing
+
+## 4. CHANGELOG.md and Release Notes
+
+Update CHANGELOG.md on the release branch before committing. Format:
+
+For each package, review the commits since the baseline. Use the **DIFF FROM** column from the `uvr release --dry-run` output — this is the actual tag the planner diffs against, which may differ from the PREVIOUS version (e.g. a `-base` tag for dev cycles vs a release tag):
+
+```bash
+git log --oneline <DIFF_FROM_TAG>..HEAD -- packages/<pkg>
+```
+
+Example entry:
+
+```markdown
+## [v0.3.4] - 2026-03-18
+
+### Fixed
+- CIFS directory listing filename truncation
+```
+
+Section headers: **Added**, **Changed**, **Deprecated**, **Removed**, **Fixed**, **Security**.
+
+For each changed package, also write release notes to `.uvr/release-notes/<pkg>/<version>.md`. This directory is gitignored — notes are ephemeral and consumed at release time.
+
+Review the commits since the last release:
+
+```bash
+git log --oneline <pkg>/v<last-version>..HEAD -- packages/<pkg>
+```
+
+Draft user-facing release notes — don't dump commit messages, write prose that helps users understand what's new, changed, or fixed. **Present the draft to the user for approval before writing the file.**
+
+```bash
+mkdir -p .uvr/release-notes/my-lib
+cat > .uvr/release-notes/my-lib/1.2.0.md << 'EOF'
+Dashboard support and stability improvements.
+
+### Added
+- New `Widget` class for building dashboards
+
+### Fixed
+- Parser no longer crashes on empty input
+EOF
+```
+
+If no `--release-notes` flag is provided, the release gets a minimal header only.
+
+## 5. Dispatch
+
+```bash
+git add -A
+git commit -m "Release v<VERSION>"
+git push -u origin "$(git branch --show-current)"
+uvr release
+```
+
+Or with custom release notes:
+
+```bash
+uvr release \
+ --release-notes my-lib @.uvr/release-notes/my-lib/1.2.0.md
+```
+
+When prompted `Dispatch release? [y/N]`, answer `y`.
+
+If `uvr release` says dependency pins were updated, commit those first and re-run:
+
+```bash
+git add -A
+git commit -m "chore: update dep pins"
+git push
+uvr release
+```
+
+## 6. Monitor
+
+```bash
+gh run list --workflow=release.yml --limit=1
+gh run watch <RUN_ID> --exit-status
+```
+
+If the workflow fails, check which job failed:
+
+```bash
+gh run view <RUN_ID> --log-failed
+```
+
+If the failure is early (build broke), fix the issue and re-dispatch from scratch:
+
+```bash
+git add <files>
+git commit -m "Fix: <description>"
+git push
+uvr release
+```
+
+If a later job failed but earlier jobs succeeded, use `--skip-to` and `--reuse-*` flags to resume without re-running what already passed. See `references/troubleshooting.md#resuming-a-partially-failed-release` for the full decision tree.
+
+## 7. Verify
+
+```bash
+gh release list --limit 15 # confirm per-package releases exist
+```
+
+If something goes wrong, see `references/troubleshooting.md`.
+
+## 8. Merge
+
+**ALWAYS** merge stable release branches back to main:
+
+```bash
+git checkout main
+git pull --rebase
+git merge --no-ff <release-branch> -m "Merge <release-branch>"
+git push
+```
+
+After merging, clean up release notes:
+
+```bash
+rm -rf .uvr/release-notes/
+```
+
+**DO NOT** merge pre-release branches back to main. Stay on the branch through the alpha → beta → rc → stable cycle, then merge after the stable release. See `references/pre-releases.md`.
+
+**TAKE CARE** merging post-release branches back to main — they branch from an old tag, so pyproject.toml versions will conflict. You may need to accept main's versions or cherry-pick just the fix commits. See `references/post-releases.md`.
+
+---
+
+## Example
+
+User says: "Let's release the new changes"
+
+1. Verify not on main, create a release branch
+2. Run `uvr release`, decline the prompt — shows `my-lib` is dirty (2 commits: added export, fixed parser)
+3. Present to user: "my-lib will bump 0.2.1 -> 0.2.2 (patch). It has a new public export — should this be a minor bump instead?"
+4. User says "yes, bump minor" — run `uvr bump --package my-lib --minor`
+5. Review docstrings and docs against current API — new `Parser` class exported but not documented. Fix docs.
+6. Draft release notes: "Added `Parser` class for structured input handling. Fixed crash on empty input." Present to user for approval.
+7. Write approved notes to `.uvr/release-notes/my-lib/0.3.0.md`
+8. Commit, push, run `uvr release --release-notes my-lib @.uvr/release-notes/my-lib/0.3.0.md` and confirm
+9. Monitor workflow, verify GitHub releases
+10. Merge release branch back to main, clean up `.uvr/release-notes/`
+
+## References
+
+**Commands:**
+- `references/cmd-init.md` — scaffold the release workflow
+- `references/cmd-validate.md` — check release.yml against schema
+- `references/cmd-release.md` — plan and dispatch a release (all flags)
+- `references/cmd-runners.md` — manage per-package build runners
+- `references/cmd-install.md` — install from GitHub releases
+- `references/cmd-skill-init.md` — copy Claude skills into project
+
+**Guides:**
+- `references/pipeline.md` — the three core jobs (build, publish, bump)
+- `references/release-plan.md` — what the release plan JSON contains
+- `references/custom-jobs.md` — how to add your own jobs to the workflow
+- `references/dev-releases.md` — publishing `.devN` versions for testing
+- `references/pre-releases.md` — alpha, beta, and release candidate versions
+- `references/post-releases.md` — correcting an already-released version
+- `references/troubleshooting.md` — common problems and fixes
diff --git a/.claude/skills/release/references/cmd-init.md b/.claude/skills/release/references/cmd-init.md
new file mode 100644
index 0000000..e2d7f03
--- /dev/null
+++ b/.claude/skills/release/references/cmd-init.md
@@ -0,0 +1,42 @@
+# `uvr workflow init`
+
+Scaffold the GitHub Actions release workflow into your repo.
+
+```bash
+uvr workflow init
+```
+
+Creates `.github/workflows/release.yml` with three core jobs: **build**, **release**, and **bump**. Run this once when setting up a new repo.
+
+The generated workflow contains only the core pipeline. You can add custom jobs (tests, linting, PyPI publish, etc.) by editing the YAML directly — see `pipeline.md`.
+
+## Flags
+
+| Flag | Description |
+|------|-------------|
+| `--force` | Overwrite an existing `release.yml` (loses any custom jobs you added) |
+| `--workflow-dir DIR` | Write to a different directory (default: `.github/workflows`) |
+
+## Upgrading
+
+When a new version of `uvr` ships template changes, run:
+
+```bash
+uvr workflow init --upgrade
+```
+
+This performs a three-way merge between your current workflow, the old template (stored in `.uvr/bases/`), and the new template. Custom jobs you added are preserved. If conflicts arise, your `--editor` is opened.
+
+If merge bases are missing (e.g. you upgraded from an older `uvr` that didn't track them), `uvr` will prompt you. To recover bases without modifying files:
+
+```bash
+uvx --from uv-release-monorepo==<old-version> uvr workflow init --base-only
+uvr workflow init --upgrade
+```
+
+## Notes
+
+- Requires a git repo with a `pyproject.toml` that defines `[tool.uv.workspace]` members.
+- After scaffolding, edit the workflow to add custom jobs for your project's quality gates.
+- Run `uvr workflow validate` after manual edits to catch schema errors (see `cmd-validate.md`).
+- `--force` overwrites the entire file. If you have custom jobs, back up first or re-add them after.
diff --git a/.claude/skills/release/references/cmd-install.md b/.claude/skills/release/references/cmd-install.md
new file mode 100644
index 0000000..3ee9819
--- /dev/null
+++ b/.claude/skills/release/references/cmd-install.md
@@ -0,0 +1,10 @@
+# `uvr install`
+
+Install a package directly from GitHub releases.
+
+```bash
+uvr install ORG/REPO/PKG # latest version
+uvr install ORG/REPO/[email protected] # specific version
+```
+
+Downloads the wheel from the GitHub release tagged `PKG/v1.2.3` and installs it with `uv pip install`. When no version is specified, finds the latest release tag for the package.
diff --git a/.claude/skills/release/references/cmd-release.md b/.claude/skills/release/references/cmd-release.md
new file mode 100644
index 0000000..ba4a763
--- /dev/null
+++ b/.claude/skills/release/references/cmd-release.md
@@ -0,0 +1,88 @@
+# `uvr release`
+
+Plan and execute a release. By default, generates a release plan and dispatches it to GitHub Actions via `gh workflow run`.
+
+The release plan is a self-contained JSON document passed as the `plan` input to the workflow. It contains version numbers, build commands, skip lists, matrix entries, and everything CI needs to execute the release without reading git history. See `release-plan.md` for the plan schema.
+
+## Basic usage
+
+```bash
+uvr release # plan + dispatch to CI
+uvr release --dry-run # preview only
+```
+
+## Mode flags
+
+| Flag | Description |
+|------|-------------|
+| `--where {ci,local}` | `ci` dispatches to GitHub Actions (default), `local` builds in this shell |
+| `--dry-run` | Print what would be released without making changes |
+| `--plan JSON` | Execute a pre-computed release plan locally |
+
+## Release type
+
+Mutually exclusive. Controls how versions are interpreted:
+
+| Flag | Description |
+|------|-------------|
+| *(none)* | Final release (default) — strips `.devN` suffix |
+| `--dev` | Dev release — publishes the current `.devN` version as-is (see `dev-releases.md`) |
+| `--pre {a,b,rc}` | Pre-release — alpha, beta, or release candidate (see `pre-releases.md`) |
+| `--post` | Post-release (see `post-releases.md`) |
+
+## Build options
+
+| Flag | Description |
+|------|-------------|
+| `--rebuild-all` | Rebuild all packages, not just changed ones |
+| `--python VER` | Python version for CI builds (default: `3.12`) |
+
+## Dispatch options (CI mode)
+
+| Flag | Description |
+|------|-------------|
+| `-y, --yes` | Skip the confirmation prompt |
+| `--skip JOB` | Skip a CI job (repeatable). Core jobs: `build`, `release`, `bump`. Custom jobs can also be skipped if they check the plan's skip list in their `if` condition. |
+| `--skip-to JOB` | Skip all core jobs before JOB. Choices: `release`, `bump`. `--skip-to release` skips build; `--skip-to bump` skips build + release. |
+| `--reuse-run RUN_ID` | Reuse build artifacts from a prior workflow run. Requires `build` to be skipped. |
+| `--reuse-release` | Assume GitHub releases already exist. Requires both `build` and `release` to be skipped. |
+
+`--reuse-run` and `--reuse-release` are mutually exclusive.
+
+## Local mode options
+
+| Flag | Description |
+|------|-------------|
+| `--no-push` | Skip `git push` after a local release |
+
+## Output options
+
+| Flag | Description |
+|------|-------------|
+| `--json` | Print only the plan JSON to stdout and exit |
+| `--workflow-dir DIR` | Workflow directory (default: `.github/workflows`) |
+
+## Common patterns
+
+```bash
+# Preview the full plan
+uvr release --dry-run
+
+# Release and skip confirmation
+uvr release -y
+
+# Resume after a failed build — reuse artifacts from run 12345678
+uvr release --skip-to release --reuse-run 12345678
+
+# Resume after release succeeded but bump failed
+uvr release --skip-to bump --reuse-release
+
+# Skip a custom job (e.g., tests you already ran locally)
+uvr release --skip checks
+
+# Build locally instead of via CI
+uvr release --where local
+
+# Get the plan as JSON for scripting
+uvr release --json
+```
diff --git a/.claude/skills/release/references/cmd-runners.md b/.claude/skills/release/references/cmd-runners.md
new file mode 100644
index 0000000..18648eb
--- /dev/null
+++ b/.claude/skills/release/references/cmd-runners.md
@@ -0,0 +1,26 @@
+# `uvr workflow runners`
+
+Manage per-package build runners. By default, all packages build on `ubuntu-latest`. Use this to add platform-specific runners for cross-platform wheel builds.
+
+```bash
+uvr workflow runners # show all package runner configs
+uvr workflow runners my-pkg # show runners for a specific package
+```
+
+## Mutation flags
+
+Mutually exclusive, require a package name:
+
+| Flag | Description |
+|------|-------------|
+| `--add RUNNER` | Add a runner to the package (e.g., `--add macos-latest`) |
+| `--remove RUNNER` | Remove a runner from the package |
+| `--clear` | Remove all custom runners (revert to default) |
+
+```bash
+uvr workflow runners my-pkg --add macos-latest
+uvr workflow runners my-pkg --remove windows-latest
+uvr workflow runners my-pkg --clear
+```
+
+Runner configuration is stored in `[tool.uvr.matrix]` in the root `pyproject.toml`. The build job's matrix expands to one job per unique runner, and each runner builds all packages assigned to it.
diff --git a/.claude/skills/release/references/cmd-skill-init.md b/.claude/skills/release/references/cmd-skill-init.md
new file mode 100644
index 0000000..b5354c7
--- /dev/null
+++ b/.claude/skills/release/references/cmd-skill-init.md
@@ -0,0 +1,10 @@
+# `uvr skill init`
+
+Copy bundled Claude Code skills into your project.
+
+```bash
+uvr skill init # write skills to .claude/skills/
+uvr skill init --force # overwrite existing skill files
+```
+
+Copies the release skill and its references into `.claude/skills/` in the current directory. Existing files are skipped unless `--force` is used.
diff --git a/.claude/skills/release/references/cmd-status.md b/.claude/skills/release/references/cmd-status.md
new file mode 100644
index 0000000..00bbb7a
--- /dev/null
+++ b/.claude/skills/release/references/cmd-status.md
@@ -0,0 +1,15 @@
+# `uvr release --dry-run`
+
+Preview what would be released without making changes.
+
+```bash
+uvr release --dry-run
+```
+
+Shows which packages have changed since their last release tag, their current versions, and whether they changed directly or transitively (via dependency updates).
+
+## Flags
+
+| Flag | Description |
+|------|-------------|
+| `--workflow-dir DIR` | Workflow directory (default: `.github/workflows`) |
diff --git a/.claude/skills/release/references/cmd-validate.md b/.claude/skills/release/references/cmd-validate.md
new file mode 100644
index 0000000..395cc96
--- /dev/null
+++ b/.claude/skills/release/references/cmd-validate.md
@@ -0,0 +1,19 @@
+# `uvr workflow validate`
+
+Check an existing `release.yml` against the expected schema.
+
+```bash
+uvr workflow validate
+```
+
+Reports whether the workflow is valid, invalid, or has warnings.
+
+- **Errors**: invalid top-level keys or missing required fields.
+- **Warnings**: modifications to frozen fields on core jobs (`if`, `strategy`, `runs-on`, `steps` on build/release/bump).
+- **Custom jobs** are accepted without validation — the workflow model allows extra jobs.
+
+## Flags
+
+| Flag | Description |
+|------|-------------|
+| `--workflow-dir DIR` | Workflow directory (default: `.github/workflows`) |
diff --git a/.claude/skills/release/references/custom-jobs.md b/.claude/skills/release/references/custom-jobs.md
new file mode 100644
index 0000000..0728dfe
--- /dev/null
+++ b/.claude/skills/release/references/custom-jobs.md
@@ -0,0 +1,44 @@
+# Adding Custom Jobs
+
+The workflow model allows extra jobs (`extra="allow"`), so you can add any job to `release.yml` and wire it into the pipeline via `needs`.
+
+## Running checks before build
+
+Read the project's existing CI workflows (e.g., `ci.yml`, `test.yml`) to understand what checks run today. Then add those as a job in `release.yml`:
+
+```yaml
+checks:
+ runs-on: ubuntu-latest
+ if: ${{ !contains(fromJSON(inputs.plan).skip, 'checks') }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: astral-sh/setup-uv@v6
+ - run: uv sync --all-packages
+ - run: uv run poe check
+ - run: uv run poe test
+
+build:
+ needs: [checks] # build waits for checks to pass
+ # ... (rest of build job unchanged)
+```
+
+## Running actions after bump
+
+For example, publishing to PyPI:
+
+```yaml
+pypi-publish:
+ needs: [bump]
+ runs-on: ubuntu-latest
+ if: ${{ always() && !failure() && !cancelled() && !contains(fromJSON(inputs.plan).skip, 'pypi-publish') }}
+ environment: pypi
+ steps:
+ # ...
+```
+
+## Tips
+
+- **Use the skip mechanism.** Add `if: ${{ !contains(fromJSON(inputs.plan).skip, '<job-name>') }}` so the job can be skipped at release time with `uvr release --skip <job-name>`.
+- **Gate core jobs via `needs`.** If your custom job should block a core job, add it to that core job's `needs` list.
+- **Run `uvr workflow validate`** after editing to check for schema errors.
+- **Use `always() && !failure() && !cancelled()`** in the `if` condition for jobs that follow skippable jobs. Without this, a skipped upstream job causes the downstream job to be skipped too.
diff --git a/.claude/skills/release/references/dev-releases.md b/.claude/skills/release/references/dev-releases.md
new file mode 100644
index 0000000..45b70d2
--- /dev/null
+++ b/.claude/skills/release/references/dev-releases.md
@@ -0,0 +1,58 @@
+# Dev Releases
+
+Dev releases publish the current `.devN` version as-is, without stripping the suffix. They follow [PEP 440](https://peps.python.org/pep-0440/#developmental-releases) versioning. Use them for in-progress testing or CI integration before a stable release.
+
+## Usage
+
+```bash
+uvr release --dev
+```
+
+## How it works
+
+1. uvr reads each changed package's version from pyproject.toml (e.g., `1.2.3.dev0`)
+2. It publishes that exact version — no stripping, no rewriting
+3. After release, the pyproject.toml version is bumped to `1.2.3.dev1` (increments the dev number)
+
+## Requirements
+
+Every changed package **must** have a `.devN` version in its pyproject.toml. If any package has a clean version (e.g., `1.2.3` without `.devN`), uvr will error with instructions to fix it:
+
+```
+--dev release requires a .devN version in pyproject.toml, but these packages
+have clean versions: my-pkg
+Fix with:
+ uv version 1.2.3.dev0 --directory packages/my-pkg
+```
+
+## Version ordering
+
+Dev releases sort before all other release types for the same base version:
+
+```
+1.0.1.dev0 < 1.0.1.dev1 < 1.0.1a0 < 1.0.1 < 1.0.1.post0
+```
+
+## When to use
+
+- **CI integration testing**: publish a dev wheel so downstream jobs or repos can test against it before the stable release
+- **Early feedback**: let collaborators `pip install my-pkg==1.2.3.dev0` to try unreleased work
+- **Iterative publishing**: each `--dev` release increments the dev number, so you can publish multiple times during development
+
+## Merging
+
+Dev release branches are typically branched from main and should be **merged back to main** after the release completes. The finalize step increments the dev number (e.g., `1.2.3.dev0` to `1.2.3.dev1`), and main needs that bump to stay in sync.
+
+```bash
+git checkout main
+git pull --rebase
+git merge --no-ff release/v1.2.3.dev0 -m "Merge dev release branch"
+git push
+```
+
+## Tag format
+
+```
+my-pkg/v1.2.3.dev0
+my-pkg/v1.2.3.dev1
+```
diff --git a/.claude/skills/release/references/pipeline.md b/.claude/skills/release/references/pipeline.md
new file mode 100644
index 0000000..5f19913
--- /dev/null
+++ b/.claude/skills/release/references/pipeline.md
@@ -0,0 +1,19 @@
+# Release Pipeline
+
+`uvr workflow init` scaffolds a `release.yml` with three core jobs:
+
+```
+build → release → bump
+```
+
+- **build** — builds wheels for changed packages (matrix over runners), uploads them as artifacts
+- **release** — tags the release commit, creates one GitHub release per changed package with wheels attached
+- **bump** — bumps to next dev version, pins internal deps, commits, and pushes
+
+Each core job's `if`, `strategy`, `runs-on`, and `steps` are frozen by uvr. `uvr workflow validate` will warn if you modify them. The `needs` list can be extended.
+
+See also:
+- `release-plan.md` — what the release plan JSON contains
+- `custom-jobs.md` — how to add your own jobs to the workflow
+- `cmd-runners.md` — configure per-package build runners (cross-platform wheels)
+- `cmd-install.md` — install packages from the GitHub releases that release creates
diff --git a/.claude/skills/release/references/post-releases.md b/.claude/skills/release/references/post-releases.md
new file mode 100644
index 0000000..5874ca5
--- /dev/null
+++ b/.claude/skills/release/references/post-releases.md
@@ -0,0 +1,106 @@
+# Post-releases
+
+Post-releases publish a corrected version of an already-released package without bumping the version number. They follow [PEP 440](https://peps.python.org/pep-0440/#post-releases) versioning.
+
+## Usage
+
+```bash
+uvr release --post
+# → 1.2.3.post0
+```
+
+## How it works
+
+1. uvr strips the `.devN` suffix from each changed package's version to get the base `X.Y.Z`
+2. It scans existing git tags to find the next available post-release number
+3. The published version becomes `X.Y.Z.post0` (or `.post1`, etc.)
+4. After release, the pyproject.toml version is bumped to `X.Y.Z.post1.dev0` (dev toward the next post-release)
+
+## Version ordering
+
+Post-releases sort after the stable release but before the next version:
+
+```
+1.0.1 < 1.0.1.post0 < 1.0.1.post1 < 1.0.2.dev0 < 1.0.2
+```
+
+## Auto-incrementing
+
+The post-release number auto-increments by scanning existing tags. If `my-pkg/v1.2.3.post0` already exists, the next `--post` release will produce `1.2.3.post1`.
+
+## When to use
+
+- **Hotfix for a released version**: a critical bug needs to be patched on an older release while main has moved on. Check out the release tag, fix, and publish with `--post`.
+- **Packaging fix**: the wheel was built incorrectly but the source code is fine
+- **Metadata correction**: wrong description, classifiers, or dependency constraints
+- **Documentation-only change**: README or other bundled docs needed updating
+
+## Tag conflict resolution
+
+If `uvr release` detects that a release tag already exists (e.g., you already published `1.2.3`), it will suggest `--post` as one of the resolution options:
+
+```
+These tags/releases already exist and would conflict:
+ my-pkg/v1.2.3
+
+To resolve, either:
+ 1. Use --post to publish a post-release:
+ my-pkg: 1.2.3.post0
+ 2. Bump past the conflict:
+ uv version 1.2.4.dev0 --directory packages/my-pkg
+```
+
+## Workflow
+
+Post-releases are made from the original release tag, not from main. **Take care merging post-release branches back to main** — pyproject.toml versions will conflict since the branch is based on an old tag.
+
+```bash
+# 1. Check out the original release tag
+git checkout my-pkg/v1.2.3
+
+# 2. Create a post-release branch
+git checkout -b post-release/my-pkg/v1.2.3
+
+# 3. Make the fix (code, packaging, metadata, etc.)
+# ...
+
+# 4. Commit and push
+git add -A
+git commit -m "fix: correct widget parsing in my-pkg"
+git push -u origin post-release/my-pkg/v1.2.3
+
+# 5. Publish the post-release
+uvr release --post
+```
+
+## Merging
+
+**TAKE CARE** merging post-release branches back to main. The branch is based on an old tag, so pyproject.toml versions will conflict — the branch has `X.Y.Z.post1.dev0` while main has `X.Y.Z+1.dev0`.
+
+Two options for getting the fix onto main:
+
+**Option 1: Cherry-pick** (simpler when the fix is small)
+
+```bash
+git checkout main
+git cherry-pick <fix-commit-hash> # pick the fix, not the finalize commits
+git push
+```
+
+**Option 2: Merge and resolve conflicts** (better when the fix touches many files)
+
+```bash
+git checkout main
+git merge --no-ff post-release/my-pkg/v1.2.3
+# resolve conflicts: accept main's versions in pyproject.toml and uv.lock
+git push
+```
+
+Leave the post-release branch as-is after publishing. It serves as a record of the hotfix.
+
+## Tag format
+
+```
+my-pkg/v1.2.3.post0
+my-pkg/v1.2.3.post1
+```
diff --git a/.claude/skills/release/references/pre-releases.md b/.claude/skills/release/references/pre-releases.md
new file mode 100644
index 0000000..f433b16
--- /dev/null
+++ b/.claude/skills/release/references/pre-releases.md
@@ -0,0 +1,78 @@
+# Pre-releases
+
+Pre-releases let you publish alpha, beta, or release candidate versions for testing before a stable release. They follow [PEP 440](https://peps.python.org/pep-0440/#pre-releases) versioning.
+
+## Usage
+
+```bash
+uvr release --pre a # alpha → 1.2.3a0
+uvr release --pre b # beta → 1.2.3b0
+uvr release --pre rc # release candidate → 1.2.3rc0
+```
+
+## How it works
+
+1. uvr strips the `.devN` suffix from each changed package's version to get the base `X.Y.Z`
+2. It scans existing git tags to find the next available pre-release number for that kind
+3. The published version becomes `X.Y.Za0` (or `b0`, `rc0`, etc.)
+4. After release, the pyproject.toml version is bumped to `X.Y.Za1.dev0` (dev toward the next pre-release of the same kind)
+
+## Version ordering
+
+Pre-releases sort before the stable release:
+
+```
+1.0.1.dev0 < 1.0.1a0 < 1.0.1a1 < 1.0.1b0 < 1.0.1rc0 < 1.0.1
+```
+
+## Auto-incrementing
+
+The pre-release number auto-increments by scanning existing tags. If `my-pkg/v1.0.1a0` already exists, the next `--pre a` release will produce `1.0.1a1`.
+
+## Example workflow
+
+```bash
+# First alpha
+uvr release --pre a
+# → publishes my-pkg 1.2.3a0
+# → bumps pyproject.toml to 1.2.3a1.dev0
+
+# Second alpha (after more changes)
+uvr release --pre a
+# → publishes my-pkg 1.2.3a1
+# → bumps pyproject.toml to 1.2.3a2.dev0
+
+# Release candidate
+uvr release --pre rc
+# → publishes my-pkg 1.2.3rc0
+
+# Final release
+uvr release
+# → publishes my-pkg 1.2.3
+# → bumps pyproject.toml to 1.2.4.dev0
+```
+
+## Merging
+
+**DO NOT merge pre-release branches back to main.** Stay on the branch through the entire cycle (alpha → beta → rc → stable) and merge only after the stable release.
+
+After `--pre a`, finalize bumps the pyproject.toml version to something like `1.2.3a1.dev0`. If you merged that to main, main's version would be an intermediate pre-release dev version — confusing and unnecessary.
+
+Keep iterating on the branch until you're ready for the stable release:
+
+```bash
+uvr release --pre a # 1.2.3a0 — stay on branch
+uvr release --pre rc # 1.2.3rc0 — stay on branch
+uvr release # 1.2.3 — now merge to main
+```
+
+Merge to main only after the stable release.
+
+## Tag format
+
+Pre-release tags follow the same pattern as stable releases:
+
+```
+my-pkg/v1.2.3a0
+my-pkg/v1.2.3rc1
+```
diff --git a/.claude/skills/release/references/release-plan.md b/.claude/skills/release/references/release-plan.md
new file mode 100644
index 0000000..e9ac660
--- /dev/null
+++ b/.claude/skills/release/references/release-plan.md
@@ -0,0 +1,13 @@
+# The Release Plan
+
+The release plan is a self-contained JSON document passed as the `plan` input to the workflow. It contains:
+
+- Version numbers and build commands for each changed package
+- A runner matrix (one entry per unique runner configuration)
+- A release matrix (one entry per changed package)
+- A skip list (job names to skip)
+- Reuse configuration (prior run ID for artifact reuse)
+
+CI reads everything from this plan — it does not inspect git history or compute anything at runtime.
+
+The plan is generated by `uvr release` and can be previewed with `uvr release --json`. See `cmd-release.md` for details.
diff --git a/.claude/skills/release/references/troubleshooting.md b/.claude/skills/release/references/troubleshooting.md
new file mode 100644
index 0000000..ef65559
--- /dev/null
+++ b/.claude/skills/release/references/troubleshooting.md
@@ -0,0 +1,132 @@
+# Troubleshooting
+
+## Pin updates block the release
+
+If `uvr release` says pins were updated, it exits without dispatching. Commit the pin changes and re-run:
+
+```bash
+git add -A
+git commit -m "chore: update dep pins"
+git push
+uvr release
+```
+
+## Partial release failure (some packages published, some failed)
+
+1. Check `gh run view <RUN_ID> --log-failed` to identify which packages failed
+2. Fix the root cause (usually a build error in one package)
+3. Re-run `uvr release` — it will only re-publish packages that haven't been released yet
+
+## Tags pushed but workflow didn't trigger
+
+Verify the workflow trigger in `.github/workflows/release.yml` matches expectations. Manually dispatch if needed:
+
+```bash
+gh workflow run release.yml
+```
+
+## Custom job failed (e.g., PyPI publish)
+
+Check the job logs:
+
+```bash
+gh run list --workflow=release.yml --limit=5
+gh run view <RUN_ID> --log-failed
+```
+
+## Resuming a partially failed release
+
+When a release fails partway through, you don't need to start over. Use `--skip`, `--skip-to`, and `--reuse-*` flags to resume from where it broke. See `cmd-release.md` for the full flag reference.
+
+**First, identify what succeeded.** Check the failed run:
+
+```bash
+gh run view <RUN_ID> --log-failed
+```
+
+The release pipeline has three core jobs in order: **build → release → bump**. Pick the right resume strategy based on where it failed:
+
+### Build failed
+
+Nothing was published — just fix the issue and re-run normally:
+
+```bash
+uvr release
+```
+
+### Build succeeded, release failed
+
+Reuse the build artifacts so you don't rebuild:
+
+```bash
+uvr release --skip-to release --reuse-run <RUN_ID>
+```
+
+`--skip-to release` skips the build job. `--reuse-run` downloads artifacts from the prior run.
+
+### Release succeeded, bump failed
+
+GitHub releases already exist, so tell uvr to skip both build and release:
+
+```bash
+uvr release --skip-to bump --reuse-release
+```
+
+`--reuse-release` means "don't try to create releases that already exist."
+
+### Skipping custom jobs
+
+If your workflow has custom jobs (tests, linting, etc.) and you want to skip one — for example, because you already ran checks locally:
+
+```bash
+uvr release --skip checks
+```
+
+`--skip` is repeatable. To skip multiple jobs:
+
+```bash
+uvr release --skip checks --skip docs
+```
+
+Custom jobs must check the plan's skip list in their `if` condition for this to work. See `custom-jobs.md`.
+
+### Constraints
+
+- `--reuse-run` requires build to be skipped (via `--skip build` or `--skip-to release`/`--skip-to bump`)
+- `--reuse-release` requires both build and release to be skipped (via `--skip-to bump`)
+- `--reuse-run` and `--reuse-release` are mutually exclusive
+
+## Main moved ahead of the release branch
+
+If other work was merged to main between when you branched and when the release completed, you'll see conflicts when merging back.
+
+**What happened:** The bump job bumps versions and pins deps on the release branch. Meanwhile, main may have new commits that touch pyproject.toml, uv.lock, or the same source files.
+
+**How to resolve:**
+
+```bash
+git checkout main
+git pull --rebase
+git merge --no-ff <release-branch>
+# resolve conflicts:
+# - pyproject.toml versions: accept the release branch's versions (they have the post-release .dev bumps)
+# - uv.lock: regenerate with `uv sync` after resolving pyproject.toml
+# - source conflicts: merge normally
+git add -A
+uv sync
+git add uv.lock
+git commit
+git push
+```
+
+After merging, verify the version bumps from the bump job landed cleanly. Check pyproject.toml versions match what the bump job set.
+
+**If the merge is too messy**, an alternative is to skip the merge and cherry-pick only your pre-release commits onto main, then let the next release pick up the changes naturally.
+
+## Rolling back a bad release
+
+GitHub releases can be deleted, but published packages (e.g., on PyPI) generally cannot. If a broken version was published:
+
+1. Delete the GitHub release: `gh release delete <tag> --yes`
+2. Delete the tag: `git push --delete origin <tag>`
+3. Fix the issue, bump the version again, and re-release
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
new file mode 100644
index 0000000..5e74ef2
--- /dev/null
+++ b/.github/workflows/check.yml
@@ -0,0 +1,22 @@
+name: Check
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ workflow_call: {}
+
+jobs:
+ checks:
+ runs-on: [self-hosted, linux, x64]
+ strategy:
+ fail-fast: false
+ matrix:
+ task: [check-code, check-format, check-types, test-unit, test-smb]
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ clean: true
+ - uses: astral-sh/setup-uv@v7
+ - run: uv run poe ${{ matrix.task }}
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
new file mode 100644
index 0000000..c9ee3cd
--- /dev/null
+++ b/.github/workflows/docs.yml
@@ -0,0 +1,48 @@
+name: Deploy Docs
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'docs/**'
+ - 'package.json'
+ - 'package-lock.json'
+ workflow_dispatch: {}
+
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+concurrency:
+ group: pages
+ cancel-in-progress: false
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+
+ - run: npm ci
+
+ - run: npm run docs:build
+
+ - uses: actions/upload-pages-artifact@v3
+ with:
+ path: docs/.vitepress/dist
+
+ deploy:
+ needs: build
+ runs-on: ubuntu-latest
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..dbf6c9e
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,226 @@
+name: Release Wheels
+on:
+ workflow_dispatch:
+ inputs:
+ plan:
+ description: Release plan JSON (generated by uvr release).
+ type: string
+ required: true
+permissions:
+ contents: write
+ actions: read
+
+jobs:
+ # --------------------------------------------------------------------------
+ # Validate
+ # --------------------------------------------------------------------------
+ uvr-validate:
+ runs-on: [self-hosted, linux, x64]
+ steps:
+ - uses: actions/checkout@v6
+ - id: setup-uv
+ uses: astral-sh/setup-uv@v7
+ with:
+ python-version: ${{ fromJSON(inputs.plan).python_version }}
+ - name: Reject releases from main
+ if: github.ref == 'refs/heads/main'
+ run: |
+ echo "::error::Release must be dispatched from a release branch (e.g. release/v0.9.1), not main."
+ exit 1
+ - id: validate-plan
+ name: Validate release plan
+ env:
+ UVR_PLAN: ${{ inputs.plan }}
+ run: uv run uvr jobs validate
+
+ # --------------------------------------------------------------------------
+ # Check (lint, format, types, unit tests)
+ # --------------------------------------------------------------------------
+ check:
+ needs: [uvr-validate]
+ runs-on: [self-hosted, linux, x64]
+ strategy:
+ fail-fast: true
+ matrix:
+ task: [check, test-unit]
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ clean: true
+ - uses: astral-sh/setup-uv@v7
+ - run: uv run poe ${{ matrix.task }}
+
+ # --------------------------------------------------------------------------
+ # Build
+ # --------------------------------------------------------------------------
+ uvr-build:
+ needs: [uvr-validate, check]
+ runs-on: ${{ matrix.runner }}
+ if: ${{ always() && !failure() && !cancelled() && !contains(fromJSON(inputs.plan).skip, 'uvr-build') }}
+ timeout-minutes: 60
+ strategy:
+ fail-fast: true
+ matrix:
+ runner: ${{ fromJSON(inputs.plan).build_matrix }}
+ steps:
+ - id: checkout
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ - id: setup-uv
+ uses: astral-sh/setup-uv@v7
+ with:
+ python-version: ${{ fromJSON(inputs.plan).python_version }}
+
+ - id: build
+ name: Build packages
+ env:
+ GH_TOKEN: ${{ github.token }}
+ UVR_PLAN: ${{ inputs.plan }}
+ UVR_RUNNER: ${{ toJSON(matrix.runner) }}
+ run: uv run uvr jobs build
+ - id: upload
+ uses: actions/upload-artifact@v4
+ with:
+ name: wheels-${{ join(matrix.runner, '-') }}
+ path: dist/*.whl
+ if-no-files-found: error
+
+ # --------------------------------------------------------------------------
+ # Verify GPL licenses in QEMU wheels
+ # --------------------------------------------------------------------------
+ verify-licenses:
+ needs: [uvr-validate, uvr-build]
+ if: always() && !failure() && !cancelled() && !contains(fromJSON(inputs.plan).skip, 'verify-licenses')
+ runs-on: [self-hosted, linux, x64]
+ steps:
+ - uses: actions/checkout@v6
+ - uses: astral-sh/setup-uv@v7
+ - uses: actions/download-artifact@v8
+ with:
+ pattern: wheels-*
+ path: dist/
+ merge-multiple: true
+ - run: uv run --no-project scripts/ci/verify_licenses.py dist/*.whl
+
+ # --------------------------------------------------------------------------
+ # Test (integration tests — boot VMs from built wheels)
+ # --------------------------------------------------------------------------
+ test:
+ needs: [uvr-build, verify-licenses]
+ if: always() && !failure() && !cancelled() && !contains(fromJSON(inputs.plan).skip, 'test')
+ runs-on: [self-hosted, linux, x64]
+ timeout-minutes: 15
+ strategy:
+ fail-fast: true
+ matrix:
+ vm: [ubuntu, alpine]
+ steps:
+ - uses: actions/checkout@v6
+ - uses: astral-sh/setup-uv@v7
+
+ - uses: actions/download-artifact@v8
+ with:
+ pattern: wheels-*
+ path: dist/
+ merge-multiple: true
+
+ - name: KVM setup
+ run: |
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \
+ | sudo tee /etc/udev/rules.d/99-kvm4all.rules
+ sudo udevadm control --reload-rules && sudo udevadm trigger --name-match=kvm || true
+
+ - name: Install packages
+ run: ${{ fromJSON(inputs.plan).test_install[matrix.vm] }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+
+ - name: Run integration tests
+ run: |
+ uv run --no-project pytest \
+ tests/integration/execution \
+ tests/integration/mounts \
+ tests/integration/network \
+ tests/integration/checkpoint \
+ -v --timeout=300
+ env:
+ QUICKSAND_TEST_VM: ${{ matrix.vm }}
+
+ # --------------------------------------------------------------------------
+ # Release — create per-package GitHub releases
+ # --------------------------------------------------------------------------
+ uvr-release:
+ needs: [uvr-build, verify-licenses, test]
+ runs-on: [self-hosted, linux, x64]
+ if: ${{ always() && !failure() && !cancelled() && !contains(fromJSON(inputs.plan).skip, 'uvr-release') }}
+ steps:
+ - id: checkout
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ - id: setup-uv
+ uses: astral-sh/setup-uv@v7
+ with:
+ python-version: ${{ fromJSON(inputs.plan).python_version }}
+ - id: download
+ name: Download wheels
+ env:
+ GH_TOKEN: ${{ github.token }}
+ UVR_PLAN: ${{ inputs.plan }}
+ run: uv run uvr jobs download
+ - id: publish
+ name: Tag and publish releases
+ env:
+ GH_TOKEN: ${{ github.token }}
+ UVR_PLAN: ${{ inputs.plan }}
+ run: uv run uvr jobs release
+
+ # --------------------------------------------------------------------------
+ # Publish — upload wheels to Azure Artifacts
+ # --------------------------------------------------------------------------
+ publish:
+ needs: [uvr-validate, check, uvr-build, verify-licenses, uvr-release]
+ if: ${{ always() && !failure() && !cancelled() && !contains(fromJSON(inputs.plan).skip, 'publish') }}
+ runs-on: [self-hosted, linux, x64]
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ clean: true
+ - uses: astral-sh/setup-uv@v7
+
+ - uses: actions/download-artifact@v8
+ with:
+ pattern: wheels-*
+ path: dist/
+ merge-multiple: true
+ run-id: ${{ fromJSON(inputs.plan).reuse_run_id != '' && fromJSON(inputs.plan).reuse_run_id || github.run_id }}
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Publish to Azure Artifacts
+ run: uv run python scripts/ci/publish_azure.py
+ env:
+ UVR_PLAN: ${{ inputs.plan }}
+
+ # --------------------------------------------------------------------------
+ # Bump — post-release version bump
+ # --------------------------------------------------------------------------
+ uvr-bump:
+ runs-on: [self-hosted, linux, x64]
+ if: ${{ always() && !failure() && !cancelled() && !contains(fromJSON(inputs.plan).skip, 'uvr-bump') }}
+ needs:
+ - uvr-release
+ steps:
+ - id: checkout
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ - id: setup-uv
+ uses: astral-sh/setup-uv@v7
+ with:
+ python-version: ${{ fromJSON(inputs.plan).python_version }}
+ - id: finalize
+ name: Finalize release
+ env:
+ UVR_PLAN: ${{ inputs.plan }}
+ run: uv run uvr jobs bump
diff --git a/.gitignore b/.gitignore
index ce89292..dc16909 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,418 +1,53 @@
-## Ignore Visual Studio temporary files, build results, and
-## files generated by popular Visual Studio add-ons.
-##
-## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
-
-# User-specific files
-*.rsuser
-*.suo
-*.user
-*.userosscache
-*.sln.docstates
-*.env
-
-# User-specific files (MonoDevelop/Xamarin Studio)
-*.userprefs
-
-# Mono auto generated files
-mono_crash.*
-
-# Build results
-[Dd]ebug/
-[Dd]ebugPublic/
-[Rr]elease/
-[Rr]eleases/
-x64/
-x86/
-[Ww][Ii][Nn]32/
-[Aa][Rr][Mm]/
-[Aa][Rr][Mm]64/
-[Aa][Rr][Mm]64[Ee][Cc]/
-bld/
-[Oo]bj/
-[Oo]ut/
-[Ll]og/
-[Ll]ogs/
-
-# Build results on 'Bin' directories
-**/[Bb]in/*
-# Uncomment if you have tasks that rely on *.refresh files to move binaries
-# (https://github.com/github/gitignore/pull/3736)
-#!**/[Bb]in/*.refresh
-
-# Visual Studio 2015/2017 cache/options directory
-.vs/
-# Uncomment if you have tasks that create the project's static files in wwwroot
-#wwwroot/
-
-# Visual Studio 2017 auto generated files
-Generated\ Files/
-
-# MSTest test Results
-[Tt]est[Rr]esult*/
-[Bb]uild[Ll]og.*
-*.trx
-
-# NUnit
-*.VisualState.xml
-TestResult.xml
-nunit-*.xml
-
-# Approval Tests result files
-*.received.*
-
-# Build Results of an ATL Project
-[Dd]ebugPS/
-[Rr]eleasePS/
-dlldata.c
-
-# Benchmark Results
-BenchmarkDotNet.Artifacts/
-
-# .NET Core
-project.lock.json
-project.fragment.lock.json
-artifacts/
-
-# ASP.NET Scaffolding
-ScaffoldingReadMe.txt
-
-# StyleCop
-StyleCopReport.xml
-
-# Files built by Visual Studio
-*_i.c
-*_p.c
-*_h.h
-*.ilk
-*.meta
-*.obj
-*.idb
-*.iobj
-*.pch
-*.pdb
-*.ipdb
-*.pgc
-*.pgd
-*.rsp
-# but not Directory.Build.rsp, as it configures directory-level build defaults
-!Directory.Build.rsp
-*.sbr
-*.tlb
-*.tli
-*.tlh
+# Python
+__pycache__/
+*.py[cod]
+*$py.class
+*.so
+.Python
+*.egg-info/
+*.egg
+dist/
+/build/
+
+# Virtual environments
+.venv/
+venv/
+ENV/
+
+# IDE
+.idea/
+.vscode/
+*.swp
+*.swo
+
+# Testing
+.pytest_cache/
+.coverage
+htmlcov/
+
+# Type checking
+.mypy_cache/
+
+# Linting
+.ruff_cache/
+
+# VM images (built during package build, not committed)
+manifest.json
+*.qcow2
+*.kernel
+*.initrd
+
+# Local scripts
+scripts/rewrite-history.sh
+
+# Temp files
*.tmp
-*.tmp_proj
-*_wpftmp.csproj
*.log
-*.tlog
-*.vspscc
-*.vssscc
-.builds
-*.pidb
-*.svclog
-*.scc
-
-# Chutzpah Test files
-_Chutzpah*
-
-# Visual C++ cache files
-ipch/
-*.aps
-*.ncb
-*.opendb
-*.opensdf
-*.sdf
-*.cachefile
-*.VC.db
-*.VC.VC.opendb
-
-# Visual Studio profiler
-*.psess
-*.vsp
-*.vspx
-*.sap
-
-# Visual Studio Trace Files
-*.e2e
-
-# TFS 2012 Local Workspace
-$tf/
-
-# Guidance Automation Toolkit
-*.gpState
-
-# ReSharper is a .NET coding add-in
-_ReSharper*/
-*.[Rr]e[Ss]harper
-*.DotSettings.user
-
-# TeamCity is a build add-in
-_TeamCity*
-
-# DotCover is a Code Coverage Tool
-*.dotCover
-
-# AxoCover is a Code Coverage Tool
-.axoCover/*
-!.axoCover/settings.json
-
-# Coverlet is a free, cross platform Code Coverage Tool
-coverage*.json
-coverage*.xml
-coverage*.info
-
-# Visual Studio code coverage results
-*.coverage
-*.coveragexml
-
-# NCrunch
-_NCrunch_*
-.NCrunch_*
-.*crunch*.local.xml
-nCrunchTemp_*
-
-# MightyMoose
-*.mm.*
-AutoTest.Net/
-
-# Web workbench (sass)
-.sass-cache/
-
-# Installshield output folder
-[Ee]xpress/
-
-# DocProject is a documentation generator add-in
-DocProject/buildhelp/
-DocProject/Help/*.HxT
-DocProject/Help/*.HxC
-DocProject/Help/*.hhc
-DocProject/Help/*.hhk
-DocProject/Help/*.hhp
-DocProject/Help/Html2
-DocProject/Help/html
-
-# Click-Once directory
-publish/
-
-# Publish Web Output
-*.[Pp]ublish.xml
-*.azurePubxml
-# Note: Comment the next line if you want to checkin your web deploy settings,
-# but database connection strings (with potential passwords) will be unencrypted
-*.pubxml
-*.publishproj
-
-# Microsoft Azure Web App publish settings. Comment the next line if you want to
-# checkin your Azure Web App publish settings, but sensitive information contained
-# in these scripts will be unencrypted
-PublishScripts/
-
-# NuGet Packages
-*.nupkg
-# NuGet Symbol Packages
-*.snupkg
-# The packages folder can be ignored because of Package Restore
-**/[Pp]ackages/*
-# except build/, which is used as an MSBuild target.
-!**/[Pp]ackages/build/
-# Uncomment if necessary however generally it will be regenerated when needed
-#!**/[Pp]ackages/repositories.config
-# NuGet v3's project.json files produces more ignorable files
-*.nuget.props
-*.nuget.targets
-
-# Microsoft Azure Build Output
-csx/
-*.build.csdef
-
-# Microsoft Azure Emulator
-ecf/
-rcf/
-
-# Windows Store app package directories and files
-AppPackages/
-BundleArtifacts/
-Package.StoreAssociation.xml
-_pkginfo.txt
-*.appx
-*.appxbundle
-*.appxupload
-
-# Visual Studio cache files
-# files ending in .cache can be ignored
-*.[Cc]ache
-# but keep track of directories ending in .cache
-!?*.[Cc]ache/
+*.zip
+.quicksand/
+.uvr/
-# Others
-ClientBin/
-~$*
-*~
-*.dbmdl
-*.dbproj.schemaview
-*.jfm
-*.pfx
-*.publishsettings
-orleans.codegen.cs
-
-# Including strong name files can present a security risk
-# (https://github.com/github/gitignore/pull/2483#issue-259490424)
-#*.snk
-
-# Since there are multiple workflows, uncomment next line to ignore bower_components
-# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
-#bower_components/
-
-# RIA/Silverlight projects
-Generated_Code/
-
-# Backup & report files from converting an old project file
-# to a newer Visual Studio version. Backup files are not needed,
-# because we have git ;-)
-_UpgradeReport_Files/
-Backup*/
-UpgradeLog*.XML
-UpgradeLog*.htm
-ServiceFabricBackup/
-*.rptproj.bak
-
-# SQL Server files
-*.mdf
-*.ldf
-*.ndf
-
-# Business Intelligence projects
-*.rdl.data
-*.bim.layout
-*.bim_*.settings
-*.rptproj.rsuser
-*- [Bb]ackup.rdl
-*- [Bb]ackup ([0-9]).rdl
-*- [Bb]ackup ([0-9][0-9]).rdl
-
-# Microsoft Fakes
-FakesAssemblies/
-
-# GhostDoc plugin setting file
-*.GhostDoc.xml
-
-# Node.js Tools for Visual Studio
-.ntvs_analysis.dat
+# Node.js / VitePress
node_modules/
-
-# Visual Studio 6 build log
-*.plg
-
-# Visual Studio 6 workspace options file
-*.opt
-
-# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
-*.vbw
-
-# Visual Studio 6 auto-generated project file (contains which files were open etc.)
-*.vbp
-
-# Visual Studio 6 workspace and project file (working project files containing files to include in project)
-*.dsw
-*.dsp
-
-# Visual Studio 6 technical files
-*.ncb
-*.aps
-
-# Visual Studio LightSwitch build output
-**/*.HTMLClient/GeneratedArtifacts
-**/*.DesktopClient/GeneratedArtifacts
-**/*.DesktopClient/ModelManifest.xml
-**/*.Server/GeneratedArtifacts
-**/*.Server/ModelManifest.xml
-_Pvt_Extensions
-
-# Paket dependency manager
-**/.paket/paket.exe
-paket-files/
-
-# FAKE - F# Make
-**/.fake/
-
-# CodeRush personal settings
-**/.cr/personal
-
-# Python Tools for Visual Studio (PTVS)
-**/__pycache__/
-*.pyc
-
-# Cake - Uncomment if you are using it
-#tools/**
-#!tools/packages.config
-
-# Tabs Studio
-*.tss
-
-# Telerik's JustMock configuration file
-*.jmconfig
-
-# BizTalk build output
-*.btp.cs
-*.btm.cs
-*.odx.cs
-*.xsd.cs
-
-# OpenCover UI analysis results
-OpenCover/
-
-# Azure Stream Analytics local run output
-ASALocalRun/
-
-# MSBuild Binary and Structured Log
-*.binlog
-MSBuild_Logs/
-
-# AWS SAM Build and Temporary Artifacts folder
-.aws-sam
-
-# NVidia Nsight GPU debugger configuration file
-*.nvuser
-
-# MFractors (Xamarin productivity tool) working folder
-**/.mfractor/
-
-# Local History for Visual Studio
-**/.localhistory/
-
-# Visual Studio History (VSHistory) files
-.vshistory/
-
-# BeatPulse healthcheck temp database
-healthchecksdb
-
-# Backup folder for Package Reference Convert tool in Visual Studio 2017
-MigrationBackup/
-
-# Ionide (cross platform F# VS Code tools) working folder
-**/.ionide/
-
-# Fody - auto-generated XML schema
-FodyWeavers.xsd
-
-# VS Code files for those working on multiple tools
-.vscode/*
-!.vscode/settings.json
-!.vscode/tasks.json
-!.vscode/launch.json
-!.vscode/extensions.json
-!.vscode/*.code-snippets
-
-# Local History for Visual Studio Code
-.history/
-
-# Built Visual Studio Code Extensions
-*.vsix
-
-# Windows Installer files from build outputs
-*.cab
-*.msi
-*.msix
-*.msm
-*.msp
+docs/.vitepress/dist/
+docs/.vitepress/cache/
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..105f88a
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,465 @@
+# Changelog
+
+All notable changes to the quicksand project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/).
+
+## [v0.10.2] - 2026-04-15
+
+### Fixed
+- **quicksand:** `quicksand install` now handles Windows ARM64 with emulated (x86_64) Python — downloads both arch variants, retags image wheels for pip compatibility
+- **quicksand-core:** QEMU runtime resolution distinguishes "not installed" from "wrong architecture installed" with actionable error messages
+- **quicksand-core:** Added `_is_emulated()` detection for platform emulation (Windows ARM64 x86_64 Python)
+- **quicksand-ubuntu/alpine:** Image-not-found errors now detect emulation and guide users to `quicksand install`
+- **quicksand-alpine:** README now correctly references Alpine 3.23 (was 3.21)
+
+### Removed
+- **uvr_hooks:** Removed fat QEMU wheel merge from release pipeline — slim per-arch wheels are now published separately
+
+## [v0.10.1] - 2026-04-13
+
+### Added
+- **quicksand-qemu:** Windows ARM64 support — detects ARM64 Windows and uses the dedicated Stefan Weil ARM installer (`qemu-arm-setup-20260401.exe`)
+- **quicksand-qemu:** Added `[self-hosted, windows, arm64]` build runner
+- **quicksand-qemu:** ARM64 wheels now include `win_arm64` platform tag
+
+### Fixed
+- **quicksand-core:** Reverted `quicksand-qemu` from required to optional dependency — the hard dependency broke git-based installs because `quicksand-build-tools` is not published to PyPI
+- **quicksand:** Restored `qemu` optional extra (`pip install quicksand[qemu]`)
+
+## [v0.10.0] - 2026-04-13
+
+### Changed
+- **quicksand-core:** `quicksand-qemu` is now a required dependency instead of optional. This ensures QEMU binaries are always available and fixes build cascade issues where rebuilding `quicksand-qemu` didn't trigger rebuilds of packages that depend on it transitively through `quicksand-core`.
+- **quicksand:** Removed `qemu` optional extra (now redundant — `quicksand-core` always includes it).
+
+## [v0.9.6] - 2026-04-08
+
+### Added
+- **quicksand-qemu:** Build hook auto-installs QEMU when not on PATH (Homebrew on macOS, apt/dnf on Linux, Stefan Weil installer on Windows)
+- **quicksand-qemu:** SOURCES.md generated at build time with upstream source URLs for every bundled GPL/LGPL component
+- **quicksand-qemu:** CI license verification validates SOURCES.md presence and content in built wheels
+
+### Changed
+- QEMU installation moved from CI workflow steps into the build hook for self-contained builds
+- Test install step uses dynamic per-VM commands from the release plan
+
+## [v0.9.5] - 2026-04-08
+
+### Fixed
+- **quicksand-core:** Drain stale auth responses from virtio-serial socket buffer after connect retries. Fixes `ExecuteResponseResult.__init__() got an unexpected keyword argument 'authenticated'` on slow-booting VMs (TCG emulation, no KVM).
+- **quicksand-core:** Validate request/response ID correlation in `send_request` and `send_stream_request`. Mismatched IDs now return a clear error instead of silently returning the wrong result.
+
+## [v0.9.4] - 2026-04-01
+
+### Changed
+- **aif-cua-agent-sandbox:** Reduced overlay image size from ~604 MB to ~445 MB by removing unused Playwright headless shell, Vulkan GPU drivers, and system Node.js
+
+### Fixed
+- **quicksand-core:** Virtio-serial agent client now keeps connection open across auth retries — disconnecting caused QEMU to stop accepting new chardev connections
+- **quicksand-core:** Pin httpx<1.0 to prevent breaking API change
+- **quicksand-core:** Fix `MountSpec` → `Mount` in README exports
+- ARM64 image wheels built on macOS are now retagged for Linux via uvr post_build hook
+- **quicksand-alpine, quicksand-ubuntu:** Restore editable install guard in build hooks
+- **quicksand-alpine-desktop, quicksand-ubuntu-desktop:** Break up large package install commands to avoid build timeouts
+
+## [v0.9.3] - 2026-03-30
+
+### Added
+- **aif-cua-agent-sandbox:** noVNC web client (port 6080), websockify, socat, and rsync in the overlay image
+
+### Fixed
+- `quicksand run -p HOST:GUEST` port forward parsing now works correctly
+
+## [v0.9.2] - 2026-03-29
+
+### Added
+- `quicksand clean` CLI command to remove local `.quicksand/` and optionally global `~/.quicksand/` data directories
+
+## [v0.9.0] - 2026-03-26
+
+### Added
+- Virtio-serial guest agent transport — 25x boot speedup (Alpine p50: 11.5s → 0.45s)
+- `Sandbox.qemu_command` property to inspect the QEMU command line
+- `Sandbox.boot_timing` property with phase-level profiling (kernel, init, agent breakdown)
+- `BootTiming` dataclass with `__str__` for human-readable boot phase display
+- `quicksand benchmark` CLI command with percentile stats, progress bar, and `--json` output
+- `quicksand uninstall` CLI command to remove installed extras
+- `-v`/`--mount` option on benchmark command for measuring boot with mounts
+
+### Changed
+- Guest images now use static IP (10.0.2.15/24) instead of DHCP — eliminates ~8s dhcpcd overhead
+- Alpine: enabled `rc_parallel="YES"` for parallel OpenRC service startup
+- Alpine: guest agent moved to `boot` runlevel (from `default`)
+- Ubuntu: guest agent moved to `After=sysinit.target` (from `After=basic.target`)
+- Rust guest agent supports dual transport: virtio-serial first, HTTP fallback
+
+## [v0.7.1] - 2026-03-24
+
+### Changed
+- `quicksand-alpine-desktop` and `quicksand-ubuntu-desktop` converted from standalone base images to overlay images built on top of their respective base packages
+- Desktop image wheels are significantly smaller (Alpine: 359MB → 286MB, Ubuntu: 575MB → 254MB) since they only contain the overlay delta
+- Desktop packages now depend on `quicksand-alpine` / `quicksand-ubuntu` respectively
+- Docker is no longer required to build desktop image packages
+
+### Removed
+- Dockerfiles for desktop image packages (build now uses overlay mechanism)
+
+## [v0.7.0] - 2026-03-24
+
+### Changed
+- **Breaking:** `ResolvedImage.base` and `ResolvedImage.overlays` replaced with unified `chain: list[Path]` — `chain[0]` is the root base qcow2, `chain[1:]` are overlay layers in bottom-to-top order
+- **Breaking:** Save format bumped to v6 — only session-local overlays are stored; installed package overlays are resolved by name at load time
+- `ImageProvider` protocol now requires an `images_dir: Path` attribute
+- `qemu-img convert -c` preserves backing file references (`-B`) instead of flattening the full chain
+
+### Added
+- `aif-cua-agent-sandbox` overlay package (first release)
+- `_verify_overlay_from_package()` validates that non-session overlays belong to installed packages at save time
+
+## [v0.6.1] - 2026-03-24
+
+### Added
+- `SandboxConfig.arch` parameter for cross-architecture VM builds via TCG emulation
+- `quicksand run --arch` flag for cross-arch boot from the CLI
+- `quicksand install --arch` flag to download cross-platform wheels
+- `quicksand run IMAGE` — image is now a required positional argument (was `-b/--base`)
+- Overlay build phase in release pipeline (`build-overlay` job, runs after base images)
+- `--reuse-base-build` and `--reuse-overlay-build` flags for independent build reuse
+- `quicksand-base-scaffold` package for scaffolding new base image packages
+- `quicksand-overlay-scaffold --base` flag to choose which base image to overlay on
+
+### Changed
+- Release pipeline `build` job renamed to `build-base` for clarity
+- `quicksand install` removed legacy save-download path — all names are package installs
+- Scaffold packages output to fixed directories (`packages/` for base, `packages/contrib/` for overlay)
+- Workflow conditions use `fromJSON` null checks instead of `contains` string matching
+
+### Fixed
+- Release artifacts from multiple runs now merge correctly (tri-source downloads)
+- KVM setup is best-effort in overlay builds (falls back to TCG gracefully)
+- `_to_title` no longer uppercases short words; avoids `SandboxSandbox` in scaffold output
+
+## [v0.6.0] - 2026-03-23
+
+### Changed
+- **Breaking:** `SandboxConfig.image` is now `str` only (was `str | Path | ImagePaths`)
+- **Breaking:** `save()` returns `SaveManifest` instead of `SaveInfo`
+- **Breaking:** Removed `load` parameter from `Sandbox.__init__()` — use `SandboxConfig(image="save-name")` instead
+- **Breaking:** Save format bumped to v5 (directory-based, no tar support)
+- **Breaking:** Removed legacy `quicksand.bases` entry point group — only `quicksand.images` is supported
+- `ImageProvider` is now a `typing.Protocol` instead of an abstract class
+- Sandbox internal state uses flat fields instead of wrapper dataclasses
+- `build_qemu_command()` takes individual path arguments instead of `ImagePaths`/`DiskPaths`
+
+### Removed
+- `SavedConfig`, `SaveInfo`, `ImagePaths`, `DiskPaths`, `_BootState`, `_VMConfig`, `SandboxSnapshot` types
+- `_WorkspaceOptions`, `_QuicksandGuestAgentState`, `_QMPState`, `_VNCState` state wrappers
+- `SavedConfig.from_sandbox_config()` and `SavedConfig.resolve()` methods
+- `get_image_path()` and `get_image_artifacts()` legacy functions from image packages
+- `sandbox/_state.py` module
+- Legacy tar-based save format support (v3/v4 manifests)
+
+### Fixed
+- `SandboxConfig` is now truly frozen — never mutated after construction
+- Config mutation bug where `config.accel` was overwritten during cross-arch save loading
+- Hardcoded `quicksand_version: "0.1.0"` in save manifests
+
+## [v0.5.0] - 2026-03-20
+
+### Changed
+- **Breaking**: Entire Sandbox public API is now async/await
+ - `Sandbox` uses `async with` (`__aenter__`/`__aexit__`) and `await start()`/`stop()`
+ - All mixins are async: `execute`, `save`, `checkpoint`, `revert`, `mount`, `unmount`, `type_text`, `press_key`, `mouse_move`, `mouse_click`, `screenshot`, etc.
+ - `QMPClient` uses asyncio streams instead of blocking sockets
+ - `QuicksandGuestAgentClient` uses `httpx.AsyncClient`
+ - Examples updated with `asyncio.run()` wrappers
+ - Tests updated to pytest-asyncio + AsyncMock
+
+## [v0.3.3] - 2026-03-18
+
+### Added
+- `python -m quicksand` entrypoint (equivalent to `quicksand` CLI)
+
+### Fixed
+- Bumped GitHub Actions to latest versions (Node.js 24 support)
+
+## [v0.3.2] - 2026-03-17
+
+### Fixed
+- `quicksand install` failing to resolve third-party dependencies (httpx) due to `--no-index` flag blocking PyPI access
+
+## [v0.3.0] - 2026-03-17
+
+### Added
+- CIFS hot-mount API: `sb.mount()` / `sb.unmount()` with `MountHandle`
+- `quicksand-smb` package: pure-Python SMB3 server spawned via QEMU guestfwd (no TCP port, no Samba, zero dependencies)
+- `NetworkMode.MOUNTS_ONLY` — mounts without internet access via guestfwd tunnels
+- `NetworkMode` enum now has three modes: `NONE`, `MOUNTS_ONLY` (default), `FULL`
+- QEMU block layer flush before snapshot pivot to prevent data loss on large writes
+- Path traversal protection in SMB server (symlink + `..` escape checks)
+- `examples/mounts.py` demonstrating boot-time, dynamic, and readonly mount patterns
+
+### Changed
+- Replaced `quicksand-smbd` (bundled Samba binary, 50MB+) with `quicksand-smb` (pure Python, ~2K LOC)
+- Default network mode is now `MOUNTS_ONLY` (was `HOST_ONLY`)
+- Mounts use CIFS over guestfwd in all network modes (no TCP port opened on host)
+
+### Removed
+- `quicksand-smbd` package (replaced by `quicksand-smb`)
+- 9p as default mount protocol (replaced by CIFS; 9p remains available via `type="9p"`)
+
+### Fixed
+- macOS SIP `PermissionError` when copying binaries
+- `NetworkMode` enum definition to properly support three modes
+
+## [v0.2.3] - 2026-03-12
+
+### Added
+- `quicksand-ubuntu-desktop` package with full Ubuntu 24.04 desktop sandbox support
+- `quicksand-alpine-desktop` package
+- `Key` enum for keyboard input
+- Image install CLI (`quicksand images install <name>`)
+- `query_display_size()` API for display introspection
+- Double-click support in input API
+- Overlay chain support in core snapshot/checkpoint system
+
+### Changed
+- Refactored core to use `NetworkMode` enum, overlay chains, and display/input subsystem
+- Updated Alpine and Ubuntu base packages for `NetworkMode` API
+- Renamed `quicksand-agent` to `quicksand-guest-agent`
+- Updated guest agent and dev tools for new core API
+- Improved desktop images with browser support, software cursor, and DNS fixes
+
+### Fixed
+- Checkpoint integration tests for overlay chain format
+- Typecheck issues with `overlay_chain` in `SandboxSnapshot`
+- CI version bump to push from latest main instead of tag HEAD
+
+## [v0.2.2] - 2026-02-27
+
+### Changed
+- Renamed `quicksand-agent` to `quicksand-guest-agent`; added package init scaffold
+
+### Fixed
+- Integration test compatibility with renamed package
+
+## [v0.2.1] - 2026-02-26
+
+### Changed
+- Refactored core internals
+- `install` command now supports multi-argument package installation
+
+## [v0.2.0] - 2026-02-26
+
+### Added
+- Streaming `execute()` API for real-time command output
+- README install instructions using `quicksand` CLI installer
+
+### Changed
+- Refactored core internals; removed `write_file`/`read_file` in favor of `execute()`
+- Updated integration tests to use `execute()` API
+
+### Fixed
+- Missing `readline` import error on Windows
+- Binary file tests to use POSIX-compatible tools (`od` instead of `xxd`)
+
+## [v0.1.27] - 2026-02-24
+
+### Fixed
+- Mount hangs when `restrict_network=True`
+
+## [v0.1.26] - 2026-02-24
+
+### Fixed
+- DNS resolution in Ubuntu sandbox (enabled `systemd-resolved`)
+- Reverted DNS changes that broke mount tests
+
+## [v0.1.25] - 2026-02-24
+
+### Changed
+- QEMU bundling is now optional
+
+## [v0.1.24] - 2026-02-24
+
+### Added
+- CLI to `quicksand` package
+- `quicksand-qemu` CI build jobs
+
+## [v0.1.23] - 2026-02-23
+
+### Added
+- Rust guest agent, replacing the Python agent for smaller images and faster startup
+- `curl` added to Alpine image for network tests
+
+## [v0.1.22] - 2026-02-20
+
+### Fixed
+- microvm + Ubuntu compatibility: match `eth*` interfaces in `systemd-networkd`
+
+## [v0.1.21] - 2026-02-20
+
+### Changed
+- Disabled microvm temporarily due to Ubuntu compatibility issues
+
+## [v0.1.20] - 2026-02-20
+
+### Fixed
+- microvm networking by using explicit `-netdev`/`-device` QEMU args
+
+## [v0.1.19] - 2026-02-20
+
+### Added
+- GPL license files for QEMU binary distribution (Section 3(c) compliance)
+- QEMU version tracking
+
+### Removed
+- Redundant `bundle_qemu.py` script (inlined into `hatch_build.py`)
+
+## [v0.1.18] - 2026-02-20
+
+### Added
+- microvm support: bundle `bios-microvm.bin` for ~4x faster boot on Linux x86_64
+- QEMU performance optimizations
+
+### Fixed
+- microvm `bios-microvm.bin` existence check before enabling
+- `_build_mount_args` signature change in tests
+
+## [v0.1.16] - 2026-02-19
+
+### Added
+- Serial console output for boot debugging
+
+### Changed
+- Renamed `install.py` to `installer.py`
+
+### Fixed
+- Docker build: remove `/etc/resolv.conf` before symlinking
+- Ubuntu DNS by enabling `systemd-resolved`
+- Installer tests
+
+## [v0.1.15] - 2026-02-17
+
+### Added
+- SMB-based mounting for Windows hosts, replacing `FileSyncAgent`
+
+### Fixed
+- Windows SMB mount (standard port 445, explicit CIFS options)
+- Build hooks importing from package being built
+- Checkpoint tests with mounts on Windows
+
+## [v0.1.14] - 2026-02-15
+
+### Changed
+- Use pyproject entry points for optional package discovery
+
+## [v0.1.13] - 2026-02-14
+
+### Changed
+- Refactored host module naming: `Platform` enum renamed to `OS`; merged runtime module
+
+## [v0.1.12] - 2026-02-12
+
+### Added
+- `ARCHITECTURE.md` documenting codebase structure and QEMU glossary
+- Comprehensive tests for `quicksand-image-tools` CLI
+- Per-package tags with bundled releases
+- Python-based wheel merge script (`merge_wheels.py`)
+
+### Changed
+- CI release flow: single tag with incremental builds
+- Separated build tasks for core and image packages
+
+### Removed
+- Committed `agent.py` from `quicksand-alpine` (now generated)
+
+## [v0.1.11] - 2026-02-12
+
+### Changed
+- Refactored `sandbox.py` into modular VM components
+- Refactored platform config to subclass-based architecture
+
+### Fixed
+- `filesync` import error on Windows guest
+
+## [v0.1.10] - 2026-02-11
+
+### Changed
+- Redesigned `image_wrapper` to properly subclass `Sandbox`
+
+## [v0.1.9] - 2026-02-11
+
+### Changed
+- Optimized QEMU boot time
+
+## [v0.1.8] - 2026-02-11
+
+### Added
+- `install.py` helper script for GitHub releases with download progress bars
+- Interactive `test` subcommand with `--mount`, `--network`, and sandbox type options
+- DNS resolution and curl HTTPS integration tests
+- Cross-platform CI: unit tests on Linux, macOS, and Windows
+- Matrix test-installer workflow across OS and image type
+
+### Fixed
+- Platform matching in `install.py` for wheel selection
+- Progress bar Unicode error on Windows
+- Network integration tests
+
+## [v0.1.7] - 2026-02-11
+
+### Changed
+- Switched to tag-based releases
+- Consolidated CI into single workflow (check, build, test)
+
+## [v0.1.6] - 2026-02-11
+
+### Changed
+- Redesigned CI workflows: separate check/build/test stages with proper release flow
+- Cross-workflow artifact handling via `gh run download`
+
+### Removed
+- Debug KVM ARM64 workflow
+
+## [v0.1.5] - 2026-02-11
+
+### Changed
+- Split CI into separate workflows
+
+## [v0.1.4] - 2026-02-11
+
+### Added
+- `sync_file()` API for explicit file sync
+- Bidirectional filesync with `use_filesync` config option
+- Standalone release workflow
+- WHPX kernel arg (`noapic`) for Windows
+
+### Fixed
+- Windows filesync: path handling, port initialization, atomic rename, bidirectional sync
+- Filesync initial sync race condition
+- WHPX kernel panic by correcting QEMU arg order
+
+## [v0.1.3] - 2026-02-10
+
+### Fixed
+- CI: removed `continue-on-error` from build and test jobs
+
+## [v0.1.2] - 2026-02-10
+
+### Changed
+- CI workflow now triggers on version tags
+
+## [v0.1.1] - 2026-02-10
+
+### Added
+- Initial release of quicksand: pip-installable Linux sandboxes powered by QEMU
+- Core sandbox API with `Sandbox` and `UbuntuSandbox` classes
+- Monorepo packages: `quicksand-core`, `quicksand-ubuntu`, `quicksand-alpine`, `quicksand-qemu`
+- QEMU binary bundling for macOS, Linux, and Windows
+- Direct kernel boot with virtio networking and 9p mounts
+- FastAPI-based HTTP guest agent
+- P2P file sync for Windows hosts (virtio-9p alternative)
+- Docker-based VM image building
+- CI/CD pipeline with per-platform wheel builds and integration tests
+- MIT License
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..8d09dd6
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,36 @@
+# Contributing to Quicksand
+
+## Development Setup
+
+```bash
+git clone https://github.com/microsoft/quicksand
+cd quicksand
+uv sync --all-packages --all-groups --all-extras
+```
+
+Run checks and tests:
+```bash
+uv run poe ci
+```
+
+## Guides
+
+| Guide | What it covers |
+|-------|---------------|
+| [Creating Images](docs/contributor-guide/01-creating-images.md) | Build a new base or overlay image package |
+| [Extending the Sandbox](docs/contributor-guide/02-extending-the-sandbox.md) | Add a method, OS, architecture, or QEMU flag |
+| [Testing](docs/contributor-guide/03-testing.md) | Run or write tests |
+| [Releasing](docs/contributor-guide/04-releasing.md) | Cut a release |
+
+See the full [Contributor Guide](docs/contributor-guide/).
+
+## Code Style
+
+- Format with `ruff format`
+- Lint with `ruff check`
+- Type check with `ty check`
+- Run `uv run poe ci` before submitting PRs
+
+## Questions?
+
+Open an issue on GitHub.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..9e841e7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+ MIT License
+
+ Copyright (c) Microsoft Corporation.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..eefd254
--- /dev/null
+++ b/README.md
@@ -0,0 +1,286 @@
+# Quicksand
+
+Quicksand is a Python API for launching and controlling [QEMU](https://www.qemu.org) virtual machines. It provides pre-built Linux VMs for ubuntu and alpine distros. It works on macOS, Linux, and Windows with no root privileges, no Docker, and no system dependencies. Just `pip install quicksand`.
+
+## Installation
+
+*Note: once released to PyPI this all just becomes: `pip install 'quicksand[qemu,ubuntu]'`*
+
+### Install from Azure DevOps Artifacts (Preferred)
+
+First, install `keyring` with the Azure Artifacts backend so `uv`/`pip` can authenticate automatically:
+
+```bash
+uv tool install keyring --with artifacts-keyring
+```
+
+Then install quicksand from the feed:
+
+```bash
+uv pip install \
+ --index-url https://pkgs.dev.azure.com/msraif/_packaging/packages/pypi/simple/ \
+ --keyring-provider subprocess \
+ 'quicksand[qemu,alpine,ubuntu]'
+```
+
+To declare the feed as a dependency source in your own `pyproject.toml`:
+
+```toml
+[tool.uv]
+keyring-provider = "subprocess"
+
+[[tool.uv.index]]
+name = "azure-msraif"
+url = "https://[email protected]/msraif/_packaging/packages/pypi/simple/"
+
+[project]
+dependencies = [
+ "quicksand[qemu,alpine,ubuntu]",
+]
+```
+
+### Install from GitHub
+
+```bash
+pip install git+ssh://[email protected]/microsoft/quicksand#subdirectory=packages/quicksand
+quicksand install qemu ubuntu
+```
+
+To declare it as a dependency in your `pyproject.toml`:
+
+```toml
+[project]
+dependencies = [
+ "quicksand",
+]
+
+[tool.uv.sources]
+quicksand = { git = "ssh://[email protected]/microsoft/quicksand", subdirectory = "packages/quicksand" }
+```
+
+To pin to a specific release, use a `quicksand/vX.Y.Z` tag:
+
+```toml
+[tool.uv.sources]
+quicksand = { git = "ssh://[email protected]/microsoft/quicksand", subdirectory = "packages/quicksand", tag = "quicksand/v0.9.0" }
+```
+
+## Usage
+
+### Hello, World!
+
+```python
+import asyncio
+from quicksand import Sandbox
+
+async def main():
+ async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("echo 'Hello from the sandbox!'")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### Run commands
+
+```python
+result = await sb.execute("apt update && apt install -y python3")
+print(result.stdout, result.exit_code)
+```
+
+### Mount host directories
+
+Share host directories into the VM at boot or on the fly.
+
+```python
+# At boot
+async with Sandbox(
+ image="ubuntu",
+ mounts=[Mount("./workspace", "/mnt/workspace")],
+) as sb:
+ ...
+
+# Or dynamically on a running sandbox
+handle = await sb.mount("/tmp/data", "/mnt/data")
+await sb.execute("ls /mnt/data")
+await sb.unmount(handle)
+```
+
+### Configure networking
+
+Sandboxes are network-isolated by default. Opt in to internet access and port forwarding with `NetworkMode.FULL`.
+
+```python
+async with Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.FULL,
+ port_forwards=[PortForward(host=8080, guest=80)],
+) as sb:
+ ...
+```
+
+### Save and load
+
+Save the VM's disk state to a directory. Load it later, even on a different machine.
+
+```python
+await sb.execute("pip install numpy pandas")
+await sb.save("my-env") # VM keeps running
+
+# Load later
+async with Sandbox(image="my-env") as sb:
+ await sb.execute("python3 -c 'import numpy; print(numpy.__version__)'")
+```
+
+
+### Checkpoint and revert
+
+Capture the full VM state and roll back if something goes wrong.
+
+```python
+await sb.checkpoint("before-experiment")
+await sb.execute("apt install -y something-risky")
+await sb.revert("before-experiment") # the VM snaps back to the checkpoint
+```
+
+### Control a desktop
+
+Desktop images provide a full Xfce4 graphical environment with a browser. Install one with `quicksand install ubuntu-desktop` or `quicksand install alpine-desktop`.
+
+```python
+async with Sandbox(image="ubuntu-desktop", enable_display=True) as sb:
+ await sb.screenshot("screen.png")
+ await sb.type_text("hello world")
+ await sb.press_key(Key.RET)
+ await sb.mouse_move(500, 300)
+ await sb.mouse_click("left")
+```
+
+### Configuration
+
+Here are all of the Sandbox configuration options:
+
+```python
+Sandbox(
+ # Image or save name to boot
+ image="ubuntu",
+ # Guest RAM (default: "512M")
+ memory="2G",
+ # Virtual CPU cores (default: 1)
+ cpus=4,
+ # Host directories shared into the VM at boot
+ mounts=[Mount("/host", "/guest")],
+ # NONE, MOUNTS_ONLY (default), or FULL internet access
+ network_mode=NetworkMode.FULL,
+ # Forward host TCP ports into the guest
+ port_forwards=[PortForward(host=8080, guest=80)],
+ # Expand the guest filesystem on boot
+ disk_size="10G",
+ # Attach virtual GPU, keyboard, and mouse for screenshot/type_text/mouse control
+ enable_display=True,
+ # Auto-save VM state on stop
+ save="my-save-name",
+)
+```
+
+## Available images
+
+| Image | Type | Wheel size | Install command | What is it |
+|-------|------|-----------|-----------------|------------|
+| `ubuntu` | Base | ~341 MB | `quicksand install ubuntu` | Ubuntu 24.04 headless |
+| `alpine` | Base | ~78 MB | `quicksand install alpine` | Alpine 3.21 headless (faster boot) |
+| `ubuntu-desktop` | Overlay (`ubuntu`) | ~263 MB | `quicksand install ubuntu-desktop` | Ubuntu 24.04 + Xfce4 + Firefox |
+| `alpine-desktop` | Overlay (`alpine`) | ~310 MB | `quicksand install alpine-desktop` | Alpine 3.21 + Xfce4 + Chromium |
+| `aif-agent-sandbox` | Overlay (`ubuntu`) | ~304 MB | `quicksand install aif-agent-sandbox` | Ubuntu + Python 3.12, uv, build-essential, requests, pyyaml, ddgs, markitdown |
+| `aif-cua-agent-sandbox` | Overlay (`aif-agent-sandbox`) | ~445 MB | `quicksand install aif-cua-agent-sandbox` | AIF Agent Sandbox + Xvfb, x11vnc, noVNC, Playwright, Chromium |
+
+## Building from source
+
+Clone the repo and set up the workspace:
+
+```bash
+git clone [email protected]:microsoft/quicksand.git
+cd quicksand
+uv sync
+```
+
+### Building individual packages
+
+Each package lives under `packages/` (or `packages/dev/`, `packages/contrib/`). To build a wheel:
+
+```bash
+uv build --package <package-name> --find-links dist/
+```
+
+Image packages (e.g. `quicksand-ubuntu`, `aif-agent-sandbox`) produce platform-specific wheels that contain qcow2 disk images. They require their base image wheels to be available in `dist/`, so use `--find-links dist/` and build dependencies first.
+
+For overlay image packages that build on top of other images, you also need `--no-sources` so the build uses the pre-built wheel rather than the editable source (which has no images):
+
+```bash
+uv build --package aif-cua-agent-sandbox --find-links dist/ --no-sources
+```
+
+### Build order
+
+Packages must be built bottom-up since image packages depend on their base:
+
+1. `quicksand-core`, `quicksand-qemu`, `quicksand-smb` (pure runtime, no images)
+2. `quicksand-ubuntu`, `quicksand-alpine` (base images, built from Dockerfiles)
+3. `quicksand-ubuntu-desktop`, `quicksand-alpine-desktop`, `aif-agent-sandbox` (overlays on base images)
+4. `aif-cua-agent-sandbox` (overlay on `aif-agent-sandbox`)
+
+### Installing and running built wheels
+
+The workspace uses editable installs by default, which means image packages won't have their bundled qcow2 files. To test a built wheel, install it explicitly and use `--no-project` to prevent `uv run` from syncing back to the editable source:
+
+```bash
+uv pip install --force-reinstall --find-links dist/ dist/aif_cua_agent_sandbox-0.1.6-py3-none-macosx_11_0_arm64.whl
+uv run --no-project quicksand run aif-cua-agent-sandbox
+```
+
+Or from Python:
+
+```bash
+uv run --no-project python -c "
+import asyncio
+from quicksand_core import Sandbox
+
+async def main():
+ async with Sandbox(image='aif-cua-agent-sandbox') as sb:
+ r = await sb.execute('echo hello')
+ print(r.stdout)
+
+asyncio.run(main())
+"
+```
+
+### Running checks
+
+```bash
+uv run poe fix # auto-format and fix lint issues
+uv run poe check # type-check, lint, and run tests
+```
+
+## Documentation
+
+| Topic | Guide | Under the Hood |
+|-------|-------|----------------|
+| Installation | [Installing packages](docs/user-guide/01-installation.md) | [QEMU binaries, kernels, qcow2 disks](docs/under-the-hood/01-installation.md) |
+| Sandbox Lifecycle | [Creating and configuring sandboxes](docs/user-guide/02-sandbox-lifecycle.md) | [`-m`, `-smp`, `-accel`, machine types](docs/under-the-hood/02-sandbox-lifecycle.md) |
+| Running Commands | [`execute()`, streaming, exit codes](docs/user-guide/03-running-commands.md) | [Kernel boot, agent tokens, `hostfwd`](docs/under-the-hood/03-running-commands.md) |
+| File Exchange | [Mounts, hot-mounts, getting data in/out](docs/user-guide/04-file-exchange.md) | [CIFS via `guestfwd`, 9p via `-fsdev`](docs/under-the-hood/04-file-exchange.md) |
+| Save and Rollback | [Checkpoints, reverts, persistent saves](docs/user-guide/05-save-and-rollback.md) | [qcow2 overlays, `savevm`, `blockdev-snapshot-sync`](docs/under-the-hood/05-save-and-rollback.md) |
+| Desktop Control | [Screenshots, keyboard, mouse](docs/user-guide/06-desktop-control.md) | [VNC, GPU, USB tablet, QMP input injection](docs/under-the-hood/06-desktop-control.md) |
+| Network and Isolation | [Network modes, port forwarding](docs/user-guide/07-network-and-isolation.md) | [SLIRP NAT, `restrict=on`, `guestfwd`](docs/under-the-hood/07-network-and-isolation.md) |
+| Performance | [What makes it fast](docs/user-guide/08-performance.md) | [`microvm`, `io_uring`, IOThreads, TCG vs KVM](docs/under-the-hood/08-performance.md) |
+
+### Contributing
+
+| Guide | When to use |
+|-------|------------|
+| [Creating Images](docs/contributor-guide/01-creating-images.md) | Build a new base or overlay image package |
+| [Extending the Sandbox](docs/contributor-guide/02-extending-the-sandbox.md) | Add a method, OS, architecture, or QEMU flag |
+| [Testing](docs/contributor-guide/03-testing.md) | Run or write tests |
+| [Releasing](docs/contributor-guide/04-releasing.md) | Cut a release |
+
+Full guides: [User Guide](docs/user-guide/) | [Under the Hood](docs/under-the-hood/) | [Contributor Guide](docs/contributor-guide/)
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..e751608
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,14 @@
+<!-- BEGIN MICROSOFT SECURITY.MD V1.0.0 BLOCK -->
+
+## Security
+
+Microsoft takes the security of our software products and services seriously, which
+includes all source code repositories in our GitHub organizations.
+
+**Please do not report security vulnerabilities through public GitHub issues.**
+
+For security reporting information, locations, contact information, and policies,
+please review the latest guidance for Microsoft repositories at
+[https://aka.ms/SECURITY.md](https://aka.ms/SECURITY.md).
+
+<!-- END MICROSOFT SECURITY.MD BLOCK -->
\ No newline at end of file
diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts
new file mode 100644
index 0000000..747cd6a
--- /dev/null
+++ b/docs/.vitepress/config.mts
@@ -0,0 +1,176 @@
+import { defineConfig } from 'vitepress'
+import { withMermaid } from 'vitepress-plugin-mermaid'
+
+export default withMermaid(
+ defineConfig({
+ title: 'Quicksand',
+ description: 'Full Linux VMs from Python',
+
+ themeConfig: {
+ nav: [
+ {
+ text: 'User Guide',
+ items: [
+ { text: 'Overview', link: '/user-guide/' },
+ { text: 'Installation', link: '/user-guide/01-installation' },
+ { text: 'Sandbox Lifecycle', link: '/user-guide/02-sandbox-lifecycle' },
+ { text: 'Running Commands', link: '/user-guide/03-running-commands' },
+ { text: 'File Exchange', link: '/user-guide/04-file-exchange' },
+ { text: 'Save and Rollback', link: '/user-guide/05-save-and-rollback' },
+ { text: 'Desktop Control', link: '/user-guide/06-desktop-control' },
+ { text: 'Network and Isolation', link: '/user-guide/07-network-and-isolation' },
+ { text: 'Performance', link: '/user-guide/08-performance' },
+ ],
+ },
+ {
+ text: 'Under the Hood',
+ items: [
+ { text: 'Overview', link: '/under-the-hood/' },
+ { text: 'Installation', link: '/under-the-hood/01-installation' },
+ { text: 'Sandbox Lifecycle', link: '/under-the-hood/02-sandbox-lifecycle' },
+ { text: 'Running Commands', link: '/under-the-hood/03-running-commands' },
+ { text: 'File Exchange', link: '/under-the-hood/04-file-exchange' },
+ { text: 'Save and Rollback', link: '/under-the-hood/05-save-and-rollback' },
+ { text: 'Desktop Control', link: '/under-the-hood/06-desktop-control' },
+ { text: 'Network and Isolation', link: '/under-the-hood/07-network-and-isolation' },
+ { text: 'Performance', link: '/under-the-hood/08-performance' },
+ ],
+ },
+ {
+ text: 'Contributing',
+ items: [
+ { text: 'Overview', link: '/contributor-guide/' },
+ { text: 'Creating Images', link: '/contributor-guide/01-creating-images' },
+ { text: 'Extending the Sandbox', link: '/contributor-guide/02-extending-the-sandbox' },
+ { text: 'Testing', link: '/contributor-guide/03-testing' },
+ { text: 'Releasing', link: '/contributor-guide/04-releasing' },
+ ],
+ },
+ {
+ text: 'Packages',
+ items: [
+ { text: 'Overview', link: '/packages/' },
+ { text: 'quicksand', link: '/packages/quicksand' },
+ { text: 'quicksand-core', link: '/packages/quicksand-core' },
+ { text: 'quicksand-qemu', link: '/packages/quicksand-qemu' },
+ { text: 'quicksand-smb', link: '/packages/quicksand-smb' },
+ { text: 'quicksand-ubuntu', link: '/packages/quicksand-ubuntu' },
+ { text: 'quicksand-alpine', link: '/packages/quicksand-alpine' },
+ { text: 'quicksand-ubuntu-desktop', link: '/packages/quicksand-ubuntu-desktop' },
+ { text: 'quicksand-alpine-desktop', link: '/packages/quicksand-alpine-desktop' },
+ { text: 'aif-agent-sandbox', link: '/packages/aif-agent-sandbox' },
+ { text: 'aif-cua-agent-sandbox', link: '/packages/aif-cua-agent-sandbox' },
+ { text: 'quicksand-image-tools', link: '/packages/quicksand-image-tools' },
+ { text: 'quicksand-base-scaffold', link: '/packages/quicksand-base-scaffold' },
+ { text: 'quicksand-overlay-scaffold', link: '/packages/quicksand-overlay-scaffold' },
+ { text: 'quicksand-build-tools', link: '/packages/quicksand-build-tools' },
+ { text: 'quicksand-gh-runners', link: '/packages/quicksand-gh-runners' },
+ ],
+ },
+ { text: 'Changelog', link: '/reference/changelog' },
+ ],
+
+ sidebar: {
+ '/user-guide/': [
+ {
+ text: 'User Guide',
+ items: [
+ { text: 'Overview', link: '/user-guide/' },
+ { text: 'Installation', link: '/user-guide/01-installation' },
+ { text: 'Sandbox Lifecycle', link: '/user-guide/02-sandbox-lifecycle' },
+ { text: 'Running Commands', link: '/user-guide/03-running-commands' },
+ { text: 'File Exchange', link: '/user-guide/04-file-exchange' },
+ { text: 'Save and Rollback', link: '/user-guide/05-save-and-rollback' },
+ { text: 'Desktop Control', link: '/user-guide/06-desktop-control' },
+ { text: 'Network and Isolation', link: '/user-guide/07-network-and-isolation' },
+ { text: 'Performance', link: '/user-guide/08-performance' },
+ ],
+ },
+ ],
+ '/under-the-hood/': [
+ {
+ text: 'Under the Hood',
+ items: [
+ { text: 'Overview', link: '/under-the-hood/' },
+ { text: 'Installation', link: '/under-the-hood/01-installation' },
+ { text: 'Sandbox Lifecycle', link: '/under-the-hood/02-sandbox-lifecycle' },
+ { text: 'Running Commands', link: '/under-the-hood/03-running-commands' },
+ { text: 'File Exchange', link: '/under-the-hood/04-file-exchange' },
+ { text: 'Save and Rollback', link: '/under-the-hood/05-save-and-rollback' },
+ { text: 'Desktop Control', link: '/under-the-hood/06-desktop-control' },
+ { text: 'Network and Isolation', link: '/under-the-hood/07-network-and-isolation' },
+ { text: 'Performance', link: '/under-the-hood/08-performance' },
+ ],
+ },
+ ],
+ '/contributor-guide/': [
+ {
+ text: 'Contributor Guide',
+ items: [
+ { text: 'Overview', link: '/contributor-guide/' },
+ { text: 'Creating Images', link: '/contributor-guide/01-creating-images' },
+ { text: 'Extending the Sandbox', link: '/contributor-guide/02-extending-the-sandbox' },
+ { text: 'Testing', link: '/contributor-guide/03-testing' },
+ { text: 'Releasing', link: '/contributor-guide/04-releasing' },
+ ],
+ },
+ ],
+ '/packages/': [
+ {
+ text: 'Runtime',
+ items: [
+ { text: 'quicksand', link: '/packages/quicksand' },
+ { text: 'quicksand-core', link: '/packages/quicksand-core' },
+ { text: 'quicksand-qemu', link: '/packages/quicksand-qemu' },
+ { text: 'quicksand-smb', link: '/packages/quicksand-smb' },
+ ],
+ },
+ {
+ text: 'Images',
+ items: [
+ { text: 'quicksand-ubuntu', link: '/packages/quicksand-ubuntu' },
+ { text: 'quicksand-alpine', link: '/packages/quicksand-alpine' },
+ { text: 'quicksand-ubuntu-desktop', link: '/packages/quicksand-ubuntu-desktop' },
+ { text: 'quicksand-alpine-desktop', link: '/packages/quicksand-alpine-desktop' },
+ { text: 'aif-agent-sandbox', link: '/packages/aif-agent-sandbox' },
+ { text: 'aif-cua-agent-sandbox', link: '/packages/aif-cua-agent-sandbox' },
+ ],
+ },
+ {
+ text: 'Dev Tools',
+ items: [
+ { text: 'quicksand-image-tools', link: '/packages/quicksand-image-tools' },
+ { text: 'quicksand-base-scaffold', link: '/packages/quicksand-base-scaffold' },
+ { text: 'quicksand-overlay-scaffold', link: '/packages/quicksand-overlay-scaffold' },
+ { text: 'quicksand-build-tools', link: '/packages/quicksand-build-tools' },
+ { text: 'quicksand-gh-runners', link: '/packages/quicksand-gh-runners' },
+ ],
+ },
+ ],
+ '/reference/': [
+ {
+ text: 'Reference',
+ items: [
+ { text: 'Changelog', link: '/reference/changelog' },
+ { text: 'Security', link: '/reference/security' },
+ ],
+ },
+ ],
+ },
+
+ socialLinks: [
+ { icon: 'github', link: 'https://github.com/microsoft/quicksand' },
+ ],
+
+ search: {
+ provider: 'local',
+ },
+
+ editLink: {
+ pattern: 'https://github.com/microsoft/quicksand/edit/main/docs/:path',
+ },
+ },
+
+ mermaid: {},
+ })
+)
diff --git a/docs/.vitepress/theme/custom.css b/docs/.vitepress/theme/custom.css
new file mode 100644
index 0000000..f71a9ab
--- /dev/null
+++ b/docs/.vitepress/theme/custom.css
@@ -0,0 +1,46 @@
+:root {
+ /* Microsoft yellow (#FFB900) as the brand color */
+ --vp-c-brand-1: #FFB900;
+ --vp-c-brand-2: #E6A700;
+ --vp-c-brand-3: #CC9500;
+ --vp-c-brand-soft: rgba(255, 185, 0, 0.14);
+
+ --vp-button-brand-border: transparent;
+ --vp-button-brand-text: #1a1a1a;
+ --vp-button-brand-bg: #FFB900;
+ --vp-button-brand-hover-border: transparent;
+ --vp-button-brand-hover-text: #1a1a1a;
+ --vp-button-brand-hover-bg: #E6A700;
+ --vp-button-brand-active-border: transparent;
+ --vp-button-brand-active-text: #1a1a1a;
+ --vp-button-brand-active-bg: #CC9500;
+
+ --vp-home-hero-name-color: #FFB900;
+}
+
+.VPHero .tagline a {
+ text-decoration: underline;
+}
+
+.VPHero .tagline,
+.VPHero .tagline span,
+.VPHero .tagline code {
+ color: var(--vp-c-text-1) !important;
+}
+
+.VPHero .tagline code {
+ background: var(--vp-c-brand-soft);
+ color: var(--vp-c-brand-1) !important;
+ padding: 2px 8px;
+ border-radius: 6px;
+ font-size: 0.95em;
+}
+
+.dark {
+ --vp-c-brand-1: #FFB900;
+ --vp-c-brand-2: #FFCA33;
+ --vp-c-brand-3: #FFD966;
+ --vp-c-brand-soft: rgba(255, 185, 0, 0.16);
+
+ --vp-home-hero-name-color: #FFB900;
+}
diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts
new file mode 100644
index 0000000..42fe9a9
--- /dev/null
+++ b/docs/.vitepress/theme/index.ts
@@ -0,0 +1,4 @@
+import DefaultTheme from 'vitepress/theme'
+import './custom.css'
+
+export default DefaultTheme
diff --git a/docs/contributor-guide/01-creating-images.md b/docs/contributor-guide/01-creating-images.md
new file mode 100644
index 0000000..e1c52bc
--- /dev/null
+++ b/docs/contributor-guide/01-creating-images.md
@@ -0,0 +1,148 @@
+# Creating Images
+
+There are two kinds: **base images** built from Dockerfiles, and **overlay images** built by running setup commands on a running base VM.
+
+## Prerequisites
+
+Install dev tools:
+```bash
+quicksand install dev
+# or: pip install 'quicksand[dev]'
+```
+
+This gives you the `quicksand dev` CLI with scaffold and image-building commands.
+
+---
+
+## Base images
+
+Base image packages (like `quicksand-ubuntu`) bundle a kernel, initrd, and qcow2 disk built from a Dockerfile.
+
+### Scaffold
+
+```bash
+quicksand dev scaffold base quicksand-mylinux
+```
+
+This creates `quicksand-mylinux/` with a Dockerfile, build hook, Python API, and pyproject.toml. In Claude Code, `/new-base-image` wraps this interactively.
+
+Use `--output-dir` to control where the package is created (defaults to `./<name>`).
+
+### Customize the Dockerfile
+
+Edit `quicksand_mylinux/docker/Dockerfile`. Every base image must provide:
+
+**Kernel + initramfs:**
+```dockerfile
+# Ubuntu
+RUN apt-get install -y linux-image-virtual \
+ && KVER=$(ls /lib/modules/ | head -1) \
+ && update-initramfs -c -k ${KVER}
+
+# Alpine
+RUN apk add --no-cache linux-virt
+```
+
+**Init system:**
+```dockerfile
+# Ubuntu (systemd)
+RUN apt-get install -y systemd systemd-sysv
+
+# Alpine (OpenRC)
+RUN apk add --no-cache openrc busybox-openrc
+```
+
+**9p modules, user, networking, agent:**
+```dockerfile
+RUN echo "9p" >> /etc/modules && echo "9pnet" >> /etc/modules && echo "9pnet_virtio" >> /etc/modules
+RUN useradd -m -s /bin/bash quicksand
+COPY quicksand-sudoers /etc/sudoers.d/quicksand
+
+# Agent via multi-stage build
+FROM rust:bookworm AS agent-builder
+COPY agent/ /build/
+RUN cd /build && cargo build --release && strip target/release/quicksand-guest-agent
+
+# In final stage:
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/
+CMD ["/sbin/init"]
+```
+
+### Build and test
+
+```bash
+uv build
+```
+
+The hatch build hook runs `quicksand_image_tools.build_image()` automatically: Docker build, export filesystem, extract kernel/initrd, create ext4, convert to qcow2.
+
+```python
+import asyncio
+from quicksand import Sandbox
+
+async def main():
+ async with Sandbox(image="mylinux") as sb:
+ print((await sb.execute("cat /etc/os-release")).stdout)
+
+asyncio.run(main())
+```
+
+### Key files
+
+- `docker/Dockerfile` is the VM definition
+- `__init__.py` exports `image` (ImageProvider) and `MylinuxSandbox` (thin wrapper accepting `**kwargs`)
+- `pyproject.toml` registers the `quicksand.images` entry point
+- `hatch_build.py` builds the image during `uv build`
+
+Reference: `packages/quicksand-ubuntu/` for a complete example.
+
+---
+
+## Overlay images
+
+Overlay packages (like `aif-agent-sandbox`) boot a base VM, run setup commands, and save the result. They layer on top of existing base images and can stack on each other.
+
+### Scaffold
+
+```bash
+quicksand dev scaffold overlay my-overlay --base ubuntu
+```
+
+`--base` is required. It specifies which image the overlay builds on. This can be a base image (`ubuntu`, `alpine`) or another overlay (`aif-agent-sandbox`). Stacking overlays is encouraged because each layer only stores its own changes, keeping wheel sizes small.
+
+Creates `my-overlay/` in the current directory. Use `--output-dir` to override. In Claude Code, `/new-overlay-image` wraps this interactively.
+
+### Write the setup function
+
+Edit `hatch_build.py`:
+
+```python
+async def _setup(shell: Shell) -> None:
+ await shell("apt-get update", timeout=120)
+ await shell("apt-get install -y your-packages", timeout=300)
+ await shell("pip install your-python-deps", timeout=300)
+```
+
+`shell()` runs commands inside the VM, streams output, and raises on failure.
+
+### Build and test
+
+```bash
+uv build
+```
+
+The first build boots a real VM, runs `_setup()`, and saves the overlay. Subsequent builds reuse the cached overlay. To force a rebuild, delete the `images/` directory and rebuild.
+
+### Key files
+
+- `hatch_build.py` contains `_setup()` and the build hook
+- `__init__.py` exports `image` (ImageProvider)
+- `pyproject.toml` registers entry points and declares the base image dependency
+
+Reference: `packages/contrib/aif-agent-sandbox/` for a complete example.
+
+---
+
+## Release integration
+
+The release pipeline auto-discovers image packages via the `quicksand.images` entry point. It uses `provider.type = "base"` for base images and `provider.type = "overlay"` for overlays. No manual registration needed.
diff --git a/docs/contributor-guide/02-extending-the-sandbox.md b/docs/contributor-guide/02-extending-the-sandbox.md
new file mode 100644
index 0000000..66377da
--- /dev/null
+++ b/docs/contributor-guide/02-extending-the-sandbox.md
@@ -0,0 +1,50 @@
+# Extending the Sandbox
+
+## Add a Sandbox method
+
+Methods live in mixins in `quicksand_core/sandbox/`. Pick the one that fits your concern:
+
+| File | Owns |
+|------|------|
+| `_execution.py` | `execute()` |
+| `_checkpoints.py` | `checkpoint()`, `revert()` |
+| `_saves.py` | `save()` |
+| `_input.py` | `screenshot()`, `type_text()`, `press_key()`, `mouse_*()` |
+| `_mounts.py` | `mount()`, `unmount()` |
+
+**Example** of adding `read_file()` to `_execution.py`:
+
+```python
+async def read_file(self, guest_path: str) -> str:
+ if not self.is_running:
+ raise RuntimeError("Sandbox is not running")
+ result = await self.execute(f"cat {guest_path}")
+ if result.exit_code != 0:
+ raise FileNotFoundError(f"Guest file not found: {guest_path}: {result.stderr}")
+ return result.stdout
+```
+
+If you need new shared state, add the field to `_SandboxProtocol` (`_protocol.py`) and initialize it in `Sandbox.__init__()` (`_sandbox.py`).
+
+Export from `quicksand_core` and the `quicksand` wrapper if it's public API.
+
+## Add a new OS
+
+1. Add `OS.FREEBSD` to the enum in `host/os_.py`
+2. Create `FreeBSDConfig(BaseOSConfig)` and implement `detect_accelerator()`, `disk_aio`, `supports_microvm`, etc.
+3. Add the detection branch in `OSConfig.__new__()` and `_detect_os()`
+4. If it needs unique QEMU flags, handle them in `build_qemu_command()` (`qemu/platform.py`)
+
+## Add a new architecture
+
+1. Add `Architecture.RISCV64` to the enum in `host/arch.py`
+2. Create `RISCV64Config(BaseArchitectureConfig)` in `qemu/arch.py` and set machine type, device names, console, GPU, CPU model
+3. Add the detection branch in `ArchitectureConfig.__new__()` and `_detect_architecture()`
+4. Build QEMU and image packages for the new architecture
+
+## Add a new QEMU flag
+
+1. If user-configurable, add the kwarg to `Sandbox` (and the underlying `SandboxConfig` in `_types.py`)
+2. Add the flag to `build_qemu_command()` in `qemu/platform.py` (or a `_build_*_args()` helper)
+3. Document in the relevant `docs/under-the-hood/` file
+4. Unit test: verify the flag appears in the generated command. Integration test: verify the feature works.
diff --git a/docs/contributor-guide/03-testing.md b/docs/contributor-guide/03-testing.md
new file mode 100644
index 0000000..79d27df
--- /dev/null
+++ b/docs/contributor-guide/03-testing.md
@@ -0,0 +1,49 @@
+# Testing
+
+## Running tests
+
+```bash
+uv run poe test # Unit tests (no QEMU needed)
+uv run poe test-integration # Integration tests (needs QEMU + images)
+uv run poe ci # Full CI: check + test
+
+# Specific file or test
+uv run pytest tests/unit/test_core_config.py
+uv run pytest tests/unit/test_core_config.py::test_default_config -v
+```
+
+## Writing a unit test
+
+Unit tests go in `tests/unit/`. They don't need QEMU. Mock dependencies as needed.
+
+```python
+def test_my_feature():
+ from quicksand_core import SandboxConfig
+ config = SandboxConfig(image="ubuntu", memory="1G") # SandboxConfig for internal/unit testing
+ assert config.memory == "1G"
+```
+
+## Writing an integration test
+
+Integration tests go in `tests/integration/`. They boot real VMs.
+
+```python
+import pytest
+
+async def test_my_feature(tmp_dir):
+ async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("echo hello")
+ assert result.exit_code == 0
+ assert "hello" in result.stdout
+```
+
+## Markers
+
+| Marker | Use when |
+|--------|----------|
+| `@pytest.mark.integration` | Test needs QEMU — skipped by `poe test` |
+| `@pytest.mark.slow` | Test takes significant time |
+| `@pytest.mark.docker` | Test needs Docker daemon |
+
+Skip conditions (`skip_no_qemu`, `skip_no_docker`, `skip_no_mke2fs`) are in `tests/conftest.py`.
diff --git a/docs/contributor-guide/04-releasing.md b/docs/contributor-guide/04-releasing.md
new file mode 100644
index 0000000..0b162a9
--- /dev/null
+++ b/docs/contributor-guide/04-releasing.md
@@ -0,0 +1,45 @@
+# Releasing
+
+Releases are managed via the `/release` Claude Code skill.
+
+## Flow
+
+1. **Dry run.** Run `uv run poe release-dry-run` to preview what will be built.
+2. **Branch.** Create `release/v{version}` from main.
+3. **Dispatch.** Run `gh workflow run release.yml --ref release/v{version}`.
+4. **Monitor.** CI runs check, build, overlay build, test, and release.
+5. **Post-release.** Verify per-package releases and test install.
+
+## Versioning
+
+| Bump | When |
+|------|------|
+| **Patch** (automatic) | Bug fixes, CI fixes, doc updates, refactors |
+| **Minor** (manual) | New features, new public API, breaking changes, new packages |
+
+Patch versions are set automatically by the previous release's dev bump.
+
+## Per-package releases
+
+Each package gets its own GitHub release (`quicksand-core/v0.7.0`, `quicksand-qemu/v0.4.0`, etc.). Unchanged packages keep their existing releases. Change detection and internal dependency pinning are handled automatically by `quicksand-plan-release`.
+
+## Fixing CI failures
+
+Fix on the release branch, push, re-dispatch:
+
+```bash
+git checkout release/v<VERSION>
+# fix the issue
+git push origin release/v<VERSION>
+gh workflow run release.yml --ref release/v<VERSION>
+```
+
+To reuse builds from a previous run:
+```bash
+gh workflow run release.yml --ref release/v<VERSION> \
+ -f plan="$(uv run quicksand-plan-release --reuse-base-build <RUN_ID> --reuse-overlay-build <RUN_ID>)"
+```
+
+## Changelog
+
+Update `CHANGELOG.md` on the release branch before dispatch. Categories: Added, Changed, Deprecated, Removed, Fixed, Security.
diff --git a/docs/contributor-guide/index.md b/docs/contributor-guide/index.md
new file mode 100644
index 0000000..b42b53e
--- /dev/null
+++ b/docs/contributor-guide/index.md
@@ -0,0 +1,38 @@
+# Contributor Guide
+
+See also: [User Guide](../user-guide/) (Python API) and [Under the Hood](../under-the-hood/) (QEMU flags).
+
+## Requirements
+
+- **Python 3.11+** and **uv** for the workspace and all packages
+- **Docker** is required for building base images (Dockerfiles are compiled into qcow2 VM images)
+- **QEMU** is required for integration tests and building overlay images (overlays boot a real VM). Install the bundled version with `quicksand install qemu`, or use a system QEMU on `PATH`.
+
+Lint, type checking, and unit tests (`poe ci`) work without Docker or QEMU.
+
+## Dev setup
+
+```bash
+git clone https://github.com/microsoft/quicksand
+cd quicksand
+uv sync --all-packages --all-groups --all-extras
+quicksand install qemu ubuntu # needed for integration tests
+uv run poe ci # lint + typecheck + tests
+```
+
+Before committing:
+```bash
+uv run poe fix && uv run poe check
+```
+
+## Common tasks
+
+| Command | What it does |
+|---------|-------------|
+| `uv run poe fix` | Auto-fix lint + formatting |
+| `uv run poe check` | Lint + format check + type check |
+| `uv run poe test` | Unit tests (no QEMU needed) |
+| `uv run poe test-integration` | Integration tests (needs QEMU + images) |
+| `uv run poe test-smb` | SMB server unit tests |
+| `uv run poe ci` | Full CI: check + test |
+
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 0000000..f330d38
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,78 @@
+---
+layout: home
+
+hero:
+ name: Quicksand
+ # text: Full Linux VMs from Python
+ tagline: <span>Launch, control, and snapshot <a href="https://www.qemu.org">QEMU</a> virtual machines through an async Python API. No root, no Docker, no cloud. Just <code>pip install quicksand</code></span>
+ actions:
+ - theme: brand
+ text: Get Started
+ link: /user-guide/01-installation
+ - theme: alt
+ text: Go Under the Hood
+ link: /under-the-hood/
+
+features:
+ - title: ⚡ Run Commands
+ details: Execute shell commands inside a VM and get stdout, stderr, and exit code back.
+ link: /user-guide/03-running-commands
+ - title: 💾 Save & Rollback
+ details: Checkpoint before risky operations and revert on failure. Save progress to disk and resume later.
+ link: /user-guide/05-save-and-rollback
+ - title: 🖥️ Desktop Control
+ details: Take screenshots, type text, click buttons, and move the mouse through a full graphical desktop.
+ link: /user-guide/06-desktop-control
+ - title: 🔒 Network Isolation
+ details: VMs are isolated by default. Opt in to internet access and port forwarding when you need it.
+ link: /user-guide/07-network-and-isolation
+ - title: 📁 File Sharing
+ details: Mount host directories into the VM at boot or on the fly. CIFS and 9p protocols supported.
+ link: /user-guide/04-file-exchange
+ - title: 🌍 Cross-Platform
+ details: Works on macOS, Linux, and Windows with hardware acceleration. No system dependencies.
+ link: /user-guide/08-performance
+---
+
+## Example: Ubuntu Hello, World
+
+Install quicksand with QEMU and an Ubuntu VM image. Everything you need in one line.
+
+```bash
+pip install 'quicksand[qemu,ubuntu]'
+```
+
+Launch a sandbox, install a package, and use it. All inside an isolated VM that boots in ~2 seconds.
+
+```python
+import asyncio
+from quicksand import Sandbox, Mount, NetworkMode
+
+async def main():
+ # Each sandbox is a real Ubuntu VM with its own kernel
+ async with Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.FULL, # Enable internet for apt
+ mounts=[Mount(".", "/mnt/workspace")], # Share your project into the VM
+ ) as sb:
+ # Full apt ecosystem — install anything you'd install on a real machine
+ await sb.execute("apt-get update && apt-get install -y figlet")
+ # Your files are right there inside the VM
+ await sb.execute("ls /mnt/workspace")
+ # Run it just like you would in a terminal
+ result = await sb.execute("figlet Quicksand")
+ print(result.stdout)
+ # VM is gone — nothing left on the host
+
+asyncio.run(main())
+```
+
+```
+ ____ _ _
+| _ \ ___ _ __| |_ __ _| |__ _____ __
+| |_) / _ \| '__| __/ _` | '_ \ / _ \ \/ /
+| __/ (_) | | | || (_| | |_) | (_) > <
+|_| \___/|_| \__\__,_|_.__/ \___/_/\_\
+```
+
+That's it. No Docker, no root, no cloud account. Just a normal user process with hypervisor-level isolation.
diff --git a/docs/packages/aif-agent-sandbox.md b/docs/packages/aif-agent-sandbox.md
new file mode 100644
index 0000000..02e88c0
--- /dev/null
+++ b/docs/packages/aif-agent-sandbox.md
@@ -0,0 +1,50 @@
+# AIF Agent Sandbox
+
+An overlay image package for [quicksand](https://github.com/microsoft/quicksand) that provides a Python 3.12 environment with common AI agent tools pre-installed. Built on top of `quicksand-ubuntu`.
+
+## Installation
+
+```bash
+quicksand install aif-agent-sandbox
+```
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from aif_agent_sandbox import AIFAgentSandbox
+
+async def main():
+ async with AIFAgentSandbox() as sb:
+ result = await sb.execute("python3 --version")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand_core import Sandbox
+
+async with Sandbox(image="aif-agent-sandbox", memory="4G", cpus=4) as sb:
+ result = await sb.execute("pip list")
+```
+
+## What's Included
+
+Built on Ubuntu 24.04, this overlay adds:
+
+- **Python 3.12** virtual environment at `/opt/python` (with `pip`)
+- **uv** fast Python package manager
+- **build-essential** (gcc, make, etc.)
+- **requests** HTTP library
+- **pyyaml** YAML parsing
+- **ddgs** DuckDuckGo Search API
+- **markitdown** Markdown conversion tool
+
+## License
+
+MIT
diff --git a/docs/packages/aif-cua-agent-sandbox.md b/docs/packages/aif-cua-agent-sandbox.md
new file mode 100644
index 0000000..cec1ef0
--- /dev/null
+++ b/docs/packages/aif-cua-agent-sandbox.md
@@ -0,0 +1,52 @@
+# AIF CUA Agent Sandbox
+
+An overlay image package for [quicksand](https://github.com/microsoft/quicksand) that adds browser automation via Playwright and Chromium with a VNC-accessible virtual display. Built on top of `aif-agent-sandbox`.
+
+## Installation
+
+```bash
+quicksand install aif-cua-agent-sandbox
+```
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from aif_cua_agent_sandbox import AifCuaAgentSandbox
+
+async def main():
+ async with AifCuaAgentSandbox() as sb:
+ # Xvfb, x11vnc, and Chromium start automatically via systemd
+ result = await sb.execute("python3 -c 'from playwright.sync_api import sync_playwright; print(\"OK\")'")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand_core import Sandbox
+
+async with Sandbox(image="aif-cua-agent-sandbox", memory="4G", cpus=4) as sb:
+ result = await sb.execute("chromium --version")
+```
+
+## What's Included
+
+Everything from [aif-agent-sandbox](aif-agent-sandbox) (Python 3.12, uv, requests, pyyaml, ddgs, markitdown), plus:
+
+- **Xvfb** virtual framebuffer (display `:0`, 1280x1024x24)
+- **x11vnc** VNC server on port 5901
+- **Playwright** browser automation library
+- **Chromium** browser (installed via Playwright)
+- **noVNC** web client on port 6080
+- **Fonts** (Liberation, Noto Color Emoji)
+
+All services (Xvfb, x11vnc, Chromium, noVNC) are enabled as systemd units and start automatically on boot.
+
+## License
+
+MIT
diff --git a/docs/packages/index.md b/docs/packages/index.md
new file mode 100644
index 0000000..9617dbc
--- /dev/null
+++ b/docs/packages/index.md
@@ -0,0 +1,33 @@
+# Packages
+
+Quicksand is a monorepo with 15 packages organized into four groups.
+
+## Runtime
+
+| Package | What it is |
+|---------|-----------|
+| [quicksand](quicksand.md) | User-facing wrapper — re-exports core + images, CLI |
+| [quicksand-core](quicksand-core.md) | Core VM sandbox implementation |
+| [quicksand-qemu](quicksand-qemu.md) | Bundled QEMU binaries (per-platform) |
+| [quicksand-smb](quicksand-smb.md) | Pure-Python SMB3 server for host-guest mounts |
+
+## Images
+
+| Package | What it is |
+|---------|-----------|
+| [quicksand-ubuntu](quicksand-ubuntu.md) | Ubuntu 24.04 headless (~341 MB) |
+| [quicksand-alpine](quicksand-alpine.md) | Alpine 3.21 headless (~78 MB) |
+| [quicksand-ubuntu-desktop](quicksand-ubuntu-desktop.md) | Ubuntu 24.04 + Xfce4 + Firefox |
+| [quicksand-alpine-desktop](quicksand-alpine-desktop.md) | Alpine 3.21 + Xfce4 + Chromium |
+| [aif-agent-sandbox](aif-agent-sandbox.md) | Ubuntu + Python 3.12, uv, build tools |
+| [aif-cua-agent-sandbox](aif-cua-agent-sandbox.md) | AIF Agent Sandbox + Playwright, Chromium |
+
+## Dev tools
+
+| Package | What it is |
+|---------|-----------|
+| [quicksand-image-tools](quicksand-image-tools.md) | CLI and API for building custom VM images |
+| [quicksand-base-scaffold](quicksand-base-scaffold.md) | Scaffold new base image packages |
+| [quicksand-overlay-scaffold](quicksand-overlay-scaffold.md) | Scaffold new overlay image packages |
+| [quicksand-build-tools](quicksand-build-tools.md) | Shared build utilities for native binary bundling |
+| [quicksand-gh-runners](quicksand-gh-runners.md) | GitHub Actions self-hosted runner management |
diff --git a/docs/packages/quicksand-alpine-desktop.md b/docs/packages/quicksand-alpine-desktop.md
new file mode 100644
index 0000000..df4072a
--- /dev/null
+++ b/docs/packages/quicksand-alpine-desktop.md
@@ -0,0 +1,50 @@
+# Quicksand Alpine Desktop
+
+Minimal Alpine Linux 3.21 desktop VM (Xfce4) for the [quicksand](https://github.com/microsoft/quicksand) agent harness. Lightweight and fast-booting. Ideal when you need GUI automation without the overhead of a full Ubuntu desktop.
+
+## Installation
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+quicksand install alpine-desktop
+```
+
+## Usage
+
+```python
+import asyncio
+from quicksand import Key
+from quicksand_alpine_desktop import AlpineDesktopSandbox
+
+async def main():
+ async with AlpineDesktopSandbox() as sb:
+ await sb.screenshot("desktop.png")
+ await sb.type_text("echo hello world")
+ await sb.press_key(Key.RET)
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## What's Included
+
+- Alpine 3.21 with Xfce4 desktop + LightDM (auto-login)
+- Chromium browser
+- Python 3, bash, curl
+- The quicksand guest agent (pre-installed)
+
+## Default Config
+
+| Setting | Default |
+|---------|---------|
+| Memory | 1G |
+| CPUs | 2 |
+| Display | Enabled (always) |
+| Boot timeout | 60s |
+| Init system | OpenRC |
+| Image size | ~300MB |
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-alpine.md b/docs/packages/quicksand-alpine.md
new file mode 100644
index 0000000..29c7ac4
--- /dev/null
+++ b/docs/packages/quicksand-alpine.md
@@ -0,0 +1,94 @@
+# Quicksand Alpine
+
+This package bundles a pre-built Alpine Linux 3.21 VM image for the [quicksand](https://github.com/microsoft/quicksand) agent harness. No downloads required after installation.
+
+Alpine is lightweight and boots quickly, making it ideal for AI agents that need fast sandbox startup.
+
+## Why Alpine?
+
+Alpine Linux is a lightweight distribution that offers:
+- **Smaller image size**: ~75MB vs ~300MB for Ubuntu
+- **Faster boot time**: Less to load means quicker startup
+- **Minimal attack surface**: Only essential packages included
+- **musl libc**: Smaller, simpler C library
+
+Use Alpine when you need fast, lightweight sandboxes. Use Ubuntu when you need broader package compatibility or glibc-dependent software.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install alpine
+```
+
+This installs `quicksand` with the bundled Alpine image.
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from quicksand import AlpineSandbox
+
+async def main():
+ async with AlpineSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand import AlpineSandbox
+
+async with AlpineSandbox(memory="512M", cpus=2) as sb:
+ result = await sb.execute("uname -a")
+```
+
+Or using `Sandbox` directly:
+
+```python
+from quicksand import Sandbox
+
+async with Sandbox(image="alpine", memory="512M", cpus=2) as sb:
+ result = await sb.execute("uname -a")
+```
+
+## What's Included
+
+The Alpine 3.21 image includes:
+- Python 3
+- Bash shell
+- curl, ca-certificates
+- Networking tools (iproute2, iputils-ping)
+- The quicksand agent (pre-installed)
+
+## Installing Additional Packages
+
+Alpine uses `apk` for package management:
+
+```python
+async with AlpineSandbox() as sb:
+ # Install packages
+ await sb.execute("apk add --no-cache git nodejs npm")
+
+ # Use them
+ result = await sb.execute("node --version")
+ print(result.stdout)
+```
+
+## Package Size
+
+The wheel is ~75MB, much smaller than Ubuntu (~300MB) because Alpine is a minimal distribution. This makes it faster to download and install.
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-base-scaffold.md b/docs/packages/quicksand-base-scaffold.md
new file mode 100644
index 0000000..97da5eb
--- /dev/null
+++ b/docs/packages/quicksand-base-scaffold.md
@@ -0,0 +1,82 @@
+# quicksand-base-scaffold
+
+Scaffold a new base image package for quicksand.
+
+Base image packages define a VM from a Dockerfile. The Dockerfile installs a Linux kernel, init system, networking, and the quicksand guest agent. The build process converts the Docker image into a qcow2 disk + kernel + initramfs that QEMU can boot.
+
+## Usage
+
+```bash
+quicksand-base-scaffold mylinux
+```
+
+This copies `quicksand-ubuntu` into `packages/quicksand-mylinux/`, renames everything, and writes a skeleton Dockerfile.
+
+To copy from Alpine instead:
+
+```bash
+quicksand-base-scaffold mylinux --base alpine
+```
+
+## Output Structure
+
+```
+packages/quicksand-mylinux/
+├── pyproject.toml
+├── hatch_build.py # Builds image during uv build
+├── README.md
+└── quicksand_mylinux/
+ ├── __init__.py # Python API + entry points
+ ├── images/ # Built images (populated during uv build)
+ └── docker/
+ ├── Dockerfile # Edit this
+ ├── agent/ # Copied automatically at build time
+ └── ... # Init configs
+```
+
+## Next Steps
+
+1. Set `DISTRO_VERSION` in `quicksand_mylinux/__init__.py`
+
+2. Edit `quicksand_mylinux/docker/Dockerfile`. Your image must include:
+ - Linux kernel with initramfs (for virtio drivers)
+ - Init system (systemd or OpenRC)
+ - 9p kernel modules (`9p`, `9pnet`, `9pnet_virtio`)
+ - `quicksand` user with passwordless sudo
+ - DHCP networking
+ - The Rust guest agent (compiled via multi-stage Docker build)
+ - `CMD ["/sbin/init"]`
+
+3. Build:
+
+```bash
+uv sync
+uv build --package quicksand-mylinux
+```
+
+4. Test:
+
+```bash
+quicksand run mylinux
+```
+
+## Dockerfile Example
+
+See `packages/quicksand-ubuntu/quicksand_ubuntu/docker/Dockerfile` for a complete Ubuntu example, or `packages/quicksand-alpine/quicksand_alpine/docker/Dockerfile` for Alpine.
+
+The key pattern is a multi-stage build:
+
+```dockerfile
+# Stage 1: Compile Rust agent
+FROM rust:bookworm AS agent-builder
+WORKDIR /build
+COPY agent/Cargo.toml agent/Cargo.lock* ./
+COPY agent/src ./src
+RUN cargo build --release && strip /build/target/release/quicksand-guest-agent
+
+# Stage 2: Your image
+FROM your-base:version
+RUN install-kernel && install-init && configure-networking
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/
+CMD ["/sbin/init"]
+```
diff --git a/docs/packages/quicksand-build-tools.md b/docs/packages/quicksand-build-tools.md
new file mode 100644
index 0000000..f2ad151
--- /dev/null
+++ b/docs/packages/quicksand-build-tools.md
@@ -0,0 +1,13 @@
+# Quicksand Build Tools
+
+Shared build utilities for bundling native binaries into quicksand wheels.
+
+Used by `quicksand-qemu` build hooks. Provides `BinaryBundler` with platform-specific logic for copying shared libraries, rewriting paths (`install_name_tool` on macOS, `patchelf` on Linux), and codesigning.
+
+## Usage
+
+This is a build-time dependency and not intended for direct use. It's consumed by `hatch_build.py` hooks in packages that bundle native binaries.
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-core.md b/docs/packages/quicksand-core.md
new file mode 100644
index 0000000..1370472
--- /dev/null
+++ b/docs/packages/quicksand-core.md
@@ -0,0 +1,104 @@
+# Quicksand Core
+
+This package provides the core implementation for the [quicksand](https://github.com/microsoft/quicksand) VM harness.
+
+It includes the abstractions for running VMs that AI agents can interact with, including command execution, file operations, and state checkpointing. Most users should install `quicksand` instead, which includes pre-built images.
+
+## Installation
+
+For most users, install via the main quicksand CLI installer:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+quicksand install ubuntu
+```
+
+For core-only (no bundled images):
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand-core"
+```
+
+## Core Exports
+
+This package exports the core building blocks:
+
+```python
+from quicksand_core import (
+ # Main classes
+ Sandbox,
+ Mount,
+ ExecuteResult,
+ # Save support
+ SaveManifest,
+ # Image resolution
+ ResolvedImage,
+ # Runtime management
+ get_runtime,
+ RuntimeInfo,
+ is_runtime_available,
+ # Accelerator detection
+ get_accelerator,
+ detect_accelerator,
+ AcceleratorStatus,
+ Accelerator,
+ # Platform configuration
+ get_platform_config,
+ PlatformConfig,
+ # Architecture/OS types
+ Architecture,
+ MachineType,
+ OS,
+)
+```
+
+## Usage with Custom Image
+
+```python
+import asyncio
+from quicksand_core import Sandbox
+
+async def main():
+ async with Sandbox(image="your-image-name", memory="1G", cpus=2) as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## Features
+
+- **Real VM isolation**: Hypervisor-level isolation (KVM, HVF, WHPX)
+- **Cross-platform**: Linux, macOS, Windows
+- **Platform abstraction**: Automatic detection of accelerators and machine types
+- **Save and load**: Save VM disk state to a directory and load it on any machine
+- **File sharing**: CIFS mounts via `quicksand-smb` (pure-Python SMB3 server, invoked as a subprocess via QEMU guestfwd)
+- **Performance optimizations**:
+ - microvm machine type (~4x faster boot on Linux x86_64 + KVM)
+ - io_uring disk AIO (~50% lower latency on Linux)
+ - IOThreads for better concurrent disk I/O (all platforms)
+
+## For Most Users
+
+Install `quicksand` with a bundled image for zero-configuration usage:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+quicksand install ubuntu
+```
+
+```python
+import asyncio
+from quicksand import UbuntuSandbox
+
+async def main():
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("ls -la /")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-gh-runners.md b/docs/packages/quicksand-gh-runners.md
new file mode 100644
index 0000000..e28606a
--- /dev/null
+++ b/docs/packages/quicksand-gh-runners.md
@@ -0,0 +1,9 @@
+# Quicksand GH Runners
+
+CLI to manage persistent self-hosted GitHub Actions runner VMs on Azure.
+
+Used internally to provision and manage the self-hosted runners that build and test quicksand packages in CI.
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-image-tools.md b/docs/packages/quicksand-image-tools.md
new file mode 100644
index 0000000..b644ff2
--- /dev/null
+++ b/docs/packages/quicksand-image-tools.md
@@ -0,0 +1,125 @@
+# Quicksand Image Tools
+
+This package provides development tools for building custom VM images for the [quicksand](https://github.com/microsoft/quicksand) agent harness.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install dev
+```
+
+This installs quicksand with the Ubuntu image and dev tools for building custom images.
+
+## CLI Usage
+
+The recommended way to build custom images:
+
+```bash
+# Initialize a build directory (creates Dockerfile, builds base image if needed)
+quicksand-image-tools init ./my-image ubuntu # or: alpine
+
+# Customize the generated Dockerfile, then build the VM image
+quicksand-image-tools build-image ./my-image/Dockerfile -o my-image.qcow2
+```
+
+### Example Dockerfile
+
+After running `quicksand-image-tools init ./my-image ubuntu`, a Dockerfile is created with the versioned base image. Add your customizations:
+
+```dockerfile
+FROM quicksand/ubuntu-base:24.04.0
+
+# Add your customizations here
+RUN apt-get update && apt-get install -y nodejs && rm -rf /var/lib/apt/lists/*
+```
+
+The base images include the kernel, agent, and init configuration. You just add your packages.
+
+## Python API
+
+Build a VM image programmatically:
+
+```python
+import asyncio
+from quicksand_image_tools import build_image
+from quicksand import Sandbox, SandboxConfig
+
+async def main():
+ # Build from a Dockerfile path
+ image_path = build_image("./Dockerfile")
+
+ # Use the custom image
+ async with Sandbox(SandboxConfig(image_path=str(image_path))) as sb:
+ result = await sb.execute("node --version")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## Dockerfile Requirements
+
+When building FROM a base image (`quicksand/ubuntu-base` or `quicksand/alpine-base`), you just add your packages - the base handles everything else.
+
+For scratch Dockerfiles, you must:
+
+1. **Install a kernel**: Ubuntu `linux-image-virtual` or Alpine `linux-virt`
+2. **Build the Rust agent** via multi-stage Docker build
+3. **Configure a systemd service or OpenRC script** to run the agent on boot
+
+See the `examples/custom_image.py` for a complete working example.
+
+## CLI Reference
+
+### `quicksand-image-tools init [directory] [ubuntu|alpine]`
+
+Initialize a directory for building custom images.
+
+- If no Dockerfile exists in the directory, you must specify a base image type (`ubuntu` or `alpine`)
+- Automatically builds the base Docker image if it doesn't exist
+- Creates a Dockerfile with the appropriate `FROM` statement
+
+### `quicksand-image-tools build-base [ubuntu|alpine|all]`
+
+Build base Docker images locally. Creates versioned images (e.g., `quicksand/ubuntu-base:24.04.0`) and tags them as `latest`. The version matches the installed `quicksand-ubuntu` or `quicksand-alpine` package version.
+
+### `quicksand-image-tools build-image <dockerfile> [-o output] [--cache-dir dir]`
+
+Build a VM image from a Dockerfile.
+
+## Python API Reference
+
+### `build_image(dockerfile, output_path=None, cache_dir=None)`
+
+Build a VM image from a Dockerfile.
+
+- `dockerfile`: Path to a Dockerfile
+- `output_path`: Where to save the qcow2 image (default: cached by hash)
+- `cache_dir`: Cache directory (default: `~/.cache/quicksand/images/`)
+
+Returns the `Path` to the built qcow2 image.
+
+### `get_agent_source_dir()`
+
+Returns the `Path` to the Rust agent source directory (`quicksand-guest-agent/`). This is used by image packages to set up symlinks for Docker builds.
+
+## How It Works
+
+1. Builds a Docker image from your Dockerfile
+2. Creates a container and exports its filesystem
+3. Extracts kernel and initrd from `/boot`
+4. Converts the filesystem to a bootable qcow2 VM image
+
+## Requirements
+
+- Docker must be installed and running
+- QEMU tools (bundled with quicksand-core, or install separately)
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-overlay-scaffold.md b/docs/packages/quicksand-overlay-scaffold.md
new file mode 100644
index 0000000..54dd748
--- /dev/null
+++ b/docs/packages/quicksand-overlay-scaffold.md
@@ -0,0 +1,58 @@
+# quicksand-overlay-scaffold
+
+Scaffold a new overlay image package for quicksand.
+
+Overlay packages boot a base VM (default: Ubuntu), run setup commands to install software, and save the result as a compressed overlay. The overlay is bundled into a wheel so users can `quicksand install` and `quicksand run` it without rebuilding.
+
+## Usage
+
+```bash
+quicksand-overlay-scaffold my-agent-sandbox
+```
+
+This creates a `my-agent-sandbox/` directory with:
+
+```
+my-agent-sandbox/
+├── pyproject.toml # Package metadata and entry points
+├── hatch_build.py # Edit _setup() with your install steps
+├── README.md
+└── my_agent_sandbox/
+ ├── __init__.py # ImageProvider entry point
+ ├── sandbox.py # Optional Sandbox subclass
+ └── images/ # Built overlay (populated during uv build)
+```
+
+## Next Steps
+
+1. Edit `hatch_build.py` and add your install commands to `_setup()`:
+
+```python
+async def _setup(shell: Shell) -> None:
+ await shell("apt-get update", timeout=120)
+ await shell("apt-get install -y your-packages", timeout=300)
+ await shell("pip install your-python-deps", timeout=300)
+```
+
+2. Build the package (boots a VM, runs setup, saves overlay):
+
+```bash
+uv build --package my-agent-sandbox
+```
+
+3. Test it:
+
+```bash
+quicksand run my-agent-sandbox
+```
+
+## How It Works
+
+During `uv build`, the `hatch_build.py` hook:
+
+1. Boots an Ubuntu VM with 4G memory, 4 CPUs, full network, 10G disk
+2. Runs your `_setup(shell)` function inside the VM
+3. Saves the VM state as a compressed qcow2 overlay
+4. Packages the overlay into a platform-specific wheel
+
+Subsequent builds skip the VM step if `images/manifest.json` already exists. Delete the `images/` directory to force a rebuild.
\ No newline at end of file
diff --git a/docs/packages/quicksand-qemu.md b/docs/packages/quicksand-qemu.md
new file mode 100644
index 0000000..0caed68
--- /dev/null
+++ b/docs/packages/quicksand-qemu.md
@@ -0,0 +1,45 @@
+# Quicksand QEMU
+
+This package bundles QEMU binaries for the [quicksand](https://github.com/microsoft/quicksand) VM harness.
+
+## Installation
+
+Install as part of quicksand:
+
+```bash
+pip install quicksand[qemu]
+```
+
+Or standalone:
+
+```bash
+pip install quicksand-qemu
+```
+
+## What's Included
+
+Platform-specific QEMU binaries:
+- `qemu-system-x86_64` or `qemu-system-aarch64` (depending on architecture)
+- `qemu-img` for disk image manipulation
+- Required BIOS/firmware files
+- Bundled shared libraries (no system dependencies)
+
+## Using System QEMU Instead
+
+If you prefer to use your system's QEMU installation, just install quicksand without the `[qemu]` extra:
+
+```bash
+pip install quicksand[ubuntu]
+```
+
+Quicksand will automatically detect QEMU in your PATH.
+
+## Package Size
+
+The wheel is ~80-150MB because it includes QEMU and all dependencies. This ensures quicksand works out of the box without system configuration.
+
+## License
+
+MIT (quicksand-qemu wrapper)
+
+QEMU binaries are licensed under GPL v2. See the bundled `licenses/` directory for full license texts.
diff --git a/docs/packages/quicksand-smb.md b/docs/packages/quicksand-smb.md
new file mode 100644
index 0000000..59aa9b7
--- /dev/null
+++ b/docs/packages/quicksand-smb.md
@@ -0,0 +1,19 @@
+# Quicksand SMB
+
+Pure-Python SMB3 server for [quicksand](https://github.com/microsoft/quicksand) host-guest directory mounts. Zero dependencies.
+
+Runs in inetd mode (stdin/stdout). QEMU spawns a new process per guest connection via `guestfwd`. No TCP port is opened on the host.
+
+## Usage
+
+Not intended to be used directly. `quicksand-core` invokes it as a subprocess:
+
+```
+python -m quicksand_smb --config /path/to/shares.json
+```
+
+The share orchestration (add/remove shares, lifecycle) is managed by `quicksand-core`'s `SMBServer` ABC in `quicksand_core/host/smb.py`.
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-ubuntu-desktop.md b/docs/packages/quicksand-ubuntu-desktop.md
new file mode 100644
index 0000000..5ab6a4a
--- /dev/null
+++ b/docs/packages/quicksand-ubuntu-desktop.md
@@ -0,0 +1,92 @@
+# Quicksand Ubuntu Desktop
+
+Pre-built Ubuntu 24.04 Desktop VM image with Xfce4 for the [quicksand](https://github.com/microsoft/quicksand) agent harness. Gives your agent a full graphical Linux desktop with keyboard, mouse, and screenshot control.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install ubuntu-desktop
+quicksand images install ubuntu-desktop
+```
+
+The image (~7.3GB) is downloaded and cached at `~/.quicksand/images/` on first install.
+
+## Usage
+
+```python
+import asyncio
+from quicksand import Key
+from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+
+async def main():
+ async with UbuntuDesktopSandbox() as sb:
+ # Take a screenshot
+ await sb.screenshot("desktop.png")
+
+ # Type text and press keys
+ await sb.type_text("echo hello world")
+ await sb.press_key(Key.RET)
+
+ # Mouse control (absolute coordinates 0-32767)
+ await sb.mouse_move(16383, 16383)
+ await sb.mouse_click()
+
+ # execute() still works alongside GUI input
+ result = await sb.execute("uname -a")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+
+async with UbuntuDesktopSandbox(memory="4G", cpus=4) as sb:
+ await sb.screenshot("desktop.png")
+```
+
+## What's Included
+
+- Ubuntu 24.04 with Xfce4 desktop + LightDM (auto-login, no password prompt)
+- Firefox ESR browser
+- Full apt/deb ecosystem
+- Python 3, bash, curl, ca-certificates
+- The quicksand guest agent (pre-installed)
+- Software rendering via Mesa (`LIBGL_ALWAYS_SOFTWARE=1`)
+
+## Default Config
+
+| Setting | Default |
+|---------|---------|
+| Memory | 1G |
+| CPUs | 2 |
+| Display | Enabled (always) |
+| Boot timeout | 60s |
+| Init system | systemd |
+
+## Desktop API
+
+All methods are async:
+
+- `await screenshot(path)` saves the guest display as a PNG
+- `await type_text(text)` types a string via keyboard events
+- `await press_key(*keys)` presses a key combo, e.g. `press_key(Key.CTRL, Key.C)`
+- `await mouse_move(x, y)` moves the mouse to an absolute position (0-32767 range)
+- `await mouse_click(button, double=False)` clicks `"left"`, `"right"`, `"middle"`, `"wheel-up"`, or `"wheel-down"`
+- `await query_display_size()` returns the display resolution as `(width, height)`
+- `await execute(cmd)` runs a shell command (same as headless sandboxes)
+- `vnc_port` is the host-side VNC port for connecting a viewer
+
+All standard sandbox features (mounts, save/load, network config) work with desktop sandboxes too.
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand-ubuntu.md b/docs/packages/quicksand-ubuntu.md
new file mode 100644
index 0000000..461e6cd
--- /dev/null
+++ b/docs/packages/quicksand-ubuntu.md
@@ -0,0 +1,69 @@
+# Quicksand Ubuntu
+
+This package bundles a pre-built Ubuntu 24.04 VM image for the [quicksand](https://github.com/microsoft/quicksand) agent harness. No downloads required after installation.
+
+Ubuntu is ideal for AI agents that need a full Linux environment with the apt package manager and broad software compatibility.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install ubuntu
+```
+
+This installs `quicksand` with the bundled Ubuntu 24.04 image.
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from quicksand import UbuntuSandbox
+
+async def main():
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand import UbuntuSandbox
+
+async with UbuntuSandbox(memory="2G", cpus=4) as sb:
+ result = await sb.execute("uname -a")
+```
+
+Or using `Sandbox` directly:
+
+```python
+from quicksand import Sandbox
+
+async with Sandbox(image="ubuntu", memory="2G", cpus=4) as sb:
+ result = await sb.execute("uname -a")
+```
+
+## What's Included
+
+The Ubuntu 24.04 image includes:
+- Python 3
+- Bash, curl, ca-certificates
+- Networking tools
+- The quicksand agent (pre-installed and configured)
+
+## Package Size
+
+The wheel is ~300MB because it includes the full VM image. This is intentional - it eliminates runtime downloads and ensures reproducible environments.
+
+## License
+
+MIT
diff --git a/docs/packages/quicksand.md b/docs/packages/quicksand.md
new file mode 100644
index 0000000..89209c6
--- /dev/null
+++ b/docs/packages/quicksand.md
@@ -0,0 +1,108 @@
+# Quicksand
+
+Quicksand is a VM harness for AI agents that works on macOS, Linux, and Windows.
+
+## Quick Start
+
+**1. Install quicksand CLI**
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+**2. Install a sandbox**
+
+```bash
+quicksand install ubuntu # Ubuntu 24.04 (~300MB)
+quicksand install alpine # Alpine 3.21 (~75MB, faster boot)
+```
+
+**3. Run the sandbox in python**
+
+```python
+import asyncio
+from quicksand import UbuntuSandbox
+
+async def main():
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("echo 'Hello from the sandbox!'")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+That's it. Docker? Don't need it. WSL2? Nope. Batteries? Included.
+
+## Usage
+
+```python
+import asyncio
+from quicksand import Sandbox, Mount, NetworkMode
+
+async def main():
+ async with Sandbox(
+ image="ubuntu",
+ mounts=[Mount("./workspace", "/mnt/workspace")],
+ network_mode=NetworkMode.FULL, # Full internet access
+ ) as sb:
+ await sb.execute("pip install requests")
+ await sb.execute("python /mnt/workspace/script.py")
+ print((await sb.execute("cat /tmp/output.txt")).stdout)
+ await sb.save("./my-save") # Save disk state, VM keeps running
+
+asyncio.run(main())
+```
+
+For implementation details, see [Under the Hood](/under-the-hood/).
+
+## How It Works
+
+```mermaid
+graph LR
+ subgraph Host["Host"]
+ HostFiles["Host Files"]
+ subgraph Process["Python Process"]
+ Code["Your Code"]
+ subgraph SB["quicksand.Sandbox"]
+ TCP["TCP Client"]
+ FileSync["FileSync (SMB/CIFS)"]
+ end
+ end
+ subgraph QEMU["QEMU Process (bundled)"]
+ subgraph Accel["KVM / HVF / WHPX (host)"]
+ subgraph VM["Linux VM (bundled)"]
+ Agent["quicksand-guest-agent"]
+ Mount["/mnt/data"]
+ end
+ end
+ end
+ end
+
+ Code <-->|".execute"| SB
+ SB -->|launches| QEMU
+ TCP <-->|commands| Agent
+ HostFiles <--> FileSync
+ FileSync <-.->|sync| Mount
+```
+
+Each sandbox runs in a real virtual machine with hypervisor-level isolation:
+
+| Platform | Accelerator | Machine | File Sharing | Performance |
+|----------|-------------|---------|--------------|-------------|
+| Linux x86_64 | KVM | microvm | SMB/CIFS | io_uring + IOThreads |
+| Linux ARM64 | KVM | virt | SMB/CIFS | io_uring + IOThreads |
+| macOS | HVF | q35/virt | SMB/CIFS | IOThreads |
+| Windows | WHPX | q35 | SMB/CIFS | IOThreads |
+
+Key components:
+- **Bundled QEMU**: No system installation required
+- **Guest agent**: Lightweight TCP server for command execution
+- **Disposable overlays**: Base image unchanged, writes go to temp overlay
+- **SMB/CIFS mounts**: Mount host directories into the VM
+- **Platform optimizations**: microvm (~4x faster boot), io_uring (~50% lower disk latency), IOThreads
+
+## Requirements
+
+- Python 3.11+
+- No system dependencies (QEMU is bundled)
+- For custom images: Docker
diff --git a/docs/reference/changelog.md b/docs/reference/changelog.md
new file mode 100644
index 0000000..afb46c3
--- /dev/null
+++ b/docs/reference/changelog.md
@@ -0,0 +1,419 @@
+# Changelog
+
+All notable changes to the quicksand project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/).
+
+## [v0.9.4] - 2026-04-01
+
+### Changed
+- **aif-cua-agent-sandbox:** Reduced overlay image size from ~604 MB to ~445 MB by removing unused Playwright headless shell, Vulkan GPU drivers, and system Node.js
+
+### Fixed
+- **quicksand-core:** Virtio-serial agent client now keeps connection open across auth retries. Disconnecting caused QEMU to stop accepting new chardev connections
+- **quicksand-core:** Pin httpx<1.0 to prevent breaking API change
+- **quicksand-core:** Fix `MountSpec` → `Mount` in README exports
+- ARM64 image wheels built on macOS are now retagged for Linux via uvr post_build hook
+- **quicksand-alpine, quicksand-ubuntu:** Restore editable install guard in build hooks
+- **quicksand-alpine-desktop, quicksand-ubuntu-desktop:** Break up large package install commands to avoid build timeouts
+
+## [v0.9.3] - 2026-03-30
+
+### Added
+- **aif-cua-agent-sandbox:** noVNC web client (port 6080), websockify, socat, and rsync in the overlay image
+
+### Fixed
+- `quicksand run -p HOST:GUEST` port forward parsing now works correctly
+
+## [v0.9.2] - 2026-03-29
+
+### Added
+- `quicksand clean` CLI command to remove local `.quicksand/` and optionally global `~/.quicksand/` data directories
+
+## [v0.9.0] - 2026-03-26
+
+### Added
+- Virtio-serial guest agent transport with 25x boot speedup (Alpine p50: 11.5s → 0.45s)
+- `Sandbox.qemu_command` property to inspect the QEMU command line
+- `Sandbox.boot_timing` property with phase-level profiling (kernel, init, agent breakdown)
+- `BootTiming` dataclass with `__str__` for human-readable boot phase display
+- `quicksand benchmark` CLI command with percentile stats, progress bar, and `--json` output
+- `quicksand uninstall` CLI command to remove installed extras
+- `-v`/`--mount` option on benchmark command for measuring boot with mounts
+
+### Changed
+- Guest images now use static IP (10.0.2.15/24) instead of DHCP. This eliminates ~8s dhcpcd overhead
+- Alpine: enabled `rc_parallel="YES"` for parallel OpenRC service startup
+- Alpine: guest agent moved to `boot` runlevel (from `default`)
+- Ubuntu: guest agent moved to `After=sysinit.target` (from `After=basic.target`)
+- Rust guest agent supports dual transport: virtio-serial first, HTTP fallback
+
+## [v0.7.1] - 2026-03-24
+
+### Changed
+- `quicksand-alpine-desktop` and `quicksand-ubuntu-desktop` converted from standalone base images to overlay images built on top of their respective base packages
+- Desktop image wheels are significantly smaller (Alpine: 359MB → 286MB, Ubuntu: 575MB → 254MB) since they only contain the overlay delta
+- Desktop packages now depend on `quicksand-alpine` / `quicksand-ubuntu` respectively
+- Docker is no longer required to build desktop image packages
+
+### Removed
+- Dockerfiles for desktop image packages (build now uses overlay mechanism)
+
+## [v0.7.0] - 2026-03-24
+
+### Changed
+- **Breaking:** `ResolvedImage.base` and `ResolvedImage.overlays` replaced with unified `chain: list[Path]`. `chain[0]` is the root base qcow2, and `chain[1:]` are overlay layers in bottom-to-top order
+- **Breaking:** Save format bumped to v6. Only session-local overlays are stored. Installed package overlays are resolved by name at load time
+- `ImageProvider` protocol now requires an `images_dir: Path` attribute
+- `qemu-img convert -c` preserves backing file references (`-B`) instead of flattening the full chain
+
+### Added
+- `aif-cua-agent-sandbox` overlay package (first release)
+- `_verify_overlay_from_package()` validates that non-session overlays belong to installed packages at save time
+
+## [v0.6.1] - 2026-03-24
+
+### Added
+- `SandboxConfig.arch` parameter for cross-architecture VM builds via TCG emulation
+- `quicksand run --arch` flag for cross-arch boot from the CLI
+- `quicksand install --arch` flag to download cross-platform wheels
+- `quicksand run IMAGE` now takes image as a required positional argument (was `-b/--base`)
+- Overlay build phase in release pipeline (`build-overlay` job, runs after base images)
+- `--reuse-base-build` and `--reuse-overlay-build` flags for independent build reuse
+- `quicksand-base-scaffold` package for scaffolding new base image packages
+- `quicksand-overlay-scaffold --base` flag to choose which base image to overlay on
+
+### Changed
+- Release pipeline `build` job renamed to `build-base` for clarity
+- `quicksand install` removed legacy save-download path. All names are package installs
+- Scaffold packages output to fixed directories (`packages/` for base, `packages/contrib/` for overlay)
+- Workflow conditions use `fromJSON` null checks instead of `contains` string matching
+
+### Fixed
+- Release artifacts from multiple runs now merge correctly (tri-source downloads)
+- KVM setup is best-effort in overlay builds (falls back to TCG gracefully)
+- `_to_title` no longer uppercases short words. This avoids `SandboxSandbox` in scaffold output
+
+## [v0.6.0] - 2026-03-23
+
+### Changed
+- **Breaking:** `SandboxConfig.image` is now `str` only (was `str | Path | ImagePaths`)
+- **Breaking:** `save()` returns `SaveManifest` instead of `SaveInfo`
+- **Breaking:** Removed `load` parameter from `Sandbox.__init__()`. Use `SandboxConfig(image="save-name")` instead
+- **Breaking:** Save format bumped to v5 (directory-based, no tar support)
+- **Breaking:** Removed legacy `quicksand.bases` entry point group. Only `quicksand.images` is supported
+- `ImageProvider` is now a `typing.Protocol` instead of an abstract class
+- Sandbox internal state uses flat fields instead of wrapper dataclasses
+- `build_qemu_command()` takes individual path arguments instead of `ImagePaths`/`DiskPaths`
+
+### Removed
+- `SavedConfig`, `SaveInfo`, `ImagePaths`, `DiskPaths`, `_BootState`, `_VMConfig`, `SandboxSnapshot` types
+- `_WorkspaceOptions`, `_QuicksandGuestAgentState`, `_QMPState`, `_VNCState` state wrappers
+- `SavedConfig.from_sandbox_config()` and `SavedConfig.resolve()` methods
+- `get_image_path()` and `get_image_artifacts()` legacy functions from image packages
+- `sandbox/_state.py` module
+- Legacy tar-based save format support (v3/v4 manifests)
+
+### Fixed
+- `SandboxConfig` is now truly frozen and never mutated after construction
+- Config mutation bug where `config.accel` was overwritten during cross-arch save loading
+- Hardcoded `quicksand_version: "0.1.0"` in save manifests
+
+## [v0.5.0] - 2026-03-20
+
+### Changed
+- **Breaking**: Entire Sandbox public API is now async/await
+ - `Sandbox` uses `async with` (`__aenter__`/`__aexit__`) and `await start()`/`stop()`
+ - All mixins are async: `execute`, `save`, `checkpoint`, `revert`, `mount`, `unmount`, `type_text`, `press_key`, `mouse_move`, `mouse_click`, `screenshot`, etc.
+ - `QMPClient` uses asyncio streams instead of blocking sockets
+ - `QuicksandGuestAgentClient` uses `httpx.AsyncClient`
+ - Examples updated with `asyncio.run()` wrappers
+ - Tests updated to pytest-asyncio + AsyncMock
+
+## [v0.3.3] - 2026-03-18
+
+### Added
+- `python -m quicksand` entrypoint (equivalent to `quicksand` CLI)
+
+### Fixed
+- Bumped GitHub Actions to latest versions (Node.js 24 support)
+
+## [v0.3.2] - 2026-03-17
+
+### Fixed
+- `quicksand install` failing to resolve third-party dependencies (httpx) due to `--no-index` flag blocking PyPI access
+
+## [v0.3.0] - 2026-03-17
+
+### Added
+- CIFS hot-mount API: `sb.mount()` / `sb.unmount()` with `MountHandle`
+- `quicksand-smb` package: pure-Python SMB3 server spawned via QEMU guestfwd (no TCP port, no Samba, zero dependencies)
+- `NetworkMode.MOUNTS_ONLY` for mounts without internet access via guestfwd tunnels
+- `NetworkMode` enum now has three modes: `NONE`, `MOUNTS_ONLY` (default), `FULL`
+- QEMU block layer flush before snapshot pivot to prevent data loss on large writes
+- Path traversal protection in SMB server (symlink + `..` escape checks)
+- `examples/mounts.py` demonstrating boot-time, dynamic, and readonly mount patterns
+
+### Changed
+- Replaced `quicksand-smbd` (bundled Samba binary, 50MB+) with `quicksand-smb` (pure Python, ~2K LOC)
+- Default network mode is now `MOUNTS_ONLY` (was `HOST_ONLY`)
+- Mounts use CIFS over guestfwd in all network modes (no TCP port opened on host)
+
+### Removed
+- `quicksand-smbd` package (replaced by `quicksand-smb`)
+- 9p as default mount protocol (replaced by CIFS). 9p remains available via `type="9p"`
+
+### Fixed
+- macOS SIP `PermissionError` when copying binaries
+- `NetworkMode` enum definition to properly support three modes
+
+## [v0.2.3] - 2026-03-12
+
+### Added
+- `quicksand-ubuntu-desktop` package with full Ubuntu 24.04 desktop sandbox support
+- `quicksand-alpine-desktop` package
+- `Key` enum for keyboard input
+- Image install CLI (`quicksand images install <name>`)
+- `query_display_size()` API for display introspection
+- Double-click support in input API
+- Overlay chain support in core snapshot/checkpoint system
+
+### Changed
+- Refactored core to use `NetworkMode` enum, overlay chains, and display/input subsystem
+- Updated Alpine and Ubuntu base packages for `NetworkMode` API
+- Renamed `quicksand-agent` to `quicksand-guest-agent`
+- Updated guest agent and dev tools for new core API
+- Improved desktop images with browser support, software cursor, and DNS fixes
+
+### Fixed
+- Checkpoint integration tests for overlay chain format
+- Typecheck issues with `overlay_chain` in `SandboxSnapshot`
+- CI version bump to push from latest main instead of tag HEAD
+
+## [v0.2.2] - 2026-02-27
+
+### Changed
+- Renamed `quicksand-agent` to `quicksand-guest-agent` and added package init scaffold
+
+### Fixed
+- Integration test compatibility with renamed package
+
+## [v0.2.1] - 2026-02-26
+
+### Changed
+- Refactored core internals
+- `install` command now supports multi-argument package installation
+
+## [v0.2.0] - 2026-02-26
+
+### Added
+- Streaming `execute()` API for real-time command output
+- README install instructions using `quicksand` CLI installer
+
+### Changed
+- Refactored core internals and removed `write_file`/`read_file` in favor of `execute()`
+- Updated integration tests to use `execute()` API
+
+### Fixed
+- Missing `readline` import error on Windows
+- Binary file tests to use POSIX-compatible tools (`od` instead of `xxd`)
+
+## [v0.1.27] - 2026-02-24
+
+### Fixed
+- Mount hangs when `restrict_network=True`
+
+## [v0.1.26] - 2026-02-24
+
+### Fixed
+- DNS resolution in Ubuntu sandbox (enabled `systemd-resolved`)
+- Reverted DNS changes that broke mount tests
+
+## [v0.1.25] - 2026-02-24
+
+### Changed
+- QEMU bundling is now optional
+
+## [v0.1.24] - 2026-02-24
+
+### Added
+- CLI to `quicksand` package
+- `quicksand-qemu` CI build jobs
+
+## [v0.1.23] - 2026-02-23
+
+### Added
+- Rust guest agent, replacing the Python agent for smaller images and faster startup
+- `curl` added to Alpine image for network tests
+
+## [v0.1.22] - 2026-02-20
+
+### Fixed
+- microvm + Ubuntu compatibility: match `eth*` interfaces in `systemd-networkd`
+
+## [v0.1.21] - 2026-02-20
+
+### Changed
+- Disabled microvm temporarily due to Ubuntu compatibility issues
+
+## [v0.1.20] - 2026-02-20
+
+### Fixed
+- microvm networking by using explicit `-netdev`/`-device` QEMU args
+
+## [v0.1.19] - 2026-02-20
+
+### Added
+- GPL license files for QEMU binary distribution (Section 3(c) compliance)
+- QEMU version tracking
+
+### Removed
+- Redundant `bundle_qemu.py` script (inlined into `hatch_build.py`)
+
+## [v0.1.18] - 2026-02-20
+
+### Added
+- microvm support: bundle `bios-microvm.bin` for ~4x faster boot on Linux x86_64
+- QEMU performance optimizations
+
+### Fixed
+- microvm `bios-microvm.bin` existence check before enabling
+- `_build_mount_args` signature change in tests
+
+## [v0.1.16] - 2026-02-19
+
+### Added
+- Serial console output for boot debugging
+
+### Changed
+- Renamed `install.py` to `installer.py`
+
+### Fixed
+- Docker build: remove `/etc/resolv.conf` before symlinking
+- Ubuntu DNS by enabling `systemd-resolved`
+- Installer tests
+
+## [v0.1.15] - 2026-02-17
+
+### Added
+- SMB-based mounting for Windows hosts, replacing `FileSyncAgent`
+
+### Fixed
+- Windows SMB mount (standard port 445, explicit CIFS options)
+- Build hooks importing from package being built
+- Checkpoint tests with mounts on Windows
+
+## [v0.1.14] - 2026-02-15
+
+### Changed
+- Use pyproject entry points for optional package discovery
+
+## [v0.1.13] - 2026-02-14
+
+### Changed
+- Refactored host module naming. `Platform` enum renamed to `OS` and merged runtime module
+
+## [v0.1.12] - 2026-02-12
+
+### Added
+- `ARCHITECTURE.md` documenting codebase structure and QEMU glossary
+- Comprehensive tests for `quicksand-image-tools` CLI
+- Per-package tags with bundled releases
+- Python-based wheel merge script (`merge_wheels.py`)
+
+### Changed
+- CI release flow: single tag with incremental builds
+- Separated build tasks for core and image packages
+
+### Removed
+- Committed `agent.py` from `quicksand-alpine` (now generated)
+
+## [v0.1.11] - 2026-02-12
+
+### Changed
+- Refactored `sandbox.py` into modular VM components
+- Refactored platform config to subclass-based architecture
+
+### Fixed
+- `filesync` import error on Windows guest
+
+## [v0.1.10] - 2026-02-11
+
+### Changed
+- Redesigned `image_wrapper` to properly subclass `Sandbox`
+
+## [v0.1.9] - 2026-02-11
+
+### Changed
+- Optimized QEMU boot time
+
+## [v0.1.8] - 2026-02-11
+
+### Added
+- `install.py` helper script for GitHub releases with download progress bars
+- Interactive `test` subcommand with `--mount`, `--network`, and sandbox type options
+- DNS resolution and curl HTTPS integration tests
+- Cross-platform CI: unit tests on Linux, macOS, and Windows
+- Matrix test-installer workflow across OS and image type
+
+### Fixed
+- Platform matching in `install.py` for wheel selection
+- Progress bar Unicode error on Windows
+- Network integration tests
+
+## [v0.1.7] - 2026-02-11
+
+### Changed
+- Switched to tag-based releases
+- Consolidated CI into single workflow (check, build, test)
+
+## [v0.1.6] - 2026-02-11
+
+### Changed
+- Redesigned CI workflows: separate check/build/test stages with proper release flow
+- Cross-workflow artifact handling via `gh run download`
+
+### Removed
+- Debug KVM ARM64 workflow
+
+## [v0.1.5] - 2026-02-11
+
+### Changed
+- Split CI into separate workflows
+
+## [v0.1.4] - 2026-02-11
+
+### Added
+- `sync_file()` API for explicit file sync
+- Bidirectional filesync with `use_filesync` config option
+- Standalone release workflow
+- WHPX kernel arg (`noapic`) for Windows
+
+### Fixed
+- Windows filesync: path handling, port initialization, atomic rename, bidirectional sync
+- Filesync initial sync race condition
+- WHPX kernel panic by correcting QEMU arg order
+
+## [v0.1.3] - 2026-02-10
+
+### Fixed
+- CI: removed `continue-on-error` from build and test jobs
+
+## [v0.1.2] - 2026-02-10
+
+### Changed
+- CI workflow now triggers on version tags
+
+## [v0.1.1] - 2026-02-10
+
+### Added
+- Initial release of quicksand: pip-installable Linux sandboxes powered by QEMU
+- Core sandbox API with `Sandbox` and `UbuntuSandbox` classes
+- Monorepo packages: `quicksand-core`, `quicksand-ubuntu`, `quicksand-alpine`, `quicksand-qemu`
+- QEMU binary bundling for macOS, Linux, and Windows
+- Direct kernel boot with virtio networking and 9p mounts
+- FastAPI-based HTTP guest agent
+- P2P file sync for Windows hosts (virtio-9p alternative)
+- Docker-based VM image building
+- CI/CD pipeline with per-platform wheel builds and integration tests
+- MIT License
diff --git a/docs/reference/security.md b/docs/reference/security.md
new file mode 100644
index 0000000..e751608
--- /dev/null
+++ b/docs/reference/security.md
@@ -0,0 +1,14 @@
+<!-- BEGIN MICROSOFT SECURITY.MD V1.0.0 BLOCK -->
+
+## Security
+
+Microsoft takes the security of our software products and services seriously, which
+includes all source code repositories in our GitHub organizations.
+
+**Please do not report security vulnerabilities through public GitHub issues.**
+
+For security reporting information, locations, contact information, and policies,
+please review the latest guidance for Microsoft repositories at
+[https://aka.ms/SECURITY.md](https://aka.ms/SECURITY.md).
+
+<!-- END MICROSOFT SECURITY.MD BLOCK -->
\ No newline at end of file
diff --git a/docs/under-the-hood/01-installation.md b/docs/under-the-hood/01-installation.md
new file mode 100644
index 0000000..d565498
--- /dev/null
+++ b/docs/under-the-hood/01-installation.md
@@ -0,0 +1,143 @@
+# Installation: Under the Hood
+
+Companion to [Installation](../user-guide/01-installation.md).
+
+## `quicksand install qemu`
+
+Installs a pre-built QEMU binary and its runtime dependencies into a Python package (`quicksand-qemu`). The package provides:
+
+```
+quicksand_qemu/bin/
+├── qemu-system-aarch64 # or qemu-system-x86_64
+├── qemu-img # Disk image manipulation tool
+├── lib/ # Shared libraries (libglib, libcrypto, etc.)
+└── share/qemu/ # Firmware files (BIOS, EFI, keymaps)
+```
+
+At runtime, Quicksand locates this via `quicksand_qemu.get_bin_dir()` and passes the firmware directory to QEMU:
+
+```bash
+qemu-system-aarch64 ... -L /path/to/share/qemu
+```
+
+The `-L` flag tells QEMU where to find firmware and keymap files. Without it, QEMU falls back to compile-time defaults which may not exist.
+
+If the bundled package isn't installed, Quicksand falls back to system QEMU found on `PATH`.
+
+### Windows ARM64 and fat wheels
+
+On Windows ARM64, most users run x86_64 Python through Microsoft's transparent emulation layer. The user may not even know they're running emulated Python — it's the default. This creates a conflict:
+
+| | Python arch | pip accepts | QEMU needed |
+|---|---|---|---|
+| Real x86_64 Windows | x86_64 | `win_amd64` | x86_64 |
+| ARM64 Windows, native Python | ARM64 | `win_arm64` | ARM64 |
+| **ARM64 Windows, emulated Python** | **x86_64** | **`win_amd64`** | **ARM64** |
+
+The third row is the problem. pip's wheel compatibility tags (PEP 425) match the Python interpreter's platform, not the hardware. An emulated x86_64 Python will only install `win_amd64` wheels — but the machine needs ARM64 QEMU binaries for hardware acceleration (WHPX).
+
+This problem is unique to Windows. Linux doesn't transparently emulate x86_64 on ARM64, and macOS users on Apple Silicon install ARM64 Python by default (Rosetta 2 exists but isn't the default Python experience).
+
+**Our solution: fat `win_amd64` wheels.** The `win_amd64` quicksand-qemu wheel ships both x86_64 and ARM64 QEMU binaries:
+
+```
+quicksand_qemu/bin/
+├── x86_64/ # x86_64 QEMU binaries
+│ ├── qemu-system-x86_64.exe
+│ ├── qemu-img.exe
+│ └── ...
+└── arm64/ # ARM64 QEMU binaries
+ ├── qemu-system-aarch64.exe
+ ├── qemu-img.exe
+ └── ...
+```
+
+At runtime, `_find_bundled_runtime()` reads the native CPU architecture from the Windows Registry (`HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE`) — this always reports the true hardware regardless of process emulation — and selects the matching subdirectory. On a single-arch wheel (Linux, macOS, or `win_arm64`), binaries live directly in `bin/` with no subdirectories.
+
+**Build pipeline:**
+1. The Windows x64 CI runner builds `win_amd64.whl` with x64 QEMU in `bin/`
+2. The Windows ARM64 CI runner builds `win_arm64.whl` with ARM64 QEMU in `bin/`
+3. A `pre_release` hook (runs after all builds, before publishing) opens the `win_amd64` wheel, moves its binaries to `bin/x86_64/`, extracts ARM64 binaries from the `win_arm64` wheel into `bin/arm64/`, and rewrites the wheel
+4. The `win_arm64` wheel ships unchanged (lean, single-arch) for the rare native ARM64 Python user
+
+This approach doubles the `win_amd64` wheel size (~44 MB → ~80 MB) but ensures `pip install quicksand-qemu` delivers hardware-accelerated QEMU on every Windows configuration without user intervention.
+
+### Platform wheel matrix
+
+#### quicksand-qemu: build runners → wheels
+
+quicksand-qemu is in `_SKIP` — never retagged. Each runner produces exactly one wheel.
+
+| Runner | QEMU Binary | Wheel Tag | After `pre_release` merge |
+|--------|-------------|-----------|--------------------------|
+| `[linux, x64]` | qemu-system-x86_64 (Linux) | `linux_x86_64` | unchanged |
+| `[linux, arm64]` | qemu-system-aarch64 (Linux) | `linux_aarch64` | unchanged |
+| `[macos, arm64]` | qemu-system-aarch64 (macOS) | `macosx_11_0_arm64` | unchanged |
+| `[windows, x64]` | qemu-system-x86_64.exe | `win_amd64` | → **fat**: x64 in `bin/x86_64/`, arm64 in `bin/arm64/` |
+| `[windows, arm64]` | qemu-system-aarch64.exe | `win_arm64` ¹ | unchanged (consumed by merge into fat wheel) |
+
+¹ **Windows ARM64 tag override:** The ARM64 runner runs x86_64 Python through transparent emulation, so `sysconfig.get_platform()` returns `win-amd64`. Without intervention, this runner would produce a **second** `win_amd64` wheel containing ARM64 binaries — colliding with the x64 runner's wheel and making the fat wheel merge impossible (no `win_arm64` to merge from). We override the wheel tag in `BinaryBundler.set_platform_wheel_tag()` (`quicksand-build-tools`, used by quicksand-qemu) and `set_platform_wheel_tag()` (`quicksand-image-tools`, used by image packages) by reading the native architecture from the Windows Registry (`HKLM\...\PROCESSOR_ARCHITECTURE`), which always reports `ARM64` regardless of process emulation.
+
+#### Image wheels (ubuntu, alpine, etc.): build runners → retag
+
+Image wheels contain qcow2 files that are cross-platform. Retag runs only on `RETAG_RUNNERS`.
+
+| Runner | Builds | Retag produces |
+|--------|--------|----------------|
+| `[linux, x64]` | `linux_x86_64` | + `macosx_10_13_x86_64`, `win_amd64` |
+| `[macos, arm64]` | `macosx_11_0_arm64` | + `linux_aarch64`, `win_arm64` |
+| `[linux, arm64]` | `linux_aarch64` | none (not in `RETAG_RUNNERS`) |
+| `[windows, *]` | — | not an image builder |
+
+#### quicksand-qemu: host → pip install
+
+| Host OS | Hardware | Python Arch | pip picks | QEMU binary used | HW accel |
+|---------|----------|-------------|-----------|------------------|----------|
+| Linux | x86_64 | x86_64 | `linux_x86_64` | qemu-system-x86_64 | KVM ✅ |
+| Linux | arm64 | arm64 | `linux_aarch64` | qemu-system-aarch64 | KVM ✅ |
+| macOS Intel | x86_64 | x86_64 | — (no wheel) | system QEMU (Homebrew) | HVF ✅ |
+| macOS Apple Silicon | arm64 | arm64 | `macosx_11_0_arm64` | qemu-system-aarch64 | HVF ✅ |
+| macOS Rosetta | arm64 | x86_64 | — (no wheel) | system QEMU (Homebrew) | TCG ❌ |
+| Windows | x86_64 | x86_64 | `win_amd64` (fat) | picks `bin/x86_64/` | WHPX ✅ |
+| Windows | arm64 | x86_64 (emulated) | `win_amd64` (fat) | picks `bin/arm64/` | WHPX ✅ |
+| Windows | arm64 | arm64 (native) | `win_arm64` | qemu-system-aarch64 | WHPX ✅ |
+
+**Notes:**
+- **No macOS x86_64 runner** — macOS Intel users fall back to system QEMU via Homebrew.
+- **Rosetta Python** — rare; gets no bundled wheel, falls back to system QEMU with software emulation (TCG).
+- **Fat wheel** — only `win_amd64` is fat (~2x size). All other wheels are single-arch.
+
+## `quicksand install ubuntu`
+
+Installs a base image package (`quicksand-ubuntu`) containing three files per architecture:
+
+```
+quicksand_ubuntu/images/
+├── ubuntu-24.04-arm64.kernel # Linux kernel binary (vmlinuz)
+├── ubuntu-24.04-arm64.initrd # Initial RAM disk
+└── ubuntu-24.04-arm64.qcow2 # Root filesystem (qcow2 format)
+```
+
+These become the `-kernel`, `-initrd`, and `-drive` arguments:
+
+```bash
+qemu-system-aarch64 \
+ -kernel /path/to/ubuntu-24.04-arm64.kernel \
+ -initrd /path/to/ubuntu-24.04-arm64.initrd \
+ -drive file=overlay.qcow2,format=qcow2,...
+```
+
+The `-drive` never points directly at the base qcow2. Quicksand creates a copy-on-write overlay on top of it (see [Save and Rollback](05-save-and-rollback.md)), so the base image is never modified.
+
+## Desktop overlay images
+
+Desktop images (`quicksand install ubuntu-desktop`) don't contain a full disk. They contain a qcow2 overlay that layers on top of the base image:
+
+```
+quicksand_ubuntu_desktop/images/
+├── manifest.json # Config defaults (memory, cpus, disk_size)
+└── overlays/
+ └── 0.qcow2 # Desktop packages layered on top of ubuntu base
+```
+
+The overlay's backing file points to the base image's qcow2. QEMU resolves this chain at boot. Reads go through the overlay first, falling through to the base for unmodified blocks.
diff --git a/docs/under-the-hood/02-sandbox-lifecycle.md b/docs/under-the-hood/02-sandbox-lifecycle.md
new file mode 100644
index 0000000..a3c8dfc
--- /dev/null
+++ b/docs/under-the-hood/02-sandbox-lifecycle.md
@@ -0,0 +1,106 @@
+# Sandbox Lifecycle: Under the Hood
+
+Companion to [Sandbox Lifecycle](../user-guide/02-sandbox-lifecycle.md).
+
+## Sandbox kwargs to QEMU command
+
+```python
+Sandbox(
+ image="ubuntu",
+ memory="2G",
+ cpus=4,
+ accel="auto",
+)
+```
+
+```bash
+qemu-system-aarch64 \
+ -nodefaults \
+ -machine virt \
+ -m 2G \
+ -smp 4 \
+ -L /path/to/share/qemu \
+ -accel hvf \
+ -cpu host \
+ ...
+```
+
+| Config field | QEMU flag | Notes |
+|---|---|---|
+| `memory="2G"` | `-m 2G` | Passed through as-is |
+| `cpus=4` | `-smp 4` | Number of virtual CPU cores |
+| `accel="auto"` | `-accel hvf` (macOS) | Auto-detected per platform (see below) |
+| `image="ubuntu"` | `-kernel`, `-initrd`, `-drive` | Resolved to image files on disk |
+
+`-nodefaults` strips QEMU's built-in devices (floppy, CD-ROM, serial ports, etc.) so the command builds the VM from scratch with only what's needed.
+
+## Machine type
+
+The `-machine` flag is selected automatically based on architecture and platform:
+
+| Architecture | Platform | Machine | Why |
+|---|---|---|---|
+| ARM64 | Any | `virt` | ARM's standard virtual machine type |
+| x86_64 | Linux + KVM | `microvm` | Minimal machine, ~4x faster boot |
+| x86_64 | macOS / Windows / TCG | `q35` | Full-featured Intel chipset |
+
+`microvm` is only used on Linux x86_64 with KVM and when the firmware file `bios-microvm.bin` exists in the data directory. It skips PCI bus emulation entirely, using MMIO (memory-mapped) virtio devices instead.
+
+## Hardware acceleration
+
+```python
+Sandbox(image="ubuntu") # accel defaults to "auto"
+```
+
+Auto-detection selects the best available accelerator:
+
+| Platform | Accelerator | QEMU flags | CPU performance |
+|---|---|---|---|
+| macOS | HVF | `-accel hvf -cpu host` | Near-native |
+| Linux | KVM | `-accel kvm -cpu host` | Near-native |
+| Windows | WHPX | `-accel whpx -cpu host` | Near-native |
+| Any (fallback) | TCG | `-accel tcg -cpu max` | 10-50x slower |
+
+With hardware acceleration (`-cpu host`), the guest runs on the real CPU. With TCG (`-cpu max`), QEMU translates every instruction in software.
+
+On Windows inside a Hyper-V VM (nested virtualization), WHPX gets an extra flag: `-accel whpx,kernel-irqchip=off`.
+
+## Device naming by machine type
+
+The machine type determines how virtio devices are attached:
+
+| Machine | Block device | Network device | Bus type |
+|---|---|---|---|
+| `virt` (ARM64) | `virtio-blk-device` | `virtio-net-device` | MMIO |
+| `q35` (x86_64) | `virtio-blk-pci` | `virtio-net-pci` | PCI |
+| `microvm` (x86_64+KVM) | `virtio-blk-device` | `virtio-net-device` | MMIO |
+
+PCI devices have a small overhead from bus emulation. MMIO devices (used by `virt` and `microvm`) skip this entirely.
+
+## Full assembled command
+
+Putting it all together, here's what Quicksand generates for a typical macOS ARM64 headless sandbox:
+
+```bash
+qemu-system-aarch64 \
+ -nodefaults \
+ -machine virt \
+ -m 512M \
+ -smp 1 \
+ -L /path/to/share/qemu \
+ -object iothread,id=iothread0 \
+ -drive file=overlay.qcow2,format=qcow2,if=none,id=drive0,cache=writethrough,discard=unmap,detect-zeroes=unmap \
+ -device virtio-blk-device,drive=drive0,iothread=iothread0 \
+ -serial stdio \
+ -nographic -vga none \
+ -cpu host \
+ -accel hvf \
+ -qmp tcp:127.0.0.1:4444,server,nowait \
+ -kernel /path/to/ubuntu-24.04-arm64.kernel \
+ -append "root=/dev/vda rw rootflags=rw console=ttyAMA0 rootfstype=ext4 quiet loglevel=0 raid=noautodetect quicksand_token=abc123 quicksand_port=8080" \
+ -initrd /path/to/ubuntu-24.04-arm64.initrd \
+ -netdev user,id=net0,restrict=on,hostfwd=tcp:127.0.0.1:8080-:8080,guestfwd=tcp:10.0.2.100:445-cmd:/path/to/smb_server \
+ -device virtio-net-device,netdev=net0
+```
+
+Every flag here maps back to either a `Sandbox` kwarg or an automatic platform decision.
diff --git a/docs/under-the-hood/03-running-commands.md b/docs/under-the-hood/03-running-commands.md
new file mode 100644
index 0000000..41b5d3f
--- /dev/null
+++ b/docs/under-the-hood/03-running-commands.md
@@ -0,0 +1,72 @@
+# Running Commands: Under the Hood
+
+Companion to [Running Commands](../user-guide/03-running-commands.md).
+
+## Direct kernel boot
+
+Instead of booting through BIOS/UEFI firmware (slow), Quicksand passes the kernel and initrd directly to QEMU:
+
+```bash
+qemu-system-aarch64 \
+ -kernel /path/to/ubuntu-24.04-arm64.kernel \
+ -initrd /path/to/ubuntu-24.04-arm64.initrd \
+ -append "root=/dev/vda rw rootflags=rw console=ttyAMA0 rootfstype=ext4 quiet loglevel=0 raid=noautodetect quicksand_token=abc123 quicksand_port=8080"
+```
+
+This skips the entire firmware boot sequence and starts the Linux kernel immediately, saving several seconds.
+
+## Agent token injection
+
+The guest agent is a minimal Rust HTTP server baked into the initrd. It reads its auth token and port from the kernel command line (`/proc/cmdline`):
+
+```
+quicksand_token=abc123 quicksand_port=8080
+```
+
+These are injected via `-append` and are unique per sandbox instance. The token prevents other processes on the host from sending commands to the VM.
+
+## Serial console
+
+```bash
+-serial stdio
+```
+
+The VM's serial port is connected to QEMU's stdin/stdout. Combined with `console=ttyAMA0` (ARM64) or `console=ttyS0` (x86_64) in the kernel command line, this lets Quicksand read kernel boot messages and detect when the guest agent is ready.
+
+## Host-to-guest routing
+
+```python
+result = await sb.execute("ls /")
+```
+
+The `execute()` call sends an HTTP POST to the guest agent. But the guest is behind QEMU's NAT. It doesn't have a real IP on the host network. The connection is routed via a port forward in the `-netdev` flags:
+
+```bash
+-netdev user,id=net0,...,hostfwd=tcp:127.0.0.1:8080-:8080
+```
+
+This means `localhost:8080` on the host is forwarded to port `8080` inside the guest, where the agent is listening. The flow:
+
+```
+sb.execute("ls /")
+ → HTTP POST http://127.0.0.1:8080/execute {"command": "ls /"}
+ → QEMU hostfwd routes to guest:8080
+ → Guest agent runs the command
+ → Returns {"stdout": "bin\nboot\n...", "exit_code": 0}
+```
+
+## Streaming
+
+```python
+result = await sb.execute("apt install -y python3", on_stdout=callback)
+```
+
+Streaming uses the `/execute_stream` endpoint instead of `/execute`. The guest agent responds with Server-Sent Events (SSE). Each event contains one output chunk.
+
+```
+data: {"type": "stdout", "data": "Reading package lists..."}
+data: {"type": "stdout", "data": "Building dependency tree..."}
+data: {"type": "exit", "exit_code": 0}
+```
+
+The HTTP connection stays open until the command finishes. Callbacks fire for each chunk as it arrives.
diff --git a/docs/under-the-hood/04-file-exchange.md b/docs/under-the-hood/04-file-exchange.md
new file mode 100644
index 0000000..8722316
--- /dev/null
+++ b/docs/under-the-hood/04-file-exchange.md
@@ -0,0 +1,80 @@
+# File Exchange: Under the Hood
+
+Companion to [File Exchange](../user-guide/04-file-exchange.md).
+
+## CIFS mounts (default)
+
+```python
+Sandbox(
+ image="ubuntu",
+ mounts=[Mount("/host/code", "/mnt/code")],
+)
+```
+
+CIFS mounts don't add any QEMU flags for the mount itself. Instead, they work through QEMU's `guestfwd` mechanism, which tunnels a TCP connection from the guest to a host process:
+
+```bash
+-netdev user,id=net0,...,guestfwd=tcp:10.0.2.100:445-cmd:/path/to/python -m quicksand_smb --inetd
+```
+
+`guestfwd` tells QEMU: "when the guest connects to `10.0.2.100:445`, spawn this command and pipe the TCP stream to its stdin/stdout." The command is Quicksand's pure-Python SMB3 server running in inetd mode. It runs one instance per connection with no listening port on the host.
+
+The guest agent then mounts the share:
+
+```bash
+mount -t cifs //10.0.2.100/QUICKSAND0 /mnt/code \
+ -o username=guest,password=,sec=none,vers=3.0,port=445
+```
+
+Each mount gets its own SMB share name (`QUICKSAND0`, `QUICKSAND1`, ...). The SMB server maps each share name to the corresponding host directory.
+
+## Hot-mounts
+
+```python
+handle = await sb.mount("/host/project", "/mnt/project")
+```
+
+Hot-mounts use the same CIFS mechanism. The SMB server is already running (started at boot via guestfwd), so adding a mount just:
+
+1. Registers a new share name in the running SMB server
+2. Sends a `mount -t cifs` command to the guest via the agent
+
+No QEMU restart or new flags needed.
+
+## 9p mounts
+
+```python
+Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.NONE,
+ mounts=[Mount("/host/data", "/mnt/data", type="9p")],
+)
+```
+
+9p mounts add QEMU flags at launch time:
+
+```bash
+-fsdev local,id=pb_fs_0,path=/host/data,security_model=none \
+-device virtio-9p-pci,id=pb_9p_0,fsdev=pb_fs_0,mount_tag=pb9p0
+```
+
+| Flag | Purpose |
+|---|---|
+| `-fsdev local,...` | Expose a host directory to QEMU via the Plan 9 protocol |
+| `security_model=none` | No UID/GID mapping — files appear as-is |
+| `-device virtio-9p-pci,...` | Attach the filesystem as a virtio device the guest can mount |
+| `mount_tag=pb9p0` | Tag used by the guest `mount -t 9p pb9p0 /mnt/data` command |
+
+On MMIO machines such as `microvm` (x86_64+KVM) and `virt` (ARM64), the device type is `virtio-9p-device` instead of `virtio-9p-pci`.
+
+Read-only 9p mounts add `,readonly=on` to the `-fsdev` flags.
+
+## Why CIFS is the default
+
+| | CIFS | 9p |
+|---|---|---|
+| Hot-mountable at runtime | Yes (share added to running SMB server) | No (requires QEMU flags at launch) |
+| Works with `NetworkMode.NONE` | No (needs guestfwd, which needs a netdev) | Yes (uses virtio device, no network) |
+| Host dependency | Pure-Python SMB server (bundled) | QEMU built-in |
+
+CIFS is default because hot-mounting is the common case. 9p exists for the `NetworkMode.NONE` scenario where no network stack is configured at all.
diff --git a/docs/under-the-hood/05-save-and-rollback.md b/docs/under-the-hood/05-save-and-rollback.md
new file mode 100644
index 0000000..197a7e7
--- /dev/null
+++ b/docs/under-the-hood/05-save-and-rollback.md
@@ -0,0 +1,106 @@
+# Save and Rollback: Under the Hood
+
+Companion to [Save and Rollback](../user-guide/05-save-and-rollback.md).
+
+## qcow2 overlay chain
+
+Every sandbox runs on a copy-on-write overlay, never the base image directly.
+
+```
+base image (read-only) overlay (read-write)
+ubuntu-24.04-arm64.qcow2 ←── overlay-1234.qcow2
+```
+
+The overlay starts empty. Reads fall through to the base. Writes go to the overlay. This is why sandbox creation is instant. No disk copying is needed.
+
+The drive flags that enable this:
+
+```bash
+-drive file=overlay.qcow2,format=qcow2,if=none,id=drive0,cache=writethrough,discard=unmap,detect-zeroes=unmap
+```
+
+| Flag | Purpose |
+|---|---|
+| `cache=writethrough` | Writes go to disk immediately — safe for snapshots |
+| `discard=unmap` | Guest TRIM commands free qcow2 clusters, keeping overlays small |
+| `detect-zeroes=unmap` | Writing zeroes is treated as a discard — also shrinks overlays |
+
+## Checkpoints
+
+```python
+await sb.checkpoint("before-experiment")
+```
+
+Sends a QMP command through the QEMU Machine Protocol (a JSON-RPC channel on a localhost TCP port):
+
+```bash
+# QEMU is started with:
+-qmp tcp:127.0.0.1:4444,server,nowait
+```
+
+```json
+{"execute": "human-monitor-command", "arguments": {"command-line": "savevm before-experiment"}}
+```
+
+`savevm` captures the entire VM state (RAM contents, CPU registers, device state, and a disk snapshot) into the qcow2 file. The VM keeps running.
+
+## Revert
+
+```python
+await sb.revert("before-experiment")
+```
+
+```json
+{"execute": "human-monitor-command", "arguments": {"command-line": "loadvm before-experiment"}}
+```
+
+`loadvm` restores the VM to the exact state when `savevm` was called. Running processes, open files, and network connections all snap back. The VM resumes execution from that point.
+
+## Saves
+
+```python
+await sb.save("dev-env")
+```
+
+Saves use a different mechanism. QMP `blockdev-snapshot-sync` pivots the overlay chain without pausing the VM.
+
+**Step 1: Flush guest and host buffers**
+
+```python
+await sb.execute("sync") # Guest: flush filesystem
+await sb.execute("fstrim -a") # Guest: TRIM freed blocks
+```
+
+```json
+{"execute": "human-monitor-command", "arguments": {"command-line": "qemu-io drive0 \"flush\""}}
+```
+
+**Step 2: Atomic overlay pivot**
+
+```json
+{"execute": "blockdev-snapshot-sync", "arguments": {"device": "drive0", "snapshot-file": "/tmp/new-overlay.qcow2", "format": "qcow2", "mode": "absolute-paths"}}
+```
+
+This tells QEMU to start writing to a new overlay. The old one is now frozen. The VM never pauses. New writes go to the new overlay while the old one is copied to the save directory.
+
+```
+Before pivot:
+ base.qcow2 ← overlay-old.qcow2 (active, being written to)
+
+After pivot:
+ base.qcow2 ← overlay-old.qcow2 (frozen) ← overlay-new.qcow2 (active)
+```
+
+**Step 3: Write to save directory**
+
+The frozen overlay chain is copied to `.quicksand/sandboxes/dev-env/`, along with a `manifest.json` recording the config and architecture.
+
+## Checkpoints vs saves at the QEMU level
+
+| | Checkpoint (`savevm`) | Save (`blockdev-snapshot-sync`) |
+|---|---|---|
+| What's captured | RAM + disk + device state | Disk only |
+| Where it lives | Inside the qcow2 file | Separate directory on host |
+| VM pauses | Briefly (< 1s) | Never |
+| Survives VM stop | No | Yes |
+| QEMU mechanism | Internal snapshot | Overlay pivot |
diff --git a/docs/under-the-hood/06-desktop-control.md b/docs/under-the-hood/06-desktop-control.md
new file mode 100644
index 0000000..0af19cd
--- /dev/null
+++ b/docs/under-the-hood/06-desktop-control.md
@@ -0,0 +1,113 @@
+# Desktop Control: Under the Hood
+
+Companion to [Desktop Control](../user-guide/06-desktop-control.md).
+
+## Display devices
+
+```python
+Sandbox(image="ubuntu-desktop", enable_display=True)
+```
+
+```bash
+# enable_display=True adds:
+-device virtio-gpu-pci \
+-display vnc=127.0.0.1:0 \
+-device usb-ehci,id=ehci \
+-device usb-tablet,bus=ehci.0 \
+-device virtio-keyboard-pci
+```
+
+```bash
+# enable_display=False (default) uses:
+-nographic -vga none
+```
+
+| Flag | Purpose |
+|---|---|
+| `-device virtio-gpu-pci` | Virtual GPU — guest renders to a framebuffer QEMU can read. On x86_64 this is `-device virtio-vga` instead. |
+| `-display vnc=127.0.0.1:0` | VNC server on localhost (display 0 = port 5900). For debugging; Quicksand uses QMP, not VNC. |
+| `-device usb-ehci,id=ehci` | USB 2.0 host controller (bus for the tablet device) |
+| `-device usb-tablet,bus=ehci.0` | Absolute-positioning input device (see [Mouse](#mouse) below) |
+| `-device virtio-keyboard-pci` | Virtual keyboard for QMP key injection. Required on ARM64 `virt` which has no PS/2 controller. |
+
+The VNC port is auto-allocated in the 5900-5999 range. QEMU's VNC syntax uses a display number: `-display vnc=127.0.0.1:{port - 5900}`.
+
+## Screenshots
+
+```python
+await sb.screenshot("screen.png")
+```
+
+```json
+{"execute": "screendump", "arguments": {"filename": "/tmp/screen.ppm"}}
+```
+
+QMP `screendump` reads the GPU framebuffer and writes it to a host file. The output format is PPM (a raw bitmap format). Quicksand converts PPM to PNG using `struct` + `zlib`. No Pillow is needed. If QEMU outputs PNG directly (some builds do), it's detected via magic bytes and used as-is.
+
+## Keyboard
+
+```python
+await sb.type_text("hello")
+```
+
+Each character is mapped to a QKeyCode and sent via QMP `send-key`:
+
+```json
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "h"}], "hold-time": 1}}
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "e"}], "hold-time": 1}}
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "l"}], "hold-time": 1}}
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "l"}], "hold-time": 1}}
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "o"}], "hold-time": 1}}
+```
+
+`hold-time=1` (1ms) is critical. The default is 100ms, which means `send-key` blocks for 100ms per character. Typing "hello" would take 500ms. At 1ms it takes ~5ms.
+
+Uppercase and symbols use shift:
+
+```python
+await sb.type_text("Hello!")
+```
+
+```json
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "shift"}, {"type": "qcode", "data": "h"}], "hold-time": 1}}
+...
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "shift"}, {"type": "qcode", "data": "1"}], "hold-time": 1}}
+```
+
+```python
+await sb.press_key(Key.CTRL, Key.C)
+```
+
+```json
+{"execute": "send-key", "arguments": {"keys": [{"type": "qcode", "data": "ctrl"}, {"type": "qcode", "data": "c"}], "hold-time": 100}}
+```
+
+`press_key()` uses the default 100ms hold time. Modifier combos need the keys held long enough for the guest to register them.
+
+## Mouse
+
+```python
+await sb.mouse_move(500, 300)
+```
+
+```json
+{"execute": "input-send-event", "arguments": {"events": [
+ {"type": "abs", "data": {"axis": "x", "value": 500}},
+ {"type": "abs", "data": {"axis": "y", "value": 300}}
+]}}
+```
+
+The coordinates are absolute (0-32767 range on each axis). This is why the input device is a USB tablet (`-device usb-tablet`) rather than a relative mouse. A relative mouse would need to know the current position and calculate deltas, and rounding errors would cause drift over time.
+
+```python
+await sb.mouse_click("left")
+```
+
+Down and up are sent as separate QMP calls so window managers see a distinct button-press event:
+
+```json
+{"execute": "input-send-event", "arguments": {"events": [{"type": "btn", "data": {"button": "left", "down": true}}]}}
+{"execute": "input-send-event", "arguments": {"events": [{"type": "btn", "data": {"button": "left", "down": false}}]}}
+```
+
+Double-clicks add a 50ms pause between the two click sequences so the window manager registers them as distinct clicks.
diff --git a/docs/under-the-hood/07-network-and-isolation.md b/docs/under-the-hood/07-network-and-isolation.md
new file mode 100644
index 0000000..4b65742
--- /dev/null
+++ b/docs/under-the-hood/07-network-and-isolation.md
@@ -0,0 +1,82 @@
+# Network and Isolation: Under the Hood
+
+Companion to [Network and Isolation](../user-guide/07-network-and-isolation.md).
+
+## Network modes
+
+```python
+Sandbox(image="ubuntu") # MOUNTS_ONLY by default
+```
+
+```bash
+# NetworkMode.MOUNTS_ONLY (default):
+-netdev user,id=net0,restrict=on,hostfwd=tcp:127.0.0.1:8080-:8080,guestfwd=tcp:10.0.2.100:445-cmd:... \
+-device virtio-net-device,netdev=net0
+```
+
+```python
+Sandbox(image="ubuntu", network_mode=NetworkMode.FULL)
+```
+
+```bash
+# NetworkMode.FULL:
+-netdev user,id=net0,hostfwd=tcp:127.0.0.1:8080-:8080,guestfwd=tcp:10.0.2.100:445-cmd:... \
+-device virtio-net-device,netdev=net0
+```
+
+```python
+Sandbox(image="ubuntu", network_mode=NetworkMode.NONE)
+```
+
+```bash
+# NetworkMode.NONE:
+-nic none
+```
+
+The only difference between `MOUNTS_ONLY` and `FULL` is `restrict=on` vs no restrict. On `microvm`, `NetworkMode.NONE` produces no network flags at all (microvm doesn't need `-nic none`).
+
+## How `restrict=on` works
+
+QEMU's SLIRP networking gives the guest a virtual NAT. The guest sees:
+
+- `10.0.2.15` — its own IP
+- `10.0.2.2` — the host (NAT gateway)
+- `10.0.2.3` — DNS server
+
+`restrict=on` blocks all outbound connections from the guest to the real network. But it does **not** block `hostfwd` or `guestfwd`. Those are internal QEMU tunnels, not real network connections. This is how file mounts work even in `MOUNTS_ONLY` mode. The guestfwd tunnel to the SMB server is unaffected by `restrict=on`.
+
+## Port forwarding
+
+```python
+Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.FULL,
+ port_forwards=[PortForward(host=8080, guest=80), PortForward(host=8443, guest=443)],
+)
+```
+
+```bash
+-netdev user,id=net0,hostfwd=tcp:127.0.0.1:{agent_port}-:{agent_port},hostfwd=tcp:127.0.0.1:8080-:80,hostfwd=tcp:127.0.0.1:8443-:443,...
+```
+
+Each `PortForward(host, guest)` pair becomes a `hostfwd` rule. The agent port's `hostfwd` is always present (it's how `execute()` reaches the guest) and uses a dynamically allocated port.
+
+All forwards bind to `127.0.0.1`. They are only accessible from the host, not from the network.
+
+## Virtio network device
+
+The device type depends on machine type:
+
+| Machine | Device | Bus |
+|---|---|---|
+| `virt` (ARM64) | `virtio-net-device` | MMIO |
+| `q35` (x86_64) | `virtio-net-pci` | PCI |
+| `microvm` (x86_64+KVM) | `virtio-net-device` | MMIO |
+
+On non-microvm x86_64 machines, an additional flag suppresses PXE boot:
+
+```bash
+-global virtio-net-pci.romfile=
+```
+
+This prevents QEMU from trying to load a PXE boot ROM, which would slow down boot and isn't needed.
diff --git a/docs/under-the-hood/08-performance.md b/docs/under-the-hood/08-performance.md
new file mode 100644
index 0000000..35b5c6d
--- /dev/null
+++ b/docs/under-the-hood/08-performance.md
@@ -0,0 +1,80 @@
+# Performance: Under the Hood
+
+Companion to [Performance](../user-guide/08-performance.md).
+
+## Boot time: machine type
+
+The biggest boot-time win is the machine type:
+
+| Machine | Boot time | Why |
+|---|---|---|
+| `microvm` | < 1 second | No PCI bus, no firmware, no device enumeration |
+| `q35` / `virt` | ~2-3 seconds | Full chipset emulation, firmware device scan |
+
+`microvm` is auto-selected on Linux x86_64 + KVM when `bios-microvm.bin` is present. It uses MMIO devices instead of PCI:
+
+```bash
+# microvm (fast):
+-machine microvm \
+-device virtio-blk-device,drive=drive0,iothread=iothread0 \
+-device virtio-net-device,netdev=net0
+
+# q35 (standard):
+-machine q35 \
+-device virtio-blk-pci,drive=drive0,iothread=iothread0 \
+-device virtio-net-pci,netdev=net0
+```
+
+## Boot time: direct kernel boot
+
+```bash
+-kernel /path/to/vmlinuz \
+-initrd /path/to/initrd.img \
+-append "root=/dev/vda rw rootfstype=ext4 quiet loglevel=0 ..."
+```
+
+Passing the kernel directly to QEMU skips BIOS/UEFI firmware entirely. Combined with `quiet loglevel=0`, the kernel suppresses most boot messages, and `raid=noautodetect` skips MD RAID scanning.
+
+## CPU acceleration
+
+```bash
+# Hardware acceleration (near-native):
+-accel kvm -cpu host # Linux
+-accel hvf -cpu host # macOS
+-accel whpx -cpu host # Windows
+
+# Software emulation (10-50x slower):
+-accel tcg -cpu max
+```
+
+`-cpu host` exposes the real CPU features to the guest. The hypervisor runs guest code directly on the hardware. `-cpu max` (TCG) emulates the most capable CPU QEMU supports, but every instruction is translated in software.
+
+## Disk I/O
+
+```bash
+-object iothread,id=iothread0 \
+-drive file=overlay.qcow2,format=qcow2,if=none,id=drive0,cache=writethrough,discard=unmap,detect-zeroes=unmap,aio=io_uring \
+-device virtio-blk-device,drive=drive0,iothread=iothread0
+```
+
+| Flag | Impact |
+|---|---|
+| `iothread` | Disk I/O runs on a dedicated thread, not QEMU's main loop. Prevents disk operations from blocking CPU emulation or display rendering. |
+| `aio=io_uring` | Linux's modern async I/O API (kernel 5.8+). ~50% lower disk latency vs the default thread-pool AIO. Only on Linux; macOS/Windows use QEMU's default (threads). |
+| `virtio-blk` | Paravirtualized block device — the guest knows it's virtual and uses an optimized driver. Much faster than emulated SATA/IDE. |
+| `cache=writethrough` | Writes hit disk immediately. Slower than `writeback` but safe for snapshots — no dirty cache to lose on pivot. |
+| `discard=unmap` | Guest TRIM commands release qcow2 clusters back to the host filesystem. Keeps overlays from growing indefinitely. |
+| `detect-zeroes=unmap` | Writing a block of zeroes is treated as a discard. Common after `fstrim` or file deletion. |
+
+## Snapshot performance
+
+**Checkpoints** (`savevm`/`loadvm`) capture full VM state inside the qcow2 file:
+- Time is proportional to RAM size (must write all of RAM to disk)
+- ~1-2 seconds for 512MB-2GB
+
+**Saves** (`blockdev-snapshot-sync`) pivot the overlay chain:
+- The pivot itself is instant (just changes where writes go)
+- The copy step (writing frozen overlays to the save directory) depends on overlay size
+- `compress=True` runs `qemu-img convert` which recompresses. This takes 10-30 seconds depending on data
+
+The `fstrim` + `qemu-io flush` before a save ensures the overlay is as small as possible (freed blocks are reclaimed) and fully consistent on disk.
diff --git a/docs/under-the-hood/index.md b/docs/under-the-hood/index.md
new file mode 100644
index 0000000..76bbb6d
--- /dev/null
+++ b/docs/under-the-hood/index.md
@@ -0,0 +1,711 @@
+# Under the Hood
+
+Quicksand is a VM harness for AI agents. It provides a Python API for running VMs that agents can interact with (executing commands, reading/writing files, browsing the web) with support for hot checkpointing, file sharing, GUI input, and cross-platform operation.
+
+```mermaid
+graph LR
+ subgraph Host["Host"]
+ HostFiles["Host Files"]
+ subgraph Process["Python Process"]
+ Code["Your Code"]
+ subgraph SB["quicksand.Sandbox"]
+ TCP["TCP Client"]
+ FileSync["FileSync (CIFS / SMB)"]
+ QMP["QMP Client"]
+ end
+ end
+ subgraph QEMU["QEMU Process (bundled)"]
+ subgraph Accel["KVM / HVF / WHPX (host)"]
+ subgraph VM["Linux VM (bundled)"]
+ Agent["quicksand-guest-agent"]
+ Mount["/mnt/data"]
+ Desktop["Xfce4 + LightDM (desktop)"]
+ end
+ end
+ VNC["VNC Server (desktop)"]
+ end
+ end
+
+ Code <-->|".execute()"| SB
+ Code <-->|".screenshot() / .type_text()"| SB
+ SB -->|launches| QEMU
+ TCP <-->|commands| Agent
+ QMP <-->|"snapshots, input, screendump"| QEMU
+ HostFiles <--> FileSync
+ FileSync <-.->|sync| Mount
+```
+
+## Why This Approach?
+
+LLMs are trained on data from real computers, including shell sessions, package managers, browsers, and GUIs. Agents work best when they get a full computer that matches what they already know how to operate. Quicksand gives each agent its own Linux VM. It is checkpointable, cross-platform, and has no system dependencies. Just `pip install`.
+
+### What agents need from a sandbox
+
+| Requirement | Why |
+|-------------|-----|
+| **Strong isolation** | Agents execute arbitrary code. Containers provide some isolation via namespaces, but they share the host kernel. A VM runs its own kernel behind a hypervisor — a stronger boundary. |
+| **Save and restore** | Agents checkpoint before risky operations and roll back on failure. Ideally fast, reliable, and without root. |
+| **Cross-platform** | Agents run on developer machines — macOS, Linux, Windows. A Linux-only solution limits adoption. |
+| **No system dependencies** | Fewer moving parts means easier setup. Ideally no Docker daemon, no cloud API keys, no admin privileges. |
+| **Full OS** | A complete Linux environment — `apt install`, browsers, GUIs — so agents can use the tools they're familiar with. |
+
+### Why not containers?
+
+Containers are the natural starting point, but they have trade-offs in this context. They share the host kernel, which provides less isolation than a hypervisor boundary. Freezing and restoring a running container requires specialized kernel support and root privileges, and tends to be fragile across kernel versions. And containers are Linux-native. On macOS and Windows, Docker Desktop runs a Linux VM behind the scenes anyway.
+
+### Why QEMU?
+
+VMs address the above trade-offs well, but most VM tools have their own limitations. Firecracker is fast but Linux-only and needs root. Apple's Virtualization.framework is macOS-only. Cloud VMs need network and API keys. WSL2 requires admin to enable and can't be bundled.
+
+QEMU is heavyweight (~60 MB bundled on macOS ARM64), but it's the only tool that works everywhere, supports checkpointing, runs as a normal user, and can be bundled into a pip package.
+
+| | QEMU | Firecracker | vfkit | Cloud VMs | Containers |
+|---|---|---|---|---|---|
+| macOS + Linux + Windows | Yes | Linux-only | macOS-only | Yes | Linux-native* |
+| Checkpointing | Yes | No | macOS 14+ | Varies | Fragile, needs root |
+| No root required | Yes | No | Yes | N/A | Needs daemon or rootless setup |
+| Bundleable (`pip install`) | Yes | No | No | No | No |
+| Offline / local | Yes | Yes | Yes | No | Yes |
+
+\* Docker Desktop runs a hidden VM on macOS and Windows.
+
+**Future:** Firecracker can be swapped in on Linux for sub-100ms snapshots without changing the Python API. vfkit could be used on macOS 14+ for a smaller bundle.
+
+---
+
+## Package Structure
+
+The project is a monorepo with 15 packages:
+
+```
+packages/
+├── quicksand-core/ # Core VM sandbox implementation
+├── quicksand-qemu/ # Bundled QEMU binaries (per-platform)
+├── quicksand-smb/ # Pure-Python SMB3 server for host-guest mounts
+├── dev/ # Dev/build/release packages
+│ ├── quicksand-build-tools/ # Shared build utilities for binary bundling
+│ ├── quicksand-image-tools/ # Build tools for custom images
+│ ├── quicksand-base-scaffold/ # Scaffolding for new base image packages
+│ ├── quicksand-overlay-scaffold/ # Scaffolding for new overlay image packages
+│ └── quicksand-gh-runners/ # GitHub Actions self-hosted runner config
+├── contrib/ # Community/team image packages
+│ ├── aif-agent-sandbox/ # Ubuntu + Python 3.12, uv, build tools
+│ └── aif-cua-agent-sandbox/ # AIF Agent Sandbox + Playwright, Chromium
+├── quicksand/ # User-facing wrapper (re-exports core + images)
+├── quicksand-ubuntu/ # Bundled Ubuntu 24.04 image
+├── quicksand-alpine/ # Bundled Alpine 3.21 image
+├── quicksand-ubuntu-desktop/# Ubuntu 24.04 + Xfce4 desktop image
+└── quicksand-alpine-desktop/# Alpine 3.21 + Xfce4 desktop image
+```
+
+**quicksand-core** — fundamental implementation. `Sandbox` class, host platform detection (`host/`), QEMU-specific subsystems (`qemu/`), and general utilities (`utils/`). No hard dependency on `quicksand-qemu`. QEMU binaries are located at runtime via `quicksand_qemu.get_bin_dir()` with a fallback to system QEMU.
+
+**quicksand-qemu** — pre-built QEMU binaries via `get_bin_dir()`. Installed via `quicksand install qemu`. Separate from core so the core works with any QEMU installation.
+
+**quicksand-smb** — pure-Python SMB3 server for host-guest directory mounting. Runs in inetd mode (stdin/stdout), spawned per-connection by QEMU's `guestfwd=cmd:`. No TCP port opened on the host, no external dependencies.
+
+**quicksand-build-tools** — shared build-time utilities for bundling native binaries into platform-specific wheels. Used by quicksand-qemu build hooks. Provides `BinaryBundler` with platform-specific logic for copying shared libraries, rewriting paths (install_name_tool on macOS, patchelf on Linux), and codesigning.
+
+**quicksand** — user-facing package that re-exports from core and conditionally from image packages. The `quicksand install` CLI downloads and installs extras from GitHub releases: `quicksand install ubuntu`, `quicksand install alpine-desktop`, etc.
+
+**quicksand-ubuntu / quicksand-alpine** — optional packages bundling pre-built headless VM images. Each provides `<Distro>Sandbox` (a `Sandbox` subclass that accepts `**kwargs`).
+
+**quicksand-ubuntu-desktop / quicksand-alpine-desktop** — optional packages bundling desktop VM images with Xfce4 + LightDM auto-login. Extend the headless images with a full graphical desktop, enabling GUI input (keyboard, mouse) and screenshot capture. Ubuntu Desktop uses systemd. Alpine Desktop uses OpenRC.
+
+**quicksand-image-tools** — build tools: the `quicksand-image-tools` CLI and the quicksand guest agent Rust source.
+
+---
+
+## Core Abstractions
+
+### Sandbox
+
+The central orchestrator:
+
+```python
+from quicksand import Sandbox
+
+async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("echo hello")
+ print(result.stdout)
+```
+
+Key methods:
+
+| Method | Description |
+|--------|-------------|
+| `await start()` / `await stop()` | VM lifecycle |
+| `await execute(command)` | Run a shell command, return `ExecuteResult` |
+| `await save(name)` | Hot save — save disk state to `.quicksand/sandboxes/<name>/`, VM keeps running |
+| `await checkpoint(tag)` | Ephemeral in-session snapshot (RAM + disk), not persisted |
+| `await revert(tag)` | Restore VM to a named in-session checkpoint |
+| `await screenshot(path)` | Save guest display as PNG (desktop mode) |
+| `await type_text(text)` | Type a string via keyboard events (desktop mode) |
+| `await press_key(*keys)` | Press a key combo (desktop mode) |
+| `await mount(host, guest)` | Hot-mount a host directory into the running VM (returns `MountHandle`) |
+| `await unmount(handle)` | Unmount a previously hot-mounted directory |
+| `await mouse_move(x, y)` | Move mouse to absolute position (desktop mode) |
+| `await mouse_click(button)` | Click a mouse button (desktop mode) |
+
+### Sandbox kwargs
+
+All configuration is passed as keyword arguments to `Sandbox(...)`:
+
+| Kwarg | Description |
+|-------|-------------|
+| `image` | Required image name (resolved via `quicksand.images` entry points or save name) |
+| `arch` | Target architecture (e.g., `"amd64"`, `"arm64"`). Auto-detected if `None`. Forces TCG emulation when cross-arch. |
+| `memory` | Memory allocation (e.g., `"512M"`, `"2G"`) |
+| `cpus` | Number of virtual CPUs |
+| `mounts` | List of `Mount` for boot-time host directory sharing |
+| `port_forwards` | List of `PortForward(host=..., guest=...)` objects |
+| `save` | Auto-save name on stop (on `Sandbox.__init__`, not `SandboxConfig`) |
+| `network_mode` | `NetworkMode` enum: `NONE`, `MOUNTS_ONLY` (default), `FULL` |
+| `extra_qemu_args` | Additional QEMU command line arguments |
+| `boot_timeout` | VM boot timeout in seconds (default: 60) |
+| `accel` | Hardware accelerator (`"auto"`, specific `Accelerator`, or `None`) |
+| `disk_size` | Expand guest disk on start (e.g., `"10G"`) |
+| `enable_display` | Enable VNC display for GUI input / screenshots (default: `False`) |
+
+### ExecuteResult
+
+```python
+result = await sb.execute("ls /")
+print(result.stdout) # standard output
+print(result.stderr) # standard error
+print(result.exit_code) # 0 = success
+```
+
+---
+
+## quicksand-core Module Layout
+
+`quicksand_core` is organized along two axes: **{host, qemu}** × **{concern}**.
+
+```
+quicksand_core/
+├── _types.py # Shared constants, config dataclasses, state dataclasses
+├── host/ # Host-side, not QEMU-specific
+│ ├── arch.py # Architecture enum + detection
+│ ├── os_.py # OS detection, accelerator detection, OS-level config
+│ ├── quicksand_guest_agent_client.py # HTTP client for host→guest agent communication
+│ └── smb.py # SMB server hierarchy (QuicksandSMBServer, WindowsSMBServer)
+├── qemu/ # QEMU-specific subsystems
+│ ├── arch.py # QEMU architecture configs (machine types, binary names)
+│ ├── platform.py # PlatformConfig, QEMU command building, runtime detection
+│ ├── process.py # VMProcessManager — QEMU subprocess lifecycle
+│ ├── overlay.py # OverlayManager — qcow2 overlay operations
+│ ├── qmp.py # QMPClient — TCP JSON-RPC for snapshots, input, display
+│ ├── save.py # create_save(), SaveManifest
+│ └── image_resolver.py # Image resolution via entry points and save directories
+├── sandbox/ # Sandbox orchestration (mixin architecture)
+│ ├── _sandbox.py # Sandbox class (composes all mixins)
+│ ├── _lifecycle.py # _LifecycleMixin — start, stop, boot sequence
+│ ├── _execution.py # _ExecutionMixin — execute
+│ ├── _checkpoints.py # _CheckpointMixin — save, load, checkpoint, revert
+│ ├── _input.py # _InputMixin — screenshot, keyboard, mouse
+│ ├── _mounts.py # _MountMixin — CIFS mount operations (boot-time + dynamic)
+│ └── _protocol.py # _SandboxProtocol — shared mixin interface
+└── utils/ # General host utilities (hashing, paths, network)
+```
+
+### Architectural Axes
+
+- **`host/`** — things that run on the host but are not QEMU-specific: OS detection, accelerator probing, the HTTP client that talks to the guest agent, and the cross-platform SMB server for CIFS file sharing. These would survive a switch to Firecracker or vfkit.
+
+- **`qemu/`** — everything QEMU-specific: architecture configs, QEMU command line construction, the QEMU subprocess manager, overlay/checkpoint machinery, and the QMP client.
+
+- **`sandbox/`** — orchestration layer that coordinates `host/` and `qemu/` through the mixin pattern.
+
+---
+
+## Sandbox Mixin Architecture
+
+`Sandbox` is built by composing six mixins, each responsible for one concern:
+
+```python
+class Sandbox(_ExecutionMixin, _CheckpointMixin, _SaveMixin, _InputMixin, _LifecycleMixin, _MountMixin):
+ ...
+```
+
+All mixins share state through flat typed attributes declared on `_SandboxProtocol`. There are no wrapper dataclasses. Each piece of state is a direct field on the sandbox instance (e.g., `_runtime_info`, `_resolved_image`, `_resolved_accel`, `_overlay_path`, `_qmp_client`, `_vnc_port`, etc.).
+
+---
+
+## Platform Abstraction
+
+### Host detection (`host/`)
+
+`host/arch.py` provides `Architecture` (enum: X86_64, ARM64) and host CPU detection.
+
+`host/os_.py` provides OS-level configuration including accelerator detection:
+
+| Class | Accelerator | Disk AIO | microvm |
+|-------|-------------|----------|---------|
+| `LinuxConfig` | KVM | io_uring | Yes |
+| `DarwinConfig` | HVF | default | No |
+| `WindowsConfig` | WHPX | default | No |
+
+### QEMU configuration (`qemu/`)
+
+`qemu/arch.py` provides QEMU-specific arch configuration:
+
+| Class | Default Machine | QEMU Binary | virtio Bus |
+|-------|-----------------|-------------|------------|
+| `X86_64Config` | Q35 (or microvm with KVM) | qemu-system-x86_64 | PCI or MMIO |
+| `ARM64Config` | VIRT | qemu-system-aarch64 | MMIO |
+
+`qemu/platform.py` composes arch + OS into `PlatformConfig` and provides:
+- `build_qemu_command(...)` — generates the full QEMU command line
+- `get_platform_config()` — cached singleton for the current host
+- `get_runtime()` — locates QEMU binaries (prefers `quicksand-qemu`, falls back to system)
+- `get_accelerator()` — detects the best available accelerator
+
+---
+
+## QEMU Subsystems
+
+### VMProcessManager (`qemu/process.py`)
+
+Manages the QEMU subprocess: start, terminate (graceful then SIGKILL), console log capture, and unexpected-exit detection.
+
+### OverlayManager (`qemu/overlay.py`)
+
+Creates qcow2 overlays backed by base images via `qemu-img create -f qcow2 -b <base>`. Each sandbox gets a thin overlay (~256KB initially). The base image is never modified.
+
+Supports overlay chains. Multiple overlays can be stacked, each backed by the previous one. The `get_overlay_chain()` method traverses backing files from top to base to reconstruct the chain. `_prepare_restored_chain()` fixes backing file paths via `qemu-img rebase -u` when restoring from a save.
+
+### QMPClient (`qemu/qmp.py`)
+
+Async JSON-RPC client over TCP (`-qmp tcp:127.0.0.1:{port},server,nowait`). TCP transport is used instead of Unix sockets for Windows compatibility. After connecting, completes the QMP capability negotiation, then accepts `execute(command, **args)` calls.
+
+QMP is used for both VM control and input injection:
+
+| QMP Command | Method | Purpose |
+|-------------|--------|---------|
+| `blockdev-snapshot-sync` | `_CheckpointMixin.save()` | Hot checkpointing — pivot to new overlay |
+| `savevm` / `loadvm` | `checkpoint()` / `revert()` | In-session RAM+disk snapshots |
+| `send-key` | `type_text()`, `press_key()` | Keyboard input injection |
+| `input-send-event` | `mouse_move()`, `mouse_click()` | Mouse input injection (absolute coordinates) |
+| `screendump` | `screenshot()` | Capture guest framebuffer |
+| `query-mice` | `query_mouse_position()` | Get mouse device state |
+
+### Save creation (`qemu/save.py`)
+
+`create_save()` packages an overlay chain + manifest into a directory at `.quicksand/sandboxes/<name>/`. Returns a `SaveManifest`.
+
+---
+
+## Host Communication (`host/`)
+
+### QuicksandGuestAgentClient (`host/quicksand_guest_agent_client.py`)
+
+HTTP client for host→guest communication over the QEMU user-mode network port forward. Authenticates with a per-session bearer token passed via kernel cmdline. Uses exponential backoff for transient errors during startup.
+
+### SMBServer (`host/smb.py`)
+
+Cross-platform SMB file sharing. `SMBServer` is the abstract base class. `QuicksandSMBServer` (macOS/Linux, pure-Python SMB3 via QEMU guestfwd) and `WindowsSMBServer` (PowerShell) are concrete implementations. Shares are named `QUICKSAND0`, `QUICKSAND1`, etc. Supports dynamic add/remove of shares at runtime for hot-mounting.
+
+---
+
+## Guest Agent (`packages/dev/quicksand-image-tools/quicksand-guest-agent/`)
+
+Minimal Rust binary running inside the VM:
+- Axum HTTP server on configurable port (~1MB binary)
+- Bearer token authentication (token passed via kernel cmdline, read from `/proc/cmdline`)
+- Multi-threaded tokio runtime for concurrent request handling
+- Compiled during Docker image builds via a multi-stage build
+
+Endpoints:
+
+| Endpoint | Method | Purpose |
+|----------|--------|---------|
+| `/authenticate` | POST | Validate bearer token |
+| `/execute` | POST | Run shell command, return `{stdout, stderr, exit_code}` |
+| `/execute_stream` | POST | Server-Sent Events streaming of command output |
+| `/ping` | GET | Health check, returns `{pong: bool, pid: uint}` |
+
+---
+
+## File Sharing
+
+All mounts (boot-time and dynamic) use CIFS over QEMU's slirp gateway. The host runs an SMB server. The guest mounts shares via `mount -t cifs`.
+
+### Architecture
+
+```
+Host Guest (10.0.2.15)
+┌──────────────────────────┐ ┌─────────────────────┐
+│ quicksand-smb │ │ mount -t cifs │
+│ (pure-Python SMB3) │◄── guestfwd ───│ //10.0.2.100:445 │
+│ spawned per-connection │ (QEMU inetd) │ /mnt/data │
+│ via stdin/stdout │ │ │
+└──────────────────────────┘ └─────────────────────┘
+```
+
+**SMB server hierarchy** (`host/smb.py`):
+- `SMBServer` — abstract base class with `start()`, `stop()`, `add_share()`, `remove_share()`
+- `QuicksandSMBServer` — macOS/Linux: pure-Python SMB3 server (`quicksand-smb`) spawned per-connection by QEMU's `guestfwd` in inetd mode (stdin/stdout). No TCP port opened on the host, no external dependencies.
+- `WindowsSMBServer` — Windows: uses native `New-SmbShare` / `Remove-SmbShare` via PowerShell.
+- `create_smb_server()` — factory that returns the appropriate implementation.
+
+### Boot-time mounts
+
+Declared via the `mounts` kwarg to `Sandbox()`:
+```python
+Sandbox(
+ image="ubuntu",
+ mounts=[Mount("/host/data", "/mnt/data", readonly=True)],
+)
+```
+
+After the guest agent connects, `_mount_shares()` creates shares via `add_share()` and mounts them in the guest via `mount -t cifs`.
+
+### Dynamic hot-mounts
+
+Added to a running sandbox via `mount()` / `unmount()`:
+```python
+handle = await sb.mount("/host/data", "/mnt/data")
+await sb.execute("ls /mnt/data")
+await sb.unmount(handle)
+```
+
+Reuses the same SMB server instance (lazily started on first mount). No QEMU restart or pre-allocation is needed. CIFS is network-based, so shares can be added at any time.
+
+### Network requirement
+
+Mounts work with `MOUNTS_ONLY` (default) or `FULL` network modes. In `MOUNTS_ONLY` mode, QEMU uses `restrict=on` but sets up guestfwd tunnels so the guest can reach the SMB server without internet access. In `FULL` mode, the guest reaches the SMB server directly via the slirp gateway (10.0.2.2). `NONE` disables networking entirely and does not support CIFS mounts (use 9p mounts instead).
+
+### Guest-side mount command
+
+```bash
+sudo mount -t cifs //10.0.2.100/QUICKSAND0 /mnt/data -o username=guest,password=,sec=none,vers=3.0,port=445
+```
+
+In `MOUNTS_ONLY` mode, `10.0.2.100` is the guestfwd virtual IP. QEMU routes guest connections to the SMB server's stdin/stdout. In `FULL` mode, the guest connects to the host via the slirp gateway (`10.0.2.2`).
+
+---
+
+## Save and Persistence
+
+### Hot Save
+
+`save()` uses QMP `blockdev-snapshot-sync` to atomically pivot the VM to a new overlay. The existing overlay is frozen and consistent, and the VM keeps running:
+
+```
+1. sync guest filesystem buffers (via guest agent)
+2. QMP blockdev-snapshot-sync → QEMU pivots writes to new overlay; current overlay frozen
+3. update _overlay_path to the new overlay
+4. copy the frozen overlay chain + manifest → .quicksand/sandboxes/<name>/
+```
+
+Because sandboxes always start from a fresh or load-restored overlay (directly backed by the base image), the frozen overlay is always self-contained. No rebase is needed.
+
+QEMU is launched with `-qmp tcp:127.0.0.1:{port},server,nowait` and the QMP client connects during `start()`.
+
+### Persistence Model
+
+| How | Mechanism | Use case |
+|-----|-----------|----------|
+| `Sandbox(image="X", save="Y")` | Auto-save to `.quicksand/sandboxes/Y/` on `stop()` | Persist work across sessions |
+| `Sandbox(image="X")` where `X` is a save name | Load from `.quicksand/sandboxes/X/` on `start()` | Resume from saved state |
+| `await sb.save("name")` | Manual hot save, VM keeps running | Mid-session snapshot to disk |
+| `await sb.checkpoint("tag")` | Ephemeral in-session snapshot (RAM + disk), not persisted | In-session rollback points |
+| `await sb.revert("tag")` | Restore VM to a named in-session checkpoint | Roll back during a session |
+
+Saves are the only persistence mechanism. There are no persistent overlay directories. Every sandbox runs from a temp overlay that is discarded on stop (unless `save=` causes an auto-save first).
+
+### Save Format (v6)
+
+A directory at `.quicksand/sandboxes/<name>/` containing:
+- `manifest.json` — version (6), config (`SandboxConfig`), arch, overlay chain list
+- `overlays/0.qcow2` — bottom overlay (backed by the base image)
+- `overlays/1.qcow2`, `overlays/2.qcow2`, ... — subsequent overlays in the chain (each backed by the previous)
+
+The overlay chain is stored bottom-to-top. `overlays/0.qcow2` is backed by the base image, and each subsequent overlay is backed by the previous one. Only session-local overlays are stored. Overlays from installed packages are resolved by name at load time. On restore, backing file paths are fixed via `qemu-img rebase -u`.
+
+`save()` returns a `SaveManifest` with fields: `version`, `config` (`SandboxConfig`), `arch`.
+
+---
+
+## Desktop Sandbox Architecture
+
+Desktop sandboxes extend headless sandboxes with a full graphical environment. When `enable_display=True`, QEMU creates additional virtual devices and starts a VNC server.
+
+### Display Stack
+
+**Guest side:** Xfce4 desktop environment + LightDM display manager with auto-login. The modesetting Xorg driver renders to the virtio-gpu framebuffer. `SWcursor=true` in xorg.conf ensures the cursor is rendered into the framebuffer (visible in screenshots).
+
+**Host side:** QEMU VNC server on a local port. The `vnc_port` property exposes the port for debugging with a VNC viewer.
+
+### Input Injection
+
+Input is injected from the host via QMP commands, which QEMU translates into virtual hardware events:
+
+- **Keyboard:** QMP `send-key` → virtio-keyboard-pci → Linux kernel → Xorg. Characters are mapped to QKeyCode values with shift-key handling. `hold_time=1` (1ms) is used in `type_text()` for speed (default 100ms blocks the QMP connection per character).
+
+- **Mouse:** QMP `input-send-event` with absolute coordinates (0-32767 range) → usb-tablet (via usb-ehci) → Linux kernel → Xorg. Absolute positioning avoids the need for mouse acceleration or relative movement tracking.
+
+### Screenshot Pipeline
+
+1. `screenshot(path)` calls QMP `screendump` to capture the framebuffer
+2. QEMU writes PPM binary (P6). Most builds lack PNG support.
+3. `_convert_to_png()` in `_input.py` converts PPM→PNG using pure Python `struct` + `zlib` (no external tools required)
+4. If the output is already PNG (magic bytes check), it's copied as-is
+
+### QEMU Device Configuration
+
+Headless mode (`enable_display=False`):
+```
+-nographic -vga none -serial stdio
+```
+
+Desktop mode (`enable_display=True`):
+```
+-device virtio-gpu # paravirtualized GPU
+-device virtio-keyboard-pci # paravirtualized keyboard
+-device usb-ehci # USB controller
+-device usb-tablet # USB tablet for absolute mouse positioning
+-vnc 127.0.0.1:{port} # VNC server on localhost
+```
+
+### Desktop Image Variants
+
+| Image | Init System | Desktop | Browser | Size |
+|-------|-------------|---------|---------|------|
+| Alpine Desktop | OpenRC | Xfce4 + LightDM | Chromium | ~300MB |
+| Ubuntu Desktop | systemd | Xfce4 + LightDM | Firefox ESR | ~600MB |
+
+Both use auto-login (no password prompt), Mesa software rendering (`LIBGL_ALWAYS_SOFTWARE=1`), and the quicksand guest agent for command execution.
+
+---
+
+## Image Distribution
+
+### Installing Images
+
+Images are installed via the `quicksand install` CLI, which downloads platform-specific wheels from GitHub releases:
+```bash
+quicksand install qemu # bundled QEMU binaries
+quicksand install ubuntu # Ubuntu 24.04 headless
+quicksand install alpine # Alpine 3.21 headless
+quicksand install alpine-desktop # Alpine 3.21 + Xfce4
+quicksand install ubuntu-desktop # Ubuntu 24.04 + Xfce4
+quicksand install all # everything (QEMU + all images + dev tools)
+```
+
+Each image package provides:
+- `<Distro>Sandbox` — Sandbox subclass with pre-configured defaults (accepts `**kwargs`)
+- An `ImageProvider` (a `typing.Protocol`) registered as an entry point
+
+### Image Discovery
+
+Image packages register via `quicksand.images` entry points:
+```toml
+[project.entry-points."quicksand.images"]
+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 Bundle Format (.quicksand)
+
+Images can also be distributed as `.quicksand` bundles (tar files):
+```
+image.quicksand:
+├── manifest.json # metadata
+├── image.qcow2 # disk image
+├── image.kernel # kernel (vmlinuz)
+└── image.initrd # initrd/initramfs
+```
+
+The lifecycle mixin auto-unpacks `.quicksand` bundles during `start()`.
+
+---
+
+## QEMU Command Construction
+
+`qemu/platform.py:build_qemu_command()` assembles the full command from `RuntimeInfo`, individual path arguments (`kernel_path`, `initrd_path`, `overlay_path`), `ResolvedAccelerator`, and config. The key flags and rationale:
+
+### Machine and resources
+
+```
+-nodefaults # blank slate — only explicitly configured devices
+-machine {type} # microvm (Linux x86_64+KVM) or q35 (x86_64 other) or virt (ARM64)
+-m {memory} # guest RAM
+-smp {cpus} # virtual CPU count
+```
+
+`-nodefaults` prevents QEMU from creating its usual set of default devices (floppy, CD-ROM, VGA, serial). Every device is explicit.
+
+`microvm` is an ultra-minimal machine type without PCI or ACPI. It boots ~4x faster than Q35 because there's no device enumeration overhead. It uses virtio-mmio devices instead of virtio-pci. Only available on Linux x86_64 + KVM.
+
+### CPU and acceleration
+
+```
+-cpu host # expose real host CPU features (with hardware accel)
+-accel {kvm|hvf|whpx} # hardware virtualization
+```
+
+`-cpu host` passes the physical CPU's feature flags through to the guest, providing near-native performance. ARM64 without hardware acceleration uses `-cpu max` (software emulation requires an explicit model).
+
+Acceleration is auto-detected. KVM is found via `/dev/kvm`, HVF via `sysctl kern.hv_support`, and WHPX via PowerShell WMI query. Falls back to TCG (software emulation, ~10-100x slower) when none are available.
+
+### Storage with IOThreads
+
+```
+-object iothread,id=iothread0
+-drive file={overlay},format=qcow2,if=none,id=drive0,aio={io_uring|threads}
+-device virtio-blk-{pci|device},drive=drive0,iothread=iothread0
+```
+
+`if=none` creates the drive backend without auto-attaching a device, so we can attach it manually with an iothread. IOThreads offload disk I/O processing to a dedicated thread, improving concurrent I/O throughput on all platforms.
+
+`aio=io_uring` (Linux only) uses the modern io_uring kernel API instead of blocking threads for async I/O, reducing disk latency by ~50%. Falls back to `threads` on macOS and Windows.
+
+`virtio-blk-pci` (Q35/VIRT machines) or `virtio-blk-device` (microvm) is the paravirtualized block device. It is much faster than emulated IDE or SCSI.
+
+### Display and console
+
+Headless mode:
+```
+-nographic # no graphical window
+-vga none # no VGA hardware emulation
+-serial stdio # serial console → terminal (for boot log capture)
+```
+
+Quicksand runs headless by default. `-nographic` alone still emulates VGA hardware. `-vga none` eliminates it entirely. `-serial stdio` connects the VM's console to the parent process's stdio, allowing boot log capture for debugging.
+
+Desktop mode (`enable_display=True`):
+```
+-device virtio-gpu # paravirtualized GPU
+-device virtio-keyboard-pci # paravirtualized keyboard
+-device usb-ehci # USB 2.0 controller
+-device usb-tablet # absolute-position mouse
+-vnc 127.0.0.1:{vnc_port} # VNC server on localhost
+```
+
+virtio-gpu provides a paravirtualized display. The usb-tablet provides absolute mouse positioning (0-32767 range), which avoids the complexity of relative mouse acceleration. VNC is bound to localhost only for security.
+
+### Direct kernel boot
+
+```
+-kernel {vmlinuz}
+-initrd {initrd.img}
+-append "root=/dev/vda rw console=ttyS0 quiet quicksand_token={token} quicksand_port={port} ..."
+```
+
+Direct kernel boot skips BIOS, UEFI, and the bootloader (GRUB etc.), cutting boot time significantly. The kernel cmdline passes agent configuration (`quicksand_token`, `quicksand_port`) that the guest agent reads from `/proc/cmdline` at startup. Windows adds `noapic` to work around IO-APIC issues with WHPX.
+
+### Networking
+
+```
+-nic user,model=virtio,restrict={on|off},hostfwd=tcp:127.0.0.1:{port}-:{port}
+-global virtio-net-pci.romfile= # disable PXE boot ROM (saves ~100-200ms)
+```
+
+User-mode networking (SLIRP) requires no root or admin privileges. The guest gets a private IP (`10.0.2.15`), and QEMU acts as a NAT router. `restrict=on` (`NetworkMode.MOUNTS_ONLY`, default) blocks guest-initiated outbound connections, but guestfwd tunnels allow the guest to reach the host SMB server for mounts. `restrict=off` (`NetworkMode.FULL`) enables full bidirectional access including internet. `NetworkMode.NONE` omits the NIC entirely.
+
+Port forwarding (`hostfwd`) enables host→guest communication for the agent API.
+
+### QMP
+
+```
+-qmp tcp:127.0.0.1:{port},server,nowait
+```
+
+Starts the QMP server on a random free port alongside QEMU. TCP transport is used instead of a Unix socket for Windows compatibility. The host QMPClient connects during `start()` after the guest agent is up.
+
+### Performance by platform
+
+| Platform | Machine | Disk AIO | IOThreads | Boot speedup |
+|----------|---------|----------|-----------|--------------|
+| Linux x86_64 + KVM | microvm | io_uring | Yes | ~4x |
+| Linux ARM64 + KVM | virt | io_uring | Yes | baseline |
+| macOS (HVF) | q35/virt | threads | Yes | baseline |
+| Windows (WHPX) | q35 | threads | Yes | baseline |
+| Any + TCG | q35/virt | varies | Yes | baseline |
+
+---
+
+## Boot Sequence
+
+### Headless
+
+1. QEMU loads kernel directly (no bootloader)
+2. initrd mounts the qcow2 overlay as root
+3. Init system (systemd/OpenRC) starts the guest agent
+4. Agent reads `quicksand_token` and `quicksand_port` from `/proc/cmdline`
+5. Agent listens on HTTP port
+6. QMP server starts alongside QEMU
+7. Host connects and authenticates with the guest agent
+8. Host connects QMPClient to the QMP port
+9. Host starts SMB server, mounts CIFS shares in guest (if mounts configured)
+10. Sandbox ready
+
+### Desktop
+
+1-6. Same as headless
+7. Host connects and authenticates with the guest agent
+8. Host connects QMPClient to the QMP port
+9. Host starts SMB server, mounts CIFS shares in guest (if mounts configured)
+10. VNC port is recorded from QEMU launch args
+11. LightDM starts Xfce4 session (auto-login, no password)
+12. Sandbox ready. `screenshot()`, `type_text()`, and `mouse_*()` are now available
+
+---
+
+## Key Files
+
+| File | Purpose |
+|------|---------|
+| `quicksand_core/sandbox/_sandbox.py` | `Sandbox` class — composes all mixins, `stop()` auto-save logic |
+| `quicksand_core/sandbox/_lifecycle.py` | VM start/stop, disk setup, agent/QMP connection |
+| `quicksand_core/sandbox/_execution.py` | `execute` |
+| `quicksand_core/sandbox/_checkpoints.py` | `save`, `checkpoint`, `revert` |
+| `quicksand_core/sandbox/_input.py` | `screenshot`, `type_text`, `press_key`, `mouse_move`, `mouse_click` |
+| `quicksand_core/sandbox/_mounts.py` | CIFS mount orchestration (boot-time + dynamic hot-mounts) |
+| `quicksand_core/sandbox/_protocol.py` | `_SandboxProtocol` — shared mixin interface |
+| `quicksand_core/_types.py` | Type definitions, constants, `SandboxConfig`, `Key`, `NetworkMode` |
+| `quicksand_core/host/arch.py` | `Architecture` enum and host CPU detection |
+| `quicksand_core/host/os_.py` | OS configs, accelerator detection |
+| `quicksand_core/host/quicksand_guest_agent_client.py` | HTTP client for guest agent |
+| `quicksand_core/host/smb.py` | SMB server hierarchy (SMBServer ABC, QuicksandSMBServer, WindowsSMBServer) |
+| `quicksand_core/qemu/arch.py` | QEMU arch configs (`X86_64Config`, `ARM64Config`) |
+| `quicksand_core/qemu/platform.py` | `PlatformConfig`, QEMU command building, runtime detection |
+| `quicksand_core/qemu/process.py` | `VMProcessManager` — QEMU subprocess lifecycle |
+| `quicksand_core/qemu/overlay.py` | `OverlayManager` — qcow2 overlay creation and chain management |
+| `quicksand_core/qemu/qmp.py` | `QMPClient` — TCP QMP for snapshots, input, and display |
+| `quicksand_core/qemu/save.py` | `create_save()`, `SaveManifest` |
+| `quicksand_core/qemu/image_resolver.py` | Image resolution via entry points and save directories |
+| `packages/dev/quicksand-image-tools/quicksand-guest-agent/` | Rust guest agent source |
+
+---
+
+## Glossary
+
+| Term | Definition |
+|------|------------|
+| **[QEMU](https://www.qemu.org/docs/master/)** | Quick Emulator — open-source machine emulator and virtualizer used by quicksand to run VMs with hardware acceleration. |
+| **[qcow2](https://www.qemu.org/docs/master/system/images.html#cmdoption-image-formats-arg-qcow2)** | QEMU Copy-On-Write v2 — disk image format supporting snapshots, compression, and backing files. |
+| **[Overlay](https://www.qemu.org/docs/master/system/images.html#disk-image-backing-files)** | A qcow2 that uses another image as its backing file. Writes go to the overlay; reads fall through to the base. Keeps the base image pristine. |
+| **[Direct kernel boot](https://www.qemu.org/docs/master/system/linuxboot.html)** | Loading the Linux kernel directly via QEMU's `-kernel` flag, bypassing BIOS/bootloaders. Cuts boot time from ~10s to ~2-3s. |
+| **initrd** | Initial ramdisk — a temporary root filesystem loaded into memory at boot to mount the real root. |
+| **Kernel cmdline** | Parameters passed to the Linux kernel via QEMU's `-append` flag; readable from `/proc/cmdline` inside the VM. Quicksand passes the agent token and port this way. |
+| **[Hardware acceleration](https://www.qemu.org/docs/master/system/introduction.html#virtualisation-accelerators)** | Using CPU virtualization extensions for near-native VM performance: **KVM** (Linux), **HVF** (macOS), **WHPX** (Windows). |
+| **[TCG](https://www.qemu.org/docs/master/devel/tcg.html)** | Tiny Code Generator — QEMU's software emulation fallback. ~10-50x slower but works everywhere. |
+| **[Machine type](https://www.qemu.org/docs/master/system/invocation.html#hxtool-1)** | Virtual hardware platform: **microvm** (ultra-minimal, ~4x faster boot, Linux x86_64+KVM only), **Q35** (modern Intel chipset, x86_64), **VIRT** (ARM64 paravirt). |
+| **[virtio](https://www.qemu.org/docs/master/system/devices/virtio.html)** | Paravirtualized I/O — efficient virtual devices where the guest knows it's virtualized. Used for disk, network, and filesystem sharing. |
+| **CIFS** | Common Internet File System — the protocol used by quicksand for host→guest file sharing. The host runs a pure-Python SMB3 server (`quicksand-smb`); the guest mounts via `mount -t cifs`. |
+| **[User-mode networking](https://www.qemu.org/docs/master/system/devices/net.html#using-the-user-mode-network-stack)** | QEMU's built-in NAT (slirp). Guest gets a private IP (10.0.2.x), host gateway at 10.0.2.2. `restrict=on` blocks guest outbound but guestfwd tunnels still work; `restrict=off` allows full bidirectional. |
+| **[QMP](https://www.qemu.org/docs/master/interop/qmp-intro.html)** | QEMU Machine Protocol — JSON-RPC protocol for host-side VM control (block snapshots, input injection, display capture). TCP transport. |
+
+---
+
+## References
+
+- [QEMU System Emulation User's Guide](https://www.qemu.org/docs/master/system/invocation.html)
+- [QEMU Machine Protocol](https://www.qemu.org/docs/master/interop/qmp-intro.html)
+- [qemu-img Documentation](https://qemu.readthedocs.io/en/latest/tools/qemu-img.html)
+- [QEMU 9pfs Setup Guide](https://wiki.qemu.org/Documentation/9psetup)
+- [VirtIO Devices](https://www.qemu.org/docs/master/system/devices/virtio/index.html)
diff --git a/docs/user-guide/01-installation.md b/docs/user-guide/01-installation.md
new file mode 100644
index 0000000..a882249
--- /dev/null
+++ b/docs/user-guide/01-installation.md
@@ -0,0 +1,150 @@
+# Installation
+
+*See [Under the Hood: Installation](../under-the-hood/01-installation.md) for how these packages map to QEMU binaries and disk images.*
+
+::: warning Not yet released to PyPI
+Quicksand is not yet on PyPI. Once released, installation will be `pip install quicksand[qemu,ubuntu]`. For now, install from GitHub or Azure DevOps Artifacts as shown below.
+:::
+
+## Install quicksand
+
+```bash
+pip install git+ssh://[email protected]/microsoft/quicksand#subdirectory=packages/quicksand
+```
+
+This installs the core Python library and CLI. No native dependencies yet. QEMU and VM images are installed separately.
+
+To declare it as a dependency in your `pyproject.toml`:
+
+```toml
+[project]
+dependencies = [
+ "quicksand",
+]
+
+[tool.uv.sources]
+quicksand = { git = "ssh://[email protected]/microsoft/quicksand", subdirectory = "packages/quicksand" }
+```
+
+To pin to a specific release, use a `quicksand/vX.Y.Z` tag:
+
+```toml
+[tool.uv.sources]
+quicksand = { git = "ssh://[email protected]/microsoft/quicksand", subdirectory = "packages/quicksand", tag = "quicksand/v0.9.0" }
+```
+
+### Install from Azure DevOps Artifacts
+
+First, install `keyring` with the Azure Artifacts backend so `uv`/`pip` can authenticate automatically:
+
+```bash
+uv tool install keyring --with artifacts-keyring
+```
+
+Then install quicksand from the feed:
+
+```bash
+uv pip install \
+ --index-url https://[email protected]/msraif/_packaging/packages/pypi/simple/ \
+ --keyring-provider subprocess \
+ 'quicksand[qemu,alpine,ubuntu]'
+```
+
+With this method QEMU and images are included as extras. No separate `quicksand install` step needed.
+
+To declare the feed as a dependency source in your own `pyproject.toml`:
+
+```toml
+[tool.uv]
+keyring-provider = "subprocess"
+
+[[tool.uv.index]]
+name = "pypi"
+url = "https://pypi.org/simple"
+default = true
+
+[[tool.uv.index]]
+name = "azure-msraif"
+url = "https://[email protected]/msraif/_packaging/packages/pypi/simple/"
+
+[project]
+dependencies = [
+ "quicksand[qemu,alpine,ubuntu]",
+]
+```
+
+## Install QEMU and an image
+
+Quicksand bundles its own QEMU, so no system install is needed. Use the `quicksand install` CLI to download platform-specific binaries and images.
+
+```bash
+quicksand install qemu # Bundled QEMU (~15MB on macOS ARM64)
+quicksand install ubuntu # Ubuntu 24.04 headless (~340MB)
+```
+
+That's enough to start using Quicksand:
+
+```python
+from quicksand import Sandbox
+
+async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("echo hello")
+ print(result.stdout)
+```
+
+## Available packages
+
+### QEMU (`quicksand install qemu`)
+
+| | macOS ARM64 | Linux ARM64 | Linux x86_64 | Windows x86_64 |
+|---|---|---|---|---|
+| Download | 14 MB | 15 MB | 15 MB | 43 MB |
+| On disk | 58 MB | 60 MB | 53 MB | 124 MB |
+
+### Images
+
+| Image | Depends on | Display | ARM64 download | ARM64 on disk | Boot p50 | Boot p95 |
+|-------|------------|---------|----------------|---------------|----------|----------|
+| `alpine` | — | No | 73 MB | 74 MB | 0.37s | 0.45s |
+| `ubuntu` | — | No | 341 MB | 346 MB | 0.88s | 0.91s |
+| `alpine-desktop` | `alpine` | Yes | 287 MB | 290 MB | 0.47s | 0.54s |
+| `ubuntu-desktop` | `ubuntu` | Yes | 252 MB | 257 MB | 0.90s | 0.96s |
+| `aif-agent-sandbox` | `ubuntu` | No | ~304 MB | ~308 MB | 0.91s | 0.92s |
+| `aif-cua-agent-sandbox` | `aif-agent-sandbox` | No | ~445 MB | ~450 MB | 0.85s | 1.01s |
+
+Boot times measured on macOS ARM64 (Apple M3 Max, HVF) with `quicksand benchmark -n 5`. First boot is slower due to cold cache.
+
+`quicksand install all` installs QEMU and all images.
+
+Alpine is smaller and boots faster. Ubuntu has a larger package ecosystem. Desktop images are overlays on their base image and add a graphical environment for screenshot/keyboard/mouse interaction. The `aif-*` images are pre-configured agent environments with Python 3.12, browser automation tools, and common AI agent dependencies.
+
+## Verify the installation
+
+```bash
+quicksand images list # Shows installed images
+```
+
+```python
+import asyncio
+from quicksand import Sandbox
+
+async def main():
+ async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("uname -a")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+If this prints a Linux kernel version, everything is working.
+
+## Requirements
+
+- **Python 3.11+**
+- **macOS, Linux, or Windows.** Hardware acceleration is auto-detected (HVF on macOS, KVM on Linux, WHPX on Windows). Software emulation (TCG) is used as a fallback but is much slower.
+- **No root/admin.** QEMU runs as a normal user process.
+- **No Docker.** Quicksand is not container-based (Docker is only needed for *building* new images, not running them).
+
+## Using system QEMU
+
+If you already have QEMU installed, Quicksand will find it on `PATH` as a fallback. But the bundled QEMU (`quicksand install qemu`) is recommended. It's tested and includes the right firmware files.
diff --git a/docs/user-guide/02-sandbox-lifecycle.md b/docs/user-guide/02-sandbox-lifecycle.md
new file mode 100644
index 0000000..68653a4
--- /dev/null
+++ b/docs/user-guide/02-sandbox-lifecycle.md
@@ -0,0 +1,107 @@
+# Sandbox Lifecycle
+
+*See [Under the Hood: Sandbox Lifecycle](../under-the-hood/02-sandbox-lifecycle.md) for how these fields translate to QEMU flags.*
+
+## Quick start
+
+```python
+from quicksand import Sandbox, Mount, NetworkMode, PortForward
+
+async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("uname -a")
+ print(result.stdout)
+# VM is automatically stopped and cleaned up here
+```
+
+The `async with` pattern handles `start()` and `stop()` for you. The VM boots in ~2-3 seconds and is fully isolated from the host.
+
+## Configuration
+
+All configuration is passed as keyword arguments to `Sandbox(...)`:
+
+```python
+sb = Sandbox(
+ image="ubuntu", # Which OS image to use
+ memory="2G", # RAM (default: "512M")
+ cpus=4, # CPU cores (default: 1)
+ enable_display=True, # Enable GUI for screenshots/input (default: False)
+ network_mode=NetworkMode.FULL, # Internet access (default: MOUNTS_ONLY)
+ port_forwards=[PortForward(host=8080, guest=80)],
+ mounts=[ # Share host directories into the VM
+ Mount("/host/code", "/mnt/code"),
+ ],
+ disk_size="10G", # Expand disk (default: image size)
+ accel="auto", # Hardware acceleration (default: auto-detect)
+ extra_qemu_args=[], # Escape hatch for advanced QEMU flags
+)
+```
+
+Most fields have sensible defaults. The minimal call is just `Sandbox(image="ubuntu")`.
+
+## Start modes
+
+**Ephemeral** (default). The VM starts fresh and is discarded on stop.
+
+```python
+async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("apt install -y python3")
+# python3 is gone — the VM was discarded
+```
+
+**Named save.** The VM auto-saves to disk when it stops.
+
+```python
+async with Sandbox(image="ubuntu", save="my-env") as sb:
+ await sb.execute("apt install -y python3")
+# saved to .quicksand/sandboxes/my-env/
+```
+
+**From save.** Resume from a previously saved state.
+
+```python
+async with Sandbox(image="my-env") as sb:
+ result = await sb.execute("python3 --version")
+ # Python 3.x — it's still installed
+```
+
+**Named + from save.** Load a save and auto-save under a new name.
+
+```python
+async with Sandbox(image="my-env", save="my-env-v2") as sb:
+ await sb.execute("pip install numpy")
+# saved to .quicksand/sandboxes/my-env-v2/
+```
+
+## Manual lifecycle
+
+If you need finer control than `async with`:
+
+```python
+sb = Sandbox(image="ubuntu")
+await sb.start()
+
+# ... use the sandbox ...
+
+await sb.stop() # auto-saves if save= was set
+```
+
+## Properties
+
+```python
+sb.is_running # bool — is the VM running?
+sb.accelerator # Accelerator enum — KVM, HVF, WHPX, or TCG
+sb.vnc_port # int | None — VNC port for debugging (if display enabled)
+sb.boot_timeout # float — effective boot timeout in seconds
+sb.active_mounts # list[MountHandle] — currently mounted directories
+```
+
+## Progress callback
+
+Track startup progress:
+
+```python
+def on_progress(stage: str, current: int, total: int):
+ print(f"{stage}: {current}/{total}")
+
+sb = Sandbox(image="ubuntu", progress_callback=on_progress)
+```
diff --git a/docs/user-guide/03-running-commands.md b/docs/user-guide/03-running-commands.md
new file mode 100644
index 0000000..ad3b006
--- /dev/null
+++ b/docs/user-guide/03-running-commands.md
@@ -0,0 +1,97 @@
+# Running Commands
+
+*See [Under the Hood: Running Commands](../under-the-hood/03-running-commands.md) for how commands reach the VM through the guest agent and QEMU's port forwarding.*
+
+## Basic execution
+
+```python
+result = await sb.execute("ls /")
+print(result.stdout) # "bin\nboot\ndev\netc\n..."
+print(result.stderr) # "" (empty if no errors)
+print(result.exit_code) # 0
+```
+
+`execute()` runs a shell command inside the VM and waits for it to finish. It returns an `ExecuteResult` with `stdout`, `stderr`, and `exit_code`.
+
+## Options
+
+```python
+result = await sb.execute(
+ "make test",
+ timeout=300, # Max execution time in seconds (default: 30)
+ cwd="/home/user/project", # Working directory
+ shell="/bin/bash", # Shell to use (default: /bin/sh)
+)
+```
+
+## Checking success
+
+```python
+result = await sb.execute("apt install -y nonexistent-package")
+if result.exit_code != 0:
+ print(f"Failed: {result.stderr}")
+```
+
+An `exit_code` of 0 means success. Anything else is a failure. The command itself never throws an exception on failure. You check `exit_code` instead.
+
+## Streaming output
+
+For long-running commands, you can get output as it arrives instead of waiting for the command to finish:
+
+```python
+def on_stdout(chunk: str):
+ print(f"[stdout] {chunk}", end="")
+
+def on_stderr(chunk: str):
+ print(f"[stderr] {chunk}", end="")
+
+result = await sb.execute(
+ "apt install -y python3",
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+)
+```
+
+The callbacks receive chunks of output in real time via Server-Sent Events. The final `ExecuteResult` still contains the complete stdout/stderr.
+
+## Multi-step workflows
+
+Commands run in independent shell sessions. There's no persistent shell state between calls. Use `&&` to chain commands, or write a script.
+
+```python
+# Each execute() is a fresh shell — cd doesn't persist
+await sb.execute("cd /tmp")
+result = await sb.execute("pwd") # still "/" — not /tmp
+
+# Use && to chain commands in one shell session
+result = await sb.execute("cd /tmp && pwd") # "/tmp"
+
+# Or use cwd= for a working directory
+result = await sb.execute("pwd", cwd="/tmp") # "/tmp"
+```
+
+## Common patterns
+
+**Install packages:**
+```python
+await sb.execute("apt update && apt install -y python3 git curl")
+```
+
+**Run a script from a mounted directory:**
+```python
+handle = await sb.mount("/host/scripts", "/mnt/scripts")
+result = await sb.execute("bash /mnt/scripts/setup.sh")
+```
+
+**Check if something is installed:**
+```python
+result = await sb.execute("which python3")
+installed = result.exit_code == 0
+```
+
+**Capture JSON output:**
+```python
+import json
+result = await sb.execute("cat /etc/os-release | jq -R -s '.'")
+data = json.loads(result.stdout)
+```
diff --git a/docs/user-guide/04-file-exchange.md b/docs/user-guide/04-file-exchange.md
new file mode 100644
index 0000000..4fd6022
--- /dev/null
+++ b/docs/user-guide/04-file-exchange.md
@@ -0,0 +1,103 @@
+# File Exchange
+
+*See [Under the Hood: File Exchange](../under-the-hood/04-file-exchange.md) for how CIFS and 9p mounts work at the QEMU level.*
+
+All examples below assume:
+```python
+from quicksand import Sandbox, Mount, NetworkMode
+```
+
+## Boot-time mounts
+
+Declare directories to share when creating the sandbox:
+
+```python
+async with Sandbox(
+ image="ubuntu",
+ mounts=[
+ Mount("/host/code", "/mnt/code"),
+ Mount("/host/data", "/mnt/data", readonly=True),
+ ],
+) as sb:
+ result = await sb.execute("ls /mnt/code")
+ await sb.execute("python3 /mnt/code/main.py")
+```
+
+Files appear inside the VM at the specified guest path. Changes to non-readonly mounts are visible on both sides immediately.
+
+## Dynamic hot-mounts
+
+Share a directory into an already-running sandbox:
+
+```python
+async with Sandbox(image="ubuntu") as sb:
+ # Mount at any time after start
+ handle = await sb.mount("/host/project", "/mnt/project")
+
+ await sb.execute("ls /mnt/project")
+ await sb.execute("echo 'new file' > /mnt/project/output.txt")
+
+ # Unmount when done
+ await sb.unmount(handle)
+```
+
+Hot-mounts use the same CIFS file-sharing protocol as boot-time mounts. New shares can be added at any time. No restart is needed.
+
+## Read-only mounts
+
+Prevent the guest from modifying host files:
+
+```python
+# Boot-time
+Mount("/host/data", "/mnt/data", readonly=True)
+
+# Dynamic
+handle = await sb.mount("/host/data", "/mnt/data", readonly=True)
+```
+
+## Getting files out without mounts
+
+If you just need to read a small file from the guest, `execute()` works:
+
+```python
+result = await sb.execute("cat /etc/hostname")
+hostname = result.stdout.strip()
+```
+
+To write a file into the guest:
+
+```python
+await sb.execute("echo 'hello' > /tmp/greeting.txt")
+```
+
+For larger file transfers, mounts are more efficient.
+
+## Listing active mounts
+
+```python
+for handle in sb.active_mounts:
+ print(f"{handle.host_path} → {handle.guest_path} (readonly={handle.readonly})")
+```
+
+## 9p mounts (no network)
+
+If you need file sharing with `NetworkMode.NONE` (no network at all), use 9p:
+
+```python
+sb = Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.NONE,
+ mounts=[Mount("/host/data", "/mnt/data", type="9p")],
+)
+```
+
+9p mounts are configured at launch time and can't be hot-added. They use a virtual device instead of the network stack.
+
+## Which mount type to use
+
+| | CIFS (default) | 9p |
+|---|---|---|
+| Hot-mountable | Yes | No (boot-time only) |
+| Works with `NONE` | No | Yes |
+| Works with `MOUNTS_ONLY` / `FULL` | Yes | Yes |
+| Protocol | Network (SMB3) | Virtual device |
diff --git a/docs/user-guide/05-save-and-rollback.md b/docs/user-guide/05-save-and-rollback.md
new file mode 100644
index 0000000..92da402
--- /dev/null
+++ b/docs/user-guide/05-save-and-rollback.md
@@ -0,0 +1,137 @@
+# Save and Rollback
+
+*See [Under the Hood: Save and Rollback](../under-the-hood/05-save-and-rollback.md) for how checkpoints use QMP `savevm`/`loadvm` and saves use overlay pivoting.*
+
+Quicksand gives agents two kinds of snapshots. **Checkpoints** are for in-session rollback, and **saves** are for persisting to disk.
+
+## Checkpoints (in-session rollback)
+
+A checkpoint captures the entire VM state (RAM, disk, running processes) at a point in time. Reverting snaps the VM back to that exact state.
+
+```python
+async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("apt update")
+
+ # Checkpoint before doing something risky
+ await sb.checkpoint("before-experiment")
+
+ result = await sb.execute("apt install -y some-experimental-package")
+ if result.exit_code != 0:
+ # Something went wrong — roll back everything
+ await sb.revert("before-experiment")
+ # The VM is now exactly as it was before the install attempt
+```
+
+Checkpoints are ephemeral. They live inside the VM's disk image and are lost when the sandbox stops. They're for in-session branching, not for persistence.
+
+You can create multiple checkpoints:
+
+```python
+await sb.checkpoint("step-1")
+await sb.execute("pip install pandas")
+
+await sb.checkpoint("step-2")
+await sb.execute("pip install sklearn")
+
+# Jump back to any checkpoint
+await sb.revert("step-1") # pandas is gone, sklearn is gone
+```
+
+Reverting restores the VM completely, including running processes, open files, and everything else. The VM continues from the exact point when `checkpoint()` was called.
+
+## Saves (persist to disk)
+
+A save copies the VM's disk state to a directory on the host. Unlike checkpoints, saves survive across sessions.
+
+**Manual save.** The VM keeps running.
+
+```python
+async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("apt install -y python3 git")
+ await sb.save("dev-env")
+ # VM is still running — you can keep working
+ await sb.execute("git clone https://...")
+ await sb.save("dev-env-with-repo")
+```
+
+**Auto-save on stop:**
+
+```python
+async with Sandbox(image="ubuntu", save="my-env") as sb:
+ await sb.execute("apt install -y python3")
+# Automatically saved to .quicksand/sandboxes/my-env/ on exit
+```
+
+**Resume from a save:**
+
+```python
+async with Sandbox(image="my-env") as sb:
+ result = await sb.execute("python3 --version")
+ # Python is still installed
+```
+
+Saves only capture disk state (not RAM). The VM boots fresh when loaded from a save, but all installed packages, files, and configuration are preserved.
+
+## Save options
+
+```python
+manifest = await sb.save(
+ "my-env",
+ workspace="/custom/path", # Save location (default: .quicksand/)
+ compress=True, # Compress overlays for smaller saves
+ delete_checkpoints=True, # Delete in-session checkpoints before saving
+)
+```
+
+`save()` returns a `SaveManifest` with the save's metadata.
+
+By default, `save()` raises an error if there are active checkpoints (because they can't be restored after the save). Pass `delete_checkpoints=True` to clear them first.
+
+## Validating a save
+
+Check if a save directory is valid without loading it:
+
+```python
+manifest = Sandbox.validate_save(".quicksand/sandboxes/my-env")
+print(manifest.version, manifest.config.image)
+```
+
+## Checkpoint vs save
+
+| | Checkpoint | Save |
+|---|---|---|
+| What's captured | RAM + disk (entire VM state) | Disk only |
+| Persists after stop | No | Yes |
+| VM keeps running | Yes | Yes |
+| Resume behavior | Exact state (running processes, everything) | Fresh boot (but disk state preserved) |
+| Use case | Try something, revert if it fails | Persist progress across sessions |
+
+## Common patterns
+
+**Explore-and-revert:**
+```python
+await sb.checkpoint("clean")
+for approach in approaches:
+ result = await sb.execute(approach)
+ if result.exit_code == 0:
+ break
+ await sb.revert("clean")
+```
+
+**Progressive saves:**
+```python
+await sb.execute("apt install -y build-essential")
+await sb.save("base-tools")
+await sb.execute("apt install -y python3 python3-pip")
+await sb.save("python-env")
+await sb.execute("pip install -r requirements.txt")
+await sb.save("project-ready")
+```
+
+**Save before long-running work:**
+```python
+await sb.save("before-training")
+result = await sb.execute("python3 train.py", timeout=3600)
+if result.exit_code == 0:
+ await sb.save("after-training")
+```
diff --git a/docs/user-guide/06-desktop-control.md b/docs/user-guide/06-desktop-control.md
new file mode 100644
index 0000000..2117b2a
--- /dev/null
+++ b/docs/user-guide/06-desktop-control.md
@@ -0,0 +1,129 @@
+# Desktop Control
+
+*See [Under the Hood: Desktop Control](../under-the-hood/06-desktop-control.md) for how display, keyboard, and mouse map to QEMU devices and QMP commands.*
+
+Desktop sandboxes give agents a full graphical Linux environment. This includes a real desktop with a window manager, browser, and file manager. Agents interact with it through screenshots and programmatic keyboard/mouse input.
+
+## Setup
+
+```python
+async with Sandbox(
+ image="ubuntu-desktop", # or "alpine-desktop"
+ enable_display=True, # Required for GUI interaction
+) as sb:
+ await sb.screenshot("screen.png")
+```
+
+Both `image` and `enable_display=True` are needed. Headless images (`"ubuntu"`, `"alpine"`) don't have a desktop environment installed.
+
+## Screenshots
+
+```python
+await sb.screenshot("screen.png")
+```
+
+Captures the current screen as a PNG file on the host. Works regardless of what the guest is doing, even during boot or when the desktop is loading.
+
+## Keyboard
+
+**Type a string:**
+```python
+await sb.type_text("hello world")
+```
+
+Characters are typed one at a time through the virtual keyboard. Shift is handled automatically for uppercase letters and symbols.
+
+**Press a key or combo:**
+```python
+from quicksand import Key
+
+await sb.press_key(Key.RET) # Enter
+await sb.press_key(Key.CTRL, Key.C) # Ctrl+C
+await sb.press_key(Key.ALT, Key.F4) # Alt+F4
+await sb.press_key(Key.CTRL, Key.ALT, Key.T) # Open terminal (Ubuntu)
+```
+
+## Mouse
+
+**Move to a position:**
+```python
+await sb.mouse_move(500, 300)
+```
+
+Coordinates are absolute (0-32767 range on each axis). The cursor goes exactly where you point. There is no acceleration and no drift.
+
+**Click:**
+```python
+await sb.mouse_click("left")
+await sb.mouse_click("right")
+await sb.mouse_click("left", double=True) # Double-click
+```
+
+**Scroll:**
+```python
+await sb.mouse_click("wheel-up")
+await sb.mouse_click("wheel-down")
+```
+
+## Display info
+
+**Get the screen resolution:**
+```python
+width, height = await sb.query_display_size()
+# e.g., (1024, 768)
+```
+
+**Get the current mouse position:**
+```python
+mouse = await sb.query_mouse_position()
+```
+
+**Connect a VNC viewer for debugging:**
+```python
+print(f"VNC port: {sb.vnc_port}")
+# Connect with: vncviewer localhost:{sb.vnc_port}
+```
+
+## Desktop images
+
+| Image | Desktop | Browser | Init | Size |
+|-------|---------|---------|------|------|
+| `alpine-desktop` | Xfce4 + LightDM | Chromium | OpenRC | 287 MB (ARM64) / 310 MB (x86_64) |
+| `ubuntu-desktop` | Xfce4 + LightDM | Firefox ESR | systemd | 252 MB (ARM64) / 263 MB (x86_64) |
+
+Both auto-login (no password prompt) and use software rendering.
+
+## Common patterns
+
+**Screenshot-action loop (CUA agent):**
+```python
+while not done:
+ await sb.screenshot("screen.png")
+ action = agent.decide(read_image("screen.png"))
+
+ if action.type == "click":
+ await sb.mouse_move(action.x, action.y)
+ await sb.mouse_click("left")
+ elif action.type == "type":
+ await sb.type_text(action.text)
+ elif action.type == "key":
+ await sb.press_key(*action.keys)
+```
+
+**Open a URL in the browser:**
+```python
+# Ubuntu desktop
+await sb.execute("firefox 'https://example.com' &")
+import asyncio; await asyncio.sleep(3) # Wait for browser to load
+await sb.screenshot("page.png")
+
+# Alpine desktop
+await sb.execute("chromium-browser 'https://example.com' &")
+```
+
+**Take a screenshot after a command:**
+```python
+await sb.execute("xdg-open /mnt/data/document.pdf &")
+import asyncio; await asyncio.sleep(2)
+await sb.screenshot("document.png")
+```
diff --git a/docs/user-guide/07-network-and-isolation.md b/docs/user-guide/07-network-and-isolation.md
new file mode 100644
index 0000000..e9bf1db
--- /dev/null
+++ b/docs/user-guide/07-network-and-isolation.md
@@ -0,0 +1,98 @@
+# Network and Isolation
+
+*See [Under the Hood: Network and Isolation](../under-the-hood/07-network-and-isolation.md) for how these modes translate to QEMU's SLIRP networking and `restrict=on`.*
+
+All examples below assume:
+```python
+from quicksand import Sandbox, NetworkMode, PortForward
+```
+
+## Default: isolated
+
+By default, the sandbox has no internet access:
+
+```python
+async with Sandbox(image="ubuntu") as sb: # network_mode=MOUNTS_ONLY by default
+ result = await sb.execute("curl https://example.com")
+ # Fails — no internet access
+```
+
+The VM can still share files with the host (via mounts) and communicate with the guest agent. Only outbound internet connections are blocked.
+
+## Enabling internet
+
+```python
+async with Sandbox(image="ubuntu", network_mode=NetworkMode.FULL) as sb:
+ await sb.execute("apt update && apt install -y python3")
+ await sb.execute("pip install requests")
+ await sb.execute("curl https://api.example.com")
+```
+
+## Network modes
+
+| Mode | Internet | File mounts (CIFS) | File mounts (9p) |
+|------|----------|-------------------|------------------|
+| `MOUNTS_ONLY` (default) | No | Yes | Yes |
+| `FULL` | Yes | Yes | Yes |
+| `NONE` | No | No | Yes (9p only) |
+
+## Port forwarding
+
+Expose a service running inside the VM to the host:
+
+```python
+async with Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.FULL,
+ port_forwards=[PortForward(host=8080, guest=80)],
+) as sb:
+ await sb.execute("apt install -y nginx && nginx")
+ # Now accessible at http://localhost:8080 on the host
+```
+
+Multiple port forwards are supported:
+
+```python
+port_forwards=[
+ PortForward(host=8080, guest=80), # HTTP
+ PortForward(host=8443, guest=443), # HTTPS
+ PortForward(host=5432, guest=5432), # PostgreSQL
+]
+```
+
+## Security boundary
+
+The VM provides strong isolation:
+
+- **Separate kernel.** The guest runs its own Linux kernel. A crash or exploit inside the VM doesn't affect the host.
+- **No shared filesystem** by default. The guest can only see files you explicitly mount.
+- **No network** by default. The guest can't reach the internet or the host network unless you opt in.
+- **No root on host.** The entire VM runs as a normal user process. No Docker daemon, no admin privileges.
+
+The agent can execute arbitrary code inside the VM, including installing packages, modifying system files, and running as root, all without any risk to the host. The point is to give the agent a computer it can't break out of.
+
+## Common patterns
+
+**Install dependencies then go offline:**
+```python
+# Phase 1: online
+async with Sandbox(image="ubuntu", network_mode=NetworkMode.FULL, save="with-deps") as sb:
+ await sb.execute("apt update && apt install -y python3 python3-pip")
+ await sb.execute("pip install -r requirements.txt")
+
+# Phase 2: offline (more secure — MOUNTS_ONLY by default)
+async with Sandbox(image="with-deps") as sb:
+ handle = await sb.mount("/host/code", "/mnt/code")
+ await sb.execute("cd /mnt/code && python3 main.py")
+```
+
+**Run a web server and test it:**
+```python
+async with Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.FULL,
+ port_forwards=[PortForward(host=3000, guest=3000)],
+) as sb:
+ await sb.execute("cd /app && node server.js &")
+ # Test from host: requests.get("http://localhost:3000")
+```
diff --git a/docs/user-guide/08-performance.md b/docs/user-guide/08-performance.md
new file mode 100644
index 0000000..f220c5c
--- /dev/null
+++ b/docs/user-guide/08-performance.md
@@ -0,0 +1,80 @@
+# Performance
+
+*See [Under the Hood: Performance](../under-the-hood/08-performance.md) for the specific QEMU flags behind each optimization.*
+
+## Boot time
+
+Measured with `quicksand benchmark -n 5` on macOS ARM64 (Apple M3 Max, HVF):
+
+| Image | Boot p50 | Boot p95 |
+|-------|----------|----------|
+| `alpine` | 0.37s | 0.45s |
+| `ubuntu` | 0.88s | 0.91s |
+| `alpine-desktop` | 0.47s | 0.54s |
+| `ubuntu-desktop` | 0.90s | 0.96s |
+| `aif-agent-sandbox` | 0.91s | 0.92s |
+| `aif-cua-agent-sandbox` | 0.85s | 1.01s |
+
+Boot time is measured from `start()` to sandbox ready (agent connected, mounts configured). The two biggest factors are the machine type (microvm is ~4x faster on Linux) and hardware acceleration (TCG is 10-50x slower).
+
+## CPU performance
+
+With hardware acceleration (KVM, HVF, WHPX), the guest runs at near-native speed. Code compiles, tests run, and browsers load at essentially the same speed as the host.
+
+Without hardware acceleration (TCG), everything is 10-50x slower. TCG is a fallback for environments that don't support virtualization, such as CI containers and nested VMs without passthrough. If your workload is CPU-intensive, hardware acceleration is essential.
+
+Quicksand auto-detects the best accelerator for the current platform. You can check what's in use:
+
+```python
+async with Sandbox(image="ubuntu") as sb:
+ print(sb.accelerator) # Accelerator.KVM, HVF, WHPX, or TCG
+```
+
+## Disk I/O
+
+Quicksand uses several optimizations for disk performance:
+
+- **IOThreads.** Disk I/O runs on a dedicated thread, not QEMU's main loop.
+- **io_uring** (Linux only). Modern async I/O kernel API, with ~50% lower latency.
+- **virtio-blk.** Paravirtualized disk device, much faster than emulated SATA.
+- **qcow2 overlays.** Thin files that only store changes, so sandbox creation is instant.
+
+## Snapshot performance
+
+| Operation | Typical time |
+|-----------|-------------|
+| `checkpoint()` | ~1-2 seconds (saves RAM + disk state) |
+| `revert()` | ~1-2 seconds (restores RAM + disk state) |
+| `save()` | ~1-5 seconds (copies overlay chain to disk) |
+| `save(compress=True)` | ~10-30 seconds (compresses overlays) |
+
+`checkpoint()` and `revert()` use QEMU's built-in snapshot mechanism. `save()` freezes the current overlay and copies it. The VM never pauses.
+
+## Memory
+
+Each sandbox uses as much host RAM as configured:
+
+```python
+Sandbox(image="ubuntu", memory="512M") # 512MB of host RAM
+Sandbox(image="ubuntu", memory="2G") # 2GB of host RAM
+```
+
+Plus ~50-100MB of overhead for the QEMU process itself. Multiple sandboxes run concurrently but each gets its own RAM allocation.
+
+## Platform comparison
+
+| | Linux + KVM | macOS + HVF | Windows + WHPX | Any + TCG |
+|---|---|---|---|---|
+| Boot (Alpine) | < 0.2s (microvm) | 0.37s | ~1-2s | ~10-30s |
+| Boot (Ubuntu) | < 0.5s (microvm) | 0.88s | ~2-3s | ~10-30s |
+| CPU performance | Near-native | Near-native | Near-native | 10-50x slower |
+| Disk AIO | io_uring | threads | threads | threads |
+| Machine type | microvm | Q35/VIRT | Q35 | Q35/VIRT |
+
+## Tips
+
+- **Use the smallest image that works.** Alpine (~75MB) boots faster than Ubuntu (~340MB).
+- **Use `save()` to avoid repeated setup.** Install packages once, save, and resume from the save.
+- **Avoid TCG for CPU-heavy workloads.** If you're in CI, ensure KVM is available (`/dev/kvm`).
+- **Use `disk_size` sparingly.** Expanding the disk adds time to boot.
+- **Concurrent sandboxes share base images.** Running 10 Ubuntu sandboxes doesn't use 10x the disk space, because overlays only store changes.
diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md
new file mode 100644
index 0000000..47af5ec
--- /dev/null
+++ b/docs/user-guide/index.md
@@ -0,0 +1,25 @@
+# Quicksand: User Guide
+
+Quicksand gives you a full Linux virtual machine from Python. Not a container and not a shell. It's a real VM with its own kernel, filesystem, package manager, and optionally a graphical desktop. You can install software, browse the web, run tests, edit files, take screenshots, and drive the mouse and keyboard, all through a Python async API.
+
+The key capabilities:
+
+- **Run commands.** Execute shell commands and get stdout/stderr/exit code.
+- **Share files.** Mount host directories into the VM, at boot or on the fly.
+- **Save and rollback.** Checkpoint before risky operations, revert on failure, save progress to disk.
+- **Control a desktop.** Take screenshots, type text, click buttons, move the mouse.
+- **Network isolation.** The VM is isolated by default, with opt-in internet access.
+
+Everything starts from a `Sandbox`:
+
+```python
+from quicksand import Sandbox
+
+async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("echo hello from inside the VM")
+ print(result.stdout) # "hello from inside the VM"
+```
+
+The VM boots in ~2-3 seconds. When the `async with` block exits, it's gone.
+
+For the QEMU machinery underneath, see [Under the Hood](../under-the-hood/).
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..ccbddf7
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,58 @@
+# Quicksand Examples
+
+Each example is a standalone script that can be run directly.
+
+## Installation
+
+First install the CLI:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+**For most examples (Ubuntu):**
+```bash
+quicksand install ubuntu
+```
+
+**For Alpine examples:**
+```bash
+quicksand install alpine
+```
+
+**For custom image examples:**
+```bash
+quicksand install dev
+```
+
+**For desktop examples:**
+```bash
+quicksand install ubuntu-desktop
+quicksand images install ubuntu-desktop
+```
+
+## Examples
+
+| File | Description | Requires |
+|------|-------------|----------|
+| `simple_usage.py` | Basic command execution | ubuntu |
+| `custom_config.py` | Memory, CPUs, mounts, ports, network | ubuntu |
+| `accelerator_config.py` | Hardware acceleration options | ubuntu |
+| `mounts.py` | Boot-time and hot mounts | ubuntu |
+| `checkpoint_revert.py` | In-session snapshots with revert | ubuntu |
+| `save.py` | Save and reload sandbox state | ubuntu |
+| `save_load_large.py` | Save/load stress test with large packages | ubuntu or alpine |
+| `error_handling.py` | Exit codes, stderr, timeouts | ubuntu |
+| `custom_image.py` | Use a custom image from Dockerfile | ubuntu + dev |
+| `gui_input.py` | Desktop GUI automation (keyboard, mouse) | ubuntu-desktop |
+
+## Running
+
+```bash
+# Run any example directly
+python examples/simple_usage.py
+
+# Or from the examples directory
+cd examples
+python simple_usage.py
+```
diff --git a/examples/accelerator_config.py b/examples/accelerator_config.py
new file mode 100644
index 0000000..7e11fba
--- /dev/null
+++ b/examples/accelerator_config.py
@@ -0,0 +1,46 @@
+"""Hardware acceleration configuration example for quicksand.
+
+By default, quicksand auto-detects the best accelerator:
+- Linux: KVM
+- macOS: HVF (Hypervisor.framework)
+- Windows: WHPX (Windows Hypervisor Platform)
+
+Falls back to TCG (software emulation) when hardware accel unavailable.
+
+Performance optimizations are applied automatically based on platform:
+- Linux x86_64 + KVM: Uses 'microvm' machine type (~4x faster boot)
+- Linux: Uses io_uring for disk I/O (~50% lower latency)
+- All platforms: Uses IOThreads for better concurrent disk I/O
+"""
+
+import asyncio
+import platform
+
+from quicksand import Accelerator, UbuntuSandbox
+
+# Auto-detect accelerator (default behavior)
+# This will use KVM on Linux, HVF on macOS, WHPX on Windows
+accel = "auto"
+
+# Alternatively, force software emulation (slower but always works)
+accel = None
+
+# Or force a specific accelerator based on platform
+if platform.system() == "Linux":
+ # KVM on Linux (requires /dev/kvm access)
+ accel = Accelerator.KVM
+elif platform.system() == "Darwin":
+ # HVF on macOS (Hypervisor.framework)
+ accel = Accelerator.HVF
+elif platform.system() == "Windows":
+ # WHPX on Windows (requires Hyper-V enabled)
+ accel = Accelerator.WHPX
+
+
+async def main():
+ async with UbuntuSandbox(accel=accel) as sb:
+ result = await sb.execute("uname -a")
+ print(f"Kernel: {result.stdout}")
+
+
+asyncio.run(main())
diff --git a/examples/checkpoint_revert.py b/examples/checkpoint_revert.py
new file mode 100644
index 0000000..2b25ee9
--- /dev/null
+++ b/examples/checkpoint_revert.py
@@ -0,0 +1,64 @@
+"""checkpoint/revert example for quicksand.
+
+checkpoint/revert are ephemeral in-session snapshots -- they save full VM state
+(RAM + disk) inside the current overlay so you can roll back during a run.
+
+Unlike save(), checkpoint snapshots:
+ - Are not persisted to a save directory on disk
+ - Are lost when the sandbox stops or when save() is called
+ - Can be restored instantly (no reboot) via revert()
+
+Use them for try/rollback patterns within a single session.
+"""
+
+import asyncio
+
+from quicksand import NetworkMode, UbuntuSandbox
+
+
+async def main():
+ print("Starting sandbox")
+ async with UbuntuSandbox(network_mode=NetworkMode.FULL) as sb:
+ # Install a baseline package
+ print("Sandbox ready")
+ await sb.execute(
+ "apt-get update -qq && apt-get install -y -qq curl",
+ on_stdout=lambda s: print(s, end="", flush=True),
+ on_stderr=lambda s: print(s, end="", flush=True),
+ )
+ print()
+ print("Baseline ready")
+
+ # Save a snapshot before a risky operation
+ await sb.checkpoint("before-experiment")
+ print("Snapshot saved")
+
+ # Do something that might fail or produce unwanted side effects
+ await sb.execute("echo 'experimental config' > /etc/myapp.conf")
+ await sb.execute("touch /tmp/experiment-artifact")
+
+ result = await sb.execute("cat /etc/myapp.conf")
+ print(f"After experiment: {result.stdout.strip()}")
+
+ # Roll back to the pre-experiment state
+ await sb.revert("before-experiment")
+ print("Rolled back")
+
+ # Confirm the changes are gone
+ result = await sb.execute("test -f /etc/myapp.conf && echo exists || echo gone")
+ print(f"Config file: {result.stdout.strip()}") # gone
+
+ result = await sb.execute("test -f /tmp/experiment-artifact && echo exists || echo gone")
+ print(f"Artifact: {result.stdout.strip()}") # gone
+
+ # Continue from the clean state
+ await sb.execute("echo 'stable config' > /etc/myapp.conf")
+ print("Clean run complete")
+
+ # save() requires explicit opt-in to delete checkpoint snapshots
+ # (they can't survive the overlay pivot anyway)
+ await sb.save("after-stable-run", delete_checkpoints=True)
+ print("Save complete (checkpoint snapshots cleared)")
+
+
+asyncio.run(main())
diff --git a/examples/custom_config.py b/examples/custom_config.py
new file mode 100644
index 0000000..9c45ffc
--- /dev/null
+++ b/examples/custom_config.py
@@ -0,0 +1,34 @@
+"""Custom configuration example for quicksand.
+
+Example with custom configuration using UbuntuSandbox.
+"""
+
+import asyncio
+
+from quicksand import Mount, NetworkMode, PortForward, UbuntuSandbox
+
+
+async def main():
+ async with UbuntuSandbox(
+ memory="1G",
+ cpus=2,
+ # Mount a host directory into the sandbox
+ mounts=[
+ Mount("/tmp/host-data", "/mnt/data", readonly=True),
+ ],
+ # Forward ports from guest to host
+ port_forwards=[PortForward(host=8080, guest=80)],
+ # Block internet access (recommended for untrusted code)
+ network_mode=NetworkMode.MOUNTS_ONLY,
+ # Boot timeout
+ boot_timeout=120.0,
+ ) as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(f"OS info:\n{result.stdout}")
+
+ # Access mounted directory
+ result = await sb.execute("ls -la /mnt/data")
+ print(f"Mounted data:\n{result.stdout}")
+
+
+asyncio.run(main())
diff --git a/examples/custom_image.py b/examples/custom_image.py
new file mode 100644
index 0000000..3d1463f
--- /dev/null
+++ b/examples/custom_image.py
@@ -0,0 +1,36 @@
+"""Custom image example for quicksand.
+
+Example for Persona 2: "I Want My Own Image"
+
+Build a custom image from a Dockerfile using quicksand-image-tools CLI.
+Install with: pip install 'quicksand[dev,ubuntu]'
+
+Prerequisites (run once):
+ # Initialize build directory (creates Dockerfile, builds base if needed)
+ quicksand-image-tools init ./my-image ubuntu
+
+Then customize ./my-image/Dockerfile:
+ FROM quicksand/ubuntu-base
+ RUN apt-get update && apt-get install -y nodejs && rm -rf /var/lib/apt/lists/*
+
+And build:
+ quicksand-image-tools build-image ./my-image/Dockerfile -o my-image.qcow2
+"""
+
+import asyncio
+
+from quicksand import Sandbox
+
+
+async def main():
+ # Use a pre-built custom image
+ async with Sandbox(image="my-image", memory="2G", cpus=4) as sb:
+ # Node.js is available because we installed it in the Dockerfile
+ result = await sb.execute("node --version")
+ print(f"Node version: {result.stdout}")
+
+ result = await sb.execute("python3 --version")
+ print(f"Python version: {result.stdout}")
+
+
+asyncio.run(main())
diff --git a/examples/error_handling.py b/examples/error_handling.py
new file mode 100644
index 0000000..164c4e6
--- /dev/null
+++ b/examples/error_handling.py
@@ -0,0 +1,29 @@
+"""Error handling example for quicksand.
+
+Example showing error handling patterns.
+"""
+
+import asyncio
+
+from quicksand import UbuntuSandbox
+
+
+async def main():
+ async with UbuntuSandbox() as sb:
+ # Command that fails
+ result = await sb.execute("exit 42")
+ if result.exit_code != 0:
+ print(f"Command failed with exit code: {result.exit_code}")
+
+ # Command that produces stderr
+ result = await sb.execute("ls /nonexistent 2>&1")
+ if result.stderr:
+ print(f"Error output: {result.stderr}")
+
+ # Command with timeout
+ result = await sb.execute("sleep 100", timeout=2)
+ if result.exit_code == -1:
+ print(f"Command timed out: {result.stderr}")
+
+
+asyncio.run(main())
diff --git a/examples/gui_input.py b/examples/gui_input.py
new file mode 100644
index 0000000..1ebed31
--- /dev/null
+++ b/examples/gui_input.py
@@ -0,0 +1,70 @@
+"""GUI input and screenshot example for quicksand.
+
+Demonstrates QEMU's built-in VNC display with QMP input injection using
+the Ubuntu Desktop image (Xfce4 + LightDM auto-login).
+
+ - UbuntuDesktopSandbox boots directly into an Xfce4 desktop
+ - sb.screenshot() captures the guest framebuffer via QMP screendump
+ - sb.type_text() and sb.press_key() inject keyboard events
+ - sb.mouse_move() and sb.mouse_click() control the pointer
+ - sb.execute() runs commands via the guest agent
+
+To watch live, connect any VNC viewer:
+ vncviewer 127.0.0.1:<sb.vnc_port>
+
+Run with: uv run python examples/gui_input.py
+Requires: pip install quicksand[ubuntu-desktop]
+"""
+
+import asyncio
+import time
+from pathlib import Path
+
+from quicksand import Key
+from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+
+SCREENSHOTS_DIR = Path(".quicksand/gui-screenshots")
+
+
+async def _shot(sb, name: str) -> None:
+ path = SCREENSHOTS_DIR / name
+ await sb.screenshot(path)
+ print(f" screenshot -> {path}")
+
+
+async def main() -> None:
+ SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)
+
+ print("Starting desktop sandbox...")
+ async with UbuntuDesktopSandbox(memory="1G", cpus=2) as sb:
+ print(f"VNC: 127.0.0.1:{sb.vnc_port} (connect any VNC viewer to watch live)")
+
+ # Verify guest agent works
+ result = await sb.execute("cat /etc/os-release | head -3")
+ print(f" OS: {result.stdout.strip()}")
+
+ # Boot screenshot
+ await _shot(sb, "01_boot.png")
+
+ # Wait for Xfce4 to fully start
+ time.sleep(10)
+ await _shot(sb, "02_desktop.png")
+
+ # Open xfce4-terminal and type a command
+ print("Launching terminal...")
+ await sb.execute("DISPLAY=:0 xfce4-terminal --geometry 80x24+50+50 &", timeout=5.0)
+ time.sleep(2)
+ await _shot(sb, "03_terminal.png")
+
+ # Type in the terminal
+ print("Typing in terminal...")
+ await sb.type_text("echo 'hello from quicksand desktop'")
+ await sb.press_key(Key.RET)
+ time.sleep(1.0)
+ await _shot(sb, "04_echo.png")
+
+ print(f"\nDone. Screenshots in {SCREENSHOTS_DIR.absolute()}")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/mounts.py b/examples/mounts.py
new file mode 100644
index 0000000..447cdcf
--- /dev/null
+++ b/examples/mounts.py
@@ -0,0 +1,71 @@
+"""Mount examples for quicksand.
+
+Demonstrates three mount patterns:
+1. Boot-time mounts via constructor (available immediately after start)
+2. Dynamic hot-mounts on a running sandbox
+3. Unmounting to free a share
+"""
+
+import asyncio
+import os
+import tempfile
+from pathlib import Path
+
+from quicksand import Mount, NetworkMode, UbuntuSandbox
+
+
+async def main():
+ # Create some host directories with test data
+ with tempfile.TemporaryDirectory(prefix="quicksand-mount-") as tmpdir:
+ # Directory available at boot
+ init_dir = Path(tmpdir) / "init-data"
+ init_dir.mkdir()
+ (init_dir / "greeting.txt").write_text("Hello from the host (boot-time mount)!\n")
+
+ # Directory mounted later at runtime
+ hot_dir = Path(tmpdir) / "hot-data"
+ hot_dir.mkdir()
+ (hot_dir / "message.txt").write_text("Hello from the host (dynamic mount)!\n")
+
+ # --- 1. Boot-time mount (declared in constructor) ---
+ # CIFS mounts require FULL network (guest must reach host's SMB server)
+ async with UbuntuSandbox(
+ mounts=[Mount(host=str(init_dir), guest="/mnt/init", readonly=True)],
+ network_mode=NetworkMode.FULL,
+ ) as sb:
+ # The boot-time mount is ready immediately
+ result = await sb.execute("cat /mnt/init/greeting.txt")
+ print(f"Boot-time mount: {result.stdout.strip()}")
+
+ # --- 2. Dynamic hot-mount ---
+ handle = await sb.mount(str(hot_dir), "/mnt/hot")
+
+ result = await sb.execute("cat /mnt/hot/message.txt")
+ print(f"Dynamic mount: {result.stdout.strip()}")
+
+ # Write from inside the guest (bidirectional)
+ await sb.execute("echo 'Written by guest' > /mnt/hot/from_guest.txt")
+ result = await sb.execute("cat /mnt/hot/from_guest.txt")
+ print(f"Guest wrote: {result.stdout.strip()}")
+ print(f" Host view: {os.listdir(hot_dir)} {(hot_dir / 'from_guest.txt').read_text()}")
+
+ # Dynamic readonly mount
+ ro_handle = await sb.mount(str(init_dir), "/mnt/hot-ro", readonly=True)
+ result = await sb.execute("cat /mnt/hot-ro/greeting.txt")
+ print(f"Readonly mount: {result.stdout.strip()}")
+
+ result = await sb.execute("touch /mnt/hot-ro/nope 2>&1; echo $?")
+ print(f"Write attempt: exit code {result.stdout.strip()} (expected non-zero)")
+ await sb.unmount(ro_handle)
+
+ # --- 3. Unmount ---
+ await sb.unmount(handle)
+
+ result = await sb.execute("ls /mnt/hot/")
+ out = result.stdout.strip() or "(empty)"
+ print(f"After unmount: {out}")
+
+ print("\nDone.")
+
+
+asyncio.run(main())
diff --git a/examples/save.py b/examples/save.py
new file mode 100644
index 0000000..82e0ed5
--- /dev/null
+++ b/examples/save.py
@@ -0,0 +1,45 @@
+"""Save/load example for quicksand.
+
+save() saves the sandbox disk state (filesystem overlay) to a directory
+so you can skip setup work on subsequent runs. The VM keeps running
+after save() returns. Use Sandbox(image=str(save_path)) to restore.
+"""
+
+import asyncio
+from pathlib import Path
+
+from quicksand import Sandbox, UbuntuSandbox
+
+# Saves are stored as directories under .quicksand/
+save_path = Path(".quicksand/sandboxes/my-save")
+
+
+async def main():
+ # Check if we have a saved directory
+ if save_path.exists():
+ # Load from save - skips setup work
+ print("Loading from save...")
+ sandbox = Sandbox(image=str(save_path))
+ await sandbox.start()
+ else:
+ # First run - do setup and save
+ print("First run - setting up...")
+ sandbox = UbuntuSandbox()
+ await sandbox.start()
+
+ # Do expensive setup work
+ await sandbox.execute("apt-get update && apt-get install -y python3-pip")
+ await sandbox.execute("pip install requests --break-system-packages")
+
+ # Save for next time (writes to .quicksand/sandboxes/my-save/)
+ info = await sandbox.save("my-save")
+ print(f"Saved: {info.version} bytes")
+
+ # Use the sandbox (setup already done if loaded from save)
+ result = await sandbox.execute("python3 -c 'import requests; print(requests.__version__)'")
+ print(f"Requests version: {result.stdout}")
+
+ await sandbox.stop()
+
+
+asyncio.run(main())
diff --git a/examples/save_load_large.py b/examples/save_load_large.py
new file mode 100644
index 0000000..fb93d62
--- /dev/null
+++ b/examples/save_load_large.py
@@ -0,0 +1,136 @@
+"""Save/load stress test with large file writes.
+
+Installs Chromium in a sandbox, saves the state, then loads it in a new
+sandbox and verifies the installation survived.
+
+This exercises the block flush path: without flushing QEMU's write cache
+before the snapshot pivot, large recent writes can be lost in the save.
+
+Supports both Alpine (fast, ~60s) and Ubuntu Desktop (heavier, ~3min).
+Usage:
+ python examples/save_load_large.py # Alpine (default)
+ python examples/save_load_large.py --desktop # Ubuntu Desktop
+"""
+
+import argparse
+import asyncio
+import shutil
+import tempfile
+from pathlib import Path
+
+from quicksand import NetworkMode, Sandbox
+
+SAVE_PATH = Path(tempfile.mkdtemp(prefix="quicksand-save-")) / "chromium-env.tar"
+
+
+def _stream(**kwargs):
+ return dict(
+ on_stdout=lambda s: print(s, end="", flush=True),
+ on_stderr=lambda s: print(s, end="", flush=True),
+ **kwargs,
+ )
+
+
+def run_alpine():
+ from quicksand_alpine import AlpineSandbox
+
+ sandbox_cls = AlpineSandbox
+ sandbox_kwargs = dict(
+ network_mode=NetworkMode.FULL,
+ memory="1G",
+ disk_size="4G",
+ )
+ install_cmd = "apk add --no-cache chromium"
+ version_cmd = "chromium --version"
+ size_cmd = "du -sh /usr/lib/chromium/"
+ binary_check = "ls -la /usr/lib/chromium/chromium && echo OK || echo MISSING"
+ return sandbox_cls, sandbox_kwargs, install_cmd, version_cmd, size_cmd, binary_check
+
+
+def run_desktop():
+ from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+
+ sandbox_cls = UbuntuDesktopSandbox
+ sandbox_kwargs = dict(
+ network_mode=NetworkMode.FULL,
+ memory="4G",
+ disk_size="8G",
+ )
+ # Use imagemagick -- a real deb package with substantial size (~200MB installed)
+ # (chromium-browser on Ubuntu 24.04 is a snap wrapper, not a real deb)
+ install_cmd = (
+ "sudo apt-get update -qq && "
+ "sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq imagemagick"
+ )
+ version_cmd = "convert --version | head -1"
+ size_cmd = (
+ "dpkg-query -W --showformat='${Installed-Size}' imagemagick"
+ " | awk '{printf \"%.0f MB\\n\", $1/1024}'"
+ )
+ binary_check = "which convert && echo OK || echo MISSING"
+ return sandbox_cls, sandbox_kwargs, install_cmd, version_cmd, size_cmd, binary_check
+
+
+async def main():
+ parser = argparse.ArgumentParser(description="Save/load stress test with Chromium")
+ parser.add_argument(
+ "--desktop", action="store_true", help="Use Ubuntu Desktop instead of Alpine"
+ )
+ args = parser.parse_args()
+
+ if args.desktop:
+ print("Using Ubuntu Desktop image")
+ sandbox_cls, sandbox_kwargs, install_cmd, version_cmd, size_cmd, binary_check = (
+ run_desktop()
+ )
+ else:
+ print("Using Alpine image (use --desktop for Ubuntu Desktop)")
+ sandbox_cls, sandbox_kwargs, install_cmd, version_cmd, size_cmd, binary_check = run_alpine()
+
+ # --- Phase 1: Install Chromium and save ---
+ print("\n=== Phase 1: Install Chromium and save ===")
+ async with sandbox_cls(**sandbox_kwargs) as sb:
+ print("Installing chromium (this may take a few minutes)...")
+ result = await sb.execute(install_cmd, timeout=600.0, **_stream())
+ print()
+ if result.exit_code != 0:
+ print(f"Install failed (exit={result.exit_code})")
+ raise SystemExit(1)
+
+ result = await sb.execute(version_cmd)
+ print(f"Installed: {result.stdout.strip()}")
+
+ result = await sb.execute(size_cmd)
+ print(f"Size: {result.stdout.strip()}")
+
+ print(f"Saving to {SAVE_PATH}...")
+ await sb.save(str(SAVE_PATH))
+ print(f"Save complete ({SAVE_PATH.stat().st_size / 1024 / 1024:.1f} MB)")
+
+ # --- Phase 2: Load and verify ---
+ print("\n=== Phase 2: Load saved environment and verify ===")
+ async with Sandbox(
+ image=str(SAVE_PATH),
+ memory=sandbox_kwargs.get("memory"),
+ cpus=sandbox_kwargs.get("cpus"),
+ ) as sb:
+ result = await sb.execute(version_cmd)
+ version = result.stdout.strip()
+ print(f"After load: {version}")
+
+ if result.exit_code == 0 and version:
+ print("SUCCESS: Installation survived save/load")
+ else:
+ print("FAILURE: Package not found after load!")
+ raise SystemExit(1)
+
+ result = await sb.execute(binary_check)
+ print(f"Binary check: {result.stdout.strip()}")
+
+ # Cleanup
+ shutil.rmtree(SAVE_PATH.parent, ignore_errors=True)
+ print("\nDone.")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/simple_usage.py b/examples/simple_usage.py
new file mode 100644
index 0000000..7e116e3
--- /dev/null
+++ b/examples/simple_usage.py
@@ -0,0 +1,34 @@
+"""Simple usage example for quicksand.
+
+Example for Persona 1: "Just Give Me a Sandbox"
+
+This shows the simplest possible usage with the bundled Ubuntu image.
+Install with: pip install quicksand[ubuntu]
+"""
+
+import asyncio
+
+from quicksand import UbuntuSandbox
+
+
+async def main():
+ # Uses the bundled Ubuntu image - no downloads or config needed
+ async with UbuntuSandbox() as sb:
+ # Execute shell commands
+ result = await sb.execute("ls -la /")
+ print(f"Directory listing:\n{result.stdout}")
+
+ # Run multiple commands
+ result = await sb.execute("echo 'hello world' > /tmp/test.txt && cat /tmp/test.txt")
+ print(f"File content: {result.stdout}")
+
+ # Check exit codes
+ result = await sb.execute("exit 42")
+ print(f"Exit code: {result.exit_code}")
+
+ # Run Python (pre-installed in Ubuntu image)
+ result = await sb.execute("python3 -c \"print('Hello from Python!')\"")
+ print(f"Python output: {result.stdout}")
+
+
+asyncio.run(main())
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..34ca281
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,3952 @@
+{
+ "name": "quicksand",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "devDependencies": {
+ "mermaid": "^11.4.1",
+ "vitepress": "^1.6.3",
+ "vitepress-plugin-mermaid": "^2.0.17"
+ }
+ },
+ "node_modules/@algolia/abtesting": {
+ "version": "1.16.1",
+ "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.16.1.tgz",
+ "integrity": "sha512-Xxk4l00pYI+jE0PNw8y0MvsQWh5278WRtZQav8/BMMi3HKi2xmeuqe11WJ3y8/6nuBHdv39w76OpJb09TMfAVQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/autocomplete-core": {
+ "version": "1.17.7",
+ "resolved": "https://registry.npmjs.org/@algolia/autocomplete-core/-/autocomplete-core-1.17.7.tgz",
+ "integrity": "sha512-BjiPOW6ks90UKl7TwMv7oNQMnzU+t/wk9mgIDi6b1tXpUek7MW0lbNOUHpvam9pe3lVCf4xPFT+lK7s+e+fs7Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/autocomplete-plugin-algolia-insights": "1.17.7",
+ "@algolia/autocomplete-shared": "1.17.7"
+ }
+ },
+ "node_modules/@algolia/autocomplete-plugin-algolia-insights": {
+ "version": "1.17.7",
+ "resolved": "https://registry.npmjs.org/@algolia/autocomplete-plugin-algolia-insights/-/autocomplete-plugin-algolia-insights-1.17.7.tgz",
+ "integrity": "sha512-Jca5Ude6yUOuyzjnz57og7Et3aXjbwCSDf/8onLHSQgw1qW3ALl9mrMWaXb5FmPVkV3EtkD2F/+NkT6VHyPu9A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/autocomplete-shared": "1.17.7"
+ },
+ "peerDependencies": {
+ "search-insights": ">= 1 < 3"
+ }
+ },
+ "node_modules/@algolia/autocomplete-preset-algolia": {
+ "version": "1.17.7",
+ "resolved": "https://registry.npmjs.org/@algolia/autocomplete-preset-algolia/-/autocomplete-preset-algolia-1.17.7.tgz",
+ "integrity": "sha512-ggOQ950+nwbWROq2MOCIL71RE0DdQZsceqrg32UqnhDz8FlO9rL8ONHNsI2R1MH0tkgVIDKI/D0sMiUchsFdWA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/autocomplete-shared": "1.17.7"
+ },
+ "peerDependencies": {
+ "@algolia/client-search": ">= 4.9.1 < 6",
+ "algoliasearch": ">= 4.9.1 < 6"
+ }
+ },
+ "node_modules/@algolia/autocomplete-shared": {
+ "version": "1.17.7",
+ "resolved": "https://registry.npmjs.org/@algolia/autocomplete-shared/-/autocomplete-shared-1.17.7.tgz",
+ "integrity": "sha512-o/1Vurr42U/qskRSuhBH+VKxMvkkUVTLU6WZQr+L5lGZZLYWyhdzWjW0iGXY7EkwRTjBqvN2EsR81yCTGV/kmg==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@algolia/client-search": ">= 4.9.1 < 6",
+ "algoliasearch": ">= 4.9.1 < 6"
+ }
+ },
+ "node_modules/@algolia/client-abtesting": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/client-abtesting/-/client-abtesting-5.50.1.tgz",
+ "integrity": "sha512-4peZlPXMwTOey9q1rQKMdCnwZb/E95/1e+7KujXpLLSh0FawJzg//U2NM+r4AiJy4+naT2MTBhj0K30yshnVTA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/client-analytics": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/client-analytics/-/client-analytics-5.50.1.tgz",
+ "integrity": "sha512-i+aWHHG8NZvGFHtPeMZkxL2Loc6Fm7iaRo15lYSMx8gFL+at9vgdWxhka7mD1fqxkrxXsQstUBCIsSY8FvkEOw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/client-common": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/client-common/-/client-common-5.50.1.tgz",
+ "integrity": "sha512-Hw52Fwapyk/7hMSV/fI4+s3H9MGZEUcRh4VphyXLAk2oLYdndVUkc6KBi0zwHSzwPAr+ZBwFPe2x6naUt9mZGw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/client-insights": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/client-insights/-/client-insights-5.50.1.tgz",
+ "integrity": "sha512-Bn/wtwhJ7p1OD/6pY+Zzn+zlu2N/SJnH46md/PAbvqIzmjVuwjNwD4y0vV5Ov8naeukXdd7UU9v550+v8+mtlg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/client-personalization": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/client-personalization/-/client-personalization-5.50.1.tgz",
+ "integrity": "sha512-0V4Tu0RWR8YxkgI9EPVOZHGE4K5pEIhkLNN0CTkP/rnPsqaaSQpNMYW3/mGWdiKOWbX0iVmwLB9QESk3H0jS5g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/client-query-suggestions": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/client-query-suggestions/-/client-query-suggestions-5.50.1.tgz",
+ "integrity": "sha512-jofcWNYMXJDDr87Z2eivlWY6o71Zn7F7aOvQCXSDAo9QTlyf7BhXEsZymLUvF0O1yU9Q9wvrjAWn8uVHYnAvgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/client-search": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/client-search/-/client-search-5.50.1.tgz",
+ "integrity": "sha512-OteRb8WubcmEvU0YlMJwCXs3Q6xrdkb0v50/qZBJP1TF0CvujFZQM++9BjEkTER/Jr9wbPHvjSFKnbMta0b4dQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/ingestion": {
+ "version": "1.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/ingestion/-/ingestion-1.50.1.tgz",
+ "integrity": "sha512-0GmfSgDQK6oiIVXnJvGxtNFOfosBspRTR7csCOYCTL1P8QtxX2vDCIKwTM7xdSAEbJaZ43QlWg25q0Qdsndz8Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/monitoring": {
+ "version": "1.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/monitoring/-/monitoring-1.50.1.tgz",
+ "integrity": "sha512-ySuigKEe4YjYV3si8NVk9BHQpFj/1B+ON7DhhvTvbrZJseHQQloxzq0yHwKmznSdlO6C956fx4pcfOKkZClsyg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/recommend": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/recommend/-/recommend-5.50.1.tgz",
+ "integrity": "sha512-Cp8T/B0gVmjFlzzp6eP47hwKh5FGyeqQp1N48/ANDdvdiQkPqLyFHQVDwLBH0LddfIPQE+yqmZIgmKc82haF4A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/requester-browser-xhr": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/requester-browser-xhr/-/requester-browser-xhr-5.50.1.tgz",
+ "integrity": "sha512-XKdGGLikfrlK66ZSXh/vWcXZZ8Vg3byDFbJD8pwEvN1FoBRGxhxya476IY2ohoTymLa4qB5LBRlIa+2TLHx3Uw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/requester-fetch": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/requester-fetch/-/requester-fetch-5.50.1.tgz",
+ "integrity": "sha512-mBAU6WyVsDwhHyGM+nodt1/oebHxgvuLlOAoMGbj/1i6LygDHZWDgL1t5JEs37x9Aywv7ZGhqbM1GsfZ54sU6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@algolia/requester-node-http": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/@algolia/requester-node-http/-/requester-node-http-5.50.1.tgz",
+ "integrity": "sha512-qmo1LXrNKLHvJE6mdQbLnsZAoZvj7VyF2ft4xmbSGWI2WWm87fx/CjUX4kEExt4y0a6T6nEts6ofpUfH5TEE1A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/client-common": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@antfu/install-pkg": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-1.1.0.tgz",
+ "integrity": "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "package-manager-detector": "^1.3.0",
+ "tinyexec": "^1.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.27.1",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.28.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.2",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz",
+ "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.0"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
+ "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.27.1",
+ "@babel/helper-validator-identifier": "^7.28.5"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@braintree/sanitize-url": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz",
+ "integrity": "sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@chevrotain/cst-dts-gen": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-11.1.2.tgz",
+ "integrity": "sha512-XTsjvDVB5nDZBQB8o0o/0ozNelQtn2KrUVteIHSlPd2VAV2utEb6JzyCJaJ8tGxACR4RiBNWy5uYUHX2eji88Q==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chevrotain/gast": "11.1.2",
+ "@chevrotain/types": "11.1.2",
+ "lodash-es": "4.17.23"
+ }
+ },
+ "node_modules/@chevrotain/cst-dts-gen/node_modules/lodash-es": {
+ "version": "4.17.23",
+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.23.tgz",
+ "integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@chevrotain/gast": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-11.1.2.tgz",
+ "integrity": "sha512-Z9zfXR5jNZb1Hlsd/p+4XWeUFugrHirq36bKzPWDSIacV+GPSVXdk+ahVWZTwjhNwofAWg/sZg58fyucKSQx5g==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chevrotain/types": "11.1.2",
+ "lodash-es": "4.17.23"
+ }
+ },
+ "node_modules/@chevrotain/gast/node_modules/lodash-es": {
+ "version": "4.17.23",
+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.23.tgz",
+ "integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@chevrotain/regexp-to-ast": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-11.1.2.tgz",
+ "integrity": "sha512-nMU3Uj8naWer7xpZTYJdxbAs6RIv/dxYzkYU8GSwgUtcAAlzjcPfX1w+RKRcYG8POlzMeayOQ/znfwxEGo5ulw==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/@chevrotain/types": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.1.2.tgz",
+ "integrity": "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/@chevrotain/utils": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-11.1.2.tgz",
+ "integrity": "sha512-4mudFAQ6H+MqBTfqLmU7G1ZwRzCLfJEooL/fsF6rCX5eePMbGhoy5n4g+G4vlh2muDcsCTJtL+uKbOzWxs5LHA==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/@docsearch/css": {
+ "version": "3.8.2",
+ "resolved": "https://registry.npmjs.org/@docsearch/css/-/css-3.8.2.tgz",
+ "integrity": "sha512-y05ayQFyUmCXze79+56v/4HpycYF3uFqB78pLPrSV5ZKAlDuIAAJNhaRi8tTdRNXh05yxX/TyNnzD6LwSM89vQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@docsearch/js": {
+ "version": "3.8.2",
+ "resolved": "https://registry.npmjs.org/@docsearch/js/-/js-3.8.2.tgz",
+ "integrity": "sha512-Q5wY66qHn0SwA7Taa0aDbHiJvaFJLOJyHmooQ7y8hlwwQLQ/5WwCcoX0g7ii04Qi2DJlHsd0XXzJ8Ypw9+9YmQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@docsearch/react": "3.8.2",
+ "preact": "^10.0.0"
+ }
+ },
+ "node_modules/@docsearch/react": {
+ "version": "3.8.2",
+ "resolved": "https://registry.npmjs.org/@docsearch/react/-/react-3.8.2.tgz",
+ "integrity": "sha512-xCRrJQlTt8N9GU0DG4ptwHRkfnSnD/YpdeaXe02iKfqs97TkZJv60yE+1eq/tjPcVnTW8dP5qLP7itifFVV5eg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/autocomplete-core": "1.17.7",
+ "@algolia/autocomplete-preset-algolia": "1.17.7",
+ "@docsearch/css": "3.8.2",
+ "algoliasearch": "^5.14.2"
+ },
+ "peerDependencies": {
+ "@types/react": ">= 16.8.0 < 19.0.0",
+ "react": ">= 16.8.0 < 19.0.0",
+ "react-dom": ">= 16.8.0 < 19.0.0",
+ "search-insights": ">= 1 < 3"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ },
+ "search-insights": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@iconify-json/simple-icons": {
+ "version": "1.2.76",
+ "resolved": "https://registry.npmjs.org/@iconify-json/simple-icons/-/simple-icons-1.2.76.tgz",
+ "integrity": "sha512-lLRlA8yaf+1L5VCPRvR9lynoSklsddKHEylchmZJKdj/q2xVQ1ZAEJ8SCQlv9cbgtMefnlyM98U+8Si2aoFZPA==",
+ "dev": true,
+ "license": "CC0-1.0",
+ "dependencies": {
+ "@iconify/types": "*"
+ }
+ },
+ "node_modules/@iconify/types": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz",
+ "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@iconify/utils": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.0.tgz",
+ "integrity": "sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@antfu/install-pkg": "^1.1.0",
+ "@iconify/types": "^2.0.0",
+ "mlly": "^1.8.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@mermaid-js/mermaid-mindmap": {
+ "version": "9.3.0",
+ "resolved": "https://registry.npmjs.org/@mermaid-js/mermaid-mindmap/-/mermaid-mindmap-9.3.0.tgz",
+ "integrity": "sha512-IhtYSVBBRYviH1Ehu8gk69pMDF8DSRqXBRDMWrEfHoaMruHeaP2DXA3PBnuwsMaCdPQhlUUcy/7DBLAEIXvCAw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@braintree/sanitize-url": "^6.0.0",
+ "cytoscape": "^3.23.0",
+ "cytoscape-cose-bilkent": "^4.1.0",
+ "cytoscape-fcose": "^2.1.0",
+ "d3": "^7.0.0",
+ "khroma": "^2.0.0",
+ "non-layered-tidy-tree-layout": "^2.0.2"
+ }
+ },
+ "node_modules/@mermaid-js/mermaid-mindmap/node_modules/@braintree/sanitize-url": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-6.0.4.tgz",
+ "integrity": "sha512-s3jaWicZd0pkP0jf5ysyHUI/RE7MHos6qlToFcGWXVp+ykHOy77OUMrfbgJ9it2C5bow7OIQwYYaHjk9XlBQ2A==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/@mermaid-js/parser": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.1.0.tgz",
+ "integrity": "sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "langium": "^4.0.0"
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz",
+ "integrity": "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.1.tgz",
+ "integrity": "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.1.tgz",
+ "integrity": "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.1.tgz",
+ "integrity": "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.1.tgz",
+ "integrity": "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.1.tgz",
+ "integrity": "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.1.tgz",
+ "integrity": "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.1.tgz",
+ "integrity": "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.1.tgz",
+ "integrity": "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.1.tgz",
+ "integrity": "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.1.tgz",
+ "integrity": "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.1.tgz",
+ "integrity": "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.1.tgz",
+ "integrity": "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.1.tgz",
+ "integrity": "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.1.tgz",
+ "integrity": "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.1.tgz",
+ "integrity": "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.1.tgz",
+ "integrity": "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.1.tgz",
+ "integrity": "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.1.tgz",
+ "integrity": "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.1.tgz",
+ "integrity": "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.1.tgz",
+ "integrity": "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.1.tgz",
+ "integrity": "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.1.tgz",
+ "integrity": "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.1.tgz",
+ "integrity": "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.1.tgz",
+ "integrity": "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@shikijs/core": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-2.5.0.tgz",
+ "integrity": "sha512-uu/8RExTKtavlpH7XqnVYBrfBkUc20ngXiX9NSrBhOVZYv/7XQRKUyhtkeflY5QsxC0GbJThCerruZfsUaSldg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/engine-javascript": "2.5.0",
+ "@shikijs/engine-oniguruma": "2.5.0",
+ "@shikijs/types": "2.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.4",
+ "hast-util-to-html": "^9.0.4"
+ }
+ },
+ "node_modules/@shikijs/engine-javascript": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-2.5.0.tgz",
+ "integrity": "sha512-VjnOpnQf8WuCEZtNUdjjwGUbtAVKuZkVQ/5cHy/tojVVRIRtlWMYVjyWhxOmIq05AlSOv72z7hRNRGVBgQOl0w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "2.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "oniguruma-to-es": "^3.1.0"
+ }
+ },
+ "node_modules/@shikijs/engine-oniguruma": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-2.5.0.tgz",
+ "integrity": "sha512-pGd1wRATzbo/uatrCIILlAdFVKdxImWJGQ5rFiB5VZi2ve5xj3Ax9jny8QvkaV93btQEwR/rSz5ERFpC5mKNIw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "2.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2"
+ }
+ },
+ "node_modules/@shikijs/langs": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-2.5.0.tgz",
+ "integrity": "sha512-Qfrrt5OsNH5R+5tJ/3uYBBZv3SuGmnRPejV9IlIbFH3HTGLDlkqgHymAlzklVmKBjAaVmkPkyikAV/sQ1wSL+w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "2.5.0"
+ }
+ },
+ "node_modules/@shikijs/themes": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-2.5.0.tgz",
+ "integrity": "sha512-wGrk+R8tJnO0VMzmUExHR+QdSaPUl/NKs+a4cQQRWyoc3YFbUzuLEi/KWK1hj+8BfHRKm2jNhhJck1dfstJpiw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/types": "2.5.0"
+ }
+ },
+ "node_modules/@shikijs/transformers": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-2.5.0.tgz",
+ "integrity": "sha512-SI494W5X60CaUwgi8u4q4m4s3YAFSxln3tzNjOSYqq54wlVgz0/NbbXEb3mdLbqMBztcmS7bVTaEd2w0qMmfeg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/core": "2.5.0",
+ "@shikijs/types": "2.5.0"
+ }
+ },
+ "node_modules/@shikijs/types": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-2.5.0.tgz",
+ "integrity": "sha512-ygl5yhxki9ZLNuNpPitBWvcy9fsSKKaRuO4BAlMyagszQidxcpLAr0qiW/q43DtSIDxO6hEbtYLiFZNXO/hdGw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.4"
+ }
+ },
+ "node_modules/@shikijs/vscode-textmate": {
+ "version": "10.0.2",
+ "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",
+ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3": {
+ "version": "7.4.3",
+ "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
+ "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/d3-axis": "*",
+ "@types/d3-brush": "*",
+ "@types/d3-chord": "*",
+ "@types/d3-color": "*",
+ "@types/d3-contour": "*",
+ "@types/d3-delaunay": "*",
+ "@types/d3-dispatch": "*",
+ "@types/d3-drag": "*",
+ "@types/d3-dsv": "*",
+ "@types/d3-ease": "*",
+ "@types/d3-fetch": "*",
+ "@types/d3-force": "*",
+ "@types/d3-format": "*",
+ "@types/d3-geo": "*",
+ "@types/d3-hierarchy": "*",
+ "@types/d3-interpolate": "*",
+ "@types/d3-path": "*",
+ "@types/d3-polygon": "*",
+ "@types/d3-quadtree": "*",
+ "@types/d3-random": "*",
+ "@types/d3-scale": "*",
+ "@types/d3-scale-chromatic": "*",
+ "@types/d3-selection": "*",
+ "@types/d3-shape": "*",
+ "@types/d3-time": "*",
+ "@types/d3-time-format": "*",
+ "@types/d3-timer": "*",
+ "@types/d3-transition": "*",
+ "@types/d3-zoom": "*"
+ }
+ },
+ "node_modules/@types/d3-array": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-axis": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",
+ "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-brush": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",
+ "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-chord": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",
+ "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-color": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-contour": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",
+ "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-array": "*",
+ "@types/geojson": "*"
+ }
+ },
+ "node_modules/@types/d3-delaunay": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
+ "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-dispatch": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",
+ "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-drag": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-dsv": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",
+ "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-ease": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-fetch": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",
+ "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-dsv": "*"
+ }
+ },
+ "node_modules/@types/d3-force": {
+ "version": "3.0.10",
+ "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",
+ "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-format": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",
+ "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-geo": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",
+ "integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/geojson": "*"
+ }
+ },
+ "node_modules/@types/d3-hierarchy": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",
+ "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-interpolate": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-color": "*"
+ }
+ },
+ "node_modules/@types/d3-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-polygon": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",
+ "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-quadtree": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",
+ "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-random": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",
+ "integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-scale": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-time": "*"
+ }
+ },
+ "node_modules/@types/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-selection": {
+ "version": "3.0.11",
+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-shape": {
+ "version": "3.1.8",
+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
+ "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-path": "*"
+ }
+ },
+ "node_modules/@types/d3-time": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-time-format": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",
+ "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-timer": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-transition": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/d3-zoom": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-interpolate": "*",
+ "@types/d3-selection": "*"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
+ "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/geojson": {
+ "version": "7946.0.16",
+ "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
+ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/hast": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",
+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/linkify-it": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz",
+ "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/markdown-it": {
+ "version": "14.1.2",
+ "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz",
+ "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/linkify-it": "^5",
+ "@types/mdurl": "^2"
+ }
+ },
+ "node_modules/@types/mdast": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",
+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
+ "node_modules/@types/mdurl": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz",
+ "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/trusted-types": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
+ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/@types/unist": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/web-bluetooth": {
+ "version": "0.0.21",
+ "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz",
+ "integrity": "sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@ungap/structured-clone": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
+ "integrity": "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/@upsetjs/venn.js": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@upsetjs/venn.js/-/venn.js-2.0.0.tgz",
+ "integrity": "sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==",
+ "dev": true,
+ "license": "MIT",
+ "optionalDependencies": {
+ "d3-selection": "^3.0.0",
+ "d3-transition": "^3.0.1"
+ }
+ },
+ "node_modules/@vitejs/plugin-vue": {
+ "version": "5.2.4",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz",
+ "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "peerDependencies": {
+ "vite": "^5.0.0 || ^6.0.0",
+ "vue": "^3.2.25"
+ }
+ },
+ "node_modules/@vue/compiler-core": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.31.tgz",
+ "integrity": "sha512-k/ueL14aNIEy5Onf0OVzR8kiqF/WThgLdFhxwa4e/KF/0qe38IwIdofoSWBTvvxQOesaz6riAFAUaYjoF9fLLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.2",
+ "@vue/shared": "3.5.31",
+ "entities": "^7.0.1",
+ "estree-walker": "^2.0.2",
+ "source-map-js": "^1.2.1"
+ }
+ },
+ "node_modules/@vue/compiler-dom": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.31.tgz",
+ "integrity": "sha512-BMY/ozS/xxjYqRFL+tKdRpATJYDTTgWSo0+AJvJNg4ig+Hgb0dOsHPXvloHQ5hmlivUqw1Yt2pPIqp4e0v1GUw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-core": "3.5.31",
+ "@vue/shared": "3.5.31"
+ }
+ },
+ "node_modules/@vue/compiler-sfc": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.31.tgz",
+ "integrity": "sha512-M8wpPgR9UJ8MiRGjppvx9uWJfLV7A/T+/rL8s/y3QG3u0c2/YZgff3d6SuimKRIhcYnWg5fTfDMlz2E6seUW8Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.2",
+ "@vue/compiler-core": "3.5.31",
+ "@vue/compiler-dom": "3.5.31",
+ "@vue/compiler-ssr": "3.5.31",
+ "@vue/shared": "3.5.31",
+ "estree-walker": "^2.0.2",
+ "magic-string": "^0.30.21",
+ "postcss": "^8.5.8",
+ "source-map-js": "^1.2.1"
+ }
+ },
+ "node_modules/@vue/compiler-ssr": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.31.tgz",
+ "integrity": "sha512-h0xIMxrt/LHOvJKMri+vdYT92BrK3HFLtDqq9Pr/lVVfE4IyKZKvWf0vJFW10Yr6nX02OR4MkJwI0c1HDa1hog==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-dom": "3.5.31",
+ "@vue/shared": "3.5.31"
+ }
+ },
+ "node_modules/@vue/devtools-api": {
+ "version": "7.7.9",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-7.7.9.tgz",
+ "integrity": "sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-kit": "^7.7.9"
+ }
+ },
+ "node_modules/@vue/devtools-kit": {
+ "version": "7.7.9",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-7.7.9.tgz",
+ "integrity": "sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/devtools-shared": "^7.7.9",
+ "birpc": "^2.3.0",
+ "hookable": "^5.5.3",
+ "mitt": "^3.0.1",
+ "perfect-debounce": "^1.0.0",
+ "speakingurl": "^14.0.1",
+ "superjson": "^2.2.2"
+ }
+ },
+ "node_modules/@vue/devtools-shared": {
+ "version": "7.7.9",
+ "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-7.7.9.tgz",
+ "integrity": "sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "rfdc": "^1.4.1"
+ }
+ },
+ "node_modules/@vue/reactivity": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.31.tgz",
+ "integrity": "sha512-DtKXxk9E/KuVvt8VxWu+6Luc9I9ETNcqR1T1oW1gf02nXaZ1kuAx58oVu7uX9XxJR0iJCro6fqBLw9oSBELo5g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/shared": "3.5.31"
+ }
+ },
+ "node_modules/@vue/runtime-core": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.31.tgz",
+ "integrity": "sha512-AZPmIHXEAyhpkmN7aWlqjSfYynmkWlluDNPHMCZKFHH+lLtxP/30UJmoVhXmbDoP1Ng0jG0fyY2zCj1PnSSA6Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/reactivity": "3.5.31",
+ "@vue/shared": "3.5.31"
+ }
+ },
+ "node_modules/@vue/runtime-dom": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.31.tgz",
+ "integrity": "sha512-xQJsNRmGPeDCJq/u813tyonNgWBFjzfVkBwDREdEWndBnGdHLHgkwNBQxLtg4zDrzKTEcnikUy1UUNecb3lJ6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/reactivity": "3.5.31",
+ "@vue/runtime-core": "3.5.31",
+ "@vue/shared": "3.5.31",
+ "csstype": "^3.2.3"
+ }
+ },
+ "node_modules/@vue/server-renderer": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.31.tgz",
+ "integrity": "sha512-GJuwRvMcdZX/CriUnyIIOGkx3rMV3H6sOu0JhdKbduaeCji6zb60iOGMY7tFoN24NfsUYoFBhshZtGxGpxO4iA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-ssr": "3.5.31",
+ "@vue/shared": "3.5.31"
+ },
+ "peerDependencies": {
+ "vue": "3.5.31"
+ }
+ },
+ "node_modules/@vue/shared": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.31.tgz",
+ "integrity": "sha512-nBxuiuS9Lj5bPkPbWogPUnjxxWpkRniX7e5UBQDWl6Fsf4roq9wwV+cR7ezQ4zXswNvPIlsdj1slcLB7XCsRAw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vueuse/core": {
+ "version": "12.8.2",
+ "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-12.8.2.tgz",
+ "integrity": "sha512-HbvCmZdzAu3VGi/pWYm5Ut+Kd9mn1ZHnn4L5G8kOQTPs/IwIAmJoBrmYk2ckLArgMXZj0AW3n5CAejLUO+PhdQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/web-bluetooth": "^0.0.21",
+ "@vueuse/metadata": "12.8.2",
+ "@vueuse/shared": "12.8.2",
+ "vue": "^3.5.13"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/@vueuse/integrations": {
+ "version": "12.8.2",
+ "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-12.8.2.tgz",
+ "integrity": "sha512-fbGYivgK5uBTRt7p5F3zy6VrETlV9RtZjBqd1/HxGdjdckBgBM4ugP8LHpjolqTj14TXTxSK1ZfgPbHYyGuH7g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vueuse/core": "12.8.2",
+ "@vueuse/shared": "12.8.2",
+ "vue": "^3.5.13"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ },
+ "peerDependencies": {
+ "async-validator": "^4",
+ "axios": "^1",
+ "change-case": "^5",
+ "drauu": "^0.4",
+ "focus-trap": "^7",
+ "fuse.js": "^7",
+ "idb-keyval": "^6",
+ "jwt-decode": "^4",
+ "nprogress": "^0.2",
+ "qrcode": "^1.5",
+ "sortablejs": "^1",
+ "universal-cookie": "^7"
+ },
+ "peerDependenciesMeta": {
+ "async-validator": {
+ "optional": true
+ },
+ "axios": {
+ "optional": true
+ },
+ "change-case": {
+ "optional": true
+ },
+ "drauu": {
+ "optional": true
+ },
+ "focus-trap": {
+ "optional": true
+ },
+ "fuse.js": {
+ "optional": true
+ },
+ "idb-keyval": {
+ "optional": true
+ },
+ "jwt-decode": {
+ "optional": true
+ },
+ "nprogress": {
+ "optional": true
+ },
+ "qrcode": {
+ "optional": true
+ },
+ "sortablejs": {
+ "optional": true
+ },
+ "universal-cookie": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vueuse/metadata": {
+ "version": "12.8.2",
+ "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-12.8.2.tgz",
+ "integrity": "sha512-rAyLGEuoBJ/Il5AmFHiziCPdQzRt88VxR+Y/A/QhJ1EWtWqPBBAxTAFaSkviwEuOEZNtW8pvkPgoCZQ+HxqW1A==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/@vueuse/shared": {
+ "version": "12.8.2",
+ "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-12.8.2.tgz",
+ "integrity": "sha512-dznP38YzxZoNloI0qpEfpkms8knDtaoQ6Y/sfS0L7Yki4zh40LFHEhur0odJC6xTHG5dxWVPiUWBXn+wCG2s5w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "vue": "^3.5.13"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/acorn": {
+ "version": "8.16.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
+ "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/algoliasearch": {
+ "version": "5.50.1",
+ "resolved": "https://registry.npmjs.org/algoliasearch/-/algoliasearch-5.50.1.tgz",
+ "integrity": "sha512-/bwdue1/8LWELn/DBalGRfuLsXBLXULJo/yOeavJtDu8rBwxIzC6/Rz9Jg19S21VkJvRuZO1k8CZXBMS73mYbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@algolia/abtesting": "1.16.1",
+ "@algolia/client-abtesting": "5.50.1",
+ "@algolia/client-analytics": "5.50.1",
+ "@algolia/client-common": "5.50.1",
+ "@algolia/client-insights": "5.50.1",
+ "@algolia/client-personalization": "5.50.1",
+ "@algolia/client-query-suggestions": "5.50.1",
+ "@algolia/client-search": "5.50.1",
+ "@algolia/ingestion": "1.50.1",
+ "@algolia/monitoring": "1.50.1",
+ "@algolia/recommend": "5.50.1",
+ "@algolia/requester-browser-xhr": "5.50.1",
+ "@algolia/requester-fetch": "5.50.1",
+ "@algolia/requester-node-http": "5.50.1"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/birpc": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz",
+ "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/antfu"
+ }
+ },
+ "node_modules/ccount": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-html4": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",
+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-legacy": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/chevrotain": {
+ "version": "11.1.2",
+ "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.1.2.tgz",
+ "integrity": "sha512-opLQzEVriiH1uUQ4Kctsd49bRoFDXGGSC4GUqj7pGyxM3RehRhvTlZJc1FL/Flew2p5uwxa1tUDWKzI4wNM8pg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@chevrotain/cst-dts-gen": "11.1.2",
+ "@chevrotain/gast": "11.1.2",
+ "@chevrotain/regexp-to-ast": "11.1.2",
+ "@chevrotain/types": "11.1.2",
+ "@chevrotain/utils": "11.1.2",
+ "lodash-es": "4.17.23"
+ }
+ },
+ "node_modules/chevrotain-allstar": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.3.1.tgz",
+ "integrity": "sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lodash-es": "^4.17.21"
+ },
+ "peerDependencies": {
+ "chevrotain": "^11.0.0"
+ }
+ },
+ "node_modules/chevrotain/node_modules/lodash-es": {
+ "version": "4.17.23",
+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.23.tgz",
+ "integrity": "sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/comma-separated-tokens": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/commander": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
+ "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/confbox": {
+ "version": "0.1.8",
+ "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz",
+ "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/copy-anything": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz",
+ "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-what": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/mesqueeb"
+ }
+ },
+ "node_modules/cose-base": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz",
+ "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "layout-base": "^1.0.0"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cytoscape": {
+ "version": "3.33.1",
+ "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.1.tgz",
+ "integrity": "sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/cytoscape-cose-bilkent": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz",
+ "integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cose-base": "^1.0.0"
+ },
+ "peerDependencies": {
+ "cytoscape": "^3.2.0"
+ }
+ },
+ "node_modules/cytoscape-fcose": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/cytoscape-fcose/-/cytoscape-fcose-2.2.0.tgz",
+ "integrity": "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cose-base": "^2.2.0"
+ },
+ "peerDependencies": {
+ "cytoscape": "^3.2.0"
+ }
+ },
+ "node_modules/cytoscape-fcose/node_modules/cose-base": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-2.2.0.tgz",
+ "integrity": "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "layout-base": "^2.0.0"
+ }
+ },
+ "node_modules/cytoscape-fcose/node_modules/layout-base": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-2.0.1.tgz",
+ "integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/d3": {
+ "version": "7.9.0",
+ "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",
+ "integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "3",
+ "d3-axis": "3",
+ "d3-brush": "3",
+ "d3-chord": "3",
+ "d3-color": "3",
+ "d3-contour": "4",
+ "d3-delaunay": "6",
+ "d3-dispatch": "3",
+ "d3-drag": "3",
+ "d3-dsv": "3",
+ "d3-ease": "3",
+ "d3-fetch": "3",
+ "d3-force": "3",
+ "d3-format": "3",
+ "d3-geo": "3",
+ "d3-hierarchy": "3",
+ "d3-interpolate": "3",
+ "d3-path": "3",
+ "d3-polygon": "3",
+ "d3-quadtree": "3",
+ "d3-random": "3",
+ "d3-scale": "4",
+ "d3-scale-chromatic": "3",
+ "d3-selection": "3",
+ "d3-shape": "3",
+ "d3-time": "3",
+ "d3-time-format": "4",
+ "d3-timer": "3",
+ "d3-transition": "3",
+ "d3-zoom": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-array": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "internmap": "1 - 2"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-axis": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",
+ "integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-brush": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",
+ "integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "3",
+ "d3-transition": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-chord": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",
+ "integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-contour": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",
+ "integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "^3.2.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-delaunay": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
+ "integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "delaunator": "5"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dispatch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-drag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-selection": "3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-dsv": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",
+ "integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "commander": "7",
+ "iconv-lite": "0.6",
+ "rw": "1"
+ },
+ "bin": {
+ "csv2json": "bin/dsv2json.js",
+ "csv2tsv": "bin/dsv2dsv.js",
+ "dsv2dsv": "bin/dsv2dsv.js",
+ "dsv2json": "bin/dsv2json.js",
+ "json2csv": "bin/json2dsv.js",
+ "json2dsv": "bin/json2dsv.js",
+ "json2tsv": "bin/json2dsv.js",
+ "tsv2csv": "bin/dsv2dsv.js",
+ "tsv2json": "bin/dsv2json.js"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-ease": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-fetch": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",
+ "integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-dsv": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-force": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",
+ "integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-quadtree": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-format": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
+ "integrity": "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-geo": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",
+ "integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.5.0 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-hierarchy": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",
+ "integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-path": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-polygon": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",
+ "integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-quadtree": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",
+ "integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-random": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",
+ "integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-sankey": {
+ "version": "0.12.3",
+ "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz",
+ "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "d3-array": "1 - 2",
+ "d3-shape": "^1.2.0"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/d3-array": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz",
+ "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "internmap": "^1.0.0"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/d3-path": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",
+ "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/d3-sankey/node_modules/d3-shape": {
+ "version": "1.3.7",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",
+ "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "d3-path": "1"
+ }
+ },
+ "node_modules/d3-sankey/node_modules/internmap": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz",
+ "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/d3-scale": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.10.0 - 3",
+ "d3-format": "1 - 3",
+ "d3-interpolate": "1.2.0 - 3",
+ "d3-time": "2.1.1 - 3",
+ "d3-time-format": "2 - 4"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-scale-chromatic": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
+ "integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-interpolate": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-selection": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time-format": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-time": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-transition": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3",
+ "d3-dispatch": "1 - 3",
+ "d3-ease": "1 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-timer": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "peerDependencies": {
+ "d3-selection": "2 - 3"
+ }
+ },
+ "node_modules/d3-zoom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "d3-dispatch": "1 - 3",
+ "d3-drag": "2 - 3",
+ "d3-interpolate": "1 - 3",
+ "d3-selection": "2 - 3",
+ "d3-transition": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/dagre-d3-es": {
+ "version": "7.0.14",
+ "resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.14.tgz",
+ "integrity": "sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "d3": "^7.9.0",
+ "lodash-es": "^4.17.21"
+ }
+ },
+ "node_modules/dayjs": {
+ "version": "1.11.20",
+ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.20.tgz",
+ "integrity": "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/delaunator": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",
+ "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "robust-predicates": "^3.0.2"
+ }
+ },
+ "node_modules/dequal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/devlop": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",
+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/dompurify": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.3.tgz",
+ "integrity": "sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==",
+ "dev": true,
+ "license": "(MPL-2.0 OR Apache-2.0)",
+ "optionalDependencies": {
+ "@types/trusted-types": "^2.0.7"
+ }
+ },
+ "node_modules/emoji-regex-xs": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz",
+ "integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.21.5",
+ "@esbuild/android-arm": "0.21.5",
+ "@esbuild/android-arm64": "0.21.5",
+ "@esbuild/android-x64": "0.21.5",
+ "@esbuild/darwin-arm64": "0.21.5",
+ "@esbuild/darwin-x64": "0.21.5",
+ "@esbuild/freebsd-arm64": "0.21.5",
+ "@esbuild/freebsd-x64": "0.21.5",
+ "@esbuild/linux-arm": "0.21.5",
+ "@esbuild/linux-arm64": "0.21.5",
+ "@esbuild/linux-ia32": "0.21.5",
+ "@esbuild/linux-loong64": "0.21.5",
+ "@esbuild/linux-mips64el": "0.21.5",
+ "@esbuild/linux-ppc64": "0.21.5",
+ "@esbuild/linux-riscv64": "0.21.5",
+ "@esbuild/linux-s390x": "0.21.5",
+ "@esbuild/linux-x64": "0.21.5",
+ "@esbuild/netbsd-x64": "0.21.5",
+ "@esbuild/openbsd-x64": "0.21.5",
+ "@esbuild/sunos-x64": "0.21.5",
+ "@esbuild/win32-arm64": "0.21.5",
+ "@esbuild/win32-ia32": "0.21.5",
+ "@esbuild/win32-x64": "0.21.5"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/focus-trap": {
+ "version": "7.8.0",
+ "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.8.0.tgz",
+ "integrity": "sha512-/yNdlIkpWbM0ptxno3ONTuf+2g318kh2ez3KSeZN5dZ8YC6AAmgeWz+GasYYiBJPFaYcSAPeu4GfhUaChzIJXA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tabbable": "^6.4.0"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/hachure-fill": {
+ "version": "0.5.2",
+ "resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz",
+ "integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/hast-util-to-html": {
+ "version": "9.0.5",
+ "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",
+ "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/unist": "^3.0.0",
+ "ccount": "^2.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "hast-util-whitespace": "^3.0.0",
+ "html-void-elements": "^3.0.0",
+ "mdast-util-to-hast": "^13.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0",
+ "stringify-entities": "^4.0.0",
+ "zwitch": "^2.0.4"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hast-util-whitespace": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",
+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hookable": {
+ "version": "5.5.3",
+ "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",
+ "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/html-void-elements": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",
+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/internmap": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/is-what": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz",
+ "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/mesqueeb"
+ }
+ },
+ "node_modules/katex": {
+ "version": "0.16.44",
+ "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.44.tgz",
+ "integrity": "sha512-EkxoDTk8ufHqHlf9QxGwcxeLkWRR3iOuYfRpfORgYfqc8s13bgb+YtRY59NK5ZpRaCwq1kqA6a5lpX8C/eLphQ==",
+ "dev": true,
+ "funding": [
+ "https://opencollective.com/katex",
+ "https://github.com/sponsors/katex"
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "commander": "^8.3.0"
+ },
+ "bin": {
+ "katex": "cli.js"
+ }
+ },
+ "node_modules/katex/node_modules/commander": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
+ "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/khroma": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz",
+ "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==",
+ "dev": true
+ },
+ "node_modules/langium": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/langium/-/langium-4.2.1.tgz",
+ "integrity": "sha512-zu9QWmjpzJcomzdJQAHgDVhLGq5bLosVak1KVa40NzQHXfqr4eAHupvnPOVXEoLkg6Ocefvf/93d//SB7du4YQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "chevrotain": "~11.1.1",
+ "chevrotain-allstar": "~0.3.1",
+ "vscode-languageserver": "~9.0.1",
+ "vscode-languageserver-textdocument": "~1.0.11",
+ "vscode-uri": "~3.1.0"
+ },
+ "engines": {
+ "node": ">=20.10.0",
+ "npm": ">=10.2.3"
+ }
+ },
+ "node_modules/layout-base": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz",
+ "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash-es": {
+ "version": "4.18.1",
+ "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",
+ "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/mark.js": {
+ "version": "8.11.1",
+ "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz",
+ "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/marked": {
+ "version": "16.4.2",
+ "resolved": "https://registry.npmjs.org/marked/-/marked-16.4.2.tgz",
+ "integrity": "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "marked": "bin/marked.js"
+ },
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/mdast-util-to-hast": {
+ "version": "13.2.1",
+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/mdast": "^4.0.0",
+ "@ungap/structured-clone": "^1.0.0",
+ "devlop": "^1.0.0",
+ "micromark-util-sanitize-uri": "^2.0.0",
+ "trim-lines": "^3.0.0",
+ "unist-util-position": "^5.0.0",
+ "unist-util-visit": "^5.0.0",
+ "vfile": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/mermaid": {
+ "version": "11.14.0",
+ "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.14.0.tgz",
+ "integrity": "sha512-GSGloRsBs+JINmmhl0JDwjpuezCsHB4WGI4NASHxL3fHo3o/BRXTxhDLKnln8/Q0lRFRyDdEjmk1/d5Sn1Xz8g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@braintree/sanitize-url": "^7.1.1",
+ "@iconify/utils": "^3.0.2",
+ "@mermaid-js/parser": "^1.1.0",
+ "@types/d3": "^7.4.3",
+ "@upsetjs/venn.js": "^2.0.0",
+ "cytoscape": "^3.33.1",
+ "cytoscape-cose-bilkent": "^4.1.0",
+ "cytoscape-fcose": "^2.2.0",
+ "d3": "^7.9.0",
+ "d3-sankey": "^0.12.3",
+ "dagre-d3-es": "7.0.14",
+ "dayjs": "^1.11.19",
+ "dompurify": "^3.3.1",
+ "katex": "^0.16.25",
+ "khroma": "^2.1.0",
+ "lodash-es": "^4.17.23",
+ "marked": "^16.3.0",
+ "roughjs": "^4.6.6",
+ "stylis": "^4.3.6",
+ "ts-dedent": "^2.2.0",
+ "uuid": "^11.1.0"
+ }
+ },
+ "node_modules/micromark-util-character": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",
+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-symbol": "^2.0.0",
+ "micromark-util-types": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-encode": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",
+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-sanitize-uri": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",
+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "micromark-util-character": "^2.0.0",
+ "micromark-util-encode": "^2.0.0",
+ "micromark-util-symbol": "^2.0.0"
+ }
+ },
+ "node_modules/micromark-util-symbol": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",
+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/micromark-util-types": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",
+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "GitHub Sponsors",
+ "url": "https://github.com/sponsors/unifiedjs"
+ },
+ {
+ "type": "OpenCollective",
+ "url": "https://opencollective.com/unified"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/minisearch": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz",
+ "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/mlly": {
+ "version": "1.8.2",
+ "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz",
+ "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "acorn": "^8.16.0",
+ "pathe": "^2.0.3",
+ "pkg-types": "^1.3.1",
+ "ufo": "^1.6.3"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/non-layered-tidy-tree-layout": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/non-layered-tidy-tree-layout/-/non-layered-tidy-tree-layout-2.0.2.tgz",
+ "integrity": "sha512-gkXMxRzUH+PB0ax9dUN0yYF0S25BqeAYqhgMaLUFmpXLEk7Fcu8f4emJuOAY0V8kjDICxROIKsTAKsV/v355xw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/oniguruma-to-es": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-3.1.1.tgz",
+ "integrity": "sha512-bUH8SDvPkH3ho3dvwJwfonjlQ4R80vjyvrU8YpxuROddv55vAEJrTuCuCVUhhsHbtlD9tGGbaNApGQckXhS8iQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex-xs": "^1.0.0",
+ "regex": "^6.0.1",
+ "regex-recursion": "^6.0.2"
+ }
+ },
+ "node_modules/package-manager-detector": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.6.0.tgz",
+ "integrity": "sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/path-data-parser": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz",
+ "integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/perfect-debounce": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
+ "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/pkg-types": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
+ "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "confbox": "^0.1.8",
+ "mlly": "^1.7.4",
+ "pathe": "^2.0.1"
+ }
+ },
+ "node_modules/points-on-curve": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz",
+ "integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/points-on-path": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz",
+ "integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-data-parser": "0.1.0",
+ "points-on-curve": "0.2.0"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.8",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
+ "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.11",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/preact": {
+ "version": "10.29.0",
+ "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.0.tgz",
+ "integrity": "sha512-wSAGyk2bYR1c7t3SZ3jHcM6xy0lcBcDel6lODcs9ME6Th++Dx2KU+6D3HD8wMMKGA8Wpw7OMd3/4RGzYRpzwRg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/preact"
+ }
+ },
+ "node_modules/property-information": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/regex": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",
+ "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "regex-utilities": "^2.3.0"
+ }
+ },
+ "node_modules/regex-recursion": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",
+ "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "regex-utilities": "^2.3.0"
+ }
+ },
+ "node_modules/regex-utilities": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",
+ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/rfdc": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
+ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/robust-predicates": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
+ "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
+ "dev": true,
+ "license": "Unlicense"
+ },
+ "node_modules/rollup": {
+ "version": "4.60.1",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz",
+ "integrity": "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.8"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@rollup/rollup-android-arm-eabi": "4.60.1",
+ "@rollup/rollup-android-arm64": "4.60.1",
+ "@rollup/rollup-darwin-arm64": "4.60.1",
+ "@rollup/rollup-darwin-x64": "4.60.1",
+ "@rollup/rollup-freebsd-arm64": "4.60.1",
+ "@rollup/rollup-freebsd-x64": "4.60.1",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.60.1",
+ "@rollup/rollup-linux-arm-musleabihf": "4.60.1",
+ "@rollup/rollup-linux-arm64-gnu": "4.60.1",
+ "@rollup/rollup-linux-arm64-musl": "4.60.1",
+ "@rollup/rollup-linux-loong64-gnu": "4.60.1",
+ "@rollup/rollup-linux-loong64-musl": "4.60.1",
+ "@rollup/rollup-linux-ppc64-gnu": "4.60.1",
+ "@rollup/rollup-linux-ppc64-musl": "4.60.1",
+ "@rollup/rollup-linux-riscv64-gnu": "4.60.1",
+ "@rollup/rollup-linux-riscv64-musl": "4.60.1",
+ "@rollup/rollup-linux-s390x-gnu": "4.60.1",
+ "@rollup/rollup-linux-x64-gnu": "4.60.1",
+ "@rollup/rollup-linux-x64-musl": "4.60.1",
+ "@rollup/rollup-openbsd-x64": "4.60.1",
+ "@rollup/rollup-openharmony-arm64": "4.60.1",
+ "@rollup/rollup-win32-arm64-msvc": "4.60.1",
+ "@rollup/rollup-win32-ia32-msvc": "4.60.1",
+ "@rollup/rollup-win32-x64-gnu": "4.60.1",
+ "@rollup/rollup-win32-x64-msvc": "4.60.1",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/roughjs": {
+ "version": "4.6.6",
+ "resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz",
+ "integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hachure-fill": "^0.5.2",
+ "path-data-parser": "^0.1.0",
+ "points-on-curve": "^0.2.0",
+ "points-on-path": "^0.2.1"
+ }
+ },
+ "node_modules/rw": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
+ "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/search-insights": {
+ "version": "2.17.3",
+ "resolved": "https://registry.npmjs.org/search-insights/-/search-insights-2.17.3.tgz",
+ "integrity": "sha512-RQPdCYTa8A68uM2jwxoY842xDhvx3E5LFL1LxvxCNMev4o5mLuokczhzjAgGwUZBAmOKZknArSxLKmXtIi2AxQ==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/shiki": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/shiki/-/shiki-2.5.0.tgz",
+ "integrity": "sha512-mI//trrsaiCIPsja5CNfsyNOqgAZUb6VpJA+340toL42UpzQlXpwRV9nch69X6gaUxrr9kaOOa6e3y3uAkGFxQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@shikijs/core": "2.5.0",
+ "@shikijs/engine-javascript": "2.5.0",
+ "@shikijs/engine-oniguruma": "2.5.0",
+ "@shikijs/langs": "2.5.0",
+ "@shikijs/themes": "2.5.0",
+ "@shikijs/types": "2.5.0",
+ "@shikijs/vscode-textmate": "^10.0.2",
+ "@types/hast": "^3.0.4"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/space-separated-tokens": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/speakingurl": {
+ "version": "14.0.1",
+ "resolved": "https://registry.npmjs.org/speakingurl/-/speakingurl-14.0.1.tgz",
+ "integrity": "sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stringify-entities": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "character-entities-html4": "^2.0.0",
+ "character-entities-legacy": "^3.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/stylis": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.6.tgz",
+ "integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/superjson": {
+ "version": "2.2.6",
+ "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz",
+ "integrity": "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "copy-anything": "^4"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tabbable": {
+ "version": "6.4.0",
+ "resolved": "https://registry.npmjs.org/tabbable/-/tabbable-6.4.0.tgz",
+ "integrity": "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz",
+ "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/trim-lines": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/ts-dedent": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz",
+ "integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.10"
+ }
+ },
+ "node_modules/ufo": {
+ "version": "1.6.3",
+ "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz",
+ "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/unist-util-is": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",
+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-position": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",
+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-stringify-position": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",
+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",
+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0",
+ "unist-util-visit-parents": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/unist-util-visit-parents": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",
+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-is": "^6.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/uuid": {
+ "version": "11.1.0",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
+ "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist/esm/bin/uuid"
+ }
+ },
+ "node_modules/vfile": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",
+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "vfile-message": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vfile-message": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",
+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^3.0.0",
+ "unist-util-stringify-position": "^4.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/vite": {
+ "version": "5.4.21",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.21.3",
+ "postcss": "^8.4.43",
+ "rollup": "^4.20.0"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "less": "*",
+ "lightningcss": "^1.21.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
+ "terser": "^5.4.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitepress": {
+ "version": "1.6.4",
+ "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-1.6.4.tgz",
+ "integrity": "sha512-+2ym1/+0VVrbhNyRoFFesVvBvHAVMZMK0rw60E3X/5349M1GuVdKeazuksqopEdvkKwKGs21Q729jX81/bkBJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@docsearch/css": "3.8.2",
+ "@docsearch/js": "3.8.2",
+ "@iconify-json/simple-icons": "^1.2.21",
+ "@shikijs/core": "^2.1.0",
+ "@shikijs/transformers": "^2.1.0",
+ "@shikijs/types": "^2.1.0",
+ "@types/markdown-it": "^14.1.2",
+ "@vitejs/plugin-vue": "^5.2.1",
+ "@vue/devtools-api": "^7.7.0",
+ "@vue/shared": "^3.5.13",
+ "@vueuse/core": "^12.4.0",
+ "@vueuse/integrations": "^12.4.0",
+ "focus-trap": "^7.6.4",
+ "mark.js": "8.11.1",
+ "minisearch": "^7.1.1",
+ "shiki": "^2.1.0",
+ "vite": "^5.4.14",
+ "vue": "^3.5.13"
+ },
+ "bin": {
+ "vitepress": "bin/vitepress.js"
+ },
+ "peerDependencies": {
+ "markdown-it-mathjax3": "^4",
+ "postcss": "^8"
+ },
+ "peerDependenciesMeta": {
+ "markdown-it-mathjax3": {
+ "optional": true
+ },
+ "postcss": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitepress-plugin-mermaid": {
+ "version": "2.0.17",
+ "resolved": "https://registry.npmjs.org/vitepress-plugin-mermaid/-/vitepress-plugin-mermaid-2.0.17.tgz",
+ "integrity": "sha512-IUzYpwf61GC6k0XzfmAmNrLvMi9TRrVRMsUyCA8KNXhg/mQ1VqWnO0/tBVPiX5UoKF1mDUwqn5QV4qAJl6JnUg==",
+ "dev": true,
+ "license": "MIT",
+ "optionalDependencies": {
+ "@mermaid-js/mermaid-mindmap": "^9.3.0"
+ },
+ "peerDependencies": {
+ "mermaid": "10 || 11",
+ "vitepress": "^1.0.0 || ^1.0.0-alpha"
+ }
+ },
+ "node_modules/vscode-jsonrpc": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz",
+ "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/vscode-languageserver": {
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz",
+ "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "vscode-languageserver-protocol": "3.17.5"
+ },
+ "bin": {
+ "installServerIntoExtension": "bin/installServerIntoExtension"
+ }
+ },
+ "node_modules/vscode-languageserver-protocol": {
+ "version": "3.17.5",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz",
+ "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "vscode-jsonrpc": "8.2.0",
+ "vscode-languageserver-types": "3.17.5"
+ }
+ },
+ "node_modules/vscode-languageserver-textdocument": {
+ "version": "1.0.12",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz",
+ "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vscode-languageserver-types": {
+ "version": "3.17.5",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz",
+ "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vscode-uri": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz",
+ "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vue": {
+ "version": "3.5.31",
+ "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.31.tgz",
+ "integrity": "sha512-iV/sU9SzOlmA/0tygSmjkEN6Jbs3nPoIPFhCMLD2STrjgOU8DX7ZtzMhg4ahVwf5Rp9KoFzcXeB1ZrVbLBp5/Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vue/compiler-dom": "3.5.31",
+ "@vue/compiler-sfc": "3.5.31",
+ "@vue/runtime-dom": "3.5.31",
+ "@vue/server-renderer": "3.5.31",
+ "@vue/shared": "3.5.31"
+ },
+ "peerDependencies": {
+ "typescript": "*"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/zwitch": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",
+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..40477e4
--- /dev/null
+++ b/package.json
@@ -0,0 +1,13 @@
+{
+ "private": true,
+ "scripts": {
+ "docs:dev": "vitepress dev docs",
+ "docs:build": "vitepress build docs",
+ "docs:preview": "vitepress preview docs"
+ },
+ "devDependencies": {
+ "vitepress": "^1.6.3",
+ "vitepress-plugin-mermaid": "^2.0.17",
+ "mermaid": "^11.4.1"
+ }
+}
diff --git a/packages/contrib/aif-agent-sandbox/CHANGELOG.md b/packages/contrib/aif-agent-sandbox/CHANGELOG.md
new file mode 100644
index 0000000..b5daa23
--- /dev/null
+++ b/packages/contrib/aif-agent-sandbox/CHANGELOG.md
@@ -0,0 +1,13 @@
+# Changelog
+
+## [v0.2.5] - 2026-03-31
+
+### Fixed
+- Export `AIFAgentSandbox` from package root so the documented import works
+- Fix stale `__version__` string in `__init__.py`
+
+## [v0.2.4.post0] - 2026-03-31
+
+### Fixed
+- Missing `manifest.json` in published package
+- Build timeout when installing `build-essential` on constrained runners
diff --git a/packages/contrib/aif-agent-sandbox/README.md b/packages/contrib/aif-agent-sandbox/README.md
new file mode 100644
index 0000000..02e88c0
--- /dev/null
+++ b/packages/contrib/aif-agent-sandbox/README.md
@@ -0,0 +1,50 @@
+# AIF Agent Sandbox
+
+An overlay image package for [quicksand](https://github.com/microsoft/quicksand) that provides a Python 3.12 environment with common AI agent tools pre-installed. Built on top of `quicksand-ubuntu`.
+
+## Installation
+
+```bash
+quicksand install aif-agent-sandbox
+```
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from aif_agent_sandbox import AIFAgentSandbox
+
+async def main():
+ async with AIFAgentSandbox() as sb:
+ result = await sb.execute("python3 --version")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand_core import Sandbox
+
+async with Sandbox(image="aif-agent-sandbox", memory="4G", cpus=4) as sb:
+ result = await sb.execute("pip list")
+```
+
+## What's Included
+
+Built on Ubuntu 24.04, this overlay adds:
+
+- **Python 3.12** virtual environment at `/opt/python` (with `pip`)
+- **uv** fast Python package manager
+- **build-essential** (gcc, make, etc.)
+- **requests** HTTP library
+- **pyyaml** YAML parsing
+- **ddgs** DuckDuckGo Search API
+- **markitdown** Markdown conversion tool
+
+## License
+
+MIT
diff --git a/packages/contrib/aif-agent-sandbox/aif_agent_sandbox/__init__.py b/packages/contrib/aif-agent-sandbox/aif_agent_sandbox/__init__.py
new file mode 100644
index 0000000..ede2bc3
--- /dev/null
+++ b/packages/contrib/aif-agent-sandbox/aif_agent_sandbox/__init__.py
@@ -0,0 +1,43 @@
+"""AIFAgentSandbox: pre-built overlay on quicksand-ubuntu."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from .sandbox import AIFAgentSandbox
+
+__version__ = "0.2.5"
+
+PACKAGE_DIR = Path(__file__).parent
+IMAGES_DIR = PACKAGE_DIR / "images"
+
+
+class _AIFAgentImageProvider:
+ """ImageProvider for the bundled AIF agent overlay."""
+
+ name = "aif-agent-sandbox"
+ type = "overlay"
+ images_dir = IMAGES_DIR
+
+ def resolve(self, arch: str | None = None):
+ 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."
+ )
+ return ImageResolver()._resolve_save(IMAGES_DIR)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _AIFAgentImageProvider()
+
+
+__all__ = [
+ "IMAGES_DIR",
+ "PACKAGE_DIR",
+ "AIFAgentSandbox",
+ "__version__",
+ "image",
+]
diff --git a/packages/contrib/aif-agent-sandbox/aif_agent_sandbox/sandbox.py b/packages/contrib/aif-agent-sandbox/aif_agent_sandbox/sandbox.py
new file mode 100644
index 0000000..86f1236
--- /dev/null
+++ b/packages/contrib/aif-agent-sandbox/aif_agent_sandbox/sandbox.py
@@ -0,0 +1,38 @@
+"""Pre-configured Sandbox using the bundled AIF agent overlay."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import Sandbox
+from quicksand_core._types import SandboxConfigParams
+
+
+class AIFAgentSandbox(Sandbox):
+ """Pre-configured Sandbox that boots from the bundled AIF agent overlay.
+
+ Requires quicksand-ubuntu to be installed (the overlay is built on top of it).
+
+ Usage::
+
+ async with AIFAgentSandbox() as sb:
+ result = await sb.execute("python3 --version")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "aif-agent-sandbox")
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
diff --git a/packages/contrib/aif-agent-sandbox/hatch_build.py b/packages/contrib/aif-agent-sandbox/hatch_build.py
new file mode 100644
index 0000000..40f6f3d
--- /dev/null
+++ b/packages/contrib/aif-agent-sandbox/hatch_build.py
@@ -0,0 +1,165 @@
+"""Hatch build hook for the AIF agent sandbox overlay.
+
+Boots Ubuntu, installs uv, Python 3.12, build-essential, and Python packages
+(requests, pyyaml, ddgs, markitdown), then saves the overlay.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+from collections.abc import Callable, Coroutine
+from pathlib import Path
+from typing import Any
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+SAVE_NAME = "aif-agent-sandbox"
+SHELL = "/bin/bash"
+
+logger = logging.getLogger("aif-agent-sandbox")
+
+
+async def _setup(shell: Callable[..., Coroutine[Any, Any, Any]]) -> None:
+ """Install steps for the AIF agent sandbox."""
+
+ # ── Install uv ──────────────────────────────────────────────
+ await shell("curl -LsSf https://astral.sh/uv/install.sh | sh", timeout=60)
+
+ # ── Create Python 3.12 venv with pip at /opt/python ────────
+ await shell("/root/.local/bin/uv venv /opt/python --python 3.12 --seed", timeout=120)
+
+ # ── Make venv discoverable on PATH ────────────────────────
+ # Symlink venv binaries into /usr/local/bin (guest agent's PATH)
+ await shell(
+ "find /opt/python/bin -maxdepth 1"
+ " \\( -type f -o -type l \\)"
+ " -executable -exec ln -sf {} /usr/local/bin/ \\;",
+ )
+
+ # The venv's python is a symlink to /usr/bin/python3.12. Linux
+ # resolves /proc/self/exe to the real binary, so Python never
+ # finds pyvenv.cfg and never adds the venv's site-packages.
+ # Fix: drop a .pth file into system dist-packages.
+ await shell(
+ "echo /opt/python/lib/python3.12/site-packages"
+ " > /usr/lib/python3/dist-packages/quicksand-venv.pth",
+ )
+
+ # profile.d for interactive shells (sets VIRTUAL_ENV + PATH)
+ await shell(
+ """cat > /etc/profile.d/python-venv.sh << 'PROF'
+export VIRTUAL_ENV=/opt/python
+export PATH=/opt/python/bin:$PATH
+PROF
+""",
+ )
+
+ # Verify
+ await shell("/opt/python/bin/python3 --version")
+ await shell("/opt/python/bin/pip --version")
+
+ # ── Install build-essential ─────────────────────────────────
+ await shell("apt-get update", timeout=120)
+ await shell("apt-get install -y build-essential", timeout=600)
+
+ # ── Install Python packages ─────────────────────────────────
+ await shell(
+ "/opt/python/bin/pip install requests 'pyyaml>=6.0'"
+ " 'ddgs>=9.11.2' 'markitdown[all]>=0.1.5'",
+ timeout=600,
+ )
+
+ await shell(
+ "/opt/python/bin/python3 -c "
+ "'import requests; import yaml; import ddgs; import markitdown;"
+ ' print("OK")\'',
+ )
+
+ # ── Clean caches ────────────────────────────────────────────
+ await shell("apt-get clean")
+ await shell("rm -rf /var/lib/apt/lists/* /root/.cache/pip /root/.cache/uv /tmp/*")
+
+
+class OverlayImageBuildHook(BuildHookInterface):
+ """Build hook that creates an overlay save from a running sandbox."""
+
+ PLUGIN_NAME = "aif-agent-sandbox-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ from quicksand_image_tools.build_utils import set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+
+ pkg_dir = Path(self.root) / "aif_agent_sandbox"
+ save_dir = pkg_dir / "images"
+ overlays_dir = save_dir / "overlays"
+
+ if not (save_dir / "manifest.json").exists() or not any(overlays_dir.glob("*.qcow2")):
+ self.app.display_info("Save not found, building overlay...")
+ asyncio.run(self._build_and_save(save_dir))
+
+ self.app.display_info(f"Including save: {save_dir}")
+
+ async def _build_and_save(self, save_dir: Path) -> None:
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+
+ from quicksand_core._types import NetworkMode
+ from quicksand_ubuntu import UbuntuSandbox
+
+ async with UbuntuSandbox(
+ memory="4G",
+ cpus=4,
+ network_mode=NetworkMode.FULL,
+ disk_size="10G",
+ ) as sb:
+ await _setup(_make_shell(sb))
+ await sb.save(SAVE_NAME, workspace=save_dir.parent, compress=True)
+
+ built = save_dir.parent / SAVE_NAME
+ if save_dir.exists():
+ shutil.rmtree(save_dir)
+ built.rename(save_dir)
+
+
+def _make_shell(sb) -> Callable[..., Coroutine[Any, Any, Any]]:
+ """Create a shell callable that streams output and raises on failure."""
+ stdout_buf: list[str] = []
+ stderr_buf: list[str] = []
+
+ def _flush_lines(buf: list[str], log_fn) -> None:
+ text = "".join(buf)
+ buf.clear()
+ for line in text.splitlines():
+ if line:
+ log_fn("%s", line)
+
+ def _on_stdout(chunk: str) -> None:
+ stdout_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stdout_buf, logger.info)
+
+ def _on_stderr(chunk: str) -> None:
+ stderr_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stderr_buf, logger.warning)
+
+ async def shell(cmd: str, **kwargs) -> None:
+ logger.info(">>> %s", cmd)
+ stdout_buf.clear()
+ stderr_buf.clear()
+ result = await sb.execute(
+ cmd,
+ shell=SHELL,
+ on_stdout=_on_stdout,
+ on_stderr=_on_stderr,
+ **kwargs,
+ )
+ _flush_lines(stdout_buf, logger.info)
+ _flush_lines(stderr_buf, logger.warning)
+ if result.exit_code != 0:
+ raise RuntimeError(f"Command failed (exit {result.exit_code}): {cmd}\n{result.stderr}")
+
+ return shell
diff --git a/packages/contrib/aif-agent-sandbox/pyproject.toml b/packages/contrib/aif-agent-sandbox/pyproject.toml
new file mode 100644
index 0000000..4f87d61
--- /dev/null
+++ b/packages/contrib/aif-agent-sandbox/pyproject.toml
@@ -0,0 +1,34 @@
+[project]
+name = "aif-agent-sandbox"
+version = "0.3.4"
+description = "Overlay image package for quicksand"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+ "quicksand-ubuntu>=0.8.4",
+]
+
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "quicksand-ubuntu", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["aif_agent_sandbox"]
+artifacts = [
+ "aif_agent_sandbox/images/manifest.json",
+ "aif_agent_sandbox/images/overlays/*.qcow2",
+]
+
+[project.entry-points."quicksand.images"]
+aif-agent-sandbox = "aif_agent_sandbox:image"
+
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
+quicksand-ubuntu = { workspace = true }
diff --git a/packages/contrib/aif-cua-agent-sandbox/CHANGELOG.md b/packages/contrib/aif-cua-agent-sandbox/CHANGELOG.md
new file mode 100644
index 0000000..5dbc1e2
--- /dev/null
+++ b/packages/contrib/aif-cua-agent-sandbox/CHANGELOG.md
@@ -0,0 +1,11 @@
+# Changelog
+
+## [v0.1.7] - 2026-03-31
+
+### Fixed
+- Slimmed overlay image by ~160 MB by removing unused Playwright caches, headless shell, Vulkan drivers, and Node.js runtime
+- Export `AifCuaAgentSandbox` from package root so the documented import works
+- Fix stale `__version__` string in `__init__.py`
+
+### Changed
+- Updated README to document noVNC web client on port 6080
diff --git a/packages/contrib/aif-cua-agent-sandbox/README.md b/packages/contrib/aif-cua-agent-sandbox/README.md
new file mode 100644
index 0000000..c384913
--- /dev/null
+++ b/packages/contrib/aif-cua-agent-sandbox/README.md
@@ -0,0 +1,52 @@
+# AIF CUA Agent Sandbox
+
+An overlay image package for [quicksand](https://github.com/microsoft/quicksand) that adds browser automation via Playwright and Chromium with a VNC-accessible virtual display. Built on top of `aif-agent-sandbox`.
+
+## Installation
+
+```bash
+quicksand install aif-cua-agent-sandbox
+```
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from aif_cua_agent_sandbox import AifCuaAgentSandbox
+
+async def main():
+ async with AifCuaAgentSandbox() as sb:
+ # Xvfb, x11vnc, and Chromium start automatically via systemd
+ result = await sb.execute("python3 -c 'from playwright.sync_api import sync_playwright; print(\"OK\")'")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand_core import Sandbox
+
+async with Sandbox(image="aif-cua-agent-sandbox", memory="4G", cpus=4) as sb:
+ result = await sb.execute("chromium --version")
+```
+
+## What's Included
+
+Everything from [aif-agent-sandbox](../aif-agent-sandbox) (Python 3.12, uv, requests, pyyaml, ddgs, markitdown), plus:
+
+- **Xvfb** virtual framebuffer (display `:0`, 1280x1024x24)
+- **x11vnc** VNC server on port 5901
+- **Playwright** browser automation library
+- **Chromium** browser (installed via Playwright)
+- **noVNC** web client on port 6080
+- **Fonts** (Liberation, Noto Color Emoji)
+
+All services (Xvfb, x11vnc, Chromium, noVNC) are enabled as systemd units and start automatically on boot.
+
+## License
+
+MIT
diff --git a/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/.DS_Store b/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/.DS_Store
new file mode 100644
index 0000000..0b1ee15
Binary files /dev/null and b/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/.DS_Store differ
diff --git a/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/__init__.py b/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/__init__.py
new file mode 100644
index 0000000..76386fc
--- /dev/null
+++ b/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/__init__.py
@@ -0,0 +1,43 @@
+"""aif-cua-agent-sandbox: overlay image package for quicksand."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from .sandbox import AifCuaAgentSandbox
+
+__version__ = "0.1.7"
+
+PACKAGE_DIR = Path(__file__).parent
+IMAGES_DIR = PACKAGE_DIR / "images"
+
+
+class _AifCuaAgentImageProvider:
+ """ImageProvider for the bundled aif-cua-agent-sandbox overlay."""
+
+ name = "aif-cua-agent-sandbox"
+ type = "overlay"
+ images_dir = IMAGES_DIR
+
+ def resolve(self, arch: str | None = None):
+ 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."
+ )
+ return ImageResolver()._resolve_save(IMAGES_DIR)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _AifCuaAgentImageProvider()
+
+
+__all__ = [
+ "IMAGES_DIR",
+ "PACKAGE_DIR",
+ "AifCuaAgentSandbox",
+ "__version__",
+ "image",
+]
diff --git a/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/sandbox.py b/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/sandbox.py
new file mode 100644
index 0000000..217d46b
--- /dev/null
+++ b/packages/contrib/aif-cua-agent-sandbox/aif_cua_agent_sandbox/sandbox.py
@@ -0,0 +1,38 @@
+"""Pre-configured Sandbox using the bundled overlay save."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import Sandbox
+from quicksand_core._types import SandboxConfigParams
+
+
+class AifCuaAgentSandbox(Sandbox):
+ """Pre-configured Sandbox that boots from the bundled overlay.
+
+ Requires aif-agent-sandbox to be installed (the overlay is built on top of it).
+
+ Usage::
+
+ async with AifCuaAgentSandbox() as sb:
+ result = await sb.execute("echo hello")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "aif-cua-agent-sandbox")
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
diff --git a/packages/contrib/aif-cua-agent-sandbox/hatch_build.py b/packages/contrib/aif-cua-agent-sandbox/hatch_build.py
new file mode 100644
index 0000000..0544e57
--- /dev/null
+++ b/packages/contrib/aif-cua-agent-sandbox/hatch_build.py
@@ -0,0 +1,259 @@
+"""Hatch build hook for overlay image packages.
+
+Edit _setup() to customize what gets installed in the sandbox.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+from collections.abc import Callable, Coroutine
+from pathlib import Path
+from typing import Any
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+SAVE_NAME = "aif-cua-agent-sandbox"
+BASE_IMAGE = "aif-agent-sandbox"
+SHELL = "/bin/bash"
+
+logger = logging.getLogger("aif-cua-agent-sandbox")
+
+# Type alias for the shell callable passed to _setup
+Shell = Callable[..., Coroutine[Any, Any, Any]]
+
+
+# =============================================================================
+# EDIT HERE — Install steps for your overlay image
+#
+# `shell` runs a command inside the sandbox, streams stdout/stderr,
+# and raises RuntimeError on non-zero exit. Pass timeout= for slow commands.
+#
+# Examples:
+# await shell("apt-get update", timeout=120)
+# await shell("pip install numpy", timeout=300)
+# =============================================================================
+
+
+async def _setup(shell: Shell) -> None:
+ # ── Install Xvfb, x11vnc, and Playwright system deps ────────
+ await shell("apt-get update", timeout=120)
+ await shell(
+ "apt-get install -y xvfb x11vnc xauth fonts-liberation fonts-noto-color-emoji",
+ timeout=300,
+ )
+ await shell(
+ "apt-get install -y novnc websockify socat rsync",
+ timeout=300,
+ )
+
+ # ── Install Playwright and Chromium via Playwright ───────────
+ await shell("/opt/python/bin/pip install playwright", timeout=300)
+ await shell(
+ "PLAYWRIGHT_BROWSERS_PATH=/opt/playwright"
+ " /opt/python/bin/python3 -m playwright install --with-deps chromium",
+ timeout=300,
+ )
+
+ # ── Environment for Playwright browser path ──────────────────
+ await shell(
+ """cat > /etc/profile.d/playwright.sh << 'PROF'
+export PLAYWRIGHT_BROWSERS_PATH=/opt/playwright
+export DISPLAY=:0
+PROF
+""",
+ )
+
+ # ── Systemd service: Xvfb on display :0 ─────────────────────
+ await shell(
+ """cat > /etc/systemd/system/xvfb.service << 'EOF'
+[Unit]
+Description=Xvfb virtual framebuffer
+After=network.target
+
+[Service]
+ExecStart=/usr/bin/Xvfb :0 -screen 0 1280x1024x24 -ac
+Restart=always
+RestartSec=2
+
+[Install]
+WantedBy=multi-user.target
+EOF
+""",
+ )
+
+ # ── Systemd service: x11vnc on port 5901 ────────────────────
+ await shell(
+ """cat > /etc/systemd/system/x11vnc.service << 'EOF'
+[Unit]
+Description=x11vnc VNC server for display :0
+After=xvfb.service
+Requires=xvfb.service
+
+[Service]
+Environment=DISPLAY=:0
+ExecStart=/usr/bin/x11vnc -display :0 -rfbport 5901 -forever -shared -nopw
+Restart=always
+RestartSec=2
+
+[Install]
+WantedBy=multi-user.target
+EOF
+""",
+ )
+
+ # ── Find Playwright's Chromium binary ─────────────────────────
+ await shell(
+ "CHROMIUM=$(find /opt/playwright -name chrome -type f"
+ " | head -1) && ln -sf $CHROMIUM /usr/local/bin/chromium",
+ )
+
+ # ── Systemd service: Chromium on display :0 ──────────────────
+ await shell(
+ """cat > /etc/systemd/system/chromium.service << 'EOF'
+[Unit]
+Description=Chromium browser on display :0
+After=xvfb.service
+Requires=xvfb.service
+
+[Service]
+Environment=DISPLAY=:0
+ExecStart=/usr/local/bin/chromium --no-sandbox --disable-gpu --start-maximized --no-first-run
+Restart=always
+RestartSec=3
+
+[Install]
+WantedBy=multi-user.target
+EOF
+""",
+ )
+
+ # ── Systemd service: noVNC web client on port 6080 ───────────
+ await shell(
+ """cat > /etc/systemd/system/novnc.service << 'EOF'
+[Unit]
+Description=noVNC web client proxying to x11vnc
+After=x11vnc.service
+Requires=x11vnc.service
+
+[Service]
+ExecStart=/usr/bin/websockify --web /usr/share/novnc 6080 localhost:5901
+Restart=always
+RestartSec=2
+
+[Install]
+WantedBy=multi-user.target
+EOF
+""",
+ )
+
+ # ── Enable all services ──────────────────────────────────────
+ await shell("systemctl enable xvfb.service")
+ await shell("systemctl enable x11vnc.service")
+ await shell("systemctl enable chromium.service")
+ await shell("systemctl enable novnc.service")
+
+ # ── Verify installs ──────────────────────────────────────────
+ await shell("/opt/python/bin/python3 -c 'import playwright; print(\"playwright OK\")'")
+ await shell("which Xvfb && which x11vnc && test -x /usr/local/bin/chromium")
+
+ # ── Clean caches ─────────────────────────────────────────────
+ await shell("apt-get clean")
+ await shell("rm -rf /var/lib/apt/lists/* /root/.cache/pip /tmp/*")
+ # Playwright caches a .zip of the browser it downloaded
+ await shell("rm -rf /root/.cache/ms-playwright")
+ # Headless shell is unused — we run full Chromium with a display
+ await shell("rm -rf /opt/playwright/chromium_headless_shell-*")
+ # Vulkan GPU drivers are useless in a QEMU VM (~97 MB)
+ # Keep libLLVM + libgallium — Chromium needs Mesa llvmpipe for software rendering
+ await shell("rm -f /usr/lib/aarch64-linux-gnu/libvulkan_*.so*")
+ # Node.js pulled in by Playwright --with-deps but not needed at runtime
+ await shell("rm -f /usr/lib/aarch64-linux-gnu/libnode.so*")
+
+
+# =============================================================================
+
+
+class OverlayImageBuildHook(BuildHookInterface):
+ """Build hook that creates an overlay save from a running sandbox."""
+
+ PLUGIN_NAME = "aif-cua-agent-sandbox-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ from quicksand_image_tools.build_utils import set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+
+ pkg_dir = Path(self.root) / "aif_cua_agent_sandbox"
+ save_dir = pkg_dir / "images"
+ overlays_dir = save_dir / "overlays"
+
+ if not (save_dir / "manifest.json").exists() or not any(overlays_dir.glob("*.qcow2")):
+ self.app.display_info("Save not found, building overlay...")
+ asyncio.run(self._build_and_save(save_dir))
+
+ self.app.display_info(f"Including save: {save_dir}")
+
+ async def _build_and_save(self, save_dir: Path) -> None:
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+
+ from quicksand_core import Sandbox
+ from quicksand_core._types import NetworkMode
+
+ async with Sandbox(
+ image=BASE_IMAGE,
+ memory="4G",
+ cpus=4,
+ network_mode=NetworkMode.FULL,
+ disk_size="10G",
+ ) as sb:
+ await _setup(_make_shell(sb))
+ await sb.save(SAVE_NAME, workspace=save_dir.parent, compress=True)
+
+ built = save_dir.parent / SAVE_NAME
+ if save_dir.exists():
+ shutil.rmtree(save_dir)
+ built.rename(save_dir)
+
+
+def _make_shell(sb) -> Shell:
+ """Create a shell callable that streams output and raises on failure."""
+ stdout_buf: list[str] = []
+ stderr_buf: list[str] = []
+
+ def _flush_lines(buf: list[str], log_fn) -> None:
+ text = "".join(buf)
+ buf.clear()
+ for line in text.splitlines():
+ if line:
+ log_fn("%s", line)
+
+ def _on_stdout(chunk: str) -> None:
+ stdout_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stdout_buf, logger.info)
+
+ def _on_stderr(chunk: str) -> None:
+ stderr_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stderr_buf, logger.warning)
+
+ async def shell(cmd: str, **kwargs) -> None:
+ logger.info(">>> %s", cmd)
+ stdout_buf.clear()
+ stderr_buf.clear()
+ result = await sb.execute(
+ cmd,
+ shell=SHELL,
+ on_stdout=_on_stdout,
+ on_stderr=_on_stderr,
+ **kwargs,
+ )
+ _flush_lines(stdout_buf, logger.info)
+ _flush_lines(stderr_buf, logger.warning)
+ if result.exit_code != 0:
+ raise RuntimeError(f"Command failed (exit {result.exit_code}): {cmd}\n{result.stderr}")
+
+ return shell
diff --git a/packages/contrib/aif-cua-agent-sandbox/pyproject.toml b/packages/contrib/aif-cua-agent-sandbox/pyproject.toml
new file mode 100644
index 0000000..e7604e4
--- /dev/null
+++ b/packages/contrib/aif-cua-agent-sandbox/pyproject.toml
@@ -0,0 +1,35 @@
+[project]
+name = "aif-cua-agent-sandbox"
+version = "0.2.4"
+description = "Overlay image package for quicksand"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+ "aif-agent-sandbox>=0.3.4",
+]
+
+
+[project.entry-points."quicksand.images"]
+aif-cua-agent-sandbox = "aif_cua_agent_sandbox:image"
+
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "aif-agent-sandbox", "quicksand-ubuntu", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["aif_cua_agent_sandbox"]
+artifacts = [
+ "aif_cua_agent_sandbox/images/manifest.json",
+ "aif_cua_agent_sandbox/images/overlays/*.qcow2",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-ubuntu = { workspace = true }
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
+aif-agent-sandbox = { workspace = true }
diff --git a/packages/dev/quicksand-base-scaffold/README.md b/packages/dev/quicksand-base-scaffold/README.md
new file mode 100644
index 0000000..27624a4
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/README.md
@@ -0,0 +1,82 @@
+# quicksand-base-scaffold
+
+Scaffold a new base image package for quicksand.
+
+Base image packages define a VM from a Dockerfile. The Dockerfile installs a Linux kernel, init system, networking, and the quicksand guest agent. The build process converts the Docker image into a qcow2 disk + kernel + initramfs that QEMU can boot.
+
+## Usage
+
+```bash
+quicksand-base-scaffold mylinux
+```
+
+This copies `quicksand-ubuntu` into `packages/quicksand-mylinux/`, renames everything, and writes a skeleton Dockerfile.
+
+To copy from Alpine instead:
+
+```bash
+quicksand-base-scaffold mylinux --base alpine
+```
+
+## Output Structure
+
+```
+packages/quicksand-mylinux/
+├── pyproject.toml
+├── hatch_build.py # Builds image during uv build
+├── README.md
+└── quicksand_mylinux/
+ ├── __init__.py # Python API + entry points
+ ├── images/ # Built images (populated during uv build)
+ └── docker/
+ ├── Dockerfile # Edit this
+ ├── agent/ # Copied automatically at build time
+ └── ... # Init configs
+```
+
+## Next Steps
+
+1. Set `DISTRO_VERSION` in `quicksand_mylinux/__init__.py`
+
+2. Edit `quicksand_mylinux/docker/Dockerfile` — your image must include:
+ - Linux kernel with initramfs (for virtio drivers)
+ - Init system (systemd or OpenRC)
+ - 9p kernel modules (`9p`, `9pnet`, `9pnet_virtio`)
+ - `quicksand` user with passwordless sudo
+ - DHCP networking
+ - The Rust guest agent (compiled via multi-stage Docker build)
+ - `CMD ["/sbin/init"]`
+
+3. Build:
+
+```bash
+uv sync
+uv build --package quicksand-mylinux
+```
+
+4. Test:
+
+```bash
+quicksand run mylinux
+```
+
+## Dockerfile Example
+
+See `packages/quicksand-ubuntu/quicksand_ubuntu/docker/Dockerfile` for a complete Ubuntu example, or `packages/quicksand-alpine/quicksand_alpine/docker/Dockerfile` for Alpine.
+
+The key pattern is a multi-stage build:
+
+```dockerfile
+# Stage 1: Compile Rust agent
+FROM rust:bookworm AS agent-builder
+WORKDIR /build
+COPY agent/Cargo.toml agent/Cargo.lock* ./
+COPY agent/src ./src
+RUN cargo build --release && strip /build/target/release/quicksand-guest-agent
+
+# Stage 2: Your image
+FROM your-base:version
+RUN install-kernel && install-init && configure-networking
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/
+CMD ["/sbin/init"]
+```
diff --git a/packages/dev/quicksand-base-scaffold/hatch_build.py b/packages/dev/quicksand-base-scaffold/hatch_build.py
new file mode 100644
index 0000000..33cdebd
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/hatch_build.py
@@ -0,0 +1,73 @@
+"""Hatch build hook for platform-specific VM image wheels."""
+
+from __future__ import annotations
+
+import logging
+import re
+from pathlib import Path
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+logger = logging.getLogger(__name__)
+
+MODULE_NAME = "quicksand_base_scaffold"
+
+
+def _read_distro_version(root: Path) -> str:
+ """Read DISTRO_VERSION from __init__.py without importing the module."""
+ init_file = root / MODULE_NAME / "__init__.py"
+ content = init_file.read_text()
+ match = re.search(r'^DISTRO_VERSION\s*=\s*["\']([^"\']+)["\']', content, re.MULTILINE)
+ if not match:
+ raise RuntimeError(f"Could not find DISTRO_VERSION in {init_file}")
+ return match.group(1)
+
+
+class BaseImageBuildHook(BuildHookInterface):
+ """Build hook that packages VM images with platform-specific wheel tags."""
+
+ PLUGIN_NAME = "quicksand-base-scaffold-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ if MODULE_NAME == "quicksand_base_scaffold":
+ return
+
+ distro_version = _read_distro_version(Path(self.root))
+ if distro_version == "VERSION":
+ # Scaffold template — not yet customized, skip image build
+ return
+
+ from quicksand_image_tools.build_utils import get_image_arch, set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+ arch = get_image_arch()
+
+ pkg_dir = Path(self.root) / MODULE_NAME
+ images_dir = pkg_dir / "images"
+ image_path = images_dir / f"quicksand-base-scaffold-{distro_version}-{arch}.qcow2"
+ dockerfile_path = pkg_dir / "docker" / "Dockerfile"
+
+ if not image_path.exists():
+ self.app.display_info(f"Image not found: {image_path.name}, building...")
+ self._build_image(dockerfile_path, image_path)
+
+ self.app.display_info(f"Including image: {image_path}")
+
+ def _build_image(self, dockerfile: Path, output: Path) -> None:
+ try:
+ from quicksand_image_tools import build_image
+
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+ build_log = logging.getLogger("quicksand-base-scaffold")
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ build_image(dockerfile, output_path=output, log=build_log)
+
+ except ImportError as e:
+ raise RuntimeError(
+ f"quicksand-image-tools is required to build images: {e}\n\n"
+ f"Install it first: pip install quicksand-image-tools"
+ ) from e
+ except Exception as e:
+ raise RuntimeError(f"Failed to build image: {e}\n\nMake sure Docker is running.") from e
diff --git a/packages/dev/quicksand-base-scaffold/pyproject.toml b/packages/dev/quicksand-base-scaffold/pyproject.toml
new file mode 100644
index 0000000..349ed18
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/pyproject.toml
@@ -0,0 +1,37 @@
+[project]
+name = "quicksand-base-scaffold"
+version = "0.2.4"
+description = "Template base image package for quicksand"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+ "tomlkit>=0.13",
+]
+
+[project.scripts]
+quicksand-base-scaffold = "quicksand_base_scaffold.scaffold:main"
+
+[project.entry-points."quicksand.images"]
+quicksand-base-scaffold = "quicksand_base_scaffold:image"
+
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_base_scaffold"]
+artifacts = [
+ "quicksand_base_scaffold/images/*.qcow2",
+ "quicksand_base_scaffold/images/*.kernel",
+ "quicksand_base_scaffold/images/*.initrd",
+ "quicksand_base_scaffold/docker/*",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-image-tools = { workspace = true }
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
diff --git a/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/__init__.py b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/__init__.py
new file mode 100644
index 0000000..b439102
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/__init__.py
@@ -0,0 +1,96 @@
+"""QuicksandBaseScaffold: template base image package for quicksand."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import ResolvedImage, Sandbox
+from quicksand_core._types import SandboxConfigParams
+from quicksand_core.host import Architecture
+from quicksand_core.qemu.platform import get_platform_config
+
+__version__ = "0.1.0"
+
+DISTRO_VERSION = "VERSION"
+
+_PACKAGE_DIR = Path(__file__).parent
+_IMAGES_DIR = _PACKAGE_DIR / "images"
+_DOCKER_DIR = _PACKAGE_DIR / "docker"
+
+
+class _QuicksandBaseScaffoldImageProvider:
+ """ImageProvider for the bundled base image."""
+
+ name = "quicksand-base-scaffold"
+ type = "base"
+ images_dir = _IMAGES_DIR
+
+ def resolve(self, arch: str | None = None) -> ResolvedImage:
+ return _get_image_artifacts(arch)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _QuicksandBaseScaffoldImageProvider()
+
+
+def _get_image_artifacts(arch: str | None = None) -> ResolvedImage:
+ if arch is None:
+ config = get_platform_config()
+ arch = "arm64" if config.arch.arch_type == Architecture.ARM64 else "amd64"
+
+ image_path = _IMAGES_DIR / f"quicksand-base-scaffold-{DISTRO_VERSION}-{arch}.qcow2"
+
+ if not image_path.exists():
+ image_path = _IMAGES_DIR / f"quicksand-base-scaffold-{DISTRO_VERSION}.qcow2"
+
+ if not image_path.exists():
+ available = list(_IMAGES_DIR.glob("*.qcow2")) if _IMAGES_DIR.exists() else []
+ if available:
+ available_str = ", ".join(p.name for p in available)
+ raise FileNotFoundError(f"Image for {arch} not found. Available: {available_str}")
+ raise FileNotFoundError(
+ f"No images found in {_IMAGES_DIR}. The package may not have been built correctly."
+ )
+
+ return ResolvedImage(
+ name="quicksand-base-scaffold",
+ chain=[image_path],
+ kernel=image_path.with_suffix(".kernel"),
+ initrd=image_path.with_suffix(".initrd"),
+ )
+
+
+class QuicksandBaseScaffoldSandbox(Sandbox):
+ """Pre-configured Sandbox using the bundled image.
+
+ Usage::
+
+ async with QuicksandBaseScaffoldSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "quicksand-base-scaffold")
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
+
+
+__all__ = [
+ "DISTRO_VERSION",
+ "QuicksandBaseScaffoldSandbox",
+ "__version__",
+ "image",
+]
diff --git a/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/docker/.gitignore b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/docker/.gitignore
new file mode 100644
index 0000000..3fc43d4
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/docker/.gitignore
@@ -0,0 +1,2 @@
+# Ignore agent source (symlinked at build time)
+agent/
diff --git a/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/docker/Dockerfile b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/docker/Dockerfile
new file mode 100644
index 0000000..0f600c0
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/docker/Dockerfile
@@ -0,0 +1,31 @@
+# quicksand-base-scaffold base image
+# See quicksand-ubuntu/docker/Dockerfile for a full example.
+
+# Stage 1: Build the Rust guest agent
+FROM rust:bookworm AS agent-builder
+WORKDIR /build
+COPY agent/Cargo.toml agent/Cargo.lock* ./
+COPY agent/src ./src
+RUN cargo build --release && strip /build/target/release/quicksand-guest-agent
+
+# Stage 2: Your base image
+FROM ubuntu:24.04
+
+# Non-interactive apt
+ENV DEBIAN_FRONTEND=noninteractive
+
+# TODO: Install your kernel and init system
+# RUN apt-get update && apt-get install -y linux-image-virtual systemd systemd-sysv
+
+# TODO: 9p modules for host file sharing
+# RUN echo "9p" >> /etc/modules && echo "9pnet" >> /etc/modules && echo "9pnet_virtio" >> /etc/modules
+
+# TODO: Create quicksand user with passwordless sudo
+# RUN useradd -m -s /bin/bash quicksand
+
+# TODO: DHCP networking
+
+# Install the guest agent
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/quicksand-guest-agent
+
+CMD ["/sbin/init"]
diff --git a/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/images/.gitignore b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/images/.gitignore
new file mode 100644
index 0000000..bb6857f
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/images/.gitignore
@@ -0,0 +1,3 @@
+# Build artifacts — generated during uv build
+*
+!.gitignore
diff --git a/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/scaffold.py b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/scaffold.py
new file mode 100644
index 0000000..29a20ac
--- /dev/null
+++ b/packages/dev/quicksand-base-scaffold/quicksand_base_scaffold/scaffold.py
@@ -0,0 +1,173 @@
+"""Scaffold a new base image package by copying this template.
+
+Copies the quicksand-base-scaffold package, renames everything to
+the target name, and resets versions.
+"""
+
+from __future__ import annotations
+
+import shutil
+import sys
+from pathlib import Path
+
+import tomlkit
+from tomlkit.container import OutOfOrderTableProxy
+from tomlkit.items import Table
+
+TEMPLATE_DIR = Path(__file__).resolve().parent.parent
+
+_ARTIFACT_EXTENSIONS = {".qcow2", ".kernel", ".initrd"}
+
+
+def _to_under(name: str) -> str:
+ return name.replace("-", "_")
+
+
+def _to_title(name: str) -> str:
+ return "".join(p.capitalize() for p in name.replace("-", " ").split())
+
+
+def _clean_pyproject(pyproject: Path) -> None:
+ """Strip monorepo-only config from a scaffolded pyproject.toml."""
+ doc = tomlkit.parse(pyproject.read_text())
+ # Remove [tool.uv.sources] (workspace refs don't apply outside monorepo)
+ if "tool" in doc:
+ tool = doc["tool"]
+ assert isinstance(tool, (Table, OutOfOrderTableProxy))
+ if "uv" in tool:
+ uv = tool["uv"]
+ assert isinstance(uv, (Table, OutOfOrderTableProxy))
+ if "sources" in uv:
+ del uv["sources"]
+ if not uv:
+ del tool["uv"]
+ if not tool:
+ del doc["tool"]
+ # Reset version, remove scaffold entry point, strip scaffold-only deps
+ project = doc["project"]
+ assert isinstance(project, (Table, OutOfOrderTableProxy))
+ project["version"] = "0.1.0"
+ if "scripts" in project:
+ del project["scripts"]
+ deps = list(project.get("dependencies", []))
+ project["dependencies"] = [d for d in deps if "tomlkit" not in str(d)]
+ pyproject.write_text(tomlkit.dumps(doc))
+
+
+def _is_text_file(path: Path) -> bool:
+ try:
+ with open(path, "rb") as f:
+ chunk = f.read(8192)
+ return b"\x00" not in chunk
+ except OSError:
+ return False
+
+
+def _ignore_artifacts(_directory: str, files: list[str]) -> set[str]:
+ ignored = set()
+ for f in files:
+ if Path(f).suffix in _ARTIFACT_EXTENSIONS:
+ ignored.add(f)
+ if f in ("__pycache__", ".pytest_cache", "scaffold.py") or f.endswith(".egg-info"):
+ ignored.add(f)
+ return ignored
+
+
+def scaffold(
+ name: str,
+ output_dir: Path | None = None,
+) -> None:
+ """Scaffold a new base image package.
+
+ Args:
+ name: Package name (e.g. ``quicksand-mylinux``).
+ output_dir: Where to create the package. Defaults to ``./<name>``.
+ """
+ name = name.lower()
+ if "/" in name or "\\" in name:
+ raise ValueError("name must be a plain package name, not a path")
+
+ if output_dir is None:
+ output_dir = Path(name)
+
+ if output_dir.exists() and any(output_dir.iterdir()):
+ raise FileExistsError(f"{output_dir} already exists and is non-empty")
+
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
+
+ # Copy template, excluding artifacts and scaffold script
+ shutil.copytree(TEMPLATE_DIR, output_dir, ignore=_ignore_artifacts)
+
+ # Rename module directory
+ old_module = output_dir / "quicksand_base_scaffold"
+ new_module = output_dir / _to_under(name)
+ if old_module.exists():
+ old_module.rename(new_module)
+
+ # String replacements
+ old_name = "quicksand-base-scaffold"
+ title = _to_title(name)
+ # Avoid QuicksandBaseScaffoldSandbox -> MySandboxSandbox
+ if title.endswith("Sandbox"):
+ title = title[: -len("Sandbox")]
+ replacements = [
+ ("quicksand_base_scaffold", _to_under(name)),
+ (old_name, name),
+ ("QuicksandBaseScaffold", title),
+ ]
+
+ for filepath in output_dir.rglob("*"):
+ if not filepath.is_file() or not _is_text_file(filepath):
+ continue
+ content = filepath.read_text()
+ original = content
+ for old, new in replacements:
+ content = content.replace(old, new)
+ if content != original:
+ filepath.write_text(content)
+
+ # Clean up pyproject.toml for standalone use
+ pyproject = output_dir / "pyproject.toml"
+ if pyproject.exists():
+ _clean_pyproject(pyproject)
+
+ # Reset README
+ readme = output_dir / "README.md"
+ readme.write_text(f"# {name}\n\n```bash\npip install {name}\n```\n")
+
+ print(f"Scaffolded base image package: {output_dir}")
+ print()
+ print("Next steps:")
+ print(f" 1. Set DISTRO_VERSION in {_to_under(name)}/__init__.py")
+ print(f" 2. Edit {_to_under(name)}/docker/Dockerfile")
+ print(" 3. pip install -e . && uv build")
+ print()
+ print("The guest agent source is copied into docker/agent/ automatically at build time.")
+
+
+def main() -> None:
+ """CLI entry point."""
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ prog="quicksand-base-scaffold",
+ description="Scaffold a new base image package from a template",
+ )
+ parser.add_argument("name", help="Package name (e.g. quicksand-mylinux)")
+ parser.add_argument(
+ "--output-dir",
+ type=Path,
+ default=None,
+ help="Output directory (default: ./<name>)",
+ )
+ args = parser.parse_args()
+
+ try:
+ scaffold(name=args.name, output_dir=args.output_dir)
+ except (ValueError, FileExistsError) as e:
+ print(f"Error: {e}", file=sys.stderr)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/dev/quicksand-build-tools/pyproject.toml b/packages/dev/quicksand-build-tools/pyproject.toml
new file mode 100644
index 0000000..1fd3057
--- /dev/null
+++ b/packages/dev/quicksand-build-tools/pyproject.toml
@@ -0,0 +1,14 @@
+[project]
+name = "quicksand-build-tools"
+version = "0.4.4.dev0"
+description = "Shared build utilities for bundling native binaries into quicksand wheels."
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = []
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_build_tools"]
diff --git a/packages/dev/quicksand-build-tools/quicksand_build_tools/__init__.py b/packages/dev/quicksand-build-tools/quicksand_build_tools/__init__.py
new file mode 100644
index 0000000..4d108ea
--- /dev/null
+++ b/packages/dev/quicksand-build-tools/quicksand_build_tools/__init__.py
@@ -0,0 +1,405 @@
+"""Shared build utilities for bundling native binaries into quicksand platform wheels.
+
+Provides platform-specific logic for:
+- Discovering and copying shared library dependencies
+- Rewriting library paths (install_name_tool on macOS, patchelf on Linux)
+- System library blocklists (libs that must NOT be bundled)
+- Binary verification (catch missing deps at build time)
+- Platform wheel tagging
+"""
+
+from __future__ import annotations
+
+import os
+import platform
+import shutil
+import subprocess
+import sysconfig
+import tempfile
+from pathlib import Path
+from typing import Protocol
+
+# System libraries that must NOT be bundled (loaded from host OS).
+# Checked by prefix matching against the library filename.
+SYSTEM_LIBS: dict[str, set[str]] = {
+ "darwin": set(), # macOS system libs don't exist on disk (dyld shared cache)
+ "linux": {
+ "libc.",
+ "libm.",
+ "libpthread.",
+ "libdl.",
+ "librt.",
+ "ld-linux",
+ "libgcc_s.",
+ "libstdc++.",
+ "linux-vdso",
+ },
+ "windows": {
+ "kernel32",
+ "ntdll",
+ "msvcrt",
+ "user32",
+ "gdi32",
+ "advapi32",
+ "shell32",
+ "ole32",
+ "oleaut32",
+ "ws2_32",
+ "crypt32",
+ "secur32",
+ "api-ms-",
+ "ext-ms-",
+ "vcruntime",
+ "ucrtbase",
+ "msvcp",
+ },
+}
+
+
+class DisplayApp(Protocol):
+ """Protocol for Hatchling's app display interface."""
+
+ def display_info(self, message: str) -> None: ...
+ def display_warning(self, message: str) -> None: ...
+
+
+class BinaryBundler:
+ """Bundles native binaries and their shared library dependencies into a wheel.
+
+ Usage::
+
+ bundler = BinaryBundler(app) # app = Hatchling BuildHookInterface
+ bundler.bundle(binary_path, bin_dir)
+ bundler.verify(binary_path, bin_dir)
+ """
+
+ def __init__(self, app: DisplayApp) -> None:
+ self.app = app
+
+ # -----------------------------------------------------------------
+ # Public API
+ # -----------------------------------------------------------------
+
+ def should_bundle(self, lib_path: str, plat: str) -> bool:
+ """Check if a library should be bundled.
+
+ Uses a consistent pattern across all platforms:
+ 1. Skip @-prefixed paths (loader-relative, macOS only)
+ 2. Skip if file doesn't exist on disk (system lib in shared cache)
+ 3. Skip if in system blocklist
+ 4. Otherwise, bundle it
+ """
+ if lib_path.startswith("@"):
+ return False
+ if not Path(lib_path).exists():
+ return False
+ lib_name = Path(lib_path).name.lower()
+ blocklist = SYSTEM_LIBS.get(plat, set())
+ return not any(lib_name.startswith(prefix) for prefix in blocklist)
+
+ def bundle(self, binary: Path, bin_dir: Path) -> None:
+ """Bundle a binary's shared library dependencies into bin_dir/lib/.
+
+ Dispatches to the appropriate platform-specific bundler.
+ """
+ system = platform.system().lower()
+ if system == "darwin":
+ self.bundle_macos_dylibs(binary, bin_dir)
+ elif system == "linux":
+ self.bundle_linux_libs(binary, bin_dir)
+ elif system == "windows":
+ self.bundle_windows_dlls(binary, bin_dir)
+
+ def verify(self, binary: Path, bin_dir: Path) -> None:
+ """Verify a bundled binary runs without missing library errors.
+
+ Clears library path env vars to force using only bundled libs,
+ then runs the binary with --version.
+ """
+ env = {k: v for k, v in os.environ.items() if not k.startswith(("DYLD_", "LD_LIBRARY"))}
+
+ lib_dir = bin_dir / "lib"
+ if lib_dir.exists():
+ if platform.system() == "Windows":
+ env["PATH"] = str(lib_dir) + os.pathsep + env.get("PATH", "")
+ else:
+ env["LD_LIBRARY_PATH"] = str(lib_dir)
+
+ try:
+ result = subprocess.run(
+ [str(binary), "--version"],
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=30,
+ stdin=subprocess.DEVNULL,
+ )
+ except subprocess.TimeoutExpired as e:
+ raise RuntimeError(
+ f"Bundled binary {binary.name} timed out during verification.\n"
+ "The binary may have missing dependencies or other issues."
+ ) from e
+ if result.returncode != 0:
+ raise RuntimeError(
+ f"Bundled binary {binary.name} failed verification:\n"
+ f" Exit code: {result.returncode}\n"
+ f" Stderr: {result.stderr}\n"
+ "A required library dependency was not bundled correctly."
+ )
+ self.app.display_info(f"Verified: {binary.name}")
+
+ def set_platform_wheel_tag(self, build_data: dict) -> None:
+ """Set build_data fields for a platform-specific py3-none wheel.
+
+ On Windows ARM64, overrides the tag from ``win_amd64`` to ``win_arm64``
+ when native hardware is ARM64 (Python may report amd64 under emulation).
+ """
+ build_data["pure_python"] = False
+ platform_tag = sysconfig.get_platform().replace("-", "_").replace(".", "_")
+
+ # Detect native arch on Windows ARM64
+ import platform as _platform
+
+ if _platform.system() == "Windows":
+ try:
+ import winreg # ty:ignore[unresolved-attribute]
+
+ key = winreg.OpenKey( # ty:ignore[unresolved-attribute]
+ winreg.HKEY_LOCAL_MACHINE, # ty:ignore[unresolved-attribute]
+ r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
+ )
+ native, _ = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE") # ty:ignore[unresolved-attribute]
+ winreg.CloseKey(key) # ty:ignore[unresolved-attribute]
+ if native.lower() in ("arm64", "aarch64") and "win_amd64" in platform_tag:
+ platform_tag = "win_arm64"
+ except Exception:
+ pass
+
+ build_data["tag"] = f"py3-none-{platform_tag}"
+
+ def force_include_bin_dir(self, bin_dir: Path, root: Path, build_data: dict) -> None:
+ """Add all files in bin_dir to the wheel's force_include."""
+ force_include = build_data.setdefault("force_include", {})
+ for f in bin_dir.rglob("*"):
+ if f.is_file():
+ rel_path = f.relative_to(root)
+ force_include[str(f)] = str(rel_path)
+
+ def make_executable(self, bin_dir: Path) -> None:
+ """chmod +x all files in bin_dir."""
+ for f in bin_dir.iterdir():
+ if f.is_file():
+ f.chmod(f.stat().st_mode | 0o755)
+
+ # -----------------------------------------------------------------
+ # macOS
+ # -----------------------------------------------------------------
+
+ def bundle_macos_dylibs(
+ self,
+ binary: Path,
+ bin_dir: Path,
+ *,
+ entitlements_plist: str | None = None,
+ ) -> None:
+ """Copy dylib dependencies and rewrite paths for macOS.
+
+ Args:
+ binary: The binary to bundle dependencies for.
+ bin_dir: Destination directory (libs go into bin_dir/lib/).
+ entitlements_plist: Optional entitlements plist XML string for codesigning
+ the main binary. If None, signs with ad-hoc only.
+ """
+ lib_dir = bin_dir / "lib"
+ lib_dir.mkdir(exist_ok=True)
+
+ self._process_binary_dylibs(binary, bin_dir, lib_dir, set())
+
+ # Re-sign all modified binaries (install_name_tool invalidates signatures)
+ self.app.display_info(f"Re-signing {binary.name}...")
+
+ # Sign dylibs with ad-hoc signature
+ for f in lib_dir.glob("*.dylib"):
+ subprocess.run(
+ ["codesign", "--force", "--sign", "-", str(f)],
+ capture_output=True,
+ )
+
+ # Sign the main binary
+ if entitlements_plist:
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".plist", delete=False) as f:
+ f.write(entitlements_plist)
+ entitlements_path = f.name
+ try:
+ subprocess.run(
+ [
+ "codesign",
+ "--force",
+ "--sign",
+ "-",
+ "--entitlements",
+ entitlements_path,
+ str(binary),
+ ],
+ capture_output=True,
+ )
+ finally:
+ Path(entitlements_path).unlink(missing_ok=True)
+ else:
+ subprocess.run(
+ ["codesign", "--force", "--sign", "-", str(binary)],
+ capture_output=True,
+ )
+
+ self.app.display_info(f"Re-signed {len(list(lib_dir.glob('*.dylib'))) + 1} files")
+
+ def _process_binary_dylibs(
+ self, binary: Path, bin_dir: Path, lib_dir: Path, processed: set[str]
+ ) -> None:
+ """Recursively process dylib dependencies for a binary."""
+ if str(binary) in processed:
+ return
+ processed.add(str(binary))
+
+ result = subprocess.run(
+ ["otool", "-L", str(binary)],
+ capture_output=True,
+ text=True,
+ )
+
+ dylibs_to_rewrite: list[tuple[str, str]] = []
+
+ for line in result.stdout.splitlines()[1:]:
+ line = line.strip()
+ if not line:
+ continue
+ dylib_path = line.split()[0]
+
+ if not self.should_bundle(dylib_path, "darwin"):
+ continue
+
+ dylib_name = Path(dylib_path).name
+ dest = lib_dir / dylib_name
+
+ if not dest.exists() and Path(dylib_path).exists():
+ shutil.copy(dylib_path, dest)
+ dest.chmod(dest.stat().st_mode | 0o755)
+ self._process_binary_dylibs(dest, bin_dir, lib_dir, processed)
+
+ dylibs_to_rewrite.append((dylib_path, dylib_name))
+
+ is_in_lib = binary.parent == lib_dir
+ loader_prefix = "@loader_path" if is_in_lib else "@loader_path/lib"
+
+ for dylib_path, dylib_name in dylibs_to_rewrite:
+ subprocess.run(
+ [
+ "install_name_tool",
+ "-change",
+ dylib_path,
+ f"{loader_prefix}/{dylib_name}",
+ str(binary),
+ ],
+ capture_output=True,
+ )
+
+ if binary.suffix == ".dylib" or ".dylib" in binary.name:
+ subprocess.run(
+ [
+ "install_name_tool",
+ "-id",
+ f"@loader_path/{binary.name}",
+ str(binary),
+ ],
+ capture_output=True,
+ )
+
+ # -----------------------------------------------------------------
+ # Linux
+ # -----------------------------------------------------------------
+
+ def bundle_linux_libs(self, binary: Path, bin_dir: Path) -> None:
+ """Copy shared library dependencies and set RPATH for Linux."""
+ if not shutil.which("patchelf"):
+ self.app.display_warning("patchelf not found, skipping library bundling")
+ return
+
+ lib_dir = bin_dir / "lib"
+ lib_dir.mkdir(exist_ok=True)
+
+ self._process_linux_libs(binary, lib_dir, set())
+
+ subprocess.run(
+ ["patchelf", "--set-rpath", "$ORIGIN/lib", str(binary)],
+ check=True,
+ )
+
+ def _process_linux_libs(self, binary: Path, lib_dir: Path, processed: set[str]) -> None:
+ """Recursively process shared library dependencies for a Linux binary."""
+ if str(binary) in processed:
+ return
+ processed.add(str(binary))
+
+ result = subprocess.run(
+ ["ldd", str(binary)],
+ capture_output=True,
+ text=True,
+ )
+
+ for line in result.stdout.splitlines():
+ if "=>" not in line or "not found" in line:
+ continue
+
+ parts = line.split("=>")
+ if len(parts) != 2:
+ continue
+
+ lib_path = parts[1].strip().split()[0]
+ if not lib_path.startswith("/"):
+ continue
+
+ if not self.should_bundle(lib_path, "linux"):
+ continue
+
+ lib_name = Path(lib_path).name
+ dest = lib_dir / lib_name
+ if not dest.exists() and Path(lib_path).exists():
+ shutil.copy(lib_path, dest)
+ dest.chmod(dest.stat().st_mode | 0o755)
+ self._process_linux_libs(dest, lib_dir, processed)
+ subprocess.run(
+ ["patchelf", "--set-rpath", "$ORIGIN", str(dest)],
+ capture_output=True,
+ )
+
+ # -----------------------------------------------------------------
+ # Windows
+ # -----------------------------------------------------------------
+
+ def bundle_windows_dlls(self, binary: Path, bin_dir: Path) -> None:
+ """Copy DLL dependencies for Windows.
+
+ Uses a simple approach: copy all DLLs from the binary's install directory.
+ """
+ install_dir = binary.parent
+ search_dirs = [install_dir, install_dir / "dll"]
+
+ count = 0
+ for search_dir in search_dirs:
+ if not search_dir.exists():
+ continue
+
+ for dll in search_dir.glob("*.dll"):
+ if not self.should_bundle(str(dll), "windows"):
+ continue
+
+ dest = bin_dir / dll.name
+ if not dest.exists():
+ shutil.copy(dll, dest)
+ count += 1
+
+ if count > 0:
+ self.app.display_info(f"Bundled {count} Windows DLLs from {install_dir}")
+
+
+__all__ = ["SYSTEM_LIBS", "BinaryBundler", "DisplayApp"]
diff --git a/packages/dev/quicksand-gh-runners/cloud-init.yaml b/packages/dev/quicksand-gh-runners/cloud-init.yaml
new file mode 100644
index 0000000..0f87031
--- /dev/null
+++ b/packages/dev/quicksand-gh-runners/cloud-init.yaml
@@ -0,0 +1,47 @@
+#cloud-config
+package_update: true
+packages:
+ - docker.io
+ - curl
+ - jq
+ - git
+ - build-essential
+
+runcmd:
+ # Docker Buildx
+ - mkdir -p /usr/local/lib/docker/cli-plugins
+ - |
+ BUILDX_VERSION=$(curl -s https://api.github.com/repos/docker/buildx/releases/latest | jq -r '.tag_name')
+ BUILDX_ARCH=$(dpkg --print-architecture)
+ curl -fLo /usr/local/lib/docker/cli-plugins/docker-buildx \
+ "https://github.com/docker/buildx/releases/download/${BUILDX_VERSION}/buildx-${BUILDX_VERSION}.linux-${BUILDX_ARCH}"
+ chmod +x /usr/local/lib/docker/cli-plugins/docker-buildx
+
+ # uv
+ - curl -LsSf https://astral.sh/uv/install.sh | UV_INSTALL_DIR=/usr/local/bin sh
+
+ # Keyring for Azure Artifacts auth (uses managed identity)
+ - uv tool install keyring --with keyrings.artifacts
+
+ # KVM (x64 only, harmless no-op on arm64)
+ - modprobe kvm 2>/dev/null || true
+ - modprobe kvm_intel 2>/dev/null || modprobe kvm_amd 2>/dev/null || true
+ - chmod 666 /dev/kvm 2>/dev/null || true
+
+ # Runner user (with passwordless sudo)
+ - useradd -m runner
+ - usermod -aG docker runner
+ - usermod -aG kvm runner 2>/dev/null || true
+ - echo "runner ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/runner
+
+ # Pre-download runner agent
+ - |
+ RUNNER_VERSION=$(curl -s https://api.github.com/repos/actions/runner/releases/latest | jq -r '.tag_name' | sed 's/^v//')
+ ARCH=$(uname -m)
+ if [ "$ARCH" = "aarch64" ]; then RUNNER_ARCH="arm64"; else RUNNER_ARCH="x64"; fi
+ mkdir -p /home/runner/actions-runner
+ cd /home/runner/actions-runner
+ curl -fLo runner.tar.gz "https://github.com/actions/runner/releases/download/v${RUNNER_VERSION}/actions-runner-linux-${RUNNER_ARCH}-${RUNNER_VERSION}.tar.gz"
+ tar xzf runner.tar.gz
+ rm runner.tar.gz
+ chown -R runner:runner /home/runner/actions-runner
diff --git a/packages/dev/quicksand-gh-runners/main.bicep b/packages/dev/quicksand-gh-runners/main.bicep
new file mode 100644
index 0000000..d2d5b60
--- /dev/null
+++ b/packages/dev/quicksand-gh-runners/main.bicep
@@ -0,0 +1,280 @@
+// Persistent self-hosted GitHub Actions runner VMs
+targetScope = 'resourceGroup'
+
+@description('Location for all resources')
+param location string = 'eastus'
+
+@description('SSH public key for Linux VMs')
+@secure()
+param sshPublicKey string
+
+@description('Admin password for Windows VM')
+@secure()
+param windowsAdminPassword string
+
+@description('Object ID of the Key Vault admin user')
+param kvAdminObjectId string
+
+// Variables
+var prefix = 'quicksand'
+var vnetName = 'vnet-${prefix}-runners'
+var nsgName = 'nsg-${prefix}-runners'
+var kvName = 'kv-${prefix}-runners'
+var shutdownTime = '0200' // 9pm EST = 02:00 UTC
+
+// Runners
+var linuxRunners = [
+ { name: 'quicksand-runner-x64', vmSize: 'Standard_D4s_v5', sku: 'server', arch: 'x64' }
+ { name: 'quicksand-runner-arm64', vmSize: 'Standard_D4ps_v5', sku: 'server-arm64', arch: 'arm64' }
+]
+
+var windowsRunner = {
+ name: 'quicksand-runner-win'
+ vmSize: 'Standard_D4s_v5'
+}
+
+// NSG — deny all inbound
+resource nsg 'Microsoft.Network/networkSecurityGroups@2023-11-01' = {
+ name: nsgName
+ location: location
+ properties: {
+ securityRules: [
+ {
+ name: 'DenyAllInbound'
+ properties: {
+ priority: 4096
+ direction: 'Inbound'
+ access: 'Deny'
+ protocol: '*'
+ sourceAddressPrefix: '*'
+ sourcePortRange: '*'
+ destinationAddressPrefix: '*'
+ destinationPortRange: '*'
+ }
+ }
+ ]
+ }
+}
+
+// VNet
+resource vnet 'Microsoft.Network/virtualNetworks@2023-11-01' = {
+ name: vnetName
+ location: location
+ properties: {
+ addressSpace: { addressPrefixes: ['10.0.0.0/16'] }
+ subnets: [
+ {
+ name: 'snet-runners'
+ properties: {
+ addressPrefix: '10.0.0.0/24'
+ networkSecurityGroup: { id: nsg.id }
+ }
+ }
+ ]
+ }
+}
+
+// ---------- Key Vault ----------
+
+resource kv 'Microsoft.KeyVault/vaults@2023-07-01' = {
+ name: kvName
+ location: location
+ properties: {
+ sku: { family: 'A', name: 'standard' }
+ tenantId: subscription().tenantId
+ enableRbacAuthorization: false
+ accessPolicies: [
+ {
+ tenantId: subscription().tenantId
+ objectId: kvAdminObjectId
+ permissions: {
+ secrets: ['all']
+ keys: ['all']
+ certificates: ['all']
+ }
+ }
+ ]
+ }
+}
+
+resource secretWinPassword 'Microsoft.KeyVault/vaults/secrets@2023-07-01' = {
+ parent: kv
+ name: 'windows-admin-password'
+ properties: { value: windowsAdminPassword }
+}
+
+resource secretSshKey 'Microsoft.KeyVault/vaults/secrets@2023-07-01' = {
+ parent: kv
+ name: 'ssh-public-key'
+ properties: { value: sshPublicKey }
+}
+
+// ---------- Linux runners ----------
+
+resource linuxPips 'Microsoft.Network/publicIPAddresses@2023-11-01' = [
+ for runner in linuxRunners: {
+ name: 'pip-${runner.name}'
+ location: location
+ sku: { name: 'Standard' }
+ properties: {
+ publicIPAllocationMethod: 'Static'
+ }
+ }
+]
+
+resource linuxNics 'Microsoft.Network/networkInterfaces@2023-11-01' = [
+ for (runner, i) in linuxRunners: {
+ name: 'nic-${runner.name}'
+ location: location
+ properties: {
+ ipConfigurations: [
+ {
+ name: 'ipconfig1'
+ properties: {
+ subnet: { id: vnet.properties.subnets[0].id }
+ privateIPAllocationMethod: 'Dynamic'
+ publicIPAddress: { id: linuxPips[i].id }
+ }
+ }
+ ]
+ }
+ }
+]
+
+resource linuxVms 'Microsoft.Compute/virtualMachines@2024-03-01' = [
+ for (runner, i) in linuxRunners: {
+ name: runner.name
+ location: location
+ identity: runner.arch == 'x64' ? { type: 'SystemAssigned' } : null
+ properties: {
+ hardwareProfile: { vmSize: runner.vmSize }
+ storageProfile: {
+ imageReference: {
+ publisher: 'Canonical'
+ offer: 'ubuntu-24_04-lts'
+ sku: runner.sku
+ version: 'latest'
+ }
+ osDisk: {
+ createOption: 'FromImage'
+ diskSizeGB: 256
+ managedDisk: { storageAccountType: 'Premium_LRS' }
+ deleteOption: 'Delete'
+ }
+ }
+ networkProfile: {
+ networkInterfaces: [
+ { id: linuxNics[i].id, properties: { deleteOption: 'Delete' } }
+ ]
+ }
+ osProfile: {
+ computerName: take(runner.name, 15)
+ adminUsername: 'runneradmin'
+ linuxConfiguration: {
+ disablePasswordAuthentication: true
+ ssh: {
+ publicKeys: [
+ {
+ path: '/home/runneradmin/.ssh/authorized_keys'
+ keyData: sshPublicKey
+ }
+ ]
+ }
+ }
+ customData: base64(loadTextContent('cloud-init.yaml'))
+ }
+ }
+ }
+]
+
+resource linuxShutdown 'Microsoft.DevTestLab/schedules@2018-09-15' = [
+ for (runner, i) in linuxRunners: {
+ name: 'shutdown-computevm-${runner.name}'
+ location: location
+ properties: {
+ status: 'Enabled'
+ taskType: 'ComputeVmShutdownTask'
+ dailyRecurrence: { time: shutdownTime }
+ timeZoneId: 'UTC'
+ targetResourceId: linuxVms[i].id
+ }
+ }
+]
+
+// ---------- Windows runner ----------
+
+resource winNic 'Microsoft.Network/networkInterfaces@2023-11-01' = {
+ name: 'nic-${windowsRunner.name}'
+ location: location
+ properties: {
+ ipConfigurations: [
+ {
+ name: 'ipconfig1'
+ properties: {
+ subnet: { id: vnet.properties.subnets[0].id }
+ privateIPAllocationMethod: 'Dynamic'
+ }
+ }
+ ]
+ }
+}
+
+resource winVm 'Microsoft.Compute/virtualMachines@2024-03-01' = {
+ name: windowsRunner.name
+ location: location
+ properties: {
+ hardwareProfile: { vmSize: windowsRunner.vmSize }
+ storageProfile: {
+ imageReference: {
+ publisher: 'MicrosoftWindowsServer'
+ offer: 'WindowsServer'
+ sku: '2022-datacenter-g2'
+ version: 'latest'
+ }
+ osDisk: {
+ createOption: 'FromImage'
+ diskSizeGB: 256
+ managedDisk: { storageAccountType: 'Premium_LRS' }
+ deleteOption: 'Delete'
+ }
+ }
+ networkProfile: {
+ networkInterfaces: [
+ { id: winNic.id, properties: { deleteOption: 'Delete' } }
+ ]
+ }
+ osProfile: {
+ computerName: 'runner-win'
+ adminUsername: 'runneradmin'
+ adminPassword: windowsAdminPassword
+ }
+ }
+}
+
+// Install pwsh, Git, and runner agent on Windows
+resource winSetup 'Microsoft.Compute/virtualMachines/extensions@2024-03-01' = {
+ parent: winVm
+ name: 'setup-runner'
+ location: location
+ properties: {
+ publisher: 'Microsoft.Compute'
+ type: 'CustomScriptExtension'
+ typeHandlerVersion: '1.10'
+ autoUpgradeMinorVersion: true
+ protectedSettings: {
+ commandToExecute: 'powershell -ExecutionPolicy Unrestricted -Command "Invoke-WebRequest -Uri https://github.com/PowerShell/PowerShell/releases/download/v7.4.7/PowerShell-7.4.7-win-x64.msi -OutFile $env:TEMP\\pwsh.msi; Start-Process msiexec.exe -ArgumentList \'/i\',$env:TEMP\'\\pwsh.msi\',\'/quiet\',\'ADD_PATH=1\' -Wait; Invoke-WebRequest -Uri https://github.com/git-for-windows/git/releases/download/v2.48.1.windows.1/Git-2.48.1-64-bit.exe -OutFile $env:TEMP\\git.exe; Start-Process $env:TEMP\\git.exe -ArgumentList \'/VERYSILENT\',\'/NORESTART\' -Wait"'
+ }
+ }
+}
+
+resource winShutdown 'Microsoft.DevTestLab/schedules@2018-09-15' = {
+ name: 'shutdown-computevm-${windowsRunner.name}'
+ location: location
+ properties: {
+ status: 'Enabled'
+ taskType: 'ComputeVmShutdownTask'
+ dailyRecurrence: { time: shutdownTime }
+ timeZoneId: 'UTC'
+ targetResourceId: winVm.id
+ }
+}
diff --git a/packages/dev/quicksand-gh-runners/pyproject.toml b/packages/dev/quicksand-gh-runners/pyproject.toml
new file mode 100644
index 0000000..04ce768
--- /dev/null
+++ b/packages/dev/quicksand-gh-runners/pyproject.toml
@@ -0,0 +1,21 @@
+[project]
+name = "quicksand-gh-runners"
+version = "0.1.0"
+description = "CLI to manage persistent self-hosted GitHub Actions runner VMs on Azure."
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "azure-identity",
+ "azure-mgmt-compute",
+ "requests",
+]
+
+[project.scripts]
+quicksand-runners = "quicksand_gh_runners.cli:main"
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_gh_runners"]
diff --git a/packages/dev/quicksand-gh-runners/quicksand_gh_runners/__init__.py b/packages/dev/quicksand-gh-runners/quicksand_gh_runners/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/packages/dev/quicksand-gh-runners/quicksand_gh_runners/__main__.py b/packages/dev/quicksand-gh-runners/quicksand_gh_runners/__main__.py
new file mode 100644
index 0000000..4e28416
--- /dev/null
+++ b/packages/dev/quicksand-gh-runners/quicksand_gh_runners/__main__.py
@@ -0,0 +1,3 @@
+from .cli import main
+
+main()
diff --git a/packages/dev/quicksand-gh-runners/quicksand_gh_runners/cli.py b/packages/dev/quicksand-gh-runners/quicksand_gh_runners/cli.py
new file mode 100644
index 0000000..34d2eca
--- /dev/null
+++ b/packages/dev/quicksand-gh-runners/quicksand_gh_runners/cli.py
@@ -0,0 +1,354 @@
+"""CLI to manage persistent self-hosted GitHub Actions runner VMs."""
+
+from __future__ import annotations
+
+import argparse
+import re
+import subprocess
+import sys
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from datetime import UTC, datetime, timedelta, timezone
+
+from azure.identity import DefaultAzureCredential
+from azure.mgmt.compute import ComputeManagementClient
+
+from . import config
+
+
+def _get_compute_client() -> ComputeManagementClient:
+ return ComputeManagementClient(DefaultAzureCredential(), config.SUBSCRIPTION_ID)
+
+
+def _resolve_runners(name: str | None) -> dict[str, str]:
+ if name is None:
+ return config.RUNNERS
+ if name not in config.RUNNERS:
+ print(f"Unknown runner: {name!r}. Choose from: {', '.join(config.RUNNERS)}")
+ sys.exit(1)
+ return {name: config.RUNNERS[name]}
+
+
+def _vm_power_state(client: ComputeManagementClient, vm_name: str) -> str:
+ view = client.virtual_machines.instance_view(config.RESOURCE_GROUP, vm_name)
+ for status in view.statuses or []:
+ code = status.code or ""
+ if code.startswith("PowerState/"):
+ return code.split("/", 1)[1]
+ return "unknown"
+
+
+def _get_shutdown_time(vm_name: str) -> str | None:
+ """Get the auto-shutdown time for a VM from DevTestLab schedules."""
+ result = subprocess.run(
+ [
+ "az",
+ "resource",
+ "show",
+ "--resource-group",
+ config.RESOURCE_GROUP,
+ "--resource-type",
+ "Microsoft.DevTestLab/schedules",
+ "--name",
+ f"shutdown-computevm-{vm_name}",
+ "--query",
+ "properties.dailyRecurrence.time",
+ "-o",
+ "tsv",
+ ],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode == 0 and result.stdout.strip():
+ utc_time = result.stdout.strip()
+ utc_hour = int(utc_time[:2])
+ est_hour = (utc_hour - 5) % 24
+ period = "am" if est_hour < 12 else "pm"
+ display_hour = est_hour % 12 or 12
+ return f"{display_hour}{period} EST"
+ return None
+
+
+def cmd_start(args: argparse.Namespace) -> None:
+ runners = _resolve_runners(args.runner)
+ client = _get_compute_client()
+
+ def start_one(alias: str, vm_name: str) -> str:
+ client.virtual_machines.begin_start(config.RESOURCE_GROUP, vm_name).result()
+ return f" {alias}: started"
+
+ print("Starting runners...")
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ futures = {pool.submit(start_one, a, v): a for a, v in runners.items()}
+ for f in as_completed(futures):
+ print(f.result())
+
+
+def cmd_stop(args: argparse.Namespace) -> None:
+ runners = _resolve_runners(args.runner)
+ client = _get_compute_client()
+
+ def stop_one(alias: str, vm_name: str) -> str:
+ client.virtual_machines.begin_deallocate(config.RESOURCE_GROUP, vm_name).result()
+ return f" {alias}: deallocated"
+
+ print("Stopping runners...")
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ futures = {pool.submit(stop_one, a, v): a for a, v in runners.items()}
+ for f in as_completed(futures):
+ print(f.result())
+
+
+def cmd_status(args: argparse.Namespace) -> None:
+ runners = _resolve_runners(args.runner)
+ client = _get_compute_client()
+
+ for alias, vm_name in runners.items():
+ try:
+ state = _vm_power_state(client, vm_name)
+ shutdown = _get_shutdown_time(vm_name)
+ shutdown_str = f" (shutdown: {shutdown})" if shutdown else ""
+ print(f" {alias:6s} {vm_name:30s} {state}{shutdown_str}")
+ except Exception as e:
+ print(f" {alias:6s} {vm_name:30s} error: {e}")
+
+
+def _parse_time(time_str: str) -> str:
+ """Parse a human time like '10pm', '11pm', '22:00' into HHMM UTC."""
+ est = timezone(timedelta(hours=-5))
+
+ match = re.match(r"^(\d{1,2})(am|pm)$", time_str.lower())
+ if match:
+ hour = int(match.group(1))
+ if match.group(2) == "pm" and hour != 12:
+ hour += 12
+ elif match.group(2) == "am" and hour == 12:
+ hour = 0
+ est_dt = datetime.now(est).replace(hour=hour, minute=0, second=0)
+ utc_dt = est_dt.astimezone(UTC)
+ return f"{utc_dt.hour:02d}{utc_dt.minute:02d}"
+
+ match = re.match(r"^(\d{2}):?(\d{2})$", time_str)
+ if match:
+ return f"{match.group(1)}{match.group(2)}"
+
+ print(f"Cannot parse time: {time_str!r}. Use e.g. '10pm', '11pm', '22:00'")
+ sys.exit(1)
+
+
+def cmd_extend(args: argparse.Namespace) -> None:
+ runners = _resolve_runners(args.runner)
+ utc_time = _parse_time(args.time) if args.time else "0300" # default: 10pm EST
+
+ for alias, vm_name in runners.items():
+ result = subprocess.run(
+ [
+ "az",
+ "vm",
+ "auto-shutdown",
+ "--resource-group",
+ config.RESOURCE_GROUP,
+ "--name",
+ vm_name,
+ "--time",
+ utc_time,
+ ],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode == 0:
+ print(f" {alias}: shutdown extended to {utc_time} UTC")
+ else:
+ print(f" {alias}: failed - {result.stderr.strip()}")
+
+
+def cmd_feed_access(_args: argparse.Namespace) -> None:
+ """Register the x64 runner's managed identity in Azure DevOps and grant feed access."""
+ import requests
+
+ # 1. Get the managed identity principal ID from the x64 runner VM
+ client = _get_compute_client()
+ vm = client.virtual_machines.get(config.RESOURCE_GROUP, config.RUNNERS["x64"])
+ if not vm.identity or not vm.identity.principal_id:
+ print("ERROR: quicksand-runner-x64 has no system-assigned managed identity")
+ sys.exit(1)
+ principal_id = vm.identity.principal_id
+ print(f"Managed identity principal ID: {principal_id}")
+
+ # 2. Get a bearer token for Azure DevOps
+ credential = DefaultAzureCredential()
+ token = credential.get_token(config.ADO_SCOPE).token
+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
+
+ # 3. Register as a service principal in the Azure DevOps org
+ print(f"Registering service principal in {config.ADO_ORG}...")
+ resp = requests.post(
+ f"https://vssps.dev.azure.com/{config.ADO_ORG}/_apis/graph/serviceprincipals?api-version=7.1-preview.1",
+ headers=headers,
+ json={"originId": principal_id},
+ )
+ if resp.status_code == 409:
+ print(" Already registered — fetching existing descriptor...")
+ # List service principals and find the one matching our principal ID
+ list_resp = requests.get(
+ f"https://vssps.dev.azure.com/{config.ADO_ORG}/_apis/graph/serviceprincipals?api-version=7.1-preview.1",
+ headers=headers,
+ )
+ list_resp.raise_for_status()
+ sps = list_resp.json().get("value", [])
+ descriptor = next(
+ (sp["descriptor"] for sp in sps if sp.get("originId") == principal_id), None
+ )
+ if not descriptor:
+ print("ERROR: could not find service principal descriptor")
+ sys.exit(1)
+ else:
+ resp.raise_for_status()
+ descriptor = resp.json()["descriptor"]
+ print(f" Subject descriptor: {descriptor}")
+
+ # 4. Resolve subject descriptor to an identity descriptor (needed by feed permissions API)
+ print(" Resolving identity descriptor...")
+ resp = requests.get(
+ f"https://vssps.dev.azure.com/{config.ADO_ORG}/_apis/identities?subjectDescriptors={descriptor}&api-version=7.1-preview.1",
+ headers=headers,
+ )
+ resp.raise_for_status()
+ identities = resp.json().get("value", [])
+ if not identities:
+ print("ERROR: could not resolve identity descriptor", file=sys.stderr)
+ sys.exit(1)
+ identity_descriptor = identities[0]["descriptor"]
+ print(f" Identity descriptor: {identity_descriptor}")
+
+ # 5. Grant contributor access to the artifacts feed
+ # Role IDs: 1=reader, 2=collaborator, 3=contributor, 4=administrator
+ print(f"Granting contributor access to feed '{config.ADO_FEED}'...")
+ resp = requests.patch(
+ f"https://feeds.dev.azure.com/{config.ADO_ORG}/_apis/packaging/feeds/{config.ADO_FEED}/permissions?api-version=7.1-preview.1",
+ headers=headers,
+ json=[{"identityDescriptor": identity_descriptor, "role": 3}],
+ )
+ if not resp.ok:
+ print(f" ERROR {resp.status_code}: {resp.text}", file=sys.stderr)
+ sys.exit(1)
+ print(" Done.")
+
+
+def cmd_setup(args: argparse.Namespace) -> None:
+ """One-time provisioning: create resource group and deploy Bicep."""
+ from pathlib import Path
+
+ bicep_path = Path(__file__).parent.parent / "main.bicep"
+ if not bicep_path.exists():
+ print(f"Bicep file not found: {bicep_path}")
+ sys.exit(1)
+
+ ssh_key = args.ssh_key
+ if not ssh_key:
+ for key_file in ["id_ed25519.pub", "id_rsa.pub"]:
+ p = Path.home() / ".ssh" / key_file
+ if p.exists():
+ ssh_key = p.read_text().strip()
+ break
+ if not ssh_key:
+ print("No SSH public key found. Pass --ssh-key or have ~/.ssh/id_ed25519.pub")
+ sys.exit(1)
+
+ print(f"Creating resource group {config.RESOURCE_GROUP}...")
+ subprocess.run(
+ [
+ "az",
+ "group",
+ "create",
+ "--name",
+ config.RESOURCE_GROUP,
+ "--location",
+ config.LOCATION,
+ "--output",
+ "none",
+ ],
+ check=True,
+ )
+
+ import secrets
+
+ win_password = f"P@{secrets.token_urlsafe(16)}"
+
+ result = subprocess.run(
+ ["az", "ad", "signed-in-user", "show", "--query", "id", "-o", "tsv"],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ user_object_id = result.stdout.strip()
+
+ print("Deploying Bicep template...")
+ subprocess.run(
+ [
+ "az",
+ "deployment",
+ "group",
+ "create",
+ "--resource-group",
+ config.RESOURCE_GROUP,
+ "--template-file",
+ str(bicep_path),
+ "--parameters",
+ f"sshPublicKey={ssh_key}",
+ f"windowsAdminPassword={win_password}",
+ f"kvAdminObjectId={user_object_id}",
+ "--output",
+ "none",
+ ],
+ check=True,
+ )
+
+ print("\nWindows admin password stored in Key Vault (kv-quicksand-runners).")
+ print()
+ print("VMs provisioned. Next: register the GitHub runner agent on each.")
+ print("Go to https://github.com/microsoft/quicksand/settings/actions/runners/new")
+ print("and follow the instructions for each platform.")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ prog="quicksand-runners",
+ description="Manage self-hosted GitHub Actions runner VMs",
+ )
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ for name, fn in [("start", cmd_start), ("stop", cmd_stop), ("status", cmd_status)]:
+ p = sub.add_parser(name)
+ p.add_argument(
+ "runner",
+ nargs="?",
+ choices=list(config.RUNNERS),
+ help="Runner to target (default: all)",
+ )
+ p.set_defaults(func=fn)
+
+ p_extend = sub.add_parser("extend", help="Extend auto-shutdown time")
+ p_extend.add_argument(
+ "time", nargs="?", help="New shutdown time, e.g. '10pm', '11pm' (default: 10pm EST)"
+ )
+ p_extend.add_argument(
+ "runner", nargs="?", choices=list(config.RUNNERS), help="Runner to target (default: all)"
+ )
+ p_extend.set_defaults(func=cmd_extend)
+
+ p_setup = sub.add_parser("setup", help="One-time VM provisioning")
+ p_setup.add_argument("--ssh-key", help="SSH public key string")
+ p_setup.set_defaults(func=cmd_setup)
+
+ p_feed = sub.add_parser(
+ "feed-access", help="Grant runner managed identity access to Azure Artifacts feed"
+ )
+ p_feed.set_defaults(func=cmd_feed_access)
+
+ args = parser.parse_args()
+ args.func(args)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/dev/quicksand-gh-runners/quicksand_gh_runners/config.py b/packages/dev/quicksand-gh-runners/quicksand_gh_runners/config.py
new file mode 100644
index 0000000..6a24c5b
--- /dev/null
+++ b/packages/dev/quicksand-gh-runners/quicksand_gh_runners/config.py
@@ -0,0 +1,19 @@
+"""Azure configuration for runner VMs."""
+
+SUBSCRIPTION_ID = "d4fe558f-6660-4fe7-99ec-ae4716b5e03f" # MSR LIT
+RESOURCE_GROUP = "rg-quicksand-runners"
+LOCATION = "eastus"
+
+RUNNERS = {
+ "x64": "quicksand-runner-x64",
+ "arm64": "quicksand-runner-arm64",
+ "win": "quicksand-runner-win",
+}
+
+DEFAULT_SHUTDOWN_TIME = "0200" # 9pm EST = 02:00 UTC
+SHUTDOWN_TIMEZONE = "UTC"
+
+# Azure DevOps
+ADO_ORG = "msraif"
+ADO_FEED = "packages"
+ADO_SCOPE = "499b84ac-1321-427f-aa17-267ca6975798/.default"
diff --git a/packages/dev/quicksand-image-tools/.gitignore b/packages/dev/quicksand-image-tools/.gitignore
new file mode 100644
index 0000000..dc31a91
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/.gitignore
@@ -0,0 +1 @@
+quicksand_image_tools/quicksand-guest-agent/target/
diff --git a/packages/dev/quicksand-image-tools/README.md b/packages/dev/quicksand-image-tools/README.md
new file mode 100644
index 0000000..b644ff2
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/README.md
@@ -0,0 +1,125 @@
+# Quicksand Image Tools
+
+This package provides development tools for building custom VM images for the [quicksand](https://github.com/microsoft/quicksand) agent harness.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install dev
+```
+
+This installs quicksand with the Ubuntu image and dev tools for building custom images.
+
+## CLI Usage
+
+The recommended way to build custom images:
+
+```bash
+# Initialize a build directory (creates Dockerfile, builds base image if needed)
+quicksand-image-tools init ./my-image ubuntu # or: alpine
+
+# Customize the generated Dockerfile, then build the VM image
+quicksand-image-tools build-image ./my-image/Dockerfile -o my-image.qcow2
+```
+
+### Example Dockerfile
+
+After running `quicksand-image-tools init ./my-image ubuntu`, a Dockerfile is created with the versioned base image. Add your customizations:
+
+```dockerfile
+FROM quicksand/ubuntu-base:24.04.0
+
+# Add your customizations here
+RUN apt-get update && apt-get install -y nodejs && rm -rf /var/lib/apt/lists/*
+```
+
+The base images include the kernel, agent, and init configuration. You just add your packages.
+
+## Python API
+
+Build a VM image programmatically:
+
+```python
+import asyncio
+from quicksand_image_tools import build_image
+from quicksand import Sandbox, SandboxConfig
+
+async def main():
+ # Build from a Dockerfile path
+ image_path = build_image("./Dockerfile")
+
+ # Use the custom image
+ async with Sandbox(SandboxConfig(image_path=str(image_path))) as sb:
+ result = await sb.execute("node --version")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## Dockerfile Requirements
+
+When building FROM a base image (`quicksand/ubuntu-base` or `quicksand/alpine-base`), you just add your packages - the base handles everything else.
+
+For scratch Dockerfiles, you must:
+
+1. **Install a kernel**: Ubuntu `linux-image-virtual` or Alpine `linux-virt`
+2. **Build the Rust agent** via multi-stage Docker build
+3. **Configure a systemd service or OpenRC script** to run the agent on boot
+
+See the `examples/custom_image.py` for a complete working example.
+
+## CLI Reference
+
+### `quicksand-image-tools init [directory] [ubuntu|alpine]`
+
+Initialize a directory for building custom images.
+
+- If no Dockerfile exists in the directory, you must specify a base image type (`ubuntu` or `alpine`)
+- Automatically builds the base Docker image if it doesn't exist
+- Creates a Dockerfile with the appropriate `FROM` statement
+
+### `quicksand-image-tools build-base [ubuntu|alpine|all]`
+
+Build base Docker images locally. Creates versioned images (e.g., `quicksand/ubuntu-base:24.04.0`) and tags them as `latest`. The version matches the installed `quicksand-ubuntu` or `quicksand-alpine` package version.
+
+### `quicksand-image-tools build-image <dockerfile> [-o output] [--cache-dir dir]`
+
+Build a VM image from a Dockerfile.
+
+## Python API Reference
+
+### `build_image(dockerfile, output_path=None, cache_dir=None)`
+
+Build a VM image from a Dockerfile.
+
+- `dockerfile`: Path to a Dockerfile
+- `output_path`: Where to save the qcow2 image (default: cached by hash)
+- `cache_dir`: Cache directory (default: `~/.cache/quicksand/images/`)
+
+Returns the `Path` to the built qcow2 image.
+
+### `get_agent_source_dir()`
+
+Returns the `Path` to the Rust agent source directory (`quicksand-guest-agent/`). This is used by image packages to set up symlinks for Docker builds.
+
+## How It Works
+
+1. Builds a Docker image from your Dockerfile
+2. Creates a container and exports its filesystem
+3. Extracts kernel and initrd from `/boot`
+4. Converts the filesystem to a bootable qcow2 VM image
+
+## Requirements
+
+- Docker must be installed and running
+- QEMU tools (bundled with quicksand-core, or install separately)
+
+## License
+
+MIT
diff --git a/packages/dev/quicksand-image-tools/pyproject.toml b/packages/dev/quicksand-image-tools/pyproject.toml
new file mode 100644
index 0000000..1c4ac6b
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/pyproject.toml
@@ -0,0 +1,30 @@
+[project]
+name = "quicksand-image-tools"
+version = "0.4.4.dev0"
+description = "Development tools for quicksand - build custom VM images from Dockerfiles"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.3.dev0",
+]
+
+[project.scripts]
+quicksand-image-tools = "quicksand_image_tools.cli:main"
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_image_tools"]
+artifacts = [
+ "quicksand_image_tools/templates/*",
+ "quicksand_image_tools/quicksand-guest-agent/**/*",
+]
+exclude = [
+ "quicksand_image_tools/quicksand-guest-agent/target",
+]
+
+[tool.uv.sources]
+quicksand-core = { workspace = true }
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/__init__.py b/packages/dev/quicksand-image-tools/quicksand_image_tools/__init__.py
new file mode 100644
index 0000000..55d274c
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/__init__.py
@@ -0,0 +1,20 @@
+"""
+Quicksand Image Tools: Build custom VM images from Dockerfiles.
+
+This package provides tools for building custom quicksand VM images.
+
+Quick start:
+ from quicksand_image_tools import build_image
+
+ # Build from a Dockerfile
+ image_path = build_image("./Dockerfile")
+
+The Rust agent source is included in this package at quicksand-guest-agent/.
+Image packages use symlinks to reference it for multi-stage Docker builds.
+"""
+
+from .build import build_image, get_agent_source_dir
+
+__all__ = ["build_image", "get_agent_source_dir"]
+
+__version__ = "0.1.0"
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/agent-openapi.yaml b/packages/dev/quicksand-image-tools/quicksand_image_tools/agent-openapi.yaml
new file mode 100644
index 0000000..eb6ae2b
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/agent-openapi.yaml
@@ -0,0 +1,218 @@
+openapi: 3.1.0
+info:
+ title: Quicksand Guest Agent
+ description: |
+ HTTP API running inside the guest VM to handle commands from the host.
+
+ ## Authentication
+ - Token and port are passed via kernel command line (`quicksand_token`, `quicksand_port`)
+ - All endpoints except `/authenticate` require `Authorization: Bearer <token>` header
+ version: 1.0.0
+
+servers:
+ - url: http://localhost:{port}
+ description: Guest VM agent
+ variables:
+ port:
+ default: "8080"
+ description: Port from kernel cmdline `quicksand_port`
+
+security:
+ - tokenAuth: []
+
+components:
+ securitySchemes:
+ tokenAuth:
+ type: http
+ scheme: bearer
+ description: Bearer token from kernel cmdline `quicksand_token`
+
+ schemas:
+ AuthRequest:
+ type: object
+ required:
+ - token
+ properties:
+ token:
+ type: string
+ description: Token to verify
+
+ AuthResponse:
+ type: object
+ required:
+ - authenticated
+ properties:
+ authenticated:
+ type: boolean
+
+ ExecuteRequest:
+ type: object
+ required:
+ - command
+ properties:
+ command:
+ type: string
+ description: Shell command to execute
+ timeout:
+ type: number
+ format: float
+ default: 30.0
+ description: Command timeout in seconds
+ cwd:
+ type: string
+ nullable: true
+ description: Working directory for command execution
+
+ ExecuteResponse:
+ type: object
+ required:
+ - stdout
+ - stderr
+ - exit_code
+ properties:
+ stdout:
+ type: string
+ description: Standard output from command
+ stderr:
+ type: string
+ description: Standard error from command
+ exit_code:
+ type: integer
+ description: Exit code (-1 for timeout/error)
+
+ ExecuteStreamEvent:
+ type: object
+ required:
+ - stream
+ properties:
+ stream:
+ type: string
+ enum: [stdout, stderr, exit]
+ data:
+ type: string
+ description: Output text (for stdout/stderr events)
+ exit_code:
+ type: integer
+ description: Process exit code (for exit events only)
+
+ PingResponse:
+ type: object
+ required:
+ - pong
+ - pid
+ properties:
+ pong:
+ type: boolean
+ const: true
+ pid:
+ type: integer
+ description: Agent process ID
+
+ ErrorResponse:
+ type: object
+ required:
+ - detail
+ properties:
+ detail:
+ type: string
+ description: Error message
+
+paths:
+ /authenticate:
+ post:
+ summary: Verify authentication token
+ description: |
+ Verify that a token is valid. This endpoint does NOT require
+ the Authorization header - the token is passed in the request body.
+ security: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AuthRequest'
+ responses:
+ '200':
+ description: Token is valid
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AuthResponse'
+ '401':
+ description: Invalid token
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+
+ /execute:
+ post:
+ summary: Execute a shell command
+ description: |
+ Run a shell command in the guest VM and return stdout, stderr, and exit code.
+ Commands are executed via `/bin/sh -c`.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ExecuteRequest'
+ responses:
+ '200':
+ description: Command executed (check exit_code for success)
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ExecuteResponse'
+ '401':
+ description: Invalid or missing token
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+
+ /execute_stream:
+ post:
+ summary: Execute a shell command with streaming output
+ description: |
+ Run a shell command and stream stdout/stderr as SSE events in real-time.
+ Same request body as /execute. The response is a text/event-stream where
+ each event has a JSON payload with "stream" (stdout/stderr/exit) and
+ "data" or "exit_code" fields.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ExecuteRequest'
+ responses:
+ '200':
+ description: SSE stream of command output
+ content:
+ text/event-stream:
+ schema:
+ $ref: '#/components/schemas/ExecuteStreamEvent'
+ '401':
+ description: Invalid or missing token
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
+
+ /ping:
+ get:
+ summary: Health check
+ description: Simple health check that returns the agent's process ID.
+ responses:
+ '200':
+ description: Agent is healthy
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PingResponse'
+ '401':
+ description: Invalid or missing token
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorResponse'
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/build.py b/packages/dev/quicksand-image-tools/quicksand_image_tools/build.py
new file mode 100644
index 0000000..c2d27a8
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/build.py
@@ -0,0 +1,423 @@
+"""Build custom VM images from Dockerfiles."""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+from quicksand_core._types import FilePatterns
+
+logger = logging.getLogger(__name__)
+
+# Path to the Rust agent source directory in this package
+AGENT_SOURCE_DIR = Path(__file__).parent / "quicksand-guest-agent"
+
+# Default cache directory
+DEFAULT_CACHE_DIR = Path.home() / ".cache/quicksand/images"
+
+
+def get_agent_source_dir() -> Path:
+ """Get the path to the Rust agent source directory.
+
+ This is used by image packages to set up symlinks for multi-stage
+ Docker builds that compile the Rust agent.
+ """
+ if not AGENT_SOURCE_DIR.exists():
+ raise RuntimeError(f"Agent source directory not found at {AGENT_SOURCE_DIR}")
+ return AGENT_SOURCE_DIR
+
+
+def build_image(
+ dockerfile: str | Path,
+ output_path: Path | None = None,
+ cache_dir: Path | None = None,
+ force: bool = False,
+ log: logging.Logger | None = None,
+) -> Path:
+ """
+ Build a VM image from a Dockerfile.
+
+ The Dockerfile should use a multi-stage build to:
+ - Compile the Rust agent from source (stage 1)
+ - Install a kernel (linux-image-virtual for Ubuntu, linux-virt for Alpine)
+ - Copy the compiled agent binary and configure a service to run it
+
+ The agent source is copied to the build context if an agent symlink exists.
+
+ Args:
+ dockerfile: Path to a Dockerfile.
+ output_path: Where to save the resulting qcow2 image.
+ If None, saves to cache directory with a hash-based name.
+ cache_dir: Directory for cached images. Defaults to ~/.cache/quicksand/images/
+
+ Returns:
+ Path to the built qcow2 image.
+
+ Raises:
+ RuntimeError: If Docker is not available or build fails.
+ """
+ log = log or logger
+
+ if not shutil.which("docker"):
+ raise RuntimeError(
+ "Docker is required to build custom images. "
+ "Install Docker from https://docs.docker.com/get-docker/"
+ )
+
+ cache = cache_dir or DEFAULT_CACHE_DIR
+ cache.mkdir(parents=True, exist_ok=True)
+
+ # Handle Dockerfile input
+ dockerfile_path = Path(dockerfile)
+ if not dockerfile_path.exists():
+ raise RuntimeError(f"Dockerfile not found: {dockerfile_path}")
+
+ dockerfile_content = dockerfile_path.read_text()
+ context_dir = dockerfile_path.parent
+
+ # Compute hash for caching
+ content_hash = hashlib.sha256(dockerfile_content.encode()).hexdigest()[:16]
+
+ if output_path is None:
+ output_path = cache / f"custom-{content_hash}.qcow2"
+
+ # Check cache
+ if output_path.exists():
+ if force:
+ output_path.unlink()
+ else:
+ log.info("Using cached image: %s", output_path)
+ return output_path
+
+ # Copy agent source to build context (Dockerfiles expect it at agent/)
+ agent_dest = context_dir / "agent"
+ if agent_dest.exists():
+ shutil.rmtree(agent_dest)
+ shutil.copytree(
+ AGENT_SOURCE_DIR,
+ agent_dest,
+ ignore=shutil.ignore_patterns("target", ".git"),
+ )
+
+ try:
+ log.info("[1/5] Building Docker image...")
+
+ with tempfile.TemporaryDirectory(prefix="quicksand-build-") as tmpdir:
+ tmpdir_path = Path(tmpdir)
+
+ # Build Docker image
+ tag = f"quicksand-build:{content_hash}"
+ _run_docker_build(dockerfile_path, context_dir, tag, log=log)
+
+ try:
+ log.info("[2/5] Exporting filesystem...")
+ _create_and_export_container(tag, tmpdir_path)
+
+ log.info("[3/5] Converting to VM image...")
+ tar_path = tmpdir_path / "rootfs.tar"
+ _tar_to_qcow2(tar_path, output_path, log=log)
+
+ finally:
+ log.info("[4/5] Cleaning up...")
+ _remove_docker_image(tag)
+
+ log.info("[5/5] Done!")
+ final_size_mb = output_path.stat().st_size / (1024 * 1024)
+ log.info("Output: %s (%.1f MB)", output_path, final_size_mb)
+
+ return output_path
+
+ finally:
+ # Clean up copied agent source
+ shutil.rmtree(agent_dest, ignore_errors=True)
+
+
+def _run_docker_build(
+ dockerfile: Path,
+ context: Path,
+ tag: str,
+ log: logging.Logger = logger,
+) -> None:
+ """Build a Docker image, streaming output to the caller's logger."""
+ cmd = [
+ "docker",
+ "build",
+ "-f",
+ str(dockerfile),
+ "-t",
+ tag,
+ str(context),
+ ]
+
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
+ assert process.stdout is not None
+ for line in process.stdout:
+ log.info("%s", line.rstrip())
+ returncode = process.wait()
+ if returncode != 0:
+ raise RuntimeError(f"Docker build failed (exit code {returncode})")
+
+
+def _create_and_export_container(image_tag: str, tmpdir: Path) -> str:
+ """Create a container and export its filesystem."""
+ # Create container
+ result = subprocess.run(
+ ["docker", "create", image_tag],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to create container: {result.stderr}")
+
+ container_id = result.stdout.strip()
+
+ try:
+ # Export filesystem
+ tar_path = tmpdir / "rootfs.tar"
+ with open(tar_path, "wb") as f:
+ result = subprocess.run(
+ ["docker", "export", container_id],
+ stdout=f,
+ stderr=subprocess.PIPE,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to export container: {result.stderr.decode()}")
+ finally:
+ # Remove container
+ subprocess.run(["docker", "rm", "-f", container_id], capture_output=True)
+
+ return container_id
+
+
+def _remove_docker_image(tag: str) -> None:
+ """Remove a Docker image."""
+ subprocess.run(["docker", "rmi", "-f", tag], capture_output=True)
+
+
+def _tar_to_qcow2(tar_path: Path, qcow2_path: Path, log: logging.Logger = logger) -> None:
+ """
+ Convert a rootfs tar to a qcow2 image with kernel/initrd extracted.
+
+ Uses Docker to create the ext4 image, ensuring proper root ownership.
+ """
+ # Find qemu-img: prefer bundled from quicksand-core, fall back to system
+ qemu_img: str | None = None
+ try:
+ from quicksand_core.qemu.platform import _find_bundled_runtime
+
+ bundled = _find_bundled_runtime()
+ if bundled and bundled.qemu_img.exists():
+ qemu_img = str(bundled.qemu_img)
+ except ImportError:
+ pass
+
+ if not qemu_img:
+ qemu_img = shutil.which("qemu-img") or shutil.which("qemu-img.exe")
+
+ if not qemu_img:
+ raise RuntimeError(
+ "qemu-img not found. Install QEMU or quicksand-core:\n"
+ " pip install quicksand-core\n"
+ " Or install QEMU directly:\n"
+ " macOS: brew install qemu\n"
+ " Linux: sudo apt install qemu-utils\n"
+ " Windows: https://www.qemu.org/download/#windows"
+ )
+
+ with tempfile.TemporaryDirectory(prefix="quicksand-convert-") as tmpdir:
+ tmpdir_path = Path(tmpdir)
+
+ # Extract tar on host to get kernel/initrd
+ rootfs_dir = tmpdir_path / "rootfs"
+ rootfs_dir.mkdir()
+
+ log.debug("Extracting tar for kernel/initrd discovery...")
+ result = subprocess.run(
+ ["tar", "-xf", str(tar_path), "-C", str(rootfs_dir)],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to extract tar: {result.stderr}")
+
+ # Find kernel and initrd
+ kernel_src = _find_kernel(rootfs_dir)
+ initrd_src = _find_initrd(rootfs_dir)
+
+ if not kernel_src:
+ raise RuntimeError(
+ "No kernel found in image. Your Dockerfile must install a kernel package.\n"
+ "For Ubuntu: RUN apt-get install -y linux-image-virtual\n"
+ "For Alpine: RUN apk add linux-virt"
+ )
+
+ log.info("Kernel: %s", kernel_src.name)
+ if initrd_src:
+ log.info("Initrd: %s", initrd_src.name)
+
+ # Copy kernel and initrd to output location
+ kernel_dst = qcow2_path.with_suffix(FilePatterns.KERNEL_SUFFIX)
+ shutil.copy(kernel_src, kernel_dst)
+
+ if initrd_src:
+ initrd_dst = qcow2_path.with_suffix(FilePatterns.INITRD_SUFFIX)
+ shutil.copy(initrd_src, initrd_dst)
+
+ # Calculate filesystem size
+ rootfs_size = _get_dir_size(rootfs_dir)
+ fs_size_bytes = max(int(rootfs_size * 1.5), 1024 * 1024 * 1024)
+ fs_size_bytes = ((fs_size_bytes + 256 * 1024 * 1024 - 1) // (256 * 1024 * 1024)) * (
+ 256 * 1024 * 1024
+ )
+ fs_size_mb = fs_size_bytes // (1024 * 1024)
+
+ # Create ext4 image inside Docker to preserve root ownership
+ raw_path = tmpdir_path / "rootfs.ext4"
+ _create_ext4_in_docker(tar_path, raw_path, fs_size_mb, log=log)
+
+ # Convert to qcow2
+ log.debug("Converting to qcow2 (compressed)...")
+ result = subprocess.run(
+ [
+ qemu_img,
+ "convert",
+ "-f",
+ "raw",
+ "-O",
+ "qcow2",
+ "-c",
+ str(raw_path),
+ str(qcow2_path),
+ ],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to convert to qcow2: {result.stderr}")
+
+
+def _create_ext4_in_docker(
+ tar_path: Path, output_path: Path, size_mb: int, log: logging.Logger = logger
+) -> None:
+ """Create an ext4 filesystem image from a tar file using Docker.
+
+ Uses docker cp instead of volume mounts for Docker-in-Docker compatibility.
+ Volume mounts fail in Docker-in-Docker because paths inside the outer container
+ don't exist on the Docker host where the daemon runs.
+ """
+ builder_image = "ubuntu:24.04"
+ import time as _time
+
+ container_name = f"quicksand-builder-{int(_time.time())}"
+
+ # Use /tmp which always exists in the container
+ build_script = f"""#!/bin/bash
+set -e
+apt-get update -qq
+apt-get install -y -qq e2fsprogs zerofree >/dev/null
+mkdir -p /rootfs
+tar -xf /tmp/rootfs.tar -C /rootfs
+mke2fs -q -t ext4 -d /rootfs -L rootfs -O ^metadata_csum,^64bit /tmp/rootfs.ext4 {size_mb}M
+zerofree /tmp/rootfs.ext4
+"""
+
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # Remove any leftover container from a previous failed build
+ subprocess.run(["docker", "rm", "-f", container_name], capture_output=True)
+
+ # Create container (but don't start it yet)
+ result = subprocess.run(
+ ["docker", "create", "--name", container_name, builder_image, "bash", "-c", build_script],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to create Docker container:\n{result.stderr or result.stdout}")
+
+ try:
+ # Copy tar file into container (use /tmp which always exists)
+ result = subprocess.run(
+ ["docker", "cp", str(tar_path), f"{container_name}:/tmp/rootfs.tar"],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to copy tar into container:\n{result.stderr}")
+
+ # Start container and wait for completion, streaming output
+ process = subprocess.Popen(
+ ["docker", "start", "-a", container_name],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ assert process.stdout is not None
+ for line in process.stdout:
+ log.info("%s", line.rstrip())
+ returncode = process.wait()
+ if returncode != 0:
+ raise RuntimeError(f"Failed to create ext4 image in Docker (exit code {returncode})")
+
+ # Copy ext4 file out of container
+ result = subprocess.run(
+ ["docker", "cp", f"{container_name}:/tmp/rootfs.ext4", str(output_path)],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to copy ext4 from container:\n{result.stderr}")
+
+ finally:
+ # Always clean up the container
+ subprocess.run(["docker", "rm", "-f", container_name], capture_output=True)
+
+ if not output_path.exists():
+ raise RuntimeError(f"Docker build completed but output file not found: {output_path}")
+
+
+def _find_kernel(rootfs: Path) -> Path | None:
+ """Find the kernel in a rootfs directory."""
+ boot_dir = rootfs / "boot"
+ if not boot_dir.exists():
+ return None
+
+ kernels = list(boot_dir.glob("vmlinuz-*"))
+ if not kernels:
+ kernels = list(boot_dir.glob("vmlinuz"))
+
+ if kernels:
+ return sorted(kernels, reverse=True)[0]
+ return None
+
+
+def _find_initrd(rootfs: Path) -> Path | None:
+ """Find the initrd/initramfs in a rootfs directory."""
+ boot_dir = rootfs / "boot"
+ if not boot_dir.exists():
+ return None
+
+ for pattern in ["initrd.img-*", "initrd-*", "initramfs-*"]:
+ initrds = list(boot_dir.glob(pattern))
+ if initrds:
+ return sorted(initrds, reverse=True)[0]
+
+ for name in ["initrd.img", "initrd", "initramfs"]:
+ path = boot_dir / name
+ if path.exists():
+ return path
+
+ return None
+
+
+def _get_dir_size(path: Path) -> int:
+ """Get the total size of a directory in bytes."""
+ total = 0
+ for entry in path.rglob("*"):
+ if entry.is_file() and not entry.is_symlink():
+ total += entry.stat().st_size
+ return total
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
new file mode 100644
index 0000000..f83be3b
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/build_utils.py
@@ -0,0 +1,55 @@
+"""Build-time utilities for quicksand image package hooks.
+
+Centralizes architecture detection and platform wheel tagging that was
+previously duplicated across every ``hatch_build.py`` in the monorepo.
+"""
+
+from __future__ import annotations
+
+import sysconfig
+
+_X86_NAMES = {"x86_64", "amd64", "x64"}
+_ARM_NAMES = {"arm64", "aarch64"}
+
+
+def get_image_arch() -> str:
+ """Return the image architecture string for the host (``"amd64"`` or ``"arm64"``).
+
+ On Windows, detects the native hardware architecture to see through
+ x86_64-on-ARM64 transparent emulation.
+ """
+ from quicksand_core.host.arch import _detect_architecture
+
+ return _detect_architecture().image_arch
+
+
+def set_platform_wheel_tag(
+ build_data: dict,
+ *,
+ target_name: str = "wheel",
+ version: str = "",
+) -> bool:
+ """Mark the wheel as platform-specific and set the ``py3-none-<platform>`` tag.
+
+ On Windows ARM64, ``sysconfig.get_platform()`` returns ``win-amd64`` when
+ Python runs under x86_64 emulation. We override the tag to ``win_arm64``
+ based on native hardware detection so the wheel is correctly tagged.
+
+ Returns ``True`` if the build should proceed (real wheel build) or ``False``
+ if it should be skipped (editable install or non-wheel target).
+
+ Raises:
+ RuntimeError: If the host architecture is unsupported (only for real builds).
+ """
+ if target_name != "wheel" or version == "editable":
+ return False
+ native_arch = get_image_arch() # validates arch, raises on unsupported
+ build_data["pure_python"] = False
+ platform_tag = sysconfig.get_platform().replace("-", "_").replace(".", "_")
+
+ # Override tag on Windows ARM64 with emulated x64 Python
+ if native_arch == "arm64" and "win_amd64" in platform_tag:
+ platform_tag = "win_arm64"
+
+ build_data["tag"] = f"py3-none-{platform_tag}"
+ return True
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/cli.py b/packages/dev/quicksand-image-tools/quicksand_image_tools/cli.py
new file mode 100644
index 0000000..3abfa7c
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/cli.py
@@ -0,0 +1,378 @@
+"""Command-line interface for quicksand-image-tools."""
+
+from __future__ import annotations
+
+import argparse
+import logging
+import sys
+from importlib.metadata import entry_points
+from pathlib import Path
+
+from quicksand_core import BaseImageInfo
+
+from .build import build_image
+
+
+def discover_bases() -> dict[str, BaseImageInfo]:
+ """Discover all installed base image packages via entry points.
+
+ Base image packages (quicksand-ubuntu, quicksand-alpine, etc.) register
+ entry points in the 'quicksand.images' group with ``type = "base"``.
+ This function loads them all and returns a dict mapping base name to
+ BaseImageInfo.
+ """
+ import importlib
+
+ bases: dict[str, BaseImageInfo] = {}
+ eps = entry_points(group="quicksand.images")
+ for ep in eps:
+ try:
+ provider = ep.load()
+ if getattr(provider, "type", None) != "base":
+ continue
+ mod_name = ep.value.split(":")[0]
+ mod = importlib.import_module(mod_name)
+ docker_dir = getattr(mod, "_DOCKER_DIR", None) or getattr(mod, "DOCKER_DIR", None)
+ version = getattr(mod, "DISTRO_VERSION", getattr(mod, "__version__", "unknown"))
+ if docker_dir is None:
+ continue
+ bases[provider.name] = BaseImageInfo(
+ name=provider.name, docker_dir=docker_dir, version=version
+ )
+ except Exception as e:
+ logging.debug(f"Failed to load base entry point {ep.name}: {e}")
+ return bases
+
+
+def _setup_logging(verbose: bool = False) -> None:
+ """Configure logging for the CLI."""
+ level = logging.DEBUG if verbose else logging.INFO
+ logging.basicConfig(
+ level=level,
+ format="%(message)s",
+ stream=sys.stderr,
+ )
+
+
+def main() -> int:
+ """Main entry point for the CLI."""
+ parser = argparse.ArgumentParser(
+ prog="quicksand-image-tools",
+ description="Build custom VM images for quicksand",
+ )
+ parser.add_argument(
+ "-v",
+ "--verbose",
+ action="store_true",
+ help="Enable verbose output",
+ )
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ # init command
+ init_parser = subparsers.add_parser(
+ "init",
+ help="Initialize a directory for building custom images",
+ )
+ init_parser.add_argument(
+ "directory",
+ type=Path,
+ nargs="?",
+ default=Path("."),
+ help="Directory to initialize (default: current directory)",
+ )
+ init_parser.add_argument(
+ "base",
+ choices=["ubuntu", "alpine"],
+ nargs="?",
+ default=None,
+ help="Base image type (required if directory has no Dockerfile)",
+ )
+
+ # build-base command
+ base_parser = subparsers.add_parser(
+ "build-base",
+ help="Build base Docker images locally (so you can FROM them)",
+ )
+ base_parser.add_argument(
+ "base",
+ choices=["ubuntu", "alpine", "all"],
+ nargs="?",
+ default="all",
+ help="Which base image to build (default: all)",
+ )
+
+ # build-image command
+ build_parser = subparsers.add_parser(
+ "build-image",
+ help="Build a VM image from a Dockerfile",
+ )
+ build_parser.add_argument(
+ "dockerfile",
+ type=Path,
+ help="Path to Dockerfile",
+ )
+ build_parser.add_argument(
+ "-o",
+ "--output",
+ type=Path,
+ help="Output path for the qcow2 image (default: auto-generated in cache)",
+ )
+ build_parser.add_argument(
+ "--cache-dir",
+ type=Path,
+ help="Directory for cached images",
+ )
+
+ # package subcommand
+ package_parser = subparsers.add_parser(
+ "package",
+ help="Manage quicksand image packages",
+ )
+ package_subparsers = package_parser.add_subparsers(dest="package_command", required=True)
+
+ pkg_init_parser = package_subparsers.add_parser(
+ "init",
+ help="Bootstrap a new quicksand image package by copying an existing base",
+ )
+ pkg_init_parser.add_argument(
+ "name",
+ help="Package name, e.g. 'mylinux' → package quicksand-mylinux",
+ )
+ pkg_init_parser.add_argument(
+ "base",
+ help="Base image package to copy and extend (e.g. ubuntu, alpine)",
+ )
+ pkg_init_parser.add_argument(
+ "--output-dir",
+ type=Path,
+ default=None,
+ help="Root directory for the new package (default: packages/quicksand-<name>)",
+ )
+
+ args = parser.parse_args()
+ _setup_logging(args.verbose)
+
+ if args.command == "init":
+ return cmd_init(args)
+ if args.command == "build-base":
+ return cmd_build_base(args)
+ if args.command == "build-image":
+ return cmd_build_image(args)
+ if args.command == "package" and args.package_command == "init":
+ return cmd_package_init(args)
+
+ return 1
+
+
+def cmd_init(args: argparse.Namespace) -> int:
+ """Handle the init command."""
+ import subprocess
+
+ dest_dir = args.directory
+ if not dest_dir.exists():
+ dest_dir.mkdir(parents=True)
+
+ dockerfile_path = dest_dir / "Dockerfile"
+
+ # If no Dockerfile exists, we need the base argument
+ if not dockerfile_path.exists():
+ if args.base is None:
+ print(
+ "Error: No Dockerfile found in directory.\n"
+ "Specify a base image type: quicksand-image-tools init <directory> ubuntu|alpine",
+ file=sys.stderr,
+ )
+ return 1
+
+ # Get version for the base image via entry point discovery
+ bases = discover_bases()
+ info = bases.get(args.base)
+ if info:
+ version = info.version
+ else:
+ print(f"Warning: {args.base} version not found, using 'latest'", file=sys.stderr)
+ version = "latest"
+
+ # Check if base image exists (try versioned tag first, then latest)
+ base_name = f"quicksand/{args.base}-base"
+ versioned_tag = f"{base_name}:{version}"
+
+ result = subprocess.run(
+ ["docker", "image", "inspect", versioned_tag],
+ capture_output=True,
+ )
+
+ if result.returncode != 0:
+ # Base image doesn't exist, build it
+ print(f"Base image {versioned_tag} not found, building...")
+ build_args = argparse.Namespace(base=args.base)
+ ret = cmd_build_base(build_args)
+ if ret != 0:
+ return ret
+
+ # Write the Dockerfile with versioned tag
+ dockerfile_content = f"""FROM {versioned_tag}
+
+# Add your customizations here
+"""
+ dockerfile_path.write_text(dockerfile_content)
+ print(f"Created {dockerfile_path}")
+
+ return 0
+
+
+def cmd_build_base(args: argparse.Namespace) -> int:
+ """Handle the build-base command.
+
+ Builds base Docker images that can be used as FROM targets.
+ The Rust agent is compiled during the Docker build via multi-stage build.
+ """
+ import shutil
+ import subprocess
+
+ from .build import get_agent_source_dir
+
+ # Discover installed base image packages via entry points
+ base_info = discover_bases()
+
+ if args.base == "all":
+ bases_to_build = list(base_info.keys())
+ if not bases_to_build:
+ print(
+ "No base image packages found. Install quicksand[ubuntu] or quicksand[alpine].",
+ file=sys.stderr,
+ )
+ return 1
+ else:
+ bases_to_build = [args.base]
+
+ built = []
+
+ for base in bases_to_build:
+ info = base_info.get(base)
+ if info is None:
+ print(f"Warning: {base} base not found (install quicksand[{base}])", file=sys.stderr)
+ continue
+
+ docker_dir = info.docker_dir
+ version = info.version
+
+ # Build Docker image with version tag
+ # The Dockerfile uses multi-stage build to compile the Rust agent
+ base_name = f"quicksand/{base}-base"
+ versioned_tag = f"{base_name}:{version}"
+ latest_tag = f"{base_name}:latest"
+
+ # Copy agent source to docker directory for the build
+ agent_dest = docker_dir / "agent"
+ if agent_dest.exists():
+ shutil.rmtree(agent_dest)
+
+ agent_source = get_agent_source_dir()
+ shutil.copytree(
+ agent_source,
+ agent_dest,
+ ignore=shutil.ignore_patterns("target", ".git"),
+ )
+
+ try:
+ print(f"Building {versioned_tag}...")
+ result = subprocess.run(
+ ["docker", "build", "-t", versioned_tag, "-t", latest_tag, "."],
+ cwd=docker_dir,
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ print(f"Error building {versioned_tag}:\n{result.stderr}", file=sys.stderr)
+ return 1
+
+ built.append(versioned_tag)
+ print(f"Built: {versioned_tag} (also tagged as {latest_tag})")
+ finally:
+ # Clean up copied agent source
+ shutil.rmtree(agent_dest, ignore_errors=True)
+
+ if built:
+ print("\nYou can now use these in your Dockerfile:")
+ for tag in built:
+ print(f" FROM {tag}")
+ return 0
+
+
+def cmd_build_image(args: argparse.Namespace) -> int:
+ """Handle the build-image command.
+
+ The Dockerfile should use a multi-stage build to compile the Rust agent.
+ See the quicksand-ubuntu or quicksand-alpine packages for examples.
+ """
+ if not args.dockerfile.exists():
+ print(f"Error: Dockerfile not found: {args.dockerfile}", file=sys.stderr)
+ return 1
+
+ try:
+ output_path = build_image(
+ args.dockerfile,
+ output_path=args.output,
+ cache_dir=args.cache_dir,
+ )
+ print(f"Built image: {output_path}")
+ return 0
+ except Exception as e:
+ print(f"Error: {e}", file=sys.stderr)
+ return 1
+
+
+def cmd_package_init(args: argparse.Namespace) -> int:
+ """Bootstrap a new quicksand image package by copying an existing base package."""
+ from . import scaffold
+
+ name = args.name.lower()
+ name_under = name.replace("-", "_")
+ base = args.base
+ old_pkg = f"quicksand-{base}"
+
+ repo_root = scaffold.find_repo_root()
+ if repo_root is None:
+ print("Error: not in a git repository", file=sys.stderr)
+ return 1
+
+ output_dir = args.output_dir or Path(name)
+
+ if output_dir.exists() and any(output_dir.iterdir()):
+ print(f"Error: {output_dir} already exists and is non-empty", file=sys.stderr)
+ return 1
+
+ base_pkg_dir = repo_root / "packages" / old_pkg
+ if not base_pkg_dir.exists():
+ print(f"Error: base package not found: {base_pkg_dir}", file=sys.stderr)
+ return 1
+
+ print(f"Copying {old_pkg} → {name}...")
+ scaffold.copy_base_package(base_pkg_dir, output_dir)
+ scaffold.rename_module(output_dir, old_pkg, name)
+ scaffold.replace_in_tree(output_dir, old_pkg, name, base)
+ scaffold.reset_versions(output_dir, name)
+ scaffold.reset_readme(output_dir, name)
+ scaffold.reset_docker_dir(output_dir, name, base)
+
+ registered = scaffold.register_package(name, repo_root)
+
+ module_dir = output_dir / name_under
+ docker_dir = module_dir / "docker"
+
+ print(f"\nPackage scaffolded: {output_dir}")
+ if registered:
+ print(f" Registered quicksand[{name}] in packages/quicksand/pyproject.toml")
+ print("\nNext steps:")
+ print(f" 1. Set DISTRO_VERSION in {module_dir}/__init__.py")
+ print(f" 2. Edit {docker_dir}/Dockerfile to customize the image")
+ print(" 3. Sync the workspace:")
+ print(" uv sync")
+ print(" 4. Build and test:")
+ print(f" uv build --package {name}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.lock b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.lock
new file mode 100644
index 0000000..644b747
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.lock
@@ -0,0 +1,571 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "async-trait"
+version = "0.1.89"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "axum"
+version = "0.7.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"
+dependencies = [
+ "async-trait",
+ "axum-core",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "rustversion",
+ "serde",
+ "serde_json",
+ "serde_path_to_error",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199"
+dependencies = [
+ "async-trait",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "rustversion",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "bytes"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
+
+[[package]]
+name = "futures-util"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "http"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hyper"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "pin-utils",
+ "smallvec",
+ "tokio",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
+dependencies = [
+ "bytes",
+ "http",
+ "http-body",
+ "hyper",
+ "pin-project-lite",
+ "tokio",
+ "tower-service",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
+
+[[package]]
+name = "libc"
+version = "0.2.182"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
+
+[[package]]
+name = "matchit"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
+
+[[package]]
+name = "memchr"
+version = "2.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "mio"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "quicksand-guest-agent"
+version = "0.1.0"
+dependencies = [
+ "axum",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tokio-stream",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "socket2"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0"
+dependencies = [
+ "libc",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+
+[[package]]
+name = "tokio"
+version = "1.49.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tokio-stream"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.toml b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.toml
new file mode 100644
index 0000000..06f165e
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "quicksand-guest-agent"
+version = "0.1.0"
+edition = "2021"
+description = "Minimal guest agent for quicksand VMs (quicksand-guest-agent)"
+license = "MIT"
+
+[dependencies]
+# Async runtime - multi-threaded for concurrent request handling
+tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "process", "time", "fs", "macros"] }
+
+# HTTP server - lightweight
+axum = { version = "0.7", default-features = false, features = ["json", "tokio", "http1"] }
+
+# JSON serialization
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+
+# SSE streaming support
+tokio-stream = "0.1"
+
+[profile.release]
+opt-level = "z" # Optimize for size
+lto = true # Link-time optimization
+codegen-units = 1 # Single codegen unit for better optimization
+panic = "abort" # Abort on panic (smaller binary)
+strip = true # Strip symbols
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/main.rs b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/main.rs
new file mode 100644
index 0000000..1f817b2
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/quicksand-guest-agent/src/main.rs
@@ -0,0 +1,705 @@
+//! Quicksand Guest Agent (quicksand-guest-agent)
+//!
+//! Minimal HTTP API running inside the guest VM to handle commands from the host.
+//! Reads configuration (token, port) from kernel command line.
+
+use axum::{
+ extract::State,
+ http::{header, StatusCode},
+ response::{
+ sse::{Event, Sse},
+ IntoResponse,
+ },
+ routing::{get, post},
+ Json, Router,
+};
+use serde::{Deserialize, Serialize};
+use std::{
+ convert::Infallible,
+ fs,
+ io::Write,
+ net::SocketAddr,
+ process::{Command, Stdio},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+ time::Duration,
+};
+use tokio::io::{AsyncBufReadExt, BufReader};
+use tokio::time::timeout;
+use tokio_stream::wrappers::ReceiverStream;
+
+// ============================================================================
+// Logging
+// ============================================================================
+
+fn log(msg: &str) {
+ let formatted = format!("[quicksand-guest-agent] {}", msg);
+ eprintln!("{}", formatted);
+ // Also write to kernel console for visibility in boot output
+ if let Ok(mut console) = fs::OpenOptions::new().write(true).open("/dev/console") {
+ let _ = writeln!(console, "{}", formatted);
+ }
+}
+
+// ============================================================================
+// Configuration
+// ============================================================================
+
+fn get_cmdline_param(name: &str) -> Option<String> {
+ let cmdline = fs::read_to_string("/proc/cmdline").ok()?;
+ let prefix = format!("{}=", name);
+ for part in cmdline.split_whitespace() {
+ if let Some(value) = part.strip_prefix(&prefix) {
+ return Some(value.to_string());
+ }
+ }
+ None
+}
+
+fn get_param(name: &str) -> Option<String> {
+ get_cmdline_param(name)
+}
+
+#[derive(Clone)]
+struct AppState {
+ token: Arc<String>,
+ /// True while an exclusive command (sync, fstrim, etc.) is running.
+ /// Other execute requests are rejected with 503 while this is set.
+ exclusive_busy: Arc<AtomicBool>,
+}
+
+// ============================================================================
+// Request/Response Types
+// ============================================================================
+
+#[derive(Deserialize)]
+struct AuthRequest {
+ token: String,
+}
+
+#[derive(Serialize)]
+struct AuthResponse {
+ authenticated: bool,
+}
+
+#[derive(Deserialize)]
+struct ExecuteRequest {
+ command: String,
+ #[serde(default = "default_timeout")]
+ timeout: f64,
+ cwd: Option<String>,
+ /// When true, reject all other execute requests while this one is running.
+ #[serde(default)]
+ exclusive: bool,
+}
+
+fn default_timeout() -> f64 {
+ 30.0
+}
+
+#[derive(Serialize)]
+struct ExecuteResponse {
+ stdout: String,
+ stderr: String,
+ exit_code: i32,
+}
+
+#[derive(Serialize)]
+struct PingResponse {
+ pong: bool,
+ pid: u32,
+}
+
+#[derive(Serialize)]
+struct ErrorResponse {
+ detail: String,
+}
+
+// ============================================================================
+// Authentication
+// ============================================================================
+
+fn extract_bearer_token(headers: &axum::http::HeaderMap) -> Option<&str> {
+ headers
+ .get(header::AUTHORIZATION)?
+ .to_str()
+ .ok()?
+ .strip_prefix("Bearer ")
+}
+
+fn verify_token(headers: &axum::http::HeaderMap, expected: &str) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
+ match extract_bearer_token(headers) {
+ Some(token) if token == expected => Ok(()),
+ _ => Err((
+ StatusCode::UNAUTHORIZED,
+ Json(ErrorResponse {
+ detail: "Invalid token".to_string(),
+ }),
+ )),
+ }
+}
+
+// ============================================================================
+// Handlers
+// ============================================================================
+
+async fn authenticate(
+ State(state): State<AppState>,
+ Json(req): Json<AuthRequest>,
+) -> impl IntoResponse {
+ if req.token == *state.token {
+ (StatusCode::OK, Json(AuthResponse { authenticated: true }))
+ } else {
+ (StatusCode::UNAUTHORIZED, Json(AuthResponse { authenticated: false }))
+ }
+}
+
+async fn execute(
+ State(state): State<AppState>,
+ headers: axum::http::HeaderMap,
+ Json(req): Json<ExecuteRequest>,
+) -> impl IntoResponse {
+ if let Err(e) = verify_token(&headers, &state.token) {
+ return e.into_response();
+ }
+
+ // Reject if an exclusive command is already running.
+ if state.exclusive_busy.load(Ordering::SeqCst) {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(ErrorResponse {
+ detail: "Exclusive command in progress".to_string(),
+ }),
+ )
+ .into_response();
+ }
+
+ // If this request is exclusive, atomically claim the lock.
+ if req.exclusive {
+ if state
+ .exclusive_busy
+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(ErrorResponse {
+ detail: "Exclusive command in progress".to_string(),
+ }),
+ )
+ .into_response();
+ }
+ }
+
+ let timeout_duration = Duration::from_secs_f64(req.timeout);
+
+ let result = timeout(timeout_duration, async {
+ let mut cmd = Command::new("/bin/sh");
+ cmd.arg("-c").arg(&req.command);
+ cmd.stdout(Stdio::piped());
+ cmd.stderr(Stdio::piped());
+
+ if let Some(cwd) = &req.cwd {
+ cmd.current_dir(cwd);
+ }
+
+ cmd.output()
+ })
+ .await;
+
+ // Release the exclusive lock if we held it.
+ if req.exclusive {
+ state.exclusive_busy.store(false, Ordering::SeqCst);
+ }
+
+ let response = match result {
+ Ok(Ok(output)) => ExecuteResponse {
+ stdout: String::from_utf8_lossy(&output.stdout).to_string(),
+ stderr: String::from_utf8_lossy(&output.stderr).to_string(),
+ exit_code: output.status.code().unwrap_or(-1),
+ },
+ Ok(Err(e)) => ExecuteResponse {
+ stdout: String::new(),
+ stderr: e.to_string(),
+ exit_code: -1,
+ },
+ Err(_) => ExecuteResponse {
+ stdout: String::new(),
+ stderr: format!("Command timed out after {} seconds", req.timeout),
+ exit_code: -1,
+ },
+ };
+
+ (StatusCode::OK, Json(response)).into_response()
+}
+
+async fn execute_stream(
+ State(state): State<AppState>,
+ headers: axum::http::HeaderMap,
+ Json(req): Json<ExecuteRequest>,
+) -> impl IntoResponse {
+ if let Err(e) = verify_token(&headers, &state.token) {
+ return e.into_response();
+ }
+
+ // Reject if an exclusive command is already running.
+ if state.exclusive_busy.load(Ordering::SeqCst) {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(ErrorResponse {
+ detail: "Exclusive command in progress".to_string(),
+ }),
+ )
+ .into_response();
+ }
+
+ // If this request is exclusive, atomically claim the lock.
+ if req.exclusive {
+ if state
+ .exclusive_busy
+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return (
+ StatusCode::SERVICE_UNAVAILABLE,
+ Json(ErrorResponse {
+ detail: "Exclusive command in progress".to_string(),
+ }),
+ )
+ .into_response();
+ }
+ }
+
+ let timeout_duration = Duration::from_secs_f64(req.timeout);
+ let (tx, rx) = tokio::sync::mpsc::channel::<Result<Event, Infallible>>(64);
+ let exclusive_busy = state.exclusive_busy.clone();
+ let is_exclusive = req.exclusive;
+
+ tokio::spawn(async move {
+ let result = timeout(timeout_duration, async {
+ let mut cmd = tokio::process::Command::new("/bin/sh");
+ cmd.arg("-c").arg(&req.command);
+ cmd.stdout(Stdio::piped());
+ cmd.stderr(Stdio::piped());
+
+ if let Some(cwd) = &req.cwd {
+ cmd.current_dir(cwd);
+ }
+
+ let mut child = match cmd.spawn() {
+ Ok(c) => c,
+ Err(e) => {
+ let data = serde_json::json!({"stream": "stderr", "data": e.to_string()});
+ let _ = tx.send(Ok(Event::default().data(data.to_string()))).await;
+ let data = serde_json::json!({"stream": "exit", "exit_code": -1});
+ let _ = tx.send(Ok(Event::default().data(data.to_string()))).await;
+ return;
+ }
+ };
+
+ let stdout = child.stdout.take().unwrap();
+ let stderr = child.stderr.take().unwrap();
+ let mut stdout_reader = BufReader::new(stdout).lines();
+ let mut stderr_reader = BufReader::new(stderr).lines();
+
+ let mut stdout_done = false;
+ let mut stderr_done = false;
+
+ while !stdout_done || !stderr_done {
+ tokio::select! {
+ line = stdout_reader.next_line(), if !stdout_done => {
+ match line {
+ Ok(Some(text)) => {
+ let data = serde_json::json!({"stream": "stdout", "data": format!("{}\n", text)});
+ if tx.send(Ok(Event::default().data(data.to_string()))).await.is_err() {
+ return;
+ }
+ }
+ _ => stdout_done = true,
+ }
+ }
+ line = stderr_reader.next_line(), if !stderr_done => {
+ match line {
+ Ok(Some(text)) => {
+ let data = serde_json::json!({"stream": "stderr", "data": format!("{}\n", text)});
+ if tx.send(Ok(Event::default().data(data.to_string()))).await.is_err() {
+ return;
+ }
+ }
+ _ => stderr_done = true,
+ }
+ }
+ }
+ }
+
+ let exit_code = match child.wait().await {
+ Ok(status) => status.code().unwrap_or(-1),
+ Err(_) => -1,
+ };
+
+ let data = serde_json::json!({"stream": "exit", "exit_code": exit_code});
+ let _ = tx.send(Ok(Event::default().data(data.to_string()))).await;
+ })
+ .await;
+
+ if result.is_err() {
+ let data = serde_json::json!({"stream": "stderr", "data": format!("Command timed out after {} seconds\n", req.timeout)});
+ let _ = tx.send(Ok(Event::default().data(data.to_string()))).await;
+ let data = serde_json::json!({"stream": "exit", "exit_code": -1});
+ let _ = tx.send(Ok(Event::default().data(data.to_string()))).await;
+ }
+
+ // Release exclusive lock if we held it.
+ if is_exclusive {
+ exclusive_busy.store(false, Ordering::SeqCst);
+ }
+ });
+
+ let stream = ReceiverStream::new(rx);
+ Sse::new(stream).into_response()
+}
+
+async fn ping(
+ State(state): State<AppState>,
+ headers: axum::http::HeaderMap,
+) -> impl IntoResponse {
+ if let Err(e) = verify_token(&headers, &state.token) {
+ return e.into_response();
+ }
+
+ (
+ StatusCode::OK,
+ Json(PingResponse {
+ pong: true,
+ pid: std::process::id(),
+ }),
+ )
+ .into_response()
+}
+
+// ============================================================================
+// Shared command execution (used by both HTTP and virtio-serial transports)
+// ============================================================================
+
+struct ExecResult {
+ stdout: String,
+ stderr: String,
+ exit_code: i32,
+}
+
+async fn run_command(command: &str, timeout_secs: f64, cwd: Option<&str>) -> ExecResult {
+ let timeout_duration = Duration::from_secs_f64(timeout_secs);
+
+ let result = timeout(timeout_duration, async {
+ let mut cmd = Command::new("/bin/sh");
+ cmd.arg("-c").arg(command);
+ cmd.stdout(Stdio::piped());
+ cmd.stderr(Stdio::piped());
+ if let Some(dir) = cwd {
+ cmd.current_dir(dir);
+ }
+ cmd.output()
+ })
+ .await;
+
+ match result {
+ Ok(Ok(output)) => ExecResult {
+ stdout: String::from_utf8_lossy(&output.stdout).to_string(),
+ stderr: String::from_utf8_lossy(&output.stderr).to_string(),
+ exit_code: output.status.code().unwrap_or(-1),
+ },
+ Ok(Err(e)) => ExecResult {
+ stdout: String::new(),
+ stderr: e.to_string(),
+ exit_code: -1,
+ },
+ Err(_) => ExecResult {
+ stdout: String::new(),
+ stderr: format!("Command timed out after {} seconds", timeout_secs),
+ exit_code: -1,
+ },
+ }
+}
+
+// ============================================================================
+// Virtio-serial transport (length-prefixed JSON frames)
+// ============================================================================
+
+const VIRTIO_SERIAL_PATH: &str = "/dev/virtio-ports/quicksand.agent.0";
+
+/// Frame format: 4-byte big-endian length + JSON payload
+async fn read_frame(reader: &mut (impl tokio::io::AsyncReadExt + Unpin)) -> std::io::Result<serde_json::Value> {
+ let mut len_buf = [0u8; 4];
+ reader.read_exact(&mut len_buf).await?;
+ let len = u32::from_be_bytes(len_buf) as usize;
+ if len > 64 * 1024 * 1024 {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Frame too large"));
+ }
+ let mut buf = vec![0u8; len];
+ reader.read_exact(&mut buf).await?;
+ serde_json::from_slice(&buf).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
+}
+
+async fn write_frame(writer: &mut (impl tokio::io::AsyncWriteExt + Unpin), msg: &serde_json::Value) -> std::io::Result<()> {
+ let payload = serde_json::to_vec(msg).unwrap();
+ let len = (payload.len() as u32).to_be_bytes();
+ writer.write_all(&len).await?;
+ writer.write_all(&payload).await?;
+ writer.flush().await?;
+ Ok(())
+}
+
+async fn handle_virtio_serial(token: String, exclusive_busy: Arc<AtomicBool>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt, BufStream};
+
+ let file = match tokio::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(VIRTIO_SERIAL_PATH)
+ .await
+ {
+ Ok(f) => f,
+ Err(e) => {
+ log(&format!("Failed to open {}: {}", VIRTIO_SERIAL_PATH, e));
+ return;
+ }
+ };
+
+ log(&format!("Virtio-serial channel open: {}", VIRTIO_SERIAL_PATH));
+
+ let stream = BufStream::new(file);
+ let (mut reader, mut writer) = tokio::io::split(stream);
+ let mut authenticated = false;
+
+ loop {
+ let frame = match read_frame(&mut reader).await {
+ Ok(f) => f,
+ Err(e) => {
+ log(&format!("Virtio-serial read error: {}", e));
+ break;
+ }
+ };
+
+ let id = frame.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
+ let method = frame.get("method").and_then(|v| v.as_str()).unwrap_or("");
+ let params = frame.get("params").cloned().unwrap_or(serde_json::json!({}));
+
+ match method {
+ "authenticate" => {
+ let req_token = params.get("token").and_then(|v| v.as_str()).unwrap_or("");
+ authenticated = req_token == token;
+ let resp = serde_json::json!({"id": id, "result": {"authenticated": authenticated}});
+ if let Err(e) = write_frame(&mut writer, &resp).await {
+ log(&format!("Write error: {}", e));
+ break;
+ }
+ }
+ "ping" if authenticated => {
+ let resp = serde_json::json!({"id": id, "result": {"pong": true, "pid": std::process::id()}});
+ if let Err(e) = write_frame(&mut writer, &resp).await {
+ log(&format!("Write error: {}", e));
+ break;
+ }
+ }
+ "execute" if authenticated => {
+ let command = params.get("command").and_then(|v| v.as_str()).unwrap_or("");
+ let timeout_secs = params.get("timeout").and_then(|v| v.as_f64()).unwrap_or(30.0);
+ let cwd = params.get("cwd").and_then(|v| v.as_str());
+ let is_exclusive = params.get("exclusive").and_then(|v| v.as_bool()).unwrap_or(false);
+
+ if exclusive_busy.load(Ordering::SeqCst) {
+ let resp = serde_json::json!({"id": id, "error": {"message": "Exclusive command in progress"}});
+ let _ = write_frame(&mut writer, &resp).await;
+ continue;
+ }
+ if is_exclusive {
+ if exclusive_busy.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() {
+ let resp = serde_json::json!({"id": id, "error": {"message": "Exclusive command in progress"}});
+ let _ = write_frame(&mut writer, &resp).await;
+ continue;
+ }
+ }
+
+ let result = run_command(command, timeout_secs, cwd).await;
+
+ if is_exclusive {
+ exclusive_busy.store(false, Ordering::SeqCst);
+ }
+
+ let resp = serde_json::json!({
+ "id": id,
+ "result": {
+ "stdout": result.stdout,
+ "stderr": result.stderr,
+ "exit_code": result.exit_code
+ }
+ });
+ if let Err(e) = write_frame(&mut writer, &resp).await {
+ log(&format!("Write error: {}", e));
+ break;
+ }
+ }
+ "execute_stream" if authenticated => {
+ let command = params.get("command").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let timeout_secs = params.get("timeout").and_then(|v| v.as_f64()).unwrap_or(30.0);
+ let cwd = params.get("cwd").and_then(|v| v.as_str()).map(|s| s.to_string());
+ let is_exclusive = params.get("exclusive").and_then(|v| v.as_bool()).unwrap_or(false);
+
+ if exclusive_busy.load(Ordering::SeqCst) {
+ let resp = serde_json::json!({"id": id, "error": {"message": "Exclusive command in progress"}});
+ let _ = write_frame(&mut writer, &resp).await;
+ continue;
+ }
+ if is_exclusive {
+ if exclusive_busy.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() {
+ let resp = serde_json::json!({"id": id, "error": {"message": "Exclusive command in progress"}});
+ let _ = write_frame(&mut writer, &resp).await;
+ continue;
+ }
+ }
+
+ let timeout_duration = Duration::from_secs_f64(timeout_secs);
+
+ let result = timeout(timeout_duration, async {
+ let mut cmd = tokio::process::Command::new("/bin/sh");
+ cmd.arg("-c").arg(&command);
+ cmd.stdout(Stdio::piped());
+ cmd.stderr(Stdio::piped());
+ if let Some(dir) = &cwd {
+ cmd.current_dir(dir);
+ }
+
+ let mut child = match cmd.spawn() {
+ Ok(c) => c,
+ Err(e) => {
+ let _ = write_frame(&mut writer, &serde_json::json!({"id": id, "stream": "stderr", "data": e.to_string()})).await;
+ let _ = write_frame(&mut writer, &serde_json::json!({"id": id, "stream": "exit", "exit_code": -1})).await;
+ return;
+ }
+ };
+
+ let stdout = child.stdout.take().unwrap();
+ let stderr = child.stderr.take().unwrap();
+ let mut stdout_reader = BufReader::new(stdout).lines();
+ let mut stderr_reader = BufReader::new(stderr).lines();
+
+ let mut stdout_done = false;
+ let mut stderr_done = false;
+
+ while !stdout_done || !stderr_done {
+ tokio::select! {
+ line = stdout_reader.next_line(), if !stdout_done => {
+ match line {
+ Ok(Some(text)) => {
+ let _ = write_frame(&mut writer, &serde_json::json!({"id": id, "stream": "stdout", "data": format!("{}\n", text)})).await;
+ }
+ _ => stdout_done = true,
+ }
+ }
+ line = stderr_reader.next_line(), if !stderr_done => {
+ match line {
+ Ok(Some(text)) => {
+ let _ = write_frame(&mut writer, &serde_json::json!({"id": id, "stream": "stderr", "data": format!("{}\n", text)})).await;
+ }
+ _ => stderr_done = true,
+ }
+ }
+ }
+ }
+
+ let exit_code = match child.wait().await {
+ Ok(status) => status.code().unwrap_or(-1),
+ Err(_) => -1,
+ };
+
+ let _ = write_frame(&mut writer, &serde_json::json!({"id": id, "stream": "exit", "exit_code": exit_code})).await;
+ })
+ .await;
+
+ if result.is_err() {
+ let _ = write_frame(&mut writer, &serde_json::json!({"id": id, "stream": "stderr", "data": format!("Command timed out after {} seconds\n", timeout_secs)})).await;
+ let _ = write_frame(&mut writer, &serde_json::json!({"id": id, "stream": "exit", "exit_code": -1})).await;
+ }
+
+ if is_exclusive {
+ exclusive_busy.store(false, Ordering::SeqCst);
+ }
+ }
+ _ if !authenticated => {
+ let resp = serde_json::json!({"id": id, "error": {"message": "Not authenticated"}});
+ let _ = write_frame(&mut writer, &resp).await;
+ }
+ _ => {
+ let resp = serde_json::json!({"id": id, "error": {"message": format!("Unknown method: {}", method)}});
+ let _ = write_frame(&mut writer, &resp).await;
+ }
+ }
+ }
+}
+
+// ============================================================================
+// Main
+// ============================================================================
+
+#[tokio::main]
+async fn main() {
+ log("Rust agent starting...");
+
+ // Read config from kernel command line (injected by host via -append).
+ let token = match get_param("quicksand_token") {
+ Some(t) => t,
+ None => {
+ log("ERROR: No quicksand_token in /proc/cmdline");
+ if let Ok(cmdline) = fs::read_to_string("/proc/cmdline") {
+ log(&format!("cmdline: {}", cmdline.trim()));
+ }
+ std::process::exit(1);
+ }
+ };
+
+ let exclusive_busy = Arc::new(AtomicBool::new(false));
+
+ // Try virtio-serial first (no network dependency, faster boot).
+ if std::path::Path::new(VIRTIO_SERIAL_PATH).exists() {
+ log("Virtio-serial port detected, using serial transport");
+ handle_virtio_serial(token, exclusive_busy).await;
+ return;
+ }
+
+ // Fallback: HTTP server on TCP port
+ let port: u16 = match get_param("quicksand_port") {
+ Some(p) => match p.parse() {
+ Ok(port) => port,
+ Err(_) => {
+ log(&format!("ERROR: Invalid quicksand_port: {}", p));
+ std::process::exit(1);
+ }
+ },
+ None => {
+ log("ERROR: No quicksand_port in /proc/cmdline");
+ std::process::exit(1);
+ }
+ };
+
+ log(&format!("Token: {}... Port: {}", &token[..8.min(token.len())], port));
+
+ let state = AppState {
+ token: Arc::new(token),
+ exclusive_busy,
+ };
+
+ let app = Router::new()
+ .route("/authenticate", post(authenticate))
+ .route("/execute", post(execute))
+ .route("/execute_stream", post(execute_stream))
+ .route("/ping", get(ping))
+ .with_state(state);
+
+ let addr = SocketAddr::from(([0, 0, 0, 0], port));
+ log(&format!("Listening on {}", addr));
+
+ let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
+ axum::serve(listener, app).await.unwrap();
+}
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/scaffold.py b/packages/dev/quicksand-image-tools/quicksand_image_tools/scaffold.py
new file mode 100644
index 0000000..77a473e
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/scaffold.py
@@ -0,0 +1,225 @@
+"""Scaffolding for new quicksand image packages.
+
+Copies an existing base image package (e.g. quicksand-ubuntu) and renames it
+to create a new image package, then registers it in the monorepo.
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+import sys
+from importlib.metadata import entry_points
+from pathlib import Path
+
+from quicksand_core import BaseImageInfo
+
+_ARTIFACT_EXTENSIONS = {".qcow2", ".kernel", ".initrd"}
+
+
+def _discover_bases() -> dict[str, BaseImageInfo]:
+ """Discover installed base image packages via entry points."""
+ import importlib
+ import logging
+
+ bases: dict[str, BaseImageInfo] = {}
+ eps = entry_points(group="quicksand.images")
+ for ep in eps:
+ try:
+ provider = ep.load()
+ if getattr(provider, "type", None) != "base":
+ continue
+ mod_name = ep.value.split(":")[0]
+ mod = importlib.import_module(mod_name)
+ docker_dir = getattr(mod, "_DOCKER_DIR", None) or getattr(mod, "DOCKER_DIR", None)
+ version = getattr(mod, "DISTRO_VERSION", getattr(mod, "__version__", "unknown"))
+ if docker_dir is None:
+ continue
+ bases[provider.name] = BaseImageInfo(
+ name=provider.name, docker_dir=docker_dir, version=version
+ )
+ except Exception as e:
+ logging.debug(f"Failed to load base entry point {ep.name}: {e}")
+ return bases
+
+
+def find_repo_root() -> Path | None:
+ """Find the repository root via git."""
+ result = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode == 0:
+ return Path(result.stdout.strip())
+ return None
+
+
+def _ignore_artifacts(_directory: str, files: list[str]) -> set[str]:
+ """shutil.copytree ignore callback — skip built images and caches."""
+ ignored = set()
+ for f in files:
+ p = Path(f)
+ if p.suffix in _ARTIFACT_EXTENSIONS:
+ ignored.add(f)
+ if f in ("__pycache__", ".pytest_cache") or f.endswith(".egg-info"):
+ ignored.add(f)
+ return ignored
+
+
+def _is_text_file(path: Path) -> bool:
+ """Check if a file is likely text (no null bytes in first 8KB)."""
+ try:
+ with open(path, "rb") as f:
+ chunk = f.read(8192)
+ return b"\x00" not in chunk
+ except OSError:
+ return False
+
+
+def _to_under(name: str) -> str:
+ return name.replace("-", "_")
+
+
+def _to_title(name: str) -> str:
+ parts = _to_under(name).split("_")
+ return "".join(p.capitalize() for p in parts)
+
+
+def copy_base_package(base_pkg_dir: Path, output_dir: Path) -> None:
+ """Copy a base image package, excluding built artifacts."""
+ shutil.copytree(base_pkg_dir, output_dir, ignore=_ignore_artifacts)
+
+
+def rename_module(output_dir: Path, old_pkg: str, new_pkg: str) -> None:
+ """Rename the Python module directory."""
+ old_module = output_dir / _to_under(old_pkg)
+ new_module = output_dir / _to_under(new_pkg)
+ if old_module.exists():
+ old_module.rename(new_module)
+
+
+def replace_in_tree(root: Path, old_pkg: str, new_pkg: str, base: str) -> None:
+ """Find-and-replace old package names with new names in all text files.
+
+ old_pkg/new_pkg are full package names like "quicksand-ubuntu" / "aif-agent-harness".
+ base is the short base name like "ubuntu".
+ """
+ old_under = _to_under(old_pkg)
+ new_under = _to_under(new_pkg)
+ base_title = _to_title(base)
+ new_title = _to_title(new_pkg)
+
+ # Ordered most-specific first to avoid partial matches
+ replacements = [
+ (old_under, new_under),
+ (old_pkg, new_pkg),
+ (base_title, new_title),
+ (base, new_pkg),
+ ]
+
+ for filepath in root.rglob("*"):
+ if not filepath.is_file():
+ continue
+ if not _is_text_file(filepath):
+ continue
+
+ content = filepath.read_text()
+ original = content
+ for old, new in replacements:
+ content = content.replace(old, new)
+ if content != original:
+ filepath.write_text(content)
+
+
+def reset_versions(output_dir: Path, pkg_name: str) -> None:
+ """Reset version fields to 0.1.0 and DISTRO_VERSION to placeholder."""
+ pkg_under = _to_under(pkg_name)
+
+ pyproject = output_dir / "pyproject.toml"
+ if pyproject.exists():
+ content = pyproject.read_text()
+ content = re.sub(
+ r'^version\s*=\s*"[^"]+"', 'version = "0.1.0"', content, flags=re.MULTILINE
+ )
+ pyproject.write_text(content)
+
+ init_py = output_dir / pkg_under / "__init__.py"
+ if init_py.exists():
+ content = init_py.read_text()
+ content = re.sub(
+ r'^__version__\s*=\s*"[^"]+"', '__version__ = "0.1.0"', content, flags=re.MULTILINE
+ )
+ content = re.sub(
+ r'^DISTRO_VERSION\s*=\s*"[^"]+"',
+ 'DISTRO_VERSION = "VERSION"',
+ content,
+ flags=re.MULTILINE,
+ )
+ init_py.write_text(content)
+
+
+def reset_readme(output_dir: Path, pkg_name: str) -> None:
+ """Overwrite README with a minimal install command."""
+ readme = output_dir / "README.md"
+ readme.write_text(f"# {pkg_name}\n\n```bash\nquicksand install {pkg_name}\n```\n")
+
+
+def reset_docker_dir(output_dir: Path, pkg_name: str, base: str) -> None:
+ """Clear docker dir and write a minimal FROM-base Dockerfile."""
+ pkg_under = _to_under(pkg_name)
+ docker_dir = output_dir / pkg_under / "docker"
+ if not docker_dir.exists():
+ return
+
+ # Keep .gitignore, remove everything else
+ for item in docker_dir.iterdir():
+ if item.name == ".gitignore":
+ continue
+ if item.is_dir():
+ shutil.rmtree(item)
+ else:
+ item.unlink()
+
+ # Discover the base version for the FROM tag
+ bases = _discover_bases()
+ info = bases.get(base)
+ version = info.version if info else "latest"
+
+ versioned_tag = f"quicksand/{base}-base:{version}"
+ dockerfile = docker_dir / "Dockerfile"
+ dockerfile.write_text(f"FROM {versioned_tag}\n\n# Add your customizations here\n")
+
+
+def register_package(pkg_name: str, repo_root: Path) -> bool:
+ """Register the new package in quicksand optional-dependencies via uv add."""
+ quicksand_pyproject = repo_root / "packages" / "quicksand" / "pyproject.toml"
+ if not quicksand_pyproject.exists():
+ return False
+
+ # Add as its own optional extra
+ result = subprocess.run(
+ ["uv", "add", "--optional", pkg_name, pkg_name, "--package", "quicksand", "--frozen"],
+ capture_output=True,
+ text=True,
+ cwd=repo_root,
+ )
+ if result.returncode != 0:
+ print(
+ f"Warning: failed to register optional dep '{pkg_name}': {result.stderr}",
+ file=sys.stderr,
+ )
+ return False
+
+ # Add to the 'all' extras
+ result = subprocess.run(
+ ["uv", "add", "--optional", "all", pkg_name, "--package", "quicksand", "--frozen"],
+ capture_output=True,
+ text=True,
+ cwd=repo_root,
+ )
+ if result.returncode != 0:
+ print(f"Warning: failed to add to 'all' extras: {result.stderr}", file=sys.stderr)
+
+ return True
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/80-dhcp.network b/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/80-dhcp.network
new file mode 100644
index 0000000..aec1849
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/80-dhcp.network
@@ -0,0 +1,5 @@
+[Match]
+Name=en*
+
+[Network]
+DHCP=yes
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/Dockerfile.j2 b/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/Dockerfile.j2
new file mode 100644
index 0000000..1e91f8e
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/Dockerfile.j2
@@ -0,0 +1,70 @@
+# Quicksand {{ name_title }} Base Image
+#
+# This Dockerfile creates a minimal {{ name_title }} system suitable for
+# running as a quicksand VM guest.
+#
+# TODO: Customize this Dockerfile for your Linux distribution.
+# See packages/quicksand-ubuntu/quicksand_ubuntu/docker/Dockerfile for a complete example.
+
+# =============================================================================
+# Stage 1: Build the Rust agent
+# =============================================================================
+# Use rust:alpine for musl (Alpine) or rust:bookworm for glibc (Ubuntu/Debian)
+FROM rust:alpine AS agent-builder
+
+RUN apk add --no-cache musl-dev
+
+WORKDIR /build
+COPY agent/Cargo.toml agent/Cargo.lock* ./
+COPY agent/src ./src
+
+RUN cargo build --release && \
+ strip /build/target/release/quicksand-guest-agent
+
+# =============================================================================
+# Stage 2: Create the VM image
+# =============================================================================
+# TODO: Set the base Docker image (e.g., ubuntu:24.04, alpine:3.21, debian:12)
+FROM {{ name }}:latest
+
+# TODO: Install kernel and required packages
+# Required packages:
+# - Linux kernel with virtio support
+# - Init system (systemd or OpenRC)
+# - sudo
+# - curl, ca-certificates (for network operations)
+
+# TODO: Create quicksand user with passwordless sudo
+# RUN useradd -m -s /bin/bash -G sudo quicksand
+# COPY quicksand-sudoers /etc/sudoers.d/quicksand
+# RUN chmod 440 /etc/sudoers.d/quicksand
+
+# TODO: Enable 9p kernel modules for host file sharing
+# RUN echo "9p" >> /etc/modules && \
+# echo "9pnet" >> /etc/modules && \
+# echo "9pnet_virtio" >> /etc/modules
+
+# TODO: Configure DHCP networking
+# For systemd:
+# COPY 80-dhcp.network /etc/systemd/network/
+# RUN systemctl enable systemd-networkd
+#
+# For OpenRC:
+# COPY interfaces /etc/network/interfaces
+# RUN rc-update add networking boot
+
+# Copy the Rust agent binary
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/quicksand-guest-agent
+RUN chmod +x /usr/local/bin/quicksand-guest-agent
+
+# TODO: Configure the agent to run on boot
+# For systemd:
+# RUN echo '[Unit]\nDescription=Quicksand Guest Agent\nAfter=network.target\n\n[Service]\nExecStart=/usr/local/bin/quicksand-guest-agent\nRestart=always\n\n[Install]\nWantedBy=multi-user.target' > /etc/systemd/system/quicksand-guest-agent.service && \
+# systemctl enable quicksand-guest-agent
+#
+# For OpenRC:
+# RUN echo '#!/sbin/openrc-run\ncommand="/usr/local/bin/quicksand-guest-agent"\ncommand_background="yes"\npidfile="/run/quicksand-guest-agent.pid"' > /etc/init.d/quicksand-guest-agent && \
+# chmod +x /etc/init.d/quicksand-guest-agent && \
+# rc-update add quicksand-guest-agent default
+
+CMD ["/sbin/init"]
diff --git a/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/quicksand-sudoers b/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/quicksand-sudoers
new file mode 100644
index 0000000..9439d4f
--- /dev/null
+++ b/packages/dev/quicksand-image-tools/quicksand_image_tools/templates/docker/quicksand-sudoers
@@ -0,0 +1,2 @@
+# Allow quicksand user to run any command without password
+quicksand ALL=(ALL) NOPASSWD: ALL
diff --git a/packages/dev/quicksand-overlay-scaffold/README.md b/packages/dev/quicksand-overlay-scaffold/README.md
new file mode 100644
index 0000000..b5552b5
--- /dev/null
+++ b/packages/dev/quicksand-overlay-scaffold/README.md
@@ -0,0 +1,58 @@
+# quicksand-overlay-scaffold
+
+Scaffold a new overlay image package for quicksand.
+
+Overlay packages boot a base VM (default: Ubuntu), run setup commands to install software, and save the result as a compressed overlay. The overlay is bundled into a wheel so users can `quicksand install` and `quicksand run` it without rebuilding.
+
+## Usage
+
+```bash
+quicksand-overlay-scaffold my-agent-sandbox
+```
+
+This creates a `my-agent-sandbox/` directory with:
+
+```
+my-agent-sandbox/
+├── pyproject.toml # Package metadata and entry points
+├── hatch_build.py # Edit _setup() with your install steps
+├── README.md
+└── my_agent_sandbox/
+ ├── __init__.py # ImageProvider entry point
+ ├── sandbox.py # Optional Sandbox subclass
+ └── images/ # Built overlay (populated during uv build)
+```
+
+## Next Steps
+
+1. Edit `hatch_build.py` — add your install commands to `_setup()`:
+
+```python
+async def _setup(shell: Shell) -> None:
+ await shell("apt-get update", timeout=120)
+ await shell("apt-get install -y your-packages", timeout=300)
+ await shell("pip install your-python-deps", timeout=300)
+```
+
+2. Build the package (boots a VM, runs setup, saves overlay):
+
+```bash
+uv build --package my-agent-sandbox
+```
+
+3. Test it:
+
+```bash
+quicksand run my-agent-sandbox
+```
+
+## How It Works
+
+During `uv build`, the `hatch_build.py` hook:
+
+1. Boots an Ubuntu VM with 4G memory, 4 CPUs, full network, 10G disk
+2. Runs your `_setup(shell)` function inside the VM
+3. Saves the VM state as a compressed qcow2 overlay
+4. Packages the overlay into a platform-specific wheel
+
+Subsequent builds skip the VM step if `images/manifest.json` already exists. Delete the `images/` directory to force a rebuild.
\ No newline at end of file
diff --git a/packages/dev/quicksand-overlay-scaffold/hatch_build.py b/packages/dev/quicksand-overlay-scaffold/hatch_build.py
new file mode 100644
index 0000000..2a707e7
--- /dev/null
+++ b/packages/dev/quicksand-overlay-scaffold/hatch_build.py
@@ -0,0 +1,129 @@
+"""Hatch build hook for overlay image packages.
+
+Edit _setup() to customize what gets installed in the sandbox.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+from collections.abc import Callable, Coroutine
+from pathlib import Path
+from typing import Any
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+SAVE_NAME = "quicksand-overlay-scaffold"
+SHELL = "/bin/bash"
+
+logger = logging.getLogger("quicksand-overlay-scaffold")
+
+# Type alias for the shell callable passed to _setup
+Shell = Callable[..., Coroutine[Any, Any, Any]]
+
+
+# =============================================================================
+# EDIT HERE — Install steps for your overlay image
+#
+# `shell` runs a command inside the sandbox, streams stdout/stderr,
+# and raises RuntimeError on non-zero exit. Pass timeout= for slow commands.
+#
+# Examples:
+# await shell("apt-get update", timeout=120)
+# await shell("pip install numpy", timeout=300)
+# =============================================================================
+
+
+async def _setup(shell: Shell) -> None:
+ await shell("echo 'Add your install steps here'")
+
+
+# =============================================================================
+
+
+class OverlayImageBuildHook(BuildHookInterface):
+ """Build hook that creates an overlay save from a running sandbox."""
+
+ PLUGIN_NAME = "quicksand-overlay-scaffold-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ if SAVE_NAME == "quicksand-overlay-scaffold":
+ # Scaffold template — not yet customized, skip image build
+ return
+
+ from quicksand_image_tools.build_utils import set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+
+ pkg_dir = Path(self.root) / "quicksand_overlay_scaffold"
+ save_dir = pkg_dir / "images"
+ overlays_dir = save_dir / "overlays"
+
+ if not (save_dir / "manifest.json").exists() or not any(overlays_dir.glob("*.qcow2")):
+ self.app.display_info("Save not found, building overlay...")
+ asyncio.run(self._build_and_save(save_dir))
+
+ self.app.display_info(f"Including save: {save_dir}")
+
+ async def _build_and_save(self, save_dir: Path) -> None:
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+
+ from quicksand_core._types import NetworkMode
+ from quicksand_ubuntu import UbuntuSandbox
+
+ async with UbuntuSandbox(
+ memory="4G",
+ cpus=4,
+ network_mode=NetworkMode.FULL,
+ disk_size="10G",
+ ) as sb:
+ await _setup(_make_shell(sb))
+ await sb.save(SAVE_NAME, workspace=save_dir.parent, compress=True)
+
+ built = save_dir.parent / SAVE_NAME
+ if save_dir.exists():
+ shutil.rmtree(save_dir)
+ built.rename(save_dir)
+
+
+def _make_shell(sb) -> Shell:
+ """Create a shell callable that streams output and raises on failure."""
+ stdout_buf: list[str] = []
+ stderr_buf: list[str] = []
+
+ def _flush_lines(buf: list[str], log_fn) -> None:
+ text = "".join(buf)
+ buf.clear()
+ for line in text.splitlines():
+ if line:
+ log_fn("%s", line)
+
+ def _on_stdout(chunk: str) -> None:
+ stdout_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stdout_buf, logger.info)
+
+ def _on_stderr(chunk: str) -> None:
+ stderr_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stderr_buf, logger.warning)
+
+ async def shell(cmd: str, **kwargs) -> None:
+ logger.info(">>> %s", cmd)
+ stdout_buf.clear()
+ stderr_buf.clear()
+ result = await sb.execute(
+ cmd,
+ shell=SHELL,
+ on_stdout=_on_stdout,
+ on_stderr=_on_stderr,
+ **kwargs,
+ )
+ _flush_lines(stdout_buf, logger.info)
+ _flush_lines(stderr_buf, logger.warning)
+ if result.exit_code != 0:
+ raise RuntimeError(f"Command failed (exit {result.exit_code}): {cmd}\n{result.stderr}")
+
+ return shell
diff --git a/packages/dev/quicksand-overlay-scaffold/pyproject.toml b/packages/dev/quicksand-overlay-scaffold/pyproject.toml
new file mode 100644
index 0000000..2702220
--- /dev/null
+++ b/packages/dev/quicksand-overlay-scaffold/pyproject.toml
@@ -0,0 +1,38 @@
+[project]
+name = "quicksand-overlay-scaffold"
+version = "0.2.4"
+description = "Overlay image package for quicksand"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+ "quicksand-ubuntu>=0.8.4",
+ "tomlkit>=0.13",
+]
+
+[project.scripts]
+quicksand-overlay-scaffold = "quicksand_overlay_scaffold.scaffold:main"
+
+[project.entry-points."quicksand.images"]
+quicksand-overlay-scaffold = "quicksand_overlay_scaffold:image"
+
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "quicksand-ubuntu", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_overlay_scaffold"]
+artifacts = [
+ "quicksand_overlay_scaffold/images/manifest.json",
+ "quicksand_overlay_scaffold/images/overlays/*.qcow2",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-qemu = { workspace = true }
+quicksand-smb = { workspace = true }
+quicksand-core = { workspace = true }
+quicksand-ubuntu = { workspace = true }
diff --git a/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/__init__.py b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/__init__.py
new file mode 100644
index 0000000..4d7b95e
--- /dev/null
+++ b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/__init__.py
@@ -0,0 +1,40 @@
+"""QuicksandOverlayScaffold: template overlay package for quicksand."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+__version__ = "0.1.0"
+
+PACKAGE_DIR = Path(__file__).parent
+IMAGES_DIR = PACKAGE_DIR / "images"
+
+
+class _OverlayScaffoldImageProvider:
+ """ImageProvider for the bundled overlay scaffold."""
+
+ name = "quicksand-overlay-scaffold"
+ type = "overlay"
+ images_dir = IMAGES_DIR
+
+ def resolve(self, arch: str | None = None):
+ 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."
+ )
+ return ImageResolver()._resolve_save(IMAGES_DIR)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _OverlayScaffoldImageProvider()
+
+
+__all__ = [
+ "IMAGES_DIR",
+ "PACKAGE_DIR",
+ "__version__",
+ "image",
+]
diff --git a/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/images/.gitignore b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/images/.gitignore
new file mode 100644
index 0000000..bb6857f
--- /dev/null
+++ b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/images/.gitignore
@@ -0,0 +1,3 @@
+# Build artifacts — generated during uv build
+*
+!.gitignore
diff --git a/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/sandbox.py b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/sandbox.py
new file mode 100644
index 0000000..cfba29d
--- /dev/null
+++ b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/sandbox.py
@@ -0,0 +1,38 @@
+"""Pre-configured Sandbox using the bundled overlay save."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import Sandbox
+from quicksand_core._types import SandboxConfigParams
+
+
+class QuicksandOverlayScaffoldSandbox(Sandbox):
+ """Pre-configured Sandbox that boots from the bundled overlay.
+
+ Requires quicksand-ubuntu to be installed (the overlay is built on top of it).
+
+ Usage::
+
+ async with QuicksandOverlayScaffoldSandbox() as sb:
+ result = await sb.execute("echo hello")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "quicksand-overlay-scaffold")
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
diff --git a/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/scaffold.py b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/scaffold.py
new file mode 100644
index 0000000..588329d
--- /dev/null
+++ b/packages/dev/quicksand-overlay-scaffold/quicksand_overlay_scaffold/scaffold.py
@@ -0,0 +1,175 @@
+"""Scaffold a new overlay package from this template.
+
+Copies the entire package, renames everything, and removes this scaffold script
+from the destination.
+"""
+
+from __future__ import annotations
+
+import shutil
+import sys
+from pathlib import Path
+
+import tomlkit
+from tomlkit.container import OutOfOrderTableProxy
+from tomlkit.items import Table
+
+
+def _to_under(name: str) -> str:
+ return name.replace("-", "_")
+
+
+def _to_title(name: str) -> str:
+ parts = _to_under(name).split("_")
+ return "".join(p.capitalize() for p in parts)
+
+
+def _clean_pyproject(pyproject: Path) -> None:
+ """Strip monorepo-only config from a scaffolded pyproject.toml."""
+ doc = tomlkit.parse(pyproject.read_text())
+ # Remove [tool.uv.sources] (workspace refs don't apply outside monorepo)
+ if "tool" in doc:
+ tool = doc["tool"]
+ assert isinstance(tool, (Table, OutOfOrderTableProxy))
+ if "uv" in tool:
+ uv = tool["uv"]
+ assert isinstance(uv, (Table, OutOfOrderTableProxy))
+ if "sources" in uv:
+ del uv["sources"]
+ if not uv:
+ del tool["uv"]
+ if not tool:
+ del doc["tool"]
+ # Reset version, remove scaffold entry point, strip scaffold-only deps
+ project = doc["project"]
+ assert isinstance(project, (Table, OutOfOrderTableProxy))
+ project["version"] = "0.1.0"
+ if "scripts" in project:
+ del project["scripts"]
+ deps = list(project.get("dependencies", []))
+ project["dependencies"] = [d for d in deps if "tomlkit" not in str(d)]
+ pyproject.write_text(tomlkit.dumps(doc))
+
+
+def _is_text_file(path: Path) -> bool:
+ try:
+ with open(path, "rb") as f:
+ chunk = f.read(8192)
+ return b"\x00" not in chunk
+ except OSError:
+ return False
+
+
+def scaffold(
+ name: str,
+ base: str,
+ output_dir: Path | None = None,
+) -> None:
+ """Scaffold a new overlay image package.
+
+ Args:
+ name: Package name (e.g. ``my-agent-sandbox``).
+ base: Base image to overlay on (e.g. ``ubuntu``, ``alpine``).
+ output_dir: Where to create the package. Defaults to ``./<name>``.
+ """
+ name = name.lower()
+ if "/" in name or "\\" in name:
+ raise ValueError("name must be a plain package name, not a path")
+
+ base = base.lower()
+ if output_dir is None:
+ output_dir = Path(name)
+
+ if output_dir.exists() and any(output_dir.iterdir()):
+ raise FileExistsError(f"{output_dir} already exists and is non-empty")
+
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
+
+ # Copy this package as template
+ pkg_root = Path(__file__).parent.parent
+ shutil.copytree(
+ pkg_root,
+ output_dir,
+ ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache", "*.egg-info"),
+ )
+
+ # Rename module directory
+ old_module = output_dir / "quicksand_overlay_scaffold"
+ new_module = output_dir / _to_under(name)
+ if old_module.exists():
+ old_module.rename(new_module)
+
+ # String replacements -- package name + base image
+ old_name = "quicksand-overlay-scaffold"
+ title = _to_title(name)
+ # Avoid QuicksandOverlayScaffoldSandbox -> MySandboxSandbox
+ if title.endswith("Sandbox"):
+ title = title[: -len("Sandbox")]
+ base_pkg = f"quicksand-{base}"
+ base_under = _to_under(base_pkg)
+ base_title = _to_title(base)
+ replacements = [
+ ("quicksand_overlay_scaffold", _to_under(name)),
+ (old_name, name),
+ ("QuicksandOverlayScaffold", title),
+ ]
+ if base != "ubuntu":
+ replacements += [
+ ("quicksand_ubuntu", base_under),
+ ("quicksand-ubuntu", base_pkg),
+ ("UbuntuSandbox", f"{base_title}Sandbox"),
+ ]
+
+ for filepath in output_dir.rglob("*"):
+ if not filepath.is_file() or not _is_text_file(filepath):
+ continue
+ content = filepath.read_text()
+ original = content
+ for old, new in replacements:
+ content = content.replace(old, new)
+ if content != original:
+ filepath.write_text(content)
+
+ # Clean up pyproject.toml for standalone use
+ pyproject = output_dir / "pyproject.toml"
+ if pyproject.exists():
+ _clean_pyproject(pyproject)
+
+ # Remove scaffold script from destination
+ scaffold_file = new_module / "scaffold.py"
+ if scaffold_file.exists():
+ scaffold_file.unlink()
+
+ print(f"Scaffolded overlay package: {output_dir}")
+ print("\nNext steps:")
+ print(" 1. Edit hatch_build.py -- add your install steps to _setup()")
+ print(" 2. pip install -e . && uv build")
+
+
+def main() -> None:
+ """CLI entry point."""
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ prog="quicksand-overlay-scaffold",
+ description="Scaffold a new overlay image package from a template",
+ )
+ parser.add_argument("name", help="Package name (e.g. my-agent-sandbox)")
+ parser.add_argument(
+ "--base",
+ required=True,
+ help="Base image to overlay on (e.g. ubuntu, alpine)",
+ )
+ parser.add_argument(
+ "--output-dir",
+ type=Path,
+ default=None,
+ help="Output directory (default: ./<name>)",
+ )
+ args = parser.parse_args()
+
+ try:
+ scaffold(name=args.name, base=args.base, output_dir=args.output_dir)
+ except (ValueError, FileExistsError) as e:
+ print(f"Error: {e}", file=sys.stderr)
+ sys.exit(1)
diff --git a/packages/quicksand-alpine-desktop/README.md b/packages/quicksand-alpine-desktop/README.md
new file mode 100644
index 0000000..a7738c5
--- /dev/null
+++ b/packages/quicksand-alpine-desktop/README.md
@@ -0,0 +1,50 @@
+# Quicksand Alpine Desktop
+
+Minimal Alpine Linux 3.21 desktop VM (Xfce4) for the [quicksand](https://github.com/microsoft/quicksand) agent harness. Lightweight and fast-booting — ideal when you need GUI automation without the overhead of a full Ubuntu desktop.
+
+## Installation
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+quicksand install alpine-desktop
+```
+
+## Usage
+
+```python
+import asyncio
+from quicksand import Key
+from quicksand_alpine_desktop import AlpineDesktopSandbox
+
+async def main():
+ async with AlpineDesktopSandbox() as sb:
+ await sb.screenshot("desktop.png")
+ await sb.type_text("echo hello world")
+ await sb.press_key(Key.RET)
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## What's Included
+
+- Alpine 3.21 with Xfce4 desktop + LightDM (auto-login)
+- Chromium browser
+- Python 3, bash, curl
+- The quicksand guest agent (pre-installed)
+
+## Default Config
+
+| Setting | Default |
+|---------|---------|
+| Memory | 1G |
+| CPUs | 2 |
+| Display | Enabled (always) |
+| Boot timeout | 60s |
+| Init system | OpenRC |
+| Image size | ~300MB |
+
+## License
+
+MIT
diff --git a/packages/quicksand-alpine-desktop/hatch_build.py b/packages/quicksand-alpine-desktop/hatch_build.py
new file mode 100644
index 0000000..e03899c
--- /dev/null
+++ b/packages/quicksand-alpine-desktop/hatch_build.py
@@ -0,0 +1,295 @@
+"""Hatch build hook for the Alpine Desktop overlay.
+
+Boots Alpine base, installs Xfce4 desktop environment with X.org, LightDM,
+Chromium, and supporting services, then saves the overlay.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+from collections.abc import Callable, Coroutine
+from pathlib import Path
+from typing import Any
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+SAVE_NAME = "alpine-desktop"
+SHELL = "/bin/sh"
+
+logger = logging.getLogger("alpine-desktop")
+
+
+async def _setup(shell: Callable[..., Coroutine[Any, Any, Any]]) -> None:
+ """Install Xfce4 desktop environment on Alpine base."""
+
+ # ── Install X.org + Xfce4 + desktop packages ─────────────────
+ await shell(
+ "apk add --no-cache xorg-server xf86-video-modesetting xf86-input-libinput",
+ timeout=120,
+ )
+ await shell(
+ "apk add --no-cache "
+ "xfce4-session xfce4-panel xfce4-terminal xfce4-settings "
+ "xfwm4 xfdesktop thunar xfce4-appfinder",
+ timeout=300,
+ )
+ await shell(
+ "apk add --no-cache "
+ "lightdm lightdm-gtk-greeter dbus dbus-x11 "
+ "mesa-dri-gallium chromium font-dejavu eudev bash",
+ timeout=300,
+ )
+
+ # ── User config: add to video+input groups, change shell ─────
+ await shell("addgroup quicksand video || true")
+ await shell("addgroup quicksand input || true")
+ await shell("sed -i 's|quicksand:/bin/sh|quicksand:/bin/bash|' /etc/passwd")
+
+ # ── LightDM auto-login ───────────────────────────────────────
+ await shell(
+ "mkdir -p /etc/lightdm && "
+ "printf '[Seat:*]\\nautologin-user=quicksand\\nautologin-session=xfce\\n"
+ "user-session=xfce\\n' > /etc/lightdm/lightdm.conf"
+ )
+
+ # ── Mesa software rendering ──────────────────────────────────
+ await shell("printf 'export LIBGL_ALWAYS_SOFTWARE=1\\n' > /etc/profile.d/quicksand-mesa.sh")
+
+ # ── Kernel modules for GPU + input ───────────────────────────
+ await shell(
+ "echo virtio-gpu >> /etc/modules && "
+ "echo drm >> /etc/modules && "
+ "echo virtio_input >> /etc/modules && "
+ "echo evdev >> /etc/modules && "
+ "echo uinput >> /etc/modules"
+ )
+
+ # ── modprobe softdep: virtio_input → evdev ───────────────────
+ await shell(
+ "mkdir -p /etc/modprobe.d && "
+ "printf 'softdep virtio_input post: evdev\\n' "
+ "> /etc/modprobe.d/quicksand-input.conf"
+ )
+
+ # ── OpenRC service: load-input-modules ───────────────────────
+ await shell(
+ """cat > /etc/init.d/load-input-modules << 'INITEOF'
+#!/sbin/openrc-run
+description="Load input kernel modules and retrigger udev"
+
+depend() {
+ need udev modules
+ before lightdm
+}
+
+start() {
+ ebegin "Loading input modules"
+ modprobe virtio_input 2>/dev/null
+ modprobe evdev 2>/dev/null
+ modprobe uinput 2>/dev/null
+ modprobe hid 2>/dev/null
+ udevadm trigger --subsystem-match=input --action=add
+ udevadm settle --timeout=5
+ eend 0
+}
+INITEOF
+chmod +x /etc/init.d/load-input-modules
+rc-update add load-input-modules boot"""
+ )
+
+ # ── Udev rules for input devices ─────────────────────────────
+ kbd_rule = (
+ 'SUBSYSTEM=="input", KERNEL=="event*", '
+ 'ATTRS{name}=="QEMU Virtio Keyboard", '
+ 'ENV{ID_INPUT_KEYBOARD}="1", ENV{ID_INPUT_KEY}="1"'
+ )
+ await shell(
+ "mkdir -p /etc/udev/rules.d\n"
+ "cat > /etc/udev/rules.d/90-quicksand-input.rules << RULESEOF\n"
+ 'SUBSYSTEM=="input", KERNEL=="event*", ENV{ID_INPUT}="1"\n'
+ f"{kbd_rule}\n"
+ 'SUBSYSTEM=="input", KERNEL=="event*", '
+ 'ATTRS{name}=="QEMU*Tablet*", ENV{ID_INPUT_MOUSE}="1"\n'
+ 'SUBSYSTEM=="input", KERNEL=="event*", TAG+="seat"\n'
+ "RULESEOF"
+ )
+
+ # ── Switch from mdev to eudev ────────────────────────────────
+ await shell("rc-update del mdev sysinit || true")
+ await shell("rc-update add udev sysinit")
+
+ # ── Change rc_sys from "lxc" to "" ───────────────────────────
+ await shell("sed -i 's/^rc_sys=.*/rc_sys=\"\"/' /etc/rc.conf")
+
+ # ── Remove hwclock (unreliable on ARM64 virt) ────────────────
+ await shell("rc-update del hwclock boot || true")
+
+ # ── Enable desktop services ──────────────────────────────────
+ await shell("rc-update add dbus default")
+ await shell("rc-update add lightdm default")
+
+ # ── Fix-devpts service ───────────────────────────────────────
+ await shell(
+ """cat > /etc/init.d/fix-devpts << 'FIXEOF'
+#!/sbin/openrc-run
+command="/bin/mount"
+command_args="-o remount,ptmxmode=666 /dev/pts"
+depend() { need devfs; }
+FIXEOF
+chmod +x /etc/init.d/fix-devpts
+rc-update add fix-devpts sysinit"""
+ )
+
+ # ── Xorg config ──────────────────────────────────────────────
+ await shell(
+ """mkdir -p /etc/X11
+cat > /etc/X11/xorg.conf << 'XORGEOF'
+# Quicksand Xorg configuration for QEMU virtio-gpu virtual display.
+#
+# We do NOT set AutoAddDevices=False here. The USB tablet (event1) and VirtIO
+# keyboard (event2) are enumerated by udev a few milliseconds after X starts;
+# letting Xorg auto-add them via the config/udev backend is the only reliable
+# way to get input working, because static InputDevice entries run at PreInit
+# time (before udev has finished, so libinput fails with ENODEV).
+
+Section "Device"
+ Identifier "VirtualGPU"
+ Driver "modesetting"
+ Option "kmsdev" "/dev/dri/card0"
+ # Render cursor into the framebuffer so QMP screendump captures it.
+ Option "SWcursor" "true"
+EndSection
+
+Section "Screen"
+ Identifier "DefaultScreen"
+ Device "VirtualGPU"
+EndSection
+XORGEOF"""
+ )
+
+ # ── Xfce4 pre-configuration ──────────────────────────────────
+ await shell(
+ """mkdir -p /home/quicksand/.config/xfce4/xfconf/xfce-perchannel-xml
+
+cat > /home/quicksand/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml << 'X1'
+<?xml version="1.0" encoding="UTF-8"?>
+<channel name="xfwm4" version="1.0">
+ <property name="general" type="empty">
+ <property name="use_compositing" type="bool" value="false"/>
+ <property name="vblank_mode" type="string" value="off"/>
+ </property>
+</channel>
+X1
+
+cat > /home/quicksand/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-screensaver.xml << 'X2'
+<?xml version="1.0" encoding="UTF-8"?>
+<channel name="xfce4-screensaver" version="1.0">
+ <property name="saver" type="empty">
+ <property name="enabled" type="bool" value="false"/>
+ </property>
+ <property name="lock" type="empty">
+ <property name="enabled" type="bool" value="false"/>
+ </property>
+</channel>
+X2
+
+cat > /home/quicksand/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml << 'X3'
+<?xml version="1.0" encoding="UTF-8"?>
+<channel name="xfce4-power-manager" version="1.0">
+ <property name="xfce4-power-manager" type="empty">
+ <property name="dpms-enabled" type="bool" value="false"/>
+ <property name="blank-on-ac" type="int" value="0"/>
+ </property>
+</channel>
+X3
+
+chown -R quicksand:quicksand /home/quicksand/.config"""
+ )
+
+ # ── Clean package caches ─────────────────────────────────────
+ await shell("rm -rf /var/cache/apk/* /tmp/*")
+
+
+class OverlayImageBuildHook(BuildHookInterface):
+ """Build hook that creates an overlay save from a running Alpine sandbox."""
+
+ PLUGIN_NAME = "alpine-desktop-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ from quicksand_image_tools.build_utils import set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+
+ pkg_dir = Path(self.root) / "quicksand_alpine_desktop"
+ save_dir = pkg_dir / "images"
+ overlays_dir = save_dir / "overlays"
+
+ if not (save_dir / "manifest.json").exists() or not any(overlays_dir.glob("*.qcow2")):
+ self.app.display_info("Save not found, building overlay...")
+ asyncio.run(self._build_and_save(save_dir))
+
+ self.app.display_info(f"Including save: {save_dir}")
+
+ async def _build_and_save(self, save_dir: Path) -> None:
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+
+ from quicksand_alpine import AlpineSandbox
+ from quicksand_core._types import NetworkMode
+
+ async with AlpineSandbox(
+ memory="2G",
+ cpus=4,
+ network_mode=NetworkMode.FULL,
+ disk_size="5G",
+ ) as sb:
+ await _setup(_make_shell(sb))
+ await sb.save(SAVE_NAME, workspace=save_dir.parent, compress=True)
+
+ built = save_dir.parent / SAVE_NAME
+ if save_dir.exists():
+ shutil.rmtree(save_dir)
+ built.rename(save_dir)
+
+
+def _make_shell(sb) -> Callable[..., Coroutine[Any, Any, Any]]:
+ """Create a shell callable that streams output and raises on failure."""
+ stdout_buf: list[str] = []
+ stderr_buf: list[str] = []
+
+ def _flush_lines(buf: list[str], log_fn) -> None:
+ text = "".join(buf)
+ buf.clear()
+ for line in text.splitlines():
+ if line:
+ log_fn("%s", line)
+
+ def _on_stdout(chunk: str) -> None:
+ stdout_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stdout_buf, logger.info)
+
+ def _on_stderr(chunk: str) -> None:
+ stderr_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stderr_buf, logger.warning)
+
+ async def shell(cmd: str, **kwargs) -> None:
+ logger.info(">>> %s", cmd)
+ stdout_buf.clear()
+ stderr_buf.clear()
+ result = await sb.execute(
+ cmd,
+ shell=SHELL,
+ on_stdout=_on_stdout,
+ on_stderr=_on_stderr,
+ **kwargs,
+ )
+ _flush_lines(stdout_buf, logger.info)
+ _flush_lines(stderr_buf, logger.warning)
+ if result.exit_code != 0:
+ raise RuntimeError(f"Command failed (exit {result.exit_code}): {cmd}\n{result.stderr}")
+
+ return shell
diff --git a/packages/quicksand-alpine-desktop/pyproject.toml b/packages/quicksand-alpine-desktop/pyproject.toml
new file mode 100644
index 0000000..2e71ace
--- /dev/null
+++ b/packages/quicksand-alpine-desktop/pyproject.toml
@@ -0,0 +1,35 @@
+[project]
+name = "quicksand-alpine-desktop"
+version = "0.8.4"
+description = "Minimal Alpine Linux desktop VM (Xfce4) for quicksand"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+ "quicksand-alpine>=0.8.4",
+]
+
+[dependency-groups]
+dev = []
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "quicksand-alpine", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_alpine_desktop"]
+artifacts = [
+ "quicksand_alpine_desktop/images/manifest.json",
+ "quicksand_alpine_desktop/images/overlays/*.qcow2",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
+quicksand-alpine = { workspace = true }
+
+[project.entry-points."quicksand.images"]
+alpine-desktop = "quicksand_alpine_desktop:image"
diff --git a/packages/quicksand-alpine-desktop/quicksand_alpine_desktop/__init__.py b/packages/quicksand-alpine-desktop/quicksand_alpine_desktop/__init__.py
new file mode 100644
index 0000000..24a434f
--- /dev/null
+++ b/packages/quicksand-alpine-desktop/quicksand_alpine_desktop/__init__.py
@@ -0,0 +1,100 @@
+"""
+Quicksand Alpine Desktop bundles a minimal Alpine Linux VM with Xfce4 desktop.
+
+Lightweight (~300MB image) and boots quickly (~15s). Built as an overlay on
+quicksand-alpine — both execute() and GUI input (screenshot/type_text/click)
+work.
+
+Quick start:
+ import asyncio
+ from quicksand import Key
+ from quicksand_alpine_desktop import AlpineDesktopSandbox
+
+ async def main():
+ async with AlpineDesktopSandbox() as sb:
+ await sb.screenshot("desktop.png")
+ await sb.type_text("hello world")
+ await sb.press_key(Key.RET)
+ result = await sb.execute("cat /etc/os-release")
+
+ asyncio.run(main())
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import Sandbox
+from quicksand_core._types import SandboxConfigParams
+
+__version__ = "0.2.3"
+
+DISTRO_VERSION = "3.21"
+
+_PACKAGE_DIR = Path(__file__).parent
+_IMAGES_DIR = _PACKAGE_DIR / "images"
+
+
+class _AlpineDesktopImageProvider:
+ """ImageProvider for the bundled Alpine Desktop overlay."""
+
+ name = "alpine-desktop"
+ type = "overlay"
+ images_dir = _IMAGES_DIR
+
+ def resolve(self, arch: str | None = None):
+ 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."
+ )
+ return ImageResolver()._resolve_save(_IMAGES_DIR)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _AlpineDesktopImageProvider()
+
+
+class AlpineDesktopSandbox(Sandbox):
+ """Pre-configured Sandbox with an Alpine Linux Xfce4 desktop.
+
+ Lightweight alternative to UbuntuDesktopSandbox: ~300MB image,
+ ~15s boot, and full guest agent support (execute() works).
+
+ Usage::
+
+ async with AlpineDesktopSandbox() as sb:
+ await sb.screenshot("boot.png")
+ await sb.type_text("hello")
+ await sb.press_key(Key.RET)
+ result = await sb.execute("uname -a")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "alpine-desktop")
+ kwargs.setdefault("memory", "1G")
+ kwargs.setdefault("cpus", 2)
+ kwargs.setdefault("enable_display", True)
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
+
+
+__all__ = [
+ "AlpineDesktopSandbox",
+ "__version__",
+]
diff --git a/packages/quicksand-alpine/README.md b/packages/quicksand-alpine/README.md
new file mode 100644
index 0000000..3d98be9
--- /dev/null
+++ b/packages/quicksand-alpine/README.md
@@ -0,0 +1,94 @@
+# Quicksand Alpine
+
+This package bundles a pre-built Alpine Linux 3.23 VM image for the [quicksand](https://github.com/microsoft/quicksand) agent harness. No downloads required after installation.
+
+Alpine is lightweight and boots quickly, making it ideal for AI agents that need fast sandbox startup.
+
+## Why Alpine?
+
+Alpine Linux is a lightweight distribution that offers:
+- **Smaller image size**: ~75MB vs ~300MB for Ubuntu
+- **Faster boot time**: Less to load means quicker startup
+- **Minimal attack surface**: Only essential packages included
+- **musl libc**: Smaller, simpler C library
+
+Use Alpine when you need fast, lightweight sandboxes. Use Ubuntu when you need broader package compatibility or glibc-dependent software.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install alpine
+```
+
+This installs `quicksand` with the bundled Alpine image.
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from quicksand import AlpineSandbox
+
+async def main():
+ async with AlpineSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand import AlpineSandbox
+
+async with AlpineSandbox(memory="512M", cpus=2) as sb:
+ result = await sb.execute("uname -a")
+```
+
+Or using `Sandbox` directly:
+
+```python
+from quicksand import Sandbox
+
+async with Sandbox(image="alpine", memory="512M", cpus=2) as sb:
+ result = await sb.execute("uname -a")
+```
+
+## What's Included
+
+The Alpine 3.23 image includes:
+- Python 3
+- Bash shell
+- curl, ca-certificates
+- Networking tools (iproute2, iputils-ping)
+- The quicksand agent (pre-installed)
+
+## Installing Additional Packages
+
+Alpine uses `apk` for package management:
+
+```python
+async with AlpineSandbox() as sb:
+ # Install packages
+ await sb.execute("apk add --no-cache git nodejs npm")
+
+ # Use them
+ result = await sb.execute("node --version")
+ print(result.stdout)
+```
+
+## Package Size
+
+The wheel is ~75MB, much smaller than Ubuntu (~300MB) because Alpine is a minimal distribution. This makes it faster to download and install.
+
+## License
+
+MIT
diff --git a/packages/quicksand-alpine/hatch_build.py b/packages/quicksand-alpine/hatch_build.py
new file mode 100644
index 0000000..e46498d
--- /dev/null
+++ b/packages/quicksand-alpine/hatch_build.py
@@ -0,0 +1,76 @@
+"""Hatch build hook for platform-specific Alpine VM image wheels."""
+
+from __future__ import annotations
+
+import logging
+import re
+from pathlib import Path
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+logger = logging.getLogger(__name__)
+
+
+def _read_distro_version(root: Path) -> str:
+ """Read DISTRO_VERSION from __init__.py without importing the module."""
+ init_file = root / "quicksand_alpine" / "__init__.py"
+ content = init_file.read_text()
+ match = re.search(r'^DISTRO_VERSION\s*=\s*["\']([^"\']+)["\']', content, re.MULTILINE)
+ if not match:
+ raise RuntimeError(f"Could not find DISTRO_VERSION in {init_file}")
+ return match.group(1)
+
+
+class AlpineImageBuildHook(BuildHookInterface):
+ """Build hook that packages Alpine VM images with platform-specific wheel tags."""
+
+ PLUGIN_NAME = "alpine-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ """Verify the image exists (building if needed) and set platform-specific wheel tags."""
+ from quicksand_image_tools.build_utils import get_image_arch, set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+ arch = get_image_arch()
+
+ # Check if image exists
+ distro_version = _read_distro_version(Path(self.root))
+
+ pkg_dir = Path(self.root) / "quicksand_alpine"
+ images_dir = pkg_dir / "images"
+ image_path = images_dir / f"alpine-{distro_version}-{arch}.qcow2"
+ dockerfile_path = Path(self.root) / "quicksand_alpine" / "docker" / "Dockerfile"
+
+ if not image_path.exists():
+ self.app.display_info(f"Image not found: {image_path.name}, building...")
+ self._build_image(dockerfile_path, image_path)
+
+ self.app.display_info(f"Including image: {image_path}")
+
+ def _build_image(self, dockerfile: Path, output: Path) -> None:
+ """Build the VM image using quicksand-image-tools.
+
+ The Dockerfile uses a multi-stage build to compile the Rust agent.
+ The agent source is accessed via symlink at docker/agent/.
+ """
+ try:
+ from quicksand_image_tools import build_image
+
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+ build_log = logging.getLogger("quicksand-alpine")
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ build_image(dockerfile, output_path=output, log=build_log)
+
+ except ImportError as e:
+ raise RuntimeError(
+ f"quicksand-image-tools is required to build images but failed to import: {e}\n\n"
+ f"This should be installed automatically as a build dependency.\n"
+ f"If building manually, install it first:\n"
+ f" pip install quicksand-image-tools"
+ ) from e
+ except Exception as e:
+ raise RuntimeError(
+ f"Failed to build image: {e}\n\nMake sure Docker is running and accessible."
+ ) from e
diff --git a/packages/quicksand-alpine/pyproject.toml b/packages/quicksand-alpine/pyproject.toml
new file mode 100644
index 0000000..4071ee9
--- /dev/null
+++ b/packages/quicksand-alpine/pyproject.toml
@@ -0,0 +1,38 @@
+[project]
+name = "quicksand-alpine"
+version = "0.8.4"
+description = "Pre-built Alpine Linux VM image for quicksand"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+]
+
+[dependency-groups]
+dev = ["quicksand-image-tools>=0.4.3"]
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_alpine"]
+artifacts = [
+ "quicksand_alpine/images/*.qcow2",
+ "quicksand_alpine/images/*.kernel",
+ "quicksand_alpine/images/*.initrd",
+]
+exclude = [
+ "quicksand_alpine/docker",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
+# Build hook in hatch_build.py builds images if they don't exist
+
+[project.entry-points."quicksand.images"]
+alpine = "quicksand_alpine:image"
diff --git a/packages/quicksand-alpine/quicksand_alpine/__init__.py b/packages/quicksand-alpine/quicksand_alpine/__init__.py
new file mode 100644
index 0000000..b49657a
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/__init__.py
@@ -0,0 +1,139 @@
+"""
+Quicksand Alpine bundles a pre-built Alpine Linux 3.23 VM image for the quicksand
+agent harness. No downloads required after installation.
+
+Alpine is lightweight (~75MB vs ~300MB for Ubuntu) and boots quickly. It uses
+the apk package manager instead of apt.
+
+Quick start:
+ import asyncio
+ from quicksand import AlpineSandbox
+
+ async def main():
+ async with AlpineSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+ asyncio.run(main())
+
+Or with custom configuration:
+ from quicksand import Sandbox
+
+ async with Sandbox(image="alpine", memory="512M", cpus=2) as sb:
+ result = await sb.execute("cat /etc/os-release")
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import ResolvedImage, Sandbox
+from quicksand_core._types import SandboxConfigParams
+from quicksand_core.host import Architecture
+from quicksand_core.qemu.platform import get_platform_config
+
+__version__ = "0.1.14"
+
+DISTRO_VERSION = "3.23"
+
+_PACKAGE_DIR = Path(__file__).parent
+_IMAGES_DIR = _PACKAGE_DIR / "images"
+_DOCKER_DIR = _PACKAGE_DIR / "docker"
+
+
+class _AlpineImageProvider:
+ """ImageProvider for the bundled Alpine base image."""
+
+ name = "alpine"
+ type = "base"
+ images_dir = _IMAGES_DIR
+
+ def resolve(self, arch: str | None = None) -> ResolvedImage:
+ return _get_image_artifacts(arch)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _AlpineImageProvider()
+
+
+def _get_image_artifacts(arch: str | None = None) -> ResolvedImage:
+ if arch is None:
+ config = get_platform_config()
+ arch = "arm64" if config.arch.arch_type == Architecture.ARM64 else "amd64"
+
+ image_path = _IMAGES_DIR / f"alpine-{DISTRO_VERSION}-{arch}.qcow2"
+
+ if not image_path.exists():
+ image_path = _IMAGES_DIR / f"alpine-{DISTRO_VERSION}.qcow2"
+
+ if not image_path.exists():
+ available = list(_IMAGES_DIR.glob("*.qcow2")) if _IMAGES_DIR.exists() else []
+ if available:
+ available_str = ", ".join(p.name for p in available)
+ from quicksand_core.host.arch import _is_emulated
+
+ if _is_emulated():
+ raise FileNotFoundError(
+ f"Alpine image for {arch} not found. Available: {available_str}\n"
+ "Python is running under platform emulation, so pip installed "
+ "the wrong architecture variant.\n"
+ "Reinstall with: quicksand install quicksand-alpine"
+ )
+ raise FileNotFoundError(
+ f"Alpine image for {arch} not found. Available: {available_str}\n"
+ "Reinstall with: quicksand install quicksand-alpine"
+ )
+ raise FileNotFoundError(
+ f"No Alpine images found in {_IMAGES_DIR}. "
+ "The package may not have been built correctly."
+ )
+
+ return ResolvedImage(
+ name="alpine",
+ chain=[image_path],
+ kernel=image_path.with_suffix(".kernel"),
+ initrd=image_path.with_suffix(".initrd"),
+ )
+
+
+class AlpineSandbox(Sandbox):
+ """Pre-configured Sandbox using the bundled Alpine image.
+
+ Alpine Linux is lightweight (~75MB image) and boots faster than Ubuntu.
+
+ Usage::
+
+ async with AlpineSandbox() as sb:
+ result = await sb.execute("cat /etc/alpine-release")
+
+ async with AlpineSandbox(save="my-env") as sb:
+ await sb.execute("apk add python3")
+
+ async with AlpineSandbox(image="my-env") as sb:
+ await sb.execute("python3 --version")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "alpine")
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
+
+
+__all__ = [
+ "DISTRO_VERSION",
+ "AlpineSandbox",
+ "__version__",
+]
diff --git a/packages/quicksand-alpine/quicksand_alpine/docker/.gitignore b/packages/quicksand-alpine/quicksand_alpine/docker/.gitignore
new file mode 100644
index 0000000..3ba6249
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/docker/.gitignore
@@ -0,0 +1 @@
+agent/
diff --git a/packages/quicksand-alpine/quicksand_alpine/docker/Dockerfile b/packages/quicksand-alpine/quicksand_alpine/docker/Dockerfile
new file mode 100644
index 0000000..a8cd2e9
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/docker/Dockerfile
@@ -0,0 +1,110 @@
+# Quicksand Alpine Linux Base Image
+#
+# This Dockerfile creates a minimal Alpine Linux system suitable for
+# running as a quicksand VM guest. Uses a Rust-based agent for minimal size.
+
+# =============================================================================
+# Stage 1: Build the Rust agent
+# =============================================================================
+FROM rust:alpine AS agent-builder
+
+# Install build dependencies
+RUN apk add --no-cache musl-dev
+
+# Set up the build directory
+WORKDIR /build
+
+# Copy agent source
+COPY agent/Cargo.toml agent/Cargo.lock* ./
+COPY agent/src ./src
+
+# Build the agent (release mode, optimized for size)
+RUN cargo build --release && \
+ strip /build/target/release/quicksand-guest-agent
+
+# =============================================================================
+# Stage 2: Create the minimal VM image
+# =============================================================================
+FROM alpine:3.23
+
+# Install kernel and essential packages (minimal set - no Python!)
+RUN apk add --no-cache \
+ # Kernel (includes virtio modules)
+ linux-virt \
+ # Init system
+ openrc \
+ busybox-openrc \
+ # Networking
+ dhcpcd \
+ curl \
+ ca-certificates \
+ # Utilities
+ sudo \
+ # Disk resize tools (for disk_size config option)
+ e2fsprogs-extra \
+ cloud-utils-growpart
+
+# Create quicksand user with passwordless sudo
+RUN adduser -D -s /bin/sh quicksand
+COPY quicksand-sudoers /etc/sudoers.d/quicksand
+RUN chmod 440 /etc/sudoers.d/quicksand
+
+# Ensure 9p kernel modules are loaded at boot
+RUN echo "9p" >> /etc/modules \
+ && echo "9pnet" >> /etc/modules \
+ && echo "9pnet_virtio" >> /etc/modules
+
+# Configure networking with static IP (QEMU slirp always uses 10.0.2.0/24)
+RUN mkdir -p /etc/network
+COPY interfaces /etc/network/interfaces
+
+# Enable essential services at boot
+RUN rc-update add devfs sysinit \
+ && rc-update add dmesg sysinit \
+ && (rc-update add mdev sysinit || true) \
+ && rc-update add hwclock boot \
+ && rc-update add modules boot \
+ && rc-update add sysctl boot \
+ && rc-update add hostname boot \
+ && rc-update add bootmisc boot \
+ && rc-update add networking boot \
+ && (rc-update add syslog boot || true) \
+ && rc-update add mount-ro shutdown \
+ && rc-update add killprocs shutdown \
+ && rc-update add savecache shutdown
+
+# Configure OpenRC for VM environment
+RUN sed -i 's/^#rc_sys=.*/rc_sys="lxc"/' /etc/rc.conf \
+ && sed -i 's/^#rc_controller_cgroups=.*/rc_controller_cgroups="NO"/' /etc/rc.conf \
+ && sed -i 's/^#rc_parallel=.*/rc_parallel="YES"/' /etc/rc.conf
+
+# Static DNS — Docker bind-mounts /etc/resolv.conf during build so we can't
+# write to it directly. Store at a stable path and copy at sysinit (before any
+# boot-level services need networking).
+COPY resolv.conf /etc/resolv.conf.quicksand
+RUN printf '#!/sbin/openrc-run\ncommand="/bin/cp"\ncommand_args="/etc/resolv.conf.quicksand /etc/resolv.conf"\n' \
+ > /etc/init.d/setup-dns && \
+ chmod +x /etc/init.d/setup-dns && \
+ rc-update add setup-dns sysinit
+
+# Set hostname
+COPY hostname /etc/hostname
+
+# Verify /sbin/init exists (created by busybox-openrc)
+RUN test -e /sbin/init || (echo "ERROR: /sbin/init not found" && exit 1)
+
+# Copy the Rust agent binary from builder stage
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/quicksand-guest-agent
+RUN chmod +x /usr/local/bin/quicksand-guest-agent
+
+# Create OpenRC service for the agent (no supervisor needed)
+RUN echo '#!/sbin/openrc-run' > /etc/init.d/quicksand-guest-agent && \
+ echo 'command="/usr/local/bin/quicksand-guest-agent"' >> /etc/init.d/quicksand-guest-agent && \
+ echo 'command_background="yes"' >> /etc/init.d/quicksand-guest-agent && \
+ echo 'pidfile="/run/quicksand-guest-agent.pid"' >> /etc/init.d/quicksand-guest-agent && \
+ echo 'output_log="/var/log/quicksand-guest-agent.log"' >> /etc/init.d/quicksand-guest-agent && \
+ echo 'error_log="/var/log/quicksand-guest-agent.log"' >> /etc/init.d/quicksand-guest-agent && \
+ chmod +x /etc/init.d/quicksand-guest-agent && \
+ rc-update add quicksand-guest-agent boot
+
+CMD ["/sbin/init"]
diff --git a/packages/quicksand-alpine/quicksand_alpine/docker/hostname b/packages/quicksand-alpine/quicksand_alpine/docker/hostname
new file mode 100644
index 0000000..901d7a0
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/docker/hostname
@@ -0,0 +1 @@
+quicksand
diff --git a/packages/quicksand-alpine/quicksand_alpine/docker/interfaces b/packages/quicksand-alpine/quicksand_alpine/docker/interfaces
new file mode 100644
index 0000000..d6b00bc
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/docker/interfaces
@@ -0,0 +1,8 @@
+auto lo
+iface lo inet loopback
+
+auto eth0
+iface eth0 inet static
+ address 10.0.2.15
+ netmask 255.255.255.0
+ gateway 10.0.2.2
diff --git a/packages/quicksand-alpine/quicksand_alpine/docker/quicksand-guest-agent.ini b/packages/quicksand-alpine/quicksand_alpine/docker/quicksand-guest-agent.ini
new file mode 100644
index 0000000..4caca71
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/docker/quicksand-guest-agent.ini
@@ -0,0 +1,6 @@
+[program:quicksand-guest-agent]
+command=/usr/local/bin/quicksand-guest-agent
+autorestart=true
+startretries=9999
+stdout_logfile=/var/log/quicksand-guest-agent.log
+stderr_logfile=/var/log/quicksand-guest-agent.log
diff --git a/packages/quicksand-alpine/quicksand_alpine/docker/quicksand-sudoers b/packages/quicksand-alpine/quicksand_alpine/docker/quicksand-sudoers
new file mode 100644
index 0000000..7aa0a0b
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/docker/quicksand-sudoers
@@ -0,0 +1 @@
+quicksand ALL=(ALL) NOPASSWD:ALL
diff --git a/packages/quicksand-alpine/quicksand_alpine/docker/resolv.conf b/packages/quicksand-alpine/quicksand_alpine/docker/resolv.conf
new file mode 100644
index 0000000..27a94c0
--- /dev/null
+++ b/packages/quicksand-alpine/quicksand_alpine/docker/resolv.conf
@@ -0,0 +1 @@
+nameserver 10.0.2.3
diff --git a/packages/quicksand-alpine/quicksand_alpine/images/.gitkeep b/packages/quicksand-alpine/quicksand_alpine/images/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/packages/quicksand-core/.gitignore b/packages/quicksand-core/.gitignore
new file mode 100644
index 0000000..e69de29
diff --git a/packages/quicksand-core/README.md b/packages/quicksand-core/README.md
new file mode 100644
index 0000000..1370472
--- /dev/null
+++ b/packages/quicksand-core/README.md
@@ -0,0 +1,104 @@
+# Quicksand Core
+
+This package provides the core implementation for the [quicksand](https://github.com/microsoft/quicksand) VM harness.
+
+It includes the abstractions for running VMs that AI agents can interact with, including command execution, file operations, and state checkpointing. Most users should install `quicksand` instead, which includes pre-built images.
+
+## Installation
+
+For most users, install via the main quicksand CLI installer:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+quicksand install ubuntu
+```
+
+For core-only (no bundled images):
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand-core"
+```
+
+## Core Exports
+
+This package exports the core building blocks:
+
+```python
+from quicksand_core import (
+ # Main classes
+ Sandbox,
+ Mount,
+ ExecuteResult,
+ # Save support
+ SaveManifest,
+ # Image resolution
+ ResolvedImage,
+ # Runtime management
+ get_runtime,
+ RuntimeInfo,
+ is_runtime_available,
+ # Accelerator detection
+ get_accelerator,
+ detect_accelerator,
+ AcceleratorStatus,
+ Accelerator,
+ # Platform configuration
+ get_platform_config,
+ PlatformConfig,
+ # Architecture/OS types
+ Architecture,
+ MachineType,
+ OS,
+)
+```
+
+## Usage with Custom Image
+
+```python
+import asyncio
+from quicksand_core import Sandbox
+
+async def main():
+ async with Sandbox(image="your-image-name", memory="1G", cpus=2) as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## Features
+
+- **Real VM isolation**: Hypervisor-level isolation (KVM, HVF, WHPX)
+- **Cross-platform**: Linux, macOS, Windows
+- **Platform abstraction**: Automatic detection of accelerators and machine types
+- **Save and load**: Save VM disk state to a directory and load it on any machine
+- **File sharing**: CIFS mounts via `quicksand-smb` (pure-Python SMB3 server, invoked as a subprocess via QEMU guestfwd)
+- **Performance optimizations**:
+ - microvm machine type (~4x faster boot on Linux x86_64 + KVM)
+ - io_uring disk AIO (~50% lower latency on Linux)
+ - IOThreads for better concurrent disk I/O (all platforms)
+
+## For Most Users
+
+Install `quicksand` with a bundled image for zero-configuration usage:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+quicksand install ubuntu
+```
+
+```python
+import asyncio
+from quicksand import UbuntuSandbox
+
+async def main():
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("ls -la /")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+## License
+
+MIT
diff --git a/packages/quicksand-core/pyproject.toml b/packages/quicksand-core/pyproject.toml
new file mode 100644
index 0000000..7d5617f
--- /dev/null
+++ b/packages/quicksand-core/pyproject.toml
@@ -0,0 +1,22 @@
+[project]
+name = "quicksand-core"
+version = "0.10.3.dev0"
+description = "Core sandbox functionality for the quicksand VM harness."
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "httpx>=0.27,<1.0", # HTTP client for agent communication
+ "pydantic>=2.0", # Structured save manifests
+ "quicksand-smb>=0.3.4.dev0", # Pure-Python SMB3 server for host-guest mounts
+]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_core"]
+
+[tool.uv.sources]
+quicksand-smb = { workspace = true }
diff --git a/packages/quicksand-core/quicksand_core/__init__.py b/packages/quicksand-core/quicksand_core/__init__.py
new file mode 100644
index 0000000..09f2705
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/__init__.py
@@ -0,0 +1,110 @@
+"""
+Quicksand Core provides the VM sandbox implementation that powers the quicksand
+agent harness. Includes save/load, file sharing, and cross-platform support.
+
+For the user-facing package, use `quicksand` instead.
+"""
+
+import logging
+
+# Re-export _types as types for external use (internal code uses _types to avoid shadowing stdlib)
+from . import _types as types
+from ._types import (
+ BaseImageInfo,
+ BootTiming,
+ ImageProvider,
+ Key,
+ Mount,
+ MountHandle,
+ MountType,
+ NetworkMode,
+ QuicksandGuestAgentMethod,
+ PortForward,
+ ResolvedImage,
+ SaveManifest,
+)
+from .host import (
+ OS,
+ Accelerator,
+ AcceleratorStatus,
+ Architecture,
+ BaseOSConfig,
+ DarwinConfig,
+ LinuxConfig,
+ OSConfig,
+ WindowsConfig,
+)
+from .qemu.arch import (
+ ArchitectureConfig,
+ ARM64Config,
+ BaseArchitectureConfig,
+ MachineType,
+ X86_64Config,
+)
+from .qemu.platform import (
+ PlatformConfig,
+ RuntimeInfo,
+ detect_accelerator,
+ get_accelerator,
+ get_machine_type,
+ get_platform_config,
+ get_runtime,
+ is_runtime_available,
+)
+from .sandbox import ExecuteResult, Sandbox, SandboxConfig, SandboxConfigParams
+
+__all__ = [ # noqa: RUF022
+ # Types module alias
+ "types",
+ # Core
+ "Sandbox",
+ "SandboxConfig",
+ "SandboxConfigParams",
+ "Mount",
+ "MountHandle",
+ "MountType",
+ "PortForward",
+ "ExecuteResult",
+ # Boot timing
+ "BootTiming",
+ # Save
+ "SaveManifest",
+ # Runtime management
+ "get_runtime",
+ "RuntimeInfo",
+ "is_runtime_available",
+ "get_machine_type",
+ # Accelerator
+ "get_accelerator",
+ "detect_accelerator",
+ "AcceleratorStatus",
+ # Platform
+ "PlatformConfig",
+ "get_platform_config",
+ # Architecture configs
+ "ArchitectureConfig",
+ "BaseArchitectureConfig",
+ "X86_64Config",
+ "ARM64Config",
+ # OS configs
+ "OSConfig",
+ "BaseOSConfig",
+ "LinuxConfig",
+ "DarwinConfig",
+ "WindowsConfig",
+ # Types
+ "Accelerator",
+ "QuicksandGuestAgentMethod",
+ "Architecture",
+ "BaseImageInfo",
+ "ImageProvider",
+ "ResolvedImage",
+ "MachineType",
+ "Key",
+ "NetworkMode",
+ "OS",
+]
+
+__version__ = "0.1.0"
+
+logging.getLogger("quicksand").addHandler(logging.NullHandler())
diff --git a/packages/quicksand-core/quicksand_core/_tcp_relay.py b/packages/quicksand-core/quicksand_core/_tcp_relay.py
new file mode 100644
index 0000000..73dd4d1
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/_tcp_relay.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""TCP relay for QEMU guestfwd cmd: tunnels.
+
+QEMU spawns a new instance of this script per guest TCP connection (inetd-style).
+stdin/stdout are connected to the guest TCP stream. This script relays
+bidirectionally between that stream and a host-side TCP connection.
+
+Usage (invoked by QEMU, not directly):
+ python3 _tcp_relay.py <host> <port>
+"""
+
+import os
+import socket
+import sys
+import threading
+
+
+def _relay(src_read, dst_write):
+ """Copy data from src_read to dst_write until EOF or error."""
+ try:
+ while True:
+ data = src_read(4096)
+ if not data:
+ break
+ dst_write(data)
+ except (OSError, BrokenPipeError):
+ pass
+
+
+def main():
+ host, port = sys.argv[1], int(sys.argv[2])
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect((host, port))
+
+ stdin_fd = sys.stdin.buffer.fileno()
+ stdout_fd = sys.stdout.buffer.fileno()
+
+ # stdin → socket (guest → host SMB server)
+ t1 = threading.Thread(
+ target=_relay,
+ args=(lambda n: os.read(stdin_fd, n), sock.sendall),
+ daemon=True,
+ )
+ # socket → stdout (host SMB server → guest)
+ t2 = threading.Thread(
+ target=_relay,
+ args=(sock.recv, lambda d: os.write(stdout_fd, d)),
+ daemon=True,
+ )
+ t1.start()
+ t2.start()
+ # Wait for either direction to close (guest disconnect or server disconnect)
+ t1.join()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/quicksand-core/quicksand_core/_types.py b/packages/quicksand-core/quicksand_core/_types.py
new file mode 100644
index 0000000..bd8dd2d
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/_types.py
@@ -0,0 +1,636 @@
+"""Type definitions for quicksand-core.
+
+This module provides strongly-typed enums, constants, and dataclasses for the
+quicksand codebase. Using these types instead of magic strings improves type
+safety, IDE autocomplete, and reduces typo-related bugs.
+
+Note: The guest agent is a standalone Rust binary and cannot share these types.
+The agent API contract is defined in quicksand-image-tools/agent-openapi.yaml.
+
+Platform and Architecture enums are in platform.py.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import StrEnum
+from pathlib import Path
+from typing import Literal, Protocol, Required, TypedDict, runtime_checkable
+
+from pydantic import BaseModel, ConfigDict
+
+from .host import Accelerator
+
+# =============================================================================
+# Mount Specification
+# =============================================================================
+
+
+MountType = Literal["cifs", "9p"]
+"""Mount protocol. ``cifs`` (default) is hot-pluggable via SMB; ``9p`` is a
+virtio-9p device configured at QEMU startup (permanent, no network required)."""
+
+
+@dataclass
+class Mount:
+ """Specification for mounting a host directory into the guest."""
+
+ host: str
+ guest: str
+ readonly: bool = False
+ type: MountType = "cifs"
+
+
+# =============================================================================
+# Network Mode
+# =============================================================================
+
+
+class NetworkMode(StrEnum):
+ """Network access mode for the guest VM.
+
+ Three modes, from most to least restrictive:
+
+ - ``NONE``: No NIC at all. Complete network isolation.
+ - ``MOUNTS_ONLY``: Guest can reach host (mounts work) but not the internet.
+ Uses QEMU restrict=on with guestfwd tunnels. Host-enforced. Default.
+ - ``FULL``: Full internet access. Guest can reach anything.
+
+ Examples:
+ network_mode = NetworkMode.NONE # air-gapped
+ network_mode = NetworkMode.MOUNTS_ONLY # mounts, no internet (default)
+ network_mode = NetworkMode.FULL # internet access
+ """
+
+ NONE = "none"
+ """No network interface — maximum isolation."""
+
+ MOUNTS_ONLY = "mounts_only"
+ """QEMU restrict=on with guestfwd tunnels for host access. Guest cannot
+ reach the internet (host-enforced) but can mount host directories via CIFS
+ over a host-controlled relay tunnel. Supports both boot-time and dynamic
+ mounts."""
+
+ FULL = "full"
+ """QEMU user-mode networking with restrict=off. Full bidirectional access —
+ guest can reach host gateway (10.0.2.2) and the internet. Mounts work
+ directly via the slirp gateway."""
+
+
+# =============================================================================
+# Port Forwarding
+# =============================================================================
+
+
+@dataclass
+class PortForward:
+ """Forward a TCP port from the host into the guest."""
+
+ host: int
+ guest: int
+
+
+# =============================================================================
+# Guest Agent Protocol
+# =============================================================================
+
+
+class Key(StrEnum):
+ """QKeyCode names for use with ``press_key()``.
+
+ Values are the QEMU QKeyCode strings. Pass one or more to
+ ``sandbox.press_key()``::
+
+ sb.press_key(Key.CTRL, Key.C)
+ sb.press_key(Key.RET)
+ sb.press_key(Key.F5)
+ """
+
+ # Letters
+ A = "a"
+ B = "b"
+ C = "c"
+ D = "d"
+ E = "e"
+ F = "f"
+ G = "g"
+ H = "h"
+ I = "i" # noqa: E741
+ J = "j"
+ K = "k"
+ L = "l"
+ M = "m"
+ N = "n"
+ O = "o" # noqa: E741
+ P = "p"
+ Q = "q"
+ R = "r"
+ S = "s"
+ T = "t"
+ U = "u"
+ V = "v"
+ W = "w"
+ X = "x"
+ Y = "y"
+ Z = "z"
+
+ # Digits
+ KEY_0 = "0"
+ KEY_1 = "1"
+ KEY_2 = "2"
+ KEY_3 = "3"
+ KEY_4 = "4"
+ KEY_5 = "5"
+ KEY_6 = "6"
+ KEY_7 = "7"
+ KEY_8 = "8"
+ KEY_9 = "9"
+
+ # Modifiers
+ SHIFT = "shift"
+ SHIFT_R = "shift_r"
+ CTRL = "ctrl"
+ CTRL_R = "ctrl_r"
+ ALT = "alt"
+ ALT_R = "alt_r"
+ META_L = "meta_l"
+ META_R = "meta_r"
+ CAPS_LOCK = "caps_lock"
+ NUM_LOCK = "num_lock"
+ SCROLL_LOCK = "scroll_lock"
+
+ # Whitespace / Navigation
+ RET = "ret"
+ SPC = "spc"
+ TAB = "tab"
+ BACKSPACE = "backspace"
+ ESC = "esc"
+ DELETE = "delete"
+ INSERT = "insert"
+ HOME = "home"
+ END = "end"
+ PGUP = "pgup"
+ PGDN = "pgdn"
+ UP = "up"
+ DOWN = "down"
+ LEFT = "left"
+ RIGHT = "right"
+
+ # Function keys
+ F1 = "f1"
+ F2 = "f2"
+ F3 = "f3"
+ F4 = "f4"
+ F5 = "f5"
+ F6 = "f6"
+ F7 = "f7"
+ F8 = "f8"
+ F9 = "f9"
+ F10 = "f10"
+ F11 = "f11"
+ F12 = "f12"
+
+ # Symbols
+ MINUS = "minus"
+ EQUAL = "equal"
+ BRACKET_LEFT = "bracket_left"
+ BRACKET_RIGHT = "bracket_right"
+ BACKSLASH = "backslash"
+ SEMICOLON = "semicolon"
+ APOSTROPHE = "apostrophe"
+ GRAVE_ACCENT = "grave_accent"
+ COMMA = "comma"
+ DOT = "dot"
+ SLASH = "slash"
+
+ # System
+ PRINT = "print"
+ PAUSE = "pause"
+ MENU = "menu"
+
+ # Numpad
+ KP_0 = "kp_0"
+ KP_1 = "kp_1"
+ KP_2 = "kp_2"
+ KP_3 = "kp_3"
+ KP_4 = "kp_4"
+ KP_5 = "kp_5"
+ KP_6 = "kp_6"
+ KP_7 = "kp_7"
+ KP_8 = "kp_8"
+ KP_9 = "kp_9"
+ KP_ADD = "kp_add"
+ KP_SUBTRACT = "kp_subtract"
+ KP_MULTIPLY = "kp_multiply"
+ KP_DIVIDE = "kp_divide"
+ KP_DECIMAL = "kp_decimal"
+ KP_ENTER = "kp_enter"
+
+
+class QuicksandGuestAgentMethod(StrEnum):
+ """Methods supported by the guest agent protocol.
+
+ These are the JSON-RPC method names used in host-guest communication.
+ """
+
+ EXECUTE = "execute"
+ EXECUTE_STREAM = "execute_stream"
+ PING = "ping"
+ AUTHENTICATE = "authenticate"
+
+
+# =============================================================================
+# File Patterns and Constants
+# =============================================================================
+
+
+class FilePatterns:
+ """Standard file extensions and names used by quicksand."""
+
+ KERNEL_SUFFIX = ".kernel"
+ INITRD_SUFFIX = ".initrd"
+ OVERLAY = "overlay.qcow2"
+ OVERLAYS_DIR = "overlays"
+ MANIFEST = "manifest.json"
+ SAVE_EXT = ".tar.gz"
+ SAVE_EXT_LEGACY = ".tar"
+ CONSOLE_LOG = "console.log"
+
+
+class KernelParams:
+ """Kernel command line parameter names passed to guest VMs."""
+
+ TOKEN = "quicksand_token"
+ PORT = "quicksand_port"
+ # SMB mount parameters (Windows)
+ SMB_PORT = "quicksand_smb_port"
+ SMB_MOUNTS = "quicksand_smb_mounts" # Base64-encoded JSON
+ SMB_GATEWAY = "quicksand_smb_gateway" # Gateway IP for guest to reach host
+
+
+# =============================================================================
+# Network Constants
+# =============================================================================
+
+
+class NetworkConstants:
+ """Network-related constants for VM configuration."""
+
+ LOCALHOST = "127.0.0.1"
+
+ # QEMU user-mode (slirp) network — deterministic, never changes.
+ QEMU_SLIRP_GATEWAY = "10.0.2.2" # Gateway IP
+ QEMU_SLIRP_GUEST_IP = "10.0.2.15" # Guest static IP
+ QEMU_SLIRP_DNS = "10.0.2.3" # Built-in DNS forwarder
+ QEMU_SLIRP_NETMASK = "255.255.255.0"
+
+ GUEST_SMB_PORT = 445 # Standard SMB port for CIFS mounts
+ GUESTFWD_SMB_IP = "10.0.2.100" # Virtual IP for guestfwd SMB tunnel (MOUNTS_ONLY mode)
+ GUESTFWD_SMB_PORT = 445 # SMB port on the guestfwd virtual IP
+
+
+# =============================================================================
+# Timeout Constants
+# =============================================================================
+
+
+class Timeouts:
+ """Timeout values in seconds.
+
+ These constants centralize timeout values that were previously scattered
+ throughout the codebase. Names indicate the context where each is used.
+ """
+
+ # Boot timeouts
+ BOOT_DEFAULT = 60.0
+ BOOT_TCG = 600.0 # Software emulation is 10-20x slower
+ BOOT_WHPX = 120.0 # Windows hypervisor is slower than KVM/HVF
+
+ # Guest agent communication
+ GUEST_AGENT_REQUEST = 30.0 # Default timeout for guest agent requests
+ GUEST_AGENT_HTTP = 5.0 # HTTP client timeout
+ GUEST_AGENT_CONNECT = 2.0 # HTTP connection timeout
+
+ # File operations
+ SMB_WAIT = 30.0 # Wait for SMB mount to complete
+ MOUNT_OPERATION = 10.0 # Filesystem mount operations
+
+ # Process management
+ PROCESS_TERMINATE = 5.0 # Graceful process termination
+ GRACEFUL_SHUTDOWN = 10.0 # Graceful VM shutdown
+
+
+# =============================================================================
+# Image Providers (entry point objects)
+# =============================================================================
+
+
+@dataclass
+class BaseImageInfo:
+ """Build-time metadata for quicksand-image-tools. Not used at runtime."""
+
+ name: str
+ docker_dir: Path
+ version: str
+
+
+@runtime_checkable
+class ImageProvider(Protocol):
+ """Protocol for image packages registered as ``quicksand.images`` entry points.
+
+ Image packages export a module-level ``ImageProvider`` instance. The resolver
+ calls :meth:`resolve` and gets back a ``ResolvedImage`` with everything
+ needed to boot.
+ """
+
+ name: str
+ type: Literal["base", "overlay"]
+ images_dir: Path
+
+ def resolve(self, arch: str | None = None) -> ResolvedImage:
+ """Resolve to concrete image paths (and overlay chain if applicable).
+
+ Args:
+ arch: Image architecture (``"amd64"`` or ``"arm64"``).
+ Defaults to the host architecture.
+ """
+ ...
+
+
+# =============================================================================
+# I/O Constants
+# =============================================================================
+
+
+class EnvironmentVariables:
+ """Environment variable names used by quicksand."""
+
+ QEMU_MODULE_DIR = "QEMU_MODULE_DIR"
+
+
+# =============================================================================
+# Guest Commands
+# =============================================================================
+
+
+class GuestCommands:
+ """Shell commands executed inside the guest VM."""
+
+ SHELL = "/bin/sh"
+ SYNC = "sync"
+ FSTRIM = "fstrim -av 2>/dev/null || true"
+ DETECT_DISK_LAYOUT = "test -b /dev/vda1 && echo partitioned || echo whole"
+ GROWPART = "growpart /dev/vda 1 2>&1 || true"
+ RESIZE_PARTITION = "resize2fs /dev/vda1 2>&1 || xfs_growfs / 2>&1 || true"
+ RESIZE_WHOLE_DISK = "resize2fs /dev/vda 2>&1 || xfs_growfs / 2>&1 || true"
+
+
+# =============================================================================
+# Execute Protocol Types
+# =============================================================================
+
+
+@dataclass
+class ExecuteParams:
+ """Parameters for an execute request to the guest agent."""
+
+ command: str
+ timeout: float
+ shell: str
+ cwd: str | None = None
+ exclusive: bool = False
+
+
+@dataclass
+class ExecuteResponseResult:
+ """Result body returned by the guest agent execute method."""
+
+ stdout: str
+ stderr: str
+ exit_code: int
+
+
+@dataclass
+class AgentErrorBody:
+ """Error body returned by the guest agent on failure."""
+
+ message: str
+ code: int = -1
+
+
+@dataclass
+class ExecuteResult:
+ """Result of executing a command in the sandbox."""
+
+ stdout: str
+ stderr: str
+ exit_code: int
+
+
+# =============================================================================
+# Mount Options
+# =============================================================================
+
+
+@dataclass(frozen=True)
+class MountHandle:
+ """Opaque handle returned by Sandbox.mount()."""
+
+ host: str
+ guest: str
+ readonly: bool
+ _share_name: str # internal SMB share name
+
+
+class MountOptions:
+ """Constants and helpers for host-guest filesystem mounts."""
+
+ STABILIZATION_DELAY = 2.0 # seconds to wait for guest to stabilize after boot
+ MAX_RETRIES = 3
+ RETRY_DELAY = 1.0 # seconds between mount retries
+
+ @staticmethod
+ def cifs_opts(username: str, password: str) -> str:
+ """Return CIFS mount options string.
+
+ Uses sec=none for guest/anonymous access, sec=ntlmssp for authenticated.
+ """
+ sec = "none" if not password else "ntlmssp"
+ return f"username={username},password={password},sec={sec},vers=3.0"
+
+
+# =============================================================================
+# Resolution Outputs (frozen, immutable after start)
+# =============================================================================
+
+
+@dataclass(frozen=True)
+class ResolvedImage:
+ """The resolved VM disk — produced by ImageResolver, consumed by lifecycle.
+
+ ``name`` is the canonical image name (e.g. ``"ubuntu"``).
+ ``chain`` is the full disk chain from base image to topmost overlay,
+ where ``chain[0]`` is the root base qcow2 (no backing file) and
+ ``chain[1:]`` are overlay layers in bottom-to-top order.
+ ``guest_arch`` is set when a cross-architecture save is loaded — the
+ resolver detected that the save was created on a different architecture
+ and the sandbox should force TCG emulation.
+ """
+
+ name: str
+ chain: list[Path]
+ kernel: Path | None = None
+ initrd: Path | None = None
+ guest_arch: str | None = None
+
+
+@dataclass(frozen=True)
+class ResolvedAccelerator:
+ """Resolved acceleration — produced by accelerator detection during start."""
+
+ accel: Accelerator
+ nested_virt: bool = False
+ boot_timeout: float = Timeouts.BOOT_DEFAULT
+
+
+@dataclass
+class BootTiming:
+ """Phase-level timing for a sandbox boot sequence."""
+
+ resolve_image_s: float = 0.0
+ detect_accelerator_s: float = 0.0
+ load_runtime_s: float = 0.0
+ setup_disk_s: float = 0.0
+ launch_process_s: float = 0.0
+ connect_agent_s: float = 0.0
+ connect_qmp_s: float = 0.0
+ post_boot_s: float = 0.0
+
+ # Sub-breakdown of connect_agent_s, parsed from console log.
+ # kernel_boot_s: time from QEMU launch to init system starting.
+ # init_system_s: time spent in init (services, DHCP, etc.).
+ # agent_startup_s: time from agent start to successful HTTP connection.
+ kernel_boot_s: float | None = None
+ init_system_s: float | None = None
+ agent_startup_s: float | None = None
+ console_log: str | None = None
+
+ @property
+ def total_s(self) -> float:
+ return (
+ self.resolve_image_s
+ + self.detect_accelerator_s
+ + self.load_runtime_s
+ + self.setup_disk_s
+ + self.launch_process_s
+ + self.connect_agent_s
+ + self.connect_qmp_s
+ + self.post_boot_s
+ )
+
+ def __str__(self) -> str:
+ phases: list[tuple[str, float]] = [
+ ("resolve_image", self.resolve_image_s),
+ ("detect_accelerator", self.detect_accelerator_s),
+ ("load_runtime", self.load_runtime_s),
+ ("setup_disk", self.setup_disk_s),
+ ("launch_process", self.launch_process_s),
+ ("connect_agent", self.connect_agent_s),
+ ]
+ if self.kernel_boot_s is not None:
+ phases.append((" ├ kernel_boot", self.kernel_boot_s))
+ if self.init_system_s is not None:
+ phases.append((" ├ init_system", self.init_system_s))
+ if self.agent_startup_s is not None:
+ phases.append((" └ agent_startup", self.agent_startup_s))
+ phases.extend(
+ [
+ ("connect_qmp", self.connect_qmp_s),
+ ("post_boot", self.post_boot_s),
+ ]
+ )
+ lines = []
+ for name, duration in phases:
+ pct = (duration / self.total_s * 100) if self.total_s > 0 else 0
+ bar_len = int(min(pct / 100, 1.0) * 20)
+ bar = "#" * bar_len + "-" * (20 - bar_len)
+ lines.append(f" {name:<22} {bar} {duration:>7.3f}s ({pct:>5.1f}%)")
+ lines.append(f" {'total':<22} {'':>20} {self.total_s:>7.3f}s")
+ return "\n".join(lines)
+
+
+# =============================================================================
+# Sandbox Configuration (frozen user input)
+# =============================================================================
+
+
+class SandboxConfig(BaseModel):
+ """Configuration for a sandbox VM.
+
+ ``image`` is a string resolved at start time: a base image name
+ (``"ubuntu"``), a save name (``"my-save"``), or a filesystem path.
+
+ Frozen after construction — never mutated.
+ """
+
+ model_config = ConfigDict(frozen=True, extra="ignore")
+
+ image: str
+ arch: str | None = None
+ memory: str = "512M"
+ cpus: int = 1
+ mounts: list[Mount] = []
+ port_forwards: list[PortForward] = []
+ network_mode: NetworkMode = NetworkMode.MOUNTS_ONLY
+ extra_qemu_args: list[str] = []
+ boot_timeout: float = Timeouts.BOOT_DEFAULT
+ accel: Accelerator | Literal["auto"] | None = "auto"
+ disk_size: str | None = None
+ enable_display: bool = False
+
+
+class SandboxConfigParams(TypedDict, total=False):
+ """TypedDict mirror of :class:`SandboxConfig` for ``Unpack``-based kwargs.
+
+ Kept in sync by the module-level assertion below.
+ """
+
+ image: Required[str]
+ arch: str | None
+ memory: str
+ cpus: int
+ mounts: list[Mount]
+ port_forwards: list[tuple[int, int]]
+ network_mode: NetworkMode
+ extra_qemu_args: list[str]
+ boot_timeout: float
+ accel: Accelerator | Literal["auto"] | None
+ disk_size: str | None
+ enable_display: bool
+
+
+_td_keys = set(SandboxConfigParams.__annotations__)
+_bm_keys = set(SandboxConfig.model_fields)
+assert _td_keys == _bm_keys, (
+ f"SandboxConfigParams / SandboxConfig out of sync — "
+ f"only in TypedDict: {_td_keys - _bm_keys}, "
+ f"only in BaseModel: {_bm_keys - _td_keys}"
+)
+
+
+# =============================================================================
+# Save Manifest (persistence format)
+# =============================================================================
+
+
+class SaveManifest(BaseModel):
+ """Manifest stored in a save directory's ``manifest.json``.
+
+ ``config`` is a ``SandboxConfig`` with ``image`` set to the canonical
+ base image name and ``mounts`` cleared. The save directory's
+ ``overlays/`` subdirectory is the canonical source for the overlay chain.
+ """
+
+ version: int
+ config: SandboxConfig
+ arch: str | None = None
diff --git a/packages/quicksand-core/quicksand_core/host/__init__.py b/packages/quicksand-core/quicksand_core/host/__init__.py
new file mode 100644
index 0000000..a4c11bc
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/host/__init__.py
@@ -0,0 +1,35 @@
+"""Platform detection and configuration.
+
+This package provides host-specific configuration including:
+- Architecture detection (x86_64, ARM64)
+- OS detection (Linux, macOS, Windows)
+- Accelerator detection (KVM, HVF, WHPX)
+"""
+
+from . import arch
+from . import os_ as os
+from .arch import Architecture
+from .os_ import (
+ OS,
+ Accelerator,
+ AcceleratorStatus,
+ BaseOSConfig,
+ DarwinConfig,
+ LinuxConfig,
+ OSConfig,
+ WindowsConfig,
+)
+
+__all__ = [
+ "OS",
+ "Accelerator",
+ "AcceleratorStatus",
+ "Architecture",
+ "BaseOSConfig",
+ "DarwinConfig",
+ "LinuxConfig",
+ "OSConfig",
+ "WindowsConfig",
+ "arch",
+ "os",
+]
diff --git a/packages/quicksand-core/quicksand_core/host/arch.py b/packages/quicksand-core/quicksand_core/host/arch.py
new file mode 100644
index 0000000..d8b0db7
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/host/arch.py
@@ -0,0 +1,109 @@
+"""Host CPU architecture detection."""
+
+from __future__ import annotations
+
+import platform as _platform
+from enum import StrEnum
+
+# All known aliases, mapped to canonical Architecture values.
+_X86_NAMES = {"x86_64", "amd64", "x64"}
+_ARM_NAMES = {"arm64", "aarch64"}
+
+
+class Architecture(StrEnum):
+ """Normalized CPU architectures.
+
+ Canonical values are ``"x86_64"`` and ``"arm64"``.
+ Use :meth:`from_str` to normalize any alias (amd64, x64, aarch64, etc.).
+ Use :attr:`image_arch` to get the name used in image file conventions (amd64/arm64).
+ """
+
+ X86_64 = "x86_64"
+ ARM64 = "arm64"
+
+ @classmethod
+ def from_str(cls, value: str) -> Architecture:
+ """Normalize any architecture alias to a canonical Architecture.
+
+ Accepts: x86_64, amd64, x64, arm64, aarch64 (case-insensitive).
+
+ Raises:
+ ValueError: If the value is not a recognized architecture.
+ """
+ v = value.lower()
+ if v in _X86_NAMES:
+ return cls.X86_64
+ if v in _ARM_NAMES:
+ return cls.ARM64
+ raise ValueError(
+ f"Unknown architecture: {value!r}. "
+ f"Expected one of: {', '.join(sorted(_X86_NAMES | _ARM_NAMES))}"
+ )
+
+ @property
+ def image_arch(self) -> str:
+ """Architecture string used in image file naming (``amd64`` or ``arm64``)."""
+ return "amd64" if self == Architecture.X86_64 else "arm64"
+
+
+def _detect_native_windows_arch() -> str | None:
+ """Read the native CPU architecture from the Windows registry.
+
+ On Windows ARM64, Python may run as x86_64 through transparent emulation,
+ causing ``platform.machine()`` to return ``"AMD64"``. The registry key
+ ``HKLM\\...\\Session Manager\\Environment\\PROCESSOR_ARCHITECTURE``
+ always reflects the true hardware architecture regardless of emulation.
+
+ Returns the registry value (e.g. ``"ARM64"``, ``"AMD64"``), or ``None``
+ if not on Windows or the key cannot be read.
+ """
+ if _platform.system() != "Windows":
+ return None
+ try:
+ import winreg # type: ignore[import-not-found] # Windows-only module
+
+ key = winreg.OpenKey( # ty:ignore[unresolved-attribute]
+ winreg.HKEY_LOCAL_MACHINE, # ty:ignore[unresolved-attribute]
+ r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
+ )
+ value, _ = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE") # ty:ignore[unresolved-attribute]
+ winreg.CloseKey(key) # ty:ignore[unresolved-attribute]
+ return value
+ except Exception:
+ return None
+
+
+def _detect_architecture() -> Architecture:
+ """Detect and normalize the host CPU architecture.
+
+ On Windows, reads the native architecture from the registry to see
+ through x86_64-on-ARM64 transparent emulation.
+ """
+ native = _detect_native_windows_arch()
+ machine = native if native else _platform.machine()
+ machine = machine.lower()
+ try:
+ return Architecture.from_str(machine)
+ except ValueError:
+ raise RuntimeError(
+ f"Unsupported CPU architecture: {machine}\n"
+ f"Quicksand supports: x86_64/amd64, arm64/aarch64"
+ ) from None
+
+
+def _is_emulated() -> bool:
+ """Return True when Python runs under architecture emulation.
+
+ On Windows ARM64, Python typically runs as x86_64 via transparent
+ emulation. The native hardware is ARM64 but ``sysconfig`` reports
+ ``win-amd64``. This detects that mismatch.
+ """
+ import sysconfig
+
+ native = _detect_architecture()
+ plat = sysconfig.get_platform() # e.g. "win-amd64", "linux-x86_64"
+ try:
+ interp = Architecture.from_str(plat.rsplit("-", 1)[-1])
+ except (ValueError, IndexError):
+ return False
+ return native != interp
diff --git a/packages/quicksand-core/quicksand_core/host/os_.py b/packages/quicksand-core/quicksand_core/host/os_.py
new file mode 100644
index 0000000..2361338
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/host/os_.py
@@ -0,0 +1,433 @@
+"""OS-specific configuration using subclass pattern.
+
+This module provides OS-specific values (accelerator, paths, kernel params, etc.)
+through a class hierarchy. Each OS has its own subclass.
+
+OS-specific features:
+- Linux: KVM acceleration, io_uring disk AIO, microvm support
+- macOS: HVF acceleration
+- Windows: WHPX acceleration, noapic kernel param
+"""
+
+from __future__ import annotations
+
+import os
+import platform as _platform
+import subprocess
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from enum import StrEnum
+from pathlib import Path
+
+
+class OS(StrEnum):
+ """Supported host operating systems."""
+
+ DARWIN = "darwin"
+ LINUX = "linux"
+ WINDOWS = "windows"
+
+
+class Accelerator(StrEnum):
+ """Hardware virtualization accelerators."""
+
+ KVM = "kvm"
+ HVF = "hvf"
+ WHPX = "whpx"
+ TCG = "tcg"
+
+
+@dataclass
+class AcceleratorStatus:
+ """Result of accelerator detection with detailed status."""
+
+ available: Accelerator | None
+ fallback: Accelerator
+ error: str | None = None
+ hint: str | None = None
+ nested: bool = False # True if running inside a hypervisor (WHPX needs kernel-irqchip=off)
+
+ @property
+ def accelerator(self) -> Accelerator:
+ """Get the accelerator to use (available or fallback)."""
+ return self.available if self.available else self.fallback
+
+
+class BaseOSConfig(ABC):
+ """Abstract base class for OS-specific configuration.
+
+ Subclasses provide concrete values for each supported OS.
+ Use OSConfig() to auto-detect the current OS.
+ """
+
+ @property
+ @abstractmethod
+ def os_type(self) -> OS:
+ """The OS enum value."""
+ ...
+
+ @property
+ @abstractmethod
+ def binary_extension(self) -> str:
+ """Extension for executable binaries (e.g., '.exe' or '')."""
+ ...
+
+ @property
+ @abstractmethod
+ def extra_kernel_params(self) -> list[str]:
+ """Extra kernel parameters needed for this OS."""
+ ...
+
+ @property
+ @abstractmethod
+ def default_accelerator(self) -> Accelerator:
+ """The default hardware accelerator for this OS."""
+ ...
+
+ @property
+ @abstractmethod
+ def kvm_device(self) -> Path | None:
+ """Path to KVM device, or None if not applicable."""
+ ...
+
+ @property
+ @abstractmethod
+ def cache_dir(self) -> Path:
+ """Default cache directory for this OS."""
+ ...
+
+ @property
+ @abstractmethod
+ def disk_aio(self) -> str | None:
+ """Disk AIO backend for this OS.
+
+ Returns:
+ 'io_uring' for Linux (best performance), None for others.
+ When None, QEMU uses its default (threads-based AIO).
+ """
+ ...
+
+ @property
+ @abstractmethod
+ def supports_microvm(self) -> bool:
+ """Whether this OS supports the microvm machine type.
+
+ microvm provides ~4x faster boot but requires KVM (Linux only).
+ """
+ ...
+
+ @abstractmethod
+ def detect_accelerator(self) -> AcceleratorStatus:
+ """Detect if hardware acceleration is available."""
+ ...
+
+ @property
+ def images_dir(self) -> Path:
+ """Directory for cached VM images."""
+ return self.cache_dir / "images"
+
+
+class LinuxConfig(BaseOSConfig):
+ """Configuration for Linux."""
+
+ @property
+ def os_type(self) -> OS:
+ return OS.LINUX
+
+ @property
+ def binary_extension(self) -> str:
+ return ""
+
+ @property
+ def extra_kernel_params(self) -> list[str]:
+ return []
+
+ @property
+ def default_accelerator(self) -> Accelerator:
+ return Accelerator.KVM
+
+ @property
+ def kvm_device(self) -> Path | None:
+ return Path("/dev/kvm")
+
+ @property
+ def cache_dir(self) -> Path:
+ xdg = os.environ.get("XDG_CACHE_HOME")
+ if xdg:
+ return Path(xdg) / "quicksand"
+ return Path.home() / ".cache" / "quicksand"
+
+ @property
+ def disk_aio(self) -> str | None:
+ # io_uring provides ~50% lower disk latency on Linux (kernel 5.8+)
+ return "io_uring"
+
+ @property
+ def supports_microvm(self) -> bool:
+ # microvm is a Linux-only machine type that provides ~4x faster boot
+ return True
+
+ def detect_accelerator(self) -> AcceleratorStatus:
+ """Detect KVM on Linux."""
+ kvm_path = self.kvm_device
+
+ if not kvm_path or not kvm_path.exists():
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error="/dev/kvm does not exist",
+ hint=(
+ "KVM may not be available if:\n"
+ " - Running in a VM without nested virtualization\n"
+ " - KVM kernel module not loaded: sudo modprobe kvm\n"
+ " - CPU doesn't support virtualization (check BIOS settings)"
+ ),
+ )
+
+ if not os.access(kvm_path, os.R_OK | os.W_OK):
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error=f"Permission denied: {kvm_path}",
+ hint="Add your user to the kvm group: sudo usermod -aG kvm $USER",
+ )
+
+ return AcceleratorStatus(available=Accelerator.KVM, fallback=Accelerator.KVM)
+
+
+class DarwinConfig(BaseOSConfig):
+ """Configuration for macOS (Darwin)."""
+
+ @property
+ def os_type(self) -> OS:
+ return OS.DARWIN
+
+ @property
+ def binary_extension(self) -> str:
+ return ""
+
+ @property
+ def extra_kernel_params(self) -> list[str]:
+ return []
+
+ @property
+ def default_accelerator(self) -> Accelerator:
+ return Accelerator.HVF
+
+ @property
+ def kvm_device(self) -> Path | None:
+ return None
+
+ @property
+ def cache_dir(self) -> Path:
+ return Path.home() / ".cache" / "quicksand"
+
+ @property
+ def disk_aio(self) -> str | None:
+ # io_uring is Linux-only; macOS uses QEMU's default (threads)
+ return None
+
+ @property
+ def supports_microvm(self) -> bool:
+ # microvm requires KVM (Linux only)
+ return False
+
+ def detect_accelerator(self) -> AcceleratorStatus:
+ """Detect Hypervisor.framework on macOS."""
+ try:
+ result = subprocess.run(
+ ["sysctl", "-n", "kern.hv_support"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if result.returncode == 0 and result.stdout.strip() == "1":
+ return AcceleratorStatus(available=Accelerator.HVF, fallback=Accelerator.HVF)
+
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error="Hypervisor.framework not supported",
+ hint="HVF requires macOS 10.10+ on Intel or Apple Silicon",
+ )
+
+ except subprocess.TimeoutExpired:
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error="sysctl timed out checking for HVF support",
+ )
+ except FileNotFoundError:
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error="sysctl command not found",
+ )
+
+
+class WindowsConfig(BaseOSConfig):
+ """Configuration for Windows."""
+
+ @property
+ def os_type(self) -> OS:
+ return OS.WINDOWS
+
+ @property
+ def binary_extension(self) -> str:
+ return ".exe"
+
+ @property
+ def extra_kernel_params(self) -> list[str]:
+ # WHPX IO-APIC workaround
+ return ["noapic"]
+
+ @property
+ def default_accelerator(self) -> Accelerator:
+ return Accelerator.WHPX
+
+ @property
+ def kvm_device(self) -> Path | None:
+ return None
+
+ @property
+ def cache_dir(self) -> Path:
+ local_app_data = os.environ.get("LOCALAPPDATA")
+ if local_app_data:
+ return Path(local_app_data) / "quicksand"
+ return Path.home() / "AppData" / "Local" / "quicksand"
+
+ @property
+ def disk_aio(self) -> str | None:
+ # io_uring is Linux-only; Windows uses QEMU's default
+ return None
+
+ @property
+ def supports_microvm(self) -> bool:
+ # microvm requires KVM (Linux only)
+ return False
+
+ def detect_accelerator(self) -> AcceleratorStatus:
+ """Detect Windows Hypervisor Platform."""
+ try:
+ # Check both WHPX availability and whether we're inside a hypervisor
+ result = subprocess.run(
+ [
+ "powershell",
+ "-Command",
+ "(Get-WmiObject Win32_ComputerSystem).HypervisorPresent;"
+ "(Get-WmiObject Win32_BaseBoard).Manufacturer",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0 and "True" in result.stdout:
+ # Nested if baseboard is "Microsoft Corporation" (Azure/Hyper-V VM)
+ nested = "Microsoft Corporation" in result.stdout
+ return AcceleratorStatus(
+ available=Accelerator.WHPX,
+ fallback=Accelerator.WHPX,
+ nested=nested,
+ )
+
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error="Windows Hypervisor Platform not enabled",
+ hint=(
+ "Enable WHPX in Windows Features:\n"
+ " 1. Open 'Turn Windows features on or off'\n"
+ " 2. Enable 'Windows Hypervisor Platform'\n"
+ " 3. Restart your computer"
+ ),
+ )
+
+ except subprocess.TimeoutExpired:
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error="PowerShell timed out checking for WHPX",
+ )
+ except FileNotFoundError:
+ return AcceleratorStatus(
+ available=None,
+ fallback=Accelerator.TCG,
+ error="PowerShell not found",
+ )
+
+
+def _detect_os() -> OS:
+ """Detect the current operating system."""
+ system = _platform.system().lower()
+ mapping = {
+ "darwin": OS.DARWIN,
+ "linux": OS.LINUX,
+ "windows": OS.WINDOWS,
+ }
+ if system not in mapping:
+ raise RuntimeError(
+ f"Unsupported operating system: {system}\n"
+ f"Quicksand supports: {', '.join(p.value for p in OS)}"
+ )
+ return mapping[system]
+
+
+class OSConfig(BaseOSConfig):
+ """Auto-detecting OS configuration.
+
+ Instantiating this class returns the appropriate subclass
+ for the current operating system.
+
+ Example:
+ config = OSConfig() # Returns LinuxConfig, DarwinConfig, or WindowsConfig
+ print(config.os_type) # OS.LINUX on Linux
+ """
+
+ def __new__(cls) -> BaseOSConfig:
+ if cls is OSConfig:
+ os_type = _detect_os()
+ if os_type == OS.LINUX:
+ return object.__new__(LinuxConfig)
+ elif os_type == OS.DARWIN:
+ return object.__new__(DarwinConfig)
+ elif os_type == OS.WINDOWS:
+ return object.__new__(WindowsConfig)
+ raise RuntimeError(f"Unsupported OS: {os_type}")
+ return object.__new__(cls)
+
+ # These are required to satisfy the ABC, but will never be called
+ # because __new__ returns a different class instance
+ @property
+ def os_type(self) -> OS:
+ raise NotImplementedError
+
+ @property
+ def binary_extension(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def extra_kernel_params(self) -> list[str]:
+ raise NotImplementedError
+
+ @property
+ def default_accelerator(self) -> Accelerator:
+ raise NotImplementedError
+
+ @property
+ def kvm_device(self) -> Path | None:
+ raise NotImplementedError
+
+ @property
+ def cache_dir(self) -> Path:
+ raise NotImplementedError
+
+ @property
+ def disk_aio(self) -> str | None:
+ raise NotImplementedError
+
+ @property
+ def supports_microvm(self) -> bool:
+ raise NotImplementedError
+
+ def detect_accelerator(self) -> AcceleratorStatus:
+ raise NotImplementedError
diff --git a/packages/quicksand-core/quicksand_core/host/quicksand_guest_agent_client.py b/packages/quicksand-core/quicksand_core/host/quicksand_guest_agent_client.py
new file mode 100644
index 0000000..fa17c9e
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/host/quicksand_guest_agent_client.py
@@ -0,0 +1,290 @@
+"""Async HTTP client for quicksand guest agent communication."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import random
+from collections.abc import Callable
+from typing import Any, TypeVar
+
+import httpx
+
+from .._types import NetworkConstants, QuicksandGuestAgentMethod, Timeouts
+
+logger = logging.getLogger("quicksand.quicksand_guest_agent")
+
+T = TypeVar("T")
+
+
+async def _retry_on_transient_error(
+ func: Callable[[], Any],
+ *,
+ max_retries: int = 3,
+ base_delay: float = 0.1,
+ max_delay: float = 2.0,
+) -> Any:
+ """Retry an async function on transient transport errors with exponential backoff.
+
+ Retries on: ConnectionResetError, BrokenPipeError, httpx.TransportError
+ Does NOT retry on: httpx.HTTPStatusError (4xx/5xx responses)
+ """
+ last_exception: Exception | None = None
+
+ for attempt in range(max_retries + 1):
+ try:
+ return await func()
+ except (ConnectionResetError, BrokenPipeError) as e:
+ last_exception = e
+ except httpx.TransportError as e:
+ last_exception = e
+ except httpx.HTTPStatusError:
+ raise
+
+ if attempt < max_retries:
+ delay = min(base_delay * (2**attempt) * (0.5 + random.random()), max_delay)
+ logger.debug(
+ f"Transient error on attempt {attempt + 1}/{max_retries + 1}, "
+ f"retrying in {delay:.2f}s: {last_exception}"
+ )
+ await asyncio.sleep(delay)
+
+ assert last_exception is not None
+ raise last_exception
+
+
+class QuicksandGuestAgentClient:
+ """Async HTTP client for communicating with the quicksand guest agent.
+
+ This class handles all HTTP communication with the guest agent,
+ including connection, authentication, and request/response handling.
+ """
+
+ def __init__(self, port: int, token: str):
+ """Initialize the quicksand guest agent client.
+
+ Args:
+ port: The port number where the agent is listening.
+ token: Authentication token for the agent.
+ """
+ self._port = port
+ self._token = token
+ self._client: httpx.AsyncClient | None = None
+ # Lazy-init: asyncio.Lock() binds to the current event loop at creation
+ # time, so we must not create it in __init__ (which may run outside any loop).
+ self._lock: asyncio.Lock | None = None
+
+ @property
+ def is_connected(self) -> bool:
+ """Check if the client is connected to the agent."""
+ return self._client is not None
+
+ async def connect(
+ self,
+ timeout: float = Timeouts.BOOT_DEFAULT,
+ process_check: Callable[[], tuple[bool, str]] | None = None,
+ ) -> None:
+ """Connect to the agent and authenticate.
+
+ Args:
+ timeout: Maximum time to wait for connection.
+ process_check: Optional callback that returns (is_running, error_info).
+ Used to detect if the VM process has exited.
+
+ Raises:
+ TimeoutError: If connection times out.
+ RuntimeError: If authentication fails or VM exits.
+ """
+ loop = asyncio.get_event_loop()
+ deadline = loop.time() + timeout
+ base_url = f"http://{NetworkConstants.LOCALHOST}:{self._port}"
+
+ logger.debug(f"Connecting to quicksand guest agent: port={self._port}, timeout={timeout}s")
+
+ self._client = httpx.AsyncClient(
+ base_url=base_url,
+ timeout=httpx.Timeout(Timeouts.GUEST_AGENT_HTTP, connect=Timeouts.GUEST_AGENT_CONNECT),
+ headers={"Authorization": f"Bearer {self._token}"},
+ )
+
+ last_error: Exception | None = None
+ attempt = 0
+
+ while loop.time() < deadline:
+ attempt += 1
+
+ # Check if VM process has exited
+ if process_check:
+ is_running, error_info = process_check()
+ if not is_running:
+ await self._client.aclose()
+ self._client = None
+ raise RuntimeError(error_info)
+
+ try:
+ logger.debug(f"Connection attempt {attempt} to {base_url}")
+ response = await self._client.post(
+ "/authenticate",
+ json={"token": self._token},
+ )
+ if response.status_code == 200:
+ data = response.json()
+ if data.get("authenticated"):
+ logger.debug("Quicksand guest agent authentication successful")
+ return # Success!
+ raise RuntimeError("Authentication rejected by quicksand guest agent")
+ raise RuntimeError(f"Authentication failed: HTTP {response.status_code}")
+
+ except (httpx.TransportError, RuntimeError) as e:
+ logger.debug(f"Connection attempt {attempt} failed: {e}")
+ last_error = e
+ await asyncio.sleep(0.5)
+
+ # Timeout
+ if self._client:
+ await self._client.aclose()
+ self._client = None
+ raise TimeoutError(
+ f"Could not connect to quicksand guest agent within {timeout}s. "
+ f"Port: {self._port}, Last error: {last_error}"
+ )
+
+ async def close(self) -> None:
+ """Close the HTTP client connection."""
+ if self._client:
+ try:
+ await self._client.aclose()
+ except Exception as e:
+ logger.warning(f"Failed to close HTTP client: {e}")
+ finally:
+ self._client = None
+
+ async def send_request(
+ self,
+ method: QuicksandGuestAgentMethod,
+ params: dict[str, Any],
+ timeout: float = Timeouts.GUEST_AGENT_REQUEST,
+ ) -> dict[str, Any]:
+ """Send a request to the quicksand guest agent.
+
+ Args:
+ method: The guest agent method to call.
+ params: Parameters for the method.
+ timeout: Request timeout in seconds.
+
+ Returns:
+ Dict with either "result" or "error" key.
+ """
+ if self._client is None:
+ raise RuntimeError("Not connected to quicksand guest agent")
+
+ if self._lock is None:
+ self._lock = asyncio.Lock()
+ async with self._lock:
+ endpoint_map = {
+ QuicksandGuestAgentMethod.EXECUTE: "/execute",
+ QuicksandGuestAgentMethod.PING: "/ping",
+ }
+
+ endpoint = endpoint_map.get(method)
+ if endpoint is None:
+ return {"error": {"message": f"Unknown method: {method}"}}
+
+ client = self._client
+
+ async def do_request() -> httpx.Response:
+ if method == QuicksandGuestAgentMethod.PING:
+ return await client.get(endpoint, timeout=timeout)
+ else:
+ return await client.post(endpoint, json=params, timeout=timeout)
+
+ try:
+ response = await _retry_on_transient_error(do_request, max_retries=3)
+
+ if response.status_code == 401:
+ return {"error": {"message": "Authentication failed"}}
+
+ if response.status_code != 200:
+ return {"error": {"message": f"HTTP {response.status_code}"}}
+
+ return {"result": response.json()}
+
+ except httpx.TransportError as e:
+ return {"error": {"message": f"Connection error after retries: {e}"}}
+ except httpx.HTTPStatusError as e:
+ return {"error": {"message": str(e)}}
+
+ async def send_stream_request(
+ self,
+ params: dict[str, Any],
+ timeout: float,
+ on_stdout: Callable[[str], None] | None = None,
+ on_stderr: Callable[[str], None] | None = None,
+ ) -> dict[str, Any]:
+ """POST to /execute_stream and parse SSE events, invoking callbacks.
+
+ Accumulates full stdout/stderr and returns them along with exit_code
+ in the same shape as send_request(): {"result": {...}} or {"error": {...}}.
+ """
+ if self._client is None:
+ raise RuntimeError("Not connected to quicksand guest agent")
+
+ if self._lock is None:
+ self._lock = asyncio.Lock()
+ async with self._lock:
+ stdout_parts: list[str] = []
+ stderr_parts: list[str] = []
+ exit_code = -1
+
+ try:
+ async with self._client.stream(
+ "POST",
+ "/execute_stream",
+ json=params,
+ timeout=httpx.Timeout(timeout, connect=Timeouts.GUEST_AGENT_CONNECT),
+ ) as response:
+ if response.status_code == 401:
+ return {"error": {"message": "Authentication failed"}}
+ if response.status_code != 200:
+ return {"error": {"message": f"HTTP {response.status_code}"}}
+
+ async for line in response.aiter_lines():
+ if not line.startswith("data: "):
+ continue
+ payload = line[6:] # strip "data: " prefix
+ try:
+ event = json.loads(payload)
+ except json.JSONDecodeError:
+ continue
+
+ stream = event.get("stream")
+ if stream == "stdout":
+ data = event.get("data", "")
+ stdout_parts.append(data)
+ if on_stdout:
+ on_stdout(data)
+ elif stream == "stderr":
+ data = event.get("data", "")
+ stderr_parts.append(data)
+ if on_stderr:
+ on_stderr(data)
+ elif stream == "exit":
+ exit_code = event.get("exit_code", -1)
+
+ return {
+ "result": {
+ "stdout": "".join(stdout_parts),
+ "stderr": "".join(stderr_parts),
+ "exit_code": exit_code,
+ }
+ }
+
+ except httpx.TransportError as e:
+ return {"error": {"message": f"Stream connection error: {e}"}}
+ except httpx.HTTPStatusError as e:
+ return {"error": {"message": str(e)}}
+
+
+# Alias for backwards compatibility
+GuestAgentClient = QuicksandGuestAgentClient
diff --git a/packages/quicksand-core/quicksand_core/host/smb.py b/packages/quicksand-core/quicksand_core/host/smb.py
new file mode 100644
index 0000000..b00ab82
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/host/smb.py
@@ -0,0 +1,275 @@
+"""SMB file sharing for host-guest directory mounting.
+
+Provides a base class and platform-specific implementations:
+- QuicksandSMBServer: Pure-Python SMB3 server via QEMU guestfwd (macOS/Linux)
+- WindowsSMBServer: Uses Windows native SMB via PowerShell
+
+All mounts (boot-time and dynamic) use CIFS over QEMU slirp networking.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import secrets
+import subprocess
+import sys
+import tempfile
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ pass
+
+logger = logging.getLogger("quicksand.smb")
+
+
+class SMBServer(ABC):
+ """Base class for SMB file sharing servers.
+
+ Implementations expose host directories as SMB shares that the guest
+ mounts via CIFS over QEMU's slirp gateway (10.0.2.2).
+ """
+
+ @abstractmethod
+ def start(self) -> None:
+ """Start the SMB server."""
+ ...
+
+ @abstractmethod
+ def stop(self) -> None:
+ """Stop the SMB server and clean up all shares."""
+ ...
+
+ @abstractmethod
+ def add_share(self, host_path: str, readonly: bool = False) -> str:
+ """Add an SMB share for a host directory.
+
+ Args:
+ host_path: Absolute path to the host directory.
+ readonly: Whether the share should be read-only.
+
+ Returns:
+ The share name (e.g., "QUICKSAND0") for use in CIFS mount commands.
+ """
+ ...
+
+ @abstractmethod
+ def remove_share(self, share_name: str) -> None:
+ """Remove a previously added share."""
+ ...
+
+ @property
+ @abstractmethod
+ def port(self) -> int:
+ """The port the SMB server is listening on."""
+ ...
+
+ @property
+ @abstractmethod
+ def credentials(self) -> tuple[str, str]:
+ """Returns (username, password) for CIFS mount authentication."""
+ ...
+
+ @abstractmethod
+ def list_shares(self) -> list[dict]:
+ """List all active shares.
+
+ Returns:
+ List of dicts with keys: share_name, host_path, readonly.
+ """
+ ...
+
+ def get_guestfwd_cmd(self) -> str | None:
+ """Return the guestfwd command for QEMU, or None if not supported.
+
+ Implementations that run as inetd-style servers (spawned by QEMU's
+ guestfwd) return the command string. TCP-based implementations
+ return None and use the relay script instead.
+ """
+ return None
+
+
+class WindowsSMBServer(SMBServer):
+ """Windows native SMB sharing via PowerShell.
+
+ Creates temporary Windows SMB shares using New-SmbShare.
+ Shares are auto-cleaned up on stop.
+ """
+
+ def __init__(self, username: str, password: str = "") -> None:
+ self._username = username
+ self._password = password
+ self._shares: dict[str, dict] = {} # share_name → {host_path, readonly}
+ self._port_value = 445 # Windows native SMB always uses 445
+
+ def _run_powershell(self, script: str) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ ["powershell", "-NoProfile", "-Command", script],
+ capture_output=True,
+ text=True,
+ )
+
+ @property
+ def port(self) -> int:
+ return self._port_value
+
+ @property
+ def credentials(self) -> tuple[str, str]:
+ return (self._username, self._password)
+
+ def start(self) -> None:
+ if sys.platform != "win32":
+ raise RuntimeError("WindowsSMBServer is only available on Windows")
+ logger.info("Windows SMB server ready")
+
+ def stop(self) -> None:
+ for share_name in list(self._shares.keys()):
+ self.remove_share(share_name)
+ logger.info("Windows SMB shares cleaned up")
+
+ def add_share(self, host_path: str, readonly: bool = False) -> str:
+ share_name = f"QUICKSAND_{secrets.token_hex(8)}"
+
+ path = str(Path(host_path).resolve())
+ Path(path).mkdir(parents=True, exist_ok=True)
+
+ # Remove existing share if present
+ self._run_powershell(
+ f"Remove-SmbShare -Name '{share_name}' -Force -ErrorAction SilentlyContinue"
+ )
+
+ user = self._username
+ if readonly:
+ script = (
+ f"New-SmbShare -Name '{share_name}' -Path '{path}' -ReadAccess '{user}' -Temporary"
+ )
+ else:
+ script = (
+ f"New-SmbShare -Name '{share_name}' -Path '{path}' -FullAccess '{user}' -Temporary"
+ )
+
+ result = self._run_powershell(script)
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to create SMB share: {result.stderr}")
+
+ self._shares[share_name] = {"host_path": host_path, "readonly": readonly}
+ logger.info("Created SMB share %s -> %s (readonly=%s)", share_name, path, readonly)
+ return share_name
+
+ def remove_share(self, share_name: str) -> None:
+ result = self._run_powershell(
+ f"Remove-SmbShare -Name '{share_name}' -Force -ErrorAction SilentlyContinue"
+ )
+ if result.returncode == 0:
+ logger.info("Removed SMB share %s", share_name)
+ self._shares.pop(share_name, None)
+
+ def list_shares(self) -> list[dict]:
+ return [
+ {"share_name": name, "host_path": info["host_path"], "readonly": info["readonly"]}
+ for name, info in self._shares.items()
+ ]
+
+
+class QuicksandSMBServer(SMBServer):
+ """Pure-Python SMB3 server spawned by QEMU guestfwd (macOS/Linux).
+
+ Does NOT start a background process or open a TCP port. Shares are
+ configured in a JSON file; QEMU spawns a new ``python -m quicksand_smb``
+ process per guest TCP connection via guestfwd.
+ """
+
+ def __init__(self) -> None:
+ self._shares: dict[str, dict] = {}
+ self._config_path: Path | None = None
+ self._temp_dir: Path | None = None
+
+ @property
+ def port(self) -> int:
+ # No real TCP port — guestfwd uses the virtual IP
+ return 445
+
+ @property
+ def credentials(self) -> tuple[str, str]:
+ return ("guest", "")
+
+ def start(self) -> None:
+ self._temp_dir = Path(tempfile.mkdtemp(prefix="quicksand-smb-"))
+ self._config_path = self._temp_dir / "smb_config.json"
+ self._write_config()
+ logger.info("QuicksandSMBServer ready (config=%s)", self._config_path)
+
+ def stop(self) -> None:
+ if self._temp_dir is not None and self._temp_dir.exists():
+ import shutil
+
+ shutil.rmtree(self._temp_dir, ignore_errors=True)
+ self._temp_dir = None
+ self._config_path = None
+ self._shares.clear()
+
+ def add_share(self, host_path: str, readonly: bool = False) -> str:
+ share_name = f"QUICKSAND_{secrets.token_hex(8)}"
+ Path(host_path).mkdir(parents=True, exist_ok=True)
+ self._shares[share_name] = {"host_path": host_path, "readonly": readonly}
+ self._write_config()
+ logger.info("Added share %s -> %s (readonly=%s)", share_name, host_path, readonly)
+ return share_name
+
+ def remove_share(self, share_name: str) -> None:
+ self._shares.pop(share_name, None)
+ self._write_config()
+ logger.info("Removed share %s", share_name)
+
+ def list_shares(self) -> list[dict]:
+ return [
+ {"share_name": name, "host_path": info["host_path"], "readonly": info["readonly"]}
+ for name, info in self._shares.items()
+ ]
+
+ def get_guestfwd_cmd(self) -> str:
+ """Return the command string for QEMU guestfwd to spawn the SMB server."""
+ assert self._config_path is not None
+ return f"{sys.executable} -m quicksand_smb --config {self._config_path}"
+
+ def _write_config(self) -> None:
+ """Atomically write the shares config JSON file."""
+ if self._config_path is None:
+ return
+
+ import json
+
+ data = {
+ "shares": {
+ name: {"host_path": info["host_path"], "readonly": info["readonly"]}
+ for name, info in self._shares.items()
+ }
+ }
+
+ # Atomic write: write to temp file then rename
+ tmp_path = self._config_path.with_suffix(".tmp")
+ tmp_path.write_text(json.dumps(data))
+ os.replace(str(tmp_path), str(self._config_path))
+
+
+def create_smb_server() -> SMBServer:
+ """Factory: returns the appropriate SMBServer for the current platform.
+
+ Windows uses native SMB via PowerShell. All other platforms use the
+ pure-Python QuicksandSMBServer (spawned by QEMU guestfwd, no TCP port).
+ """
+ if sys.platform == "win32":
+ username = os.environ.get("QUICKSAND_SMB_USERNAME", "")
+ password = os.environ.get("QUICKSAND_SMB_PASSWORD", "")
+ if not username:
+ try:
+ username = os.getlogin()
+ except OSError:
+ import getpass as _getpass
+
+ username = _getpass.getuser()
+ return WindowsSMBServer(username, password)
+
+ return QuicksandSMBServer()
diff --git a/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py b/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
new file mode 100644
index 0000000..70eedd9
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
@@ -0,0 +1,302 @@
+"""Async client for quicksand guest agent over virtio-serial (Unix/TCP socket).
+
+Uses length-prefixed JSON framing over a QEMU chardev socket, bypassing
+the guest networking stack entirely.
+
+Frame format:
+ ┌──────────┬─────────────────────┐
+ │ 4 bytes │ N bytes │
+ │ length N │ JSON payload (UTF-8)│
+ │ (big-end)│ │
+ └──────────┴─────────────────────┘
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+import logging
+import struct
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+from .._types import QuicksandGuestAgentMethod, Timeouts
+
+logger = logging.getLogger("quicksand.virtio_agent")
+
+_HEADER_FMT = "!I" # 4-byte big-endian unsigned int
+_HEADER_SIZE = struct.calcsize(_HEADER_FMT)
+_MAX_FRAME_SIZE = 64 * 1024 * 1024 # 64 MB sanity limit
+
+
+def _encode_frame(msg: dict) -> bytes:
+ """Encode a message as a length-prefixed JSON frame."""
+ payload = json.dumps(msg, separators=(",", ":")).encode("utf-8")
+ return struct.pack(_HEADER_FMT, len(payload)) + payload
+
+
+async def _read_frame(reader: asyncio.StreamReader) -> dict:
+ """Read one length-prefixed JSON frame from the stream."""
+ header = await reader.readexactly(_HEADER_SIZE)
+ (length,) = struct.unpack(_HEADER_FMT, header)
+ if length > _MAX_FRAME_SIZE:
+ raise RuntimeError(f"Frame too large: {length} bytes")
+ payload = await reader.readexactly(length)
+ return json.loads(payload)
+
+
+class VirtioSerialAgentClient:
+ """Async client for the quicksand guest agent over virtio-serial.
+
+ Communicates via QEMU's chardev Unix domain socket (or TCP on Windows)
+ using length-prefixed JSON framing. Provides the same interface as
+ QuicksandGuestAgentClient.
+ """
+
+ def __init__(self, socket_path: str | Path, token: str):
+ self._socket_path = str(socket_path)
+ self._token = token
+ self._reader: asyncio.StreamReader | None = None
+ self._writer: asyncio.StreamWriter | None = None
+ self._lock: asyncio.Lock | None = None
+ self._request_id = 0
+
+ @property
+ def is_connected(self) -> bool:
+ return self._writer is not None
+
+ def _next_id(self) -> int:
+ self._request_id += 1
+ return self._request_id
+
+ async def connect(
+ self,
+ timeout: float = Timeouts.BOOT_DEFAULT,
+ process_check: Callable[[], tuple[bool, str]] | None = None,
+ ) -> None:
+ """Connect to the agent via the chardev socket and authenticate.
+
+ Retries until the socket is ready (QEMU creates it at launch) and
+ the guest agent sends a valid authentication response.
+
+ Once connected to the QEMU chardev socket, the connection is kept
+ open across auth retries. Disconnecting causes QEMU to stop
+ accepting new connections on the chardev, so reconnection is only
+ attempted on hard connection errors (socket gone, refused, reset).
+ """
+ loop = asyncio.get_event_loop()
+ deadline = loop.time() + timeout
+ last_error: Exception | None = None
+ attempt = 0
+
+ logger.debug("Connecting to agent via virtio-serial: %s", self._socket_path)
+
+ while loop.time() < deadline:
+ attempt += 1
+
+ if process_check:
+ is_running, error_info = process_check()
+ if not is_running:
+ raise RuntimeError(error_info)
+
+ # Re-use an existing connection if we already have one
+ # (previous auth timed out waiting for the guest agent to open
+ # the virtio-serial device).
+ if self._writer is None:
+ try:
+ reader, writer = await asyncio.open_unix_connection(self._socket_path)
+ self._reader = reader
+ self._writer = writer
+ except (OSError, ConnectionRefusedError) as e:
+ logger.debug("Connection attempt %d failed: %s", attempt, e)
+ last_error = e
+ await asyncio.sleep(0.1)
+ continue
+
+ assert self._writer is not None and self._reader is not None
+ try:
+ # Authenticate
+ auth_msg = {
+ "id": self._next_id(),
+ "method": "authenticate",
+ "params": {"token": self._token},
+ }
+ self._writer.write(_encode_frame(auth_msg))
+ await self._writer.drain()
+
+ remaining = max(deadline - loop.time(), 1.0)
+ read_timeout = min(Timeouts.GUEST_AGENT_HTTP, remaining)
+ response = await asyncio.wait_for(_read_frame(self._reader), timeout=read_timeout)
+ result = response.get("result", {})
+ if result.get("authenticated"):
+ logger.debug("Virtio-serial agent authentication successful")
+ # Drain stale auth responses from previous retries
+ drained = 0
+ stale_expected = attempt - 1
+ while drained < stale_expected:
+ try:
+ _ = await asyncio.wait_for(_read_frame(self._reader), timeout=2.0)
+ drained += 1
+ except TimeoutError:
+ break
+ if drained:
+ logger.debug("Drained %d stale auth responses", drained)
+ # Reset request ID so future requests start fresh
+ self._request_id = 0
+ return
+
+ raise RuntimeError("Authentication rejected by agent")
+
+ except TimeoutError:
+ # Guest agent hasn't opened the device yet — keep the
+ # connection open and retry.
+ logger.debug("Connection attempt %d: auth read timed out, retrying", attempt)
+ last_error = TimeoutError("auth read timed out")
+ continue
+
+ except (
+ OSError,
+ ConnectionRefusedError,
+ ConnectionResetError,
+ asyncio.IncompleteReadError,
+ RuntimeError,
+ ) as e:
+ logger.debug("Connection attempt %d failed: %s", attempt, e)
+ last_error = e
+ self._close_transport()
+ await asyncio.sleep(0.1)
+
+ raise TimeoutError(
+ f"Could not connect to agent within {timeout}s via {self._socket_path}. "
+ f"Last error: {last_error}"
+ )
+
+ def _close_transport(self) -> None:
+ if self._writer:
+ with contextlib.suppress(Exception):
+ self._writer.close()
+ self._reader = None
+ self._writer = None
+
+ async def close(self) -> None:
+ self._close_transport()
+
+ async def send_request(
+ self,
+ method: QuicksandGuestAgentMethod,
+ params: dict[str, Any],
+ timeout: float = Timeouts.GUEST_AGENT_REQUEST,
+ ) -> dict[str, Any]:
+ if self._writer is None or self._reader is None:
+ raise RuntimeError("Not connected to agent")
+
+ if self._lock is None:
+ self._lock = asyncio.Lock()
+ async with self._lock:
+ method_map = {
+ QuicksandGuestAgentMethod.EXECUTE: "execute",
+ QuicksandGuestAgentMethod.PING: "ping",
+ }
+ method_name = method_map.get(method)
+ if method_name is None:
+ return {"error": {"message": f"Unknown method: {method}"}}
+
+ msg = {"id": self._next_id(), "method": method_name, "params": params}
+
+ try:
+ self._writer.write(_encode_frame(msg))
+ await self._writer.drain()
+
+ response = await asyncio.wait_for(_read_frame(self._reader), timeout=timeout)
+
+ resp_id = response.get("id")
+ if resp_id != msg["id"]:
+ return {
+ "error": {
+ "message": (
+ f"Response ID mismatch: expected {msg['id']}, got {resp_id}"
+ )
+ }
+ }
+
+ if "error" in response:
+ return {"error": response["error"]}
+ return {"result": response.get("result", response)}
+
+ except TimeoutError:
+ return {"error": {"message": f"Request timed out after {timeout}s"}}
+ except (ConnectionResetError, BrokenPipeError, OSError) as e:
+ return {"error": {"message": f"Connection error: {e}"}}
+
+ async def send_stream_request(
+ self,
+ params: dict[str, Any],
+ timeout: float,
+ on_stdout: Callable[[str], None] | None = None,
+ on_stderr: Callable[[str], None] | None = None,
+ ) -> dict[str, Any]:
+ if self._writer is None or self._reader is None:
+ raise RuntimeError("Not connected to agent")
+
+ if self._lock is None:
+ self._lock = asyncio.Lock()
+ async with self._lock:
+ msg = {"id": self._next_id(), "method": "execute_stream", "params": params}
+ stdout_parts: list[str] = []
+ stderr_parts: list[str] = []
+ exit_code = -1
+
+ try:
+ self._writer.write(_encode_frame(msg))
+ await self._writer.drain()
+
+ deadline = asyncio.get_event_loop().time() + timeout
+ while True:
+ remaining = deadline - asyncio.get_event_loop().time()
+ if remaining <= 0:
+ return {"error": {"message": f"Stream timed out after {timeout}s"}}
+
+ frame = await asyncio.wait_for(_read_frame(self._reader), timeout=remaining)
+
+ frame_id = frame.get("id")
+ if frame_id != msg["id"]:
+ return {
+ "error": {
+ "message": (
+ f"Stream response ID mismatch: expected {msg['id']}, "
+ f"got {frame_id}"
+ )
+ }
+ }
+
+ stream = frame.get("stream")
+ if stream == "stdout":
+ data = frame.get("data", "")
+ stdout_parts.append(data)
+ if on_stdout:
+ on_stdout(data)
+ elif stream == "stderr":
+ data = frame.get("data", "")
+ stderr_parts.append(data)
+ if on_stderr:
+ on_stderr(data)
+ elif stream == "exit":
+ exit_code = frame.get("exit_code", -1)
+ break
+ elif "error" in frame:
+ return {"error": frame["error"]}
+
+ return {
+ "result": {
+ "stdout": "".join(stdout_parts),
+ "stderr": "".join(stderr_parts),
+ "exit_code": exit_code,
+ }
+ }
+
+ except TimeoutError:
+ return {"error": {"message": f"Stream timed out after {timeout}s"}}
+ except (ConnectionResetError, BrokenPipeError, OSError) as e:
+ return {"error": {"message": f"Stream connection error: {e}"}}
diff --git a/packages/quicksand-core/quicksand_core/py.typed b/packages/quicksand-core/quicksand_core/py.typed
new file mode 100644
index 0000000..e69de29
diff --git a/packages/quicksand-core/quicksand_core/qemu/__init__.py b/packages/quicksand-core/quicksand_core/qemu/__init__.py
new file mode 100644
index 0000000..08754a2
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/__init__.py
@@ -0,0 +1,11 @@
+"""QEMU-specific subsystems: overlay, process, save, and platform configuration."""
+
+from .overlay import OverlayManager
+from .process import VMProcessManager
+from .qmp import QMPClient
+
+__all__ = [
+ "OverlayManager",
+ "QMPClient",
+ "VMProcessManager",
+]
diff --git a/packages/quicksand-core/quicksand_core/qemu/arch.py b/packages/quicksand-core/quicksand_core/qemu/arch.py
new file mode 100644
index 0000000..0d174dd
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/arch.py
@@ -0,0 +1,195 @@
+"""QEMU architecture-specific configuration.
+
+Provides machine types and virtio device names for each supported CPU architecture.
+
+Machine types:
+- x86_64: q35 (default) or microvm (with KVM for ~4x faster boot)
+- ARM64: virt
+
+Device types vary by machine:
+- PCI machines (q35): virtio-blk-pci, virtio-net-pci
+- MMIO machines (virt, microvm): virtio-blk-device, virtio-net-device
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from enum import StrEnum
+
+from ..host.arch import Architecture, _detect_architecture
+
+
+class MachineType(StrEnum):
+ """QEMU machine types."""
+
+ VIRT = "virt"
+ Q35 = "q35"
+ MICROVM = "microvm"
+
+
+class BaseArchitectureConfig(ABC):
+ """Abstract base class for architecture-specific QEMU configuration."""
+
+ @property
+ @abstractmethod
+ def arch_type(self) -> Architecture: ...
+
+ @property
+ @abstractmethod
+ def machine_type(self) -> MachineType: ...
+
+ @property
+ @abstractmethod
+ def qemu_suffix(self) -> str: ...
+
+ @property
+ @abstractmethod
+ def console_device(self) -> str: ...
+
+ @property
+ @abstractmethod
+ def virtio_net_device(self) -> str: ...
+
+ @property
+ @abstractmethod
+ def virtio_blk_device(self) -> str: ...
+
+ @property
+ @abstractmethod
+ def virtio_gpu_device(self) -> str: ...
+
+ @property
+ @abstractmethod
+ def default_cpu_model(self) -> str: ...
+
+ def build_cpu_args(self, has_hw_accel: bool) -> list[str]:
+ """Build QEMU -cpu arguments."""
+ if has_hw_accel:
+ return ["-cpu", "host"]
+ elif self.default_cpu_model:
+ return ["-cpu", self.default_cpu_model]
+ return []
+
+
+class X86_64Config(BaseArchitectureConfig):
+ """QEMU configuration for x86_64 (amd64)."""
+
+ @property
+ def arch_type(self) -> Architecture:
+ return Architecture.X86_64
+
+ @property
+ def machine_type(self) -> MachineType:
+ return MachineType.Q35
+
+ @property
+ def qemu_suffix(self) -> str:
+ return "x86_64"
+
+ @property
+ def console_device(self) -> str:
+ return "ttyS0"
+
+ @property
+ def virtio_net_device(self) -> str:
+ return "virtio-net-pci"
+
+ @property
+ def virtio_blk_device(self) -> str:
+ return "virtio-blk-pci"
+
+ @property
+ def virtio_gpu_device(self) -> str:
+ return "virtio-vga"
+
+ @property
+ def default_cpu_model(self) -> str:
+ return ""
+
+
+class ARM64Config(BaseArchitectureConfig):
+ """QEMU configuration for ARM64 (aarch64)."""
+
+ @property
+ def arch_type(self) -> Architecture:
+ return Architecture.ARM64
+
+ @property
+ def machine_type(self) -> MachineType:
+ return MachineType.VIRT
+
+ @property
+ def qemu_suffix(self) -> str:
+ return "aarch64"
+
+ @property
+ def console_device(self) -> str:
+ return "ttyAMA0"
+
+ @property
+ def virtio_net_device(self) -> str:
+ return "virtio-net-device"
+
+ @property
+ def virtio_blk_device(self) -> str:
+ return "virtio-blk-device"
+
+ @property
+ def virtio_gpu_device(self) -> str:
+ return "virtio-gpu-pci"
+
+ @property
+ def default_cpu_model(self) -> str:
+ return "max"
+
+
+class ArchitectureConfig(BaseArchitectureConfig):
+ """Auto-detecting QEMU architecture configuration.
+
+ Instantiating returns the appropriate subclass for the current CPU.
+
+ Example:
+ config = ArchitectureConfig() # Returns X86_64Config or ARM64Config
+ """
+
+ def __new__(cls) -> BaseArchitectureConfig:
+ if cls is ArchitectureConfig:
+ arch = _detect_architecture()
+ if arch == Architecture.X86_64:
+ return object.__new__(X86_64Config)
+ elif arch == Architecture.ARM64:
+ return object.__new__(ARM64Config)
+ raise RuntimeError(f"Unsupported architecture: {arch}")
+ return object.__new__(cls)
+
+ @property
+ def arch_type(self) -> Architecture:
+ raise NotImplementedError
+
+ @property
+ def machine_type(self) -> MachineType:
+ raise NotImplementedError
+
+ @property
+ def qemu_suffix(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def console_device(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def virtio_net_device(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def virtio_blk_device(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def virtio_gpu_device(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def default_cpu_model(self) -> str:
+ raise NotImplementedError
diff --git a/packages/quicksand-core/quicksand_core/qemu/image_resolver.py b/packages/quicksand-core/quicksand_core/qemu/image_resolver.py
new file mode 100644
index 0000000..2036c4c
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/image_resolver.py
@@ -0,0 +1,242 @@
+"""Image resolution — unified lookup for base images and saves.
+
+Resolution order for string image references:
+
+1. Explicit path (file or directory on disk) — load as save
+2. ``$CWD/.quicksand/sandboxes/{name}/`` — local save
+3. ``~/.quicksand/sandboxes/{name}/`` — global save
+4. Entry points (``quicksand.images`` group) — base image packages
+5. Error
+"""
+
+from __future__ import annotations
+
+import logging
+from importlib.metadata import entry_points
+from pathlib import Path
+
+from .._types import FilePatterns, ResolvedImage, SaveManifest
+from ..host.arch import Architecture, _detect_architecture
+
+logger = logging.getLogger("quicksand.image")
+
+# Current save file format version
+SAVE_VERSION = 6
+
+
+class ImageResolver:
+ """Resolves an image name to concrete artifacts.
+
+ Saves are always directories. Tar files are not supported — users must
+ extract them before use.
+ """
+
+ # =================================================================
+ # Public: image resolution
+ # =================================================================
+
+ def resolve(self, image: str, *, arch: str | None = None) -> ResolvedImage:
+ """Resolve an image reference to concrete paths.
+
+ Args:
+ image: Image name (``"ubuntu"``), save name, or filesystem path.
+ arch: Force a specific image architecture (e.g. ``"amd64"``).
+ When set, the sandbox will use TCG emulation if the host
+ architecture differs.
+ """
+ # 1-3. Check filesystem: explicit path, local save, global save
+ save_dir = self._find_save_dir(image)
+ if save_dir is not None:
+ return self._resolve_save(save_dir)
+
+ # 4. Entry points (quicksand.images)
+ result = self._resolve_base_by_name(image, arch=arch)
+ if result is not None:
+ # Tag with guest_arch when cross-building
+ if arch is not None:
+ host_arch = _detect_architecture()
+ image_arch = Architecture.from_str(arch).image_arch
+ if image_arch != str(host_arch):
+ result = ResolvedImage(
+ name=result.name,
+ chain=result.chain,
+ kernel=result.kernel,
+ initrd=result.initrd,
+ guest_arch=image_arch,
+ )
+ return result
+
+ # 5. Fail
+ raise RuntimeError(
+ f"Image not found: '{image}'\n"
+ f"Not a local/global save and no matching entry point.\n"
+ f"Install it with: quicksand install {image}"
+ )
+
+ # =================================================================
+ # Public: save validation
+ # =================================================================
+
+ def validate_save(self, path: Path) -> SaveManifest:
+ """Validate save structure: manifest version and overlays directory.
+
+ Args:
+ path: Path to the save directory.
+
+ Returns:
+ The parsed SaveManifest.
+
+ Raises:
+ ValueError: If save is invalid.
+ """
+ if not path.is_dir():
+ raise ValueError(f"Save path is not a directory: {path}")
+
+ manifest = _load_manifest(path)
+
+ if manifest.version > SAVE_VERSION:
+ raise ValueError(
+ f"Save version {manifest.version} is newer than supported version {SAVE_VERSION}"
+ )
+
+ overlays_dir = path / FilePatterns.OVERLAYS_DIR
+ if not overlays_dir.is_dir():
+ raise ValueError(f"Missing {FilePatterns.OVERLAYS_DIR}/ directory in save: {path}")
+
+ overlays = sorted(overlays_dir.glob("*.qcow2"))
+ if not overlays:
+ raise ValueError(f"No overlay files found in {overlays_dir}")
+
+ return manifest
+
+ # =================================================================
+ # Internal: save resolution
+ # =================================================================
+
+ def _resolve_save(self, save_dir: Path) -> ResolvedImage:
+ """Load a save directory and resolve its base image."""
+ manifest = _load_manifest(save_dir)
+
+ if manifest.version > SAVE_VERSION:
+ raise ValueError(
+ f"Save version {manifest.version} is newer than supported version {SAVE_VERSION}"
+ )
+
+ # Read overlays from the directory (canonical source)
+ overlays_dir = save_dir / FilePatterns.OVERLAYS_DIR
+ if not overlays_dir.is_dir():
+ raise ValueError(f"Missing {FilePatterns.OVERLAYS_DIR}/ directory in save: {save_dir}")
+ overlays = sorted(overlays_dir.glob("*.qcow2"))
+ if not overlays:
+ raise ValueError(f"No overlay files found in {overlays_dir}")
+
+ # Cross-arch detection
+ host_arch = _detect_architecture()
+ save_arch = manifest.arch
+ image_arch: str | None = None
+
+ if save_arch is not None and save_arch != str(host_arch):
+ image_arch = Architecture.from_str(save_arch).image_arch
+ logger.warning(
+ "Save was created on %s but host is %s. "
+ "Running in TCG (software emulation) — performance will be degraded.",
+ save_arch,
+ host_arch,
+ )
+
+ # Recursively resolve the parent image to get its full chain
+ parent_name = manifest.config.image
+ parent_resolved = self._resolve_base_by_name(parent_name, arch=image_arch)
+
+ if parent_resolved is None:
+ arch_msg = f" for {image_arch}" if image_arch else ""
+ raise RuntimeError(
+ f"Base image '{parent_name}'{arch_msg} not installed.\n"
+ f"Install it with: quicksand install {parent_name}"
+ + (f" --arch {image_arch}" if image_arch else "")
+ )
+
+ # Merge: parent's full chain + this save's overlays
+ full_chain = list(parent_resolved.chain) + overlays
+
+ logger.info(
+ "Loaded save: parent=%s, own_overlays=%d, total_chain=%d",
+ parent_name,
+ len(overlays),
+ len(full_chain),
+ )
+
+ return ResolvedImage(
+ name=parent_name,
+ chain=full_chain,
+ kernel=parent_resolved.kernel,
+ initrd=parent_resolved.initrd,
+ guest_arch=image_arch,
+ )
+
+ # =================================================================
+ # Internal: base image resolution
+ # =================================================================
+
+ @staticmethod
+ def _resolve_base_by_name(name: str, *, arch: str | None = None) -> ResolvedImage | None:
+ """Look up a base image by name via quicksand.images entry points."""
+ for ep in entry_points(group="quicksand.images"):
+ if ep.name != name:
+ continue
+ try:
+ provider = ep.load()
+ result = provider.resolve(arch=arch)
+ if result.name != name:
+ # Provider may return a generic name; override with the
+ # entry-point name for consistency.
+ result = ResolvedImage(
+ name=name,
+ chain=result.chain,
+ kernel=result.kernel,
+ initrd=result.initrd,
+ )
+ logger.info("Resolved base image via entry point: %s", name)
+ return result
+ except Exception:
+ logger.debug("Failed to load entry point %s", ep.name, exc_info=True)
+ continue
+ return None
+
+ # =================================================================
+ # Internal: utilities
+ # =================================================================
+
+ @staticmethod
+ def _find_save_dir(image: str) -> Path | None:
+ """Check filesystem locations for a save matching the image name.
+
+ Checks in order: explicit path, local saves, global saves.
+ Tar files are not supported — raises an error if encountered.
+ """
+ candidates = [
+ Path(image), # 1. Explicit path
+ Path.cwd() / ".quicksand" / "sandboxes" / image, # 2. Local save
+ Path.home() / ".quicksand" / "sandboxes" / image, # 3. Global save
+ ]
+ for candidate in candidates:
+ if candidate.is_file():
+ if candidate.name.endswith((".tar.gz", ".tar")):
+ raise RuntimeError(
+ f"Tar save files are no longer supported: {candidate}\n"
+ f"Extract the archive first: tar xzf {candidate}"
+ )
+ # Not a tar — skip (not a save directory)
+ continue
+ if candidate.is_dir() and (candidate / FilePatterns.MANIFEST).exists():
+ logger.info("Found save directory: %s", candidate)
+ return candidate
+ return None
+
+
+def _load_manifest(save_dir: Path) -> SaveManifest:
+ """Load and parse manifest.json from a save directory."""
+ manifest_path = save_dir / FilePatterns.MANIFEST
+ if not manifest_path.exists():
+ raise ValueError(f"Missing {FilePatterns.MANIFEST} in save: {save_dir}")
+ return SaveManifest.model_validate_json(manifest_path.read_text())
diff --git a/packages/quicksand-core/quicksand_core/qemu/overlay.py b/packages/quicksand-core/quicksand_core/qemu/overlay.py
new file mode 100644
index 0000000..85fdb38
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/overlay.py
@@ -0,0 +1,182 @@
+"""QEMU overlay (qcow2) image management."""
+
+from __future__ import annotations
+
+import json
+import logging
+import subprocess
+from pathlib import Path
+
+logger = logging.getLogger("quicksand.overlay")
+
+
+class OverlayManager:
+ """Manages qcow2 overlay creation and resize operations."""
+
+ def __init__(self, qemu_img: Path):
+ self._qemu_img = qemu_img
+
+ # ------------------------------------------------------------------
+ # Overlay creation
+ # ------------------------------------------------------------------
+
+ def create_overlay(
+ self,
+ image_path: Path,
+ overlay_path: Path,
+ restore_chain: list[Path] | None = None,
+ disk_size: str | None = None,
+ ) -> None:
+ """Create a qcow2 overlay backed by the base image.
+
+ Args:
+ image_path: Path to the base qcow2 image.
+ overlay_path: Path to write the overlay file.
+ restore_chain: If restoring from a save, the extracted overlay
+ chain (bottom-to-top). A fresh overlay is created on top.
+ disk_size: Optional size to resize the overlay to (e.g., "2G").
+ """
+ if restore_chain:
+ self._prepare_restored_chain(restore_chain, image_path)
+ # Create a fresh overlay backed by the top of the restored chain.
+ backing = restore_chain[-1]
+ subprocess.run(
+ [
+ str(self._qemu_img),
+ "create",
+ "-f",
+ "qcow2",
+ "-b",
+ str(backing.absolute()),
+ "-F",
+ "qcow2",
+ str(overlay_path),
+ ],
+ check=True,
+ capture_output=True,
+ )
+ if disk_size:
+ self.resize_overlay(overlay_path, disk_size)
+ return
+
+ subprocess.run(
+ [
+ str(self._qemu_img),
+ "create",
+ "-f",
+ "qcow2",
+ "-b",
+ str(image_path.absolute()),
+ "-F",
+ "qcow2",
+ str(overlay_path),
+ ],
+ check=True,
+ capture_output=True,
+ )
+
+ if disk_size:
+ self.resize_overlay(overlay_path, disk_size)
+
+ def resize_overlay(self, overlay_path: Path, disk_size: str) -> None:
+ """Resize an overlay disk image."""
+ logger.debug(f"Resizing overlay to {disk_size}")
+ subprocess.run(
+ [
+ str(self._qemu_img),
+ "resize",
+ str(overlay_path),
+ disk_size,
+ ],
+ check=True,
+ capture_output=True,
+ )
+
+ # ------------------------------------------------------------------
+ # Overlay chain introspection
+ # ------------------------------------------------------------------
+
+ def get_backing_file(self, overlay_path: Path) -> str | None:
+ """Read the backing file path from a qcow2 overlay.
+
+ Returns None if the overlay has no backing file.
+ """
+ result = subprocess.run(
+ [str(self._qemu_img), "info", "--output=json", str(overlay_path)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ info = json.loads(result.stdout)
+ return info.get("backing-filename")
+
+ def get_overlay_chain(self, top_overlay: Path, base_image: Path) -> list[Path]:
+ """Walk the backing chain from top overlay down to the base image.
+
+ Returns a list in bottom-to-top order (base-adjacent overlay first).
+ The base image itself is NOT included.
+ """
+ chain: list[Path] = []
+ current = top_overlay
+ while True:
+ chain.append(current)
+ backing = self.get_backing_file(current)
+ if backing is None:
+ break
+ backing_path = Path(backing)
+ if backing_path.resolve() == base_image.resolve():
+ break
+ current = backing_path
+ chain.reverse()
+ return chain
+
+ # ------------------------------------------------------------------
+ # Chain preparation for restore
+ # ------------------------------------------------------------------
+
+ def _prepare_restored_chain(self, chain: list[Path], base_image: Path) -> None:
+ """Fix backing file references in a restored overlay chain.
+
+ After extraction from a tar, the overlays' internal backing paths
+ point to the original temp directory (now deleted). This method
+ updates each overlay to reference the correct file using
+ ``qemu-img rebase -u`` (metadata-only, instant).
+
+ Args:
+ chain: Overlay paths in bottom-to-top order.
+ base_image: Current path to the base qcow2 image.
+ """
+ for i, overlay in enumerate(chain):
+ if i == 0:
+ expected_backing = str(base_image.absolute())
+ else:
+ expected_backing = str(chain[i - 1].absolute())
+
+ current_backing = self.get_backing_file(overlay)
+ if current_backing is not None:
+ try:
+ if Path(current_backing).resolve() == Path(expected_backing).resolve():
+ continue
+ except (OSError, ValueError):
+ pass # stale path that can't be resolved — needs rebase
+
+ logger.debug(
+ "Rebasing overlay %s: %s -> %s",
+ overlay.name,
+ current_backing,
+ expected_backing,
+ )
+ subprocess.run(
+ [
+ str(self._qemu_img),
+ "rebase",
+ "-u",
+ "-b",
+ expected_backing,
+ "-F",
+ "qcow2",
+ str(overlay),
+ ],
+ check=True,
+ capture_output=True,
+ )
diff --git a/packages/quicksand-core/quicksand_core/qemu/platform.py b/packages/quicksand-core/quicksand_core/qemu/platform.py
new file mode 100644
index 0000000..03ad4c3
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/platform.py
@@ -0,0 +1,599 @@
+"""QEMU platform configuration and command building.
+
+Provides PlatformConfig which composes architecture + OS configuration to produce
+QEMU command lines. Also provides runtime discovery (get_runtime, get_accelerator).
+
+Performance optimizations applied automatically:
+- microvm machine type: ~4x faster boot (Linux x86_64 + KVM only)
+- io_uring disk AIO: ~50% lower disk latency (Linux only)
+- IOThreads: Better concurrent disk I/O (all platforms)
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from functools import lru_cache
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from .._types import KernelParams, NetworkConstants, NetworkMode
+from ..host.arch import Architecture
+from ..host.os_ import (
+ Accelerator,
+ AcceleratorStatus,
+ BaseOSConfig,
+ OSConfig,
+)
+from ..host.smb import SMBServer
+from .arch import (
+ ArchitectureConfig,
+ BaseArchitectureConfig,
+ MachineType,
+)
+
+if TYPE_CHECKING:
+ from .._types import SandboxConfig
+
+__all__ = [
+ "PlatformConfig",
+ "RuntimeInfo",
+ "detect_accelerator",
+ "get_accelerator",
+ "get_machine_type",
+ "get_platform_config",
+ "get_platform_config_for_arch",
+ "get_runtime",
+ "is_runtime_available",
+]
+
+
+@dataclass
+class RuntimeInfo:
+ """Resolved paths to QEMU binaries."""
+
+ qemu_binary: Path
+ qemu_img: Path
+ runtime_dir: Path
+ data_dir: Path | None = None # share/qemu/ for firmware/ROMs
+ module_dir: Path | None = None # lib/qemu/ for accelerator modules (Linux)
+
+
+class PlatformConfig:
+ """Composed platform configuration combining architecture + OS.
+
+ Use get_platform_config() to get the cached singleton for the current platform.
+ """
+
+ def __init__(
+ self,
+ arch: BaseArchitectureConfig | None = None,
+ os: BaseOSConfig | None = None,
+ ):
+ self.arch = arch if arch is not None else ArchitectureConfig()
+ self.os = os if os is not None else OSConfig()
+
+ @property
+ def platform_key(self) -> str:
+ return f"{self.os.os_type}-{self.arch.arch_type}"
+
+ def qemu_system_binary(self) -> str:
+ return f"qemu-system-{self.arch.qemu_suffix}{self.os.binary_extension}"
+
+ def qemu_img_binary(self) -> str:
+ return f"qemu-img{self.os.binary_extension}"
+
+ def detect_accelerator(self) -> AcceleratorStatus:
+ return self.os.detect_accelerator()
+
+ def get_accelerator(self) -> Accelerator:
+ return self.detect_accelerator().accelerator
+
+ @property
+ def machine_type(self) -> MachineType:
+ return self.arch.machine_type
+
+ @property
+ def console_device(self) -> str:
+ return self.arch.console_device
+
+ @property
+ def virtio_net_device(self) -> str:
+ return self.arch.virtio_net_device
+
+ @property
+ def virtio_blk_device(self) -> str:
+ return self.arch.virtio_blk_device
+
+ @property
+ def cache_dir(self) -> Path:
+ return self.os.cache_dir
+
+ @property
+ def images_dir(self) -> Path:
+ return self.os.images_dir
+
+ @property
+ def disk_aio(self) -> str | None:
+ return self.os.disk_aio
+
+ def _use_microvm(self, accelerator: Accelerator | None, data_dir: Path | None = None) -> bool:
+ if not (
+ self.os.supports_microvm
+ and self.arch.arch_type == Architecture.X86_64
+ and accelerator == Accelerator.KVM
+ ):
+ return False
+ return not (data_dir and not (data_dir / "bios-microvm.bin").exists())
+
+ def _get_effective_machine_type(
+ self, accelerator: Accelerator | None, data_dir: Path | None = None
+ ) -> MachineType:
+ if self._use_microvm(accelerator, data_dir):
+ return MachineType.MICROVM
+ return self.arch.machine_type
+
+ def _get_virtio_blk_device(
+ self, accelerator: Accelerator | None, data_dir: Path | None = None
+ ) -> str:
+ if self._use_microvm(accelerator, data_dir):
+ return "virtio-blk-device"
+ return self.arch.virtio_blk_device
+
+ def _get_virtio_net_device(
+ self, accelerator: Accelerator | None, data_dir: Path | None = None
+ ) -> str:
+ if self._use_microvm(accelerator, data_dir):
+ return "virtio-net-device"
+ return self.arch.virtio_net_device
+
+ # =========================================================================
+ # QEMU Command Building
+ # =========================================================================
+
+ def build_qemu_command(
+ self,
+ config: SandboxConfig,
+ runtime_info: RuntimeInfo,
+ kernel_path: Path | None,
+ initrd_path: Path | None,
+ overlay_path: Path,
+ agent_port: int,
+ agent_token: str,
+ accelerator: Accelerator | None,
+ nested_virt: bool = False,
+ qmp_port: int | None = None,
+ vnc_port: int | None = None,
+ smb_port: int | None = None,
+ smb_server: SMBServer | None = None,
+ agent_socket_path: Path | None = None,
+ ) -> list[str]:
+ """Build the complete QEMU command line."""
+ data_dir = runtime_info.data_dir
+ use_microvm = self._use_microvm(accelerator, data_dir)
+ effective_machine = self._get_effective_machine_type(accelerator, data_dir)
+ virtio_blk = self._get_virtio_blk_device(accelerator, data_dir)
+
+ drive_opts = (
+ f"file={overlay_path},format=qcow2,if=none,id=drive0,"
+ f"cache=writethrough,discard=unmap,detect-zeroes=unmap"
+ )
+ if self.disk_aio:
+ drive_opts += f",aio={self.disk_aio}"
+
+ cmd = [
+ str(runtime_info.qemu_binary),
+ "-nodefaults",
+ "-machine",
+ effective_machine,
+ "-m",
+ config.memory,
+ "-smp",
+ str(config.cpus),
+ ]
+
+ # -L must come before -display so QEMU can locate keymap files.
+ if data_dir and data_dir.exists():
+ cmd.extend(["-L", str(data_dir)])
+
+ cmd.extend(
+ [
+ "-object",
+ "iothread,id=iothread0",
+ "-drive",
+ drive_opts,
+ "-device",
+ f"{virtio_blk},drive=drive0,iothread=iothread0",
+ "-serial",
+ "stdio",
+ ]
+ )
+
+ if vnc_port is not None:
+ # Enable virtual display for input injection and screenshots.
+ # VNC is bound to localhost only.
+ # QEMU VNC syntax: -display vnc=host:display where port = 5900 + display.
+ # find_free_vnc_port() allocates in 5900-5999, so display = port - 5900.
+ # The GPU device is arch-specific: virtio-vga (x86) or virtio-gpu-pci (ARM64).
+ vnc_display = vnc_port - 5900
+ gpu_device = self.arch.virtio_gpu_device
+ cmd.extend(
+ [
+ "-device",
+ gpu_device,
+ "-display",
+ f"vnc=127.0.0.1:{vnc_display}",
+ # USB tablet provides absolute mouse coordinates for input-send-event.
+ # Without it, QEMU has no absolute input handler and rejects abs events.
+ "-device",
+ "usb-ehci,id=ehci",
+ "-device",
+ "usb-tablet,bus=ehci.0",
+ # VirtIO keyboard: QMP send-key injects through this device.
+ # Without it, send-key has no keyboard backend on ARM64 virt
+ # (no PS/2 i8042 controller exists on this machine type).
+ "-device",
+ "virtio-keyboard-pci",
+ ]
+ )
+ else:
+ cmd.extend(["-nographic", "-vga", "none"])
+
+ if not use_microvm:
+ cmd.extend(["-global", "virtio-net-pci.romfile="])
+
+ has_hw_accel = accelerator in (Accelerator.KVM, Accelerator.HVF)
+ cmd.extend(self.arch.build_cpu_args(has_hw_accel))
+
+ if accelerator:
+ accel_arg = accelerator.value
+ if accelerator == Accelerator.WHPX and nested_virt:
+ accel_arg = "whpx,kernel-irqchip=off"
+ cmd.extend(["-accel", accel_arg])
+
+ if qmp_port is not None:
+ cmd.extend(["-qmp", f"tcp:127.0.0.1:{qmp_port},server,nowait"])
+
+ if agent_socket_path is not None:
+ cmd.extend(self._build_virtio_serial_args(agent_socket_path, accelerator, data_dir))
+
+ cmd.extend(
+ self._build_kernel_args(config, kernel_path, initrd_path, agent_port, agent_token)
+ )
+ cmd.extend(
+ self._build_network_args(
+ config, agent_port, accelerator, data_dir, smb_port, smb_server
+ )
+ )
+ cmd.extend(self._build_9p_args(config, accelerator, data_dir))
+ cmd.extend(config.extra_qemu_args)
+
+ return cmd
+
+ def _build_kernel_args(
+ self,
+ config: SandboxConfig,
+ kernel_path: Path | None,
+ initrd_path: Path | None,
+ agent_port: int,
+ agent_token: str,
+ ) -> list[str]:
+ if not kernel_path:
+ return []
+
+ cmd = ["-kernel", str(kernel_path)]
+
+ kernel_args = (
+ f"root=/dev/vda rw rootflags=rw console={self.console_device} rootfstype=ext4 "
+ f"quiet loglevel=0 raid=noautodetect "
+ f"{KernelParams.TOKEN}={agent_token} "
+ f"{KernelParams.PORT}={agent_port}"
+ )
+
+ for param in self.os.extra_kernel_params:
+ kernel_args += f" {param}"
+
+ cmd.extend(["-append", kernel_args])
+
+ if initrd_path:
+ cmd.extend(["-initrd", str(initrd_path)])
+
+ return cmd
+
+ def _build_virtio_serial_args(
+ self,
+ socket_path: Path,
+ accelerator: Accelerator | None = None,
+ data_dir: Path | None = None,
+ ) -> list[str]:
+ """Build QEMU args for virtio-serial agent channel."""
+ use_microvm = self._use_microvm(accelerator, data_dir)
+ serial_device = "virtio-serial-device" if use_microvm else "virtio-serial-pci"
+
+ return [
+ "-device",
+ serial_device,
+ "-chardev",
+ f"socket,path={socket_path},server=on,wait=off,id=vserial0",
+ "-device",
+ "virtserialport,chardev=vserial0,name=quicksand.agent.0",
+ ]
+
+ def _build_9p_args(
+ self,
+ config: SandboxConfig,
+ accelerator: Accelerator | None = None,
+ data_dir: Path | None = None,
+ ) -> list[str]:
+ """Build QEMU args for virtio-9p (Plan 9) mounts.
+
+ Each 9p mount in config.mounts gets a ``-fsdev``/``-device`` pair.
+ The mount tag is ``pb9p{i}`` where i is the 0-based index among 9p
+ mounts only. The same tag is used in the guest ``mount -t 9p`` command.
+ """
+ plan9_mounts = [m for m in config.mounts if m.type == "9p"]
+ if not plan9_mounts:
+ return []
+
+ use_microvm = self._use_microvm(accelerator, data_dir)
+ # MMIO machines (virt, microvm) use virtio-*-device; PCI machines (q35) use virtio-*-pci
+ use_mmio = use_microvm or self.arch.machine_type == MachineType.VIRT
+ device_type = "virtio-9p-device" if use_mmio else "virtio-9p-pci"
+
+ cmd: list[str] = []
+ for i, mount in enumerate(plan9_mounts):
+ tag = f"pb9p{i}"
+ ro = ",readonly=on" if mount.readonly else ""
+ cmd.extend(
+ [
+ "-fsdev",
+ f"local,id=pb_fs_{i},path={mount.host},security_model=none{ro}",
+ "-device",
+ f"{device_type},id=pb_9p_{i},fsdev=pb_fs_{i},mount_tag={tag}",
+ ]
+ )
+ return cmd
+
+ def _build_network_args(
+ self,
+ config: SandboxConfig,
+ agent_port: int,
+ accelerator: Accelerator | None = None,
+ data_dir: Path | None = None,
+ smb_port: int | None = None,
+ smb_server: SMBServer | None = None,
+ ) -> list[str]:
+ use_microvm = self._use_microvm(accelerator, data_dir)
+
+ if config.network_mode is NetworkMode.NONE:
+ if use_microvm:
+ return []
+ return ["-nic", "none"]
+
+ hostfwd = f"hostfwd=tcp:127.0.0.1:{agent_port}-:{agent_port}"
+
+ for pf in config.port_forwards:
+ hostfwd += f",hostfwd=tcp:127.0.0.1:{pf.host}-:{pf.guest}"
+
+ restrict = "off" if config.network_mode is NetworkMode.FULL else "on"
+
+ # Add guestfwd tunnel for SMB access. QEMU spawns a new process per
+ # guest TCP connection (inetd-style). QuicksandSMBServer is the SMB
+ # server itself; SambaSMBServer uses a TCP relay to an external smbd.
+ guestfwd = ""
+ guestfwd_ip = NetworkConstants.GUESTFWD_SMB_IP
+ guestfwd_port = NetworkConstants.GUESTFWD_SMB_PORT
+
+ guestfwd_cmd = smb_server.get_guestfwd_cmd() if smb_server is not None else None
+ if guestfwd_cmd is not None:
+ # QuicksandSMBServer: spawn the pure-Python SMB server directly.
+ # Works in both MOUNTS_ONLY and FULL modes — no TCP port needed.
+ guestfwd = f",guestfwd=tcp:{guestfwd_ip}:{guestfwd_port}-cmd:{guestfwd_cmd}"
+ elif config.network_mode is NetworkMode.MOUNTS_ONLY and smb_port is not None:
+ # SambaSMBServer fallback: relay to external smbd via TCP.
+ import sys
+
+ relay_script = str(Path(__file__).resolve().parent.parent / "_tcp_relay.py")
+ guestfwd = (
+ f",guestfwd=tcp:{guestfwd_ip}:{guestfwd_port}-"
+ f"cmd:{sys.executable} {relay_script} "
+ f"{NetworkConstants.LOCALHOST} {smb_port}"
+ )
+
+ netdev_opts = f"user,id=net0,restrict={restrict},{hostfwd}{guestfwd}"
+
+ if use_microvm:
+ return [
+ "-netdev",
+ netdev_opts,
+ "-device",
+ "virtio-net-device,netdev=net0",
+ ]
+
+ virtio_net = self._get_virtio_net_device(accelerator, data_dir)
+ return [
+ "-netdev",
+ netdev_opts,
+ "-device",
+ f"{virtio_net},netdev=net0",
+ ]
+
+
+@lru_cache(maxsize=1)
+def get_platform_config() -> PlatformConfig:
+ """Get the current platform config (cached singleton)."""
+ return PlatformConfig()
+
+
+def get_platform_config_for_arch(arch: str) -> PlatformConfig:
+ """Get a PlatformConfig for a specific guest architecture.
+
+ Uses the given architecture's QEMU config (machine type, virtio devices,
+ console) with the host OS config. Used for cross-architecture save loading.
+
+ Args:
+ arch: Guest architecture (``"x86_64"``, ``"arm64"``, or any alias
+ accepted by :meth:`Architecture.from_str`).
+ """
+ from ..host.arch import Architecture
+
+ guest = Architecture.from_str(arch)
+ if guest == Architecture.X86_64:
+ from .arch import X86_64Config
+
+ arch_config = X86_64Config()
+ else:
+ from .arch import ARM64Config
+
+ arch_config = ARM64Config()
+ return PlatformConfig(arch=arch_config)
+
+
+def detect_accelerator() -> AcceleratorStatus:
+ """Detect available hardware accelerator with detailed status."""
+ return get_platform_config().detect_accelerator()
+
+
+def get_accelerator() -> Accelerator:
+ """Get the best available accelerator."""
+ return detect_accelerator().accelerator
+
+
+def get_machine_type() -> MachineType:
+ """Get the appropriate machine type for the current architecture."""
+ return get_platform_config().machine_type
+
+
+# =============================================================================
+# Runtime discovery
+# =============================================================================
+
+
+def get_runtime(config: PlatformConfig | None = None) -> RuntimeInfo:
+ """Get the QEMU runtime, trying bundled first then system.
+
+ Args:
+ config: Platform config to use for binary name resolution.
+ Defaults to the host platform config. Pass a guest-arch
+ config for cross-architecture save loading.
+
+ Raises:
+ RuntimeError: If no QEMU runtime is found.
+ """
+ if config is None:
+ config = get_platform_config()
+
+ try:
+ bundled = _find_bundled_runtime(config)
+ if bundled:
+ return bundled
+ except _WrongArchError:
+ raise # installed but wrong arch — don't fall through to system QEMU
+
+ system = _find_system_runtime(config)
+ if system:
+ return system
+
+ raise RuntimeError(
+ "QEMU not found. Either:\n"
+ " - Install bundled: pip install quicksand-qemu\n"
+ " - Or install system QEMU and ensure it's in PATH"
+ )
+
+
+class _WrongArchError(RuntimeError):
+ """Raised when quicksand-qemu is installed but built for a different architecture."""
+
+
+def _find_bundled_runtime(config: PlatformConfig | None = None) -> RuntimeInfo | None:
+ """Return the bundled QEMU runtime, or None if quicksand-qemu is not installed.
+
+ Raises _WrongArchError if the package is installed but contains
+ binaries for a different architecture than the host hardware.
+ """
+ try:
+ from quicksand_qemu import get_bin_dir
+
+ bin_dir = get_bin_dir()
+ except ImportError:
+ return None
+ except FileNotFoundError:
+ return None
+
+ if config is None:
+ config = get_platform_config()
+
+ # Legacy fat wheel support: older win_amd64 wheels may contain both
+ # bin/x86_64/ and bin/arm64/ subdirectories. Pick the one matching
+ # the native hardware architecture. New slim wheels store binaries
+ # directly in bin/ so this check is a backward-compatibility fallback.
+ from ..host.arch import _detect_architecture
+
+ arch = _detect_architecture()
+ arch_subdir = bin_dir / ("arm64" if arch.image_arch == "arm64" else "x86_64")
+ if arch_subdir.is_dir():
+ bin_dir = arch_subdir
+
+ qemu_binary = bin_dir / config.qemu_system_binary()
+ qemu_img = bin_dir / config.qemu_img_binary()
+
+ if qemu_binary.exists() and qemu_img.exists():
+ data_dir = bin_dir / "share" / "qemu"
+ module_dir = bin_dir / "lib" / "qemu"
+ return RuntimeInfo(
+ qemu_binary=qemu_binary,
+ qemu_img=qemu_img,
+ runtime_dir=bin_dir.parent,
+ data_dir=data_dir if data_dir.exists() else None,
+ module_dir=module_dir if module_dir.exists() else None,
+ )
+
+ # quicksand-qemu is installed but binaries don't match native arch.
+ from ..host.arch import _is_emulated
+
+ if _is_emulated():
+ raise _WrongArchError(
+ f"quicksand-qemu is installed but contains binaries for a different "
+ f"architecture ({arch} expected).\n"
+ f"Python is running under platform emulation, so pip installed "
+ f"the wrong variant.\n"
+ f"Reinstall with the correct architecture:\n"
+ f" quicksand install quicksand-qemu"
+ )
+
+ raise _WrongArchError(
+ f"quicksand-qemu is installed but QEMU binaries for {arch} were not found.\n"
+ f"Reinstall with: quicksand install quicksand-qemu"
+ )
+
+
+def _find_system_runtime(config: PlatformConfig | None = None) -> RuntimeInfo | None:
+ import shutil
+
+ if config is None:
+ config = get_platform_config()
+ qemu_binary = shutil.which(config.qemu_system_binary())
+ qemu_img = shutil.which(config.qemu_img_binary())
+
+ if qemu_binary and qemu_img:
+ # Infer data_dir from the binary's prefix (e.g. /usr or /opt/homebrew).
+ # Handles Homebrew (/opt/homebrew/bin -> /opt/homebrew/share/qemu) and
+ # standard Linux installs (/usr/bin -> /usr/share/qemu).
+ bin_parent = Path(qemu_binary).parent # e.g. /opt/homebrew/bin
+ candidate_data = bin_parent.parent / "share" / "qemu"
+ data_dir = candidate_data if candidate_data.exists() else None
+ return RuntimeInfo(
+ qemu_binary=Path(qemu_binary),
+ qemu_img=Path(qemu_img),
+ runtime_dir=bin_parent,
+ data_dir=data_dir,
+ module_dir=None,
+ )
+ return None
+
+
+def is_runtime_available() -> bool:
+ """Check if any QEMU runtime is available (bundled or system)."""
+ try:
+ return _find_bundled_runtime() is not None or _find_system_runtime() is not None
+ except _WrongArchError:
+ return False
diff --git a/packages/quicksand-core/quicksand_core/qemu/process.py b/packages/quicksand-core/quicksand_core/qemu/process.py
new file mode 100644
index 0000000..e2e578d
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/process.py
@@ -0,0 +1,201 @@
+"""QEMU process lifecycle management.
+
+This module extracts process management logic from sandbox.py to improve
+code organization and testability.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import subprocess
+from pathlib import Path
+from typing import IO
+
+from .._types import Timeouts
+
+logger = logging.getLogger("quicksand.process")
+
+
+class VMProcessManager:
+ """Manages QEMU process lifecycle.
+
+ Handles starting, monitoring, and terminating the QEMU process,
+ as well as capturing console output for debugging.
+ """
+
+ def __init__(self):
+ """Initialize the process manager."""
+ self._process: subprocess.Popen | None = None
+ self._command: list[str] | None = None
+ self._console_log: Path | None = None
+ self._console_file: IO[str] | None = None
+
+ @property
+ def is_running(self) -> bool:
+ """Check if the process is still running."""
+ return self._process is not None and self._process.poll() is None
+
+ @property
+ def process(self) -> subprocess.Popen | None:
+ """Get the underlying process object."""
+ return self._process
+
+ @property
+ def pid(self) -> int | None:
+ """Get the process ID, or None if not running."""
+ return self._process.pid if self._process else None
+
+ @property
+ def returncode(self) -> int | None:
+ """Get the return code, or None if still running."""
+ return self._process.returncode if self._process else None
+
+ @property
+ def command(self) -> list[str] | None:
+ """Get the QEMU command that was used to start the process."""
+ return list(self._command) if self._command else None
+
+ def start(
+ self,
+ command: list[str],
+ env: dict[str, str],
+ console_log_path: Path,
+ ) -> None:
+ """Start the QEMU process.
+
+ Args:
+ command: The QEMU command line arguments.
+ env: Environment variables for the process.
+ console_log_path: Path to write console output.
+ """
+ if self._process is not None:
+ raise RuntimeError("Process already started")
+
+ self._command = list(command)
+ self._console_log = console_log_path
+ self._console_file = self._console_log.open("w")
+
+ self._process = subprocess.Popen(
+ command,
+ stdout=self._console_file,
+ stderr=subprocess.PIPE,
+ stdin=subprocess.PIPE,
+ env=env,
+ )
+
+ logger.debug(f"Started QEMU process with PID {self._process.pid}")
+
+ def write_serial(self, data: bytes) -> None:
+ """Write raw bytes to the VM's serial port (stdin of QEMU process).
+
+ Used to send keystrokes to the serial console (e.g., to dismiss
+ interactive prompts that appear before autoinstall takes over).
+ """
+ if self._process and self._process.stdin:
+ self._process.stdin.write(data)
+ self._process.stdin.flush()
+
+ def get_console_output(self, max_bytes: int = 2000) -> str:
+ """Get console output from the guest.
+
+ Flushes any buffered content and returns the last N bytes.
+
+ Args:
+ max_bytes: Maximum number of bytes to return.
+
+ Returns:
+ Console output string, truncated if necessary.
+ """
+ if not self._console_log:
+ return ""
+ try:
+ # Flush the console file if it's still open
+ if self._console_file is not None:
+ self._console_file.flush()
+ # Read the last N bytes of the log
+ if self._console_log.exists():
+ content = self._console_log.read_text()
+ return content[-max_bytes:] if len(content) > max_bytes else content
+ except Exception as e:
+ logger.debug(f"Failed to read console output: {e}")
+ return ""
+
+ def get_stderr(self) -> str:
+ """Get stderr output from the process."""
+ if self._process and self._process.stderr:
+ try:
+ return self._process.stderr.read().decode()
+ except Exception:
+ pass
+ return ""
+
+ def terminate(
+ self,
+ graceful_timeout: float = Timeouts.PROCESS_TERMINATE,
+ ) -> list[tuple[str, Exception]]:
+ """Terminate the QEMU process.
+
+ First attempts graceful termination, then forceful kill if needed.
+
+ Args:
+ graceful_timeout: Seconds to wait for graceful termination.
+
+ Returns:
+ List of (component, exception) tuples for any errors.
+ """
+ errors: list[tuple[str, Exception]] = []
+
+ # Close console file
+ if self._console_file is not None:
+ try:
+ self._console_file.close()
+ except Exception as e:
+ errors.append(("console file", e))
+ logger.warning("Failed to close console file: %s", e)
+ finally:
+ self._console_file = None
+
+ # Terminate process
+ if self._process:
+ pid = self._process.pid
+ try:
+ self._process.terminate()
+ try:
+ self._process.wait(timeout=graceful_timeout)
+ except subprocess.TimeoutExpired:
+ logger.warning(
+ "QEMU process %d did not terminate gracefully, sending SIGKILL", pid
+ )
+ self._process.kill()
+ self._process.wait(timeout=graceful_timeout)
+ except Exception as e:
+ errors.append(("QEMU process", e))
+ logger.error("Failed to terminate QEMU process (pid=%d): %s", pid, e)
+ # Try one more kill
+ if self._process.poll() is None:
+ with contextlib.suppress(Exception):
+ self._process.kill()
+ finally:
+ self._process = None
+
+ return errors
+
+ def check_exited(self) -> tuple[bool, str]:
+ """Check if the process has exited unexpectedly.
+
+ Returns:
+ Tuple of (has_exited, error_message).
+ """
+ if self._process is None:
+ return (True, "Process not started")
+
+ if self._process.poll() is not None:
+ stderr = self.get_stderr()
+ return (
+ True,
+ f"VM process exited unexpectedly (exit code: {self._process.returncode}).\n"
+ f"QEMU stderr:\n{stderr or '(empty)'}",
+ )
+
+ return (False, "")
diff --git a/packages/quicksand-core/quicksand_core/qemu/qmp.py b/packages/quicksand-core/quicksand_core/qemu/qmp.py
new file mode 100644
index 0000000..bda29e1
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/qmp.py
@@ -0,0 +1,314 @@
+"""QEMU Machine Protocol (QMP) client.
+
+QMP is a JSON-RPC protocol exposed by QEMU for host-side VM control
+(block device snapshots, pause/resume, status queries, etc.).
+It is NOT for executing commands inside the guest — that is the guest agent's job.
+
+We use TCP transport (127.0.0.1:port) so the same code works on all platforms.
+Unix sockets are not supported on Windows.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+import logging
+
+logger = logging.getLogger("quicksand.qmp")
+
+# ---------------------------------------------------------------------------
+# Character → QKeyCode mapping used by QMPClient.type_text()
+# ---------------------------------------------------------------------------
+# Each entry: char → (key_codes, needs_shift)
+# key_codes is the list of keys to pass to send-key (without the shift modifier).
+# ---------------------------------------------------------------------------
+
+_CHAR_TO_KEYS: dict[str, tuple[list[str], bool]] = {
+ # Lowercase letters
+ **{c: ([c], False) for c in "abcdefghijklmnopqrstuvwxyz"},
+ # Uppercase letters
+ **{c.upper(): ([c], True) for c in "abcdefghijklmnopqrstuvwxyz"},
+ # Digits
+ **{str(n): ([str(n)], False) for n in range(10)},
+ # Whitespace / control
+ " ": (["spc"], False),
+ "\n": (["ret"], False),
+ "\t": (["tab"], False),
+ # Unshifted symbols
+ "-": (["minus"], False),
+ "=": (["equal"], False),
+ "[": (["bracket_left"], False),
+ "]": (["bracket_right"], False),
+ "\\": (["backslash"], False),
+ ";": (["semicolon"], False),
+ "'": (["apostrophe"], False),
+ "`": (["grave_accent"], False),
+ ",": (["comma"], False),
+ ".": (["dot"], False),
+ "/": (["slash"], False),
+ # Shifted symbols
+ "!": (["1"], True),
+ "@": (["2"], True),
+ "#": (["3"], True),
+ "$": (["4"], True),
+ "%": (["5"], True),
+ "^": (["6"], True),
+ "&": (["7"], True),
+ "*": (["8"], True),
+ "(": (["9"], True),
+ ")": (["0"], True),
+ "_": (["minus"], True),
+ "+": (["equal"], True),
+ "{": (["bracket_left"], True),
+ "}": (["bracket_right"], True),
+ "|": (["backslash"], True),
+ ":": (["semicolon"], True),
+ '"': (["apostrophe"], True),
+ "~": (["grave_accent"], True),
+ "<": (["comma"], True),
+ ">": (["dot"], True),
+ "?": (["slash"], True),
+}
+
+
+class QMPClient:
+ """Async QMP client over TCP.
+
+ Usage:
+ client = QMPClient("127.0.0.1", port)
+ await client.connect(timeout=30)
+ await client.execute("blockdev-snapshot-sync",
+ device="drive0",
+ **{"snapshot-file": "/path/new.qcow2"},
+ format="qcow2")
+ await client.close()
+ """
+
+ def __init__(self, host: str, port: int) -> None:
+ self._host = host
+ self._port = port
+ self._reader: asyncio.StreamReader | None = None
+ self._writer: asyncio.StreamWriter | None = None
+ self._buf = ""
+
+ async def connect(self, timeout: float = 30.0) -> None:
+ """Connect and complete the QMP capability negotiation.
+
+ QEMU sends a greeting immediately on connect; we respond with
+ qmp_capabilities to enter command mode.
+
+ Raises:
+ TimeoutError: If QEMU does not accept the connection within timeout.
+ """
+ deadline = asyncio.get_event_loop().time() + timeout
+ last_exc: Exception = ConnectionRefusedError("QMP port not yet open")
+
+ while asyncio.get_event_loop().time() < deadline:
+ try:
+ reader, writer = await asyncio.wait_for(
+ asyncio.open_connection(self._host, self._port),
+ timeout=2.0,
+ )
+ self._reader = reader
+ self._writer = writer
+
+ # QEMU sends greeting immediately
+ greeting = await self._recv_json()
+ if "QMP" not in greeting:
+ raise RuntimeError(f"Unexpected QMP greeting: {greeting}")
+
+ # Enter command mode
+ await self._send_json({"execute": "qmp_capabilities"})
+ resp = await self._recv_json()
+ if "error" in resp:
+ raise RuntimeError(f"qmp_capabilities failed: {resp['error']}")
+
+ logger.debug("QMP connected on port %d", self._port)
+ return
+
+ except (ConnectionRefusedError, OSError) as e:
+ last_exc = e
+ if self._writer:
+ self._writer.close()
+ with contextlib.suppress(Exception):
+ await self._writer.wait_closed()
+ self._writer = None
+ self._reader = None
+ await asyncio.sleep(0.05)
+
+ raise TimeoutError(
+ f"Could not connect to QMP on 127.0.0.1:{self._port} within {timeout}s: {last_exc}"
+ )
+
+ async def execute(self, command: str, **arguments: object) -> dict:
+ """Send a QMP command and return the response.
+
+ Async events (prefixed with "event") that arrive before the response
+ are silently discarded — we only care about command responses here.
+
+ Args:
+ command: QMP command name (e.g. "blockdev-snapshot-sync").
+ **arguments: Command arguments. Use ** unpacking for hyphenated keys:
+ client.execute("cmd", **{"hyphen-key": value})
+
+ Returns:
+ The full QMP response dict (contains "return" or "error" key).
+
+ Raises:
+ RuntimeError: If not connected or QEMU returns an error.
+ """
+ if self._writer is None:
+ raise RuntimeError("QMPClient is not connected")
+
+ msg: dict = {"execute": command}
+ if arguments:
+ msg["arguments"] = arguments
+
+ await self._send_json(msg)
+
+ # Skip async events until we get the command response
+ while True:
+ resp = await self._recv_json()
+ if "return" in resp or "error" in resp:
+ if "error" in resp:
+ raise RuntimeError(f"QMP command '{command}' failed: {resp['error']}")
+ return resp
+ # Event — log and discard
+ logger.debug("QMP event: %s", resp.get("event", resp))
+
+ async def close(self) -> None:
+ """Close the QMP connection."""
+ if self._writer is not None:
+ try:
+ self._writer.close()
+ await self._writer.wait_closed()
+ except OSError:
+ pass
+ finally:
+ self._writer = None
+ self._reader = None
+
+ # ------------------------------------------------------------------
+ # Input injection
+ # ------------------------------------------------------------------
+
+ async def send_key(self, keys: list[str], hold_time: int = 100) -> None:
+ """Send a key combination to the guest.
+
+ Args:
+ keys: List of Key enum values or QKeyCode strings to press
+ simultaneously, e.g. [Key.CTRL, Key.C] or [Key.A].
+ hold_time: How long to hold the keys in milliseconds.
+ """
+ key_values = [{"type": "qcode", "data": k} for k in keys]
+ await self.execute("send-key", keys=key_values, **{"hold-time": hold_time})
+
+ async def input_send_event(self, events: list[dict]) -> None:
+ """Send raw input events via QMP input-send-event.
+
+ Each event dict must have "type" and "data" matching the QAPI InputEvent schema.
+ See: https://www.qemu.org/docs/master/interop/qemu-qmp-ref.html
+ """
+ await self.execute("input-send-event", events=events)
+
+ async def type_text(self, text: str) -> None:
+ """Type a string into the guest by sending key events per character.
+
+ Handles uppercase letters and common symbols via shift key combinations.
+ Unsupported characters are silently skipped.
+ """
+ for char in text:
+ mapping = _CHAR_TO_KEYS.get(char)
+ if mapping is None:
+ logger.debug("type_text: skipping unsupported character %r", char)
+ continue
+ key_codes, needs_shift = mapping
+ keys = (["shift", *key_codes]) if needs_shift else key_codes
+ # hold_time=1ms keeps the key press short so QMP returns fast.
+ # The default 100ms causes send-key to block for 100ms per character,
+ # making type_text take 3+ seconds for a typical command.
+ await self.send_key(keys, hold_time=1)
+
+ async def mouse_move(self, x: int, y: int) -> None:
+ """Move the mouse to absolute coordinates (0-32767 range).
+
+ Args:
+ x: Absolute X coordinate (0 = left, 32767 = right).
+ y: Absolute Y coordinate (0 = top, 32767 = bottom).
+ """
+ await self.input_send_event(
+ [
+ {"type": "abs", "data": {"axis": "x", "value": x}},
+ {"type": "abs", "data": {"axis": "y", "value": y}},
+ ]
+ )
+
+ async def mouse_click(self, button: str = "left", *, double: bool = False) -> None:
+ """Click a mouse button.
+
+ Args:
+ button: One of "left", "middle", "right", "wheel-up", "wheel-down".
+ double: If True, send two click sequences for a double-click.
+ """
+ down = {"type": "btn", "data": {"button": button, "down": True}}
+ up = {"type": "btn", "data": {"button": button, "down": False}}
+ # Send down and up as separate calls so window managers that trigger on
+ # "Press" (button-down only) — such as Openbox's root-window menu —
+ # see a distinct down event before the up arrives.
+ await self.input_send_event([down])
+ await self.input_send_event([up])
+ if double:
+ # Brief pause so the window manager registers a distinct second
+ # click rather than merging the events into one.
+ await asyncio.sleep(0.05)
+ await self.input_send_event([down])
+ await self.input_send_event([up])
+
+ async def screendump(self, path: str) -> None:
+ """Save the current guest display as an image file on the host.
+
+ QEMU writes the file directly; no guest involvement required.
+ Requires the VM to have a display device (enable_display=True in config).
+
+ Args:
+ path: Absolute host path for the output file (PNG or PPM).
+ """
+ await self.execute("screendump", filename=path)
+
+ # ------------------------------------------------------------------
+ # Query methods
+ # ------------------------------------------------------------------
+
+ async def query_mice(self) -> list[dict]:
+ """Query the connected mouse devices and current pointer position.
+
+ Returns a list of mouse device dicts. Each dict includes at least
+ ``name``, ``absolute`` (whether the device uses absolute coords),
+ and ``current`` (True for the active device).
+
+ Returns:
+ The raw QMP ``query-mice`` response list.
+ """
+ return (await self.execute("query-mice"))["return"]
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ async def _send_json(self, obj: dict) -> None:
+ assert self._writer is not None
+ data = (json.dumps(obj) + "\r\n").encode()
+ self._writer.write(data)
+ await self._writer.drain()
+
+ async def _recv_json(self) -> dict:
+ """Read one complete JSON line from the stream."""
+ assert self._reader is not None
+ while "\n" not in self._buf:
+ chunk = await self._reader.read(4096)
+ if not chunk:
+ raise ConnectionError("QMP connection closed by QEMU")
+ self._buf += chunk.decode()
+ line, self._buf = self._buf.split("\n", 1)
+ return json.loads(line.strip())
diff --git a/packages/quicksand-core/quicksand_core/qemu/save.py b/packages/quicksand-core/quicksand_core/qemu/save.py
new file mode 100644
index 0000000..8531c5b
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/save.py
@@ -0,0 +1,144 @@
+"""Save lifecycle operations for sandbox VMs."""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import shutil
+import subprocess
+from pathlib import Path
+
+from .._types import FilePatterns, SaveManifest
+
+logger = logging.getLogger("quicksand.save")
+
+SAVES_DIR = ".quicksand/sandboxes"
+"""Default directory for saves, relative to cwd."""
+
+SAVE_VERSION = 6
+
+
+class SaveWriter:
+ """Writes sandbox saves to disk.
+
+ Centralizes path construction, atomic writes, and overwrite semantics.
+ Saves are always written as directories under ``<workspace>/<name>/``.
+
+ Args:
+ name: Save name (e.g. "my-env").
+ workspace: Parent directory for saves. Defaults to ``$CWD/.quicksand/sandboxes/``.
+ """
+
+ def __init__(self, name: str, workspace: Path | None = None):
+ self.name = name
+ self.workspace = workspace or (Path.cwd() / SAVES_DIR)
+ self.path = self.workspace / name
+
+ def write(
+ self,
+ overlay_chain: list[Path],
+ manifest: SaveManifest,
+ *,
+ compress: bool = False,
+ qemu_img: Path | None = None,
+ backing_files: list[Path] | None = None,
+ ) -> SaveManifest:
+ """Write a save directory.
+
+ If a save already exists at this path, it is replaced atomically.
+ The manifest is pre-built by the caller; SaveWriter copies overlay
+ files and serializes the manifest to disk.
+
+ Args:
+ overlay_chain: Overlay files in bottom-to-top order.
+ manifest: Pre-built SaveManifest to serialize.
+ compress: Compress overlay qcow2 files to reduce save size.
+ Requires qemu_img. Slower but produces smaller saves.
+ qemu_img: Path to qemu-img binary (required if compress=True).
+ backing_files: Backing file for each overlay (parallel to
+ overlay_chain). Required when compress=True so that
+ ``qemu-img convert`` preserves the delta rather than
+ flattening the entire backing chain.
+
+ Returns:
+ The SaveManifest (same object passed in).
+ """
+ if compress and qemu_img is None:
+ raise ValueError("qemu_img path required when compress=True")
+ if compress and backing_files is None:
+ raise ValueError("backing_files required when compress=True")
+
+ self.workspace.mkdir(parents=True, exist_ok=True)
+
+ tmp_dir = self.path.parent / f"{self.name}.tmp"
+ try:
+ # Write to tmp directory first for crash safety
+ if tmp_dir.exists():
+ shutil.rmtree(tmp_dir)
+ tmp_dir.mkdir(parents=True)
+ overlays_dir = tmp_dir / FilePatterns.OVERLAYS_DIR
+ overlays_dir.mkdir()
+
+ for i, overlay_path in enumerate(overlay_chain):
+ dest = overlays_dir / f"{i}.qcow2"
+ if compress:
+ assert qemu_img is not None and backing_files is not None
+ self._compress_overlay(qemu_img, overlay_path, dest, backing=backing_files[i])
+ else:
+ shutil.copy2(overlay_path, dest)
+
+ # Write manifest
+ (tmp_dir / FilePatterns.MANIFEST).write_text(manifest.model_dump_json(indent=2))
+
+ # Atomic swap: remove old, rename tmp -> final
+ if self.path.exists():
+ shutil.rmtree(self.path)
+ tmp_dir.rename(self.path)
+
+ return manifest
+
+ except Exception:
+ with contextlib.suppress(OSError):
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ raise
+
+ @staticmethod
+ def _compress_overlay(qemu_img: Path, src: Path, dest: Path, *, backing: Path) -> None:
+ """Compress a qcow2 overlay using qemu-img convert -c.
+
+ ``-B`` preserves the overlay's backing file reference so that only
+ the delta clusters are written (and compressed). Without it,
+ ``qemu-img convert`` flattens the entire backing chain into the
+ destination, producing a much larger standalone image.
+ """
+ result = subprocess.run(
+ [
+ str(qemu_img),
+ "convert",
+ "-f",
+ "qcow2",
+ "-O",
+ "qcow2",
+ "-c",
+ "-B",
+ str(backing),
+ "-F",
+ "qcow2",
+ str(src),
+ str(dest),
+ ],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"Failed to compress overlay: {result.stderr}")
+
+
+def _get_version() -> str:
+ """Get the quicksand-core version without circular imports."""
+ try:
+ from importlib.metadata import version
+
+ return version("quicksand-core")
+ except Exception:
+ return "unknown"
diff --git a/packages/quicksand-core/quicksand_core/sandbox/__init__.py b/packages/quicksand-core/quicksand_core/sandbox/__init__.py
new file mode 100644
index 0000000..16530b9
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/__init__.py
@@ -0,0 +1,6 @@
+"""Sandbox package — re-exports the public surface."""
+
+from .._types import ExecuteResult, SandboxConfig, SandboxConfigParams
+from ._sandbox import Sandbox
+
+__all__ = ["ExecuteResult", "Sandbox", "SandboxConfig", "SandboxConfigParams"]
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_checkpoints.py b/packages/quicksand-core/quicksand_core/sandbox/_checkpoints.py
new file mode 100644
index 0000000..7badce6
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_checkpoints.py
@@ -0,0 +1,71 @@
+"""Ephemeral in-session QMP snapshot operations (checkpoint/revert) for the Sandbox class."""
+
+from __future__ import annotations
+
+import logging
+
+from ._protocol import _SandboxProtocol
+
+logger = logging.getLogger("quicksand.sandbox")
+
+
+class _CheckpointMixin(_SandboxProtocol):
+ """Mixin providing ephemeral in-session QMP snapshots: checkpoint and revert.
+
+ Dependencies (is_running, _qmp_client, _qmp_checkpoints) are declared
+ by _SandboxProtocol.
+ """
+
+ async def checkpoint(self, tag: str) -> None:
+ """Save the current VM state (RAM + disk) as an ephemeral in-session snapshot.
+
+ The snapshot lives only in the current session's overlay. It is NOT
+ persisted to disk and is NOT included when save() is called — save()
+ deletes all checkpoint snapshots before freezing the overlay.
+
+ Use checkpoint/revert for in-session branching and rollback:
+
+ await sb.checkpoint("before-install")
+ await sb.execute("pip install heavy-package")
+ # something went wrong — roll back
+ await sb.revert("before-install")
+
+ Args:
+ tag: Name for the snapshot (e.g. "before-install").
+ """
+ if not self.is_running:
+ raise RuntimeError("Cannot checkpoint a non-running sandbox")
+ if self._qmp_client is None:
+ raise RuntimeError("QMP is not connected")
+ await self._qmp_client.execute(
+ "human-monitor-command",
+ **{"command-line": f"savevm {tag}"},
+ )
+ if tag not in self._qmp_checkpoints:
+ self._qmp_checkpoints.append(tag)
+
+ async def revert(self, tag: str) -> None:
+ """Restore the VM state (RAM + disk) from an ephemeral in-session snapshot.
+
+ The VM resumes execution from the point when checkpoint(tag) was called.
+ Only snapshots created in the current session are restorable.
+
+ Args:
+ tag: Name of the snapshot to restore.
+
+ Raises:
+ ValueError: If no snapshot with that tag exists in this session.
+ """
+ if not self.is_running:
+ raise RuntimeError("Cannot revert a non-running sandbox")
+ if self._qmp_client is None:
+ raise RuntimeError("QMP is not connected")
+ if tag not in self._qmp_checkpoints:
+ available = self._qmp_checkpoints or ["(none)"]
+ raise ValueError(
+ f"No checkpoint '{tag}' in current session. Available: {', '.join(available)}"
+ )
+ await self._qmp_client.execute(
+ "human-monitor-command",
+ **{"command-line": f"loadvm {tag}"},
+ )
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_execution.py b/packages/quicksand-core/quicksand_core/sandbox/_execution.py
new file mode 100644
index 0000000..c0472ab
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_execution.py
@@ -0,0 +1,92 @@
+"""Execution mixin — command execution methods for the Sandbox class.
+
+Analogous to an API router: groups the 'commands' concern.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from dataclasses import asdict
+
+from .._types import (
+ AgentErrorBody,
+ ExecuteParams,
+ ExecuteResponseResult,
+ ExecuteResult,
+ GuestCommands,
+ QuicksandGuestAgentMethod,
+ Timeouts,
+)
+from ._protocol import _SandboxProtocol
+
+
+class _ExecutionMixin(_SandboxProtocol):
+ """Mixin providing command execution via the guest agent.
+
+ Analogous to an API router for the 'commands' concern.
+ Dependencies (is_running, _send_request) are declared by _SandboxProtocol.
+ """
+
+ async def execute(
+ self,
+ command: str,
+ timeout: float = Timeouts.GUEST_AGENT_REQUEST,
+ cwd: str | None = None,
+ shell: str = GuestCommands.SHELL,
+ on_stdout: Callable[[str], None] | None = None,
+ on_stderr: Callable[[str], None] | None = None,
+ exclusive: bool = False,
+ ) -> ExecuteResult:
+ """
+ Execute a shell command inside the sandbox.
+
+ Args:
+ command: The shell command to execute.
+ timeout: Maximum execution time in seconds.
+ cwd: Working directory for the command.
+ shell: Shell to use for execution (default: /bin/sh).
+ Common options: /bin/sh, /bin/bash, /bin/zsh
+ on_stdout: Optional callback invoked with each chunk of stdout
+ as it arrives. When provided, the command is executed
+ in streaming mode via SSE.
+ on_stderr: Optional callback invoked with each chunk of stderr
+ as it arrives. When provided, the command is executed
+ in streaming mode via SSE.
+ exclusive: If True, the guest agent will reject other requests
+ while this command is running. Used for system commands
+ like sync/fstrim that need exclusive access.
+
+ Returns:
+ ExecuteResult with stdout, stderr, and exit_code.
+ """
+ if not self.is_running:
+ raise RuntimeError("Sandbox is not running")
+
+ params = ExecuteParams(
+ command=command, timeout=timeout, shell=shell, cwd=cwd, exclusive=exclusive
+ )
+ params_dict = {k: v for k, v in asdict(params).items() if v is not None}
+
+ if on_stdout is not None or on_stderr is not None:
+ client = self._agent_client
+ if client is None:
+ raise RuntimeError("Not connected to guest agent")
+ response = await client.send_stream_request(
+ params_dict,
+ timeout=timeout + 5,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ )
+ else:
+ response = await self._send_request(
+ QuicksandGuestAgentMethod.EXECUTE,
+ params_dict,
+ timeout=timeout + 5,
+ )
+
+ if "error" in response:
+ error = AgentErrorBody(**response["error"])
+ return ExecuteResult(stdout="", stderr=error.message, exit_code=-1)
+
+ result = ExecuteResponseResult(**response["result"])
+ return ExecuteResult(stdout=result.stdout, stderr=result.stderr, exit_code=result.exit_code)
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_input.py b/packages/quicksand-core/quicksand_core/sandbox/_input.py
new file mode 100644
index 0000000..be5a774
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_input.py
@@ -0,0 +1,222 @@
+"""Input injection mixin — keyboard, mouse, and screenshot operations."""
+
+from __future__ import annotations
+
+import contextlib
+import struct
+import zlib
+from pathlib import Path
+
+from ._protocol import _SandboxProtocol
+
+
+def _convert_to_png(src: str, dst: str) -> None:
+ """Convert *src* (PPM or PNG) to a proper PNG at *dst*.
+
+ QEMU's screendump writes PPM binary (P6) even when the filename ends in
+ .png, because many QEMU builds lack PNG support. This function reads the
+ raw RGB data from the PPM and writes a spec-compliant PNG using only the
+ Python standard library (struct + zlib). If *src* already starts with the
+ PNG magic bytes it is simply copied as-is.
+ """
+ raw = Path(src).read_bytes()
+
+ # Already a real PNG — just copy.
+ if raw[:8] == b"\x89PNG\r\n\x1a\n":
+ Path(dst).write_bytes(raw)
+ return
+
+ # Parse PPM P6 header: "P6\n<width> <height>\n<maxval>\n<data>"
+ if not raw.startswith(b"P6"):
+ raise ValueError(f"Unsupported screendump format in {src!r} (expected P6 PPM or PNG)")
+
+ lines = raw.split(b"\n", 3)
+ # Skip comment lines (lines starting with '#')
+ header_parts: list[bytes] = []
+ pos = 0
+ for line in lines[:3]:
+ if line.startswith(b"#"):
+ pos += len(line) + 1
+ continue
+ header_parts.append(line)
+ pos += len(line) + 1
+ if len(header_parts) == 3:
+ break
+
+ width, height = map(int, header_parts[1].split())
+ pixels = raw[pos:] # 3 bytes per pixel (R, G, B)
+
+ def _png_chunk(tag: bytes, data: bytes) -> bytes:
+ length = struct.pack(">I", len(data))
+ body = tag + data
+ crc = struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
+ return length + body + crc
+
+ # IHDR: width, height, bit_depth=8, color_type=2 (RGB), compress=0, filter=0, interlace=0
+ ihdr_data = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
+
+ # Build filtered scanlines (filter type 0 = None for each row)
+ row_size = width * 3
+ scanlines = bytearray()
+ for y in range(height):
+ scanlines.append(0) # filter byte
+ scanlines.extend(pixels[y * row_size : (y + 1) * row_size])
+
+ idat_data = zlib.compress(bytes(scanlines), level=1)
+
+ png = (
+ b"\x89PNG\r\n\x1a\n"
+ + _png_chunk(b"IHDR", ihdr_data)
+ + _png_chunk(b"IDAT", idat_data)
+ + _png_chunk(b"IEND", b"")
+ )
+ Path(dst).write_bytes(png)
+
+
+class _InputMixin(_SandboxProtocol):
+ """Mixin providing input injection and screenshot operations via QMP.
+
+ Requires ``enable_display=True`` in the sandbox config. All methods
+ raise ``RuntimeError`` if called when the sandbox is not running or
+ display is not enabled.
+ """
+
+ def _require_display(self) -> None:
+ if not self.is_running:
+ raise RuntimeError("Sandbox is not running")
+ if not self.config.enable_display:
+ raise RuntimeError("Display is not enabled. Set enable_display=True in SandboxConfig.")
+ if self._qmp_client is None:
+ raise RuntimeError("QMP client is not connected")
+
+ async def type_text(self, text: str) -> None:
+ """Type a string into the guest via keyboard events.
+
+ Characters that have no QKeyCode mapping are silently skipped.
+ Requires ``enable_display=True``.
+ """
+ self._require_display()
+ assert self._qmp_client is not None
+ await self._qmp_client.type_text(text)
+
+ async def press_key(self, *keys: str) -> None:
+ """Press a key or key combination in the guest.
+
+ Args:
+ *keys: Key enum values or QKeyCode strings, e.g.
+ ``press_key(Key.CTRL, Key.C)`` or ``press_key(Key.RET)``.
+ Requires ``enable_display=True``.
+ """
+ self._require_display()
+ assert self._qmp_client is not None
+ await self._qmp_client.send_key(list(keys))
+
+ async def mouse_move(self, x: int, y: int) -> None:
+ """Move the mouse to absolute coordinates.
+
+ Args:
+ x: Absolute X position in the range 0-32767.
+ y: Absolute Y position in the range 0-32767.
+ Requires ``enable_display=True``.
+ """
+ self._require_display()
+ assert self._qmp_client is not None
+ await self._qmp_client.mouse_move(x, y)
+
+ async def mouse_click(self, button: str = "left", *, double: bool = False) -> None:
+ """Click a mouse button.
+
+ Args:
+ button: ``"left"``, ``"middle"``, ``"right"``,
+ ``"wheel-up"``, or ``"wheel-down"``.
+ double: If ``True``, send a double-click.
+ Requires ``enable_display=True``.
+ """
+ self._require_display()
+ assert self._qmp_client is not None
+ await self._qmp_client.mouse_click(button, double=double)
+
+ async def screenshot(self, path: str | Path) -> None:
+ """Save the current guest display as a PNG file on the host.
+
+ QEMU writes the raw framebuffer; this method converts it to a proper
+ PNG regardless of whether QEMU was compiled with PNG support (it often
+ outputs PPM binary data even when given a .png filename).
+
+ Args:
+ path: Destination path on the host for the PNG file.
+ Requires ``enable_display=True``.
+ """
+ import tempfile
+
+ self._require_display()
+ assert self._qmp_client is not None
+
+ dest = Path(path).resolve()
+ dest.parent.mkdir(parents=True, exist_ok=True)
+
+ # Capture to a temp file so we can inspect and convert if needed.
+ with tempfile.NamedTemporaryFile(suffix=".ppm", delete=False) as tmp:
+ tmp_path = tmp.name
+
+ try:
+ await self._qmp_client.screendump(tmp_path)
+ _convert_to_png(tmp_path, str(dest))
+ finally:
+ with contextlib.suppress(OSError):
+ Path(tmp_path).unlink()
+
+ async def query_display_size(self) -> tuple[int, int]:
+ """Return the guest display resolution as ``(width, height)`` in pixels.
+
+ Takes a screendump and reads the PPM header to get the actual
+ framebuffer dimensions. There is no QMP command that directly
+ returns the display resolution.
+
+ Requires ``enable_display=True``.
+ """
+ import tempfile
+
+ self._require_display()
+ assert self._qmp_client is not None
+
+ with tempfile.NamedTemporaryFile(suffix=".ppm", delete=False) as tmp:
+ tmp_path = tmp.name
+
+ try:
+ await self._qmp_client.screendump(tmp_path)
+ header = Path(tmp_path).read_bytes()[:128]
+ # PPM P6 header: "P6\n<width> <height>\n<maxval>\n"
+ # Skip comment lines starting with '#'
+ lines = header.split(b"\n")
+ data_lines = [line for line in lines if not line.startswith(b"#")]
+ if len(data_lines) >= 2 and data_lines[0] == b"P6":
+ parts = data_lines[1].split()
+ width, height = int(parts[0]), int(parts[1])
+ return (width, height)
+ return (0, 0)
+ finally:
+ with contextlib.suppress(OSError):
+ Path(tmp_path).unlink()
+
+ async def query_mouse_position(self) -> dict | None:
+ """Return information about the current mouse device and position.
+
+ Returns the dict for the currently-active mouse device from QMP
+ ``query-mice``, or ``None`` if no mouse device is found. The dict
+ includes at least ``name``, ``absolute``, and ``current``.
+
+ Requires ``enable_display=True``.
+ """
+ self._require_display()
+ assert self._qmp_client is not None
+ mice = await self._qmp_client.query_mice()
+ for mouse in mice:
+ if mouse.get("current"):
+ return mouse
+ return mice[0] if mice else None
+
+ @property
+ def vnc_port(self) -> int | None:
+ """The host-side VNC port, or ``None`` if display is not enabled."""
+ return self._vnc_port
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_lifecycle.py b/packages/quicksand-core/quicksand_core/sandbox/_lifecycle.py
new file mode 100644
index 0000000..b95f082
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_lifecycle.py
@@ -0,0 +1,407 @@
+"""Lifecycle mixin — VM start, stop, and cleanup methods for the Sandbox class."""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import secrets
+import shutil
+import tempfile
+import warnings
+from collections.abc import Callable
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from .._types import (
+ EnvironmentVariables,
+ FilePatterns,
+ NetworkMode,
+ ResolvedAccelerator,
+ Timeouts,
+)
+from ..host.quicksand_guest_agent_client import QuicksandGuestAgentClient
+from ..qemu import OverlayManager
+from ..qemu.platform import get_platform_config, get_platform_config_for_arch, get_runtime
+from ._protocol import _SandboxProtocol
+
+if TYPE_CHECKING:
+ from ..qemu.platform import PlatformConfig
+
+logger = logging.getLogger("quicksand.sandbox")
+
+
+class _LifecycleMixin(_SandboxProtocol):
+ """Mixin providing VM lifecycle operations: start phases, stop, and cleanup."""
+
+ # ------------------------------------------------------------------
+ # start() sub-phases
+ # ------------------------------------------------------------------
+
+ def _get_platform_config(self) -> PlatformConfig:
+ """Get platform config, using guest arch when loading a cross-arch save."""
+ if self._image and self._image.guest_arch:
+ return get_platform_config_for_arch(self._image.guest_arch)
+ return get_platform_config()
+
+ def _resolve_image(self) -> None:
+ """Resolve config.image to concrete paths using ImageResolver."""
+ from ..qemu.image_resolver import ImageResolver
+
+ self._image = ImageResolver().resolve(self.config.image, arch=self.config.arch)
+
+ def _detect_accelerator(self) -> None:
+ """Resolve config.accel to a concrete Accelerator and adjust boot timeout."""
+ from ..host import Accelerator
+
+ # Cross-arch saves always require TCG (software emulation)
+ if self._image and self._image.guest_arch:
+ self._accel = ResolvedAccelerator(
+ accel=Accelerator.TCG,
+ nested_virt=False,
+ boot_timeout=Timeouts.BOOT_TCG,
+ )
+ logger.warning(
+ "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
+ " WARNING: QEMU is using TCG (pure software emulation).\n"
+ " Hardware acceleration (KVM/HVF) is not available.\n"
+ " Performance will be 10-20x slower than normal.\n"
+ " Boot timeout increased to %ss.\n"
+ "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",
+ Timeouts.BOOT_TCG,
+ )
+ return
+
+ nested = False
+ if self.config.accel == "auto":
+ status = self._get_platform_config().detect_accelerator()
+ accel = status.accelerator
+ nested = status.nested
+ elif self.config.accel is None:
+ accel = Accelerator.TCG
+ else:
+ accel = self.config.accel
+
+ boot_timeout = self.config.boot_timeout
+
+ if accel == Accelerator.TCG and boot_timeout == Timeouts.BOOT_DEFAULT:
+ boot_timeout = Timeouts.BOOT_TCG
+ logger.warning(
+ "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
+ " WARNING: QEMU is using TCG (pure software emulation).\n"
+ " Hardware acceleration (KVM/HVF) is not available.\n"
+ " Performance will be 10-20x slower than normal.\n"
+ " Boot timeout increased to %ss.\n"
+ "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",
+ boot_timeout,
+ )
+
+ if accel == Accelerator.WHPX and boot_timeout == Timeouts.BOOT_DEFAULT:
+ boot_timeout = Timeouts.BOOT_WHPX
+ logger.info("Using WHPX - increasing boot timeout to %ss", boot_timeout)
+
+ self._accel = ResolvedAccelerator(
+ accel=accel,
+ nested_virt=nested,
+ boot_timeout=boot_timeout,
+ )
+
+ def _load_runtime(self) -> None:
+ """Fetch the QEMU runtime.
+
+ For cross-arch saves, resolves the QEMU binary for the guest architecture.
+ """
+ self._runtime_info = get_runtime(self._get_platform_config())
+ self._overlay_manager = OverlayManager(self._runtime_info.qemu_img)
+
+ def _setup_disk(self) -> None:
+ """Create the working directory and qcow2 overlay (fresh or restored from save).
+
+ If ``_image.overlays`` is set (save or overlay package), the
+ overlay chain is restored. Otherwise a fresh overlay is created.
+ """
+ self._temp_dir = Path(tempfile.mkdtemp(prefix="quicksand-"))
+ self._overlay_path = self._temp_dir / FilePatterns.OVERLAY
+ self._create_overlay()
+
+ def _launch_process(self) -> None:
+ """Generate agent credentials, build the VM command, and start QEMU."""
+ from ..utils import find_free_port, find_free_vnc_port
+
+ self._agent_token = secrets.token_hex(16)
+ self._agent_port = find_free_port()
+ self._qmp_port = find_free_port()
+
+ if self.config.enable_display:
+ self._vnc_port = find_free_vnc_port()
+
+ # Create virtio-serial socket path for agent communication.
+ assert self._temp_dir is not None
+ self._agent_socket_path = self._temp_dir / "agent.sock"
+
+ # Start the SMB server early so the guestfwd command can be embedded
+ # in the QEMU command line. QuicksandSMBServer uses guestfwd in all
+ # modes (no TCP port), so we always start it when mounts are possible.
+ if self.config.network_mode in (NetworkMode.MOUNTS_ONLY, NetworkMode.FULL):
+ self._ensure_smb_server()
+
+ cmd = self._build_vm_command()
+ logger.debug(
+ "Starting VM: port=%s, image=%s",
+ self._agent_port,
+ self._image.chain[0] if self._image else None,
+ )
+ logger.debug("QEMU command: %s", " ".join(str(c) for c in cmd))
+
+ env = os.environ.copy()
+ if (
+ self._runtime_info is not None
+ and self._runtime_info.module_dir is not None
+ and self._runtime_info.module_dir.exists()
+ ):
+ env[EnvironmentVariables.QEMU_MODULE_DIR] = str(self._runtime_info.module_dir)
+
+ assert self._temp_dir is not None
+ console_log_path = self._temp_dir / FilePatterns.CONSOLE_LOG
+ self._process_manager.start(cmd, env, console_log_path)
+
+ async def _connect_to_guest_agent(self) -> None:
+ """Wait for the guest agent; clean up and re-raise on failure."""
+ try:
+ await self._wait_for_guest_agent()
+ except Exception as e:
+ console_output = self._get_console_output()
+ await self._cleanup()
+ error_msg = f"Failed to connect to guest agent: {e}"
+ if console_output:
+ error_msg += f"\n\nConsole output (last 2KB):\n{console_output}"
+ raise RuntimeError(error_msg) from e
+
+ async def _connect_to_qmp(self) -> None:
+ """Connect the QMP client. Required for checkpointing."""
+ from ..qemu.qmp import QMPClient
+
+ assert self._qmp_port is not None
+ assert self._accel is not None
+ client = QMPClient("127.0.0.1", self._qmp_port)
+ await client.connect(timeout=self._accel.boot_timeout)
+ self._qmp_client = client
+ logger.debug("QMP client connected on port %d", self._qmp_port)
+
+ async def _post_boot_setup(self) -> None:
+ """Expand the filesystem (non-fatal) and mount shares (fatal on failure)."""
+ if self.config.disk_size:
+ try:
+ await self._expand_guest_filesystem()
+ except Exception as e:
+ logger.warning(f"Failed to expand filesystem: {e}")
+
+ if self.config.mounts:
+ try:
+ await self._mount_shares()
+ except Exception as e:
+ await self._cleanup()
+ raise RuntimeError(f"Failed to mount shares: {e}") from e
+
+ # ------------------------------------------------------------------
+ # start() helpers
+ # ------------------------------------------------------------------
+
+ def _create_overlay(self) -> None:
+ assert self._overlay_manager is not None
+ assert self._image is not None
+ assert self._overlay_path is not None
+
+ self._overlay_manager.create_overlay(
+ self._image.chain[0],
+ self._overlay_path,
+ restore_chain=self._image.chain[1:] or None,
+ disk_size=self.config.disk_size,
+ )
+
+ async def _expand_guest_filesystem(self) -> None:
+ from .._types import GuestCommands
+
+ logger.debug("Expanding guest filesystem")
+ result = await self.execute(GuestCommands.DETECT_DISK_LAYOUT, timeout=30.0)
+ disk_layout = result.stdout.strip()
+ logger.debug(f"Disk layout: {disk_layout}")
+
+ if disk_layout == "partitioned":
+ result = await self.execute(GuestCommands.GROWPART, timeout=30.0)
+ logger.debug(f"growpart output: {result.stdout}")
+ await self.execute(GuestCommands.RESIZE_PARTITION, timeout=30.0)
+ else:
+ result = await self.execute(GuestCommands.RESIZE_WHOLE_DISK, timeout=30.0)
+
+ logger.debug(f"Filesystem resize output: {result.stdout}")
+
+ def _build_vm_command(self) -> list[str]:
+ assert self._runtime_info is not None
+ assert self._overlay_path is not None
+ assert self._agent_port is not None
+ assert self._agent_token is not None
+ assert self._accel is not None
+
+ platform = self._get_platform_config()
+
+ smb_port = self._smb_server.port if self._smb_server is not None else None
+
+ return platform.build_qemu_command(
+ config=self.config,
+ runtime_info=self._runtime_info,
+ kernel_path=self._image.kernel if self._image else None,
+ initrd_path=self._image.initrd if self._image else None,
+ overlay_path=self._overlay_path,
+ agent_port=self._agent_port,
+ agent_token=self._agent_token,
+ accelerator=self._accel.accel,
+ nested_virt=self._accel.nested_virt,
+ qmp_port=self._qmp_port,
+ vnc_port=self._vnc_port,
+ smb_port=smb_port,
+ smb_server=self._smb_server,
+ agent_socket_path=self._agent_socket_path,
+ )
+
+ async def _wait_for_guest_agent(self) -> None:
+ assert self._agent_port is not None
+ assert self._agent_token is not None
+ assert self._accel is not None
+ assert self._process_manager.is_running
+
+ def check_process() -> tuple[bool, str]:
+ exited, error_info = self._process_manager.check_exited()
+ if exited:
+ return (False, error_info)
+ return (True, "")
+
+ # Try virtio-serial first (faster: no guest networking dependency).
+ # Fall back to HTTP if the socket path doesn't exist or connection fails.
+ if self._agent_socket_path is not None:
+ try:
+ from ..host.virtio_serial_agent_client import VirtioSerialAgentClient
+
+ client = VirtioSerialAgentClient(self._agent_socket_path, self._agent_token)
+ await client.connect(
+ timeout=self._accel.boot_timeout,
+ process_check=check_process,
+ )
+ self._agent_client = client
+ logger.debug("Connected to agent via virtio-serial")
+ return
+ except (TimeoutError, RuntimeError, OSError) as e:
+ logger.debug("Virtio-serial connection failed, falling back to HTTP: %s", e)
+
+ # Fallback: HTTP via hostfwd
+ self._agent_client = QuicksandGuestAgentClient(self._agent_port, self._agent_token)
+
+ try:
+ await self._agent_client.connect(
+ timeout=self._accel.boot_timeout,
+ process_check=check_process,
+ )
+ except TimeoutError as e:
+ console_output = self._get_console_output(max_bytes=4000)
+ qemu_running = self._process_manager.is_running
+ stderr = self._process_manager.get_stderr() if not qemu_running else ""
+ raise TimeoutError(
+ f"Could not connect to agent within "
+ f"{self._accel.boot_timeout}s.\n"
+ f"Agent port: {self._agent_port}\n"
+ f"QEMU process running: {qemu_running}\n"
+ f"Original error: {e}\n"
+ f"QEMU stderr: {stderr or '(empty)'}\n"
+ f"Console output (last 4KB):\n{console_output or '(empty)'}"
+ ) from e
+
+ # ------------------------------------------------------------------
+ # stop() helpers
+ # ------------------------------------------------------------------
+
+ async def _cleanup(self) -> None:
+ """Clean up resources. Logs errors but continues cleanup."""
+ self._is_running = False
+ cleanup_errors: list[tuple[str, Exception]] = []
+
+ cleanup_errors.extend(await self._cleanup_mounts())
+
+ if self._agent_client:
+ try:
+ await self._agent_client.close()
+ except Exception as e:
+ cleanup_errors.append(("agent client", e))
+ logger.warning("Failed to close agent client: %s", e)
+ finally:
+ self._agent_client = None
+
+ if self._qmp_client:
+ with contextlib.suppress(Exception):
+ await self._qmp_client.close()
+ self._qmp_client = None
+
+ process_errors = self._process_manager.terminate()
+ cleanup_errors.extend(process_errors)
+
+ if self._temp_dir and self._temp_dir.exists():
+ try:
+ shutil.rmtree(self._temp_dir)
+ except Exception as e:
+ cleanup_errors.append(("temp directory", e))
+ logger.error(
+ "Failed to remove temp directory %s: %s. "
+ "You may need to manually clean up /tmp/quicksand-* directories.",
+ self._temp_dir,
+ e,
+ )
+ finally:
+ self._temp_dir = None
+
+ self._overlay_path = None
+ self._agent_port = None
+ self._agent_token = None
+ self._agent_socket_path = None
+
+ if cleanup_errors:
+ error_summary = "; ".join(f"{resource}: {err}" for resource, err in cleanup_errors)
+ warnings.warn(
+ f"Sandbox cleanup completed with errors: {error_summary}",
+ ResourceWarning,
+ stacklevel=2,
+ )
+
+ async def _graceful_shutdown(self) -> None:
+ if not self._is_running:
+ return
+
+ from .._types import GuestCommands
+
+ with contextlib.suppress(Exception):
+ await self.execute(GuestCommands.SYNC, timeout=Timeouts.MOUNT_OPERATION)
+
+ if self._agent_client is not None:
+ with contextlib.suppress(Exception):
+ await self._agent_client.close()
+
+ if self._qmp_client is not None:
+ with contextlib.suppress(Exception):
+ await self._qmp_client.close()
+ self._qmp_client = None
+
+ self._process_manager.terminate(graceful_timeout=Timeouts.GRACEFUL_SHUTDOWN)
+ self._is_running = False
+ self._agent_client = None
+
+ # ------------------------------------------------------------------
+ # Utilities
+ # ------------------------------------------------------------------
+
+ def _make_progress_cb(self, stage: str) -> Callable[[int, int], None]:
+ def cb(downloaded: int, total: int) -> None:
+ if self._progress_callback:
+ self._progress_callback(stage, downloaded, total)
+
+ return cb
+
+ def _get_console_output(self, max_bytes: int = 2000) -> str:
+ return self._process_manager.get_console_output(max_bytes)
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_mounts.py b/packages/quicksand-core/quicksand_core/sandbox/_mounts.py
new file mode 100644
index 0000000..1d1ed15
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_mounts.py
@@ -0,0 +1,257 @@
+"""Mount mixin — host-guest filesystem mounting operations for the Sandbox class.
+
+Boot-time mounts support two protocols:
+- ``cifs`` (default): CIFS/SMB3 over QEMU slirp networking. Hot-pluggable via
+ mount()/unmount(). Requires network_mode=FULL or MOUNTS_ONLY.
+- ``9p``: virtio-9p device configured at QEMU startup. No network required;
+ works with network_mode=NONE. Init-time only (not hot-pluggable).
+
+The SMB server is lazily started only when CIFS mounts are present.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+
+from .._types import MountHandle, MountOptions, NetworkConstants, NetworkMode, Timeouts
+from ..host.smb import SMBServer, create_smb_server
+from ._protocol import _SandboxProtocol
+
+logger = logging.getLogger("quicksand.mounts")
+
+
+class _MountMixin(_SandboxProtocol):
+ """Mixin providing host-guest mount operations via CIFS.
+
+ Supports both boot-time mounts (from config.mounts) and dynamic
+ mounts via mount()/unmount() on a running sandbox.
+ """
+
+ def _ensure_smb_server(self) -> SMBServer:
+ """Lazily start the SMB server on first mount."""
+ if self._smb_server is None:
+ self._smb_server = create_smb_server()
+ self._smb_server.start()
+ return self._smb_server
+
+ async def _mount_9p_share(self, tag: str, guest_path: str, readonly: bool) -> None:
+ """Mount a virtio-9p share inside the guest."""
+ await self.execute(
+ f"sudo mkdir -p {guest_path}",
+ timeout=Timeouts.MOUNT_OPERATION,
+ )
+ ro_opt = ",ro" if readonly else ""
+ result = await self.execute(
+ f"sudo mount -t 9p -o trans=virtio,version=9p2000.L{ro_opt} {tag} {guest_path}",
+ timeout=Timeouts.MOUNT_OPERATION,
+ )
+ if result.exit_code != 0:
+ raise RuntimeError(
+ f"Failed to mount 9p share {tag} at {guest_path}: {result.stderr or result.stdout}"
+ )
+
+ async def _mount_cifs_share(self, share_name: str, guest_path: str, readonly: bool) -> None:
+ """Mount a single CIFS share inside the guest."""
+ assert self._smb_server is not None
+
+ await self.execute(
+ f"sudo mkdir -p {guest_path}",
+ timeout=Timeouts.MOUNT_OPERATION,
+ )
+
+ ro_opt = ",ro" if readonly else ""
+
+ # QuicksandSMBServer uses guestfwd in ALL modes (no TCP port).
+ # SambaSMBServer uses guestfwd in MOUNTS_ONLY, direct TCP in FULL.
+ uses_guestfwd = self._smb_server.get_guestfwd_cmd() is not None
+
+ if uses_guestfwd or self.config.network_mode is NetworkMode.MOUNTS_ONLY:
+ gateway = NetworkConstants.GUESTFWD_SMB_IP
+ port = NetworkConstants.GUESTFWD_SMB_PORT
+ else:
+ gateway = NetworkConstants.QEMU_SLIRP_GATEWAY
+ port = self._smb_server.port
+
+ username, password = self._smb_server.credentials
+ cifs_opts = MountOptions.cifs_opts(username, password)
+ mount_cmd = (
+ f"sudo mount -t cifs //{gateway}/{share_name} {guest_path} "
+ f"-o {cifs_opts},port={port}{ro_opt}"
+ )
+
+ last_error = ""
+ for attempt in range(MountOptions.MAX_RETRIES):
+ result = await self.execute(mount_cmd, timeout=Timeouts.MOUNT_OPERATION)
+ if result.exit_code == 0:
+ return
+ last_error = result.stderr or result.stdout
+ if attempt < MountOptions.MAX_RETRIES - 1:
+ logger.debug(
+ "Mount attempt %d/%d failed for %s, retrying in %ss: %s",
+ attempt + 1,
+ MountOptions.MAX_RETRIES,
+ share_name,
+ MountOptions.RETRY_DELAY,
+ last_error,
+ )
+ await asyncio.sleep(MountOptions.RETRY_DELAY)
+
+ raise RuntimeError(f"Failed to mount CIFS share {share_name}: {last_error}")
+
+ async def _mount_shares(self) -> None:
+ """Mount boot-time shares (from config.mounts) using CIFS or 9p."""
+ if not self.config.mounts:
+ return
+
+ cifs_mounts = [m for m in self.config.mounts if m.type == "cifs"]
+
+ if cifs_mounts and self.config.network_mode not in (
+ NetworkMode.FULL,
+ NetworkMode.MOUNTS_ONLY,
+ ):
+ raise ValueError(
+ "CIFS mounts require network_mode=FULL or MOUNTS_ONLY. "
+ "Use type='9p' for mounts with network_mode=NONE."
+ )
+
+ await asyncio.sleep(MountOptions.STABILIZATION_DELAY)
+
+ server = self._ensure_smb_server() if cifs_mounts else None
+ mounted_cifs: list[tuple[str, str]] = [] # (share_name, guest_path)
+ mounted_9p: list[str] = [] # guest_paths (for rollback umount only)
+
+ p9_idx = 0
+
+ try:
+ for mount in self.config.mounts:
+ if mount.type == "cifs":
+ assert server is not None
+ share_name = server.add_share(mount.host, mount.readonly)
+ await self._mount_cifs_share(share_name, mount.guest, mount.readonly)
+ mounted_cifs.append((share_name, mount.guest))
+ elif mount.type == "9p":
+ tag = f"pb9p{p9_idx}"
+ await self._mount_9p_share(tag, mount.guest, mount.readonly)
+ mounted_9p.append(mount.guest)
+ p9_idx += 1
+ except Exception:
+ # Rollback: unmount in reverse order
+ for guest_path in reversed(mounted_9p):
+ with contextlib.suppress(Exception):
+ await self.execute(
+ f"sudo umount {guest_path}",
+ timeout=Timeouts.MOUNT_OPERATION,
+ )
+ for share_name, guest_path in reversed(mounted_cifs):
+ with contextlib.suppress(Exception):
+ await self.execute(
+ f"sudo umount {guest_path}",
+ timeout=Timeouts.MOUNT_OPERATION,
+ )
+ with contextlib.suppress(Exception):
+ if server is not None:
+ server.remove_share(share_name)
+ raise
+
+ # ------------------------------------------------------------------
+ # Dynamic mount API
+ # ------------------------------------------------------------------
+
+ async def mount(self, host: str, guest: str, readonly: bool = False) -> MountHandle:
+ """Mount a host directory into the running sandbox.
+
+ Can be called any time after start(). Uses CIFS over QEMU slirp networking.
+
+ Args:
+ host: Absolute path to the host directory.
+ guest: Path inside the guest where the directory will be mounted.
+ readonly: Whether the mount should be read-only.
+
+ Returns:
+ A MountHandle that can be passed to unmount().
+
+ Raises:
+ RuntimeError: If the sandbox is not running, network is disabled,
+ or the mount fails.
+ """
+ if not self.is_running:
+ raise RuntimeError("Sandbox is not running")
+
+ if self.config.network_mode not in (NetworkMode.FULL, NetworkMode.MOUNTS_ONLY):
+ raise RuntimeError(
+ "Dynamic mounts require network_mode=FULL or MOUNTS_ONLY. "
+ "NONE disables networking entirely."
+ )
+
+ server = self._ensure_smb_server()
+ share_name = server.add_share(host, readonly)
+
+ try:
+ await self._mount_cifs_share(share_name, guest, readonly)
+ except Exception:
+ server.remove_share(share_name)
+ raise
+
+ handle = MountHandle(
+ host=host,
+ guest=guest,
+ readonly=readonly,
+ _share_name=share_name,
+ )
+ self._dynamic_mounts.append(handle)
+ return handle
+
+ async def unmount(self, handle: MountHandle) -> None:
+ """Unmount a previously mounted directory.
+
+ Args:
+ handle: The MountHandle returned by mount().
+ """
+ result = await self.execute(f"sudo umount {handle.guest}", timeout=Timeouts.MOUNT_OPERATION)
+ if result.exit_code != 0:
+ logger.warning(
+ "umount %s failed: %s",
+ handle.guest,
+ result.stderr or result.stdout,
+ )
+
+ if self._smb_server is not None:
+ self._smb_server.remove_share(handle._share_name)
+
+ if handle in self._dynamic_mounts:
+ self._dynamic_mounts.remove(handle)
+
+ @property
+ def active_mounts(self) -> list[MountHandle]:
+ """List currently active dynamic mounts."""
+ return list(self._dynamic_mounts)
+
+ # ------------------------------------------------------------------
+ # Cleanup
+ # ------------------------------------------------------------------
+
+ async def _cleanup_mounts(self) -> list[tuple[str, Exception]]:
+ """Stop SMB server if running. Returns list of (component, error) pairs."""
+ errors: list[tuple[str, Exception]] = []
+
+ # Unmount dynamic mounts in guest
+ for handle in reversed(self._dynamic_mounts):
+ with contextlib.suppress(Exception):
+ await self.execute(
+ f"sudo umount {handle.guest}",
+ timeout=Timeouts.MOUNT_OPERATION,
+ )
+ self._dynamic_mounts.clear()
+
+ # Stop SMB server
+ if self._smb_server is not None:
+ try:
+ self._smb_server.stop()
+ except Exception as e:
+ errors.append(("SMB server", e))
+ logger.warning("Failed to stop SMB server: %s", e)
+ self._smb_server = None
+
+ return errors
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_protocol.py b/packages/quicksand-core/quicksand_core/sandbox/_protocol.py
new file mode 100644
index 0000000..cfd6733
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_protocol.py
@@ -0,0 +1,123 @@
+"""Base protocol declaring the Sandbox API surface accessible within mixins."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Protocol
+
+from .._types import (
+ ExecuteResult,
+ MountHandle,
+ QuicksandGuestAgentMethod,
+ ResolvedAccelerator,
+ ResolvedImage,
+ SandboxConfig,
+ SaveManifest,
+ Timeouts,
+)
+from ..host.smb import SMBServer
+from ..qemu import OverlayManager, VMProcessManager
+from ..qemu.platform import RuntimeInfo
+
+if TYPE_CHECKING:
+ from ..host.quicksand_guest_agent_client import QuicksandGuestAgentClient
+ from ..host.virtio_serial_agent_client import VirtioSerialAgentClient
+ from ..qemu.qmp import QMPClient
+
+ AgentClient = QuicksandGuestAgentClient | VirtioSerialAgentClient
+
+
+class _SandboxProtocol(Protocol):
+ """Protocol for the full Sandbox interface, as seen by mixin classes."""
+
+ # ------------------------------------------------------------------
+ # State attributes (flat fields)
+ # ------------------------------------------------------------------
+
+ config: SandboxConfig
+ _is_running: bool
+ _image: ResolvedImage | None
+ _accel: ResolvedAccelerator | None
+ _overlay_path: Path | None
+ _temp_dir: Path | None
+ _process_manager: VMProcessManager
+ _smb_server: SMBServer | None
+ _dynamic_mounts: list[MountHandle]
+ _progress_callback: Callable[[str, int, int], None] | None
+ _overlay_manager: OverlayManager | None
+ _runtime_info: RuntimeInfo | None
+ _save_name: str | None
+ _workspace: Path | None
+ _agent_client: AgentClient | None
+ _agent_port: int | None
+ _agent_token: str | None
+ _qmp_client: QMPClient | None
+ _qmp_port: int | None
+ _qmp_checkpoints: list[str]
+ _vnc_port: int | None
+
+ # ------------------------------------------------------------------
+ # Public API
+ # ------------------------------------------------------------------
+
+ @property
+ def is_running(self) -> bool: ...
+
+ async def execute(
+ self,
+ command: str,
+ timeout: float = Timeouts.GUEST_AGENT_REQUEST,
+ cwd: str | None = None,
+ shell: str = "",
+ on_stdout: Callable[[str], None] | None = None,
+ on_stderr: Callable[[str], None] | None = None,
+ exclusive: bool = False,
+ ) -> ExecuteResult: ...
+
+ async def save(
+ self,
+ name: str,
+ *,
+ workspace: str | Path | None = None,
+ compress: bool = False,
+ delete_checkpoints: bool = False,
+ ) -> SaveManifest: ...
+
+ # Input / display API (implemented by _InputMixin)
+
+ @property
+ def vnc_port(self) -> int | None: ...
+
+ async def type_text(self, text: str) -> None: ...
+
+ async def press_key(self, *keys: str) -> None: ...
+
+ async def mouse_move(self, x: int, y: int) -> None: ...
+
+ async def mouse_click(self, button: str = "left", *, double: bool = False) -> None: ...
+
+ async def screenshot(self, path: str | Path) -> None: ...
+
+ async def query_display_size(self) -> tuple[int, int]: ...
+
+ async def query_mouse_position(self) -> dict | None: ...
+
+ # ------------------------------------------------------------------
+ # Internal API used across mixins
+ # ------------------------------------------------------------------
+
+ async def _send_request(
+ self,
+ method: QuicksandGuestAgentMethod,
+ params: dict[str, Any],
+ timeout: float = Timeouts.GUEST_AGENT_REQUEST,
+ ) -> dict[str, Any]: ...
+
+ async def _graceful_shutdown(self) -> None: ...
+
+ def _ensure_smb_server(self) -> SMBServer: ...
+
+ async def _mount_shares(self) -> None: ...
+
+ async def _cleanup_mounts(self) -> list[tuple[str, Exception]]: ...
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_sandbox.py b/packages/quicksand-core/quicksand_core/sandbox/_sandbox.py
new file mode 100644
index 0000000..c69fc02
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_sandbox.py
@@ -0,0 +1,293 @@
+"""Sandbox class — public API and VM lifecycle orchestration."""
+
+from __future__ import annotations
+
+import logging
+import time
+from collections.abc import Callable
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Unpack
+
+from .._types import (
+ BootTiming,
+ ExecuteResult,
+ QuicksandGuestAgentMethod,
+ ResolvedAccelerator,
+ ResolvedImage,
+ SandboxConfig,
+ SandboxConfigParams,
+ Timeouts,
+)
+from ..qemu import OverlayManager, VMProcessManager
+from ._checkpoints import _CheckpointMixin
+from ._execution import _ExecutionMixin
+from ._input import _InputMixin
+from ._lifecycle import _LifecycleMixin
+from ._mounts import _MountMixin
+from ._saves import _SaveMixin
+
+if TYPE_CHECKING:
+ from ..host.quicksand_guest_agent_client import QuicksandGuestAgentClient
+ from ..host.virtio_serial_agent_client import VirtioSerialAgentClient
+ from ..qemu.qmp import QMPClient
+
+ AgentClient = QuicksandGuestAgentClient | VirtioSerialAgentClient
+
+logger = logging.getLogger("quicksand.sandbox")
+
+# Re-exported for backwards compatibility — defined in _types.py
+__all__ = ["ExecuteResult", "Sandbox", "SandboxConfig"]
+
+
+class Sandbox(
+ _ExecutionMixin, _CheckpointMixin, _SaveMixin, _InputMixin, _LifecycleMixin, _MountMixin
+):
+ """
+ Manages a single VM sandbox.
+
+ Start modes:
+
+ - Ephemeral (default): temporary overlay, discarded on stop.
+ Sandbox(image="ubuntu")
+
+ - Named: saves to .quicksand/<name>/ on stop.
+ Sandbox(image="ubuntu", save="my-env")
+
+ - From save: set ``image`` to a save name or path.
+ Sandbox(image="my-save")
+
+ - Named + from save: auto-save on stop.
+ Sandbox(image="my-save", save="next")
+
+ Manual save (VM keeps running)::
+
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("pip install numpy")
+ await sb.save("my-save")
+
+ async with Sandbox(image="my-save") as sb:
+ await sb.execute("python3 -c 'import numpy'")
+ """
+
+ def __init__(
+ self,
+ _config: SandboxConfig | None = None,
+ /,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ):
+ if _config is not None:
+ if kwargs:
+ raise TypeError("Cannot pass both a SandboxConfig and keyword arguments")
+ self.config = SandboxConfig.model_validate(_config)
+ else:
+ self.config = SandboxConfig.model_validate(kwargs)
+ self._progress_callback = progress_callback
+ self._save_name = save
+ self._workspace = Path(workspace) if workspace else None
+ self._is_running = False
+
+ # Resolution outputs (set during start)
+ self._image: ResolvedImage | None = None
+ self._accel: ResolvedAccelerator | None = None
+
+ # Runtime state
+ self._overlay_path: Path | None = None
+ self._temp_dir: Path | None = None
+ self._process_manager = VMProcessManager()
+ self._smb_server: Any = None
+ self._dynamic_mounts: list = []
+ self._agent_client: AgentClient | None = None
+ self._agent_port: int | None = None
+ self._agent_token: str | None = None
+ self._agent_socket_path: Path | None = None
+ self._qmp_client: QMPClient | None = None
+ self._qmp_port: int | None = None
+ self._qmp_checkpoints: list[str] = []
+ self._vnc_port: int | None = None
+ self._overlay_manager: OverlayManager | None = None
+ self._runtime_info = None
+ self._boot_timing: BootTiming | None = None
+
+ @property
+ def is_running(self) -> bool:
+ return self._is_running and self._process_manager.is_running
+
+ @property
+ def accelerator(self):
+ """The hardware accelerator in use. None before start()."""
+ return self._accel.accel if self._accel else None
+
+ @property
+ def boot_timeout(self) -> float:
+ """Effective boot timeout. May differ from config if TCG is used."""
+ return self._accel.boot_timeout if self._accel else self.config.boot_timeout
+
+ @property
+ def qemu_command(self) -> list[str] | None:
+ """The QEMU command line used to launch this sandbox. None before start()."""
+ return self._process_manager.command
+
+ @property
+ def boot_timing(self) -> BootTiming | None:
+ """Phase-level boot timing. None before start() completes."""
+ return self._boot_timing
+
+ async def start(self) -> None:
+ """Start the sandbox VM."""
+ if self.is_running:
+ raise RuntimeError("Sandbox is already running")
+
+ timing = BootTiming()
+
+ t = time.perf_counter()
+ self._resolve_image()
+ timing.resolve_image_s = round(time.perf_counter() - t, 4)
+
+ t = time.perf_counter()
+ self._detect_accelerator()
+ timing.detect_accelerator_s = round(time.perf_counter() - t, 4)
+
+ t = time.perf_counter()
+ self._load_runtime()
+ timing.load_runtime_s = round(time.perf_counter() - t, 4)
+
+ t = time.perf_counter()
+ self._setup_disk()
+ timing.setup_disk_s = round(time.perf_counter() - t, 4)
+
+ t = time.perf_counter()
+ self._launch_process()
+ timing.launch_process_s = round(time.perf_counter() - t, 4)
+
+ t = time.perf_counter()
+ await self._connect_to_guest_agent()
+ timing.connect_agent_s = round(time.perf_counter() - t, 4)
+
+ # Parse console log to break down connect_agent into sub-phases.
+ timing.console_log = self._get_console_output(max_bytes=16000)
+ self._parse_boot_sub_phases(timing)
+
+ t = time.perf_counter()
+ await self._connect_to_qmp()
+ timing.connect_qmp_s = round(time.perf_counter() - t, 4)
+
+ self._is_running = True
+
+ t = time.perf_counter()
+ await self._post_boot_setup()
+ timing.post_boot_s = round(time.perf_counter() - t, 4)
+
+ self._boot_timing = timing
+
+ async def stop(self) -> None:
+ """Stop the sandbox VM.
+
+ If ``save`` was provided at construction, saves to
+ ``<workspace>/<save>/`` before stopping.
+ """
+ if not self._is_running:
+ return
+ if self._save_name is not None:
+ try:
+ await self.save(
+ self._save_name,
+ workspace=self._workspace,
+ )
+ except Exception as e:
+ logger.warning(
+ "Auto-save for '%s' failed: %s",
+ self._save_name,
+ e,
+ )
+ await self._cleanup()
+
+ async def _send_request(
+ self,
+ method: QuicksandGuestAgentMethod,
+ params: dict,
+ timeout: float = Timeouts.GUEST_AGENT_REQUEST,
+ ) -> dict:
+ if self._agent_client is None:
+ raise RuntimeError("Not connected to guest agent")
+ return await self._agent_client.send_request(method, params, timeout)
+
+ async def __aenter__(self) -> Sandbox:
+ await self.start()
+ return self
+
+ async def __aexit__(self, _exc_type, _exc_val, _exc_tb) -> None:
+ await self.stop()
+
+ # ------------------------------------------------------------------
+ # Boot timing helpers
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _parse_boot_sub_phases(timing: BootTiming) -> None:
+ """Parse console log to estimate kernel, init, and agent sub-phases.
+
+ Uses kernel timestamps ``[ X.XXXXXX]`` when available, and known
+ marker strings to split connect_agent_s into sub-phases.
+ """
+ import re
+
+ console = timing.console_log or ""
+ if not console:
+ return
+
+ # Extract kernel timestamps [ 0.000000] if present (not suppressed by quiet)
+ kernel_ts = [float(m) for m in re.findall(r"\[\s*(\d+\.\d+)\]", console)]
+
+ # Detect key console markers
+ lines = console.splitlines()
+ has_init = any(
+ marker in line
+ for line in lines
+ for marker in ("is starting up", "Welcome to", "systemd", "OpenRC")
+ )
+ has_agent_start = any("quicksand-guest-agent" in line for line in lines)
+
+ if kernel_ts and has_init:
+ # Kernel timestamps give us wall-clock relative to kernel start.
+ # kernel_boot = time from kernel start to init (first init marker).
+ # We approximate: the last kernel timestamp before the init marker
+ # is when the kernel finished.
+ max_kernel_ts = max(kernel_ts)
+
+ # Estimate: kernel handed off to init at max_kernel_ts
+ timing.kernel_boot_s = round(max_kernel_ts, 4)
+ remaining = timing.connect_agent_s - max_kernel_ts
+
+ if has_agent_start and remaining > 0:
+ # Split remaining between init and agent roughly.
+ # Agent startup is typically fast; init (DHCP etc.) is slow.
+ timing.init_system_s = round(remaining * 0.85, 4)
+ timing.agent_startup_s = round(remaining * 0.15, 4)
+ else:
+ timing.init_system_s = round(max(remaining, 0), 4)
+
+ elif has_init:
+ # No kernel timestamps (quiet mode). Use marker positions to
+ # estimate ratios from line count.
+ init_line = 0
+ agent_line = len(lines)
+ for i, line in enumerate(lines):
+ if any(m in line for m in ("is starting up", "Welcome to", "systemd", "OpenRC")):
+ init_line = i
+ break
+ for i, line in enumerate(lines):
+ if "quicksand-guest-agent" in line and "starting" in line.lower():
+ agent_line = i
+ break
+
+ total_lines = max(len(lines), 1)
+ init_frac = init_line / total_lines
+ agent_frac = agent_line / total_lines
+
+ timing.kernel_boot_s = round(timing.connect_agent_s * init_frac, 4)
+ timing.init_system_s = round(timing.connect_agent_s * (agent_frac - init_frac), 4)
+ timing.agent_startup_s = round(timing.connect_agent_s * (1 - agent_frac), 4)
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_saves.py b/packages/quicksand-core/quicksand_core/sandbox/_saves.py
new file mode 100644
index 0000000..2742f87
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/sandbox/_saves.py
@@ -0,0 +1,213 @@
+"""Persisted save/load operations for the Sandbox class.
+
+Saving uses QMP blockdev-snapshot-sync:
+ 1. Guest sync via guest agent — flush filesystem buffers.
+ 2. Flush QEMU block layer — ensure host qcow2 is fully up-to-date.
+ 3. QMP blockdev-snapshot-sync — QEMU atomically pivots writes to a new
+ overlay; the old overlay is left frozen and consistent.
+ 4. Write the frozen overlay chain to a save directory.
+
+QMP is always started alongside QEMU, so save() is always non-destructive.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from pathlib import Path
+
+from .._types import GuestCommands, SaveManifest
+from ._protocol import _SandboxProtocol
+
+logger = logging.getLogger("quicksand.sandbox")
+
+
+class _SaveMixin(_SandboxProtocol):
+ """Mixin providing persisted save/load operations."""
+
+ async def save(
+ self,
+ name: str,
+ *,
+ workspace: str | Path | None = None,
+ compress: bool = False,
+ delete_checkpoints: bool = False,
+ ) -> SaveManifest:
+ """Save the sandbox disk state to a directory.
+
+ The sandbox keeps running after the save (hot save via QMP). Only disk
+ state is saved — no RAM state is included. The saved directory can be
+ shared and loaded on any machine via ``SandboxConfig(image="save-name")``.
+
+ Args:
+ name: Save name (e.g. "my-env"). Written to ``<workspace>/<name>/``.
+ workspace: Parent directory for saves. Defaults to ``$CWD/.quicksand/``.
+ compress: Compress overlay qcow2 files to reduce save size.
+ Slower but produces smaller saves for distribution.
+ delete_checkpoints: If True, delete all active in-session checkpoint
+ snapshots before saving. If False (default) and snapshots exist,
+ raises RuntimeError.
+
+ Returns:
+ SaveManifest with details about the saved state.
+
+ Raises:
+ RuntimeError: If sandbox is not running, has active checkpoint snapshots
+ (when delete_checkpoints=False), or save fails.
+ """
+ if not self.is_running:
+ raise RuntimeError("Cannot save a non-running sandbox")
+
+ if self._qmp_client is None:
+ raise RuntimeError(
+ "QMP is not connected — cannot save a running sandbox. "
+ "This should not happen; QMP is started automatically with the VM."
+ )
+
+ if self._qmp_checkpoints and not delete_checkpoints:
+ tags = self._qmp_checkpoints
+ raise RuntimeError(
+ f"save() called with active checkpoint snapshots: {tags}. "
+ "These snapshots will not be accessible after the save pivot. "
+ "Pass delete_checkpoints=True to delete them before saving."
+ )
+
+ ws = Path(workspace) if workspace else None
+ return await self._save(name, ws, compress, delete_checkpoints)
+
+ async def _save(
+ self,
+ name: str,
+ workspace: Path | None,
+ compress: bool,
+ delete_checkpoints: bool,
+ ) -> SaveManifest:
+ """Save using QMP blockdev-snapshot-sync — VM keeps running."""
+ from ..host.arch import _detect_architecture
+ from ..qemu.image_resolver import SAVE_VERSION
+ from ..qemu.save import SaveWriter
+
+ assert self._overlay_path is not None
+ assert self._temp_dir is not None
+ assert self._image is not None
+
+ # 1. Sync guest filesystem buffers.
+ await self.execute(GuestCommands.SYNC, timeout=30.0, exclusive=True)
+
+ # 1b. TRIM freed blocks so QEMU can deallocate qcow2 clusters.
+ await self.execute(GuestCommands.FSTRIM, timeout=60.0, exclusive=True)
+
+ # 2. Delete checkpoint snapshots if requested.
+ assert self._qmp_client is not None
+ if delete_checkpoints:
+ for tag in self._qmp_checkpoints:
+ logger.debug("Deleting checkpoint snapshot '%s' before save", tag)
+ await self._qmp_client.execute(
+ "human-monitor-command",
+ **{"command-line": f"delvm {tag}"},
+ )
+ self._qmp_checkpoints.clear()
+
+ # 3. Flush QEMU block layer.
+ logger.debug("Flushing QEMU block layer for drive0 before snapshot pivot")
+ await self._qmp_client.execute(
+ "human-monitor-command",
+ **{"command-line": 'qemu-io drive0 "flush"'},
+ )
+
+ # 4. QMP atomic pivot — VM continues on a new overlay.
+ snapshot_overlay = self._overlay_path
+ new_overlay = self._temp_dir / f"overlay-{time.time_ns()}.qcow2"
+
+ await self._qmp_client.execute(
+ "blockdev-snapshot-sync",
+ device="drive0",
+ **{"snapshot-file": str(new_overlay)},
+ format="qcow2",
+ mode="absolute-paths",
+ )
+ self._overlay_path = new_overlay
+
+ # 5. Collect the overlay chain, keeping only this session's overlays.
+ # Overlays from installed packages (outside our temp dir) are
+ # excluded — they'll be resolved by name at load time.
+ # We also track each overlay's backing file so that compress can
+ # pass -B to qemu-img convert (avoids flattening the chain).
+ assert self._overlay_manager is not None
+ base = self._image.chain[0]
+ full_chain = self._overlay_manager.get_overlay_chain(snapshot_overlay, base)
+ chain: list[Path] = []
+ backing_files: list[Path] = []
+ prev: Path = base
+ for p in full_chain:
+ if p.resolve().is_relative_to(self._temp_dir.resolve()):
+ chain.append(p)
+ backing_files.append(prev)
+ else:
+ _verify_overlay_from_package(p)
+ prev = p
+
+ save_config = self.config.model_copy(update={"image": self._image.name, "mounts": []})
+ manifest = SaveManifest(
+ version=SAVE_VERSION,
+ config=save_config,
+ arch=str(_detect_architecture()),
+ )
+
+ writer = SaveWriter(name, workspace=workspace)
+ qemu_img = self._overlay_manager._qemu_img if compress else None
+ return writer.write(
+ overlay_chain=chain,
+ manifest=manifest,
+ compress=compress,
+ qemu_img=qemu_img,
+ backing_files=backing_files if compress else None,
+ )
+
+ @staticmethod
+ def validate_save(path: str | Path) -> SaveManifest:
+ """Validate a save without loading it.
+
+ Args:
+ path: Path to the save directory.
+
+ Returns:
+ SaveManifest if valid.
+
+ Raises:
+ FileNotFoundError: If save path doesn't exist.
+ ValueError: If save is invalid.
+ """
+ from ..qemu.image_resolver import ImageResolver
+
+ save_path = Path(path)
+ if not save_path.exists():
+ raise FileNotFoundError(f"Save not found: {save_path}")
+
+ return ImageResolver().validate_save(save_path)
+
+
+def _verify_overlay_from_package(overlay_path: Path) -> None:
+ """Verify that an overlay outside the temp dir belongs to an installed package.
+
+ Each ``quicksand.images`` entry point provider exposes an ``images_dir``
+ attribute. We check whether the overlay lives under one of those dirs.
+
+ Logs a warning if the overlay can't be attributed to any package.
+ """
+ from importlib.metadata import entry_points
+
+ resolved = overlay_path.resolve()
+ for ep in entry_points(group="quicksand.images"):
+ try:
+ provider = ep.load()
+ if resolved.is_relative_to(provider.images_dir.resolve()):
+ return
+ except Exception:
+ continue
+
+ logger.warning(
+ "Overlay %s is outside temp dir but not found in any installed package. "
+ "It will be excluded from the save.",
+ overlay_path,
+ )
diff --git a/packages/quicksand-core/quicksand_core/utils/__init__.py b/packages/quicksand-core/quicksand_core/utils/__init__.py
new file mode 100644
index 0000000..a7fc360
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/utils/__init__.py
@@ -0,0 +1,11 @@
+"""Shared utilities for quicksand-core."""
+
+from .hashing import DEFAULT_CHUNK_SIZE, compute_file_sha256
+from .network import find_free_port, find_free_vnc_port
+
+__all__ = [
+ "DEFAULT_CHUNK_SIZE",
+ "compute_file_sha256",
+ "find_free_port",
+ "find_free_vnc_port",
+]
diff --git a/packages/quicksand-core/quicksand_core/utils/hashing.py b/packages/quicksand-core/quicksand_core/utils/hashing.py
new file mode 100644
index 0000000..08c4e76
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/utils/hashing.py
@@ -0,0 +1,33 @@
+"""File hashing utilities.
+
+This module consolidates hash computation that was previously duplicated
+across checkpoint.py, image.py, and manifest.py.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from pathlib import Path
+
+# Optimal chunk size for file operations (64KB)
+DEFAULT_CHUNK_SIZE = 65536
+
+
+def compute_file_sha256(path: Path, *, chunk_size: int = DEFAULT_CHUNK_SIZE) -> str:
+ """Compute SHA-256 hash of a file using streaming.
+
+ Uses chunked reading to handle large files without loading
+ the entire file into memory.
+
+ Args:
+ path: Path to the file to hash.
+ chunk_size: Size of chunks to read at a time.
+
+ Returns:
+ Hexadecimal SHA-256 digest of the file contents.
+ """
+ sha256 = hashlib.sha256()
+ with open(path, "rb") as f:
+ while chunk := f.read(chunk_size):
+ sha256.update(chunk)
+ return sha256.hexdigest()
diff --git a/packages/quicksand-core/quicksand_core/utils/network.py b/packages/quicksand-core/quicksand_core/utils/network.py
new file mode 100644
index 0000000..12e3a47
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/utils/network.py
@@ -0,0 +1,31 @@
+"""Network utilities for quicksand-core."""
+
+from __future__ import annotations
+
+import socket
+
+from .._types import NetworkConstants
+
+
+def find_free_port() -> int:
+ """Find an available TCP port on localhost."""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind((NetworkConstants.LOCALHOST, 0))
+ return s.getsockname()[1]
+
+
+def find_free_vnc_port() -> int:
+ """Find an available VNC port on localhost (5900-5999).
+
+ QEMU VNC uses display numbers: port = 5900 + display.
+ This returns the actual port (5900-5999); callers pass display = port - 5900
+ to QEMU's -display vnc=host:display argument.
+ """
+ for port in range(5900, 6000):
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind((NetworkConstants.LOCALHOST, port))
+ return port
+ except OSError:
+ continue
+ raise RuntimeError("No free VNC ports available in range 5900-5999")
diff --git a/packages/quicksand-qemu/.gitignore b/packages/quicksand-qemu/.gitignore
new file mode 100644
index 0000000..2723a0c
--- /dev/null
+++ b/packages/quicksand-qemu/.gitignore
@@ -0,0 +1 @@
+quicksand_qemu/bin/
diff --git a/packages/quicksand-qemu/README.md b/packages/quicksand-qemu/README.md
new file mode 100644
index 0000000..0caed68
--- /dev/null
+++ b/packages/quicksand-qemu/README.md
@@ -0,0 +1,45 @@
+# Quicksand QEMU
+
+This package bundles QEMU binaries for the [quicksand](https://github.com/microsoft/quicksand) VM harness.
+
+## Installation
+
+Install as part of quicksand:
+
+```bash
+pip install quicksand[qemu]
+```
+
+Or standalone:
+
+```bash
+pip install quicksand-qemu
+```
+
+## What's Included
+
+Platform-specific QEMU binaries:
+- `qemu-system-x86_64` or `qemu-system-aarch64` (depending on architecture)
+- `qemu-img` for disk image manipulation
+- Required BIOS/firmware files
+- Bundled shared libraries (no system dependencies)
+
+## Using System QEMU Instead
+
+If you prefer to use your system's QEMU installation, just install quicksand without the `[qemu]` extra:
+
+```bash
+pip install quicksand[ubuntu]
+```
+
+Quicksand will automatically detect QEMU in your PATH.
+
+## Package Size
+
+The wheel is ~80-150MB because it includes QEMU and all dependencies. This ensures quicksand works out of the box without system configuration.
+
+## License
+
+MIT (quicksand-qemu wrapper)
+
+QEMU binaries are licensed under GPL v2. See the bundled `licenses/` directory for full license texts.
diff --git a/packages/quicksand-qemu/hatch_build.py b/packages/quicksand-qemu/hatch_build.py
new file mode 100644
index 0000000..15d0d7c
--- /dev/null
+++ b/packages/quicksand-qemu/hatch_build.py
@@ -0,0 +1,1044 @@
+"""Hatch build hook for platform-specific quicksand-qemu wheels with bundled QEMU."""
+
+from __future__ import annotations
+
+import json
+import os
+import platform
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+from quicksand_build_tools import BinaryBundler
+
+
+def _detect_native_machine() -> str:
+ """Detect the native CPU architecture, seeing through Windows emulation.
+
+ On Windows ARM64, Python may run as x86_64 through transparent emulation,
+ causing ``platform.machine()`` to return ``"AMD64"``. The registry key
+ ``HKLM\\...\\PROCESSOR_ARCHITECTURE`` always reflects the true hardware.
+
+ Returns a lowercase architecture string (e.g. ``"arm64"``, ``"amd64"``).
+ """
+ if platform.system() == "Windows":
+ try:
+ import winreg # type: ignore[import-not-found]
+
+ key = winreg.OpenKey( # ty:ignore[unresolved-attribute]
+ winreg.HKEY_LOCAL_MACHINE, # ty:ignore[unresolved-attribute]
+ r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
+ )
+ value, _ = winreg.QueryValueEx(key, "PROCESSOR_ARCHITECTURE") # ty:ignore[unresolved-attribute]
+ winreg.CloseKey(key) # ty:ignore[unresolved-attribute]
+ return value.lower()
+ except Exception:
+ pass
+ return platform.machine().lower()
+
+
+# macOS entitlements plist for hypervisor access
+MACOS_ENTITLEMENTS = """\
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.hypervisor</key>
+ <true/>
+</dict>
+</plist>
+"""
+
+
+class RuntimeBuildHook(BuildHookInterface):
+ """Build hook that bundles QEMU binaries into quicksand-qemu."""
+
+ PLUGIN_NAME = "runtime"
+
+ def _bundle_qemu_data_files(self, bin_dir: Path, qemu_binary: str) -> None:
+ """Bundle BIOS, boot ROM, and keymap files.
+
+ x86_64 needs BIOS/ROM files. ARM64 doesn't (virt machine loads kernels directly).
+ Keymaps are needed on all architectures for VNC display.
+ """
+ qemu_path = Path(qemu_binary)
+ qemu_share_dir_linux = qemu_path.parent.parent / "share" / "qemu"
+ qemu_share_dir_windows = qemu_path.parent / "share"
+
+ # Create destination directory
+ data_dir = bin_dir / "share" / "qemu"
+ data_dir.mkdir(parents=True, exist_ok=True)
+
+ # Bundle keymaps (needed on all architectures for VNC display)
+ keymaps_sources = [
+ qemu_share_dir_linux / "keymaps",
+ qemu_share_dir_windows / "keymaps",
+ Path("/usr/share/qemu/keymaps"),
+ ]
+ for src in keymaps_sources:
+ if src.is_dir():
+ dest = data_dir / "keymaps"
+ shutil.copytree(src, dest, dirs_exist_ok=True)
+ self.app.display_info(f"Bundled keymaps from {src}")
+ break
+ else:
+ self.app.display_warning("Keymaps not found — VNC display may not work")
+
+ # BIOS/ROM files only needed for x86_64
+ if _detect_native_machine() in ("arm64", "aarch64"):
+ return
+
+ # Required files for x86_64 direct kernel boot
+ required_files = {
+ "bios-256k.bin": [
+ Path("/usr/share/seabios/bios-256k.bin"), # Ubuntu seabios
+ qemu_share_dir_windows / "bios-256k.bin", # Windows (Stefan Weil)
+ qemu_share_dir_linux / "bios-256k.bin", # macOS/Linux
+ Path("/usr/share/qemu/bios-256k.bin"),
+ ],
+ "linuxboot_dma.bin": [
+ qemu_share_dir_windows / "linuxboot_dma.bin", # Windows (Stefan Weil)
+ qemu_share_dir_linux / "linuxboot_dma.bin", # macOS/Linux
+ Path("/usr/share/qemu/linuxboot_dma.bin"),
+ Path("/usr/lib/ipxe/qemu/linuxboot_dma.bin"), # Ubuntu ipxe-qemu
+ ],
+ }
+
+ for filename, search_paths in required_files.items():
+ found = False
+ for src in search_paths:
+ if src.exists():
+ shutil.copy2(src, data_dir / filename)
+ self.app.display_info(f"Bundled: {filename} (from {src})")
+ found = True
+ break
+
+ if not found:
+ raise RuntimeError(
+ f"Required file not found: {filename}\n"
+ f"Searched: {[str(p) for p in search_paths]}\n"
+ "Ensure QEMU and seabios/ipxe-qemu are installed."
+ )
+
+ # Optional files for performance optimizations
+ # These enable faster boot with microvm machine type on Linux x86_64 + KVM
+ optional_files = {
+ "bios-microvm.bin": [
+ qemu_share_dir_windows / "bios-microvm.bin", # Windows (Stefan Weil)
+ qemu_share_dir_linux / "bios-microvm.bin", # macOS/Linux
+ Path("/usr/share/qemu/bios-microvm.bin"), # Standard Linux
+ Path("/usr/share/seabios/bios-microvm.bin"), # Ubuntu seabios
+ ],
+ }
+
+ for filename, search_paths in optional_files.items():
+ for src in search_paths:
+ if src.exists():
+ shutil.copy2(src, data_dir / filename)
+ self.app.display_info(f"Bundled (optional): {filename} (from {src})")
+ break
+ else:
+ self.app.display_warning(
+ f"Optional file not found: {filename} - microvm optimization disabled"
+ )
+
+ def _find_qemu_install_dir(self, qemu_path: Path) -> Path:
+ """Find the QEMU installation directory from a binary path."""
+ system = platform.system().lower()
+
+ if system == "darwin":
+ # Homebrew: /opt/homebrew/Cellar/qemu/10.2.0/bin/qemu-system-*
+ return qemu_path.parent.parent
+
+ elif system == "windows":
+ # Stefan Weil: C:\Program Files\qemu\qemu-system-*.exe
+ return qemu_path.parent
+
+ else: # Linux
+ # apt: /usr/bin/qemu-system-*
+ return Path("/usr")
+
+ def _find_qemu_license_files(self, install_dir: Path) -> list[Path]:
+ """Find upstream license files for GPL compliance."""
+ system = platform.system().lower()
+ found: list[Path] = []
+
+ if system == "darwin":
+ for filename in ["COPYING", "COPYING.LIB", "LICENSE"]:
+ path = install_dir / filename
+ if path.exists():
+ found.append(path)
+
+ elif system == "linux":
+ doc_dirs = list(Path("/usr/share/doc").glob("qemu-system-*"))
+ for doc_dir in doc_dirs:
+ copyright_file = doc_dir / "copyright"
+ if copyright_file.exists():
+ found.append(copyright_file)
+ break
+
+ for path in [
+ Path("/usr/share/doc/qemu-system-common/COPYING"),
+ Path("/usr/share/licenses/qemu/COPYING"),
+ Path("/usr/share/doc/qemu/COPYING"),
+ ]:
+ if path.exists():
+ found.append(path)
+ break
+
+ elif system == "windows":
+ for pattern in ["COPYING*", "LICENSE*"]:
+ found.extend(install_dir.glob(pattern))
+
+ return found
+
+ def _bundle_upstream_licenses(self, bin_dir: Path, qemu_binary: str) -> None:
+ """Copy license files from QEMU installation for GPL compliance."""
+ qemu_path = Path(qemu_binary).resolve()
+ install_dir = self._find_qemu_install_dir(qemu_path)
+
+ license_files = self._find_qemu_license_files(install_dir)
+ if not license_files:
+ raise RuntimeError(
+ f"No GPL license files found for QEMU installation.\n"
+ f"QEMU binary: {qemu_binary}\n"
+ f"Install dir: {install_dir}\n"
+ f"Platform: {platform.system()}\n"
+ f"Expected locations:\n"
+ f" macOS: <cellar>/qemu/<version>/COPYING\n"
+ f" Linux: /usr/share/doc/qemu-system-*/copyright\n"
+ f" Windows: <install_dir>/COPYING\n"
+ f"GPL compliance requires distributing license files with binaries."
+ )
+
+ licenses_dir = bin_dir / "licenses"
+ licenses_dir.mkdir(parents=True, exist_ok=True)
+
+ for src in license_files:
+ dest = licenses_dir / src.name
+ shutil.copy2(src, dest)
+ self.app.display_info(f"Copied upstream license: {src.name}")
+
+ self.app.display_info(f"GPL compliance: bundled {len(license_files)} license files")
+
+ # -----------------------------------------------------------------
+ # SOURCES.md — source URL resolution for GPL compliance
+ # -----------------------------------------------------------------
+
+ def _generate_sources_md(self, bin_dir: Path, qemu_binary: str) -> None:
+ """Generate SOURCES.md listing source URLs for every bundled component.
+
+ GPL compliance requires providing (or offering) source code for
+ GPL-licensed binaries we redistribute. This method queries the
+ system package manager to resolve each bundled library back to
+ its upstream source tarball URL and writes the result into the
+ wheel's ``licenses/`` directory.
+ """
+ system = platform.system().lower()
+ qemu_path = Path(qemu_binary).resolve()
+
+ libs = self._collect_bundled_libs(bin_dir, system)
+ qemu_ver = self._get_qemu_version(qemu_path)
+
+ if system == "darwin":
+ entries = self._resolve_sources_macos(libs, qemu_ver)
+ elif system == "linux":
+ entries = self._resolve_sources_linux(libs, qemu_ver)
+ elif system == "windows":
+ entries = self._resolve_sources_windows(bin_dir, qemu_ver)
+ else:
+ self.app.display_warning(f"Unknown platform {system}, skipping SOURCES.md")
+ return
+
+ licenses_dir = bin_dir / "licenses"
+ licenses_dir.mkdir(parents=True, exist_ok=True)
+ self._write_sources_md(licenses_dir / "SOURCES.md", entries, qemu_ver, system)
+ self.app.display_info(f"Generated SOURCES.md with {len(entries)} component(s)")
+
+ @staticmethod
+ def _get_qemu_version(binary: Path) -> str:
+ """Extract the QEMU version string from a binary."""
+ data = binary.read_bytes()
+ m = re.search(rb"QEMU emulator version (\d+\.\d+\.\d+)", data)
+ if m:
+ return m.group(1).decode()
+ m = re.search(rb"version (\d+\.\d+\.\d+)", data)
+ if m:
+ return m.group(1).decode()
+ return "unknown"
+
+ @staticmethod
+ def _collect_bundled_libs(bin_dir: Path, system: str) -> list[Path]:
+ """Return paths of all bundled native libraries."""
+ libs: list[Path] = []
+ lib_dir = bin_dir / "lib"
+ if lib_dir.exists():
+ for f in sorted(lib_dir.rglob("*")):
+ if not f.is_file():
+ continue
+ name = f.name
+ if name.endswith(".dylib") or ".so." in name or name.endswith(".so"):
+ # Skip QEMU's own accelerator modules
+ try:
+ if f.relative_to(lib_dir).parts[0] == "qemu":
+ continue
+ except (ValueError, IndexError):
+ pass
+ libs.append(f)
+ # Windows: DLLs sit directly in bin_dir
+ if system == "windows":
+ for f in sorted(bin_dir.iterdir()):
+ if f.is_file() and f.suffix.lower() == ".dll":
+ libs.append(f)
+ return libs
+
+ # -- macOS (Homebrew) --------------------------------------------------
+
+ def _resolve_sources_macos(self, libs: list[Path], qemu_ver: str) -> list[dict[str, str]]:
+ """Resolve source URLs via QEMU's Homebrew dependency tree.
+
+ The bundled dylibs are copies (not symlinks), so we cannot
+ reverse-map them to the Cellar. Instead we query ``brew info
+ --json=v2 qemu`` which includes the full recursive dependency
+ list, then fetch metadata for each dependency.
+ """
+ entries: list[dict[str, str]] = []
+
+ # QEMU itself
+ qemu_info = self._brew_formula_info("qemu")
+ entries.append(
+ {
+ "name": "QEMU",
+ "version": qemu_info["version"] if qemu_info else qemu_ver,
+ "license": "GPL-2.0-only",
+ "source": qemu_info["source"]
+ if qemu_info
+ else f"https://download.qemu.org/qemu-{qemu_ver}.tar.xz",
+ "homepage": "https://www.qemu.org/",
+ }
+ )
+
+ # Resolve every runtime dependency of the qemu formula
+ deps = self._brew_runtime_deps("qemu")
+ for dep in deps:
+ info = self._brew_formula_info(dep)
+ if info:
+ entries.append(info)
+
+ return entries
+
+ @staticmethod
+ def _brew_runtime_deps(formula: str) -> list[str]:
+ """Return the recursive runtime dependency names for a formula."""
+ try:
+ result = subprocess.run(
+ ["brew", "deps", "--installed", formula],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ if result.returncode == 0:
+ return [d.strip() for d in result.stdout.strip().splitlines() if d.strip()]
+ except (subprocess.TimeoutExpired, FileNotFoundError):
+ pass
+ return []
+
+ @staticmethod
+ def _brew_formula_info(formula: str) -> dict[str, str] | None:
+ """Get name, version, license, source URL and homepage for a formula."""
+ try:
+ result = subprocess.run(
+ ["brew", "info", "--json=v2", formula],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ if result.returncode != 0:
+ return None
+ data = json.loads(result.stdout)
+ f = data["formulae"][0]
+ return {
+ "name": f["name"],
+ "version": f["versions"]["stable"],
+ "license": f.get("license") or "Unknown",
+ "source": f["urls"]["stable"]["url"],
+ "homepage": f.get("homepage", ""),
+ }
+ except (
+ subprocess.TimeoutExpired,
+ json.JSONDecodeError,
+ KeyError,
+ IndexError,
+ ):
+ return None
+
+ # -- Linux (dpkg / rpm) ------------------------------------------------
+
+ def _resolve_sources_linux(self, libs: list[Path], qemu_ver: str) -> list[dict[str, str]]:
+ """Resolve source URLs via ``dpkg -S`` + ``apt-cache show`` (or rpm)."""
+ entries: list[dict[str, str]] = []
+
+ # QEMU itself
+ qemu_src = self._apt_source_url("qemu-system-x86") or self._apt_source_url(
+ "qemu-system-arm"
+ )
+ entries.append(
+ {
+ "name": "QEMU",
+ "version": qemu_ver,
+ "license": "GPL-2.0-only",
+ "source": qemu_src or f"https://download.qemu.org/qemu-{qemu_ver}.tar.xz",
+ "homepage": "https://www.qemu.org/",
+ }
+ )
+
+ # SeaBIOS (x86_64 only)
+ seabios_src = self._apt_source_url("seabios")
+ if seabios_src:
+ seabios_ver = self._dpkg_version("seabios") or "unknown"
+ entries.append(
+ {
+ "name": "SeaBIOS",
+ "version": seabios_ver,
+ "license": "LGPL-3.0-or-later",
+ "source": seabios_src,
+ "homepage": "https://www.seabios.org/",
+ }
+ )
+
+ seen_pkgs: set[str] = set()
+ for lib in libs:
+ pkg = self._dpkg_package_for_lib(lib)
+ if not pkg:
+ pkg = self._rpm_package_for_lib(lib)
+ if pkg and pkg not in seen_pkgs:
+ seen_pkgs.add(pkg)
+ info = self._linux_package_info(pkg)
+ if info:
+ entries.append(info)
+
+ return entries
+
+ @staticmethod
+ def _dpkg_package_for_lib(lib: Path) -> str | None:
+ """Find the owning Debian package for a library file."""
+ # The library was copied into the wheel; find the original system path.
+ # dpkg -S searches by filename pattern.
+ try:
+ result = subprocess.run(
+ ["dpkg", "-S", lib.name],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ # Output: "libfoo1:amd64: /usr/lib/x86_64-linux-gnu/libfoo.so.1"
+ first_line = result.stdout.strip().splitlines()[0]
+ return first_line.split(":")[0]
+ except (subprocess.TimeoutExpired, IndexError, FileNotFoundError):
+ pass
+ return None
+
+ @staticmethod
+ def _rpm_package_for_lib(lib: Path) -> str | None:
+ """Find the owning RPM package for a library file (Fedora/RHEL)."""
+ try:
+ result = subprocess.run(
+ ["rpm", "-qf", "--qf", "%{NAME}", f"/usr/lib64/{lib.name}"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ return result.stdout.strip()
+ except (subprocess.TimeoutExpired, FileNotFoundError):
+ pass
+ return None
+
+ @staticmethod
+ def _dpkg_version(pkg: str) -> str | None:
+ """Get the installed version of a Debian package."""
+ try:
+ result = subprocess.run(
+ ["dpkg-query", "-W", "-f", "${Version}", pkg],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ return result.stdout.strip()
+ except (subprocess.TimeoutExpired, FileNotFoundError):
+ pass
+ return None
+
+ @staticmethod
+ def _apt_source_url(pkg: str) -> str | None:
+ """Get the upstream homepage / source URL from apt-cache."""
+ try:
+ result = subprocess.run(
+ ["apt-cache", "show", pkg],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0:
+ for line in result.stdout.splitlines():
+ if line.startswith("Homepage:"):
+ return line.split(":", 1)[1].strip()
+ except (subprocess.TimeoutExpired, FileNotFoundError):
+ pass
+ return None
+
+ def _linux_package_info(self, pkg: str) -> dict[str, str] | None:
+ """Assemble source info for a Linux package."""
+ version = self._dpkg_version(pkg) or "unknown"
+ homepage = self._apt_source_url(pkg) or ""
+
+ # Build a source-package URL for Debian/Ubuntu
+ src_pkg = self._dpkg_source_package(pkg)
+ if src_pkg:
+ source = f"https://tracker.debian.org/pkg/{src_pkg}" if homepage == "" else homepage
+ else:
+ source = homepage or f"https://packages.debian.org/{pkg}"
+
+ return {
+ "name": pkg,
+ "version": version,
+ "license": self._dpkg_license(pkg),
+ "source": source,
+ "homepage": homepage,
+ }
+
+ @staticmethod
+ def _dpkg_source_package(pkg: str) -> str | None:
+ """Get the source package name for a binary package."""
+ try:
+ result = subprocess.run(
+ ["dpkg-query", "-W", "-f", "${source:Package}", pkg],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ if result.returncode == 0 and result.stdout.strip():
+ return result.stdout.strip()
+ except (subprocess.TimeoutExpired, FileNotFoundError):
+ pass
+ return None
+
+ @staticmethod
+ def _dpkg_license(pkg: str) -> str:
+ """Extract the license from a Debian copyright file (best-effort)."""
+ copyright_path = Path(f"/usr/share/doc/{pkg}/copyright")
+ if not copyright_path.exists():
+ return "Unknown"
+ try:
+ text = copyright_path.read_text(errors="replace")[:4096]
+ # Look for SPDX-style or common license references
+ for pattern, spdx in [
+ (r"Apache.*2\.0", "Apache-2.0"),
+ (r"GPL-3", "GPL-3.0-or-later"),
+ (r"GPL-2", "GPL-2.0-or-later"),
+ (r"LGPL-3", "LGPL-3.0-or-later"),
+ (r"LGPL-2\.1", "LGPL-2.1-or-later"),
+ (r"LGPL-2", "LGPL-2.0-or-later"),
+ (r"MIT", "MIT"),
+ (r"BSD-3", "BSD-3-Clause"),
+ (r"BSD-2", "BSD-2-Clause"),
+ (r"MPL-2", "MPL-2.0"),
+ (r"Zlib", "Zlib"),
+ ]:
+ if re.search(pattern, text):
+ return spdx
+ except OSError:
+ pass
+ return "Unknown"
+
+ # -- Windows (Stefan Weil QEMU distribution) ---------------------------
+
+ def _resolve_sources_windows(self, bin_dir: Path, qemu_ver: str) -> list[dict[str, str]]:
+ """Resolve sources for the Stefan Weil / MSYS2 QEMU distribution."""
+ entries: list[dict[str, str]] = []
+
+ entries.append(
+ {
+ "name": "QEMU",
+ "version": qemu_ver,
+ "license": "GPL-2.0-only",
+ "source": f"https://download.qemu.org/qemu-{qemu_ver.rstrip('.90')}.tar.xz"
+ if ".90" not in qemu_ver
+ else "https://gitlab.com/qemu-project/qemu (development snapshot)",
+ "homepage": "https://www.qemu.org/",
+ }
+ )
+
+ # Windows QEMU distributions bundle MSYS2/MinGW packages.
+ # Map DLL filenames to MSYS2 package names and upstream projects.
+ dll_to_upstream = self._windows_dll_upstream_map()
+
+ seen: set[str] = set()
+ for f in sorted(bin_dir.iterdir()):
+ if not f.is_file() or f.suffix.lower() != ".dll":
+ continue
+ name = f.stem.lower()
+ # Normalize: strip lib prefix and version suffix
+ key = re.sub(r"^lib", "", name)
+ key = re.sub(r"[-_]?\d[\d.]*$", "", key)
+
+ info = dll_to_upstream.get(key)
+ if not info:
+ # Try the full stem
+ info = dll_to_upstream.get(name)
+ if not info:
+ # Try with lib prefix
+ info = dll_to_upstream.get(f"lib{key}")
+
+ if info and info["name"] not in seen:
+ seen.add(info["name"])
+ entries.append(info)
+
+ return entries
+
+ @staticmethod
+ def _windows_dll_upstream_map() -> dict[str, dict[str, str]]:
+ """Mapping of Windows DLL basenames to upstream source metadata.
+
+ The Windows QEMU build from qemu.weilnetz.de bundles MSYS2/MinGW
+ libraries. Since there is no package manager to query at build
+ time on Windows CI, we maintain a static mapping here.
+ """
+
+ # Helper to reduce repetition
+ def _e(name: str, license: str, source: str, homepage: str = "") -> dict[str, str]:
+ return {
+ "name": name,
+ "license": license,
+ "source": source,
+ "homepage": homepage or source,
+ }
+
+ gnu_mirror = "https://ftp.gnu.org/gnu"
+ return {
+ # Core
+ "capstone": _e(
+ "Capstone", "BSD-3-Clause", "https://github.com/capstone-engine/capstone"
+ ),
+ "fdt": _e("dtc (libfdt)", "BSD-2-Clause", "https://github.com/dgibson/dtc"),
+ "ffi": _e("libffi", "MIT", "https://github.com/libffi/libffi"),
+ "pixman": _e("Pixman", "MIT", "https://gitlab.freedesktop.org/pixman/pixman"),
+ "slirp": _e(
+ "libslirp", "BSD-3-Clause", "https://gitlab.freedesktop.org/slirp/libslirp"
+ ),
+ # TLS / crypto
+ "crypto": _e("OpenSSL", "Apache-2.0", "https://github.com/openssl/openssl"),
+ "ssl": _e("OpenSSL", "Apache-2.0", "https://github.com/openssl/openssl"),
+ "gnutls": _e("GnuTLS", "LGPL-2.1-or-later", "https://www.gnutls.org/"),
+ "nettle": _e("Nettle", "LGPL-3.0-or-later", f"{gnu_mirror}/nettle/"),
+ "hogweed": _e("Nettle", "LGPL-3.0-or-later", f"{gnu_mirror}/nettle/"),
+ "tasn1": _e("libtasn1", "LGPL-2.1-or-later", f"{gnu_mirror}/libtasn1/"),
+ "p11-kit": _e("p11-kit", "BSD-3-Clause", "https://github.com/p11-glue/p11-kit"),
+ "nss3": _e("NSS", "MPL-2.0", "https://firefox-source-docs.mozilla.org/security/nss/"),
+ "nspr4": _e("NSPR", "MPL-2.0", "https://firefox-source-docs.mozilla.org/nspr/"),
+ # GLib
+ "glib": _e("GLib", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/glib"),
+ "gio": _e("GLib", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/glib"),
+ "gobject": _e("GLib", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/glib"),
+ "gmodule": _e("GLib", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/glib"),
+ "gmp": _e("GMP", "LGPL-3.0-or-later", f"{gnu_mirror}/gmp/"),
+ "pcre2": _e("PCRE2", "BSD-3-Clause", "https://github.com/PCRE2Project/pcre2"),
+ "intl": _e("gettext", "LGPL-2.1-or-later", f"{gnu_mirror}/gettext/"),
+ "iconv": _e("libiconv", "LGPL-2.1-or-later", f"{gnu_mirror}/libiconv/"),
+ # Compression
+ "z": _e("zlib", "Zlib", "https://github.com/madler/zlib"),
+ "zlib1": _e("zlib", "Zlib", "https://github.com/madler/zlib"),
+ "zstd": _e("Zstandard", "BSD-3-Clause", "https://github.com/facebook/zstd"),
+ "lzma": _e("XZ Utils", "0BSD", "https://github.com/tukaani-project/xz"),
+ "lzo2": _e("LZO", "GPL-2.0-or-later", "http://www.oberhumer.com/opensource/lzo/"),
+ "snappy": _e("Snappy", "BSD-3-Clause", "https://github.com/google/snappy"),
+ "bz2": _e("bzip2", "bzip2-1.0.6", "https://sourceware.org/bzip2/"),
+ "deflate": _e("libdeflate", "MIT", "https://github.com/ebiggers/libdeflate"),
+ "lz4": _e("LZ4", "BSD-2-Clause", "https://github.com/lz4/lz4"),
+ "brotlicommon": _e("Brotli", "MIT", "https://github.com/google/brotli"),
+ "brotlidec": _e("Brotli", "MIT", "https://github.com/google/brotli"),
+ "brotlienc": _e("Brotli", "MIT", "https://github.com/google/brotli"),
+ # Image / pixel
+ "png16": _e("libpng", "Zlib", "https://github.com/pnggroup/libpng"),
+ "jpeg": _e(
+ "libjpeg-turbo",
+ "IJG AND BSD-3-Clause AND Zlib",
+ "https://github.com/libjpeg-turbo/libjpeg-turbo",
+ ),
+ "tiff": _e("libtiff", "libtiff", "https://gitlab.com/libtiff/libtiff"),
+ "webp": _e("libwebp", "BSD-3-Clause", "https://chromium.googlesource.com/webm/libwebp"),
+ "webpdemux": _e(
+ "libwebp", "BSD-3-Clause", "https://chromium.googlesource.com/webm/libwebp"
+ ),
+ "sharpyuv": _e(
+ "libwebp", "BSD-3-Clause", "https://chromium.googlesource.com/webm/libwebp"
+ ),
+ "jxl": _e("JPEG XL", "BSD-3-Clause", "https://github.com/libjxl/libjxl"),
+ "jxl_cms": _e("JPEG XL", "BSD-3-Clause", "https://github.com/libjxl/libjxl"),
+ "avif": _e("libavif", "BSD-2-Clause", "https://github.com/AOMediaCodec/libavif"),
+ "aom": _e("libaom", "BSD-2-Clause", "https://aomedia.googlesource.com/aom/"),
+ "dav1d": _e("dav1d", "BSD-2-Clause", "https://code.videolan.org/videolan/dav1d"),
+ "svtav1enc": _e("SVT-AV1", "BSD-3-Clause", "https://gitlab.com/AOMediaCodec/SVT-AV1"),
+ "rav1e": _e("rav1e", "BSD-2-Clause", "https://github.com/xiph/rav1e"),
+ "yuv": _e("libyuv", "BSD-3-Clause", "https://chromium.googlesource.com/libyuv/libyuv"),
+ "hwy": _e("Highway", "Apache-2.0", "https://github.com/google/highway"),
+ "lerc": _e("LERC", "Apache-2.0", "https://github.com/Esri/lerc"),
+ "lcms2": _e("Little CMS 2", "MIT", "https://github.com/mm2/Little-CMS"),
+ "jbig": _e("JBIG-KIT", "GPL-2.0-or-later", "https://www.cl.cam.ac.uk/~mgk25/jbigkit/"),
+ # Networking
+ "idn2": _e("libidn2", "LGPL-3.0-or-later", f"{gnu_mirror}/libidn/"),
+ "unistring": _e("libunistring", "LGPL-3.0-or-later", f"{gnu_mirror}/libunistring/"),
+ "ssh": _e("libssh", "LGPL-2.1-or-later", "https://www.libssh.org/"),
+ "ssh2": _e("libssh2", "BSD-3-Clause", "https://github.com/libssh2/libssh2"),
+ "curl": _e("curl", "MIT", "https://github.com/curl/curl"),
+ "psl": _e("libpsl", "MIT", "https://github.com/nicjansma/libpsl"),
+ "sasl2": _e("Cyrus SASL", "BSD-4-Clause-UC", "https://github.com/cyrusimap/cyrus-sasl"),
+ "nfs": _e("libnfs", "LGPL-2.1-or-later", "https://github.com/sahlberg/libnfs"),
+ # GUI
+ "sdl2": _e("SDL2", "Zlib", "https://github.com/libsdl-org/SDL"),
+ "sdl2_image": _e("SDL2_image", "Zlib", "https://github.com/libsdl-org/SDL_image"),
+ "gtk": _e("GTK 3", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/gtk"),
+ "gdk": _e("GTK 3", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/gtk"),
+ "gdk_pixbuf": _e(
+ "gdk-pixbuf", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/gdk-pixbuf"
+ ),
+ "cairo": _e("Cairo", "LGPL-2.1-or-later", "https://www.cairographics.org/"),
+ "pango": _e("Pango", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/pango"),
+ "pangocairo": _e("Pango", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/pango"),
+ "pangoft2": _e("Pango", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/pango"),
+ "pangowin32": _e("Pango", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/pango"),
+ "harfbuzz": _e("HarfBuzz", "MIT", "https://github.com/harfbuzz/harfbuzz"),
+ "freetype": _e("FreeType", "FTL", "https://gitlab.freedesktop.org/freetype/freetype"),
+ "fontconfig": _e(
+ "Fontconfig", "MIT", "https://gitlab.freedesktop.org/fontconfig/fontconfig"
+ ),
+ "fribidi": _e("FriBidi", "LGPL-2.1-or-later", "https://github.com/fribidi/fribidi"),
+ "graphite2": _e(
+ "Graphite2", "LGPL-2.1-or-later", "https://github.com/nicjansma/graphite"
+ ),
+ "atk": _e("ATK", "LGPL-2.1-or-later", "https://gitlab.gnome.org/GNOME/atk"),
+ "epoxy": _e("libepoxy", "MIT", "https://github.com/anholt/libepoxy"),
+ "expat": _e("Expat", "MIT", "https://github.com/libexpat/libexpat"),
+ "datrie": _e("libdatrie", "LGPL-2.1-or-later", "https://github.com/tlwg/libdatrie"),
+ "thai": _e("libthai", "LGPL-2.1-or-later", "https://github.com/tlwg/libthai"),
+ # GStreamer
+ "gstreamer": _e(
+ "GStreamer",
+ "LGPL-2.1-or-later",
+ "https://gitlab.freedesktop.org/gstreamer/gstreamer",
+ ),
+ "gstbase": _e(
+ "GStreamer",
+ "LGPL-2.1-or-later",
+ "https://gitlab.freedesktop.org/gstreamer/gstreamer",
+ ),
+ "gstapp": _e(
+ "GStreamer",
+ "LGPL-2.1-or-later",
+ "https://gitlab.freedesktop.org/gstreamer/gstreamer",
+ ),
+ # Audio
+ "opus": _e("Opus", "BSD-3-Clause", "https://github.com/xiph/opus"),
+ "orc": _e("ORC", "BSD-3-Clause", "https://gitlab.freedesktop.org/gstreamer/orc"),
+ "jack64": _e("JACK Audio", "LGPL-2.1-or-later", "https://github.com/jackaudio/jack2"),
+ # Virtualization
+ "spice-server": _e(
+ "SPICE", "LGPL-2.1-or-later", "https://gitlab.freedesktop.org/spice/spice"
+ ),
+ "virglrenderer": _e(
+ "virglrenderer", "MIT", "https://gitlab.freedesktop.org/virgl/virglrenderer"
+ ),
+ "usbredirparser": _e(
+ "usbredir", "LGPL-2.1-or-later", "https://gitlab.freedesktop.org/spice/usbredir"
+ ),
+ "u2f-emu": _e(
+ "u2f-emulated", "LGPL-2.1-or-later", "https://github.com/nicjansma/u2f-emulated"
+ ),
+ "brlapi": _e("BRLTTY", "LGPL-2.1-or-later", "https://github.com/brltty/brltty"),
+ "cacard": _e(
+ "libcacard", "LGPL-2.1-or-later", "https://gitlab.freedesktop.org/spice/libcacard"
+ ),
+ "usb": _e("libusb", "LGPL-2.1-or-later", "https://github.com/libusb/libusb"),
+ # MinGW runtime
+ "gcc_s_seh": _e(
+ "GCC (runtime)", "GPL-3.0-or-later WITH GCC-exception-3.1", "https://gcc.gnu.org/"
+ ),
+ "stdc++": _e(
+ "GCC (libstdc++)", "GPL-3.0-or-later WITH GCC-exception-3.1", "https://gcc.gnu.org/"
+ ),
+ "winpthread": _e("mingw-w64", "MIT", "https://github.com/mingw-w64/mingw-w64"),
+ "ssp": _e(
+ "GCC (libssp)", "GPL-3.0-or-later WITH GCC-exception-3.1", "https://gcc.gnu.org/"
+ ),
+ "systre": _e("mingw-w64", "MIT", "https://github.com/mingw-w64/mingw-w64"),
+ "tre": _e("TRE", "BSD-2-Clause", "https://github.com/laurikari/tre"),
+ "db": _e(
+ "Berkeley DB",
+ "Sleepycat",
+ "https://www.oracle.com/database/technologies/related/berkeleydb.html",
+ ),
+ "ncursesw": _e("ncurses", "X11", f"{gnu_mirror}/ncurses/"),
+ # Misc
+ "plc4": _e("NSPR", "MPL-2.0", "https://firefox-source-docs.mozilla.org/nspr/"),
+ "plds4": _e("NSPR", "MPL-2.0", "https://firefox-source-docs.mozilla.org/nspr/"),
+ }
+
+ # -- Write SOURCES.md --------------------------------------------------
+
+ @staticmethod
+ def _write_sources_md(
+ path: Path,
+ entries: list[dict[str, str]],
+ qemu_ver: str,
+ system: str,
+ ) -> None:
+ """Write a Markdown file listing all bundled components and their sources."""
+ lines = [
+ "# Source Code Availability",
+ "",
+ "This wheel bundles QEMU and its runtime dependencies as pre-built",
+ "binaries. Several of these components are licensed under the GNU",
+ "GPL or LGPL, which requires that source code be made available.",
+ "",
+ "The table below lists every bundled component, its license, and",
+ "where to obtain the corresponding source code.",
+ "",
+ "| Component | Version | License | Source |",
+ "|-----------|---------|---------|--------|",
+ ]
+
+ for e in entries:
+ version = e.get("version", "")
+ source = e["source"]
+ lines.append(f"| {e['name']} | {version} | {e['license']} | {source} |")
+
+ lines.append("")
+ lines.append("If you have questions about source availability, please open an issue at")
+ lines.append("https://github.com/microsoft/quicksand.")
+ lines.append("")
+
+ path.write_text("\n".join(lines))
+
+ def _bundle_qemu_modules(self, bin_dir: Path, qemu_binary: str) -> None:
+ """Bundle QEMU accelerator modules (Linux only)."""
+ if platform.system() != "Linux":
+ return
+
+ qemu_path = Path(qemu_binary)
+
+ module_search_paths = [
+ qemu_path.parent.parent / "lib" / "qemu",
+ qemu_path.parent.parent / "lib" / "x86_64-linux-gnu" / "qemu",
+ qemu_path.parent.parent / "libexec" / "qemu",
+ Path("/usr/lib/qemu"),
+ Path("/usr/lib/x86_64-linux-gnu/qemu"),
+ Path("/usr/lib/aarch64-linux-gnu/qemu"),
+ Path("/usr/libexec/qemu"),
+ ]
+
+ source_dir = None
+ for path in module_search_paths:
+ if path.exists() and list(path.glob("*.so")):
+ source_dir = path
+ break
+
+ if not source_dir:
+ self.app.display_warning("QEMU module directory not found, skipping module bundling")
+ return
+
+ module_dir = bin_dir / "lib" / "qemu"
+ module_dir.mkdir(parents=True, exist_ok=True)
+
+ accel_patterns = ["accel-*.so"]
+ count = 0
+ for pattern in accel_patterns:
+ for module in source_dir.glob(pattern):
+ shutil.copy2(module, module_dir / module.name)
+ self.app.display_info(f"Bundled module: {module.name}")
+ count += 1
+
+ if count == 0:
+ self.app.display_warning(
+ f"No accelerator modules found in {source_dir}. TCG may be built-in on this system."
+ )
+
+ # -----------------------------------------------------------------
+ # QEMU installation
+ # -----------------------------------------------------------------
+
+ # Stefan Weil Windows installer — update URL when upgrading QEMU.
+ _WINDOWS_QEMU_INSTALLER = "qemu-w64-setup-20260324.exe"
+ _WINDOWS_QEMU_URL = f"https://qemu.weilnetz.de/w64/2026/{_WINDOWS_QEMU_INSTALLER}"
+
+ _WINDOWS_ARM64_QEMU_INSTALLER = "qemu-arm-setup-20260401.exe"
+ _WINDOWS_ARM64_QEMU_URL = f"https://qemu.weilnetz.de/aarch64/{_WINDOWS_ARM64_QEMU_INSTALLER}"
+
+ def _ensure_qemu_installed(self, qemu_name: str) -> None:
+ """Install QEMU if it is not already on PATH.
+
+ Supports macOS (Homebrew), Linux (apt), and Windows (Stefan Weil
+ installer). On Linux the build is expected to run as root (or
+ with passwordless sudo) inside a CI runner container.
+ """
+ if shutil.which(qemu_name):
+ self.app.display_info(f"Found {qemu_name} on PATH")
+ return
+
+ system = platform.system().lower()
+ self.app.display_info(f"QEMU not found — installing for {system}...")
+
+ if system == "darwin":
+ self._install_qemu_macos()
+ elif system == "linux":
+ self._install_qemu_linux()
+ elif system == "windows":
+ self._install_qemu_windows()
+ else:
+ raise RuntimeError(f"Unsupported platform for automatic QEMU install: {system}")
+
+ def _install_qemu_macos(self) -> None:
+ """Install QEMU via Homebrew."""
+ if not shutil.which("brew"):
+ raise RuntimeError(
+ "Homebrew is required to install QEMU on macOS.\nInstall it from https://brew.sh"
+ )
+ subprocess.run(["brew", "install", "qemu"], check=True)
+ self.app.display_info("Installed QEMU via Homebrew")
+
+ def _install_qemu_linux(self) -> None:
+ """Install QEMU via apt (Debian/Ubuntu)."""
+ machine = _detect_native_machine()
+ pkg = "qemu-system-x86" if machine in ("x86_64", "amd64") else "qemu-system-arm"
+
+ if shutil.which("apt-get"):
+ env = {**dict(os.environ), "DEBIAN_FRONTEND": "noninteractive"}
+ subprocess.run(
+ ["sudo", "apt-get", "update", "-qq"],
+ check=True,
+ env=env,
+ )
+ subprocess.run(
+ ["sudo", "apt-get", "install", "-y", "-qq", pkg, "qemu-utils"],
+ check=True,
+ env=env,
+ )
+ self.app.display_info(f"Installed {pkg} and qemu-utils via apt")
+ elif shutil.which("dnf"):
+ subprocess.run(
+ ["sudo", "dnf", "install", "-y", "qemu-system-x86-core", "qemu-img"],
+ check=True,
+ )
+ self.app.display_info("Installed QEMU via dnf")
+ else:
+ raise RuntimeError(
+ "No supported package manager found (apt-get or dnf).\n"
+ "Please install QEMU manually."
+ )
+
+ def _install_qemu_windows(self) -> None:
+ """Install QEMU via the Stefan Weil Windows installer."""
+ import urllib.request
+
+ machine = _detect_native_machine()
+ if machine in ("arm64", "aarch64"):
+ installer_name = self._WINDOWS_ARM64_QEMU_INSTALLER
+ installer_url = self._WINDOWS_ARM64_QEMU_URL
+ else:
+ installer_name = self._WINDOWS_QEMU_INSTALLER
+ installer_url = self._WINDOWS_QEMU_URL
+
+ installer = Path(installer_name)
+ if not installer.exists():
+ self.app.display_info(f"Downloading {installer_url}...")
+ urllib.request.urlretrieve(installer_url, installer)
+
+ self.app.display_info("Running QEMU installer (silent)...")
+ subprocess.run([str(installer), "/S"], check=True)
+
+ # Add to PATH for this process
+ qemu_dir = Path(r"C:\Program Files\qemu")
+ if qemu_dir.exists():
+ os.environ["PATH"] = str(qemu_dir) + os.pathsep + os.environ.get("PATH", "")
+ self.app.display_info(f"Installed QEMU to {qemu_dir}")
+ else:
+ raise RuntimeError(
+ f"QEMU installer completed but {qemu_dir} not found.\n"
+ "The installer may have failed silently."
+ )
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ """Bundle QEMU binaries into the package."""
+ if self.target_name != "wheel" or version == "editable":
+ return
+
+ bundler = BinaryBundler(self.app)
+
+ # Detect architecture
+ machine = _detect_native_machine()
+ if machine in ("arm64", "aarch64"):
+ qemu_name = "qemu-system-aarch64"
+ else:
+ qemu_name = "qemu-system-x86_64"
+
+ # Install QEMU if not present, then locate it
+ self._ensure_qemu_installed(qemu_name)
+ qemu_binary = shutil.which(qemu_name)
+ qemu_img = shutil.which("qemu-img")
+
+ if not qemu_binary or not qemu_img:
+ raise RuntimeError(
+ f"QEMU not found after installation attempt.\n"
+ f"Looked for: {qemu_name}, qemu-img\n"
+ f"Platform: {platform.system()}, arch: {machine}\n"
+ "Please install QEMU manually and ensure it is on PATH."
+ )
+
+ # Copy binaries to package
+ bin_dir = Path(self.root) / "quicksand_qemu" / "bin"
+ bin_dir.mkdir(exist_ok=True)
+
+ dest_qemu = bin_dir / Path(qemu_binary).name
+ dest_img = bin_dir / Path(qemu_img).name
+
+ # Use shutil.copy (not copy2) to avoid PermissionError from macOS SIP
+ # flags on Homebrew binaries
+ shutil.copy(qemu_binary, dest_qemu)
+ shutil.copy(qemu_img, dest_img)
+
+ # Bundle platform-specific dependencies
+ system = platform.system().lower()
+ if system == "darwin":
+ bundler.bundle_macos_dylibs(dest_qemu, bin_dir, entitlements_plist=MACOS_ENTITLEMENTS)
+ bundler.bundle_macos_dylibs(dest_img, bin_dir)
+ elif system == "linux":
+ bundler.bundle_linux_libs(dest_qemu, bin_dir)
+ bundler.bundle_linux_libs(dest_img, bin_dir)
+ elif system == "windows":
+ bundler.bundle_windows_dlls(Path(qemu_binary), bin_dir)
+ bundler.bundle_windows_dlls(Path(qemu_img), bin_dir)
+
+ bundler.make_executable(bin_dir)
+ self.app.display_info(f"Bundled QEMU: {dest_qemu.name}")
+
+ # QEMU-specific data files
+ self._bundle_qemu_data_files(bin_dir, qemu_binary)
+ self._bundle_qemu_modules(bin_dir, qemu_binary)
+ self._bundle_upstream_licenses(bin_dir, qemu_binary)
+ self._generate_sources_md(bin_dir, qemu_binary)
+
+ # Verify bundled binaries work
+ self.app.display_info("Verifying qemu-system...")
+ bundler.verify(dest_qemu, bin_dir)
+ self.app.display_info("Verifying qemu-img...")
+ bundler.verify(dest_img, bin_dir)
+
+ # Force include all files in bin/ directory
+ bundler.force_include_bin_dir(bin_dir, Path(self.root), build_data)
+
+ # Mark as platform-specific wheel
+ if version != "editable":
+ bundler.set_platform_wheel_tag(build_data)
diff --git a/packages/quicksand-qemu/pyproject.toml b/packages/quicksand-qemu/pyproject.toml
new file mode 100644
index 0000000..fd652e4
--- /dev/null
+++ b/packages/quicksand-qemu/pyproject.toml
@@ -0,0 +1,18 @@
+[project]
+name = "quicksand-qemu"
+version = "0.4.8"
+description = "Bundled QEMU binaries for the quicksand VM harness."
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = []
+
+[build-system]
+requires = ["hatchling", "quicksand-build-tools"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_qemu"]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+# Build hook in hatch_build.py bundles QEMU binaries
diff --git a/packages/quicksand-qemu/quicksand_qemu/__init__.py b/packages/quicksand-qemu/quicksand_qemu/__init__.py
new file mode 100644
index 0000000..197f337
--- /dev/null
+++ b/packages/quicksand-qemu/quicksand_qemu/__init__.py
@@ -0,0 +1,33 @@
+"""
+Quicksand QEMU bundles QEMU binaries for the quicksand VM harness.
+
+This package contains pre-built QEMU binaries that work out of the box.
+Install with: pip install quicksand[qemu]
+"""
+
+from pathlib import Path
+
+__version__ = "0.1.0"
+
+_PACKAGE_DIR = Path(__file__).parent
+_BIN_DIR = _PACKAGE_DIR / "bin"
+
+
+def get_bin_dir() -> Path:
+ """Get the path to the bundled QEMU bin directory.
+
+ Returns:
+ Path to the directory containing qemu-system-* and qemu-img binaries.
+
+ Raises:
+ FileNotFoundError: If the bin directory doesn't exist (package not built correctly).
+ """
+ if not _BIN_DIR.exists():
+ raise FileNotFoundError(
+ f"Bundled QEMU binaries not found at {_BIN_DIR}. "
+ "The package may not have been built correctly."
+ )
+ return _BIN_DIR
+
+
+__all__ = ["__version__", "get_bin_dir"]
diff --git a/packages/quicksand-smb/CLAUDE.md b/packages/quicksand-smb/CLAUDE.md
new file mode 100644
index 0000000..bf60013
--- /dev/null
+++ b/packages/quicksand-smb/CLAUDE.md
@@ -0,0 +1,150 @@
+# quicksand-smb
+
+Pure-Python SMB3 server for quicksand host-guest directory mounting.
+
+## Overview
+
+An inetd-style SMB3 file server that reads/writes on stdin/stdout. QEMU's `guestfwd=cmd:` spawns one instance per guest TCP connection. No TCP port is opened on the host, eliminating the attack surface that Samba's smbd had.
+
+## Acceptance Criteria
+
+- [x] `mount -t cifs //10.0.2.100/SHARE /mnt -o sec=none,vers=3.0` succeeds from Ubuntu guest
+- [x] `ls`, `cat`, `stat` work on mounted files (read path)
+- [x] `echo "data" > file`, `mkdir`, `rm`, `mv` work (write path)
+- [x] No TCP ports opened on host during operation
+- [x] Path traversal attacks blocked (symlink escapes, `../` escapes)
+- [x] Dynamic mounts work (add shares after VM boot via config file reload)
+- [x] Read-only shares enforce read-only (writes fail with permission denied)
+- [x] Multiple concurrent shares work
+- [x] Binary files transfer correctly (no newline translation)
+- [ ] Large file I/O works (files > 1MB) — tested at protocol level, not yet in VM
+- [ ] Alpine guest mount validation
+
+## Key Protocol Details
+
+### NTLMSSP Authentication (sec=none still requires it)
+
+The Linux kernel CIFS client **always** performs a full NTLMSSP exchange, even with `sec=none`:
+
+1. **NEGOTIATE**: Server sends SPNEGO `negTokenInit` offering NTLMSSP OID
+2. **SESSION_SETUP round 1**: Client sends raw NTLMSSP_NEGOTIATE → Server sends **raw NTLMSSP_CHALLENGE** (NOT SPNEGO-wrapped)
+3. **SESSION_SETUP round 2**: Client sends raw NTLMSSP_AUTH → Server returns STATUS_SUCCESS
+
+**Critical**: The SMB2/3 kernel code uses `RawNTLMSSP` — it does NOT unwrap SPNEGO from SESSION_SETUP responses. SPNEGO is only used in the NEGOTIATE response. Wrapping the NTLMSSP_CHALLENGE in SPNEGO causes `error(22): Invalid argument`.
+
+### SecurityMode MUST be non-zero
+
+Per MS-SMB2 Section 3.3.5.4, the NEGOTIATE response **MUST** have `SMB2_NEGOTIATE_SIGNING_ENABLED (0x0001)` set. Setting SecurityMode=0 causes the client to silently disconnect after NEGOTIATE.
+
+### IPC$ Share Required
+
+The CIFS client always connects to `IPC$` before the real share (for IOCTL validation). The server must accept `IPC$` as a valid share with `ShareType=PIPE (0x02)`.
+
+### Compound Related Operations
+
+The CIFS client sends compound requests (CREATE+QUERY_INFO+CLOSE) with `SMB2_FLAGS_RELATED_OPERATIONS (0x04)`. In related operations, the FileId in QUERY_INFO/CLOSE is `0xFFFFFFFF...` meaning "use the FileId from the previous CREATE response". The server must track the last FileId and substitute it.
+
+### FILE_ALL_INFORMATION Struct Alignment
+
+The composite `FileAllInformation` response requires exact field sizes:
+- `FileBasicInformation`: **40 bytes** (4 timestamps + attributes + 4-byte reserved)
+- `FileStandardInformation`: **24 bytes** (2 sizes + nlinks + 2 bools + 2-byte reserved)
+
+Missing the reserved padding fields causes `get root inode failed`.
+
+### FSCTL_VALIDATE_NEGOTIATE_INFO
+
+The IOCTL response body is **48 bytes** (not 44 — includes a Reserved2 field). The OutputOffset must account for the full 48-byte body. Off-by-4 causes `buffer length N smaller than minimum size 28`.
+
+### QUERY_DIRECTORY Info Classes and Reserved Fields
+
+The Linux kernel CIFS client uses `FILE_ID_FULL_DIRECTORY_INFORMATION` (info class 38) for readdir — NOT class 3 or 37 as you might expect. Every directory info struct has reserved/padding fields that must be included or the FileName offset shifts and filenames appear truncated.
+
+Critical struct sizes (fixed header before FileName):
+- `FILE_DIRECTORY_INFORMATION` (1): **64 bytes**
+- `FILE_BOTH_DIRECTORY_INFORMATION` (3): **94 bytes** (includes ShortNameLength(1) + Reserved(1) + ShortName(24))
+- `FILE_ID_BOTH_DIRECTORY_INFORMATION` (37): **104 bytes** (adds Reserved2(2) + FileId(8))
+- `FILE_ID_FULL_DIRECTORY_INFORMATION` (38): **80 bytes** (includes EaSize(4) + **Reserved(4)** + FileId(8))
+
+The Reserved(4) field in class 38 between EaSize and FileId is easy to miss — omitting it shifts FileName by 4 bytes (2 UTF-16LE chars), causing filenames like `README.md` to appear as `ADME.md`.
+
+### Dynamic Mount Config Reload
+
+The CIFS client reuses existing TCP connections for new mounts. The server process reads the config file once at startup, so `reload_config()` must re-read the config file on each TREE_CONNECT to pick up dynamically added shares.
+
+## Mandatory Verification Process
+
+When adding or modifying any SMB struct (directory info, file info, IOCTL, etc.):
+
+1. **Field-by-field spec check**: Open the MS-FSCC or MS-SMB2 spec section for the struct. List every field and its size. Compare against the `struct.pack` format string. Count total bytes with `struct.calcsize()`. Reserved/padding fields with value 0 are still required on the wire.
+2. **Integration test**: Every struct that reaches the guest kernel MUST be validated by an integration test running in the real sandbox — not just a unit test. Unit test parsers can silently share the same offset bugs as the server (this has happened: see FILE_ID_FULL_DIRECTORY_INFORMATION below).
+3. **Verify the actual info class**: Add debug logging (`logger.debug`) to confirm which info class/level the kernel actually requests. Do not assume — the kernel may use a different class than expected (e.g., it uses class 38, not 37, for readdir).
+
+This project has been bitten THREE times by missing Reserved/padding fields in SMB structs. Every zero-valued field in the spec exists for a reason — the client-side struct layout depends on it.
+
+## Gotchas
+
+### Compound Requests
+The Linux CIFS client batches requests (e.g., CREATE+QUERY_INFO+CLOSE). The `NextCommand` field in the SMB2 header links them. Must split and process sequentially, then chain responses with `NextCommand` offsets.
+
+### FSCTL_QUERY_NETWORK_INTERFACE_INFO
+The CIFS client sends this IOCTL on the IPC$ tree. Return `STATUS_NOT_SUPPORTED` — the client gracefully falls back to single-channel.
+
+### UTF-16LE Everywhere
+All SMB3 paths and filenames are UTF-16LE encoded. Length fields are in bytes, not characters. Paths use backslash separators. No null terminators in wire format.
+
+### Windows FILETIME
+Timestamps are 100-nanosecond intervals since January 1, 1601. Convert from Unix: `filetime = int((unix_time + 11644473600) * 10_000_000)`.
+
+### Binary stdin/stdout
+QEMU's guestfwd passes raw TCP bytes via stdin/stdout. Must use `os.read()`/`os.write()` on raw file descriptors — NOT `sys.stdin.readline()` or print(). No buffering, no newline translation.
+
+### Credit System
+SMB3 uses credits for flow control. Grant generously (256 per response) to avoid stalls.
+
+## Previous Failed Attempts
+
+### Samba smbd (abandoned)
+Used bundled Samba `smbd` binary listening on localhost TCP with anonymous access.
+- **Problem 1**: No password auth without root (smbd needs PAM/root for smbpasswd)
+- **Problem 2**: Different local users could port-scan, enumerate shares via IPC$/srvsvc
+- **Problem 3**: 50MB+ binary dependency per platform
+- **Problem 4**: MD4 hash needed for NTLM auth, unavailable on OpenSSL 3.0+
+
+### smbpasswd auth approach (abandoned)
+Attempted to write smbpasswd file directly. NT hash requires MD4(UTF-16LE(password)), but MD4 is unavailable in Python 3.13+ / OpenSSL 3.0+. Decided auth was unnecessary with the guestfwd approach.
+
+### SPNEGO-wrapped NTLMSSP_CHALLENGE (failed)
+Wrapped the NTLMSSP_CHALLENGE in a SPNEGO negTokenResp for SESSION_SETUP response. The Linux kernel SMB2 code does NOT support SPNEGO in session setup — it expects raw NTLMSSP tokens.
+
+### SecurityMode=0 (failed)
+Set SecurityMode=0x0000 in NEGOTIATE response. MS-SMB2 spec requires SIGNING_ENABLED (0x0001) to be set. Client silently disconnects.
+
+### Missing Reserved field in FILE_ID_FULL_DIRECTORY_INFORMATION (fixed 2026-03)
+- **Symptom**: All filenames in `ls` were truncated by their first 2 characters (e.g. `README.md` → `ADME.md`)
+- **Root cause**: `_build_dir_entry` for info class 38 was missing a 4-byte `Reserved` field between `EaSize` and `FileId` (MS-FSCC 2.3.6). Fixed header was 76 bytes instead of 80, shifting FileName by 4 bytes (2 UTF-16LE chars).
+- **How it was missed**: Unit tests parsed entries using our own offset constants, which had the same bug. Only caught by running integration tests against the real sandbox kernel.
+- **Lesson**: Always validate directory listing structs with an integration test (`ls` in guest), not just protocol-level parsing. Unit test parsers can share the same wrong offsets as the server.
+
+## Useful Resources
+
+- [MS-SMB2](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-smb2/) — The authoritative protocol specification
+- [MS-NLMP](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/) — NTLMSSP authentication
+- [MS-FSCC](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/) — File system control codes and info classes
+- [Linux kernel fs/smb/client/](https://github.com/torvalds/linux/tree/master/fs/smb/client) — The CIFS client source (sess.c, smb2pdu.c)
+- [RFC 4178](https://tools.ietf.org/html/rfc4178) — SPNEGO (used in NEGOTIATE response only)
+
+## Changelog
+
+### 0.1.0 (initial)
+- Pure-Python SMB3 server with inetd/stdio transport
+- NEGOTIATE with SPNEGO negTokenInit, NTLMSSP authentication
+- SESSION_SETUP with raw NTLMSSP (NEGOTIATE → CHALLENGE → AUTH)
+- TREE_CONNECT/DISCONNECT (including IPC$ support)
+- CREATE, CLOSE, READ, WRITE, FLUSH
+- QUERY_INFO (file + filesystem), QUERY_DIRECTORY, SET_INFO
+- IOCTL (FSCTL_VALIDATE_NEGOTIATE_INFO, FSCTL_QUERY_NETWORK_INTERFACE_INFO stub)
+- Compound related operations support
+- Dynamic mount config reload on TREE_CONNECT
+- Path traversal protection
+- No external dependencies
diff --git a/packages/quicksand-smb/README.md b/packages/quicksand-smb/README.md
new file mode 100644
index 0000000..811dd7f
--- /dev/null
+++ b/packages/quicksand-smb/README.md
@@ -0,0 +1,19 @@
+# Quicksand SMB
+
+Pure-Python SMB3 server for [quicksand](https://github.com/microsoft/quicksand) host-guest directory mounts. Zero dependencies.
+
+Runs in inetd mode (stdin/stdout) — QEMU spawns a new process per guest connection via `guestfwd`. No TCP port is opened on the host.
+
+## Usage
+
+Not intended to be used directly. `quicksand-core` invokes it as a subprocess:
+
+```
+python -m quicksand_smb --config /path/to/shares.json
+```
+
+The share orchestration (add/remove shares, lifecycle) is managed by `quicksand-core`'s `SMBServer` ABC in `quicksand_core/host/smb.py`.
+
+## License
+
+MIT
diff --git a/packages/quicksand-smb/pyproject.toml b/packages/quicksand-smb/pyproject.toml
new file mode 100644
index 0000000..67dbc45
--- /dev/null
+++ b/packages/quicksand-smb/pyproject.toml
@@ -0,0 +1,14 @@
+[project]
+name = "quicksand-smb"
+version = "0.3.4.dev0"
+description = "Pure-Python SMB3 server for quicksand host-guest directory mounts."
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = []
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_smb"]
diff --git a/packages/quicksand-smb/quicksand_smb/__init__.py b/packages/quicksand-smb/quicksand_smb/__init__.py
new file mode 100644
index 0000000..b79cfed
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/__init__.py
@@ -0,0 +1,302 @@
+"""quicksand-smb: Pure-Python SMB3 server for host-guest directory mounts.
+
+This server runs in inetd mode (stdin/stdout) and is spawned per-connection
+by QEMU's guestfwd mechanism. No TCP listener, no auth, no external deps.
+
+Usage:
+ python -m quicksand_smb --config /path/to/config.json
+
+Public API:
+ SMBConfig — share configuration
+ serve_stdio — main server loop (reads stdin, writes stdout)
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import struct
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from ._files import (
+ HandleManager,
+ handle_close,
+ handle_create,
+ handle_flush,
+ handle_read,
+ handle_write,
+)
+from ._ioctl import handle_ioctl
+from ._negotiate import NegotiateState, handle_negotiate, handle_session_setup
+from ._protocol import (
+ Command,
+ SMBRequest,
+ _init_io,
+ build_error_response,
+ parse_request,
+ read_frame,
+ split_compound,
+ write_frame,
+)
+from ._query import handle_query_directory, handle_query_info, handle_set_info
+from ._status import STATUS_NOT_IMPLEMENTED, STATUS_SUCCESS
+from ._tree import handle_tree_connect, handle_tree_disconnect
+
+__version__ = "0.1.0"
+
+logger = logging.getLogger("quicksand.smb")
+
+
+@dataclass
+class ShareConfig:
+ """Configuration for a single SMB share."""
+
+ host_path: str
+ readonly: bool = False
+
+
+@dataclass
+class SMBConfig:
+ """Configuration for the SMB3 server."""
+
+ shares: dict[str, ShareConfig] = field(default_factory=dict)
+
+ @classmethod
+ def from_json_file(cls, path: str) -> SMBConfig:
+ with open(path) as f:
+ data = json.load(f)
+ shares = {}
+ for name, info in data.get("shares", {}).items():
+ if isinstance(info, dict):
+ shares[name] = ShareConfig(
+ host_path=info["host_path"],
+ readonly=info.get("readonly", False),
+ )
+ else:
+ shares[name] = ShareConfig(host_path=str(info))
+ return cls(shares=shares)
+
+ def to_dict(self) -> dict:
+ return {
+ "shares": {
+ name: {"host_path": sc.host_path, "readonly": sc.readonly}
+ for name, sc in self.shares.items()
+ }
+ }
+
+
+@dataclass
+class SMBSession:
+ """Per-connection server state."""
+
+ config: SMBConfig
+ config_path: str | None = None # path to reload config from for dynamic mounts
+ negotiate_state: NegotiateState | None = None
+ session_id: int = 0
+ next_tree_id: int = 1
+ tree_map: dict[int, str] = field(default_factory=dict) # tree_id → share_name
+ handles: HandleManager = field(default_factory=HandleManager)
+
+ def reload_config(self) -> None:
+ """Reload shares from config file (picks up dynamic mounts)."""
+ if self.config_path:
+ self.config = SMBConfig.from_json_file(self.config_path)
+
+ @property
+ def shares_dict(self) -> dict[str, dict]:
+ """Return shares as plain dicts for internal use."""
+ return {
+ name: {"host_path": sc.host_path, "readonly": sc.readonly}
+ for name, sc in self.config.shares.items()
+ }
+
+
+def _dispatch(session: SMBSession, req: SMBRequest) -> bytes:
+ """Dispatch a single SMB request to the appropriate handler."""
+ cmd = req.header.command
+ try:
+ cmd_name = Command(cmd).name
+ except ValueError:
+ cmd_name = f"0x{cmd:04X}"
+ logger.debug(
+ "CMD=%s mid=%d tid=%d sid=%d payload=%d bytes",
+ cmd_name,
+ req.header.message_id,
+ req.header.tree_id,
+ req.header.session_id,
+ len(req.payload),
+ )
+
+ if cmd == Command.NEGOTIATE:
+ response, state = handle_negotiate(req)
+ session.negotiate_state = state
+ return response
+
+ elif cmd == Command.SESSION_SETUP:
+ session.session_id = 1
+ return handle_session_setup(req, session.session_id)
+
+ elif cmd == Command.LOGOFF:
+ body = struct.pack("<HH", 4, 0)
+ from ._protocol import build_response_header
+
+ return build_response_header(req.header, STATUS_SUCCESS, len(body)) + body
+
+ elif cmd == Command.TREE_CONNECT:
+ # Reload config to pick up dynamically added shares
+ session.reload_config()
+ response, tree_id = handle_tree_connect(
+ req, session.shares_dict, session.tree_map, session.next_tree_id
+ )
+ if tree_id is not None:
+ session.next_tree_id = tree_id + 1
+ return response
+
+ elif cmd == Command.TREE_DISCONNECT:
+ return handle_tree_disconnect(req, session.tree_map)
+
+ elif cmd == Command.CREATE:
+ share_name = session.tree_map.get(req.header.tree_id)
+ if share_name is None or share_name not in session.shares_dict:
+ from ._status import STATUS_NETWORK_NAME_DELETED
+
+ return build_error_response(req.header, STATUS_NETWORK_NAME_DELETED)
+ share = session.shares_dict[share_name]
+ return handle_create(
+ req,
+ Path(share["host_path"]),
+ share["readonly"],
+ session.handles,
+ req.header.tree_id,
+ )
+
+ elif cmd == Command.CLOSE:
+ return handle_close(req, session.handles)
+
+ elif cmd == Command.READ:
+ return handle_read(req, session.handles)
+
+ elif cmd == Command.WRITE:
+ return handle_write(req, session.handles)
+
+ elif cmd == Command.FLUSH:
+ return handle_flush(req, session.handles)
+
+ elif cmd == Command.QUERY_INFO:
+ return handle_query_info(req, session.handles, session.shares_dict, session.tree_map)
+
+ elif cmd == Command.SET_INFO:
+ return handle_set_info(req, session.handles)
+
+ elif cmd == Command.QUERY_DIRECTORY:
+ return handle_query_directory(req, session.handles, session.shares_dict, session.tree_map)
+
+ elif cmd == Command.IOCTL:
+ return handle_ioctl(req, session.negotiate_state)
+
+ elif cmd == Command.ECHO:
+ body = struct.pack("<HH", 4, 0)
+ from ._protocol import build_response_header
+
+ return build_response_header(req.header, STATUS_SUCCESS, len(body)) + body
+
+ elif cmd in (Command.LOCK, Command.CHANGE_NOTIFY, Command.CANCEL):
+ return build_error_response(req.header, STATUS_NOT_IMPLEMENTED)
+
+ else:
+ return build_error_response(req.header, STATUS_NOT_IMPLEMENTED)
+
+
+def serve_stdio(config: SMBConfig, config_path: str | None = None) -> None:
+ """Main server loop: read SMB frames from stdin, dispatch, write responses to stdout.
+
+ Runs until stdin is closed (QEMU terminates the connection).
+ """
+ _init_io()
+ session = SMBSession(config=config, config_path=config_path)
+
+ while True:
+ try:
+ raw = read_frame()
+ except EOFError:
+ break
+
+ logger.debug("Frame: %d bytes, hex=%s", len(raw), raw.hex())
+
+ # SMB1 negotiate: some clients send \xFFSMB first to discover SMB2.
+ # Respond with SMB2 negotiate error to force protocol upgrade.
+ if raw[:4] == b"\xffSMB":
+ logger.debug("Received SMB1 negotiate, sending SMB2 upgrade response")
+ # SMB2 negotiate response with dialect 0x02FF (wildcard) tells
+ # the client to retry with SMB2. But the simplest approach is
+ # to just send back a minimal SMB2 negotiate response.
+ # The Linux CIFS client with vers=3.0 should NOT send SMB1,
+ # but vers=default might. Log and continue.
+ continue
+
+ # Handle compound requests
+ messages = split_compound(raw)
+
+ responses: list[bytes] = []
+ last_file_id: bytes = b"\x00" * 16
+ last_tree_id: int = 0
+ for msg_data in messages:
+ try:
+ req = parse_request(msg_data)
+
+ # Compound related operations: inherit FileId/TreeId from
+ # the previous response in the chain
+ if req.header.flags & 0x04: # SMB2_FLAGS_RELATED_OPERATIONS
+ if req.header.tree_id == 0:
+ req.header.tree_id = last_tree_id
+ # Replace sentinel FileId (0xFFFF...) in payload
+ sentinel = b"\xff" * 16
+ if sentinel in req.payload:
+ req = SMBRequest(
+ header=req.header,
+ payload=req.payload.replace(sentinel, last_file_id, 1),
+ raw=req.raw,
+ )
+
+ resp = _dispatch(session, req)
+ responses.append(resp)
+
+ # Track FileId from CREATE responses for compound chains
+ if req.header.command == Command.CREATE and len(resp) >= 64 + 82:
+ status = struct.unpack_from("<I", resp, 8)[0]
+ if status == 0:
+ last_file_id = resp[64 + 64 : 64 + 80]
+ last_tree_id = struct.unpack_from("<I", resp, 36)[0]
+ except Exception as e:
+ logger.error("Error processing SMB request: %s", e, exc_info=True)
+ try:
+ from ._protocol import parse_header
+
+ hdr = parse_header(msg_data)
+ from ._status import STATUS_UNSUCCESSFUL
+
+ responses.append(build_error_response(hdr, STATUS_UNSUCCESSFUL))
+ except Exception:
+ break
+
+ # Write compound response
+ if len(responses) == 1:
+ write_frame(responses[0])
+ elif responses:
+ # Chain responses: set NextCommand in headers
+ parts = []
+ for i, resp in enumerate(responses):
+ if i < len(responses) - 1:
+ # Pad to 8-byte alignment and set NextCommand
+ padded_len = (len(resp) + 7) & ~7
+ resp = resp.ljust(padded_len, b"\x00")
+ # NextCommand is at offset 20 in SMB2 header
+ ba = bytearray(resp)
+ struct.pack_into("<I", ba, 20, padded_len)
+ resp = bytes(ba)
+ parts.append(resp)
+ write_frame(b"".join(parts))
+
+ # Cleanup
+ session.handles.close_all()
diff --git a/packages/quicksand-smb/quicksand_smb/__main__.py b/packages/quicksand-smb/quicksand_smb/__main__.py
new file mode 100644
index 0000000..e35c35f
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/__main__.py
@@ -0,0 +1,28 @@
+"""Entry point: python -m quicksand_smb --config /path/to/config.json"""
+
+import argparse
+import logging
+import sys
+
+from . import SMBConfig, serve_stdio
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="quicksand SMB3 server (inetd/stdio)")
+ parser.add_argument("--config", required=True, help="Path to JSON config file")
+ parser.add_argument("--debug", action="store_true", help="Enable debug logging to stderr")
+ args = parser.parse_args()
+
+ if args.debug:
+ logging.basicConfig(
+ level=logging.DEBUG,
+ stream=sys.stderr,
+ format="%(name)s %(levelname)s: %(message)s",
+ )
+
+ config = SMBConfig.from_json_file(args.config)
+ serve_stdio(config, config_path=args.config)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/quicksand-smb/quicksand_smb/_files.py b/packages/quicksand-smb/quicksand_smb/_files.py
new file mode 100644
index 0000000..6a4038d
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/_files.py
@@ -0,0 +1,557 @@
+"""CREATE, CLOSE, READ, WRITE, and FLUSH command handlers.
+
+Manages file handles (FileId ↔ OS file descriptor) and performs I/O.
+Path traversal is checked on every CREATE to prevent sandbox escapes.
+
+Reference: [MS-SMB2] Sections 2.2.13-2.2.20.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import struct
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from ._protocol import SMBRequest, build_error_response, build_response_header
+from ._status import (
+ STATUS_ACCESS_DENIED,
+ STATUS_END_OF_FILE,
+ STATUS_FILE_IS_A_DIRECTORY,
+ STATUS_INVALID_HANDLE,
+ STATUS_INVALID_PARAMETER,
+ STATUS_NO_SUCH_FILE,
+ STATUS_NOT_A_DIRECTORY,
+ STATUS_OBJECT_NAME_COLLISION,
+ STATUS_OBJECT_NAME_NOT_FOUND,
+ STATUS_OBJECT_PATH_NOT_FOUND,
+ STATUS_SUCCESS,
+)
+
+# CreateDisposition values
+FILE_SUPERSEDE = 0x00000000
+FILE_OPEN = 0x00000001
+FILE_CREATE = 0x00000002
+FILE_OPEN_IF = 0x00000003
+FILE_OVERWRITE = 0x00000004
+FILE_OVERWRITE_IF = 0x00000005
+
+# CreateOptions flags
+FILE_DIRECTORY_FILE = 0x00000001
+FILE_NON_DIRECTORY_FILE = 0x00000040
+FILE_DELETE_ON_CLOSE = 0x00001000
+
+# File attribute constants
+FILE_ATTRIBUTE_READONLY = 0x00000001
+FILE_ATTRIBUTE_DIRECTORY = 0x00000010
+FILE_ATTRIBUTE_ARCHIVE = 0x00000020
+FILE_ATTRIBUTE_NORMAL = 0x00000080
+
+# DesiredAccess flags (simplified)
+FILE_READ_DATA = 0x00000001
+FILE_WRITE_DATA = 0x00000002
+FILE_APPEND_DATA = 0x00000004
+FILE_READ_ATTRIBUTES = 0x00000080
+GENERIC_READ = 0x80000000
+GENERIC_WRITE = 0x40000000
+GENERIC_ALL = 0x10000000
+DELETE = 0x00010000
+MAXIMUM_ALLOWED = 0x02000000
+
+# CreateAction values (returned in response)
+FILE_OPENED = 0x00000001
+FILE_CREATED = 0x00000002
+FILE_OVERWRITTEN = 0x00000003
+
+
+@dataclass
+class HandleInfo:
+ """State for an open file handle."""
+
+ fd: int # OS file descriptor (-1 for directories)
+ path: Path
+ is_dir: bool
+ tree_id: int
+ readonly: bool
+ delete_on_close: bool = False
+ dir_entries: list | None = None # cached entry names for QUERY_DIRECTORY
+ dir_offset: int = 0
+ _scandir_cache: dict | None = None # name → DirEntry cache for QUERY_DIRECTORY
+
+
+@dataclass
+class HandleManager:
+ """Maps 16-byte FileIds to HandleInfo."""
+
+ handles: dict[bytes, HandleInfo] = field(default_factory=dict)
+ _counter: int = 0
+
+ def allocate(self, info: HandleInfo) -> bytes:
+ """Allocate a new FileId and store the handle."""
+ self._counter += 1
+ # FileId: 8 bytes persistent + 8 bytes volatile
+ file_id = struct.pack("<QQ", 0, self._counter)
+ self.handles[file_id] = info
+ return file_id
+
+ def get(self, file_id: bytes) -> HandleInfo | None:
+ return self.handles.get(file_id)
+
+ def remove(self, file_id: bytes) -> HandleInfo | None:
+ return self.handles.pop(file_id, None)
+
+ def close_all(self) -> None:
+ for info in self.handles.values():
+ if info.fd >= 0:
+ with contextlib.suppress(OSError):
+ os.close(info.fd)
+ self.handles.clear()
+
+
+def _resolve_path(share_root: Path, filename: str) -> Path | None:
+ """Resolve a guest-requested filename to a host path, with traversal checks.
+
+ Returns None if the path escapes the share root.
+ """
+ # Normalize: strip leading separators, convert backslash
+ filename = filename.replace("\\", "/").lstrip("/")
+ if not filename:
+ return share_root
+
+ target = (share_root / filename).resolve()
+ share_resolved = share_root.resolve()
+
+ # Verify the resolved path is within the share
+ try:
+ target.relative_to(share_resolved)
+ except ValueError:
+ return None
+
+ return target
+
+
+def _stat_to_attrs(st: os.stat_result, is_dir: bool) -> int:
+ """Convert os.stat mode to SMB file attributes."""
+ attrs = 0
+ if is_dir:
+ attrs |= FILE_ATTRIBUTE_DIRECTORY
+ else:
+ attrs |= FILE_ATTRIBUTE_ARCHIVE
+ if not os.access(str(is_dir), os.W_OK):
+ attrs |= FILE_ATTRIBUTE_READONLY
+ return attrs or FILE_ATTRIBUTE_NORMAL
+
+
+def _filetime(t: float) -> int:
+ """Convert Unix timestamp to Windows FILETIME."""
+ return int((t + 11644473600) * 10_000_000)
+
+
+def _filetime_now() -> int:
+ return _filetime(time.time())
+
+
+def handle_create(
+ req: SMBRequest,
+ share_root: Path,
+ share_readonly: bool,
+ handles: HandleManager,
+ tree_id: int,
+) -> bytes:
+ """Handle CREATE (open/create file or directory)."""
+ payload = req.payload
+
+ # CREATE request body (57 bytes fixed):
+ # StructureSize(57)(2), SecurityFlags(1), RequestedOplockLevel(1),
+ # ImpersonationLevel(4), SmbCreateFlags(8), Reserved(8),
+ # DesiredAccess(4), FileAttributes(4), ShareAccess(4),
+ # CreateDisposition(4), CreateOptions(4),
+ # NameOffset(2), NameLength(2),
+ # CreateContextsOffset(4), CreateContextsLength(4)
+ if len(payload) < 56:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ (
+ _struct_size,
+ _sec_flags,
+ _oplock_level,
+ _impersonation,
+ _smb_create_flags,
+ _reserved,
+ desired_access,
+ _file_attributes,
+ _share_access,
+ create_disposition,
+ create_options,
+ name_offset,
+ name_length,
+ _ctx_offset,
+ _ctx_length,
+ ) = struct.unpack_from("<HBBIqQIIIIIHHII", payload)
+
+ # Extract filename
+ name_start = name_offset - 64 # offset from header start
+ if name_start < 0:
+ name_start = 56 # fallback: right after fixed part
+ if name_length > 0 and name_start + name_length <= len(payload):
+ filename = payload[name_start : name_start + name_length].decode(
+ "utf-16-le", errors="replace"
+ )
+ else:
+ filename = ""
+
+ # Resolve and validate path
+ target = _resolve_path(share_root, filename)
+ if target is None:
+ return build_error_response(req.header, STATUS_ACCESS_DENIED)
+
+ # Check readonly
+ wants_write = desired_access & (
+ FILE_WRITE_DATA | FILE_APPEND_DATA | GENERIC_WRITE | GENERIC_ALL | DELETE
+ )
+ if share_readonly and wants_write and create_disposition not in (FILE_OPEN,):
+ return build_error_response(req.header, STATUS_ACCESS_DENIED)
+
+ is_dir_request = bool(create_options & FILE_DIRECTORY_FILE)
+ is_nondir_request = bool(create_options & FILE_NON_DIRECTORY_FILE)
+ delete_on_close = bool(create_options & FILE_DELETE_ON_CLOSE)
+
+ target_exists = target.exists()
+ target_is_dir = target.is_dir() if target_exists else False
+
+ # Validate directory constraints
+ if target_exists:
+ if is_dir_request and not target_is_dir:
+ return build_error_response(req.header, STATUS_NOT_A_DIRECTORY)
+ if is_nondir_request and target_is_dir:
+ return build_error_response(req.header, STATUS_FILE_IS_A_DIRECTORY)
+
+ # Handle CreateDisposition
+ action = FILE_OPENED
+ try:
+ if create_disposition == FILE_OPEN:
+ if not target_exists:
+ return build_error_response(req.header, STATUS_OBJECT_NAME_NOT_FOUND)
+ elif create_disposition == FILE_CREATE:
+ if target_exists:
+ return build_error_response(req.header, STATUS_OBJECT_NAME_COLLISION)
+ if is_dir_request:
+ target.mkdir(parents=False, exist_ok=False)
+ else:
+ target.touch(exist_ok=False)
+ action = FILE_CREATED
+ elif create_disposition == FILE_OPEN_IF:
+ if not target_exists:
+ if is_dir_request:
+ target.mkdir(parents=False, exist_ok=True)
+ else:
+ target.touch(exist_ok=True)
+ action = FILE_CREATED
+ elif create_disposition in (FILE_OVERWRITE, FILE_OVERWRITE_IF):
+ if not target_exists:
+ if create_disposition == FILE_OVERWRITE:
+ return build_error_response(req.header, STATUS_OBJECT_NAME_NOT_FOUND)
+ target.touch(exist_ok=True)
+ action = FILE_CREATED
+ else:
+ if not target_is_dir:
+ target.write_bytes(b"") # truncate
+ action = FILE_OVERWRITTEN
+ elif create_disposition == FILE_SUPERSEDE:
+ if target_exists and not target_is_dir:
+ target.write_bytes(b"")
+ elif not target_exists:
+ if is_dir_request:
+ target.mkdir(parents=False, exist_ok=True)
+ else:
+ target.touch(exist_ok=True)
+ action = FILE_CREATED if not target_exists else FILE_OVERWRITTEN
+ except PermissionError:
+ return build_error_response(req.header, STATUS_ACCESS_DENIED)
+ except FileNotFoundError:
+ return build_error_response(req.header, STATUS_OBJECT_PATH_NOT_FOUND)
+ except OSError:
+ return build_error_response(req.header, STATUS_NO_SUCH_FILE)
+
+ # Open file descriptor
+ fd = -1
+ is_dir = target.is_dir()
+ if not is_dir:
+ flags = os.O_RDONLY
+ if not share_readonly and wants_write:
+ flags = os.O_RDWR
+ try:
+ fd = os.open(str(target), flags)
+ except PermissionError:
+ return build_error_response(req.header, STATUS_ACCESS_DENIED)
+ except FileNotFoundError:
+ return build_error_response(req.header, STATUS_OBJECT_NAME_NOT_FOUND)
+ except OSError:
+ return build_error_response(req.header, STATUS_NO_SUCH_FILE)
+
+ handle_info = HandleInfo(
+ fd=fd,
+ path=target,
+ is_dir=is_dir,
+ tree_id=tree_id,
+ readonly=share_readonly,
+ delete_on_close=delete_on_close,
+ )
+ file_id = handles.allocate(handle_info)
+
+ # Stat for response
+ try:
+ st = target.stat()
+ except OSError:
+ st = None
+
+ creation_time = _filetime(st.st_ctime) if st else _filetime_now()
+ last_access_time = _filetime(st.st_atime) if st else _filetime_now()
+ last_write_time = _filetime(st.st_mtime) if st else _filetime_now()
+ change_time = last_write_time
+ file_attrs = FILE_ATTRIBUTE_DIRECTORY if is_dir else FILE_ATTRIBUTE_ARCHIVE
+ alloc_size = ((st.st_size + 4095) // 4096 * 4096) if st else 0
+ end_of_file = st.st_size if st and not is_dir else 0
+
+ # CREATE response (89 bytes fixed):
+ # StructureSize(89), OplockLevel(1), Flags(1), CreateAction(4),
+ # CreationTime(8), LastAccessTime(8), LastWriteTime(8), ChangeTime(8),
+ # AllocationSize(8), EndOfFile(8), FileAttributes(4), Reserved2(4),
+ # FileId(16), CreateContextsOffset(4), CreateContextsLength(4)
+ body = struct.pack(
+ "<H" # StructureSize (89)
+ "B" # OplockLevel (none)
+ "B" # Flags
+ "I" # CreateAction
+ "Q" # CreationTime
+ "Q" # LastAccessTime
+ "Q" # LastWriteTime
+ "Q" # ChangeTime
+ "Q" # AllocationSize
+ "Q" # EndOfFile
+ "I" # FileAttributes
+ "I" # Reserved2
+ "16s" # FileId
+ "I" # CreateContextsOffset
+ "I", # CreateContextsLength
+ 89,
+ 0, # OplockLevel: none
+ 0, # Flags
+ action,
+ creation_time,
+ last_access_time,
+ last_write_time,
+ change_time,
+ alloc_size,
+ end_of_file,
+ file_attrs,
+ 0, # Reserved2
+ file_id,
+ 0, # No create contexts
+ 0,
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body))
+ return header + body
+
+
+def handle_close(req: SMBRequest, handles: HandleManager) -> bytes:
+ """Handle CLOSE request."""
+ payload = req.payload
+
+ # CLOSE request: StructureSize(24), Flags(2), Reserved(4), FileId(16)
+ if len(payload) < 24:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ _struct_size, flags = struct.unpack_from("<HH", payload)
+ file_id = payload[8:24]
+
+ info = handles.remove(file_id)
+ if info is None:
+ return build_error_response(req.header, STATUS_INVALID_HANDLE)
+
+ # Close the fd
+ if info.fd >= 0:
+ with contextlib.suppress(OSError):
+ os.close(info.fd)
+
+ # Delete on close
+ if info.delete_on_close:
+ try:
+ if info.is_dir:
+ info.path.rmdir()
+ else:
+ info.path.unlink()
+ except OSError:
+ pass
+
+ # Stat for response (if flags request it)
+ if flags & 0x0001 and info.path.exists(): # SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB
+ st = info.path.stat()
+ response_flags = 0x0001
+ creation_time = _filetime(st.st_ctime)
+ last_access_time = _filetime(st.st_atime)
+ last_write_time = _filetime(st.st_mtime)
+ change_time = last_write_time
+ alloc_size = (st.st_size + 4095) // 4096 * 4096
+ end_of_file = st.st_size
+ file_attrs = FILE_ATTRIBUTE_DIRECTORY if info.is_dir else FILE_ATTRIBUTE_ARCHIVE
+ else:
+ response_flags = 0
+ creation_time = last_access_time = last_write_time = change_time = 0
+ alloc_size = end_of_file = 0
+ file_attrs = 0
+
+ # CLOSE response: StructureSize(60), Flags(2), Reserved(4),
+ # CreationTime(8), LastAccessTime(8), LastWriteTime(8), ChangeTime(8),
+ # AllocationSize(8), EndOfFile(8), FileAttributes(4)
+ body = struct.pack(
+ "<HHI" # StructureSize, Flags, Reserved
+ "QQQQ" # timestamps
+ "QQ" # sizes
+ "I", # FileAttributes
+ 60,
+ response_flags,
+ 0,
+ creation_time,
+ last_access_time,
+ last_write_time,
+ change_time,
+ alloc_size,
+ end_of_file,
+ file_attrs,
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body))
+ return header + body
+
+
+def handle_read(req: SMBRequest, handles: HandleManager) -> bytes:
+ """Handle READ request."""
+ payload = req.payload
+
+ # READ request: StructureSize(49), Padding(1), Flags(1), Length(4),
+ # Offset(8), FileId(16), MinimumCount(4), Channel(4),
+ # RemainingBytes(4), ReadChannelInfoOffset(2), ReadChannelInfoLength(2)
+ if len(payload) < 48:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ _struct_size, _padding, _flags, length, offset = struct.unpack_from("<HBBIQ", payload)
+ file_id = payload[16:32]
+
+ info = handles.get(file_id)
+ if info is None:
+ return build_error_response(req.header, STATUS_INVALID_HANDLE)
+
+ if info.is_dir:
+ return build_error_response(req.header, STATUS_FILE_IS_A_DIRECTORY)
+
+ try:
+ data = os.pread(info.fd, length, offset)
+ except OSError:
+ return build_error_response(req.header, STATUS_END_OF_FILE)
+
+ if not data:
+ return build_error_response(req.header, STATUS_END_OF_FILE)
+
+ # READ response: StructureSize(17), DataOffset(1), Reserved(4),
+ # DataLength(4), DataRemaining(4), Reserved2(4), Data(variable)
+ data_offset = 64 + 16 # header + fixed body (16 bytes, StructureSize=17)
+
+ body = struct.pack(
+ "<H" # StructureSize (17)
+ "B" # DataOffset
+ "x" # Reserved (1 byte padding)
+ "I" # DataLength
+ "I" # DataRemaining
+ "I", # Reserved2
+ 17,
+ data_offset,
+ len(data),
+ 0, # DataRemaining
+ 0, # Reserved2
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body) + len(data))
+ return header + body + data
+
+
+def handle_write(req: SMBRequest, handles: HandleManager) -> bytes:
+ """Handle WRITE request."""
+ payload = req.payload
+
+ # WRITE request: StructureSize(49), DataOffset(2), Length(4),
+ # Offset(8), FileId(16), Channel(4), RemainingBytes(4),
+ # WriteChannelInfoOffset(2), WriteChannelInfoLength(2), Flags(4)
+ if len(payload) < 48:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ _struct_size, data_offset_field, length, offset = struct.unpack_from("<HHIQ", payload)
+ file_id = payload[16:32]
+
+ info = handles.get(file_id)
+ if info is None:
+ return build_error_response(req.header, STATUS_INVALID_HANDLE)
+
+ if info.is_dir:
+ return build_error_response(req.header, STATUS_FILE_IS_A_DIRECTORY)
+
+ if info.readonly:
+ return build_error_response(req.header, STATUS_ACCESS_DENIED)
+
+ # Data starts at data_offset_field relative to header start
+ data_start = data_offset_field - 64
+ if data_start < 0:
+ data_start = 48 # fallback after fixed part
+ write_data = payload[data_start : data_start + length]
+
+ try:
+ written = os.pwrite(info.fd, write_data, offset)
+ except OSError:
+ return build_error_response(req.header, STATUS_ACCESS_DENIED)
+
+ # WRITE response: StructureSize(17), Reserved(2), Count(4),
+ # Remaining(4), WriteChannelInfoOffset(2), WriteChannelInfoLength(2)
+ body = struct.pack(
+ "<H" # StructureSize (17)
+ "H" # Reserved
+ "I" # Count
+ "I" # Remaining
+ "H" # WriteChannelInfoOffset
+ "H", # WriteChannelInfoLength
+ 17,
+ 0,
+ written,
+ 0,
+ 0,
+ 0,
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body))
+ return header + body
+
+
+def handle_flush(req: SMBRequest, handles: HandleManager) -> bytes:
+ """Handle FLUSH request."""
+ payload = req.payload
+
+ if len(payload) < 24:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ # FLUSH request: StructureSize(24), Reserved1(2), Reserved2(4), FileId(16)
+ file_id = payload[8:24]
+
+ info = handles.get(file_id)
+ if info is None:
+ return build_error_response(req.header, STATUS_INVALID_HANDLE)
+
+ if info.fd >= 0:
+ with contextlib.suppress(OSError):
+ os.fsync(info.fd)
+
+ # FLUSH response: StructureSize(4), Reserved(2)
+ body = struct.pack("<HH", 4, 0)
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body))
+ return header + body
diff --git a/packages/quicksand-smb/quicksand_smb/_ioctl.py b/packages/quicksand-smb/quicksand_smb/_ioctl.py
new file mode 100644
index 0000000..b6a1917
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/_ioctl.py
@@ -0,0 +1,106 @@
+"""IOCTL command handler.
+
+The critical IOCTL is FSCTL_VALIDATE_NEGOTIATE_INFO — the SMB3 client sends
+this to verify the negotiate wasn't tampered with. We replay stored negotiate
+parameters. All other IOCTLs return STATUS_NOT_SUPPORTED.
+
+Reference: [MS-SMB2] Section 2.2.31-2.2.32 and [MS-FSA].
+"""
+
+from __future__ import annotations
+
+import struct
+
+from ._negotiate import NegotiateState
+from ._protocol import SMBRequest, build_error_response, build_response_header
+from ._status import STATUS_NOT_SUPPORTED, STATUS_SUCCESS
+
+# IOCTL codes
+FSCTL_VALIDATE_NEGOTIATE_INFO = 0x00140204
+FSCTL_PIPE_WAIT = 0x00110018
+FSCTL_PIPE_TRANSCEIVE = 0x0011C017
+FSCTL_DFS_GET_REFERRALS = 0x00060194
+FSCTL_SRV_ENUMERATE_SNAPSHOTS = 0x00144064
+FSCTL_SRV_REQUEST_RESUME_KEY = 0x00140078
+FSCTL_SRV_COPYCHUNK = 0x001440F2
+FSCTL_QUERY_NETWORK_INTERFACE_INFO = 0x001401FC
+
+
+def handle_ioctl(req: SMBRequest, negotiate_state: NegotiateState | None) -> bytes:
+ """Handle IOCTL request."""
+ payload = req.payload
+
+ # IOCTL request body:
+ # StructureSize(57), Reserved/Reserved2(2), CtlCode(4), FileId(16),
+ # InputOffset(4), InputCount(4), MaxInputResponse(4),
+ # OutputOffset(4), OutputCount(4), MaxOutputResponse(4), Flags(4)
+ if len(payload) < 56:
+ return build_error_response(req.header, STATUS_NOT_SUPPORTED)
+
+ _struct_size, _reserved, ctl_code = struct.unpack_from("<HHI", payload)
+ # FileId at offset 8 (16 bytes), InputOffset at 24, InputCount at 28
+ input_offset, input_count = struct.unpack_from("<II", payload, 24)
+ _max_input, _output_offset, _output_count, _max_output = struct.unpack_from(
+ "<IIII", payload, 32
+ )
+
+ if ctl_code == FSCTL_VALIDATE_NEGOTIATE_INFO:
+ return _handle_validate_negotiate(req, payload, input_offset, input_count, negotiate_state)
+
+ return build_error_response(req.header, STATUS_NOT_SUPPORTED)
+
+
+def _handle_validate_negotiate(
+ req: SMBRequest,
+ payload: bytes,
+ input_offset: int,
+ input_count: int,
+ state: NegotiateState | None,
+) -> bytes:
+ """Handle FSCTL_VALIDATE_NEGOTIATE_INFO.
+
+ Client sends: Capabilities(4), Guid(16), SecurityMode(2), DialectCount(2), Dialects(2*N)
+ Server responds: Capabilities(4), Guid(16), SecurityMode(2), Dialect(2)
+ """
+ if state is None:
+ return build_error_response(req.header, STATUS_NOT_SUPPORTED)
+
+ # Build the validate negotiate info response
+ output_data = struct.pack(
+ "<I16sHH",
+ state.capabilities,
+ state.server_guid,
+ state.security_mode,
+ state.dialect,
+ )
+
+ # IOCTL response body:
+ # StructureSize(49), Reserved/Reserved2(2), CtlCode(4), FileId(16),
+ # InputOffset(4), InputCount(4), OutputOffset(4), OutputCount(4), Flags(4)
+ file_id = payload[8:24] # echo back the FileId from request
+ output_offset = 64 + 48 # header(64) + fixed ioctl response body(48)
+
+ body = struct.pack(
+ "<HH" # StructureSize(49), Reserved
+ "I" # CtlCode
+ "16s" # FileId
+ "I" # InputOffset
+ "I" # InputCount
+ "I" # OutputOffset
+ "I" # OutputCount
+ "I" # Flags
+ "I", # Reserved2
+ 49,
+ 0,
+ FSCTL_VALIDATE_NEGOTIATE_INFO,
+ file_id,
+ 0, # InputOffset (no input in response)
+ 0, # InputCount
+ output_offset,
+ len(output_data),
+ 0, # Flags
+ 0, # Reserved2
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body) + len(output_data))
+ return header + body + output_data
diff --git a/packages/quicksand-smb/quicksand_smb/_negotiate.py b/packages/quicksand-smb/quicksand_smb/_negotiate.py
new file mode 100644
index 0000000..091433c
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/_negotiate.py
@@ -0,0 +1,364 @@
+"""NEGOTIATE and SESSION_SETUP command handlers.
+
+NEGOTIATE establishes the SMB3 dialect and server capabilities.
+SESSION_SETUP handles NTLMSSP authentication (accepts any credentials).
+
+The Linux CIFS client always performs NTLMSSP exchange even with sec=none:
+ 1. Client sends NTLMSSP_NEGOTIATE → server replies NTLMSSP_CHALLENGE
+ 2. Client sends NTLMSSP_AUTH → server replies SUCCESS
+
+Reference: [MS-SMB2] Sections 2.2.3-2.2.6, [MS-NLMP].
+"""
+
+from __future__ import annotations
+
+import os
+import struct
+from dataclasses import dataclass
+
+from ._protocol import SMBRequest, build_response_header
+from ._status import STATUS_MORE_PROCESSING_REQUIRED, STATUS_SUCCESS
+
+
+@dataclass
+class NegotiateState:
+ """Stored negotiate parameters for FSCTL_VALIDATE_NEGOTIATE_INFO replay."""
+
+ server_guid: bytes # 16 bytes
+ dialect: int
+ security_mode: int
+ capabilities: int
+ max_transact_size: int
+ max_read_size: int
+ max_write_size: int
+
+
+# Dialect values
+SMB_300 = 0x0300
+SMB_302 = 0x0302
+SMB_311 = 0x0311
+SMB_210 = 0x0210
+SMB_202 = 0x0202
+
+# Preferred dialects in order
+SUPPORTED_DIALECTS = (SMB_311, SMB_302, SMB_300, SMB_210, SMB_202)
+
+# Capabilities: LARGE_MTU enables multi-credit requests (required for SMB 3.0)
+SERVER_CAPABILITIES = 0x00000004 # SMB2_GLOBAL_CAP_LARGE_MTU
+
+# SecurityMode: signing enabled (MUST be set per MS-SMB2 3.3.5.4)
+SERVER_SECURITY_MODE = 0x0001 # SMB2_NEGOTIATE_SIGNING_ENABLED
+
+# Transfer sizes
+MAX_TRANSACT_SIZE = 1 * 1024 * 1024 # 1 MB
+MAX_READ_SIZE = 1 * 1024 * 1024
+MAX_WRITE_SIZE = 1 * 1024 * 1024
+
+# NTLMSSP constants
+NTLMSSP_SIGNATURE = b"NTLMSSP\x00"
+NTLMSSP_NEGOTIATE = 1
+NTLMSSP_CHALLENGE = 2
+NTLMSSP_AUTH = 3
+
+# SPNEGO OIDs (for wrapping NTLMSSP tokens)
+# These are the minimal ASN.1/DER bytes for SPNEGO negotiation
+_SPNEGO_OID = b"\x06\x06\x2b\x06\x01\x05\x05\x02" # 1.3.6.1.5.5.2
+_NTLMSSP_OID = b"\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a" # 1.3.6.1.4.1.311.2.2.10
+
+
+def handle_negotiate(req: SMBRequest) -> tuple[bytes, NegotiateState]:
+ """Handle SMB2 NEGOTIATE request. Returns (response_bytes, state)."""
+ payload = req.payload
+
+ # Parse NEGOTIATE request
+ _struct_size, dialect_count, _sec_mode, _reserved, _caps = struct.unpack_from("<HHHHI", payload)
+
+ dialects_offset = 36 # relative to payload start
+ dialects = []
+ for i in range(dialect_count):
+ d = struct.unpack_from("<H", payload, dialects_offset + i * 2)[0]
+ dialects.append(d)
+
+ # Select best supported dialect
+ selected = None
+ for d in SUPPORTED_DIALECTS:
+ if d in dialects:
+ selected = d
+ break
+ if selected is None:
+ selected = dialects[0] if dialects else SMB_202
+
+ server_guid = os.urandom(16)
+
+ state = NegotiateState(
+ server_guid=server_guid,
+ dialect=selected,
+ security_mode=SERVER_SECURITY_MODE,
+ capabilities=SERVER_CAPABILITIES,
+ max_transact_size=MAX_TRANSACT_SIZE,
+ max_read_size=MAX_READ_SIZE,
+ max_write_size=MAX_WRITE_SIZE,
+ )
+
+ # Build SPNEGO negTokenInit with NTLMSSP OID for the security buffer.
+ # This tells the client we support NTLMSSP authentication.
+ security_buffer = _build_spnego_neg_token_init()
+ security_offset = 128 # 64 (header) + 64 (negotiate response body)
+
+ body = struct.pack(
+ "<H" # StructureSize (65)
+ "H" # SecurityMode
+ "H" # DialectRevision
+ "H" # NegotiateContextCount (0 for non-3.1.1)
+ "16s" # ServerGuid
+ "I" # Capabilities
+ "I" # MaxTransactSize
+ "I" # MaxReadSize
+ "I" # MaxWriteSize
+ "Q" # SystemTime (FILETIME)
+ "Q" # ServerStartTime (FILETIME)
+ "H" # SecurityBufferOffset
+ "H" # SecurityBufferLength
+ "I", # NegotiateContextOffset (0)
+ 65, # StructureSize
+ SERVER_SECURITY_MODE,
+ selected,
+ 0, # NegotiateContextCount
+ server_guid,
+ SERVER_CAPABILITIES,
+ MAX_TRANSACT_SIZE,
+ MAX_READ_SIZE,
+ MAX_WRITE_SIZE,
+ _current_filetime(),
+ 0, # ServerStartTime
+ security_offset,
+ len(security_buffer),
+ 0, # NegotiateContextOffset
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body) + len(security_buffer))
+ return header + body + security_buffer, state
+
+
+def handle_session_setup(req: SMBRequest, session_id: int) -> bytes:
+ """Handle SESSION_SETUP request with NTLMSSP exchange.
+
+ The Linux CIFS client always sends NTLMSSP tokens even with sec=none.
+ Round 1: NTLMSSP_NEGOTIATE → reply with NTLMSSP_CHALLENGE + MORE_PROCESSING_REQUIRED
+ Round 2: NTLMSSP_AUTH → reply with SUCCESS
+ """
+ payload = req.payload
+
+ # Parse the security buffer from the request
+ # SESSION_SETUP request body:
+ # StructureSize(25)(2), Flags(1), SecurityMode(1), Capabilities(4),
+ # Channel(4), SecurityBufferOffset(2), SecurityBufferLength(2),
+ # PreviousSessionId(8)
+ if len(payload) >= 24:
+ sec_offset = struct.unpack_from("<H", payload, 12)[0]
+ sec_length = struct.unpack_from("<H", payload, 14)[0]
+ sec_start = sec_offset - 64 # offset from header start
+ if sec_start >= 0 and sec_length > 0 and sec_start + sec_length <= len(payload):
+ sec_blob = payload[sec_start : sec_start + sec_length]
+ else:
+ sec_blob = b""
+ else:
+ sec_blob = b""
+
+ # Extract NTLMSSP token from SPNEGO wrapper (or raw NTLMSSP)
+ ntlmssp_token = _extract_ntlmssp(sec_blob)
+
+ if ntlmssp_token and len(ntlmssp_token) >= 12:
+ msg_type = struct.unpack_from("<I", ntlmssp_token, 8)[0]
+ else:
+ msg_type = 0
+
+ if msg_type == NTLMSSP_NEGOTIATE:
+ # Round 1: Send back raw NTLMSSP_CHALLENGE (no SPNEGO wrapper).
+ # The Linux kernel SMB2 client uses RawNTLMSSP — it sends and expects
+ # bare NTLMSSP tokens in SESSION_SETUP, not SPNEGO-wrapped ones.
+ # SPNEGO is only used in the NEGOTIATE response.
+ security_buffer = _build_ntlmssp_challenge()
+ status = STATUS_MORE_PROCESSING_REQUIRED
+ else:
+ # Round 2 (NTLMSSP_AUTH) or unknown: Accept unconditionally
+ security_buffer = b""
+ status = STATUS_SUCCESS
+
+ security_offset = 72 # 64 (header) + 8 (fixed session setup response body)
+
+ body = struct.pack(
+ "<H" # StructureSize (9)
+ "H" # SessionFlags
+ "H" # SecurityBufferOffset
+ "H", # SecurityBufferLength
+ 9,
+ 0x0001 if status == STATUS_SUCCESS else 0, # IS_GUEST on final success
+ security_offset,
+ len(security_buffer),
+ )
+
+ header = build_response_header(
+ req.header,
+ status,
+ len(body) + len(security_buffer),
+ session_id=session_id,
+ )
+ return header + body + security_buffer
+
+
+# ---------------------------------------------------------------------------
+# NTLMSSP helpers
+# ---------------------------------------------------------------------------
+
+
+def _build_ntlmssp_challenge() -> bytes:
+ """Build an NTLMSSP_CHALLENGE message.
+
+ The Linux kernel CIFS client validates the challenge strictly:
+ - NegotiateFlags must include EXTENDED_SESSIONSECURITY
+ - TargetInfo must be present (with at least MsvAvEOL terminator)
+ - All offsets must point within the message
+
+ Structure (48 bytes fixed + variable):
+ Signature(8), MessageType(4),
+ TargetNameLen(2), TargetNameMaxLen(2), TargetNameOffset(4),
+ NegotiateFlags(4), ServerChallenge(8), Reserved(8),
+ TargetInfoLen(2), TargetInfoMaxLen(2), TargetInfoOffset(4)
+ [TargetName bytes] [TargetInfo bytes]
+ """
+ server_challenge = os.urandom(8)
+
+ flags = (
+ 0x00000001 # NEGOTIATE_UNICODE
+ | 0x00000002 # NEGOTIATE_OEM
+ | 0x00000004 # REQUEST_TARGET
+ | 0x00000010 # NEGOTIATE_SIGN
+ | 0x00000020 # NEGOTIATE_SEAL
+ | 0x00000200 # NEGOTIATE_NTLM
+ | 0x00008000 # NEGOTIATE_ALWAYS_SIGN
+ | 0x00080000 # NEGOTIATE_EXTENDED_SESSIONSECURITY
+ | 0x00800000 # NEGOTIATE_TARGET_INFO
+ | 0x02000000 # NEGOTIATE_128
+ | 0x20000000 # NEGOTIATE_KEY_EXCH
+ )
+
+ # Target name: "QUICKSAND" in UTF-16LE
+ target_name = "QUICKSAND".encode("utf-16-le")
+
+ # TargetInfo: MsvAvNbDomainName + MsvAvEOL terminator
+ # MsvAvNbDomainName (AvId=2): domain name "QUICKSAND" in UTF-16LE
+ domain = "QUICKSAND".encode("utf-16-le")
+ target_info = struct.pack("<HH", 2, len(domain)) + domain
+ # MsvAvEOL terminator (AvId=0, AvLen=0)
+ target_info += struct.pack("<HH", 0, 0)
+
+ # Fixed header is 48 bytes; variable data follows
+ fixed_size = 48
+ target_name_offset = fixed_size
+ target_info_offset = fixed_size + len(target_name)
+
+ msg = struct.pack(
+ "<8sI" # Signature + MessageType
+ "HHI" # TargetNameLen, TargetNameMaxLen, TargetNameOffset
+ "I" # NegotiateFlags
+ "8s" # ServerChallenge
+ "8s" # Reserved
+ "HHI", # TargetInfoLen, TargetInfoMaxLen, TargetInfoOffset
+ NTLMSSP_SIGNATURE,
+ NTLMSSP_CHALLENGE,
+ len(target_name),
+ len(target_name),
+ target_name_offset,
+ flags,
+ server_challenge,
+ b"\x00" * 8,
+ len(target_info),
+ len(target_info),
+ target_info_offset,
+ )
+ return msg + target_name + target_info
+
+
+def _extract_ntlmssp(blob: bytes) -> bytes | None:
+ """Extract the NTLMSSP token from a SPNEGO wrapper or raw NTLMSSP blob."""
+ if not blob:
+ return None
+
+ # Raw NTLMSSP (starts with "NTLMSSP\0")
+ if blob[:8] == NTLMSSP_SIGNATURE:
+ return blob
+
+ # SPNEGO wrapped — search for NTLMSSP signature within the blob
+ idx = blob.find(NTLMSSP_SIGNATURE)
+ if idx >= 0:
+ return blob[idx:]
+
+ return None
+
+
+def _build_spnego_neg_token_init() -> bytes:
+ """Build a minimal SPNEGO negTokenInit offering NTLMSSP.
+
+ Structure per RFC 4178:
+ APPLICATION[0] IMPLICIT SEQUENCE {
+ OID(1.3.6.1.5.5.2), -- SPNEGO
+ [0] NegTokenInit SEQUENCE {
+ [0] MechTypeList SEQUENCE {
+ OID(NTLMSSP)
+ }
+ }
+ }
+ """
+ # MechTypeList: SEQUENCE { OID(NTLMSSP) }
+ mech_types = b"\x30" + bytes([len(_NTLMSSP_OID)]) + _NTLMSSP_OID
+ # mechTypes [0] MechTypeList
+ mech_type_ctx = b"\xa0" + bytes([len(mech_types)]) + mech_types
+ # NegTokenInit SEQUENCE { mechTypes }
+ neg_token_init_seq = b"\x30" + _der_length(len(mech_type_ctx)) + mech_type_ctx
+ # [0] EXPLICIT NegTokenInit
+ neg_token_init = b"\xa0" + _der_length(len(neg_token_init_seq)) + neg_token_init_seq
+ # APPLICATION[0] is IMPLICIT SEQUENCE — no extra 0x30 wrapper
+ inner = _SPNEGO_OID + neg_token_init
+ return b"\x60" + _der_length(len(inner)) + inner
+
+
+def _build_spnego_neg_token_resp(ntlmssp_token: bytes) -> bytes:
+ """Build a SPNEGO negTokenResp wrapping an NTLMSSP token.
+
+ Structure per RFC 4178:
+ [1] NegTokenResp SEQUENCE {
+ [0] negState ENUMERATED { accept-incomplete(1) },
+ [1] supportedMech OID (NTLMSSP),
+ [2] responseToken OCTET STRING (NTLMSSP_CHALLENGE)
+ }
+ """
+ # negState [0] ENUMERATED { accept-incomplete(1) }
+ neg_state = b"\xa0\x03\x0a\x01\x01"
+ # supportedMech [1] OID (NTLMSSP)
+ supported_mech = b"\xa1" + bytes([len(_NTLMSSP_OID) + 0]) + _NTLMSSP_OID
+ # responseToken [2] OCTET STRING
+ octet_string = b"\x04" + _der_length(len(ntlmssp_token)) + ntlmssp_token
+ response_token = b"\xa2" + _der_length(len(octet_string)) + octet_string
+ # NegTokenResp SEQUENCE
+ seq_content = neg_state + supported_mech + response_token
+ seq = b"\x30" + _der_length(len(seq_content)) + seq_content
+ # context [1]
+ return b"\xa1" + _der_length(len(seq)) + seq
+
+
+def _der_length(length: int) -> bytes:
+ """Encode an ASN.1 DER length."""
+ if length < 0x80:
+ return bytes([length])
+ elif length < 0x100:
+ return bytes([0x81, length])
+ else:
+ return bytes([0x82, (length >> 8) & 0xFF, length & 0xFF])
+
+
+def _current_filetime() -> int:
+ """Return current time as Windows FILETIME (100ns since 1601-01-01)."""
+ import time
+
+ return int((time.time() + 11644473600) * 10_000_000)
diff --git a/packages/quicksand-smb/quicksand_smb/_protocol.py b/packages/quicksand-smb/quicksand_smb/_protocol.py
new file mode 100644
index 0000000..796d6bb
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/_protocol.py
@@ -0,0 +1,230 @@
+"""SMB3 binary protocol: NetBIOS framing, header parsing, and command dispatch.
+
+All SMB3 messages are prefixed with a 4-byte NetBIOS session service header
+(big-endian length), followed by the SMB3 header (64 bytes) and command payload.
+
+Reference: [MS-SMB2] Sections 2.2.1 (header) and 2.2.3 (negotiate).
+"""
+
+from __future__ import annotations
+
+import os
+import struct
+import sys
+from dataclasses import dataclass
+from enum import IntEnum
+
+# SMB2/3 magic: 0xFE 'S' 'M' 'B'
+SMB2_MAGIC = b"\xfeSMB"
+
+# Header flags
+SMB2_FLAGS_SERVER_TO_REDIR = 0x00000001
+SMB2_FLAGS_RELATED_OPERATIONS = 0x00000004
+
+# Header size
+SMB2_HEADER_SIZE = 64
+
+# Default credits to grant per response
+DEFAULT_CREDITS = 256
+
+
+class Command(IntEnum):
+ NEGOTIATE = 0x0000
+ SESSION_SETUP = 0x0001
+ LOGOFF = 0x0002
+ TREE_CONNECT = 0x0003
+ TREE_DISCONNECT = 0x0004
+ CREATE = 0x0005
+ CLOSE = 0x0006
+ FLUSH = 0x0007
+ READ = 0x0008
+ WRITE = 0x0009
+ LOCK = 0x000A
+ IOCTL = 0x000B
+ CANCEL = 0x000C
+ ECHO = 0x000D
+ QUERY_DIRECTORY = 0x000E
+ CHANGE_NOTIFY = 0x000F
+ QUERY_INFO = 0x0010
+ SET_INFO = 0x0011
+
+
+@dataclass
+class SMBHeader:
+ """Parsed SMB2/3 sync header."""
+
+ credit_charge: int
+ status: int
+ command: int
+ credit_request: int
+ flags: int
+ next_command: int
+ message_id: int
+ tree_id: int
+ session_id: int
+
+
+@dataclass
+class SMBRequest:
+ """A single SMB request: header + raw payload (everything after header)."""
+
+ header: SMBHeader
+ payload: bytes # bytes after the 64-byte header
+ raw: bytes # full raw message including header
+
+
+# ---------------------------------------------------------------------------
+# I/O: read/write on stdin/stdout in binary mode
+# ---------------------------------------------------------------------------
+
+_stdin_fd: int = -1
+_stdout_fd: int = -1
+
+
+def _init_io() -> None:
+ """Grab raw file descriptors for binary I/O."""
+ global _stdin_fd, _stdout_fd
+ _stdin_fd = sys.stdin.buffer.fileno()
+ _stdout_fd = sys.stdout.buffer.fileno()
+
+
+def _read_exactly(n: int) -> bytes:
+ """Read exactly n bytes from stdin, or raise EOFError."""
+ buf = bytearray()
+ while len(buf) < n:
+ chunk = os.read(_stdin_fd, n - len(buf))
+ if not chunk:
+ raise EOFError("stdin closed")
+ buf.extend(chunk)
+ return bytes(buf)
+
+
+def read_frame() -> bytes:
+ """Read one NetBIOS-framed SMB message from stdin."""
+ length_bytes = _read_exactly(4)
+ length = struct.unpack(">I", length_bytes)[0]
+ return _read_exactly(length)
+
+
+def write_frame(data: bytes) -> None:
+ """Write one NetBIOS-framed SMB message to stdout."""
+ header = struct.pack(">I", len(data))
+ os.write(_stdout_fd, header + data)
+
+
+# ---------------------------------------------------------------------------
+# Header parsing / building
+# ---------------------------------------------------------------------------
+
+# SMB2 sync header layout (64 bytes):
+# 4s ProtocolId (\xfeSMB)
+# H StructureSize (64)
+# H CreditCharge
+# I Status
+# H Command
+# H CreditRequest/Response
+# I Flags
+# I NextCommand
+# Q MessageId
+# I Reserved (sync: ProcessId)
+# I TreeId
+# Q SessionId
+# 16s Signature
+_HEADER_FMT = "<4sHHIHHIIQIIQ16s"
+_HEADER_SIZE = struct.calcsize(_HEADER_FMT) # 64
+assert _HEADER_SIZE == SMB2_HEADER_SIZE
+
+
+def parse_header(data: bytes) -> SMBHeader:
+ """Parse a 64-byte SMB2/3 sync header."""
+ (
+ magic,
+ _struct_size,
+ credit_charge,
+ status,
+ command,
+ credit_request,
+ flags,
+ next_command,
+ message_id,
+ _reserved,
+ tree_id,
+ session_id,
+ _signature,
+ ) = struct.unpack_from(_HEADER_FMT, data)
+ if magic != SMB2_MAGIC:
+ raise ValueError(f"Bad SMB2 magic: {magic!r}")
+ return SMBHeader(
+ credit_charge=credit_charge,
+ status=status,
+ command=command,
+ credit_request=credit_request,
+ flags=flags,
+ next_command=next_command,
+ message_id=message_id,
+ tree_id=tree_id,
+ session_id=session_id,
+ )
+
+
+def build_response_header(
+ req: SMBHeader,
+ status: int,
+ payload_size: int,
+ session_id: int | None = None,
+ tree_id: int | None = None,
+) -> bytes:
+ """Build a 64-byte SMB3 response header."""
+ return struct.pack(
+ _HEADER_FMT,
+ SMB2_MAGIC,
+ 64, # StructureSize
+ req.credit_charge or 1,
+ status,
+ req.command,
+ DEFAULT_CREDITS, # CreditResponse
+ SMB2_FLAGS_SERVER_TO_REDIR | (req.flags & SMB2_FLAGS_RELATED_OPERATIONS),
+ 0, # NextCommand (set later for compound)
+ req.message_id,
+ 0, # Reserved
+ tree_id if tree_id is not None else req.tree_id,
+ session_id if session_id is not None else req.session_id,
+ b"\x00" * 16, # Signature (no signing)
+ )
+
+
+def build_error_response(req: SMBHeader, status: int) -> bytes:
+ """Build a minimal error response (header + 9-byte error body)."""
+ # SMB2 ERROR Response: StructureSize(9), ErrorContextCount(0), Reserved(0),
+ # ByteCount(0), ErrorData(empty)
+ header = build_response_header(req, status, 9)
+ body = struct.pack("<HBxI", 9, 0, 0) # StructureSize=9, ErrorContextCount=0, ByteCount=0
+ return header + body
+
+
+# ---------------------------------------------------------------------------
+# Compound request splitting
+# ---------------------------------------------------------------------------
+
+
+def split_compound(data: bytes) -> list[bytes]:
+ """Split a compound SMB message into individual requests."""
+ messages: list[bytes] = []
+ offset = 0
+ while offset < len(data):
+ if offset + SMB2_HEADER_SIZE > len(data):
+ break
+ next_command = struct.unpack_from("<I", data, offset + 20)[0] # NextCommand at offset 20
+ if next_command == 0:
+ messages.append(data[offset:])
+ break
+ messages.append(data[offset : offset + next_command])
+ offset += next_command
+ return messages
+
+
+def parse_request(data: bytes) -> SMBRequest:
+ """Parse raw message bytes into an SMBRequest."""
+ header = parse_header(data)
+ payload = data[SMB2_HEADER_SIZE:]
+ return SMBRequest(header=header, payload=payload, raw=data)
diff --git a/packages/quicksand-smb/quicksand_smb/_query.py b/packages/quicksand-smb/quicksand_smb/_query.py
new file mode 100644
index 0000000..50d6899
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/_query.py
@@ -0,0 +1,761 @@
+"""QUERY_INFO, QUERY_DIRECTORY, and SET_INFO command handlers.
+
+Implements file/filesystem metadata queries and directory enumeration.
+
+Reference: [MS-SMB2] Sections 2.2.37-2.2.42 and [MS-FSCC].
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import struct
+from pathlib import Path
+
+from ._files import (
+ FILE_ATTRIBUTE_ARCHIVE,
+ FILE_ATTRIBUTE_DIRECTORY,
+ HandleInfo,
+ HandleManager,
+ _filetime,
+ _filetime_now,
+)
+from ._protocol import SMBRequest, build_error_response, build_response_header
+from ._status import (
+ STATUS_ACCESS_DENIED,
+ STATUS_BUFFER_OVERFLOW,
+ STATUS_BUFFER_TOO_SMALL,
+ STATUS_INVALID_HANDLE,
+ STATUS_INVALID_PARAMETER,
+ STATUS_NO_MORE_FILES,
+ STATUS_NOT_SUPPORTED,
+ STATUS_OBJECT_NAME_NOT_FOUND,
+ STATUS_SUCCESS,
+)
+
+logger = logging.getLogger("quicksand.smb.query")
+
+# InfoType values
+SMB2_0_INFO_FILE = 0x01
+SMB2_0_INFO_FILESYSTEM = 0x02
+
+# FileInfoClass values
+FILE_BASIC_INFORMATION = 4
+FILE_STANDARD_INFORMATION = 5
+FILE_INTERNAL_INFORMATION = 6
+FILE_EA_INFORMATION = 7
+FILE_ACCESS_INFORMATION = 8
+FILE_POSITION_INFORMATION = 14
+FILE_MODE_INFORMATION = 16
+FILE_ALIGNMENT_INFORMATION = 17
+FILE_ALL_INFORMATION = 18
+FILE_NETWORK_OPEN_INFORMATION = 34
+FILE_ATTRIBUTE_TAG_INFORMATION = 35
+FILE_STREAM_INFORMATION = 22
+FILE_COMPRESSION_INFORMATION = 28
+
+# FsInfoClass values
+FS_VOLUME_INFORMATION = 1
+FS_SIZE_INFORMATION = 3
+FS_DEVICE_INFORMATION = 4
+FS_ATTRIBUTE_INFORMATION = 5
+FS_FULL_SIZE_INFORMATION = 7
+FS_SECTOR_SIZE_INFORMATION = 11
+
+# FileInfoClass for directory queries
+FILE_DIRECTORY_INFORMATION = 1
+FILE_BOTH_DIRECTORY_INFORMATION = 3
+FILE_ID_BOTH_DIRECTORY_INFORMATION = 37
+FILE_ID_FULL_DIRECTORY_INFORMATION = 38
+FILE_NAMES_INFORMATION = 12
+
+# QUERY_DIRECTORY flags
+SMB2_RESTART_SCANS = 0x01
+SMB2_RETURN_SINGLE_ENTRY = 0x02
+SMB2_INDEX_SPECIFIED = 0x04
+
+# SET_INFO FileInfoClass
+FILE_DISPOSITION_INFORMATION = 13
+FILE_RENAME_INFORMATION = 10
+FILE_END_OF_FILE_INFORMATION = 20
+FILE_ALLOCATION_INFORMATION = 19
+
+
+def _build_basic_info(st: os.stat_result, is_dir: bool) -> bytes:
+ """FileBasicInformation: timestamps + attributes (40 bytes)."""
+ attrs = FILE_ATTRIBUTE_DIRECTORY if is_dir else FILE_ATTRIBUTE_ARCHIVE
+ return struct.pack(
+ "<QQQQII",
+ _filetime(st.st_ctime), # CreationTime
+ _filetime(st.st_atime), # LastAccessTime
+ _filetime(st.st_mtime), # LastWriteTime
+ _filetime(st.st_mtime), # ChangeTime
+ attrs, # FileAttributes
+ 0, # Reserved (padding to 40 bytes)
+ )
+
+
+def _build_standard_info(st: os.stat_result, is_dir: bool) -> bytes:
+ """FileStandardInformation: sizes + link count + delete/dir flags (24 bytes)."""
+ alloc_size = (st.st_size + 4095) // 4096 * 4096 if not is_dir else 0
+ eof = st.st_size if not is_dir else 0
+ return struct.pack(
+ "<QQI??H",
+ alloc_size,
+ eof,
+ st.st_nlink,
+ False, # DeletePending
+ is_dir, # Directory
+ 0, # Reserved (padding to 24 bytes)
+ )
+
+
+def _build_internal_info(st: os.stat_result) -> bytes:
+ """FileInternalInformation: inode number."""
+ return struct.pack("<Q", st.st_ino)
+
+
+def _build_ea_info() -> bytes:
+ """FileEaInformation: EA size (always 0)."""
+ return struct.pack("<I", 0)
+
+
+def _build_access_info() -> bytes:
+ """FileAccessInformation: granted access mask."""
+ return struct.pack("<I", 0x001F01FF) # FILE_ALL_ACCESS
+
+
+def _build_position_info() -> bytes:
+ """FilePositionInformation."""
+ return struct.pack("<Q", 0)
+
+
+def _build_mode_info() -> bytes:
+ """FileModeInformation."""
+ return struct.pack("<I", 0)
+
+
+def _build_alignment_info() -> bytes:
+ """FileAlignmentInformation."""
+ return struct.pack("<I", 0) # FILE_BYTE_ALIGNMENT
+
+
+def _build_name_info(info: HandleInfo, share_root: Path) -> bytes:
+ """FileNameInformation: relative path within share."""
+ try:
+ rel = info.path.relative_to(share_root)
+ name = "\\" + str(rel).replace("/", "\\")
+ except ValueError:
+ name = "\\"
+ name_bytes = name.encode("utf-16-le")
+ return struct.pack("<I", len(name_bytes)) + name_bytes
+
+
+def _build_network_open_info(st: os.stat_result, is_dir: bool) -> bytes:
+ """FileNetworkOpenInformation."""
+ attrs = FILE_ATTRIBUTE_DIRECTORY if is_dir else FILE_ATTRIBUTE_ARCHIVE
+ alloc_size = (st.st_size + 4095) // 4096 * 4096 if not is_dir else 0
+ eof = st.st_size if not is_dir else 0
+ return struct.pack(
+ "<QQQQQQI4x", # 4x for Reserved
+ _filetime(st.st_ctime),
+ _filetime(st.st_atime),
+ _filetime(st.st_mtime),
+ _filetime(st.st_mtime),
+ alloc_size,
+ eof,
+ attrs,
+ )
+
+
+def _build_attribute_tag_info(is_dir: bool) -> bytes:
+ """FileAttributeTagInformation."""
+ attrs = FILE_ATTRIBUTE_DIRECTORY if is_dir else FILE_ATTRIBUTE_ARCHIVE
+ return struct.pack("<II", attrs, 0) # ReparseTag = 0
+
+
+def handle_query_info(
+ req: SMBRequest,
+ handles: HandleManager,
+ shares: dict[str, dict],
+ tree_map: dict[int, str],
+) -> bytes:
+ """Handle QUERY_INFO request."""
+ payload = req.payload
+
+ # QUERY_INFO request: StructureSize(41), InfoType(1), FileInfoClass(1),
+ # OutputBufferLength(4), InputBufferOffset(2), Reserved(2),
+ # InputBufferLength(4), AdditionalInformation(4), Flags(4), FileId(16)
+ if len(payload) < 40:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ _struct_size, info_type, file_info_class, output_buffer_length = struct.unpack_from(
+ "<HBBI", payload
+ )
+ file_id = payload[24:40]
+
+ import logging
+
+ logging.getLogger("quicksand.smb").debug(
+ "QUERY_INFO: type=%d class=%d buflen=%d fid=%s",
+ info_type,
+ file_info_class,
+ output_buffer_length,
+ file_id.hex(),
+ )
+
+ info = handles.get(file_id)
+ if info is None:
+ return build_error_response(req.header, STATUS_INVALID_HANDLE)
+
+ try:
+ st = info.path.stat()
+ except OSError:
+ return build_error_response(req.header, STATUS_OBJECT_NAME_NOT_FOUND)
+
+ # Get share root for name info
+ share_name = tree_map.get(info.tree_id)
+ share_root = (
+ Path(shares[share_name]["host_path"])
+ if share_name and share_name in shares
+ else info.path.parent
+ )
+
+ if info_type == SMB2_0_INFO_FILE:
+ output = _handle_file_info(file_info_class, st, info, share_root)
+ elif info_type == SMB2_0_INFO_FILESYSTEM:
+ output = _handle_fs_info(file_info_class, info.path)
+ else:
+ output = None
+
+ if output is None:
+ return build_error_response(req.header, STATUS_NOT_SUPPORTED)
+
+ if len(output) > output_buffer_length:
+ # Truncate and return BUFFER_OVERFLOW for some info classes
+ output = output[:output_buffer_length]
+ status = STATUS_BUFFER_OVERFLOW
+ else:
+ status = STATUS_SUCCESS
+
+ # QUERY_INFO response: StructureSize(9), OutputBufferOffset(2),
+ # OutputBufferLength(4), Output(variable)
+ output_offset = 64 + 8 # header + fixed body
+ body = struct.pack(
+ "<HHI",
+ 9, # StructureSize
+ output_offset,
+ len(output),
+ )
+
+ header = build_response_header(req.header, status, len(body) + len(output))
+ return header + body + output
+
+
+def _handle_file_info(
+ info_class: int,
+ st: os.stat_result,
+ info: HandleInfo,
+ share_root: Path,
+) -> bytes | None:
+ """Build response data for SMB2_0_INFO_FILE queries."""
+ if info_class == FILE_BASIC_INFORMATION:
+ return _build_basic_info(st, info.is_dir)
+ elif info_class == FILE_STANDARD_INFORMATION:
+ return _build_standard_info(st, info.is_dir)
+ elif info_class == FILE_INTERNAL_INFORMATION:
+ return _build_internal_info(st)
+ elif info_class == FILE_EA_INFORMATION:
+ return _build_ea_info()
+ elif info_class == FILE_ACCESS_INFORMATION:
+ return _build_access_info()
+ elif info_class == FILE_POSITION_INFORMATION:
+ return _build_position_info()
+ elif info_class == FILE_MODE_INFORMATION:
+ return _build_mode_info()
+ elif info_class == FILE_ALIGNMENT_INFORMATION:
+ return _build_alignment_info()
+ elif info_class == FILE_ALL_INFORMATION:
+ # Composite: Basic(40) + Standard(24) + Internal(8) + EA(4) +
+ # Access(4) + Position(8) + Mode(4) + Alignment(4) + Name(4+var)
+ # Total fixed: 100 bytes before FileName variable part
+ data = _build_basic_info(st, info.is_dir) # 40
+ data += _build_standard_info(st, info.is_dir) # 24
+ data += _build_internal_info(st) # 8
+ data += _build_ea_info() # 4
+ data += _build_access_info() # 4
+ data += _build_position_info() # 8
+ data += _build_mode_info() # 4
+ data += _build_alignment_info() # 4
+ data += _build_name_info(info, share_root) # 4 + name bytes
+ return data
+ elif info_class == FILE_NETWORK_OPEN_INFORMATION:
+ return _build_network_open_info(st, info.is_dir)
+ elif info_class == FILE_ATTRIBUTE_TAG_INFORMATION:
+ return _build_attribute_tag_info(info.is_dir)
+ elif info_class == FILE_STREAM_INFORMATION:
+ # Return a single default data stream
+ stream_name = "::$DATA".encode("utf-16-le")
+ return (
+ struct.pack(
+ "<IIQQ",
+ 0, # NextEntryOffset
+ len(stream_name),
+ st.st_size,
+ (st.st_size + 4095) // 4096 * 4096,
+ )
+ + stream_name
+ )
+ elif info_class == FILE_COMPRESSION_INFORMATION:
+ return struct.pack("<QHBxI", st.st_size, 0, 0, 0)
+ return None
+
+
+def _handle_fs_info(info_class: int, path: Path) -> bytes | None:
+ """Build response data for SMB2_0_INFO_FILESYSTEM queries."""
+ try:
+ svfs = os.statvfs(str(path))
+ except OSError:
+ svfs = None
+
+ if info_class == FS_VOLUME_INFORMATION:
+ label = "quicksand".encode("utf-16-le")
+ return (
+ struct.pack(
+ "<QI?xI",
+ _filetime_now(), # VolumeCreationTime
+ 0x12345678, # VolumeSerialNumber
+ False, # SupportsObjects
+ len(label), # VolumeLabelLength
+ )
+ + label
+ )
+
+ elif info_class == FS_SIZE_INFORMATION:
+ if svfs is None:
+ return struct.pack("<QQIi", 0, 0, 4096, 1)
+ total_units = svfs.f_blocks
+ avail_units = svfs.f_bavail
+ return struct.pack("<QQIi", total_units, avail_units, svfs.f_frsize, 1)
+
+ elif info_class == FS_FULL_SIZE_INFORMATION:
+ if svfs is None:
+ return struct.pack("<QQQIi", 0, 0, 0, 4096, 1)
+ return struct.pack(
+ "<QQQIi",
+ svfs.f_blocks, # TotalAllocationUnits
+ svfs.f_bavail, # CallerAvailableAllocationUnits
+ svfs.f_bfree, # ActualAvailableAllocationUnits
+ svfs.f_frsize, # BytesPerSector (use fragment size)
+ 1, # SectorsPerAllocationUnit
+ )
+
+ elif info_class == FS_DEVICE_INFORMATION:
+ return struct.pack(
+ "<II",
+ 0x00000007, # FILE_DEVICE_DISK
+ 0x00000020, # FILE_DEVICE_IS_MOUNTED
+ )
+
+ elif info_class == FS_ATTRIBUTE_INFORMATION:
+ # FILE_CASE_PRESERVED_NAMES | FILE_UNICODE_ON_DISK
+ fs_name = "quicksand".encode("utf-16-le")
+ return (
+ struct.pack(
+ "<III",
+ 0x00000002 | 0x00000004, # FileSystemAttributes
+ 255, # MaximumComponentNameLength
+ len(fs_name), # FileSystemNameLength
+ )
+ + fs_name
+ )
+
+ elif info_class == FS_SECTOR_SIZE_INFORMATION:
+ return struct.pack(
+ "<IIIII",
+ 4096, # LogicalBytesPerSector
+ 4096, # PhysicalBytesPerSectorForAtomicity
+ 4096, # PhysicalBytesPerSectorForPerformance
+ 4096, # FileSystemEffectivePhysicalBytesPerSectorForAtomicity
+ 0, # Flags
+ )
+
+ return None
+
+
+# ---------------------------------------------------------------------------
+# QUERY_DIRECTORY
+# ---------------------------------------------------------------------------
+
+
+def _build_dir_entry(
+ entry: os.DirEntry | None,
+ info_class: int,
+ next_offset: int = 0,
+ root_path: Path | None = None,
+ is_dot: str | None = None,
+) -> bytes | None:
+ """Build a single directory entry in the requested format.
+
+ `is_dot` should be "." or ".." for the special entries, None for regular.
+ """
+ if is_dot:
+ name = is_dot
+ if root_path:
+ try:
+ st = root_path.stat()
+ except OSError:
+ return None
+ is_dir = root_path.is_dir()
+ else:
+ return None
+ elif entry is not None:
+ name = entry.name
+ try:
+ st = entry.stat(follow_symlinks=False)
+ except OSError:
+ return None
+ is_dir = entry.is_dir(follow_symlinks=False)
+ else:
+ return None
+
+ name_bytes = name.encode("utf-16-le")
+ attrs = FILE_ATTRIBUTE_DIRECTORY if is_dir else FILE_ATTRIBUTE_ARCHIVE
+ alloc_size = (st.st_size + 4095) // 4096 * 4096 if not is_dir else 0
+ eof = st.st_size if not is_dir else 0
+
+ if info_class in (FILE_BOTH_DIRECTORY_INFORMATION, FILE_ID_BOTH_DIRECTORY_INFORMATION):
+ # FileBothDirectoryInformation:
+ # NextEntryOffset(4), FileIndex(4), CreationTime(8), LastAccessTime(8),
+ # LastWriteTime(8), ChangeTime(8), EndOfFile(8), AllocationSize(8),
+ # FileAttributes(4), FileNameLength(4), EaSize(4), ShortNameLength(1),
+ # Reserved(1), ShortName(24), FileName(variable)
+ fixed = struct.pack(
+ "<II" # NextEntryOffset, FileIndex
+ "QQQQ" # timestamps
+ "QQ" # EOF, AllocationSize
+ "II" # FileAttributes, FileNameLength
+ "I" # EaSize
+ "Bx" # ShortNameLength, Reserved
+ "24s", # ShortName (empty)
+ 0, # NextEntryOffset (patched later)
+ 0, # FileIndex
+ _filetime(st.st_ctime),
+ _filetime(st.st_atime),
+ _filetime(st.st_mtime),
+ _filetime(st.st_mtime),
+ eof,
+ alloc_size,
+ attrs,
+ len(name_bytes),
+ 0, # EaSize
+ 0, # ShortNameLength
+ b"\x00" * 24, # ShortName
+ )
+ if info_class == FILE_ID_BOTH_DIRECTORY_INFORMATION:
+ # Additional: Reserved2(2), FileId(8) before FileName
+ fixed += struct.pack("<HQ", 0, st.st_ino)
+
+ entry_data = fixed + name_bytes
+
+ elif info_class == FILE_DIRECTORY_INFORMATION:
+ fixed = struct.pack(
+ "<IIQQQQQQII",
+ 0,
+ 0,
+ _filetime(st.st_ctime),
+ _filetime(st.st_atime),
+ _filetime(st.st_mtime),
+ _filetime(st.st_mtime),
+ eof,
+ alloc_size,
+ attrs,
+ len(name_bytes),
+ )
+ entry_data = fixed + name_bytes
+
+ elif info_class == FILE_NAMES_INFORMATION:
+ fixed = struct.pack("<III", 0, 0, len(name_bytes))
+ entry_data = fixed + name_bytes
+
+ elif info_class == FILE_ID_FULL_DIRECTORY_INFORMATION:
+ fixed = struct.pack(
+ "<II"
+ "QQQQ"
+ "QQ"
+ "II"
+ "I" # EaSize
+ "I" # Reserved
+ "Q", # FileId
+ 0,
+ 0,
+ _filetime(st.st_ctime),
+ _filetime(st.st_atime),
+ _filetime(st.st_mtime),
+ _filetime(st.st_mtime),
+ eof,
+ alloc_size,
+ attrs,
+ len(name_bytes),
+ 0, # EaSize
+ 0, # Reserved
+ st.st_ino,
+ )
+ entry_data = fixed + name_bytes
+
+ else:
+ return None
+
+ # Pad to 8-byte alignment
+ padded_len = (len(entry_data) + 7) & ~7
+ entry_data = entry_data.ljust(padded_len, b"\x00")
+
+ # Set NextEntryOffset in first 4 bytes
+ if next_offset != 0:
+ struct.pack_into("<I", bytearray(entry_data), 0, len(entry_data))
+ entry_data = bytes(bytearray(entry_data)[:4]) + entry_data[4:]
+ # Actually, let's do this properly
+ ba = bytearray(entry_data)
+ struct.pack_into("<I", ba, 0, len(ba))
+ entry_data = bytes(ba)
+
+ return entry_data
+
+
+def handle_query_directory(
+ req: SMBRequest,
+ handles: HandleManager,
+ shares: dict[str, dict],
+ tree_map: dict[int, str],
+) -> bytes:
+ """Handle QUERY_DIRECTORY request."""
+ payload = req.payload
+
+ # QUERY_DIRECTORY request: StructureSize(33), FileInfoClass(1),
+ # Flags(1), FileIndex(4), FileId(16), FileNameOffset(2),
+ # FileNameLength(2), OutputBufferLength(4)
+ if len(payload) < 32:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ _struct_size, info_class, flags, _file_index = struct.unpack_from("<HBBI", payload)
+ file_id = payload[8:24]
+ name_offset, name_length, output_buffer_length = struct.unpack_from("<HHI", payload, 24)
+ logger.debug("QUERY_DIRECTORY: info_class=%d flags=0x%x", info_class, flags)
+
+ info = handles.get(file_id)
+ if info is None:
+ return build_error_response(req.header, STATUS_INVALID_HANDLE)
+
+ if not info.is_dir:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ # Parse search pattern
+ pattern_start = name_offset - 64
+ if pattern_start >= 0 and name_length > 0 and pattern_start + name_length <= len(payload):
+ payload[pattern_start : pattern_start + name_length].decode("utf-16-le", errors="replace")
+ else:
+ pass
+
+ restart = bool(flags & SMB2_RESTART_SCANS)
+ single_entry = bool(flags & SMB2_RETURN_SINGLE_ENTRY)
+
+ # Build or reset directory listing
+ if info.dir_entries is None or restart:
+ try:
+ entries = list(os.scandir(str(info.path)))
+ except OSError:
+ return build_error_response(req.header, STATUS_OBJECT_NAME_NOT_FOUND)
+
+ # Prepend . and ..
+ info.dir_entries = ["..", "."] + [e.name for e in entries]
+ info._scandir_cache = {e.name: e for e in entries}
+ info.dir_offset = 0
+
+ if info.dir_offset >= len(info.dir_entries):
+ return build_error_response(req.header, STATUS_NO_MORE_FILES)
+
+ # Build entries fitting in output buffer
+ result_entries: list[bytes] = []
+ total_size = 0
+
+ while info.dir_offset < len(info.dir_entries):
+ entry_name = info.dir_entries[info.dir_offset]
+
+ if entry_name in (".", ".."):
+ entry_data = _build_dir_entry(None, info_class, root_path=info.path, is_dot=entry_name)
+ else:
+ scandir_entry = info._scandir_cache.get(entry_name) if info._scandir_cache else None
+ if scandir_entry is None:
+ info.dir_offset += 1
+ continue
+ entry_data = _build_dir_entry(scandir_entry, info_class)
+
+ if entry_data is None:
+ info.dir_offset += 1
+ continue
+
+ if total_size + len(entry_data) > output_buffer_length:
+ if not result_entries:
+ # First entry doesn't fit — buffer too small
+ return build_error_response(req.header, STATUS_BUFFER_TOO_SMALL)
+ break
+
+ result_entries.append(entry_data)
+ total_size += len(entry_data)
+ info.dir_offset += 1
+
+ if single_entry:
+ break
+
+ if not result_entries:
+ return build_error_response(req.header, STATUS_NO_MORE_FILES)
+
+ # Chain entries: set NextEntryOffset for all except last
+ output = bytearray()
+ for i, entry in enumerate(result_entries):
+ ba = bytearray(entry)
+ if i < len(result_entries) - 1:
+ struct.pack_into("<I", ba, 0, len(ba)) # NextEntryOffset = own length
+ else:
+ struct.pack_into("<I", ba, 0, 0) # Last entry: 0
+ output.extend(ba)
+
+ output = bytes(output)
+
+ # QUERY_DIRECTORY response: StructureSize(9), OutputBufferOffset(2),
+ # OutputBufferLength(4), Output(variable)
+ output_offset = 64 + 8 # header + fixed body
+ body = struct.pack(
+ "<HHI",
+ 9,
+ output_offset,
+ len(output),
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body) + len(output))
+ return header + body + output
+
+
+# ---------------------------------------------------------------------------
+# SET_INFO
+# ---------------------------------------------------------------------------
+
+
+def handle_set_info(
+ req: SMBRequest,
+ handles: HandleManager,
+) -> bytes:
+ """Handle SET_INFO request."""
+ payload = req.payload
+
+ # SET_INFO request: StructureSize(33), InfoType(1), FileInfoClass(1),
+ # BufferLength(4), BufferOffset(2), Reserved(2),
+ # AdditionalInformation(4), FileId(16)
+ if len(payload) < 32:
+ return build_error_response(req.header, STATUS_INVALID_PARAMETER)
+
+ _struct_size, info_type, file_info_class, buffer_length = struct.unpack_from("<HBBI", payload)
+ buffer_offset = struct.unpack_from("<H", payload, 8)[0]
+ file_id = payload[16:32]
+
+ info = handles.get(file_id)
+ if info is None:
+ return build_error_response(req.header, STATUS_INVALID_HANDLE)
+
+ # Extract the input buffer
+ buf_start = buffer_offset - 64
+ if buf_start < 0:
+ buf_start = 32
+ buffer_data = payload[buf_start : buf_start + buffer_length]
+
+ if info_type == SMB2_0_INFO_FILE:
+ result = _handle_set_file_info(file_info_class, buffer_data, info)
+ else:
+ result = STATUS_NOT_SUPPORTED
+
+ if result != STATUS_SUCCESS:
+ return build_error_response(req.header, result)
+
+ # SET_INFO response: StructureSize(2)
+ body = struct.pack("<H", 2)
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body))
+ return header + body
+
+
+def _handle_set_file_info(
+ info_class: int,
+ data: bytes,
+ info: HandleInfo,
+) -> int:
+ """Apply SET_INFO for file info classes. Returns NTSTATUS."""
+ if info.readonly:
+ return STATUS_ACCESS_DENIED
+
+ if info_class == FILE_BASIC_INFORMATION:
+ # CreationTime(8), LastAccessTime(8), LastWriteTime(8), ChangeTime(8), FileAttributes(4)
+ if len(data) < 36:
+ return STATUS_INVALID_PARAMETER
+ _creation, last_access, last_write, _change, _attrs = struct.unpack_from("<QQQQI", data)
+ try:
+ # Convert FILETIME to Unix time (only if non-zero)
+ atime = (last_access / 10_000_000 - 11644473600) if last_access else None
+ mtime = (last_write / 10_000_000 - 11644473600) if last_write else None
+ if atime is not None or mtime is not None:
+ cur_st = info.path.stat()
+ os.utime(
+ str(info.path),
+ (atime or cur_st.st_atime, mtime or cur_st.st_mtime),
+ )
+ except OSError:
+ pass # Best effort
+ return STATUS_SUCCESS
+
+ elif info_class == FILE_DISPOSITION_INFORMATION:
+ if len(data) < 1:
+ return STATUS_INVALID_PARAMETER
+ delete_pending = struct.unpack_from("<B", data)[0]
+ info.delete_on_close = bool(delete_pending)
+ return STATUS_SUCCESS
+
+ elif info_class == FILE_END_OF_FILE_INFORMATION:
+ if len(data) < 8:
+ return STATUS_INVALID_PARAMETER
+ new_size = struct.unpack_from("<Q", data)[0]
+ try:
+ if info.fd >= 0:
+ os.ftruncate(info.fd, new_size)
+ except OSError:
+ return STATUS_ACCESS_DENIED
+ return STATUS_SUCCESS
+
+ elif info_class == FILE_ALLOCATION_INFORMATION:
+ # Can treat same as end-of-file for our purposes
+ if len(data) < 8:
+ return STATUS_INVALID_PARAMETER
+ return STATUS_SUCCESS # No-op
+
+ elif info_class == FILE_RENAME_INFORMATION:
+ # ReplaceIfExists(1), Reserved(7), RootDirectory(8),
+ # FileNameLength(4), FileName(variable)
+ if len(data) < 20:
+ return STATUS_INVALID_PARAMETER
+ replace_if_exists = struct.unpack_from("<B", data)[0]
+ name_length = struct.unpack_from("<I", data, 16)[0]
+ name_bytes = data[20 : 20 + name_length]
+ new_name = name_bytes.decode("utf-16-le", errors="replace")
+ # The name might be a full path like \newname or just newname
+ new_name = new_name.lstrip("\\").replace("\\", "/")
+ new_path = info.path.parent / new_name
+
+ try:
+ if new_path.exists() and not replace_if_exists:
+ from ._status import STATUS_OBJECT_NAME_COLLISION
+
+ return STATUS_OBJECT_NAME_COLLISION
+ os.rename(str(info.path), str(new_path))
+ info.path = new_path
+ except OSError:
+ return STATUS_ACCESS_DENIED
+ return STATUS_SUCCESS
+
+ return STATUS_NOT_SUPPORTED
diff --git a/packages/quicksand-smb/quicksand_smb/_status.py b/packages/quicksand-smb/quicksand_smb/_status.py
new file mode 100644
index 0000000..cee8fb5
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/_status.py
@@ -0,0 +1,41 @@
+"""NTSTATUS codes used by the SMB3 server.
+
+Reference: [MS-ERREF] Section 2.3 — NTSTATUS values.
+"""
+
+# Success
+STATUS_SUCCESS = 0x00000000
+STATUS_PENDING = 0x00000103
+
+# Informational
+STATUS_BUFFER_OVERFLOW = 0x80000005
+STATUS_NO_MORE_FILES = 0x80000006
+
+# Warning
+STATUS_MORE_PROCESSING_REQUIRED = 0xC0000016
+
+# Error
+STATUS_UNSUCCESSFUL = 0xC0000001
+STATUS_NOT_IMPLEMENTED = 0xC0000002
+STATUS_INVALID_PARAMETER = 0xC000000D
+STATUS_NO_SUCH_FILE = 0xC000000F
+STATUS_END_OF_FILE = 0xC0000011
+STATUS_ACCESS_DENIED = 0xC0000022
+STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034
+STATUS_OBJECT_NAME_COLLISION = 0xC0000035
+STATUS_OBJECT_PATH_NOT_FOUND = 0xC000003A
+STATUS_BAD_NETWORK_NAME = 0xC00000CC
+STATUS_NOT_SUPPORTED = 0xC00000BB
+STATUS_FILE_IS_A_DIRECTORY = 0xC00000BA
+STATUS_DIRECTORY_NOT_EMPTY = 0xC0000101
+STATUS_NOT_A_DIRECTORY = 0xC0000103
+STATUS_INVALID_HANDLE = 0xC0000008
+STATUS_FILE_CLOSED = 0xC0000128
+STATUS_OBJECT_NAME_INVALID = 0xC0000033
+STATUS_SHARING_VIOLATION = 0xC0000043
+STATUS_LOGON_FAILURE = 0xC000006D
+STATUS_USER_SESSION_DELETED = 0xC0000203
+STATUS_NETWORK_NAME_DELETED = 0xC00000C9
+STATUS_BUFFER_TOO_SMALL = 0xC0000023
+STATUS_NO_SUCH_DEVICE = 0xC000000E
+STATUS_INVALID_DEVICE_REQUEST = 0xC0000010
diff --git a/packages/quicksand-smb/quicksand_smb/_tree.py b/packages/quicksand-smb/quicksand_smb/_tree.py
new file mode 100644
index 0000000..c2ffd0d
--- /dev/null
+++ b/packages/quicksand-smb/quicksand_smb/_tree.py
@@ -0,0 +1,93 @@
+"""TREE_CONNECT and TREE_DISCONNECT handlers.
+
+TREE_CONNECT maps a UNC share path (e.g., \\\\10.0.2.100\\SHARE_NAME) to a
+host directory. TREE_DISCONNECT releases the mapping.
+
+Reference: [MS-SMB2] Sections 2.2.9-2.2.10.
+"""
+
+from __future__ import annotations
+
+import struct
+
+from ._protocol import SMBRequest, build_error_response, build_response_header
+from ._status import STATUS_BAD_NETWORK_NAME, STATUS_SUCCESS
+
+# Share type constants
+SMB2_SHARE_TYPE_DISK = 0x01
+SMB2_SHARE_TYPE_PIPE = 0x02
+
+
+def handle_tree_connect(
+ req: SMBRequest,
+ shares: dict[str, dict],
+ tree_map: dict[int, str],
+ next_tree_id: int,
+) -> tuple[bytes, int | None]:
+ """Handle TREE_CONNECT. Returns (response_bytes, new_tree_id or None on failure)."""
+ payload = req.payload
+
+ # TREE_CONNECT request body:
+ # StructureSize(9), Reserved/Flags(2), PathOffset(2), PathLength(2)
+ _struct_size, _flags, path_offset, path_length = struct.unpack_from("<HHHH", payload)
+
+ # PathOffset is from start of SMB header. Payload starts at byte 64.
+ path_start = path_offset - 64
+ if path_start < 0 or path_start + path_length > len(payload):
+ return build_error_response(req.header, STATUS_BAD_NETWORK_NAME), None
+
+ path_bytes = payload[path_start : path_start + path_length]
+ path_str = path_bytes.decode("utf-16-le", errors="replace")
+
+ # Extract share name: \\server\SHARE_NAME → SHARE_NAME
+ parts = path_str.replace("\\", "/").strip("/").split("/")
+ share_name = parts[-1] if parts else ""
+
+ # Case-insensitive lookup. Also accept IPC$ (required by CIFS clients).
+ is_ipc = share_name.upper() == "IPC$"
+
+ share_info = None
+ if not is_ipc:
+ for name, info in shares.items():
+ if name.upper() == share_name.upper():
+ share_info = info
+ share_name = name
+ break
+
+ if share_info is None:
+ return build_error_response(req.header, STATUS_BAD_NETWORK_NAME), None
+
+ tree_id = next_tree_id
+ tree_map[tree_id] = "IPC$" if is_ipc else share_name
+
+ # TREE_CONNECT response:
+ # StructureSize(16), ShareType(1), Reserved(1), ShareFlags(4),
+ # Capabilities(4), MaximalAccess(4)
+ share_type = SMB2_SHARE_TYPE_PIPE if is_ipc else SMB2_SHARE_TYPE_DISK
+ body = struct.pack(
+ "<H" # StructureSize (16)
+ "B" # ShareType
+ "B" # Reserved
+ "I" # ShareFlags
+ "I" # Capabilities
+ "I", # MaximalAccess
+ 16,
+ share_type,
+ 0, # Reserved
+ 0, # ShareFlags (no caching, no DFS)
+ 0, # Capabilities
+ 0x001F01FF, # MaximalAccess: FILE_ALL_ACCESS
+ )
+
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body), tree_id=tree_id)
+ return header + body, tree_id
+
+
+def handle_tree_disconnect(req: SMBRequest, tree_map: dict[int, str]) -> bytes:
+ """Handle TREE_DISCONNECT. Returns response bytes."""
+ tree_map.pop(req.header.tree_id, None)
+
+ # TREE_DISCONNECT response: StructureSize(4), Reserved(2)
+ body = struct.pack("<HH", 4, 0)
+ header = build_response_header(req.header, STATUS_SUCCESS, len(body))
+ return header + body
diff --git a/packages/quicksand-ubuntu-desktop/README.md b/packages/quicksand-ubuntu-desktop/README.md
new file mode 100644
index 0000000..65f5b21
--- /dev/null
+++ b/packages/quicksand-ubuntu-desktop/README.md
@@ -0,0 +1,92 @@
+# Quicksand Ubuntu Desktop
+
+Pre-built Ubuntu 24.04 Desktop VM image with Xfce4 for the [quicksand](https://github.com/microsoft/quicksand) agent harness. Gives your agent a full graphical Linux desktop with keyboard, mouse, and screenshot control.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install ubuntu-desktop
+quicksand images install ubuntu-desktop
+```
+
+The image (~7.3GB) is downloaded and cached at `~/.quicksand/images/` on first install.
+
+## Usage
+
+```python
+import asyncio
+from quicksand import Key
+from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+
+async def main():
+ async with UbuntuDesktopSandbox() as sb:
+ # Take a screenshot
+ await sb.screenshot("desktop.png")
+
+ # Type text and press keys
+ await sb.type_text("echo hello world")
+ await sb.press_key(Key.RET)
+
+ # Mouse control (absolute coordinates 0-32767)
+ await sb.mouse_move(16383, 16383)
+ await sb.mouse_click()
+
+ # execute() still works alongside GUI input
+ result = await sb.execute("uname -a")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+
+async with UbuntuDesktopSandbox(memory="4G", cpus=4) as sb:
+ await sb.screenshot("desktop.png")
+```
+
+## What's Included
+
+- Ubuntu 24.04 with Xfce4 desktop + LightDM (auto-login, no password prompt)
+- Firefox ESR browser
+- Full apt/deb ecosystem
+- Python 3, bash, curl, ca-certificates
+- The quicksand guest agent (pre-installed)
+- Software rendering via Mesa (`LIBGL_ALWAYS_SOFTWARE=1`)
+
+## Default Config
+
+| Setting | Default |
+|---------|---------|
+| Memory | 1G |
+| CPUs | 2 |
+| Display | Enabled (always) |
+| Boot timeout | 60s |
+| Init system | systemd |
+
+## Desktop API
+
+All methods are async:
+
+- `await screenshot(path)` — save the guest display as a PNG
+- `await type_text(text)` — type a string via keyboard events
+- `await press_key(*keys)` — press a key combo, e.g. `press_key(Key.CTRL, Key.C)`
+- `await mouse_move(x, y)` — move mouse to absolute position (0-32767 range)
+- `await mouse_click(button, double=False)` — click `"left"`, `"right"`, `"middle"`, `"wheel-up"`, or `"wheel-down"`
+- `await query_display_size()` — get display resolution as `(width, height)`
+- `await execute(cmd)` — run a shell command (same as headless sandboxes)
+- `vnc_port` — host-side VNC port for connecting a viewer
+
+All standard sandbox features (mounts, save/load, network config) work with desktop sandboxes too.
+
+## License
+
+MIT
diff --git a/packages/quicksand-ubuntu-desktop/hatch_build.py b/packages/quicksand-ubuntu-desktop/hatch_build.py
new file mode 100644
index 0000000..6d6f485
--- /dev/null
+++ b/packages/quicksand-ubuntu-desktop/hatch_build.py
@@ -0,0 +1,202 @@
+"""Hatch build hook for the Ubuntu Desktop overlay.
+
+Boots Ubuntu base, installs Xfce4 desktop environment with X.org, LightDM,
+Firefox ESR, and supporting services, then saves the overlay.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+from collections.abc import Callable, Coroutine
+from pathlib import Path
+from typing import Any
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+SAVE_NAME = "ubuntu-desktop"
+SHELL = "/bin/bash"
+
+logger = logging.getLogger("ubuntu-desktop")
+
+
+async def _setup(shell: Callable[..., Coroutine[Any, Any, Any]]) -> None:
+ """Install Xfce4 desktop environment on Ubuntu base."""
+
+ # ── Install Xfce4 desktop packages ───────────────────────────
+ await shell("DEBIAN_FRONTEND=noninteractive apt-get update", timeout=120)
+ await shell(
+ "DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "
+ "xserver-xorg-core xserver-xorg-video-modesetting xserver-xorg-input-libinput",
+ timeout=300,
+ )
+ await shell(
+ "DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "
+ "xfce4-session xfce4-panel xfce4-terminal xfce4-settings "
+ "xfwm4 xfdesktop4 thunar",
+ timeout=300,
+ )
+ await shell(
+ "DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "
+ "lightdm lightdm-gtk-greeter dbus-x11 libgl1-mesa-dri fonts-dejavu-core",
+ timeout=300,
+ )
+
+ # ── Install Firefox ESR from Mozilla PPA ─────────────────────
+ await shell(
+ "DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "
+ "software-properties-common",
+ timeout=120,
+ )
+ await shell(
+ "add-apt-repository -y ppa:mozillateam/ppa && "
+ "printf 'Package: firefox*\\nPin: release o=LP-PPA-mozillateam\\n"
+ "Pin-Priority: 1001\\n' > /etc/apt/preferences.d/mozilla-firefox",
+ timeout=120,
+ )
+ await shell("apt-get update", timeout=120)
+ await shell(
+ "DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends firefox-esr",
+ timeout=300,
+ )
+ await shell(
+ "apt-get remove --purge -y software-properties-common && apt-get autoremove --purge -y",
+ timeout=120,
+ )
+
+ # ── LightDM auto-login ───────────────────────────────────────
+ await shell(
+ "mkdir -p /etc/lightdm && "
+ "printf '[Seat:*]\\nautologin-user=quicksand\\nautologin-session=xfce\\n"
+ "user-session=xfce\\n' > /etc/lightdm/lightdm.conf"
+ )
+
+ # ── Mesa software rendering ──────────────────────────────────
+ await shell("echo 'LIBGL_ALWAYS_SOFTWARE=1' >> /etc/environment")
+
+ # ── Kernel module: virtio-gpu ────────────────────────────────
+ await shell("echo virtio-gpu >> /etc/modules")
+
+ # ── Switch default target to graphical ───────────────────────
+ await shell("systemctl set-default graphical.target")
+
+ # ── Xorg config ──────────────────────────────────────────────
+ await shell(
+ """mkdir -p /etc/X11
+cat > /etc/X11/xorg.conf << 'XORGEOF'
+# Quicksand Xorg configuration for QEMU virtio-gpu virtual display.
+#
+# We do NOT set AutoAddDevices=False here. The USB tablet (event1) and VirtIO
+# keyboard (event2) are enumerated by udev a few milliseconds after X starts;
+# letting Xorg auto-add them via the config/udev backend is the only reliable
+# way to get input working, because static InputDevice entries run at PreInit
+# time (before udev has finished, so libinput fails with ENODEV).
+
+Section "Device"
+ Identifier "VirtualGPU"
+ Driver "modesetting"
+ Option "kmsdev" "/dev/dri/card0"
+ # Render cursor into the framebuffer so QMP screendump captures it.
+ Option "SWcursor" "true"
+EndSection
+
+Section "Screen"
+ Identifier "DefaultScreen"
+ Device "VirtualGPU"
+EndSection
+XORGEOF"""
+ )
+
+ # ── Xfce4 pre-configuration ──────────────────────────────────
+ await shell(
+ "mkdir -p /home/quicksand/.config/xfce4/xfconf/xfce-perchannel-xml && "
+ "chown -R quicksand:quicksand /home/quicksand/.config"
+ )
+
+ # ── Clean package caches ─────────────────────────────────────
+ await shell("apt-get clean")
+ await shell("rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/* /tmp/*")
+
+
+class OverlayImageBuildHook(BuildHookInterface):
+ """Build hook that creates an overlay save from a running Ubuntu sandbox."""
+
+ PLUGIN_NAME = "ubuntu-desktop-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ from quicksand_image_tools.build_utils import set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+
+ pkg_dir = Path(self.root) / "quicksand_ubuntu_desktop"
+ save_dir = pkg_dir / "images"
+ overlays_dir = save_dir / "overlays"
+
+ if not (save_dir / "manifest.json").exists() or not any(overlays_dir.glob("*.qcow2")):
+ self.app.display_info("Save not found, building overlay...")
+ asyncio.run(self._build_and_save(save_dir))
+
+ self.app.display_info(f"Including save: {save_dir}")
+
+ async def _build_and_save(self, save_dir: Path) -> None:
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+
+ from quicksand_core._types import NetworkMode
+ from quicksand_ubuntu import UbuntuSandbox
+
+ async with UbuntuSandbox(
+ memory="4G",
+ cpus=4,
+ network_mode=NetworkMode.FULL,
+ disk_size="5G",
+ ) as sb:
+ await _setup(_make_shell(sb))
+ await sb.save(SAVE_NAME, workspace=save_dir.parent, compress=True)
+
+ built = save_dir.parent / SAVE_NAME
+ if save_dir.exists():
+ shutil.rmtree(save_dir)
+ built.rename(save_dir)
+
+
+def _make_shell(sb) -> Callable[..., Coroutine[Any, Any, Any]]:
+ """Create a shell callable that streams output and raises on failure."""
+ stdout_buf: list[str] = []
+ stderr_buf: list[str] = []
+
+ def _flush_lines(buf: list[str], log_fn) -> None:
+ text = "".join(buf)
+ buf.clear()
+ for line in text.splitlines():
+ if line:
+ log_fn("%s", line)
+
+ def _on_stdout(chunk: str) -> None:
+ stdout_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stdout_buf, logger.info)
+
+ def _on_stderr(chunk: str) -> None:
+ stderr_buf.append(chunk)
+ if "\n" in chunk:
+ _flush_lines(stderr_buf, logger.warning)
+
+ async def shell(cmd: str, **kwargs) -> None:
+ logger.info(">>> %s", cmd)
+ stdout_buf.clear()
+ stderr_buf.clear()
+ result = await sb.execute(
+ cmd,
+ shell=SHELL,
+ on_stdout=_on_stdout,
+ on_stderr=_on_stderr,
+ **kwargs,
+ )
+ _flush_lines(stdout_buf, logger.info)
+ _flush_lines(stderr_buf, logger.warning)
+ if result.exit_code != 0:
+ raise RuntimeError(f"Command failed (exit {result.exit_code}): {cmd}\n{result.stderr}")
+
+ return shell
diff --git a/packages/quicksand-ubuntu-desktop/pyproject.toml b/packages/quicksand-ubuntu-desktop/pyproject.toml
new file mode 100644
index 0000000..05b8054
--- /dev/null
+++ b/packages/quicksand-ubuntu-desktop/pyproject.toml
@@ -0,0 +1,35 @@
+[project]
+name = "quicksand-ubuntu-desktop"
+version = "0.8.4"
+description = "Ubuntu 24.04 Desktop VM (Xfce4) for quicksand"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+ "quicksand-ubuntu>=0.8.4",
+]
+
+[dependency-groups]
+dev = []
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "quicksand-ubuntu", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_ubuntu_desktop"]
+artifacts = [
+ "quicksand_ubuntu_desktop/images/manifest.json",
+ "quicksand_ubuntu_desktop/images/overlays/*.qcow2",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
+quicksand-ubuntu = { workspace = true }
+
+[project.entry-points."quicksand.images"]
+ubuntu-desktop = "quicksand_ubuntu_desktop:image"
diff --git a/packages/quicksand-ubuntu-desktop/quicksand_ubuntu_desktop/__init__.py b/packages/quicksand-ubuntu-desktop/quicksand_ubuntu_desktop/__init__.py
new file mode 100644
index 0000000..37c804f
--- /dev/null
+++ b/packages/quicksand-ubuntu-desktop/quicksand_ubuntu_desktop/__init__.py
@@ -0,0 +1,99 @@
+"""
+Quicksand Ubuntu Desktop bundles an Ubuntu 24.04 VM with Xfce4 desktop.
+
+Full apt/deb ecosystem with guest agent support — both execute() and
+GUI input (screenshot/type_text/click) work. Built as an overlay on
+quicksand-ubuntu.
+
+Quick start:
+ import asyncio
+ from quicksand import Key
+ from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+
+ async def main():
+ async with UbuntuDesktopSandbox() as sb:
+ await sb.screenshot("desktop.png")
+ await sb.type_text("hello world")
+ await sb.press_key(Key.RET)
+ result = await sb.execute("apt list --installed")
+
+ asyncio.run(main())
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import Sandbox
+from quicksand_core._types import SandboxConfigParams
+
+__version__ = "0.2.3"
+
+DISTRO_VERSION = "24.04"
+
+_PACKAGE_DIR = Path(__file__).parent
+_IMAGES_DIR = _PACKAGE_DIR / "images"
+
+
+class _UbuntuDesktopImageProvider:
+ """ImageProvider for the bundled Ubuntu Desktop overlay."""
+
+ name = "ubuntu-desktop"
+ type = "overlay"
+ images_dir = _IMAGES_DIR
+
+ def resolve(self, arch: str | None = None):
+ 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."
+ )
+ return ImageResolver()._resolve_save(_IMAGES_DIR)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _UbuntuDesktopImageProvider()
+
+
+class UbuntuDesktopSandbox(Sandbox):
+ """Pre-configured Sandbox with an Ubuntu 24.04 Xfce4 desktop.
+
+ Full apt/deb ecosystem with guest agent support.
+
+ Usage::
+
+ async with UbuntuDesktopSandbox() as sb:
+ await sb.screenshot("boot.png")
+ await sb.type_text("hello")
+ await sb.press_key(Key.RET)
+ result = await sb.execute("uname -a")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "ubuntu-desktop")
+ kwargs.setdefault("memory", "1G")
+ kwargs.setdefault("cpus", 2)
+ kwargs.setdefault("enable_display", True)
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
+
+
+__all__ = [
+ "UbuntuDesktopSandbox",
+ "__version__",
+]
diff --git a/packages/quicksand-ubuntu/README.md b/packages/quicksand-ubuntu/README.md
new file mode 100644
index 0000000..461e6cd
--- /dev/null
+++ b/packages/quicksand-ubuntu/README.md
@@ -0,0 +1,69 @@
+# Quicksand Ubuntu
+
+This package bundles a pre-built Ubuntu 24.04 VM image for the [quicksand](https://github.com/microsoft/quicksand) agent harness. No downloads required after installation.
+
+Ubuntu is ideal for AI agents that need a full Linux environment with the apt package manager and broad software compatibility.
+
+## Installation
+
+Install quicksand CLI first:
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+```bash
+quicksand install ubuntu
+```
+
+This installs `quicksand` with the bundled Ubuntu 24.04 image.
+
+## Usage
+
+### Simple (recommended)
+
+```python
+import asyncio
+from quicksand import UbuntuSandbox
+
+async def main():
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+### With custom config
+
+```python
+from quicksand import UbuntuSandbox
+
+async with UbuntuSandbox(memory="2G", cpus=4) as sb:
+ result = await sb.execute("uname -a")
+```
+
+Or using `Sandbox` directly:
+
+```python
+from quicksand import Sandbox
+
+async with Sandbox(image="ubuntu", memory="2G", cpus=4) as sb:
+ result = await sb.execute("uname -a")
+```
+
+## What's Included
+
+The Ubuntu 24.04 image includes:
+- Python 3
+- Bash, curl, ca-certificates
+- Networking tools
+- The quicksand agent (pre-installed and configured)
+
+## Package Size
+
+The wheel is ~300MB because it includes the full VM image. This is intentional - it eliminates runtime downloads and ensures reproducible environments.
+
+## License
+
+MIT
diff --git a/packages/quicksand-ubuntu/hatch_build.py b/packages/quicksand-ubuntu/hatch_build.py
new file mode 100644
index 0000000..6f0b7af
--- /dev/null
+++ b/packages/quicksand-ubuntu/hatch_build.py
@@ -0,0 +1,76 @@
+"""Hatch build hook for platform-specific Ubuntu VM image wheels."""
+
+from __future__ import annotations
+
+import logging
+import re
+from pathlib import Path
+
+from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+
+logger = logging.getLogger(__name__)
+
+
+def _read_distro_version(root: Path) -> str:
+ """Read DISTRO_VERSION from __init__.py without importing the module."""
+ init_file = root / "quicksand_ubuntu" / "__init__.py"
+ content = init_file.read_text()
+ match = re.search(r'^DISTRO_VERSION\s*=\s*["\']([^"\']+)["\']', content, re.MULTILINE)
+ if not match:
+ raise RuntimeError(f"Could not find DISTRO_VERSION in {init_file}")
+ return match.group(1)
+
+
+class UbuntuImageBuildHook(BuildHookInterface):
+ """Build hook that packages Ubuntu VM images with platform-specific wheel tags."""
+
+ PLUGIN_NAME = "ubuntu-image"
+
+ def initialize(self, version: str, build_data: dict) -> None:
+ """Verify the image exists (building if needed) and set platform-specific wheel tags."""
+ from quicksand_image_tools.build_utils import get_image_arch, set_platform_wheel_tag
+
+ if not set_platform_wheel_tag(build_data, target_name=self.target_name, version=version):
+ return
+ arch = get_image_arch()
+
+ # Check if image exists
+ distro_version = _read_distro_version(Path(self.root))
+
+ pkg_dir = Path(self.root) / "quicksand_ubuntu"
+ images_dir = pkg_dir / "images"
+ image_path = images_dir / f"ubuntu-{distro_version}-{arch}.qcow2"
+ dockerfile_path = Path(self.root) / "quicksand_ubuntu" / "docker" / "Dockerfile"
+
+ if not image_path.exists():
+ self.app.display_info(f"Image not found: {image_path.name}, building...")
+ self._build_image(dockerfile_path, image_path)
+
+ self.app.display_info(f"Including image: {image_path}")
+
+ def _build_image(self, dockerfile: Path, output: Path) -> None:
+ """Build the VM image using quicksand-image-tools.
+
+ The Dockerfile uses a multi-stage build to compile the Rust agent.
+ The agent source is accessed via symlink at docker/agent/.
+ """
+ try:
+ from quicksand_image_tools import build_image
+
+ logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
+ build_log = logging.getLogger("quicksand-ubuntu")
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ build_image(dockerfile, output_path=output, log=build_log)
+
+ except ImportError as e:
+ raise RuntimeError(
+ f"quicksand-image-tools is required to build images but failed to import: {e}\n\n"
+ f"This should be installed automatically as a build dependency.\n"
+ f"If building manually, install it first:\n"
+ f" pip install quicksand-image-tools"
+ ) from e
+ except Exception as e:
+ raise RuntimeError(
+ f"Failed to build image: {e}\n\nMake sure Docker is running and accessible."
+ ) from e
diff --git a/packages/quicksand-ubuntu/pyproject.toml b/packages/quicksand-ubuntu/pyproject.toml
new file mode 100644
index 0000000..2260f9d
--- /dev/null
+++ b/packages/quicksand-ubuntu/pyproject.toml
@@ -0,0 +1,39 @@
+[project]
+name = "quicksand-ubuntu"
+version = "0.8.4"
+description = "Pre-built Ubuntu 24.04 VM image for quicksand"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.2",
+]
+
+[dependency-groups]
+dev = ["quicksand-image-tools>=0.4.3"]
+
+[build-system]
+requires = ["hatchling", "quicksand-image-tools", "quicksand-core", "quicksand-qemu", "quicksand-smb"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand_ubuntu"]
+artifacts = [
+ "quicksand_ubuntu/images/*.qcow2",
+ "quicksand_ubuntu/images/*.kernel",
+ "quicksand_ubuntu/images/*.initrd",
+]
+exclude = [
+ "quicksand_ubuntu/docker",
+ "quicksand_ubuntu/docker-desktop",
+]
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+
+[tool.uv.sources]
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
+# Build hook in hatch_build.py builds images if they don't exist
+
+[project.entry-points."quicksand.images"]
+ubuntu = "quicksand_ubuntu:image"
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/__init__.py b/packages/quicksand-ubuntu/quicksand_ubuntu/__init__.py
new file mode 100644
index 0000000..3cb862e
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/__init__.py
@@ -0,0 +1,137 @@
+"""
+Quicksand Ubuntu bundles a pre-built Ubuntu 24.04 VM image for the quicksand
+agent harness. No downloads required after installation.
+
+Ubuntu is ideal for AI agents that need a full Linux environment with the apt
+package manager and broad software compatibility.
+
+Quick start:
+ import asyncio
+ from quicksand import UbuntuSandbox
+
+ async def main():
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+ print(result.stdout)
+
+ asyncio.run(main())
+
+Or with custom configuration:
+ from quicksand import Sandbox
+
+ async with Sandbox(image="ubuntu", memory="4G", cpus=4) as sb:
+ result = await sb.execute("cat /etc/os-release")
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+from typing import Unpack
+
+from quicksand_core import ResolvedImage, Sandbox
+from quicksand_core._types import SandboxConfigParams
+from quicksand_core.host import Architecture
+from quicksand_core.qemu.platform import get_platform_config
+
+__version__ = "0.1.14"
+
+DISTRO_VERSION = "24.04"
+
+_PACKAGE_DIR = Path(__file__).parent
+_IMAGES_DIR = _PACKAGE_DIR / "images"
+_DOCKER_DIR = _PACKAGE_DIR / "docker"
+
+
+class _UbuntuImageProvider:
+ """ImageProvider for the bundled Ubuntu base image."""
+
+ name = "ubuntu"
+ type = "base"
+ images_dir = _IMAGES_DIR
+
+ def resolve(self, arch: str | None = None) -> ResolvedImage:
+ return _get_image_artifacts(arch)
+
+
+# Module-level instance — registered as quicksand.images entry point
+image = _UbuntuImageProvider()
+
+
+def _get_image_artifacts(arch: str | None = None) -> ResolvedImage:
+ if arch is None:
+ config = get_platform_config()
+ arch = "arm64" if config.arch.arch_type == Architecture.ARM64 else "amd64"
+
+ image_path = _IMAGES_DIR / f"ubuntu-{DISTRO_VERSION}-{arch}.qcow2"
+
+ if not image_path.exists():
+ image_path = _IMAGES_DIR / f"ubuntu-{DISTRO_VERSION}.qcow2"
+
+ if not image_path.exists():
+ available = list(_IMAGES_DIR.glob("*.qcow2")) if _IMAGES_DIR.exists() else []
+ if available:
+ available_str = ", ".join(p.name for p in available)
+ from quicksand_core.host.arch import _is_emulated
+
+ if _is_emulated():
+ raise FileNotFoundError(
+ f"Ubuntu image for {arch} not found. Available: {available_str}\n"
+ "Python is running under platform emulation, so pip installed "
+ "the wrong architecture variant.\n"
+ "Reinstall with: quicksand install quicksand-ubuntu"
+ )
+ raise FileNotFoundError(
+ f"Ubuntu image for {arch} not found. Available: {available_str}\n"
+ "Reinstall with: quicksand install quicksand-ubuntu"
+ )
+ raise FileNotFoundError(
+ f"No Ubuntu images found in {_IMAGES_DIR}. "
+ "The package may not have been built correctly."
+ )
+
+ return ResolvedImage(
+ name="ubuntu",
+ chain=[image_path],
+ kernel=image_path.with_suffix(".kernel"),
+ initrd=image_path.with_suffix(".initrd"),
+ )
+
+
+class UbuntuSandbox(Sandbox):
+ """Pre-configured Sandbox using the bundled Ubuntu image.
+
+ Usage::
+
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("cat /etc/os-release")
+
+ async with UbuntuSandbox(save="my-env") as sb:
+ await sb.execute("pip install numpy")
+
+ async with UbuntuSandbox(image="my-env") as sb:
+ await sb.execute("python3 -c 'import numpy'")
+ """
+
+ def __init__(
+ self,
+ *,
+ progress_callback: Callable[[str, int, int], None] | None = None,
+ save: str | None = None,
+ workspace: str | Path | None = None,
+ **kwargs: Unpack[SandboxConfigParams],
+ ) -> None:
+ kwargs.setdefault("image", "ubuntu")
+ super().__init__(
+ progress_callback=progress_callback,
+ save=save,
+ workspace=workspace,
+ **kwargs,
+ )
+
+
+__all__ = [
+ "DISTRO_VERSION",
+ "UbuntuSandbox",
+ "__version__",
+]
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/.gitignore b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/.gitignore
new file mode 100644
index 0000000..3ba6249
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/.gitignore
@@ -0,0 +1 @@
+agent/
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/80-dhcp.network b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/80-dhcp.network
new file mode 100644
index 0000000..dc83b95
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/80-dhcp.network
@@ -0,0 +1,10 @@
+[Match]
+# Match both predictable names (en*: ens3, enp0s3) and classic names (eth0)
+# Classic names are used by virtio-mmio devices (microvm machine type)
+Name=e*
+
+[Network]
+# Static IP — QEMU slirp always uses 10.0.2.0/24
+Address=10.0.2.15/24
+Gateway=10.0.2.2
+DNS=10.0.2.3
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/Dockerfile b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/Dockerfile
new file mode 100644
index 0000000..c95e38e
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/Dockerfile
@@ -0,0 +1,95 @@
+# Quicksand Ubuntu 24.04 Base Image
+#
+# This Dockerfile creates a minimal Ubuntu 24.04 system suitable for
+# running as a quicksand VM guest. Uses a Rust-based agent for minimal footprint.
+
+# =============================================================================
+# Stage 1: Build the Rust agent
+# =============================================================================
+FROM rust:bookworm AS agent-builder
+
+WORKDIR /build
+COPY agent/Cargo.toml agent/Cargo.lock* ./
+COPY agent/src ./src
+
+RUN cargo build --release && \
+ strip /build/target/release/quicksand-guest-agent
+
+# =============================================================================
+# Stage 2: Create the Ubuntu VM image
+# =============================================================================
+FROM ubuntu:24.04
+
+# Avoid interactive prompts
+ENV DEBIAN_FRONTEND=noninteractive
+
+# Install kernel, modules, generate initramfs, install remaining packages
+# All in one layer to minimize image size.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ linux-image-virtual \
+ && KVER=$(ls /lib/modules/ | head -1) \
+ && apt-get install -y --no-install-recommends linux-modules-extra-${KVER} \
+ # Generate initramfs (not done automatically in Docker).
+ # initramfs-tools is removed after — it's not needed at runtime.
+ && apt-get install -y --no-install-recommends initramfs-tools \
+ && update-initramfs -c -k ${KVER} \
+ && apt-get remove --purge -y initramfs-tools initramfs-tools-core \
+ initramfs-tools-bin busybox-initramfs klibc-utils libklibc \
+ dracut-install cpio \
+ # Remaining packages
+ && apt-get install -y --no-install-recommends \
+ systemd systemd-sysv \
+ iproute2 iputils-ping \
+ sudo curl ca-certificates \
+ cifs-utils cloud-guest-utils e2fsprogs \
+ && apt-get clean \
+ && rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/* /tmp/* /var/tmp/*
+
+# Create quicksand user with passwordless sudo
+RUN useradd -m -s /bin/bash -G sudo quicksand
+COPY quicksand-sudoers /etc/sudoers.d/quicksand
+RUN chmod 440 /etc/sudoers.d/quicksand
+
+# Ensure 9p kernel modules are loaded at boot
+RUN echo "9p" >> /etc/modules \
+ && echo "9pnet" >> /etc/modules \
+ && echo "9pnet_virtio" >> /etc/modules
+
+# Configure networking with systemd-networkd
+RUN mkdir -p /etc/systemd/network
+COPY 80-dhcp.network /etc/systemd/network/80-dhcp.network
+RUN systemctl enable systemd-networkd
+
+# Configure systemd for VM environment
+# NOTE: We disable systemd-resolved because it can cause boot delays when
+# restrict-network=True. Instead, we use a static resolv.conf via tmpfiles.d.
+RUN systemctl set-default multi-user.target \
+ && systemctl disable systemd-resolved \
+ && systemctl mask systemd-resolved.service \
+ && systemctl mask NetworkManager-wait-online.service \
+ || true
+
+# Use static DNS config pointing to QEMU SLIRP DNS server (10.0.2.3)
+# tmpfiles.d creates the symlink at boot since /etc/resolv.conf is bind-mounted
+# during Docker build and can't be modified directly.
+COPY resolv.conf /etc/resolv.conf.quicksand
+COPY tmpfiles-resolv.conf /etc/tmpfiles.d/resolv.conf
+
+# Set hostname
+COPY hostname /etc/hostname
+
+# /etc/hosts is required for sudo to work without DNS (hostname resolution)
+# Docker bind-mounts /etc/hosts during build, so we copy to a different location
+# and use tmpfiles.d to copy it at boot time
+COPY hosts /etc/hosts.quicksand
+COPY tmpfiles-hosts.conf /etc/tmpfiles.d/hosts.conf
+
+# Copy the Rust agent binary
+COPY --from=agent-builder /build/target/release/quicksand-guest-agent /usr/local/bin/quicksand-guest-agent
+RUN chmod +x /usr/local/bin/quicksand-guest-agent
+
+# Install systemd service for the agent
+COPY quicksand-guest-agent.service /etc/systemd/system/quicksand-guest-agent.service
+RUN systemctl enable quicksand-guest-agent
+
+CMD ["/sbin/init"]
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/hostname b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/hostname
new file mode 100644
index 0000000..901d7a0
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/hostname
@@ -0,0 +1 @@
+quicksand
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/hosts b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/hosts
new file mode 100644
index 0000000..03d5433
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/hosts
@@ -0,0 +1,7 @@
+127.0.0.1 localhost
+127.0.1.1 quicksand
+
+# IPv6
+::1 localhost ip6-localhost ip6-loopback
+ff02::1 ip6-allnodes
+ff02::2 ip6-allrouters
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/quicksand-guest-agent.service b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/quicksand-guest-agent.service
new file mode 100644
index 0000000..059ac55
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/quicksand-guest-agent.service
@@ -0,0 +1,16 @@
+[Unit]
+Description=Quicksand Guest Agent
+# Start as early as possible. With virtio-serial transport, the agent
+# does not need networking — the chardev is available at sysinit.
+# Falls back to HTTP on TCP if virtio-serial port is absent.
+After=sysinit.target
+Wants=sysinit.target
+
+[Service]
+Type=simple
+ExecStart=/usr/local/bin/quicksand-guest-agent
+Restart=always
+RestartSec=1
+
+[Install]
+WantedBy=multi-user.target
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/quicksand-sudoers b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/quicksand-sudoers
new file mode 100644
index 0000000..7aa0a0b
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/quicksand-sudoers
@@ -0,0 +1 @@
+quicksand ALL=(ALL) NOPASSWD:ALL
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/resolv.conf b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/resolv.conf
new file mode 100644
index 0000000..27a94c0
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/resolv.conf
@@ -0,0 +1 @@
+nameserver 10.0.2.3
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/resolved-setup.conf b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/resolved-setup.conf
new file mode 100644
index 0000000..42b5e8f
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/resolved-setup.conf
@@ -0,0 +1,2 @@
+[Service]
+ExecStartPre=/bin/sh -c 'rm -f /etc/resolv.conf && ln -s /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf'
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/tmpfiles-hosts.conf b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/tmpfiles-hosts.conf
new file mode 100644
index 0000000..7a9eae6
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/tmpfiles-hosts.conf
@@ -0,0 +1,3 @@
+# Symlink /etc/hosts at boot (Docker can't write to /etc/hosts during build)
+# L+ removes existing file/symlink and creates a new symlink
+L+ /etc/hosts - - - - /etc/hosts.quicksand
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/tmpfiles-resolv.conf b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/tmpfiles-resolv.conf
new file mode 100644
index 0000000..ca3a0a8
--- /dev/null
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/tmpfiles-resolv.conf
@@ -0,0 +1,3 @@
+# Symlink resolv.conf at boot (Docker can't write to /etc/resolv.conf during build)
+# L+ removes existing file/symlink and creates a new symlink
+L+ /etc/resolv.conf - - - - /etc/resolv.conf.quicksand
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/images/.gitkeep b/packages/quicksand-ubuntu/quicksand_ubuntu/images/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/packages/quicksand/README.md b/packages/quicksand/README.md
new file mode 100644
index 0000000..0ec6cd9
--- /dev/null
+++ b/packages/quicksand/README.md
@@ -0,0 +1,108 @@
+# Quicksand
+
+Quicksand is a VM harness for AI agents that works on macOS, Linux, and Windows.
+
+## Quick Start
+
+**1. Install quicksand CLI**
+
+```bash
+pip install "git+ssh://[email protected]/microsoft/quicksand.git#subdirectory=packages/quicksand"
+```
+
+**2. Install a sandbox**
+
+```bash
+quicksand install ubuntu # Ubuntu 24.04 (~300MB)
+quicksand install alpine # Alpine 3.21 (~75MB, faster boot)
+```
+
+**3. Run the sandbox in python**
+
+```python
+import asyncio
+from quicksand import UbuntuSandbox
+
+async def main():
+ async with UbuntuSandbox() as sb:
+ result = await sb.execute("echo 'Hello from the sandbox!'")
+ print(result.stdout)
+
+asyncio.run(main())
+```
+
+That's it. Docker? Don't need it. WSL2? Nope. Batteries? Included.
+
+## Usage
+
+```python
+import asyncio
+from quicksand import Sandbox, Mount, NetworkMode
+
+async def main():
+ async with Sandbox(
+ image="ubuntu",
+ mounts=[Mount("./workspace", "/mnt/workspace")],
+ network_mode=NetworkMode.FULL, # Full internet access
+ ) as sb:
+ await sb.execute("pip install requests")
+ await sb.execute("python /mnt/workspace/script.py")
+ print((await sb.execute("cat /tmp/output.txt")).stdout)
+ await sb.save("./my-save") # Save disk state, VM keeps running
+
+asyncio.run(main())
+```
+
+See [examples/](examples/) for more. For implementation details, see [ARCHITECTURE.md](ARCHITECTURE.md).
+
+## How It Works
+
+```mermaid
+graph LR
+ subgraph Host["Host"]
+ HostFiles["Host Files"]
+ subgraph Process["Python Process"]
+ Code["Your Code"]
+ subgraph SB["quicksand.Sandbox"]
+ TCP["TCP Client"]
+ FileSync["FileSync (SMB/CIFS)"]
+ end
+ end
+ subgraph QEMU["QEMU Process (bundled)"]
+ subgraph Accel["KVM / HVF / WHPX (host)"]
+ subgraph VM["Linux VM (bundled)"]
+ Agent["quicksand-guest-agent"]
+ Mount["/mnt/data"]
+ end
+ end
+ end
+ end
+
+ Code <-->|".execute"| SB
+ SB -->|launches| QEMU
+ TCP <-->|commands| Agent
+ HostFiles <--> FileSync
+ FileSync <-.->|sync| Mount
+```
+
+Each sandbox runs in a real virtual machine with hypervisor-level isolation:
+
+| Platform | Accelerator | Machine | File Sharing | Performance |
+|----------|-------------|---------|--------------|-------------|
+| Linux x86_64 | KVM | microvm | SMB/CIFS | io_uring + IOThreads |
+| Linux ARM64 | KVM | virt | SMB/CIFS | io_uring + IOThreads |
+| macOS | HVF | q35/virt | SMB/CIFS | IOThreads |
+| Windows | WHPX | q35 | SMB/CIFS | IOThreads |
+
+Key components:
+- **Bundled QEMU**: No system installation required
+- **Guest agent**: Lightweight TCP server for command execution
+- **Disposable overlays**: Base image unchanged, writes go to temp overlay
+- **SMB/CIFS mounts**: Mount host directories into the VM
+- **Platform optimizations**: microvm (~4x faster boot), io_uring (~50% lower disk latency), IOThreads
+
+## Requirements
+
+- Python 3.11+
+- No system dependencies (QEMU is bundled)
+- For custom images: Docker
diff --git a/packages/quicksand/pyproject.toml b/packages/quicksand/pyproject.toml
new file mode 100644
index 0000000..c352b83
--- /dev/null
+++ b/packages/quicksand/pyproject.toml
@@ -0,0 +1,42 @@
+[project]
+name = "quicksand"
+version = "0.10.3.dev0"
+description = "A VM harness for AI agents that works on macOS, Linux, and Windows."
+readme = "README.md"
+requires-python = ">=3.11"
+license = "MIT"
+dependencies = [
+ "quicksand-core>=0.10.3.dev0",
+]
+
+[project.optional-dependencies]
+qemu = ["quicksand-qemu>=0.4.3"]
+ubuntu = ["quicksand-ubuntu>=0.7.2"]
+alpine = ["quicksand-alpine>=0.7.2"]
+alpine-desktop = ["quicksand-alpine-desktop>=0.7.5"]
+ubuntu-desktop = ["quicksand-ubuntu-desktop>=0.7.5"]
+dev = ["quicksand-image-tools>=0.3.2", "quicksand-overlay-scaffold>=0.1.4", "quicksand-base-scaffold>=0.1.3"]
+all = [
+ "quicksand-qemu>=0.4.3",
+ "quicksand-ubuntu>=0.7.2",
+ "quicksand-alpine>=0.7.2",
+ "quicksand-alpine-desktop>=0.7.5",
+ "quicksand-ubuntu-desktop>=0.7.5",
+ "quicksand-image-tools>=0.3.2",
+]
+
+[project.scripts]
+quicksand = "quicksand.cli:main"
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["quicksand"]
+
+[tool.uv.sources]
+quicksand-overlay-scaffold = { workspace = true }
+quicksand-base-scaffold = { workspace = true }
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
diff --git a/packages/quicksand/quicksand/__init__.py b/packages/quicksand/quicksand/__init__.py
new file mode 100644
index 0000000..9337ff9
--- /dev/null
+++ b/packages/quicksand/quicksand/__init__.py
@@ -0,0 +1,149 @@
+"""
+Quicksand is a VM harness for AI agents.
+
+It gives agents a real computer to work with. They can install packages, run
+scripts, browse the web, and manipulate files inside a sandboxed VM.
+
+Quick start (pip install quicksand[ubuntu]):
+ import asyncio
+ from quicksand import Sandbox
+
+ async def main():
+ async with Sandbox(image="ubuntu") as sb:
+ result = await sb.execute("ls -la /")
+ print(result.stdout)
+
+ asyncio.run(main())
+
+Or with Alpine (pip install quicksand[alpine]):
+ from quicksand import Sandbox
+
+ async with Sandbox(image="alpine") as sb:
+ result = await sb.execute("cat /etc/os-release")
+
+Or with custom configuration:
+ from quicksand import Sandbox
+
+ async with Sandbox(image="ubuntu", memory="2G", cpus=4) as sb:
+ result = await sb.execute("cat /etc/os-release")
+
+Install extras:
+ pip install quicksand[ubuntu] # Bundled Ubuntu image (~341MB)
+ pip install quicksand[alpine] # Bundled Alpine image (~78MB, faster boot)
+ pip install quicksand[dev] # Build custom images from Dockerfiles
+"""
+
+# Re-export everything from quicksand-core
+from quicksand_core import (
+ OS,
+ Accelerator,
+ AcceleratorStatus,
+ Architecture,
+ BootTiming,
+ ExecuteResult,
+ Key,
+ MachineType,
+ Mount,
+ MountType,
+ NetworkMode,
+ PlatformConfig,
+ PortForward,
+ RuntimeInfo,
+ Sandbox,
+ SandboxConfig,
+ SandboxConfigParams,
+ SaveManifest,
+ detect_accelerator,
+ get_accelerator,
+ get_machine_type,
+ get_platform_config,
+ get_runtime,
+ is_runtime_available,
+)
+
+from quicksand.cli.install import install
+
+
+class _MissingOptionalSandbox:
+ """Placeholder for optional sandbox types that aren't installed."""
+
+ def __init__(self, install_extra: str, sandbox_type: str):
+ self._install_extra = install_extra
+ self._sandbox_type = sandbox_type
+
+ def __call__(self, *args, **kwargs):
+ raise ImportError(
+ f"{self._sandbox_type} requires the '{self._install_extra}' extra.\n"
+ f"Install with: pip install 'quicksand[{self._install_extra}]'"
+ )
+
+ def __repr__(self):
+ return f"<{self._sandbox_type}: not installed>"
+
+
+# Conditionally import image extras if available
+try:
+ from quicksand_ubuntu import UbuntuSandbox
+except ImportError:
+ UbuntuSandbox = _MissingOptionalSandbox("ubuntu", "UbuntuSandbox") # type: ignore[misc, assignment] # ty: ignore[invalid-assignment]
+
+try:
+ from quicksand_alpine import AlpineSandbox
+except ImportError:
+ AlpineSandbox = _MissingOptionalSandbox("alpine", "AlpineSandbox") # type: ignore[misc, assignment] # ty: ignore[invalid-assignment]
+
+try:
+ from quicksand_alpine_desktop import AlpineDesktopSandbox
+except ImportError:
+ AlpineDesktopSandbox = _MissingOptionalSandbox("alpine-desktop", "AlpineDesktopSandbox") # type: ignore[misc, assignment] # ty: ignore[invalid-assignment]
+
+try:
+ from quicksand_ubuntu_desktop import UbuntuDesktopSandbox
+except ImportError:
+ UbuntuDesktopSandbox = _MissingOptionalSandbox("ubuntu-desktop", "UbuntuDesktopSandbox") # type: ignore[misc, assignment] # ty: ignore[invalid-assignment]
+
+__all__ = [ # noqa: RUF022
+ # Core
+ "Sandbox",
+ "SandboxConfig",
+ "SandboxConfigParams",
+ "Mount",
+ "MountType",
+ "PortForward",
+ "ExecuteResult",
+ # Boot timing
+ "BootTiming",
+ # Save
+ "SaveManifest",
+ # Runtime management
+ "get_runtime",
+ "RuntimeInfo",
+ "is_runtime_available",
+ "get_machine_type",
+ # Accelerator
+ "get_accelerator",
+ "detect_accelerator",
+ "AcceleratorStatus",
+ # Platform
+ "get_platform_config",
+ "PlatformConfig",
+ # Types
+ "Key",
+ "Accelerator",
+ "Architecture",
+ "MachineType",
+ "NetworkMode",
+ "OS",
+ # Install API
+ "install",
+ # Ubuntu extras (available with quicksand[ubuntu])
+ "UbuntuSandbox",
+ # Alpine extras (available with quicksand[alpine])
+ "AlpineSandbox",
+ # Alpine Desktop extras (available with quicksand[alpine-desktop])
+ "AlpineDesktopSandbox",
+ # Ubuntu Desktop extras (available with quicksand[ubuntu-desktop])
+ "UbuntuDesktopSandbox",
+]
+
+__version__ = "0.1.0"
diff --git a/packages/quicksand/quicksand/__main__.py b/packages/quicksand/quicksand/__main__.py
new file mode 100644
index 0000000..3566cc2
--- /dev/null
+++ b/packages/quicksand/quicksand/__main__.py
@@ -0,0 +1,3 @@
+from quicksand.cli import main
+
+main()
diff --git a/packages/quicksand/quicksand/benchmark.py b/packages/quicksand/quicksand/benchmark.py
new file mode 100644
index 0000000..7a32eac
--- /dev/null
+++ b/packages/quicksand/quicksand/benchmark.py
@@ -0,0 +1,256 @@
+"""Benchmark sandbox boot times.
+
+Usage::
+
+ import asyncio
+ from quicksand.benchmark import benchmark
+
+ result = asyncio.run(benchmark("ubuntu", iterations=5))
+ print(result)
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import math
+import sys
+import time
+
+from pydantic import BaseModel, ConfigDict
+
+from quicksand import BootTiming, Mount, Sandbox, install
+
+
+class BootSample(BaseModel):
+ """A single boot-time measurement."""
+
+ model_config = ConfigDict(frozen=True)
+
+ iteration: int
+ boot_time_s: float
+
+
+class BenchmarkResult(BaseModel):
+ """Aggregate result of a boot-time benchmark run."""
+
+ model_config = ConfigDict(frozen=True)
+
+ image: str
+ iterations: int
+ qemu_command: list[str]
+ samples: list[BootSample]
+ boot_timing: BootTiming | None
+ min_s: float
+ p50_s: float
+ p90_s: float
+ p95_s: float
+ p99_s: float
+ max_s: float
+
+ def __str__(self) -> str:
+ lines = [
+ "Quicksand Boot Benchmark",
+ f" Image: {self.image}",
+ f" Iterations: {self.iterations}",
+ "",
+ "QEMU Command:",
+ self._format_qemu_command(),
+ "",
+ ]
+ for s in self.samples:
+ bar_len = int(min(s.boot_time_s / self.max_s, 1.0) * 20)
+ bar = "█" * bar_len + "░" * (20 - bar_len)
+ lines.append(f" #{s.iteration + 1:<3} {bar} {s.boot_time_s:>7.3f}s")
+ lines.append("")
+ for label, val in [
+ ("min", self.min_s),
+ ("p50", self.p50_s),
+ ("p90", self.p90_s),
+ ("p95", self.p95_s),
+ ("p99", self.p99_s),
+ ("max", self.max_s),
+ ]:
+ lines.append(f" {label:<4} {val:>7.3f}s")
+ if self.boot_timing:
+ lines.append("")
+ lines.append("Boot Phase Breakdown (last run):")
+ lines.append(str(self.boot_timing))
+ return "\n".join(lines)
+
+ def _format_qemu_command(self) -> str:
+ """Format the QEMU command as a readable, arg-per-line shell command."""
+ if not self.qemu_command:
+ return " (not captured)"
+ parts = list(self.qemu_command)
+ result_lines: list[str] = [f" {parts[0]}"]
+ i = 1
+ while i < len(parts):
+ arg = parts[i]
+ if arg.startswith("-") and i + 1 < len(parts) and not parts[i + 1].startswith("-"):
+ result_lines.append(f" {arg} {parts[i + 1]} \\")
+ i += 2
+ else:
+ result_lines.append(f" {arg} \\")
+ i += 1
+ # Remove trailing backslash from last line
+ if result_lines:
+ result_lines[-1] = result_lines[-1].rstrip(" \\")
+ return "\n".join(result_lines)
+
+
+async def benchmark(
+ image: str,
+ *,
+ iterations: int = 5,
+ install_extras: list[str] | None = None,
+ mounts: list[Mount] | None = None,
+) -> BenchmarkResult:
+ """Measure boot time over *iterations* runs.
+
+ Args:
+ image: Image name to benchmark (e.g. ``"ubuntu"``).
+ iterations: Number of boot cycles.
+ install_extras: Extras to ``quicksand.install()`` before benchmarking.
+ Pass an explicit list to install packages (e.g. ``["qemu", "ubuntu"]``).
+ By default nothing is installed, so a system QEMU is used.
+ mounts: Optional list of :class:`Mount` specs to include during boot.
+
+ Returns:
+ A :class:`BenchmarkResult` with per-iteration samples and summary stats.
+ """
+ if install_extras:
+ install(*install_extras)
+
+ samples: list[BootSample] = []
+ qemu_command: list[str] = []
+ boot_timing: BootTiming | None = None
+
+ for i in range(iterations):
+ _print_progress(i, iterations)
+
+ sandbox = Sandbox(image=image, mounts=mounts or [])
+ t0 = time.perf_counter()
+ await sandbox.start()
+ boot_time = time.perf_counter() - t0
+
+ if not qemu_command:
+ qemu_command = sandbox.qemu_command or []
+ boot_timing = sandbox.boot_timing
+
+ await sandbox.stop()
+
+ samples.append(
+ BootSample(
+ iteration=i,
+ boot_time_s=round(boot_time, 4),
+ )
+ )
+
+ _print_progress(iterations, iterations)
+ sys.stdout.write("\n")
+
+ times = sorted(s.boot_time_s for s in samples)
+ return BenchmarkResult(
+ image=image,
+ iterations=iterations,
+ qemu_command=qemu_command,
+ boot_timing=boot_timing,
+ samples=samples,
+ min_s=times[0],
+ p50_s=_percentile(times, 50),
+ p90_s=_percentile(times, 90),
+ p95_s=_percentile(times, 95),
+ p99_s=_percentile(times, 99),
+ max_s=times[-1],
+ )
+
+
+def _percentile(sorted_values: list[float], p: float) -> float:
+ """Compute the p-th percentile from a sorted list (nearest-rank)."""
+ k = (p / 100) * (len(sorted_values) - 1)
+ f = math.floor(k)
+ c = math.ceil(k)
+ if f == c:
+ return sorted_values[int(k)]
+ return round(sorted_values[f] * (c - k) + sorted_values[c] * (k - f), 4)
+
+
+# ── CLI integration ───────────────────────────────────────────────────
+
+
+def _print_progress(completed: int, total: int) -> None:
+ """Print a cross-platform progress bar matching the install download style."""
+ bar_width = 30
+ filled = int(bar_width * completed / total) if total > 0 else 0
+ bar = "#" * filled + "-" * (bar_width - filled)
+ percent = (completed / total * 100) if total > 0 else 0
+ sys.stdout.write(f"\r {bar} {percent:5.1f}% ({completed}/{total} iterations)")
+ sys.stdout.flush()
+
+
+def _parse_mount(value: str) -> Mount:
+ """Parse ``HOST:GUEST[:TYPE]`` into a :class:`Mount`."""
+ parts = value.split(":")
+ if len(parts) < 2:
+ raise argparse.ArgumentTypeError(
+ f"Invalid mount format: {value} (expected HOST:GUEST[:TYPE])"
+ )
+ host, guest = parts[0], parts[1]
+ mount_type = parts[2] if len(parts) > 2 else "cifs"
+ if mount_type not in ("cifs", "9p"):
+ raise argparse.ArgumentTypeError(f"Invalid mount type: {mount_type} (expected cifs or 9p)")
+ from typing import cast
+
+ from quicksand import MountType
+
+ return Mount(host=host, guest=guest, type=cast(MountType, mount_type))
+
+
+def register_args(parser: argparse.ArgumentParser) -> None:
+ """Add benchmark arguments to a parser."""
+ parser.add_argument("image", help="Image to benchmark (e.g. ubuntu)")
+ parser.add_argument(
+ "-n", "--iterations", type=int, default=5, help="Number of boot iterations (default: 5)"
+ )
+ parser.add_argument(
+ "-v",
+ "--mount",
+ action="append",
+ metavar="HOST:GUEST[:TYPE]",
+ help="Mount host directory into sandbox during boot (repeatable)",
+ )
+ parser.add_argument(
+ "--json", action="store_true", dest="json_output", help="Output results as JSON"
+ )
+
+
+def register(subparsers: argparse._SubParsersAction) -> None:
+ """Register the benchmark subcommand."""
+ parser = subparsers.add_parser(
+ "benchmark",
+ help="Benchmark sandbox boot times",
+ )
+ register_args(parser)
+
+
+def cmd(args: argparse.Namespace) -> int:
+ """Run the benchmark CLI command."""
+ mounts = [_parse_mount(m) for m in args.mount] if args.mount else None
+ result = asyncio.run(benchmark(args.image, iterations=args.iterations, mounts=mounts))
+ if args.json_output:
+ print(result.model_dump_json(indent=2))
+ else:
+ print(result)
+ return 0
+
+
+if __name__ == "__main__":
+ import argparse as _argparse
+
+ _parser = _argparse.ArgumentParser(description="Benchmark quicksand boot times")
+ register_args(_parser)
+ _args = _parser.parse_args()
+
+ _result = asyncio.run(benchmark(_args.image, iterations=_args.iterations))
+ print(_result)
diff --git a/packages/quicksand/quicksand/cli/__init__.py b/packages/quicksand/quicksand/cli/__init__.py
new file mode 100644
index 0000000..ea7a869
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/__init__.py
@@ -0,0 +1,58 @@
+"""Quicksand CLI - run sandboxes from the command line."""
+
+from __future__ import annotations
+
+import argparse
+import sys
+
+from . import clean, dev, install, qemu, release_save, run, uninstall
+
+
+def main() -> int:
+ """Main entry point for the quicksand CLI."""
+ parser = argparse.ArgumentParser(
+ prog="quicksand",
+ description="A VM harness for AI agents.",
+ )
+ subparsers = parser.add_subparsers(dest="command")
+
+ # Register subcommands
+ run.register(subparsers)
+ install.register(subparsers)
+ uninstall.register(subparsers)
+ clean.register(subparsers)
+ release_save.register(subparsers)
+ qemu.register(subparsers)
+ dev.register(subparsers)
+
+ from .. import benchmark as benchmark_mod
+
+ benchmark_mod.register(subparsers)
+
+ args = parser.parse_args()
+
+ if args.command == "run":
+ return run.cmd(args)
+ elif args.command == "install":
+ return install.cmd(args)
+ elif args.command == "uninstall":
+ return uninstall.cmd(args)
+ elif args.command == "release":
+ return release_save.cmd(args)
+ elif args.command == "qemu":
+ return qemu.cmd(args)
+ elif args.command == "clean":
+ return clean.cmd(args)
+ elif args.command == "dev":
+ return dev.cmd(args)
+ elif args.command == "benchmark":
+ from .. import benchmark as benchmark_mod
+
+ return benchmark_mod.cmd(args)
+ else:
+ parser.print_help()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/packages/quicksand/quicksand/cli/clean.py b/packages/quicksand/quicksand/cli/clean.py
new file mode 100644
index 0000000..0b66d96
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/clean.py
@@ -0,0 +1,78 @@
+"""Clean quicksand data directories.
+
+Programmatic API::
+
+ from quicksand.cli.clean import clean
+
+ clean() # remove local .quicksand/
+ clean(global_=True) # also remove ~/.quicksand/
+"""
+
+from __future__ import annotations
+
+import argparse
+import shutil
+from pathlib import Path
+
+LOCAL_DIR = Path.cwd() / ".quicksand"
+GLOBAL_DIR = Path.home() / ".quicksand"
+
+
+def _dir_size(path: Path) -> int:
+ """Return total size in bytes of all files under *path*."""
+ return sum(f.stat().st_size for f in path.rglob("*") if f.is_file())
+
+
+def _fmt_size(size: int) -> str:
+ n = float(size)
+ for unit in ("B", "KB", "MB", "GB"):
+ if n < 1024:
+ return f"{n:.1f} {unit}" if unit != "B" else f"{int(n)} {unit}"
+ n /= 1024
+ return f"{n:.1f} TB"
+
+
+def _remove(path: Path) -> None:
+ if not path.exists():
+ return
+ size = _dir_size(path)
+ shutil.rmtree(path)
+ print(f" Removed {path} ({_fmt_size(size)})")
+
+
+def clean(*, global_: bool = False) -> None:
+ """Remove quicksand data directories.
+
+ Args:
+ global_: If True, also remove ``~/.quicksand/``.
+
+ Examples::
+
+ from quicksand.cli.clean import clean
+
+ clean()
+ clean(global_=True)
+ """
+ _remove(LOCAL_DIR)
+ if global_:
+ _remove(GLOBAL_DIR)
+
+
+def register(subparsers: argparse._SubParsersAction) -> None:
+ """Register the clean subcommand."""
+ parser = subparsers.add_parser(
+ "clean",
+ help="Remove quicksand data directories",
+ )
+ parser.add_argument(
+ "--global",
+ dest="global_",
+ action="store_true",
+ help="Also remove ~/.quicksand/",
+ )
+
+
+def cmd(args: argparse.Namespace) -> int:
+ """Clean quicksand data directories."""
+ clean(global_=args.global_)
+ return 0
diff --git a/packages/quicksand/quicksand/cli/dev.py b/packages/quicksand/quicksand/cli/dev.py
new file mode 100644
index 0000000..7a16a51
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/dev.py
@@ -0,0 +1,124 @@
+"""Development tools for building images and packages.
+
+Routes scaffold commands to their respective packages and delegates
+everything else to quicksand-image-tools.
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+
+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])",
+ )
+ dev_sub = parser.add_subparsers(dest="dev_command")
+
+ # quicksand dev scaffold overlay <name> --base <base> [--output-dir DIR]
+ scaffold_parser = dev_sub.add_parser("scaffold", help="Scaffold a new image package")
+ scaffold_sub = scaffold_parser.add_subparsers(dest="scaffold_type")
+
+ overlay_parser = scaffold_sub.add_parser("overlay", help="Scaffold an overlay image package")
+ overlay_parser.add_argument("name", help="Package name (e.g. my-agent-sandbox)")
+ overlay_parser.add_argument("--base", required=True, help="Base image (e.g. ubuntu, alpine)")
+ overlay_parser.add_argument("--output-dir", type=Path, default=None, help="Output directory")
+
+ base_parser = scaffold_sub.add_parser("base", help="Scaffold a base image package")
+ 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
+
+
+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()
+
+
+def _cmd_scaffold(args: argparse.Namespace) -> int:
+ """Handle scaffold subcommands."""
+ if args.scaffold_type == "overlay":
+ try:
+ from quicksand_overlay_scaffold.scaffold import scaffold
+ except ImportError:
+ print(
+ "Error: quicksand-overlay-scaffold is not installed.\n\n"
+ "Install with: pip install 'quicksand[dev]'",
+ file=sys.stderr,
+ )
+ return 1
+ try:
+ scaffold(name=args.name, base=args.base, output_dir=args.output_dir)
+ except (ValueError, FileExistsError) as e:
+ print(f"Error: {e}", file=sys.stderr)
+ return 1
+ return 0
+
+ if args.scaffold_type == "base":
+ try:
+ from quicksand_base_scaffold.scaffold import scaffold
+ except ImportError:
+ print(
+ "Error: quicksand-base-scaffold is not installed.\n\n"
+ "Install with: pip install 'quicksand[dev]'",
+ file=sys.stderr,
+ )
+ return 1
+ try:
+ scaffold(name=args.name, output_dir=args.output_dir)
+ except (ValueError, FileExistsError) as e:
+ print(f"Error: {e}", file=sys.stderr)
+ return 1
+ return 0
+
+ # No scaffold type — show help
+ print("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.py
new file mode 100644
index 0000000..cdd3795
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/images.py
@@ -0,0 +1,191 @@
+"""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 quicksand[alpine-desktop] or quicksand[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/install.py b/packages/quicksand/quicksand/cli/install.py
new file mode 100644
index 0000000..c526db9
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/install.py
@@ -0,0 +1,643 @@
+"""Install optional quicksand extras from GitHub releases.
+
+Programmatic API::
+
+ from quicksand import install
+
+ install("qemu", "ubuntu") # install specific extras
+ install("all") # install all main packages
+ install("ubuntu", version="0.4.0") # pin a version
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import platform
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+from pathlib import Path
+
+REPO = "microsoft/quicksand"
+
+# Short aliases → actual package names on GitHub
+ALIASES: dict[str, list[str]] = {
+ "qemu": ["quicksand-qemu"],
+ "ubuntu": ["quicksand-ubuntu"],
+ "alpine": ["quicksand-alpine"],
+ "alpine-desktop": ["quicksand-alpine-desktop"],
+ "ubuntu-desktop": ["quicksand-ubuntu-desktop"],
+ "dev": ["quicksand-image-tools", "quicksand-overlay-scaffold", "quicksand-base-scaffold"],
+ "all": [
+ "quicksand-qemu",
+ "quicksand-ubuntu",
+ "quicksand-alpine",
+ "quicksand-alpine-desktop",
+ "quicksand-ubuntu-desktop",
+ ],
+}
+
+
+# ── Helpers ───────────────────────────────────────────────────────────
+
+
+def _parse_extra(raw: str) -> tuple[str, str | None]:
+ """Parse ``"name"`` or ``"name@version"`` into ``(name, version|None)``."""
+ if "@" in raw:
+ name, ver = raw.split("@", 1)
+ return name, ver
+ return raw, None
+
+
+def _resolve_packages(name: str) -> list[str]:
+ """Resolve a name to a list of package names.
+
+ Aliases (e.g. "ubuntu") expand to their mapped packages.
+ All other names are treated as literal package names.
+ """
+ return ALIASES.get(name, [name])
+
+
+# ── Public API ────────────────────────────────────────────────────────
+
+
+def install(*extras: str, arch: str | None = None) -> None:
+ """Install quicksand extras from GitHub releases.
+
+ Downloads all wheels for requested packages into a temporary directory,
+ then uses ``pip install --find-links`` to resolve platform compatibility
+ and dependencies automatically.
+
+ Use ``"name@version"`` to pin a specific version; without ``@`` the
+ latest release is used.
+
+ Args:
+ *extras: One or more extra/package names (e.g. ``"qemu"``, ``"ubuntu"``,
+ ``"all"``, ``"[email protected]"``, ``"aif-agent-sandbox"``).
+ arch: Target architecture (e.g. ``"amd64"``, ``"arm64"``).
+ 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.
+
+ Examples::
+
+ from quicksand import install
+
+ install("qemu", "ubuntu")
+ install("all")
+ install("[email protected]")
+ install("ubuntu", arch="amd64") # cross-arch
+ """
+ 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:
+ name, ver = _parse_extra(raw)
+ for pkg in _resolve_packages(name):
+ if pkg not in packages:
+ packages.append(pkg)
+ versions[pkg] = ver
+
+ rc = _install_packages(packages, versions, arch=arch)
+ if rc != 0:
+ raise RuntimeError(f"Failed to install packages: {packages}")
+
+
+def register(subparsers: argparse._SubParsersAction) -> None:
+ """Register the install subcommand."""
+ all_aliases = ", ".join(ALIASES.keys())
+ parser = subparsers.add_parser(
+ "install",
+ help="Install packages from GitHub releases",
+ )
+ parser.add_argument(
+ "extras",
+ nargs="+",
+ metavar="NAME[@VERSION]",
+ help=(
+ f"Packages to install (use @version to pin, e.g. [email protected]). "
+ f"Aliases: {all_aliases}. "
+ "Other names are looked up as package releases on GitHub."
+ ),
+ )
+ parser.add_argument(
+ "--arch",
+ default=None,
+ help="Install for a specific architecture (e.g. amd64, arm64). "
+ "Downloads cross-platform wheels for use with quicksand run --arch.",
+ )
+
+
+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:
+ name, ver = _parse_extra(raw)
+ for pkg in _resolve_packages(name):
+ if pkg not in packages:
+ packages.append(pkg)
+ versions[pkg] = ver
+
+ return _install_packages(packages, versions, arch=args.arch)
+
+
+# ── 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 _install_packages(
+ packages: list[str],
+ versions: dict[str, str | None],
+ arch: str | None = None,
+) -> int:
+ """Download wheels to a temp dir, then pip install --find-links."""
+ print(f"Installing: {', '.join(packages)}")
+ emulated = _is_platform_emulated()
+ if arch:
+ print(f"Platform: {platform.system()} {platform.machine()} (target arch: {arch})")
+ elif emulated:
+ print(
+ f"Platform: {platform.system()} {platform.machine()} "
+ f"(Python arch: {_get_pip_arch_tag()}, native: {_get_host_arch_tag()})"
+ )
+ else:
+ print(f"Platform: {platform.system()} {platform.machine()}")
+ # Resolve compatible versions based on installed quicksand version
+ quicksand_ver = _get_quicksand_version()
+ quicksand_date: str | None = None
+ all_releases: dict[str, str] = {}
+ if quicksand_ver:
+ all_releases = _get_all_releases_with_dates()
+ quicksand_date = all_releases.get(f"quicksand/v{quicksand_ver}")
+ if quicksand_date:
+ print(f"Resolving versions compatible with quicksand {quicksand_ver}")
+ else:
+ print(f"Warning: no release found for quicksand {quicksand_ver}, using latest versions")
+ print()
+
+ with tempfile.TemporaryDirectory() as tmp:
+ wheel_dir = Path(tmp)
+
+ # Download requested packages and their transitive quicksand deps
+ seen: set[str] = set()
+ queue = list(packages)
+ while queue:
+ pkg_name = queue.pop(0)
+ if pkg_name in seen:
+ continue
+ seen.add(pkg_name)
+
+ ver = versions.get(pkg_name)
+ if ver:
+ tag = f"{pkg_name}/v{ver}"
+ elif quicksand_date:
+ tag = _resolve_compatible_tag(pkg_name, quicksand_date, all_releases)
+ else:
+ tag = _get_latest_release_tag(pkg_name)
+ 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}")
+ return 1
+ continue # not a quicksand package, pip will resolve from PyPI
+
+ resolved_ver = tag.split("/v")[-1]
+ print(f" {pkg_name} → v{resolved_ver}")
+
+ new_wheels = _download_release_wheels(tag, wheel_dir)
+ # Scan downloaded wheels for transitive deps that have GH releases
+ for whl in new_wheels:
+ for dep in _extract_dep_names(whl):
+ if dep not in seen:
+ queue.append(dep)
+
+ if arch:
+ _retag_wheels_for_arch(wheel_dir)
+ elif emulated:
+ print("Retagging image wheels for pip compatibility (emulated platform)")
+ _retag_wheels_for_arch(wheel_dir)
+ _cleanup_incompatible_wheels(wheel_dir)
+
+ # Let pip handle platform matching, dep resolution, and conflicts.
+ # --force-reinstall ensures downloaded wheels overwrite editable installs
+ # or same-version packages that may shadow the correct entry points.
+ pip_args = [
+ sys.executable,
+ "-m",
+ "pip",
+ "install",
+ "--force-reinstall",
+ "--find-links",
+ str(wheel_dir),
+ ]
+ pip_args.extend(packages)
+
+ print(f"Running: pip install --find-links {wheel_dir.name} {' '.join(packages)}")
+ result = subprocess.run(pip_args)
+ if result.returncode != 0:
+ print("\nError: pip install failed.")
+ return 1
+
+ print(f"\nInstalled {len(packages)} package(s)")
+ return 0
+
+
+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:
+ return None
+ tags = [t for t in result.stdout.strip().splitlines() if t and not t.endswith("-dev")]
+ return tags[-1] if tags else None
+
+
+def _get_quicksand_version() -> str | None:
+ """Return the installed quicksand version, or ``None`` if unavailable."""
+ try:
+ from importlib.metadata import version
+
+ return version("quicksand")
+ except Exception:
+ return None
+
+
+def _version_tuple(ver: str) -> tuple[int, ...]:
+ """Parse ``'1.2.3'`` into ``(1, 2, 3)`` for comparison."""
+ parts: list[int] = []
+ for p in ver.split("."):
+ try:
+ parts.append(int(p))
+ except ValueError:
+ break
+ return tuple(parts)
+
+
+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
+ return releases
+
+
+def _resolve_compatible_tag(
+ pkg_name: str,
+ quicksand_date: str,
+ all_releases: dict[str, str],
+) -> str | None:
+ """Pick the best release tag for *pkg_name* given a quicksand release date.
+
+ 1. Find the latest release published **at or before** *quicksand_date* to
+ establish a baseline ``major.minor``.
+ 2. Return the newest ``major.minor.*`` release (patch bumps are always
+ compatible, even if published after the quicksand release).
+
+ Returns ``None`` if the package has no releases, or none were published
+ before *quicksand_date*.
+ """
+ prefix = f"{pkg_name}/v"
+ pkg_releases: list[tuple[str, str, str]] = [] # (tag, version, date)
+ for tag, date in all_releases.items():
+ if tag.startswith(prefix) and not tag.endswith("-dev"):
+ pkg_releases.append((tag, tag[len(prefix) :], date))
+
+ if not pkg_releases:
+ return None
+
+ pkg_releases.sort(key=lambda x: _version_tuple(x[1]))
+
+ # Baseline: latest version released at or before quicksand
+ baseline = None
+ for tag, ver, date in pkg_releases:
+ if date <= quicksand_date:
+ baseline = (tag, ver)
+
+ if not baseline:
+ return None
+
+ parts = baseline[1].split(".")
+ if len(parts) < 2:
+ return baseline[0]
+ major_minor = f"{parts[0]}.{parts[1]}"
+
+ # Newest patch in the same major.minor series
+ best = baseline[0]
+ for tag, ver, _date in pkg_releases:
+ vp = ver.split(".")
+ if len(vp) >= 2 and f"{vp[0]}.{vp[1]}" == major_minor:
+ best = tag
+
+ return best
+
+
+def _get_host_arch_tag() -> str:
+ """Return the architecture tag substring for the native hardware.
+
+ On Windows, detects the native hardware architecture to prefer
+ the correct wheel even when Python runs under x86_64 emulation.
+ """
+ from quicksand_core.host.arch import _detect_architecture
+
+ arch = _detect_architecture()
+ return "arm64" if arch.image_arch == "arm64" else "x86_64"
+
+
+def _get_pip_arch_tag() -> str:
+ """Return the architecture tag that pip will accept on this host.
+
+ Unlike :func:`_get_host_arch_tag` (which reports native hardware),
+ this returns the arch from Python's perspective — matching what pip
+ uses for wheel compatibility checks.
+ """
+ import sysconfig
+
+ plat = sysconfig.get_platform() # e.g. "win-amd64", "macosx-14.0-arm64"
+ if "arm64" in plat or "aarch64" in plat:
+ return "arm64"
+ return "x86_64"
+
+
+def _is_platform_emulated() -> bool:
+ """True when native hardware arch differs from Python's interpreter arch.
+
+ This happens on Windows ARM64 where Python runs under x86_64 emulation.
+ The native hardware is ARM64 but ``sysconfig.get_platform()`` reports
+ ``win-amd64``, causing pip to reject ``win_arm64`` wheels.
+ """
+ return _get_host_arch_tag() != _get_pip_arch_tag()
+
+
+def _macos_version_compatible(name: str) -> bool:
+ """Check if a macosx wheel targets a version this host can run.
+
+ macOS is backwards-compatible: a host running 15.x can install wheels
+ built for 11.0 through 15.0. Parse the version from the wheel tag
+ (e.g. ``macosx_14_0_arm64`` → 14) and accept if <= host major version.
+ """
+ import re
+
+ match = re.search(r"macosx_(\d+)_", name)
+ if not match:
+ return True # not a macosx tag, let other checks handle it
+ wheel_major = int(match.group(1))
+ host_major = int(platform.mac_ver()[0].split(".")[0])
+ return wheel_major <= host_major
+
+
+def _wheel_compatible_with_host(name: str) -> bool:
+ """Quick check: could this wheel possibly install on this host?
+
+ Rejects wheels that are clearly for another OS, architecture, or
+ macOS version. pip does the final precise matching — this just avoids
+ downloading hundreds of MB of obviously-wrong wheels.
+
+ When platform emulation is detected (e.g. Windows ARM64 with x86_64
+ Python), accepts wheels for *either* the native arch or the
+ pip-compatible arch so we can download both arm64 image wheels
+ (correct VM images) and amd64 binary wheels (pip-installable).
+ """
+ if "py3-none-any" in name:
+ return True
+
+ native_tag = _get_host_arch_tag()
+ pip_tag = _get_pip_arch_tag()
+
+ if native_tag != pip_tag:
+ # Emulated: accept wheels matching either architecture
+ if native_tag not in name and pip_tag not in name:
+ return False
+ else:
+ if native_tag not in name:
+ return False
+
+ system = platform.system().lower()
+ if system == "darwin":
+ return "macosx" in name and _macos_version_compatible(name)
+ if system == "linux":
+ return "linux" in name or "manylinux" in name
+ if system == "windows":
+ return "win" in name
+ return False
+
+
+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:
+ 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"):
+ continue
+ if not _wheel_compatible_with_host(asset["name"]):
+ continue
+ dest = dest_dir / asset["name"]
+ if dest.exists():
+ continue
+ print(f"Downloading {asset['name']}")
+ _download_with_progress(asset["url"], dest, token, asset["size"])
+ downloaded.append(dest)
+ return downloaded
+
+
+def _extract_dep_names(wheel_path: Path) -> list[str]:
+ """Extract dependency package names from a wheel's METADATA."""
+ import zipfile
+ from email.parser import Parser
+
+ with zipfile.ZipFile(wheel_path) as zf:
+ metadata_files = [n for n in zf.namelist() if n.endswith(".dist-info/METADATA")]
+ if not metadata_files:
+ return []
+ metadata_text = zf.read(metadata_files[0]).decode("utf-8")
+
+ msg = Parser().parsestr(metadata_text)
+ requires = msg.get_all("Requires-Dist") or []
+ names = []
+ for r in requires:
+ r = r.split(";")[0] # drop environment markers
+ for ch in "(<>=!~":
+ r = r.split(ch)[0] # drop version specifiers
+ names.append(r.strip().lower().replace("_", "-"))
+ return names
+
+
+def _is_image_wheel(wheel_path: Path) -> bool:
+ """Check if a wheel provides a quicksand.images entry point."""
+ import zipfile
+
+ with zipfile.ZipFile(wheel_path) as zf:
+ entry_points_files = [n for n in zf.namelist() if n.endswith(".dist-info/entry_points.txt")]
+ if not entry_points_files:
+ return False
+ content = zf.read(entry_points_files[0]).decode("utf-8")
+ return "quicksand.images" in content
+
+
+def _retag_wheels_for_arch(wheel_dir: Path) -> None:
+ """Retag cross-arch image wheels so pip accepts them on this host.
+
+ Only retags wheels that provide quicksand.images entry points (VM image
+ packages). Native binary packages (like quicksand-qemu) must not be
+ retagged — they contain real binaries that only work on their target OS.
+ """
+ import sysconfig
+
+ host_tag = sysconfig.get_platform().replace("-", "_").replace(".", "_")
+ for whl in wheel_dir.glob("*.whl"):
+ parts = whl.stem.rsplit("-", 1)
+ if len(parts) != 2:
+ continue
+ prefix, old_tag = parts
+ if old_tag == "any" or host_tag in old_tag:
+ continue
+ if not _is_image_wheel(whl):
+ continue
+ new_path = whl.parent / f"{prefix}-{host_tag}.whl"
+ whl.rename(new_path)
+
+
+def _cleanup_incompatible_wheels(wheel_dir: Path) -> None:
+ """Remove non-image wheels that pip cannot install on this host.
+
+ After downloading both arch variants (native + pip-compatible) and
+ retagging image wheels, non-image wheels for the native arch remain.
+ pip cannot install them, so remove any that have a pip-compatible
+ counterpart already present in the directory.
+ """
+ import sysconfig
+
+ pip_plat = sysconfig.get_platform().replace("-", "_").replace(".", "_")
+ native_tag = _get_host_arch_tag()
+
+ # Build the native platform tag (e.g. "win_arm64")
+ if platform.system().lower() == "windows":
+ native_plat = f"win_{native_tag}"
+ elif platform.system().lower() == "darwin":
+ native_plat = native_tag # part of macosx_..._arm64
+ else:
+ native_plat = f"linux_{native_tag}"
+
+ for whl in list(wheel_dir.glob("*.whl")):
+ if native_plat not in whl.name:
+ continue
+ # Check if a pip-compatible variant exists
+ pip_name = whl.name.replace(native_plat, pip_plat)
+ pip_variant = whl.parent / pip_name
+ if pip_variant.exists() and pip_variant != whl:
+ 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)
+ for unit in ["B", "KB", "MB", "GB"]:
+ if size < 1024:
+ return f"{size:.1f}{unit}"
+ size /= 1024
+ return f"{size:.1f}TB"
+
+
+def _download_with_progress(url: str, dest: Path, token: str, size: int) -> None:
+ """Download a file with progress bar."""
+ req = urllib.request.Request(url)
+ req.add_header("Authorization", f"Bearer {token}")
+ req.add_header("Accept", "application/octet-stream")
+
+ start_time = time.time()
+ downloaded = 0
+
+ with urllib.request.urlopen(req) as response, open(dest, "wb") as out_file:
+ block_size = 8192
+ while True:
+ buffer = response.read(block_size)
+ if not buffer:
+ break
+ out_file.write(buffer)
+ downloaded += len(buffer)
+
+ elapsed = time.time() - start_time
+ speed = downloaded / elapsed if elapsed > 0 else 0
+ percent = (downloaded / size * 100) if size > 0 else 0
+
+ bar_width = 30
+ filled = int(bar_width * downloaded / size) if size > 0 else 0
+ bar = "#" * filled + "-" * (bar_width - filled)
+
+ sys.stdout.write(
+ f"\r {bar} {percent:5.1f}% {_format_size(downloaded)}/{_format_size(size)} "
+ f"({_format_size(int(speed))}/s)"
+ )
+ sys.stdout.flush()
+
+ sys.stdout.write("\n")
diff --git a/packages/quicksand/quicksand/cli/qemu.py b/packages/quicksand/quicksand/cli/qemu.py
new file mode 100644
index 0000000..413e5d0
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/qemu.py
@@ -0,0 +1,55 @@
+"""QEMU status command."""
+
+from __future__ import annotations
+
+import argparse
+import subprocess
+
+
+def register(subparsers: argparse._SubParsersAction) -> None:
+ """Register the qemu subcommand."""
+ subparsers.add_parser(
+ "qemu",
+ help="Show QEMU installation info",
+ )
+
+
+def cmd(args: argparse.Namespace) -> int:
+ """Show QEMU installation info."""
+ from quicksand_core.qemu.platform import get_runtime
+
+ try:
+ runtime = get_runtime()
+ except RuntimeError as e:
+ print(f"QEMU not available: {e}")
+ return 1
+
+ # Determine source
+ try:
+ from quicksand_qemu import get_bin_dir
+
+ bin_dir = get_bin_dir()
+ if str(runtime.qemu_binary).startswith(str(bin_dir)):
+ source = "bundled (quicksand-qemu)"
+ else:
+ source = "system"
+ except (ImportError, FileNotFoundError):
+ source = "system"
+
+ print(f"Source: {source}")
+ print(f"Path: {runtime.qemu_binary}")
+
+ # Get version
+ try:
+ result = subprocess.run(
+ [runtime.qemu_binary, "--version"],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode == 0:
+ version_line = result.stdout.strip().split("\n")[0]
+ print(f"Version: {version_line}")
+ except Exception:
+ pass
+
+ return 0
diff --git a/packages/quicksand/quicksand/cli/release_save.py b/packages/quicksand/quicksand/cli/release_save.py
new file mode 100644
index 0000000..bac0e54
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/release_save.py
@@ -0,0 +1,275 @@
+"""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
diff --git a/packages/quicksand/quicksand/cli/run.py b/packages/quicksand/quicksand/cli/run.py
new file mode 100644
index 0000000..c3c9c1a
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/run.py
@@ -0,0 +1,287 @@
+"""Run an interactive shell in a sandbox."""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import contextlib
+import sys
+from pathlib import Path
+
+GLOBAL_SAVES_DIR = Path.home() / ".quicksand" / "sandboxes"
+
+
+def register(subparsers: argparse._SubParsersAction) -> None:
+ """Register the run subcommand."""
+ parser = subparsers.add_parser(
+ "run",
+ help="Run an interactive shell in a sandbox",
+ )
+ _add_arguments(parser)
+
+
+def _add_arguments(parser: argparse.ArgumentParser) -> None:
+ """Add run command arguments to the parser."""
+ parser.add_argument(
+ "image",
+ metavar="IMAGE",
+ help="Image to boot: base name (ubuntu, alpine), overlay package, save name, or path",
+ )
+ parser.add_argument(
+ "--arch",
+ default=None,
+ help="Target architecture (e.g. amd64, arm64). "
+ "Auto-detected if omitted. Forces TCG emulation when cross-arch.",
+ )
+ parser.add_argument(
+ "-o",
+ "--output",
+ metavar="NAME_OR_PATH",
+ help="Save sandbox state on exit (name or path)",
+ )
+ parser.add_argument(
+ "--memory",
+ default="512M",
+ help="Memory allocation (default: 512M)",
+ )
+ parser.add_argument(
+ "--cpus",
+ type=int,
+ default=1,
+ help="Number of CPUs (default: 1)",
+ )
+ parser.add_argument(
+ "-v",
+ "--mount",
+ action="append",
+ metavar="HOST:GUEST",
+ help="Mount host directory into sandbox (can be repeated)",
+ )
+ parser.add_argument(
+ "--network",
+ choices=["none", "mounts-only", "full"],
+ default=None,
+ help="Network mode (default: mounts-only)",
+ )
+ parser.add_argument(
+ "-p",
+ "--port",
+ action="append",
+ metavar="HOST:GUEST",
+ help="Forward host port to guest port (can be repeated)",
+ )
+ parser.add_argument(
+ "--boot-timeout",
+ type=float,
+ default=None,
+ help="Boot timeout in seconds",
+ )
+ parser.add_argument(
+ "--accel",
+ choices=["auto", "kvm", "hvf", "whpx", "tcg", "none"],
+ default=None,
+ help="Hardware acceleration (default: auto)",
+ )
+ parser.add_argument(
+ "--disk-size",
+ default=None,
+ help="Resize disk (e.g., '2G', '4G')",
+ )
+ parser.add_argument(
+ "--enable-display",
+ action="store_true",
+ help="Enable virtual display (VNC) for input injection / screenshots",
+ )
+ parser.add_argument(
+ "--extra-args",
+ action="append",
+ metavar="ARG",
+ help="Extra QEMU argument (can be repeated)",
+ )
+ parser.add_argument(
+ "--log-level",
+ choices=["debug", "info", "warning", "error"],
+ default="warning",
+ help="Log level (default: warning)",
+ )
+
+
+_SAVE_EXTS = (".tar.gz", ".tar")
+
+
+def _resolve_save_name(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
+
+ Returns None if not found.
+ """
+ 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
+
+ # Directory first, then .tar.gz, then legacy .tar
+ 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 _save_output_path(name: str) -> Path:
+ """Resolve an output save name to a path (for writing).
+
+ Literal paths are used as-is. Plain names go to ~/.quicksand/sandboxes/<name>/.
+ """
+ if "/" in name or "\\" in name or any(name.endswith(ext) for ext in _SAVE_EXTS):
+ return Path(name)
+ return GLOBAL_SAVES_DIR / name
+
+
+def cmd(args: argparse.Namespace) -> int:
+ """Run an interactive shell in a sandbox."""
+ return asyncio.run(_cmd_async(args))
+
+
+async def _cmd_async(args: argparse.Namespace) -> int:
+ """Async implementation of the run command."""
+ import logging
+
+ from quicksand_core import Mount, Sandbox
+ from quicksand_core._types import NetworkMode
+ from quicksand_core.host import Accelerator
+
+ # Configure logging
+ level = getattr(logging, args.log_level.upper())
+ logging.basicConfig(level=level, format="%(name)s: %(message)s")
+
+ # Parse mounts
+ mounts: list[Mount] = []
+ if args.mount:
+ for mount_str in args.mount:
+ if ":" not in mount_str:
+ print(f"Invalid mount format: {mount_str} (expected HOST:GUEST)", file=sys.stderr)
+ return 1
+ host_path, guest_path = mount_str.split(":", 1)
+ mounts.append(Mount(host=host_path, guest=guest_path))
+
+ # Parse port forwards
+ from quicksand_core._types import PortForward
+
+ port_forwards: list[PortForward] = []
+ if args.port:
+ for pf_str in args.port:
+ if ":" not in pf_str:
+ print(
+ f"Invalid port-forward format: {pf_str} (expected HOST:GUEST)",
+ file=sys.stderr,
+ )
+ return 1
+ host_port, guest_port = pf_str.split(":", 1)
+ try:
+ port_forwards.append(PortForward(host=int(host_port), guest=int(guest_port)))
+ except ValueError:
+ print(f"Invalid port numbers: {pf_str}", file=sys.stderr)
+ return 1
+
+ # Resolve network mode
+ _network_mode_map = {
+ "none": NetworkMode.NONE,
+ "mounts-only": NetworkMode.MOUNTS_ONLY,
+ "full": NetworkMode.FULL,
+ }
+ network_mode = _network_mode_map[args.network] if args.network else NetworkMode.MOUNTS_ONLY
+
+ # Resolve accelerator
+ _accel_map = {
+ "kvm": Accelerator.KVM,
+ "hvf": Accelerator.HVF,
+ "whpx": Accelerator.WHPX,
+ "tcg": Accelerator.TCG,
+ }
+ accel: Accelerator | str | None = "auto"
+ if args.accel is not None:
+ if args.accel == "auto":
+ accel = "auto"
+ elif args.accel == "none":
+ accel = None
+ else:
+ accel = _accel_map[args.accel]
+
+ # Common config kwargs
+ config_kwargs: dict = {
+ "memory": args.memory,
+ "cpus": args.cpus,
+ "mounts": mounts,
+ "network_mode": network_mode,
+ "port_forwards": port_forwards,
+ "extra_qemu_args": args.extra_args or [],
+ "accel": accel,
+ "enable_display": args.enable_display,
+ }
+ if args.boot_timeout is not None:
+ config_kwargs["boot_timeout"] = args.boot_timeout
+ if args.disk_size is not None:
+ config_kwargs["disk_size"] = args.disk_size
+ if args.arch is not None:
+ config_kwargs["arch"] = args.arch
+
+ # Unified image resolution: base name, save name, overlay package, or path
+ image = args.image
+ sb = Sandbox(image=image, **config_kwargs)
+
+ # Start sandbox and run interactive shell
+ label = image
+ print(f"Starting {label} sandbox...")
+ await sb.start()
+
+ try:
+ print("Welcome to quicksand! Type 'exit' to quit.\n")
+ await _run_interactive_shell(sb)
+ except KeyboardInterrupt:
+ print("\nInterrupted.")
+ finally:
+ if args.output:
+ print(f"\nSaving as: {args.output}...")
+ await sb.save(args.output)
+ print(f"Saved: {args.output}")
+ print("\nStopping sandbox...")
+ await sb.stop()
+
+ return 0
+
+
+async def _run_interactive_shell(sb) -> None:
+ """Run an interactive shell loop."""
+ with contextlib.suppress(ImportError):
+ import readline # noqa: F401 - enables line editing in input()
+
+ while True:
+ try:
+ command = input("$ ")
+ except EOFError:
+ # Ctrl+D
+ break
+
+ if not command.strip():
+ continue
+
+ if command.strip() in ("exit", "quit"):
+ break
+
+ try:
+ result = await sb.execute(
+ command,
+ on_stdout=lambda s: print(s, end="", flush=True),
+ on_stderr=lambda s: print(s, end="", file=sys.stderr, flush=True),
+ )
+ if result.exit_code != 0 and result.stderr:
+ print(result.stderr, end="", file=sys.stderr)
+ except KeyboardInterrupt:
+ print("^C")
diff --git a/packages/quicksand/quicksand/cli/uninstall.py b/packages/quicksand/quicksand/cli/uninstall.py
new file mode 100644
index 0000000..add1c53
--- /dev/null
+++ b/packages/quicksand/quicksand/cli/uninstall.py
@@ -0,0 +1,99 @@
+"""Uninstall quicksand extras.
+
+Programmatic API::
+
+ from quicksand.cli.uninstall import uninstall
+
+ uninstall("qemu", "ubuntu")
+ uninstall("all")
+"""
+
+from __future__ import annotations
+
+import argparse
+import subprocess
+import sys
+
+from .install import ALIASES, _parse_extra, _resolve_packages
+
+
+def uninstall(*extras: str) -> None:
+ """Uninstall quicksand extras.
+
+ Args:
+ *extras: One or more extra/package names (e.g. ``"qemu"``, ``"ubuntu"``,
+ ``"all"``).
+
+ Raises:
+ ValueError: If no extras are provided.
+ RuntimeError: If pip uninstall fails.
+
+ Examples::
+
+ from quicksand.cli.uninstall import uninstall
+
+ uninstall("qemu", "ubuntu")
+ uninstall("all")
+ """
+ if not extras:
+ raise ValueError("At least one extra name is required")
+
+ packages: list[str] = []
+ for raw in extras:
+ name, _ver = _parse_extra(raw)
+ for pkg in _resolve_packages(name):
+ if pkg not in packages:
+ packages.append(pkg)
+
+ rc = _uninstall_packages(packages)
+ if rc != 0:
+ raise RuntimeError(f"Failed to uninstall packages: {packages}")
+
+
+def register(subparsers: argparse._SubParsersAction) -> None:
+ """Register the uninstall subcommand."""
+ all_aliases = ", ".join(ALIASES.keys())
+ parser = subparsers.add_parser(
+ "uninstall",
+ help="Uninstall quicksand extras",
+ )
+ parser.add_argument(
+ "extras",
+ nargs="+",
+ metavar="NAME",
+ help=(f"Packages to uninstall. Aliases: {all_aliases}."),
+ )
+
+
+def cmd(args: argparse.Namespace) -> int:
+ """Uninstall quicksand extras."""
+ packages: list[str] = []
+ for raw in args.extras:
+ name, _ver = _parse_extra(raw)
+ for pkg in _resolve_packages(name):
+ if pkg not in packages:
+ packages.append(pkg)
+
+ return _uninstall_packages(packages)
+
+
+def _uninstall_packages(packages: list[str]) -> int:
+ """Run pip uninstall for the given packages."""
+ print(f"Uninstalling: {', '.join(packages)}")
+
+ pip_args = [
+ sys.executable,
+ "-m",
+ "pip",
+ "uninstall",
+ "-y",
+ *packages,
+ ]
+
+ result = subprocess.run(pip_args)
+ if result.returncode != 0:
+ print("\nError: pip uninstall failed.")
+ return 1
+
+ print(f"\nUninstalled {len(packages)} package(s)")
+ return 0
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..e7afae7
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,120 @@
+# Root pyproject.toml for the quicksand monorepo
+# Individual packages are in packages/
+
+[tool.uv]
+keyring-provider = "subprocess"
+override-dependencies = ["httpx>=0.27,<1"]
+constraint-dependencies = ["setuptools>=78.1.1"]
+
+[tool.uv.workspace]
+members = ["packages/*", "packages/dev/*", "packages/contrib/*"]
+exclude = ["packages/dev", "packages/contrib"]
+
+[[tool.uv.index]]
+name = "pypi"
+url = "https://pypi.org/simple"
+default = true
+
+[[tool.uv.index]]
+name = "azure-msraif"
+url = "https://[email protected]/msraif/_packaging/packages/pypi/simple/"
+explicit = true
+
+[tool.uvr.config]
+latest = "quicksand"
+exclude = ["quicksand-gh-runners"]
+workflow_version = "0.28.1"
+skill_version = "0.27.1a3"
+
+[tool.uvr.matrix]
+aif-agent-sandbox = [["self-hosted", "linux", "x64"], ["self-hosted", "macos", "arm64"]]
+aif-cua-agent-sandbox = [["self-hosted", "linux", "x64"], ["self-hosted", "macos", "arm64"]]
+quicksand = [["self-hosted", "linux", "x64"]]
+quicksand-alpine = [["self-hosted", "linux", "x64"], ["self-hosted", "macos", "arm64"]]
+quicksand-alpine-desktop = [["self-hosted", "linux", "x64"], ["self-hosted", "macos", "arm64"]]
+quicksand-base-scaffold = [["self-hosted", "linux", "x64"]]
+quicksand-core = [["self-hosted", "linux", "x64"]]
+quicksand-image-tools = [["self-hosted", "linux", "x64"]]
+quicksand-overlay-scaffold = [["self-hosted", "linux", "x64"]]
+quicksand-qemu = [["self-hosted", "windows", "x64"], ["self-hosted", "windows", "arm64"], ["self-hosted", "linux", "x64"], ["self-hosted", "linux", "arm64"], ["self-hosted", "macos", "arm64"]]
+quicksand-smb = [["self-hosted", "linux", "x64"]]
+quicksand-ubuntu = [["self-hosted", "linux", "x64"], ["self-hosted", "macos", "arm64"]]
+quicksand-ubuntu-desktop = [["self-hosted", "linux", "x64"], ["self-hosted", "macos", "arm64"]]
+
+[tool.uv.sources]
+quicksand = { workspace = true }
+quicksand-core = { workspace = true }
+quicksand-qemu = { workspace = true }
+quicksand-image-tools = { workspace = true }
+quicksand-ubuntu = { workspace = true }
+quicksand-ubuntu-desktop = { workspace = true }
+quicksand-alpine = { workspace = true }
+quicksand-alpine-desktop = { workspace = true }
+quicksand-build-tools = { workspace = true }
+quicksand-smb = { workspace = true }
+quicksand-overlay-scaffold = { workspace = true }
+quicksand-base-scaffold = { workspace = true }
+
+
+[dependency-groups]
+dev = [
+ "ruff",
+ "ty",
+ "poethepoet",
+ "pytest",
+ "pytest-asyncio",
+ "pytest-timeout",
+ "hatchling",
+ "twine",
+ "keyring",
+ "keyrings.artifacts",
+ "uv-release==0.28.1",
+]
+
+[tool.poe.tasks]
+check = ["check-code", "check-format", "check-types"]
+check-code = "ruff check ."
+check-format = "ruff format --check ."
+check-types = "ty check ."
+fix = ["fix-format", "fix-code"]
+fix-format = "ruff format ."
+fix-code = "ruff check --fix --unsafe-fixes ."
+test = "pytest tests/ -x -v --timeout=120 -m 'not docker'"
+test-smb = "pytest tests/unit/smb/ -v --timeout=30"
+release-dry-run = "quicksand-plan-release --format summary"
+release-plan = "quicksand-plan-release"
+test-unit = "pytest tests/unit -v --timeout=60"
+test-integration = "pytest tests/integration -v --timeout=300"
+test-integration-execution = "pytest tests/integration/execution -v --timeout=300"
+test-integration-mounts-readonly = "pytest tests/integration/mounts/readonly -v --timeout=300"
+test-integration-mounts-readwrite = "pytest tests/integration/mounts/readwrite -v --timeout=300"
+test-integration-mounts-multiple = "pytest tests/integration/mounts/multiple -v --timeout=300"
+test-integration-network-unrestricted = "pytest tests/integration/network/unrestricted -v --timeout=300"
+test-integration-checkpoint = "pytest tests/integration/checkpoint -v --timeout=300"
+test-integration-dev = "pytest tests/integration/dev -v --timeout=600 -m docker"
+test-all = "pytest tests/ -x -v --timeout=120"
+ci = ["check-code", "check-format", "check-types", "test"]
+clean = "python scripts/clean.py"
+docs-dev = { shell = "npx vitepress dev docs" }
+docs-build = { shell = "npx vitepress build docs" }
+docs-preview = { shell = "npx vitepress preview docs" }
+
+[tool.pytest.ini_options]
+asyncio_mode = "auto"
+asyncio_default_fixture_loop_scope = "module"
+asyncio_default_test_loop_scope = "module"
+
+[tool.ruff]
+target-version = "py311"
+line-length = 100
+
+[tool.ruff.lint]
+select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF"]
+
+[tool.ty.environment]
+python-version = "3.11"
+extra-paths = ["scripts"]
+
+[tool.ty.src]
+# Scripts meant to run inside sandboxes, not the host
+exclude = ["examples/playwright_vnc/browser_script.py"]
diff --git a/scripts/ci/publish_azure.py b/scripts/ci/publish_azure.py
new file mode 100644
index 0000000..c5fc44a
--- /dev/null
+++ b/scripts/ci/publish_azure.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""Publish wheels to Azure Artifacts using managed identity.
+
+Acquires a bearer token via ManagedIdentityCredential (Azure IMDS) and
+uploads changed wheels in the dist directory using twine.
+
+Usage (CI):
+ UVR_PLAN='...' python scripts/ci/publish_azure.py
+ UVR_PLAN='...' python scripts/ci/publish_azure.py --dist dist/
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+from glob import glob
+from pathlib import Path
+
+# Azure DevOps resource scope (for token acquisition)
+ADO_SCOPE = "499b84ac-1321-427f-aa17-267ca6975798/.default"
+REPO_URL = "https://pkgs.dev.azure.com/msraif/_packaging/packages/pypi/upload/"
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Publish wheels to Azure Artifacts")
+ parser.add_argument(
+ "--dist", default="dist/", help="Directory containing wheel files (default: dist/)"
+ )
+ args = parser.parse_args()
+
+ plan_json = os.environ.get("UVR_PLAN")
+ if not plan_json:
+ print("ERROR: UVR_PLAN environment variable not set", file=sys.stderr)
+ return 1
+
+ plan = json.loads(plan_json)
+ changed = set(plan.get("changed", {}))
+ if not changed:
+ print("No changed packages in plan — nothing to publish.")
+ return 0
+
+ # Convert package names to dist name prefixes (e.g. quicksand-core -> quicksand_core)
+ dist_prefixes = {name.replace("-", "_") for name in changed}
+
+ all_wheels = sorted(glob(f"{args.dist}/*.whl"))
+ wheels = [w for w in all_wheels if any(Path(w).name.startswith(p + "-") for p in dist_prefixes)]
+
+ if not wheels:
+ print(
+ f"ERROR: no .whl files found for changed packages: {', '.join(sorted(changed))}",
+ file=sys.stderr,
+ )
+ return 1
+ print(f"Publishing {len(wheels)} wheels for {len(changed)} changed packages...")
+
+ from azure.identity import ManagedIdentityCredential
+
+ token = ManagedIdentityCredential().get_token(ADO_SCOPE).token
+
+ # Upload one at a time so a 409 (already exists) doesn't abort the batch.
+ failed = []
+ for wheel in wheels:
+ name = Path(wheel).name
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "twine",
+ "upload",
+ "--repository-url",
+ REPO_URL,
+ "--username",
+ "VssSessionToken",
+ "--password",
+ token,
+ wheel,
+ ],
+ capture_output=True,
+ text=True,
+ )
+ output = result.stdout + result.stderr
+ if result.returncode == 0:
+ print(f" {name}: uploaded", flush=True)
+ elif "409" in output or "Conflict" in output or "already contains" in output:
+ print(f" {name}: already exists, skipping", flush=True)
+ else:
+ print(f" {name}: FAILED", flush=True)
+ print(output, flush=True)
+ failed.append(name)
+
+ if failed:
+ print(f"ERROR: {len(failed)} wheel(s) failed to upload", file=sys.stderr)
+ return 1
+ print("Done.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/retag_wheels.py b/scripts/ci/retag_wheels.py
new file mode 100644
index 0000000..001d640
--- /dev/null
+++ b/scripts/ci/retag_wheels.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Re-tag wheel files for different platforms.
+
+VM image wheels contain qcow2 files that are architecture-specific but OS-agnostic.
+This script creates copies with platform tags for macOS and Windows so they can
+be installed on any host. Output is flat (no subdirectories).
+
+Usage:
+ python scripts/retag_wheels.py dist/
+"""
+
+from __future__ import annotations
+
+import argparse
+import re
+import shutil
+import sys
+from pathlib import Path
+
+WHEEL_PATTERN = re.compile(
+ r"^(?P<name>.+?)-(?P<version>.+?)-(?P<python>\w+)-(?P<abi>\w+)-(?P<platform>.+)\.whl$"
+)
+
+# Architecture (extracted from the platform tag suffix) -> target platform tags.
+# The source OS is irrelevant — these wheels contain OS-agnostic qcow2 images.
+_ARCH_RE = re.compile(r"(?:x86_64|aarch64|arm64|amd64)$")
+
+ARCH_TARGETS = {
+ "x86_64": ["linux_x86_64", "macosx_10_13_x86_64", "win_amd64"],
+ "amd64": ["linux_x86_64", "macosx_10_13_x86_64", "win_amd64"],
+ "aarch64": ["linux_aarch64", "macosx_11_0_arm64"],
+ "arm64": ["linux_aarch64", "macosx_11_0_arm64"],
+}
+
+
+SKIP_RETAG = {"quicksand_qemu"}
+
+
+def retag_wheel(wheel_path: Path, output_dir: Path) -> list[Path]:
+ """Re-tag a wheel for multiple platforms. Returns created file paths."""
+ match = WHEEL_PATTERN.match(wheel_path.name)
+ if not match:
+ print(f" Skipping (not a valid wheel): {wheel_path.name}", file=sys.stderr)
+ return []
+
+ parts = match.groupdict()
+
+ if parts["name"] in SKIP_RETAG:
+ print(f" Skipping (natively built on all platforms): {wheel_path.name}")
+ return [wheel_path]
+ source_platform = parts["platform"]
+ arch_match = _ARCH_RE.search(source_platform)
+
+ if not arch_match:
+ print(f" Skipping (unknown arch in platform {source_platform}): {wheel_path.name}")
+ dest = output_dir / wheel_path.name
+ if dest.resolve() != wheel_path.resolve():
+ shutil.copy2(wheel_path, dest)
+ return [dest]
+
+ targets = ARCH_TARGETS[arch_match.group()]
+
+ created = []
+ for target_platform in targets:
+ new_name = f"{parts['name']}-{parts['version']}-py3-none-{target_platform}.whl"
+ dest = output_dir / new_name
+ if dest.resolve() != wheel_path.resolve():
+ shutil.copy2(wheel_path, dest)
+ created.append(dest)
+ print(f" -> {new_name}")
+
+ return created
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Re-tag wheels for multiple platforms")
+ parser.add_argument("wheels", nargs="+", type=Path, help="Wheel files or directories")
+ parser.add_argument(
+ "-o", "--output", type=Path, default=None, help="Output directory (default: same as input)"
+ )
+ args = parser.parse_args()
+
+ wheel_files: list[Path] = []
+ for path in args.wheels:
+ if path.is_dir():
+ wheel_files.extend(path.glob("*.whl"))
+ elif path.suffix == ".whl":
+ wheel_files.append(path)
+
+ if not wheel_files:
+ print("No wheel files found", file=sys.stderr)
+ return 1
+
+ output_dir = args.output or wheel_files[0].parent
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ all_created: list[Path] = []
+ for wheel in sorted(wheel_files):
+ print(f"Processing: {wheel.name}")
+ all_created.extend(retag_wheel(wheel, output_dir))
+
+ print(f"\nCreated {len(all_created)} wheels:")
+ for w in sorted(all_created):
+ size_mb = w.stat().st_size / (1024 * 1024)
+ print(f" {w.name} ({size_mb:.1f} MB)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/verify_licenses.py b/scripts/ci/verify_licenses.py
new file mode 100644
index 0000000..cdcbe5a
--- /dev/null
+++ b/scripts/ci/verify_licenses.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3
+"""Verify GPL license files are present in quicksand-qemu wheels.
+
+quicksand-qemu bundles GPL-licensed QEMU binaries. This script verifies
+that the required license files are present for GPL compliance.
+
+Usage:
+ python scripts/verify_licenses.py dist/*.whl
+"""
+
+from __future__ import annotations
+
+import sys
+import zipfile
+from pathlib import Path
+
+# Required license files by platform
+REQUIRED_FILES: dict[str, list[str]] = {
+ "darwin": ["COPYING", "LICENSE"],
+ "linux": ["copyright"],
+ "win": ["COPYING"],
+}
+
+
+def _detect_platform(wheel_name: str) -> str | None:
+ """Map a wheel filename to a platform key."""
+ name = wheel_name.lower()
+ if "macosx" in name:
+ return "darwin"
+ if "linux" in name:
+ return "linux"
+ if "win" in name:
+ return "win"
+ return None
+
+
+def verify_wheel(wheel_path: Path) -> bool:
+ """Check that required license files exist in the wheel."""
+ plat = _detect_platform(wheel_path.name)
+ if plat is None:
+ print(f" FAIL: Unknown platform in {wheel_path.name}")
+ return False
+
+ required = REQUIRED_FILES[plat]
+ ok = True
+
+ with zipfile.ZipFile(wheel_path) as zf:
+ names = zf.namelist()
+ license_files = [n for n in names if "/licenses/" in n]
+
+ print(f"\n{wheel_path.name}:")
+ print(f" Platform: {plat}")
+ print(f" License files found: {[Path(f).name for f in license_files]}")
+
+ # --- Check required license texts ---------------------------------
+ missing = []
+ for req in required:
+ if not any(req in f for f in license_files):
+ missing.append(req)
+
+ if missing:
+ print(f" FAIL: Missing required license files: {missing}")
+ ok = False
+ else:
+ print(" OK: All required license files present")
+
+ # --- Check SOURCES.md ---------------------------------------------
+ sources_files = [n for n in license_files if n.endswith("SOURCES.md")]
+ if not sources_files:
+ print(" FAIL: SOURCES.md not found in licenses/")
+ ok = False
+ else:
+ content = zf.read(sources_files[0]).decode()
+ ok = _verify_sources_md(content) and ok
+
+ return ok
+
+
+def _verify_sources_md(content: str) -> bool:
+ """Validate that SOURCES.md is well-formed and non-trivial."""
+ ok = True
+
+ # Must have the header row and at least QEMU
+ lines = [ln for ln in content.splitlines() if ln.startswith("|") and "---" not in ln]
+ # First line is header, rest are data rows
+ data_rows = lines[1:] if len(lines) > 1 else []
+
+ if not data_rows:
+ print(" FAIL: SOURCES.md contains no component entries")
+ return False
+
+ # QEMU itself must be listed
+ if not any("QEMU" in row for row in data_rows):
+ print(" FAIL: SOURCES.md does not list QEMU")
+ ok = False
+
+ # Every row must have a source URL (non-empty 4th column)
+ empty_source = []
+ for row in data_rows:
+ cols = [c.strip() for c in row.split("|")]
+ # cols[0] is empty (before first |), cols are: '', name, ver, lic, src, ''
+ if len(cols) >= 5 and not cols[4]:
+ empty_source.append(cols[1])
+
+ if empty_source:
+ print(f" FAIL: SOURCES.md entries missing source URL: {empty_source}")
+ ok = False
+
+ if ok:
+ print(f" OK: SOURCES.md lists {len(data_rows)} component(s) with source URLs")
+
+ return ok
+
+
+def main() -> int:
+ if len(sys.argv) < 2:
+ print("Usage: verify_licenses.py <wheel> [wheel ...]")
+ return 1
+
+ wheels = [Path(p) for p in sys.argv[1:]]
+ qemu_wheels = [w for w in wheels if "quicksand_qemu" in w.name or "quicksand-qemu" in w.name]
+
+ if not qemu_wheels:
+ print("No quicksand-qemu wheels found to verify.")
+ return 0
+
+ print(f"Verifying {len(qemu_wheels)} quicksand-qemu wheel(s)...")
+ results = [verify_wheel(w) for w in qemu_wheels]
+
+ print(f"\n{'=' * 60}")
+ passed = sum(results)
+ total = len(results)
+ print(f"Results: {passed}/{total} wheels passed license verification")
+ return 0 if all(results) else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/clean.py b/scripts/clean.py
new file mode 100644
index 0000000..493b4cc
--- /dev/null
+++ b/scripts/clean.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+"""Clean build artifacts from the quicksand monorepo."""
+
+from __future__ import annotations
+
+import shutil
+import sys
+import tempfile
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).parent.parent
+
+
+def main() -> int:
+ print("Cleaning build artifacts...")
+
+ # Remove dist directories
+ _rmtree(REPO_ROOT / "dist")
+ for pkg in (REPO_ROOT / "packages").iterdir():
+ if pkg.is_dir():
+ _rmtree(pkg / "dist")
+
+ # Remove egg-info and __pycache__
+ for pattern in ["**/*.egg-info", "**/__pycache__"]:
+ for path in REPO_ROOT.glob(pattern):
+ _rmtree(path)
+
+ # Remove built VM images (keep directory structure)
+ for ext in ["*.qcow2", "*.initrd", "*.kernel", "manifest.json"]:
+ for path in REPO_ROOT.glob(f"packages/**/images/**/{ext}"):
+ path.unlink(missing_ok=True)
+ print(f" Removed: {path.relative_to(REPO_ROOT)}")
+ for path in REPO_ROOT.glob(f"packages/**/images/{ext}"):
+ path.unlink(missing_ok=True)
+ print(f" Removed: {path.relative_to(REPO_ROOT)}")
+
+ # Remove bundled QEMU binaries (keep .gitkeep)
+ bin_dir = REPO_ROOT / "packages/quicksand-core/quicksand_core/bin"
+ if bin_dir.exists():
+ for item in bin_dir.iterdir():
+ if item.name != ".gitkeep":
+ if item.is_dir():
+ shutil.rmtree(item)
+ else:
+ item.unlink()
+ print(f" Removed: {item.relative_to(REPO_ROOT)}")
+
+ # Remove temp quicksand directories
+ tmp = Path(tempfile.gettempdir())
+ for path in tmp.glob("quicksand-*"):
+ _rmtree(path)
+ print(f" Removed: {path}")
+
+ print("Clean complete.")
+ return 0
+
+
+def _rmtree(path: Path) -> None:
+ """Remove a directory tree if it exists."""
+ if path.exists():
+ shutil.rmtree(path)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/test_aif_agent_sandboxes.py b/test_aif_agent_sandboxes.py
new file mode 100644
index 0000000..2fe7a6d
--- /dev/null
+++ b/test_aif_agent_sandboxes.py
@@ -0,0 +1,77 @@
+"""Load the saved AIF agent sandboxes and verify everything works via bare commands."""
+
+import asyncio
+import sys
+from pathlib import Path
+
+from quicksand import UbuntuSandbox
+
+SAVE_DIR = Path(__file__).parent
+
+
+async def run(sb, cmd, timeout=30.0):
+ print(f">>> {cmd}")
+ result = await sb.execute(cmd, timeout=timeout, shell="/bin/bash")
+ print(result.stdout, end="")
+ if result.stderr:
+ print(result.stderr, end="", file=sys.stderr)
+ if result.exit_code != 0:
+ raise RuntimeError(f"FAIL (exit {result.exit_code}): {cmd}")
+ return result
+
+
+async def test_agent_harness():
+ print("=" * 60)
+ print("Testing aif-agent-harness")
+ print("=" * 60)
+
+ sb = UbuntuSandbox(image=str(SAVE_DIR / "aif-agent-harness.tar.gz"))
+ async with sb:
+ # Bare python/pip on PATH (no /opt/python/bin prefix)
+ await run(sb, "python3 --version")
+ await run(sb, "python --version")
+ await run(sb, "pip --version")
+ await run(sb, "pip3 --version")
+
+ # Packages importable
+ await run(sb, "python -c 'import requests; print(f\"requests {requests.__version__}\")'")
+ await run(sb, "python -c 'import markitdown; print(\"markitdown OK\")'")
+
+ print("\naif-agent-harness: PASSED\n")
+
+
+async def test_cua_agent_harness():
+ print("=" * 60)
+ print("Testing aif-cua-agent-harness")
+ print("=" * 60)
+
+ sb = UbuntuSandbox(image=str(SAVE_DIR / "aif-cua-agent-harness.tar.gz"))
+ async with sb:
+ # Everything from layer 1 still works
+ await run(sb, "python --version")
+ await run(sb, "pip --version")
+ await run(sb, "python -c 'import requests; import markitdown; print(\"layer 1 OK\")'")
+
+ # Playwright importable and chromium installed
+ await run(
+ sb,
+ "python -c 'from playwright.sync_api import sync_playwright; print(\"playwright OK\")'",
+ )
+ await run(sb, "playwright --version")
+
+ # VNC stack present
+ await run(sb, "which Xvfb")
+ await run(sb, "which x11vnc")
+ await run(sb, "which openbox")
+
+ print("\naif-cua-agent-harness: PASSED\n")
+
+
+async def main():
+ await test_agent_harness()
+ await test_cua_agent_harness()
+ print("All tests passed.")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/test_cua_sandbox.py b/test_cua_sandbox.py
new file mode 100644
index 0000000..97296fe
--- /dev/null
+++ b/test_cua_sandbox.py
@@ -0,0 +1,37 @@
+"""Load aif-cua-agent-sandbox-slim and verify chromium-vnc service starts."""
+
+import asyncio
+import random
+import time
+
+from quicksand import PortForward, Sandbox
+from quicksand_core._types import NetworkMode
+
+HOST_PORT = random.randint(20000, 50000)
+
+
+async def main():
+ sb = Sandbox(
+ image="aif-cua-agent-sandbox-slim.tar.gz",
+ port_forwards=[PortForward(host=HOST_PORT, guest=5901)],
+ network_mode=NetworkMode.FULL,
+ )
+ async with sb:
+ time.sleep(5)
+
+ r = await sb.execute("rc-status", shell="/bin/sh")
+ print(r.stdout)
+
+ r = await sb.execute("ss -tlnp | grep 5901", shell="/bin/sh")
+ print(f"VNC listening: {r.stdout.strip()}")
+
+ print(f"\nConnect VNC viewer to localhost:{HOST_PORT}")
+ print("Ctrl+C to stop")
+ try:
+ while True:
+ time.sleep(1)
+ except KeyboardInterrupt:
+ pass
+
+
+asyncio.run(main())
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..b920454
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1 @@
+"""Quicksand tests."""
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..a765795
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,232 @@
+"""Shared pytest fixtures for quicksand tests."""
+
+from __future__ import annotations
+
+import shutil
+import tempfile
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# ============================================================================
+# Markers
+# ============================================================================
+
+
+def pytest_configure(config):
+ """Register custom markers."""
+ config.addinivalue_line("markers", "integration: integration tests (require QEMU)")
+ config.addinivalue_line("markers", "slow: marks tests as slow")
+ config.addinivalue_line("markers", "docker: marks tests that require Docker")
+
+
+# ============================================================================
+# Skip conditions
+# ============================================================================
+
+
+def has_qemu() -> bool:
+ """Check if bundled QEMU is available from quicksand-core."""
+ try:
+ from quicksand_core.qemu.platform import get_runtime
+
+ runtime = get_runtime()
+ return runtime.qemu_binary.exists()
+ except Exception:
+ return False
+
+
+def has_docker() -> bool:
+ """Check if Docker is available."""
+ return shutil.which("docker") is not None
+
+
+def has_mke2fs() -> bool:
+ """Check if mke2fs is available."""
+ if shutil.which("mke2fs"):
+ return True
+ # Check Homebrew keg-only locations on macOS
+ for path in [
+ "/opt/homebrew/opt/e2fsprogs/sbin/mke2fs", # Apple Silicon
+ "/usr/local/opt/e2fsprogs/sbin/mke2fs", # Intel Mac
+ ]:
+ if Path(path).exists():
+ return True
+ return False
+
+
+skip_no_qemu = pytest.mark.skipif(not has_qemu(), reason="QEMU not installed")
+skip_no_docker = pytest.mark.skipif(not has_docker(), reason="Docker not installed")
+skip_no_mke2fs = pytest.mark.skipif(not has_mke2fs(), reason="mke2fs not installed")
+
+
+# ============================================================================
+# Fixtures - Temporary directories
+# ============================================================================
+
+
+def tmp_dir():
+ """Create a temporary directory that is cleaned up after the test."""
+ path = Path(tempfile.mkdtemp(prefix="quicksand-test-"))
+ yield path
+ shutil.rmtree(path, ignore_errors=True)
+
+
+def cache_dir(tmp_dir):
+ """Create a temporary cache directory."""
+ cache = tmp_dir / "cache"
+ cache.mkdir()
+ return cache
+
+
+# ============================================================================
+# Fixtures - Mock runtime
+# ============================================================================
+
+
+def mock_runtime(tmp_dir):
+ """Create a mock runtime with fake QEMU binaries."""
+ from quicksand_core.qemu.platform import RuntimeInfo
+
+ # Create fake binaries
+ runtime_dir = tmp_dir / "runtime"
+ runtime_dir.mkdir()
+ qemu_binary = tmp_dir / "qemu-system-x86_64"
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_binary.touch()
+ qemu_img.touch()
+ qemu_binary.chmod(0o755)
+ qemu_img.chmod(0o755)
+
+ return RuntimeInfo(
+ qemu_binary=qemu_binary,
+ qemu_img=qemu_img,
+ runtime_dir=runtime_dir,
+ )
+
+
+def mock_get_runtime(mock_runtime):
+ """Patch get_runtime to return mock runtime."""
+ with patch("quicksand_core.qemu.platform.get_runtime", return_value=mock_runtime):
+ yield mock_runtime
+
+
+# ============================================================================
+# Fixtures - Mock images
+# ============================================================================
+
+
+def fake_qcow2(tmp_dir):
+ """Create a fake qcow2 image file."""
+ image_path = tmp_dir / "test-image.qcow2"
+ # Write a minimal qcow2 header (just enough to be recognized)
+ image_path.write_bytes(b"QFI\xfb" + b"\x00" * 100)
+ return image_path
+
+
+def fake_kernel(tmp_dir):
+ """Create a fake kernel file."""
+ kernel_path = tmp_dir / "test-image.kernel"
+ kernel_path.write_bytes(b"fake kernel")
+ return kernel_path
+
+
+def fake_initrd(tmp_dir):
+ """Create a fake initrd file."""
+ initrd_path = tmp_dir / "test-image.initrd"
+ initrd_path.write_bytes(b"fake initrd")
+ return initrd_path
+
+
+def fake_image_set(tmp_dir):
+ """Create a complete fake image set (qcow2 + kernel + initrd)."""
+ base = tmp_dir / "test-image"
+
+ qcow2 = base.with_suffix(".qcow2")
+ kernel = base.with_suffix(".kernel")
+ initrd = base.with_suffix(".initrd")
+
+ qcow2.write_bytes(b"QFI\xfb" + b"\x00" * 100)
+ kernel.write_bytes(b"fake kernel")
+ initrd.write_bytes(b"fake initrd")
+
+ return {"qcow2": qcow2, "kernel": kernel, "initrd": initrd}
+
+
+# ============================================================================
+# Fixtures - Dockerfile content
+# ============================================================================
+
+
+def simple_dockerfile():
+ """A simple Dockerfile for testing."""
+ return """
+FROM alpine:3.20
+RUN apk add --no-cache python3
+CMD ["/bin/sh"]
+"""
+
+
+def ubuntu_dockerfile():
+ """Ubuntu Dockerfile with kernel."""
+ return """
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive
+RUN apt-get update && apt-get install -y linux-image-virtual
+CMD ["/bin/bash"]
+"""
+
+
+# ============================================================================
+# Fixtures - Mock subprocess
+# ============================================================================
+
+
+def mock_subprocess():
+ """Mock subprocess.run for testing commands without execution."""
+ with patch("subprocess.run") as mock_run:
+ mock_run.return_value = MagicMock(
+ returncode=0,
+ stdout="",
+ stderr="",
+ )
+ yield mock_run
+
+
+def mock_popen():
+ """Mock subprocess.Popen for testing process creation."""
+ with patch("subprocess.Popen") as mock_popen_cls:
+ mock_process = MagicMock()
+ mock_process.poll.return_value = None
+ mock_process.returncode = None
+ mock_process.stderr = MagicMock()
+ mock_process.stderr.read.return_value = b""
+ mock_popen_cls.return_value = mock_process
+ yield mock_popen_cls, mock_process
+
+
+# ============================================================================
+# Fixtures - Mock socket
+# ============================================================================
+
+
+def mock_socket():
+ """Mock socket for testing virtio-serial communication."""
+ with patch("socket.socket") as mock_socket_cls:
+ mock_sock = MagicMock()
+ mock_socket_cls.return_value = mock_sock
+ yield mock_socket_cls, mock_sock
diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py
new file mode 100644
index 0000000..e66b8e0
--- /dev/null
+++ b/tests/integration/__init__.py
@@ -0,0 +1 @@
+# Integration tests for quicksand
diff --git a/tests/integration/checkpoint/__init__.py b/tests/integration/checkpoint/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/checkpoint/conftest.py b/tests/integration/checkpoint/conftest.py
new file mode 100644
index 0000000..b929ed3
--- /dev/null
+++ b/tests/integration/checkpoint/conftest.py
@@ -0,0 +1,7 @@
+"""Fixtures for checkpoint tests - no shared sandbox (exception).
+
+Checkpoint tests inherently require boot -> checkpoint -> stop -> restore cycles,
+so each test manages its own sandbox(es).
+"""
+
+from __future__ import annotations
diff --git a/tests/integration/checkpoint/test_create.py b/tests/integration/checkpoint/test_create.py
new file mode 100644
index 0000000..19a0ad3
--- /dev/null
+++ b/tests/integration/checkpoint/test_create.py
@@ -0,0 +1,59 @@
+"""Tests for save creation."""
+
+from __future__ import annotations
+
+import pytest
+from quicksand import Sandbox
+
+from tests.conftest import skip_no_qemu
+
+
+class TestSaveCreate:
+ """Save creation tests."""
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_save_creates_files(self, real_image, real_kernel, tmp_dir):
+ """Test that save() creates a directory with the expected contents."""
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("echo 'test' > /tmp/marker.txt")
+ manifest = await sb.save("my-save", workspace=tmp_dir)
+
+ # Save is a directory
+ save_path = tmp_dir / "my-save"
+ assert save_path.is_dir()
+ assert (save_path / "manifest.json").exists()
+ assert (save_path / "overlays" / "0.qcow2").exists()
+
+ assert manifest.version == 6
+ assert manifest.config.image == "ubuntu"
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_save_overwrites_existing(self, real_image, real_kernel, tmp_dir):
+ """Test that save atomically replaces an existing save."""
+ existing = tmp_dir / "my-save"
+ existing.mkdir()
+ (existing / "old-file.txt").write_text("should be replaced")
+
+ async with Sandbox(image="ubuntu") as sb:
+ manifest = await sb.save("my-save", workspace=tmp_dir)
+
+ assert existing.is_dir()
+ assert not (existing / "old-file.txt").exists()
+ assert (existing / "manifest.json").exists()
+ assert manifest.version == 6
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_validate_save(self, real_image, real_kernel, tmp_dir):
+ """Test validate_save returns correct manifest."""
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.save("my-save", workspace=tmp_dir)
+
+ save_path = tmp_dir / "my-save"
+ manifest = Sandbox.validate_save(save_path)
+ assert manifest.version == 6
+ assert manifest.config.image == "ubuntu"
diff --git a/tests/integration/checkpoint/test_restore.py b/tests/integration/checkpoint/test_restore.py
new file mode 100644
index 0000000..2820624
--- /dev/null
+++ b/tests/integration/checkpoint/test_restore.py
@@ -0,0 +1,167 @@
+"""Tests for save/load (restore) cycle."""
+
+from __future__ import annotations
+
+import warnings
+
+import pytest
+from quicksand import OS, Mount, NetworkMode, Sandbox, get_platform_config
+
+from tests.conftest import skip_no_qemu
+
+
+class TestSaveLoad:
+ """Save and load (restore) tests."""
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_save_load_cycle(self, real_image, real_kernel, tmp_dir):
+ """Test full save and load cycle."""
+ # Use /home/quicksand since /tmp is cleared on boot by systemd
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("echo 'save test' > /home/quicksand/marker.txt")
+ await sb.save("my-save", workspace=tmp_dir)
+
+ loaded = Sandbox(image=str(tmp_dir / "my-save"))
+ async with loaded:
+ result = await loaded.execute("cat /home/quicksand/marker.txt")
+ assert result.exit_code == 0
+ assert "save test" in result.stdout
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_load_clears_mounts_by_default(self, real_image, real_kernel, tmp_dir):
+ """Test that load clears mounts by default."""
+ # Skip on Windows - SMB mounts not supported in CI
+ platform_config = get_platform_config()
+ if platform_config.os.os_type == OS.WINDOWS:
+ pytest.skip("SMB mounts not supported in Windows CI environment")
+
+ mount_dir = tmp_dir / "mount"
+ mount_dir.mkdir()
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ async with Sandbox(
+ image="ubuntu",
+ mounts=[Mount(str(mount_dir), "/mnt/test")],
+ network_mode=NetworkMode.FULL,
+ ) as sb:
+ await sb.save("my-save", workspace=tmp_dir)
+
+ loaded = Sandbox(image=str(tmp_dir / "my-save"))
+ assert len(loaded.config.mounts) == 0
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_load_with_config_overrides(self, real_image, real_kernel, tmp_dir):
+ """Test that config overrides work when loading a save."""
+ async with Sandbox(image="ubuntu", memory="512M") as sb:
+ await sb.save("my-save", workspace=tmp_dir)
+
+ loaded = Sandbox(image=str(tmp_dir / "my-save"), memory="1G")
+ assert loaded.config.memory == "1G"
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_load_with_new_mounts(self, real_image, real_kernel, tmp_dir):
+ """Test that new mounts can be specified on load."""
+ # Skip on Windows - SMB mounts not supported in CI
+ platform_config = get_platform_config()
+ if platform_config.os.os_type == OS.WINDOWS:
+ pytest.skip("SMB mounts not supported in Windows CI environment")
+
+ mount_dir = tmp_dir / "new_mount"
+ mount_dir.mkdir()
+ (mount_dir / "testfile.txt").write_text("from host")
+
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.save("my-save", workspace=tmp_dir)
+
+ loaded = Sandbox(
+ image=str(tmp_dir / "my-save"),
+ mounts=[Mount(str(mount_dir), "/mnt/data")],
+ network_mode=NetworkMode.FULL,
+ )
+
+ async with loaded:
+ # File should be visible immediately (true filesystem mount)
+ result = await loaded.execute("cat /mnt/data/testfile.txt")
+ assert result.exit_code == 0
+ assert "from host" in result.stdout
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_multiple_saves(self, real_image, real_kernel, tmp_dir):
+ """Test creating and loading multiple saves."""
+ # Use /home/quicksand since /tmp is cleared on boot by systemd
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("echo 'state1' > /home/quicksand/state.txt")
+ await sb.save("save1", workspace=tmp_dir)
+
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("echo 'state2' > /home/quicksand/state.txt")
+ await sb.save("save2", workspace=tmp_dir)
+
+ loaded1 = Sandbox(image=str(tmp_dir / "save1"))
+ async with loaded1:
+ result = await loaded1.execute("cat /home/quicksand/state.txt")
+ assert "state1" in result.stdout
+
+ loaded2 = Sandbox(image=str(tmp_dir / "save2"))
+ async with loaded2:
+ result = await loaded2.execute("cat /home/quicksand/state.txt")
+ assert "state2" in result.stdout
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_save_load_save_cycle(self, real_image, real_kernel, tmp_dir):
+ """Test that data persists across load -> write -> save (same name) -> load."""
+ # First save: create a file on rootfs
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("echo 'round1' > /home/quicksand/persist.txt")
+ await sb.save("reusable", workspace=tmp_dir)
+
+ # Load, write more, save again to the same name
+ loaded = Sandbox(
+ image=str(tmp_dir / "reusable"),
+ save="reusable",
+ workspace=tmp_dir,
+ )
+ async with loaded:
+ result = await loaded.execute("cat /home/quicksand/persist.txt")
+ assert "round1" in result.stdout
+ await loaded.execute("echo 'round2' >> /home/quicksand/persist.txt")
+ # stop() auto-saves to tmp_dir/reusable (overwrites existing)
+
+ # Load the re-saved directory -- both rounds should be present
+ loaded2 = Sandbox(image=str(tmp_dir / "reusable"))
+ async with loaded2:
+ result = await loaded2.execute("cat /home/quicksand/persist.txt")
+ assert "round1" in result.stdout
+ assert "round2" in result.stdout
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_multi_save_in_session(self, real_image, real_kernel, tmp_dir):
+ """Test two save() calls on the same running sandbox produce valid saves."""
+ async with Sandbox(image="ubuntu") as sb:
+ await sb.execute("echo 'first' > /home/quicksand/state.txt")
+ await sb.save("snap-a", workspace=tmp_dir)
+
+ await sb.execute("echo 'second' >> /home/quicksand/state.txt")
+ await sb.save("snap-b", workspace=tmp_dir)
+
+ loaded_a = Sandbox(image=str(tmp_dir / "snap-a"))
+ async with loaded_a:
+ result = await loaded_a.execute("cat /home/quicksand/state.txt")
+ assert "first" in result.stdout
+ assert "second" not in result.stdout
+
+ loaded_b = Sandbox(image=str(tmp_dir / "snap-b"))
+ async with loaded_b:
+ result = await loaded_b.execute("cat /home/quicksand/state.txt")
+ assert "first" in result.stdout
+ assert "second" in result.stdout
diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py
new file mode 100644
index 0000000..c82a2ee
--- /dev/null
+++ b/tests/integration/conftest.py
@@ -0,0 +1,89 @@
+"""Shared fixtures for all integration tests."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import tempfile
+from pathlib import Path
+
+import pytest
+from quicksand_core import detect_accelerator
+from quicksand_core.host import Accelerator
+
+_accel_status = detect_accelerator()
+_has_hw_accel = _accel_status.accelerator in (
+ Accelerator.KVM,
+ Accelerator.HVF,
+ Accelerator.WHPX,
+)
+
+pytestmark = pytest.mark.skipif(
+ not _has_hw_accel,
+ reason=f"No hardware acceleration available ({_accel_status.error or 'TCG only'})",
+)
+
+
+def get_vm_type() -> str:
+ """Get VM type from environment variable."""
+ return os.environ.get("QUICKSAND_TEST_VM", "ubuntu")
+
+
+def _get_image_artifacts():
+ """Get image path and kernel path for the configured VM type.
+
+ Uses the ImageProvider.resolve() method from the installed image package.
+ """
+ vm_type = get_vm_type()
+
+ if vm_type == "ubuntu":
+ try:
+ from quicksand_ubuntu import _UbuntuImageProvider
+
+ resolved = _UbuntuImageProvider().resolve()
+ return str(resolved.chain[0]), str(resolved.kernel) if resolved.kernel else None
+ except ImportError:
+ pytest.skip("quicksand-ubuntu not installed")
+ elif vm_type == "alpine":
+ try:
+ from quicksand_alpine import _AlpineImageProvider
+
+ resolved = _AlpineImageProvider().resolve()
+ return str(resolved.chain[0]), str(resolved.kernel) if resolved.kernel else None
+ except ImportError:
+ pytest.skip("quicksand-alpine not installed")
+ else:
+ pytest.skip(f"Unknown VM type: {vm_type}")
+
+
[email protected](scope="module")
+def real_image():
+ """Get path to pre-built VM image.
+
+ VM type is determined by QUICKSAND_TEST_VM environment variable.
+ Defaults to 'ubuntu' if not set.
+ """
+ image_path, _kernel_path = _get_image_artifacts()
+ return image_path
+
+
[email protected](scope="module")
+def real_kernel():
+ """Get path to pre-built VM kernel.
+
+ VM type is determined by QUICKSAND_TEST_VM environment variable.
+ Defaults to 'ubuntu' if not set.
+ """
+ _image_path, kernel_path = _get_image_artifacts()
+ return kernel_path
+
+
[email protected](scope="module")
+def integration_tmp_dir():
+ """Module-scoped temp directory for integration tests.
+
+ Shared across tests in a module for setting up mount directories, etc.
+ """
+ path = Path(tempfile.mkdtemp(prefix="quicksand-integration-"))
+ yield path
+ shutil.rmtree(path, ignore_errors=True)
diff --git a/tests/integration/dev/__init__.py b/tests/integration/dev/__init__.py
new file mode 100644
index 0000000..2d6c2a4
--- /dev/null
+++ b/tests/integration/dev/__init__.py
@@ -0,0 +1 @@
+"""Integration tests for quicksand-image-tools."""
diff --git a/tests/integration/dev/conftest.py b/tests/integration/dev/conftest.py
new file mode 100644
index 0000000..4a5c683
--- /dev/null
+++ b/tests/integration/dev/conftest.py
@@ -0,0 +1,60 @@
+"""Fixtures for quicksand-image-tools integration tests."""
+
+from __future__ import annotations
+
+import itertools
+import shutil
+import subprocess
+import tempfile
+from pathlib import Path
+
+import pytest
+
+_build_dir_counter = itertools.count()
+
+
[email protected](scope="module")
+def dev_tmp_dir():
+ """Create a temporary directory for dev integration tests."""
+ path = Path(tempfile.mkdtemp(prefix="quicksand-image-tools-test-"))
+ yield path
+ shutil.rmtree(path, ignore_errors=True)
+
+
+def build_dir(dev_tmp_dir):
+ """Create a fresh build directory for each test."""
+ path = dev_tmp_dir / f"build-{next(_build_dir_counter)}"
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def docker_image_exists(tag: str) -> bool:
+ """Check if a Docker image exists locally."""
+ result = subprocess.run(
+ ["docker", "image", "inspect", tag],
+ capture_output=True,
+ )
+ return result.returncode == 0
+
+
+def remove_docker_image(tag: str) -> None:
+ """Remove a Docker image if it exists."""
+ subprocess.run(
+ ["docker", "rmi", "-f", tag],
+ capture_output=True,
+ )
+
+
+def clean_test_image():
+ """Ensure test image is cleaned up after test."""
+ tags_to_clean = []
+
+ def register(tag: str):
+ tags_to_clean.append(tag)
+
+ yield register
+
+ for tag in tags_to_clean:
+ remove_docker_image(tag)
diff --git a/tests/integration/dev/test_dev_commands.py b/tests/integration/dev/test_dev_commands.py
new file mode 100644
index 0000000..d7210cc
--- /dev/null
+++ b/tests/integration/dev/test_dev_commands.py
@@ -0,0 +1,296 @@
+"""Integration tests for quicksand-image-tools CLI commands.
+
+These tests require Docker to be installed and running.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from tests.conftest import skip_no_docker
+from tests.integration.dev.conftest import docker_image_exists
+
+
+@skip_no_docker
+class TestBuildBase:
+ """Integration tests for build-base command."""
+
+ def test_build_base_ubuntu(self, clean_test_image):
+ """Test building Ubuntu base image."""
+ # Skip if quicksand-ubuntu not installed
+ try:
+ from quicksand_ubuntu import DISTRO_VERSION as ubuntu_version
+ except ImportError:
+ pytest.skip("quicksand-ubuntu not installed")
+
+ versioned_tag = f"quicksand/ubuntu-base:{ubuntu_version}"
+ latest_tag = "quicksand/ubuntu-base:latest"
+ clean_test_image(versioned_tag)
+ clean_test_image(latest_tag)
+
+ result = subprocess.run(
+ ["quicksand-image-tools", "build-base", "ubuntu"],
+ capture_output=True,
+ text=True,
+ timeout=300,
+ )
+
+ assert result.returncode == 0, f"build-base failed: {result.stderr}"
+ assert docker_image_exists(versioned_tag)
+ assert docker_image_exists(latest_tag)
+ assert f"Built: {versioned_tag}" in result.stdout
+
+ def test_build_base_alpine(self, clean_test_image):
+ """Test building Alpine base image."""
+ # Skip if quicksand-alpine not installed
+ try:
+ from quicksand_alpine import DISTRO_VERSION as alpine_version
+ except ImportError:
+ pytest.skip("quicksand-alpine not installed")
+
+ versioned_tag = f"quicksand/alpine-base:{alpine_version}"
+ latest_tag = "quicksand/alpine-base:latest"
+ clean_test_image(versioned_tag)
+ clean_test_image(latest_tag)
+
+ result = subprocess.run(
+ ["quicksand-image-tools", "build-base", "alpine"],
+ capture_output=True,
+ text=True,
+ timeout=300,
+ )
+
+ assert result.returncode == 0, f"build-base failed: {result.stderr}"
+ assert docker_image_exists(versioned_tag)
+ assert docker_image_exists(latest_tag)
+
+
+@skip_no_docker
+class TestInit:
+ """Integration tests for init command."""
+
+ def test_init_creates_dockerfile(self, build_dir, clean_test_image):
+ """Test that init creates a Dockerfile."""
+ # Skip if quicksand-ubuntu not installed
+ try:
+ from quicksand_ubuntu import DISTRO_VERSION as ubuntu_version
+ except ImportError:
+ pytest.skip("quicksand-ubuntu not installed")
+
+ versioned_tag = f"quicksand/ubuntu-base:{ubuntu_version}"
+ clean_test_image(versioned_tag)
+ clean_test_image("quicksand/ubuntu-base:latest")
+
+ result = subprocess.run(
+ ["quicksand-image-tools", "init", str(build_dir), "ubuntu"],
+ capture_output=True,
+ text=True,
+ timeout=300,
+ )
+
+ assert result.returncode == 0, f"init failed: {result.stderr}"
+
+ dockerfile = build_dir / "Dockerfile"
+ assert dockerfile.exists()
+
+ content = dockerfile.read_text()
+ assert f"FROM {versioned_tag}" in content
+
+ def test_init_builds_base_if_missing(self, build_dir, clean_test_image):
+ """Test that init builds base image if it doesn't exist."""
+ try:
+ from quicksand_ubuntu import DISTRO_VERSION as ubuntu_version
+ except ImportError:
+ pytest.skip("quicksand-ubuntu not installed")
+
+ versioned_tag = f"quicksand/ubuntu-base:{ubuntu_version}"
+ latest_tag = "quicksand/ubuntu-base:latest"
+
+ # Remove the image first
+ subprocess.run(["docker", "rmi", "-f", versioned_tag], capture_output=True)
+ subprocess.run(["docker", "rmi", "-f", latest_tag], capture_output=True)
+
+ clean_test_image(versioned_tag)
+ clean_test_image(latest_tag)
+
+ result = subprocess.run(
+ ["quicksand-image-tools", "init", str(build_dir), "ubuntu"],
+ capture_output=True,
+ text=True,
+ timeout=300,
+ )
+
+ assert result.returncode == 0, f"init failed: {result.stderr}"
+ assert "not found, building" in result.stdout
+ assert docker_image_exists(versioned_tag)
+
+ def test_init_skips_existing_dockerfile(self, build_dir):
+ """Test that init doesn't overwrite existing Dockerfile."""
+ dockerfile = build_dir / "Dockerfile"
+ original_content = "FROM my-custom-image:latest\n"
+ dockerfile.write_text(original_content)
+
+ result = subprocess.run(
+ ["quicksand-image-tools", "init", str(build_dir), "ubuntu"],
+ capture_output=True,
+ text=True,
+ )
+
+ # Should succeed but not modify the Dockerfile
+ assert result.returncode == 0
+ assert dockerfile.read_text() == original_content
+
+ def test_init_error_without_base(self, build_dir):
+ """Test that init errors when no base specified and no Dockerfile."""
+ result = subprocess.run(
+ ["quicksand-image-tools", "init", str(build_dir)],
+ capture_output=True,
+ text=True,
+ )
+
+ assert result.returncode == 1
+ assert "No Dockerfile found" in result.stderr
+ assert "ubuntu|alpine" in result.stderr
+
+
+@skip_no_docker
+class TestBuildImage:
+ """Integration tests for build-image command.
+
+ These tests are slow because they actually build Docker images
+ and convert them to qcow2.
+ """
+
+ def test_build_image_simple(self, build_dir, clean_test_image):
+ """Test building a simple custom image."""
+ try:
+ from quicksand_ubuntu import DISTRO_VERSION as ubuntu_version
+ except ImportError:
+ pytest.skip("quicksand-ubuntu not installed")
+
+ # First ensure base image exists
+ versioned_tag = f"quicksand/ubuntu-base:{ubuntu_version}"
+ if not docker_image_exists(versioned_tag):
+ subprocess.run(
+ ["quicksand-image-tools", "build-base", "ubuntu"],
+ capture_output=True,
+ timeout=300,
+ )
+
+ clean_test_image(versioned_tag)
+ clean_test_image("quicksand/ubuntu-base:latest")
+
+ # Create Dockerfile
+ dockerfile = build_dir / "Dockerfile"
+ dockerfile.write_text(f"""FROM {versioned_tag}
+RUN echo "test" > /tmp/test.txt
+""")
+
+ output_path = build_dir / "test-image.qcow2"
+
+ result = subprocess.run(
+ ["quicksand-image-tools", "build-image", str(dockerfile), "-o", str(output_path)],
+ capture_output=True,
+ text=True,
+ timeout=600,
+ )
+
+ assert result.returncode == 0, f"build-image failed: {result.stderr}"
+ assert output_path.exists()
+ assert output_path.stat().st_size > 0
+
+ def test_build_image_with_cache(self, build_dir, clean_test_image):
+ """Test that build-image uses cache directory."""
+ try:
+ from quicksand_ubuntu import DISTRO_VERSION as ubuntu_version
+ except ImportError:
+ pytest.skip("quicksand-ubuntu not installed")
+
+ versioned_tag = f"quicksand/ubuntu-base:{ubuntu_version}"
+ if not docker_image_exists(versioned_tag):
+ subprocess.run(
+ ["quicksand-image-tools", "build-base", "ubuntu"],
+ capture_output=True,
+ timeout=300,
+ )
+
+ clean_test_image(versioned_tag)
+ clean_test_image("quicksand/ubuntu-base:latest")
+
+ # Create Dockerfile
+ dockerfile = build_dir / "Dockerfile"
+ dockerfile.write_text(f"FROM {versioned_tag}\n")
+
+ cache_dir = build_dir / "cache"
+ output_path = build_dir / "test-image.qcow2"
+
+ result = subprocess.run(
+ [
+ "quicksand-image-tools",
+ "build-image",
+ str(dockerfile),
+ "-o",
+ str(output_path),
+ "--cache-dir",
+ str(cache_dir),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=600,
+ )
+
+ # Build should succeed
+ assert result.returncode == 0, f"build-image failed: {result.stderr}"
+ assert output_path.exists()
+
+
+@skip_no_docker
+class TestEndToEndWorkflow:
+ """End-to-end workflow tests."""
+
+ def test_full_workflow_init_and_build(self, build_dir, clean_test_image):
+ """Test the complete workflow: init -> customize -> build."""
+ try:
+ from quicksand_ubuntu import DISTRO_VERSION as ubuntu_version
+ except ImportError:
+ pytest.skip("quicksand-ubuntu not installed")
+
+ versioned_tag = f"quicksand/ubuntu-base:{ubuntu_version}"
+ clean_test_image(versioned_tag)
+ clean_test_image("quicksand/ubuntu-base:latest")
+
+ # Step 1: Initialize
+ result = subprocess.run(
+ ["quicksand-image-tools", "init", str(build_dir), "ubuntu"],
+ capture_output=True,
+ text=True,
+ timeout=300,
+ )
+ assert result.returncode == 0, f"init failed: {result.stderr}"
+
+ # Step 2: Customize Dockerfile
+ dockerfile = build_dir / "Dockerfile"
+ original = dockerfile.read_text()
+ dockerfile.write_text(original + "\nRUN echo 'customized' > /customized.txt\n")
+
+ # Step 3: Build
+ output_path = build_dir / "custom.qcow2"
+ result = subprocess.run(
+ ["quicksand-image-tools", "build-image", str(dockerfile), "-o", str(output_path)],
+ capture_output=True,
+ text=True,
+ timeout=600,
+ )
+ assert result.returncode == 0, f"build failed: {result.stderr}"
+ assert output_path.exists()
diff --git a/tests/integration/execution/__init__.py b/tests/integration/execution/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/execution/conftest.py b/tests/integration/execution/conftest.py
new file mode 100644
index 0000000..f19c558
--- /dev/null
+++ b/tests/integration/execution/conftest.py
@@ -0,0 +1,47 @@
+"""Fixtures for execution tests - shared sandbox for efficiency."""
+
+from __future__ import annotations
+
+import pytest
+import pytest_asyncio
+
+from tests.conftest import has_qemu
+from tests.integration.conftest import get_vm_type
+
+
+def _get_sandbox_class():
+ """Get the appropriate sandbox class based on VM type."""
+ vm_type = get_vm_type()
+
+ if vm_type == "ubuntu":
+ from quicksand import UbuntuSandbox
+
+ return UbuntuSandbox
+ elif vm_type == "alpine":
+ from quicksand import AlpineSandbox
+
+ return AlpineSandbox
+ else:
+ raise ValueError(f"Unknown VM type: {vm_type}")
+
+
+@pytest_asyncio.fixture(scope="module")
+async def shared_sandbox():
+ """Module-scoped sandbox for execution tests.
+
+ All tests in this group share one sandbox for fast execution.
+ Tests should not leave the sandbox in a broken state.
+ VM type is determined by QUICKSAND_TEST_VM environment variable.
+ """
+ try:
+ SandboxClass = _get_sandbox_class()
+ except ImportError:
+ pytest.skip(f"quicksand-{get_vm_type()} not installed")
+
+ if not has_qemu():
+ pytest.skip("QEMU not installed")
+
+ sandbox = SandboxClass()
+ await sandbox.start()
+ yield sandbox
+ await sandbox.stop()
diff --git a/tests/integration/execution/test_commands.py b/tests/integration/execution/test_commands.py
new file mode 100644
index 0000000..9378106
--- /dev/null
+++ b/tests/integration/execution/test_commands.py
@@ -0,0 +1,55 @@
+"""Tests for basic command execution."""
+
+from __future__ import annotations
+
+import pytest
+
+
+class TestBasicCommands:
+ """Basic command execution tests using shared sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_execute_echo(self, shared_sandbox):
+ """Test simple echo command."""
+ result = await shared_sandbox.execute("echo 'hello world'")
+ assert result.exit_code == 0
+ assert "hello world" in result.stdout
+
+ @pytest.mark.asyncio
+ async def test_execute_exit_code(self, shared_sandbox):
+ """Test command exit codes are captured."""
+ result = await shared_sandbox.execute("exit 42")
+ assert result.exit_code == 42
+
+ @pytest.mark.asyncio
+ async def test_execute_stderr(self, shared_sandbox):
+ """Test stderr is captured."""
+ result = await shared_sandbox.execute("echo error >&2")
+ assert "error" in result.stderr
+
+ @pytest.mark.asyncio
+ async def test_execute_with_cwd(self, shared_sandbox):
+ """Test command execution with working directory."""
+ result = await shared_sandbox.execute("pwd", cwd="/tmp")
+ assert "/tmp" in result.stdout
+
+ @pytest.mark.asyncio
+ async def test_multiline_script(self, shared_sandbox):
+ """Test executing a multiline script."""
+ script = """
+ x=5
+ y=10
+ echo $((x + y))
+ """
+ result = await shared_sandbox.execute(script)
+ assert result.exit_code == 0
+ assert "15" in result.stdout
+
+ @pytest.mark.asyncio
+ async def test_environment_persistence(self, shared_sandbox):
+ """Test that environment changes don't persist between commands."""
+ await shared_sandbox.execute("export TESTVAR=value1")
+ result = await shared_sandbox.execute("echo $TESTVAR")
+ # Environment should not persist (each execute is a new shell)
+ assert "value1" not in result.stdout or result.stdout.strip() == ""
diff --git a/tests/integration/execution/test_files.py b/tests/integration/execution/test_files.py
new file mode 100644
index 0000000..c4a6f51
--- /dev/null
+++ b/tests/integration/execution/test_files.py
@@ -0,0 +1,25 @@
+"""Tests for file read/write operations via execute()."""
+
+from __future__ import annotations
+
+import pytest
+
+
+class TestFileOperations:
+ """File operation tests using shared sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_write_and_read_file(self, shared_sandbox):
+ """Test writing and reading a text file via shell commands."""
+ await shared_sandbox.execute("echo -n 'test content' > /tmp/test.txt")
+ result = await shared_sandbox.execute("cat /tmp/test.txt")
+ assert result.stdout.strip() == "test content"
+
+ @pytest.mark.asyncio
+ async def test_write_and_read_binary(self, shared_sandbox):
+ """Test writing and reading binary data via shell commands."""
+ # Write binary bytes using printf with POSIX octal escapes
+ await shared_sandbox.execute(r"printf '\000\001\002\377' > /tmp/binary.bin")
+ result = await shared_sandbox.execute("od -A n -t x1 /tmp/binary.bin | tr -d ' \\n'")
+ assert result.stdout.strip() == "000102ff"
diff --git a/tests/integration/execution/test_lifecycle.py b/tests/integration/execution/test_lifecycle.py
new file mode 100644
index 0000000..44ea8eb
--- /dev/null
+++ b/tests/integration/execution/test_lifecycle.py
@@ -0,0 +1,39 @@
+"""Integration tests for sandbox lifecycle (no real VM needed)."""
+
+from __future__ import annotations
+
+import pytest
+from quicksand import Sandbox
+
+from tests.conftest import skip_no_qemu
+
+
+class TestSandboxLifecycle:
+ """Tests for sandbox lifecycle that don't require a real VM."""
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_sandbox_start_requires_image(self, tmp_dir):
+ """Test that starting sandbox without image fails gracefully."""
+ sandbox = Sandbox(image="nonexistent-image-that-does-not-exist")
+
+ with pytest.raises(RuntimeError, match="Image not found"):
+ await sandbox.start()
+
+ @skip_no_qemu
+ def test_sandbox_not_running_initially(self, fake_qcow2):
+ """Test sandbox is not running after creation."""
+ sandbox = Sandbox(image="ubuntu")
+
+ assert sandbox.is_running is False
+
+ @skip_no_qemu
+ @pytest.mark.asyncio
+ async def test_sandbox_stop_when_not_running(self, fake_qcow2):
+ """Test that stopping a non-running sandbox is safe."""
+ sandbox = Sandbox(image="ubuntu")
+
+ # Should not raise
+ await sandbox.stop()
+ assert sandbox.is_running is False
diff --git a/tests/integration/execution/test_network_default.py b/tests/integration/execution/test_network_default.py
new file mode 100644
index 0000000..c92bbea
--- /dev/null
+++ b/tests/integration/execution/test_network_default.py
@@ -0,0 +1,18 @@
+"""Tests for default network behavior (NetworkMode.MOUNTS_ONLY)."""
+
+from __future__ import annotations
+
+import pytest
+
+
+class TestNetworkDefault:
+ """Default network tests using shared sandbox (NetworkMode.MOUNTS_ONLY)."""
+
+ @pytest.mark.asyncio
+ async def test_mounts_only_blocks_external(self, shared_sandbox):
+ """Test that NetworkMode.MOUNTS_ONLY blocks internet access."""
+ # Try to ping an external host (should fail/timeout)
+ result = await shared_sandbox.execute("ping -c 1 -W 2 8.8.8.8", timeout=5.0)
+ # Should fail - restricted network blocks external traffic
+ assert result.exit_code != 0
diff --git a/tests/integration/execution/test_timeouts.py b/tests/integration/execution/test_timeouts.py
new file mode 100644
index 0000000..1270f5f
--- /dev/null
+++ b/tests/integration/execution/test_timeouts.py
@@ -0,0 +1,16 @@
+"""Tests for command timeout handling."""
+
+from __future__ import annotations
+
+import pytest
+
+
+class TestTimeouts:
+ """Timeout tests using shared sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_command_timeout(self, shared_sandbox):
+ """Test command timeout handling."""
+ result = await shared_sandbox.execute("sleep 10", timeout=1.0)
+ assert result.exit_code != 0 or "timeout" in result.stderr.lower()
diff --git a/tests/integration/mounts/__init__.py b/tests/integration/mounts/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/mounts/multiple/__init__.py b/tests/integration/mounts/multiple/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/mounts/multiple/conftest.py b/tests/integration/mounts/multiple/conftest.py
new file mode 100644
index 0000000..bf9c68c
--- /dev/null
+++ b/tests/integration/mounts/multiple/conftest.py
@@ -0,0 +1,53 @@
+"""Fixtures for multiple mount tests - shared sandbox with multiple mounts."""
+
+from __future__ import annotations
+
+import pytest
+import pytest_asyncio
+from quicksand import OS, Mount, NetworkMode, Sandbox, get_platform_config
+
+from tests.conftest import has_qemu
+
+
+@pytest_asyncio.fixture(scope="module")
+async def shared_sandbox(real_image, real_kernel, integration_tmp_dir):
+ """Module-scoped sandbox with multiple mounts configured.
+
+ All tests in this group share one sandbox with multiple mounts.
+ """
+ if not has_qemu():
+ pytest.skip("QEMU not installed")
+
+ # Skip on Windows - SMB mounts require specific server configuration
+ # that isn't available in CI environments
+ platform_config = get_platform_config()
+ if platform_config.os.os_type == OS.WINDOWS:
+ pytest.skip("SMB mounts not supported in Windows CI environment")
+
+ dir1 = integration_tmp_dir / "mount1"
+ dir2 = integration_tmp_dir / "mount2"
+ dir1.mkdir(exist_ok=True)
+ dir2.mkdir(exist_ok=True)
+ (dir1 / "file1.txt").write_text("content1")
+ (dir2 / "file2.txt").write_text("content2")
+
+ sandbox = Sandbox(
+ image="ubuntu",
+ mounts=[
+ Mount(str(dir1), "/mnt/one"),
+ Mount(str(dir2), "/mnt/two"),
+ ],
+ network_mode=NetworkMode.FULL,
+ )
+ await sandbox.start()
+ yield sandbox
+ await sandbox.stop()
+
+
[email protected](scope="module")
+def mount_dirs(integration_tmp_dir):
+ """Return the mount directory paths for assertions."""
+ return {
+ "one": integration_tmp_dir / "mount1",
+ "two": integration_tmp_dir / "mount2",
+ }
diff --git a/tests/integration/mounts/multiple/test_multiple.py b/tests/integration/mounts/multiple/test_multiple.py
new file mode 100644
index 0000000..90dbb6b
--- /dev/null
+++ b/tests/integration/mounts/multiple/test_multiple.py
@@ -0,0 +1,29 @@
+"""Tests for multiple mounts."""
+
+from __future__ import annotations
+
+import pytest
+
+
+class TestMultipleMounts:
+ """Multiple mount tests using shared sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_multiple_mounts_readable(self, shared_sandbox):
+ """Test reading from multiple mounts."""
+ result1 = await shared_sandbox.execute("cat /mnt/one/file1.txt")
+ result2 = await shared_sandbox.execute("cat /mnt/two/file2.txt")
+
+ assert result1.exit_code == 0
+ assert "content1" in result1.stdout
+ assert result2.exit_code == 0
+ assert "content2" in result2.stdout
+
+ @pytest.mark.asyncio
+ async def test_multiple_mounts_isolated(self, shared_sandbox):
+ """Test that mounts are isolated from each other."""
+ # File from mount1 should not be visible in mount2
+ result = await shared_sandbox.execute("ls /mnt/two/file1.txt")
+ assert result.exit_code != 0
diff --git a/tests/integration/mounts/readonly/__init__.py b/tests/integration/mounts/readonly/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/mounts/readonly/conftest.py b/tests/integration/mounts/readonly/conftest.py
new file mode 100644
index 0000000..1e21007
--- /dev/null
+++ b/tests/integration/mounts/readonly/conftest.py
@@ -0,0 +1,44 @@
+"""Fixtures for readonly mount tests - shared sandbox with readonly mount."""
+
+from __future__ import annotations
+
+import pytest
+import pytest_asyncio
+from quicksand import OS, Mount, NetworkMode, Sandbox, get_platform_config
+
+from tests.conftest import has_qemu
+
+
+@pytest_asyncio.fixture(scope="module")
+async def shared_sandbox(real_image, real_kernel, integration_tmp_dir):
+ """Module-scoped sandbox with readonly mount configured.
+
+ All tests in this group share one sandbox with a readonly mount.
+ """
+ if not has_qemu():
+ pytest.skip("QEMU not installed")
+
+ # Skip on Windows - SMB mounts require specific server configuration
+ # that isn't available in CI environments
+ platform_config = get_platform_config()
+ if platform_config.os.os_type == OS.WINDOWS:
+ pytest.skip("SMB mounts not supported in Windows CI environment")
+
+ mount_dir = integration_tmp_dir / "readonly"
+ mount_dir.mkdir(exist_ok=True)
+ (mount_dir / "test.txt").write_text("host content")
+
+ sandbox = Sandbox(
+ image="ubuntu",
+ mounts=[Mount(str(mount_dir), "/mnt/host", readonly=True)],
+ network_mode=NetworkMode.FULL,
+ )
+ await sandbox.start()
+ yield sandbox
+ await sandbox.stop()
+
+
[email protected](scope="module")
+def mount_dir(integration_tmp_dir):
+ """Return the mount directory path for assertions."""
+ return integration_tmp_dir / "readonly"
diff --git a/tests/integration/mounts/readonly/test_readonly.py b/tests/integration/mounts/readonly/test_readonly.py
new file mode 100644
index 0000000..141a572
--- /dev/null
+++ b/tests/integration/mounts/readonly/test_readonly.py
@@ -0,0 +1,24 @@
+"""Tests for readonly mounts."""
+
+from __future__ import annotations
+
+import pytest
+
+
+class TestReadonlyMount:
+ """Readonly mount tests using shared sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_readonly_can_read(self, shared_sandbox):
+ """Test reading from readonly mount."""
+ result = await shared_sandbox.execute("cat /mnt/host/test.txt")
+ assert result.exit_code == 0
+ assert "host content" in result.stdout
+
+ @pytest.mark.asyncio
+ async def test_readonly_cannot_write(self, shared_sandbox):
+ """Test writing to readonly mount fails (enforced by 9p and SMB)."""
+ result = await shared_sandbox.execute("touch /mnt/host/newfile.txt")
+ assert result.exit_code != 0
diff --git a/tests/integration/mounts/readwrite/__init__.py b/tests/integration/mounts/readwrite/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/mounts/readwrite/conftest.py b/tests/integration/mounts/readwrite/conftest.py
new file mode 100644
index 0000000..018a037
--- /dev/null
+++ b/tests/integration/mounts/readwrite/conftest.py
@@ -0,0 +1,43 @@
+"""Fixtures for readwrite mount tests - shared sandbox with readwrite mount."""
+
+from __future__ import annotations
+
+import pytest
+import pytest_asyncio
+from quicksand import OS, Mount, NetworkMode, Sandbox, get_platform_config
+
+from tests.conftest import has_qemu
+
+
+@pytest_asyncio.fixture(scope="module")
+async def shared_sandbox(real_image, real_kernel, integration_tmp_dir):
+ """Module-scoped sandbox with readwrite mount configured.
+
+ All tests in this group share one sandbox with a readwrite mount.
+ """
+ if not has_qemu():
+ pytest.skip("QEMU not installed")
+
+ # Skip on Windows - SMB mounts require specific server configuration
+ # that isn't available in CI environments
+ platform_config = get_platform_config()
+ if platform_config.os.os_type == OS.WINDOWS:
+ pytest.skip("SMB mounts not supported in Windows CI environment")
+
+ mount_dir = integration_tmp_dir / "readwrite"
+ mount_dir.mkdir(exist_ok=True)
+
+ sandbox = Sandbox(
+ image="ubuntu",
+ mounts=[Mount(str(mount_dir), "/mnt/host", readonly=False)],
+ network_mode=NetworkMode.FULL,
+ )
+ await sandbox.start()
+ yield sandbox
+ await sandbox.stop()
+
+
[email protected](scope="module")
+def mount_dir(integration_tmp_dir):
+ """Return the mount directory path for assertions."""
+ return integration_tmp_dir / "readwrite"
diff --git a/tests/integration/mounts/readwrite/test_readwrite.py b/tests/integration/mounts/readwrite/test_readwrite.py
new file mode 100644
index 0000000..3d71bf0
--- /dev/null
+++ b/tests/integration/mounts/readwrite/test_readwrite.py
@@ -0,0 +1,122 @@
+"""Tests for read-write mounts."""
+
+from __future__ import annotations
+
+import tempfile
+import time
+from pathlib import Path
+
+import pytest
+
+
+def wait_for_file(path, timeout: float = 10.0, content: str | None = None) -> bool:
+ """Wait for a file to appear and optionally contain expected content."""
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if path.exists():
+ if content is None:
+ return True
+ try:
+ if content in path.read_text():
+ return True
+ except OSError:
+ pass # File may be in-progress
+ time.sleep(0.1)
+ return False
+
+
+class TestReadWriteMount:
+ """Read-write mount tests using shared sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_readwrite_can_write(self, shared_sandbox, mount_dir):
+ """Test writing to read-write mount."""
+ await shared_sandbox.execute("echo 'from sandbox' > /mnt/host/sandbox.txt")
+
+ # File should appear on host (instant for both 9p and SMB mounts)
+ assert wait_for_file(mount_dir / "sandbox.txt", content="from sandbox")
+
+ @pytest.mark.asyncio
+ async def test_readwrite_can_read(self, shared_sandbox, mount_dir):
+ """Test reading from read-write mount."""
+ # Create file on host
+ host_file = mount_dir / "host_file.txt"
+ host_file.write_text("from host")
+
+ # File should be visible in guest immediately (true filesystem mount)
+ result = await shared_sandbox.execute("cat /mnt/host/host_file.txt")
+ assert result.exit_code == 0
+ assert "from host" in result.stdout
+
+ @pytest.mark.asyncio
+ async def test_directory_listing_filenames(self, shared_sandbox, mount_dir):
+ """Test that ls inside the guest returns correct filenames.
+
+ Regression test: a bug caused filenames to lose their first ~2
+ characters when listed via CIFS mount (e.g. README.md -> ADME.md).
+ """
+ # Create files with known names on host
+ test_files = ["README.md", "LICENSE", ".github", "setup.py", "pyproject.toml"]
+ for name in test_files:
+ path = mount_dir / name
+ if not path.exists():
+ if name == ".github":
+ path.mkdir(exist_ok=True)
+ else:
+ path.write_text(f"content of {name}")
+
+ # List directory inside guest
+ result = await shared_sandbox.execute("ls -1a /mnt/host/")
+ assert result.exit_code == 0
+
+ listed = result.stdout.strip().split("\n")
+ for name in test_files:
+ assert name in listed, f"Expected '{name}' in guest ls output, got: {listed}"
+
+ @pytest.mark.asyncio
+ async def test_dynamic_mount_and_unmount(self, shared_sandbox):
+ """Test dynamic hot-mount and unmount on a running sandbox."""
+ with tempfile.TemporaryDirectory(prefix="quicksand-dynmount-") as tmpdir:
+ hot_dir = Path(tmpdir)
+ (hot_dir / "dynamic.txt").write_text("dynamic content")
+
+ # Dynamic mount
+ handle = await shared_sandbox.mount(str(hot_dir), "/mnt/dynamic")
+
+ result = await shared_sandbox.execute("cat /mnt/dynamic/dynamic.txt")
+ assert result.exit_code == 0
+ assert "dynamic content" in result.stdout
+
+ # Write from guest
+ await shared_sandbox.execute("echo 'from guest' > /mnt/dynamic/guest.txt")
+ assert (hot_dir / "guest.txt").exists()
+ assert "from guest" in (hot_dir / "guest.txt").read_text()
+
+ # Unmount
+ await shared_sandbox.unmount(handle)
+
+ result = await shared_sandbox.execute("ls /mnt/dynamic/ 2>&1")
+ # After unmount, directory should be empty or mount point gone
+ assert "dynamic.txt" not in result.stdout
+
+ @pytest.mark.asyncio
+ async def test_dynamic_readonly_mount(self, shared_sandbox):
+ """Test dynamic readonly mount rejects writes."""
+ with tempfile.TemporaryDirectory(prefix="quicksand-romount-") as tmpdir:
+ ro_dir = Path(tmpdir)
+ (ro_dir / "readonly.txt").write_text("read only content")
+
+ handle = await shared_sandbox.mount(str(ro_dir), "/mnt/dynro", readonly=True)
+
+ # Read should work
+ result = await shared_sandbox.execute("cat /mnt/dynro/readonly.txt")
+ assert result.exit_code == 0
+ assert "read only content" in result.stdout
+
+ # Write should fail
+ result = await shared_sandbox.execute("touch /mnt/dynro/nope 2>&1")
+ assert result.exit_code != 0
+
+ await shared_sandbox.unmount(handle)
diff --git a/tests/integration/network/__init__.py b/tests/integration/network/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/network/unrestricted/__init__.py b/tests/integration/network/unrestricted/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/integration/network/unrestricted/conftest.py b/tests/integration/network/unrestricted/conftest.py
new file mode 100644
index 0000000..92b6196
--- /dev/null
+++ b/tests/integration/network/unrestricted/conftest.py
@@ -0,0 +1,31 @@
+"""Fixtures for full network tests - shared sandbox with NetworkMode.FULL."""
+
+from __future__ import annotations
+
+import pytest
+import pytest_asyncio
+from quicksand import NetworkMode, Sandbox
+
+from tests.conftest import has_qemu
+
+
+@pytest_asyncio.fixture(scope="module")
+async def shared_sandbox(real_image, real_kernel):
+ """Module-scoped sandbox with full network.
+
+ All tests in this group share one sandbox with NetworkMode.FULL.
+ """
+ if not has_qemu():
+ pytest.skip("QEMU not installed")
+
+ sandbox = Sandbox(
+ image="ubuntu",
+ network_mode=NetworkMode.FULL,
+ )
+ await sandbox.start()
+
+ # Configure DNS (not configured by default in minimal images)
+ await sandbox.execute('echo "nameserver 8.8.8.8" > /etc/resolv.conf')
+
+ yield sandbox
+ await sandbox.stop()
diff --git a/tests/integration/network/unrestricted/test_unrestricted.py b/tests/integration/network/unrestricted/test_unrestricted.py
new file mode 100644
index 0000000..86d630c
--- /dev/null
+++ b/tests/integration/network/unrestricted/test_unrestricted.py
@@ -0,0 +1,66 @@
+"""Tests for unrestricted network mode."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+
+async def _wait_for_network(sandbox, timeout: float = 15.0) -> None:
+ """Wait for guest networking to be ready (default route present).
+
+ With virtio-serial, the agent connects before networking is up.
+ """
+ for _ in range(int(timeout / 0.5)):
+ result = await sandbox.execute("ip route show default", timeout=5.0)
+ if result.exit_code == 0 and "default" in result.stdout:
+ return
+ await asyncio.sleep(0.5)
+
+
+class TestUnrestrictedNetwork:
+ """Unrestricted network tests using shared sandbox."""
+
+ @pytest.mark.asyncio
+ async def test_unrestricted_can_reach_external(self, shared_sandbox):
+ """Test that unrestricted network can reach external hosts.
+
+ Note: This test may fail in some CI environments that don't have
+ internet access. The key assertion is that the network is not
+ blocked at the QEMU level.
+ """
+ await _wait_for_network(shared_sandbox)
+ # Try to reach an external host - this tests that QEMU isn't blocking
+ result = await shared_sandbox.execute("ping -c 1 -W 5 8.8.8.8", timeout=10.0)
+ # If we have internet, this should succeed. If not, at least verify
+ # we got a proper network error (not a QEMU firewall block)
+ # Exit code 0 = success, 1 = host unreachable (but network worked)
+ # Exit code 2 = network error
+ assert result.exit_code in (0, 1, 2)
+
+ @pytest.mark.asyncio
+ async def test_dns_resolution(self, shared_sandbox):
+ """Test that DNS resolution works in unrestricted network mode."""
+ await _wait_for_network(shared_sandbox)
+ # Try to resolve a well-known hostname using getent (portable)
+ result = await shared_sandbox.execute("getent hosts google.com", timeout=10.0)
+ # getent should succeed if DNS is working
+ assert result.exit_code == 0, f"DNS resolution failed: {result.stderr}"
+ assert "google.com" in result.stdout, "Expected hostname in getent output"
+
+ @pytest.mark.asyncio
+ async def test_curl_https(self, shared_sandbox):
+ """Test that HTTPS requests work (requires DNS + network)."""
+ await _wait_for_network(shared_sandbox)
+ # Try to fetch a URL - this tests both DNS and network connectivity
+ result = await shared_sandbox.execute(
+ "curl -s -o /dev/null -w '%{http_code}' --max-time 10 https://google.com",
+ timeout=15.0,
+ )
+ # Should get a redirect (301/302) or success (200)
+ assert result.exit_code == 0, f"curl failed: {result.stderr}"
+ http_code = result.stdout.strip()
+ assert http_code in ("200", "301", "302"), f"Unexpected HTTP code: {http_code}"
diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py
new file mode 100644
index 0000000..ed4144c
--- /dev/null
+++ b/tests/unit/__init__.py
@@ -0,0 +1 @@
+# Unit tests for quicksand
diff --git a/tests/unit/smb/test_protocol.py b/tests/unit/smb/test_protocol.py
new file mode 100644
index 0000000..53ed1fa
--- /dev/null
+++ b/tests/unit/smb/test_protocol.py
@@ -0,0 +1,157 @@
+"""Unit tests for SMB3 protocol framing and header parsing."""
+
+import struct
+
+from quicksand_smb._protocol import (
+ SMB2_HEADER_SIZE,
+ SMB2_MAGIC,
+ Command,
+ SMBHeader,
+ build_error_response,
+ build_response_header,
+ parse_header,
+ parse_request,
+ split_compound,
+)
+from quicksand_smb._status import STATUS_NOT_SUPPORTED, STATUS_SUCCESS
+
+
+def _build_test_header(
+ command: int = Command.NEGOTIATE,
+ message_id: int = 0,
+ tree_id: int = 0,
+ session_id: int = 0,
+ flags: int = 0,
+ next_command: int = 0,
+) -> bytes:
+ """Build a minimal SMB2 header for testing."""
+ return struct.pack(
+ "<4sHHIHHIIQIIQ16s",
+ SMB2_MAGIC,
+ 64, # StructureSize
+ 1, # CreditCharge
+ 0, # Status
+ command,
+ 1, # CreditRequest
+ flags,
+ next_command,
+ message_id,
+ 0, # Reserved
+ tree_id,
+ session_id,
+ b"\x00" * 16, # Signature
+ )
+
+
+class TestHeaderParsing:
+ def test_parse_negotiate_header(self):
+ data = _build_test_header(command=Command.NEGOTIATE, message_id=42)
+ hdr = parse_header(data)
+ assert hdr.command == Command.NEGOTIATE
+ assert hdr.message_id == 42
+ assert hdr.tree_id == 0
+ assert hdr.session_id == 0
+
+ def test_parse_header_with_tree_and_session(self):
+ data = _build_test_header(tree_id=5, session_id=99)
+ hdr = parse_header(data)
+ assert hdr.tree_id == 5
+ assert hdr.session_id == 99
+
+ def test_parse_request(self):
+ header = _build_test_header()
+ payload = b"\x01\x02\x03\x04"
+ req = parse_request(header + payload)
+ assert req.header.command == Command.NEGOTIATE
+ assert req.payload == payload
+ assert len(req.raw) == SMB2_HEADER_SIZE + 4
+
+ def test_bad_magic_raises(self):
+ data = b"\x00" * 64
+ try:
+ parse_header(data)
+ raise AssertionError("Should have raised ValueError")
+ except ValueError as e:
+ assert "Bad SMB2 magic" in str(e)
+
+
+class TestResponseBuilding:
+ def test_build_response_header_size(self):
+ req_hdr = SMBHeader(
+ credit_charge=1,
+ status=0,
+ command=Command.NEGOTIATE,
+ credit_request=1,
+ flags=0,
+ next_command=0,
+ message_id=0,
+ tree_id=0,
+ session_id=0,
+ )
+ resp = build_response_header(req_hdr, STATUS_SUCCESS, 100)
+ assert len(resp) == SMB2_HEADER_SIZE
+
+ # Check magic
+ assert resp[:4] == SMB2_MAGIC
+
+ # Check server-to-redir flag is set
+ flags = struct.unpack_from("<I", resp, 16)[0]
+ assert flags & 0x01
+
+ def test_build_error_response(self):
+ req_hdr = SMBHeader(
+ credit_charge=1,
+ status=0,
+ command=Command.CREATE,
+ credit_request=1,
+ flags=0,
+ next_command=0,
+ message_id=5,
+ tree_id=1,
+ session_id=1,
+ )
+ resp = build_error_response(req_hdr, STATUS_NOT_SUPPORTED)
+ assert len(resp) == SMB2_HEADER_SIZE + 8 # header + error body
+
+ # Check status in header
+ status = struct.unpack_from("<I", resp, 8)[0]
+ assert status == STATUS_NOT_SUPPORTED
+
+ def test_response_preserves_message_id(self):
+ req_hdr = SMBHeader(
+ credit_charge=1,
+ status=0,
+ command=Command.READ,
+ credit_request=1,
+ flags=0,
+ next_command=0,
+ message_id=42,
+ tree_id=3,
+ session_id=7,
+ )
+ resp = build_response_header(req_hdr, STATUS_SUCCESS, 0)
+ msg_id = struct.unpack_from("<Q", resp, 24)[0]
+ assert msg_id == 42
+
+
+class TestCompoundSplitting:
+ def test_single_message(self):
+ msg = _build_test_header() + b"\x00" * 10
+ parts = split_compound(msg)
+ assert len(parts) == 1
+ assert parts[0] == msg
+
+ def test_two_messages(self):
+ # First message has NextCommand pointing to second
+ msg1_size = 80 # 64 header + 16 payload, 8-byte aligned
+ msg1 = _build_test_header(command=Command.CREATE, next_command=msg1_size)
+ msg1 += b"\x00" * (msg1_size - SMB2_HEADER_SIZE)
+
+ msg2 = _build_test_header(command=Command.CLOSE)
+ msg2 += b"\x00" * 8
+
+ combined = msg1 + msg2
+ parts = split_compound(combined)
+ assert len(parts) == 2
+ assert len(parts[0]) == msg1_size
+ assert parts[1][:4] == SMB2_MAGIC
diff --git a/tests/unit/smb/test_smb_server.py b/tests/unit/smb/test_smb_server.py
new file mode 100644
index 0000000..ae5f514
--- /dev/null
+++ b/tests/unit/smb/test_smb_server.py
@@ -0,0 +1,906 @@
+"""Integration tests for the SMB3 server.
+
+Tests the full SMB3 protocol by piping a real Linux CIFS client through
+the server's stdin/stdout. Uses subprocess to simulate the inetd-style
+invocation that QEMU's guestfwd would use.
+
+These tests verify the server works end-to-end WITHOUT requiring a VM.
+They use a loopback approach: start the SMB server process, connect to
+it via a local TCP bridge, and mount using the kernel CIFS client.
+
+For CI (no root / no mount), we test at the protocol level by replaying
+captured SMB3 packet sequences.
+"""
+
+import json
+import os
+import shutil
+import struct
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+# Ensure the package is importable
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+from quicksand_smb import ShareConfig, SMBConfig, SMBSession, _dispatch
+from quicksand_smb._negotiate import handle_negotiate, handle_session_setup
+from quicksand_smb._protocol import (
+ SMB2_MAGIC,
+ Command,
+ parse_request,
+)
+from quicksand_smb._status import (
+ STATUS_ACCESS_DENIED,
+ STATUS_BAD_NETWORK_NAME,
+ STATUS_END_OF_FILE,
+ STATUS_INVALID_HANDLE,
+ STATUS_NO_MORE_FILES,
+ STATUS_OBJECT_NAME_COLLISION,
+ STATUS_OBJECT_NAME_NOT_FOUND,
+ STATUS_SUCCESS,
+)
+
+
+def _smb_header(
+ command: int,
+ message_id: int = 0,
+ tree_id: int = 0,
+ session_id: int = 0,
+ flags: int = 0,
+) -> bytes:
+ """Build a raw SMB2 header."""
+ return struct.pack(
+ "<4sHHIHHIIQIIQ16s",
+ SMB2_MAGIC,
+ 64,
+ 1,
+ 0,
+ command,
+ 1,
+ flags,
+ 0,
+ message_id,
+ 0,
+ tree_id,
+ session_id,
+ b"\x00" * 16,
+ )
+
+
+def _frame(data: bytes) -> bytes:
+ """Add NetBIOS framing (4-byte big-endian length prefix)."""
+ return struct.pack(">I", len(data)) + data
+
+
+def _read_response(data: bytes, offset: int = 0) -> tuple[bytes, int]:
+ """Read a NetBIOS-framed response from a buffer. Returns (payload, new_offset)."""
+ length = struct.unpack_from(">I", data, offset)[0]
+ payload = data[offset + 4 : offset + 4 + length]
+ return payload, offset + 4 + length
+
+
+def _get_status(response: bytes) -> int:
+ """Extract NTSTATUS from an SMB2 response."""
+ return struct.unpack_from("<I", response, 8)[0]
+
+
+class TestNegotiate:
+ """Test NEGOTIATE + SESSION_SETUP flow."""
+
+ def test_negotiate_selects_smb3(self):
+ """Server should select SMB 3.0 dialect."""
+ # Build NEGOTIATE request with dialects 2.02, 2.10, 3.0.0
+ dialects = struct.pack("<HHH", 0x0202, 0x0210, 0x0300)
+ body = struct.pack(
+ "<HHHHI16sIHH",
+ 36, # StructureSize
+ 3, # DialectCount
+ 0, # SecurityMode
+ 0, # Reserved
+ 0, # Capabilities
+ os.urandom(16), # ClientGuid
+ 0,
+ 0,
+ 0, # NegotiateContext fields
+ )
+ # Pad to offset 36 for dialects
+ body = body[:36] + dialects
+
+ header = _smb_header(Command.NEGOTIATE)
+ req = parse_request(header + body)
+
+ response, state = handle_negotiate(req)
+ assert _get_status(response) == STATUS_SUCCESS
+ assert state.dialect == 0x0300
+
+ def test_session_setup_accepts_guest(self):
+ """SESSION_SETUP should accept any auth and return IS_GUEST."""
+ body = struct.pack(
+ "<HBBIIHH",
+ 25, # StructureSize
+ 0, # Flags
+ 0, # SecurityMode
+ 0, # Capabilities
+ 0, # Channel
+ 72, # SecurityBufferOffset
+ 0, # SecurityBufferLength
+ )
+ # Pad to match structure
+ body = body.ljust(24, b"\x00")
+
+ header = _smb_header(Command.SESSION_SETUP)
+ req = parse_request(header + body)
+
+ response = handle_session_setup(req, session_id=1)
+ assert _get_status(response) == STATUS_SUCCESS
+
+ # Check SessionFlags has IS_GUEST (0x0001)
+ session_flags = struct.unpack_from("<H", response, 64 + 2)[0]
+ assert session_flags & 0x0001
+
+
+class TestTreeConnect:
+ """Test TREE_CONNECT with shares."""
+
+ def _make_session(self, share_dir: Path) -> SMBSession:
+ config = SMBConfig(
+ shares={
+ "TESTSHARE": ShareConfig(host_path=str(share_dir), readonly=False),
+ }
+ )
+ return SMBSession(config=config)
+
+ def test_tree_connect_valid_share(self, tmp_path):
+ session = self._make_session(tmp_path)
+ session.session_id = 1
+
+ path = "\\\\10.0.2.100\\TESTSHARE".encode("utf-16-le")
+ body = struct.pack("<HHHH", 9, 0, 64 + 8, len(path))
+ body = body.ljust(8, b"\x00") + path
+
+ header = _smb_header(Command.TREE_CONNECT, session_id=1)
+ req = parse_request(header + body)
+
+ response = _dispatch(session, req)
+ assert _get_status(response) == STATUS_SUCCESS
+ assert 1 in session.tree_map
+
+ def test_tree_connect_bad_share(self, tmp_path):
+ session = self._make_session(tmp_path)
+ session.session_id = 1
+
+ path = "\\\\10.0.2.100\\NONEXISTENT".encode("utf-16-le")
+ body = struct.pack("<HHHH", 9, 0, 64 + 8, len(path))
+ body = body.ljust(8, b"\x00") + path
+
+ header = _smb_header(Command.TREE_CONNECT, session_id=1)
+ req = parse_request(header + body)
+
+ response = _dispatch(session, req)
+ assert _get_status(response) == STATUS_BAD_NETWORK_NAME
+
+
+class TestFileOperations:
+ """Test CREATE, READ, WRITE, CLOSE operations."""
+
+ def _setup_session(self, share_dir: Path, readonly: bool = False) -> SMBSession:
+ config = SMBConfig(
+ shares={
+ "SHARE": ShareConfig(host_path=str(share_dir), readonly=readonly),
+ }
+ )
+ session = SMBSession(config=config)
+ session.session_id = 1
+ session.tree_map[1] = "SHARE"
+ session.next_tree_id = 2
+ return session
+
+ def _create_file(
+ self,
+ session: SMBSession,
+ filename: str,
+ tree_id: int = 1,
+ disposition: int = 0x03,
+ options: int = 0,
+ access: int = 0x12019F,
+ ) -> tuple[bytes, bytes]:
+ """Send CREATE request, return (response, file_id or empty)."""
+ name_bytes = filename.encode("utf-16-le")
+ name_offset = 64 + 56 # header + fixed body
+
+ body = struct.pack(
+ "<HBBIqQIIIIIHHII",
+ 57, # StructureSize
+ 0, # SecurityFlags
+ 0, # RequestedOplockLevel
+ 0, # ImpersonationLevel
+ 0, # SmbCreateFlags
+ 0, # Reserved
+ access, # DesiredAccess
+ 0x80, # FileAttributes (NORMAL)
+ 0x07, # ShareAccess (all)
+ disposition,
+ options,
+ name_offset,
+ len(name_bytes),
+ 0,
+ 0, # CreateContexts
+ )
+ body += name_bytes
+
+ header = _smb_header(Command.CREATE, tree_id=tree_id, session_id=1)
+ req = parse_request(header + body)
+ response = _dispatch(session, req)
+
+ status = _get_status(response)
+ if status == STATUS_SUCCESS:
+ # FileId is at offset 64+66 in response (bytes 66-82 of body)
+ file_id = response[64 + 64 : 64 + 80]
+ return response, file_id
+ return response, b""
+
+ def _close_file(self, session: SMBSession, file_id: bytes) -> bytes:
+ body = struct.pack("<HH4x", 24, 0) + file_id
+ header = _smb_header(Command.CLOSE, tree_id=1, session_id=1)
+ req = parse_request(header + body)
+ return _dispatch(session, req)
+
+ def _read_file(
+ self, session: SMBSession, file_id: bytes, length: int, offset: int = 0
+ ) -> bytes:
+ body = struct.pack(
+ "<HBBIQ16sIIIHH",
+ 49, # StructureSize
+ 0, # Padding
+ 0, # Flags
+ length,
+ offset,
+ file_id,
+ 0, # MinimumCount
+ 0, # Channel
+ 0, # RemainingBytes
+ 0,
+ 0, # ReadChannelInfo
+ )
+ header = _smb_header(Command.READ, tree_id=1, session_id=1)
+ req = parse_request(header + body)
+ return _dispatch(session, req)
+
+ def _write_file(
+ self, session: SMBSession, file_id: bytes, data: bytes, offset: int = 0
+ ) -> bytes:
+ data_offset = 64 + 48 # header + fixed write body
+ body = struct.pack(
+ "<HHIQ16sIIHHI",
+ 49, # StructureSize
+ data_offset, # DataOffset
+ len(data),
+ offset,
+ file_id,
+ 0, # Channel
+ 0, # RemainingBytes
+ 0,
+ 0, # WriteChannelInfo
+ 0, # Flags
+ )
+ body += data
+ header = _smb_header(Command.WRITE, tree_id=1, session_id=1)
+ req = parse_request(header + body)
+ return _dispatch(session, req)
+
+ def test_create_existing_file(self, tmp_path):
+ (tmp_path / "hello.txt").write_text("world")
+ session = self._setup_session(tmp_path)
+
+ response, file_id = self._create_file(session, "hello.txt", disposition=0x01) # FILE_OPEN
+ assert _get_status(response) == STATUS_SUCCESS
+ assert len(file_id) == 16
+ self._close_file(session, file_id)
+
+ def test_create_new_file(self, tmp_path):
+ session = self._setup_session(tmp_path)
+
+ response, file_id = self._create_file(session, "new.txt", disposition=0x02) # FILE_CREATE
+ assert _get_status(response) == STATUS_SUCCESS
+ assert (tmp_path / "new.txt").exists()
+ self._close_file(session, file_id)
+
+ def test_create_nonexistent_fails(self, tmp_path):
+ session = self._setup_session(tmp_path)
+
+ response, _ = self._create_file(session, "nope.txt", disposition=0x01) # FILE_OPEN
+ assert _get_status(response) == STATUS_OBJECT_NAME_NOT_FOUND
+
+ def test_create_duplicate_fails(self, tmp_path):
+ (tmp_path / "existing.txt").write_text("data")
+ session = self._setup_session(tmp_path)
+
+ response, _ = self._create_file(session, "existing.txt", disposition=0x02) # FILE_CREATE
+ assert _get_status(response) == STATUS_OBJECT_NAME_COLLISION
+
+ def test_read_file(self, tmp_path):
+ (tmp_path / "data.txt").write_bytes(b"Hello, SMB3!")
+ session = self._setup_session(tmp_path)
+
+ _, file_id = self._create_file(session, "data.txt", disposition=0x01)
+ response = self._read_file(session, file_id, 4096)
+
+ assert _get_status(response) == STATUS_SUCCESS
+ # Data is after header + fixed read response body
+ data_offset_field = struct.unpack_from("<B", response, 64 + 2)[0]
+ data_length = struct.unpack_from("<I", response, 64 + 4)[0]
+ data = response[data_offset_field : data_offset_field + data_length]
+ assert data == b"Hello, SMB3!"
+
+ self._close_file(session, file_id)
+
+ def test_read_past_eof(self, tmp_path):
+ (tmp_path / "small.txt").write_bytes(b"hi")
+ session = self._setup_session(tmp_path)
+
+ _, file_id = self._create_file(session, "small.txt", disposition=0x01)
+ response = self._read_file(session, file_id, 4096, offset=100)
+ assert _get_status(response) == STATUS_END_OF_FILE
+
+ self._close_file(session, file_id)
+
+ def test_write_file(self, tmp_path):
+ session = self._setup_session(tmp_path)
+
+ _, file_id = self._create_file(
+ session,
+ "output.txt",
+ disposition=0x03,
+ access=0x12019F, # GENERIC_READ | GENERIC_WRITE
+ )
+ response = self._write_file(session, file_id, b"Written via SMB3")
+ assert _get_status(response) == STATUS_SUCCESS
+
+ self._close_file(session, file_id)
+ assert (tmp_path / "output.txt").read_bytes() == b"Written via SMB3"
+
+ def test_write_readonly_share_denied(self, tmp_path):
+ session = self._setup_session(tmp_path, readonly=True)
+
+ _, file_id = self._create_file(session, "test.txt", disposition=0x03)
+ if file_id:
+ response = self._write_file(session, file_id, b"should fail")
+ assert _get_status(response) == STATUS_ACCESS_DENIED
+ self._close_file(session, file_id)
+
+ def test_close_invalid_handle(self, tmp_path):
+ session = self._setup_session(tmp_path)
+
+ fake_id = b"\xff" * 16
+ response = self._close_file(session, fake_id)
+ assert _get_status(response) == STATUS_INVALID_HANDLE
+
+ def test_binary_data_roundtrip(self, tmp_path):
+ """Binary data should survive read/write without corruption."""
+ binary_data = bytes(range(256)) * 10 # 2560 bytes of all byte values
+ session = self._setup_session(tmp_path)
+
+ _, file_id = self._create_file(session, "binary.bin", disposition=0x03, access=0x12019F)
+ self._write_file(session, file_id, binary_data)
+ self._close_file(session, file_id)
+
+ # Re-open and read back
+ _, file_id = self._create_file(session, "binary.bin", disposition=0x01)
+ response = self._read_file(session, file_id, 4096)
+ assert _get_status(response) == STATUS_SUCCESS
+
+ data_offset_field = struct.unpack_from("<B", response, 64 + 2)[0]
+ data_length = struct.unpack_from("<I", response, 64 + 4)[0]
+ data = response[data_offset_field : data_offset_field + data_length]
+ assert data == binary_data
+
+ self._close_file(session, file_id)
+
+ def test_large_file_io(self, tmp_path):
+ """Test reading/writing files > 64KB."""
+ large_data = os.urandom(256 * 1024) # 256 KB
+ (tmp_path / "large.bin").write_bytes(large_data)
+
+ session = self._setup_session(tmp_path)
+ _, file_id = self._create_file(session, "large.bin", disposition=0x01)
+
+ # Read in chunks
+ read_data = b""
+ offset = 0
+ chunk_size = 65536
+ while True:
+ response = self._read_file(session, file_id, chunk_size, offset)
+ status = _get_status(response)
+ if status == STATUS_END_OF_FILE:
+ break
+ assert status == STATUS_SUCCESS
+ data_offset_field = struct.unpack_from("<B", response, 64 + 2)[0]
+ data_length = struct.unpack_from("<I", response, 64 + 4)[0]
+ chunk = response[data_offset_field : data_offset_field + data_length]
+ read_data += chunk
+ offset += len(chunk)
+ if len(chunk) < chunk_size:
+ break
+
+ assert read_data == large_data
+ self._close_file(session, file_id)
+
+
+class TestPathTraversal:
+ """Security tests: path traversal must be blocked."""
+
+ def _setup_session(self, share_dir: Path) -> SMBSession:
+ config = SMBConfig(
+ shares={
+ "SHARE": ShareConfig(host_path=str(share_dir)),
+ }
+ )
+ session = SMBSession(config=config)
+ session.session_id = 1
+ session.tree_map[1] = "SHARE"
+ return session
+
+ def _try_create(self, session: SMBSession, filename: str) -> int:
+ name_bytes = filename.encode("utf-16-le")
+ name_offset = 64 + 56
+ body = struct.pack(
+ "<HBBIqQIIIIIHHII",
+ 57,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0x80,
+ 0x80,
+ 0x07,
+ 0x01,
+ 0,
+ name_offset,
+ len(name_bytes),
+ 0,
+ 0,
+ )
+ body += name_bytes
+ header = _smb_header(Command.CREATE, tree_id=1, session_id=1)
+ req = parse_request(header + body)
+ response = _dispatch(session, req)
+ return _get_status(response)
+
+ def test_dotdot_escape(self, tmp_path):
+ share_dir = tmp_path / "share"
+ share_dir.mkdir()
+ (tmp_path / "secret.txt").write_text("secret")
+
+ session = self._setup_session(share_dir)
+ status = self._try_create(session, "..\\secret.txt")
+ assert status == STATUS_ACCESS_DENIED
+
+ def test_dotdot_deep_escape(self, tmp_path):
+ share_dir = tmp_path / "a" / "b" / "share"
+ share_dir.mkdir(parents=True)
+
+ session = self._setup_session(share_dir)
+ status = self._try_create(session, "..\\..\\..\\..\\etc\\passwd")
+ assert status == STATUS_ACCESS_DENIED
+
+ def test_symlink_escape(self, tmp_path):
+ share_dir = tmp_path / "share"
+ share_dir.mkdir()
+ secret = tmp_path / "secret.txt"
+ secret.write_text("secret")
+
+ # Create symlink inside share pointing outside
+ link = share_dir / "escape"
+ link.symlink_to(secret)
+
+ session = self._setup_session(share_dir)
+ status = self._try_create(session, "escape")
+ assert status == STATUS_ACCESS_DENIED
+
+
+class TestDirectoryOperations:
+ """Test QUERY_DIRECTORY (ls) operations."""
+
+ def _setup_session(self, share_dir: Path) -> SMBSession:
+ config = SMBConfig(
+ shares={
+ "SHARE": ShareConfig(host_path=str(share_dir)),
+ }
+ )
+ session = SMBSession(config=config)
+ session.session_id = 1
+ session.tree_map[1] = "SHARE"
+ return session
+
+ def _open_dir(self, session: SMBSession, path: str = "") -> bytes:
+ """Open a directory handle."""
+ name_bytes = path.encode("utf-16-le")
+ name_offset = 64 + 56
+ body = struct.pack(
+ "<HBBIqQIIIIIHHII",
+ 57,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0x80, # DesiredAccess: FILE_READ_ATTRIBUTES
+ 0x10, # FileAttributes: DIRECTORY
+ 0x07, # ShareAccess
+ 0x01, # CreateDisposition: FILE_OPEN
+ 0x01, # CreateOptions: FILE_DIRECTORY_FILE
+ name_offset,
+ len(name_bytes),
+ 0,
+ 0,
+ )
+ body += name_bytes
+ header = _smb_header(Command.CREATE, tree_id=1, session_id=1)
+ req = parse_request(header + body)
+ response = _dispatch(session, req)
+ assert _get_status(response) == STATUS_SUCCESS
+ return response[64 + 64 : 64 + 80] # FileId
+
+ def _query_dir(self, session: SMBSession, file_id: bytes, flags: int = 0) -> bytes:
+ """Send QUERY_DIRECTORY request."""
+ pattern = "*".encode("utf-16-le")
+ name_offset = 64 + 32
+
+ body = struct.pack(
+ "<HBBI16sHHI",
+ 33, # StructureSize
+ 3, # FileInfoClass: FileBothDirectoryInformation
+ flags,
+ 0, # FileIndex
+ file_id,
+ name_offset,
+ len(pattern),
+ 65536, # OutputBufferLength
+ )
+ body += pattern
+
+ header = _smb_header(Command.QUERY_DIRECTORY, tree_id=1, session_id=1)
+ req = parse_request(header + body)
+ return _dispatch(session, req)
+
+ def _parse_dir_entries(self, response: bytes, info_class: int = 3) -> list[str]:
+ """Parse filenames from a QUERY_DIRECTORY response.
+
+ Supports FILE_BOTH_DIRECTORY_INFORMATION (3) and
+ FILE_ID_BOTH_DIRECTORY_INFORMATION (37).
+ """
+ assert _get_status(response) == STATUS_SUCCESS
+ output_offset = struct.unpack_from("<H", response, 64 + 2)[0]
+ output_length = struct.unpack_from("<I", response, 64 + 4)[0]
+ data = response[output_offset : output_offset + output_length]
+
+ # Fixed header size before FileName
+ if info_class == 3:
+ fname_offset = 94 # FileBothDirectoryInformation
+ elif info_class == 37:
+ fname_offset = 104 # FileIdBothDirectoryInformation
+ elif info_class == 38:
+ fname_offset = 80 # FileIdFullDirectoryInformation
+ else:
+ raise ValueError(f"Unsupported info class {info_class}")
+
+ names: list[str] = []
+ pos = 0
+ while pos < len(data):
+ next_entry_offset = struct.unpack_from("<I", data, pos)[0]
+ fname_len = struct.unpack_from("<I", data, pos + 60)[0]
+ fname_bytes = data[pos + fname_offset : pos + fname_offset + fname_len]
+ names.append(fname_bytes.decode("utf-16-le"))
+ if next_entry_offset == 0:
+ break
+ pos += next_entry_offset
+ return names
+
+ def _query_dir_with_class(
+ self, session: SMBSession, file_id: bytes, info_class: int = 3, flags: int = 0
+ ) -> bytes:
+ """Send QUERY_DIRECTORY with a specific FileInfoClass."""
+ pattern = "*".encode("utf-16-le")
+ name_offset = 64 + 32
+
+ body = struct.pack(
+ "<HBBI16sHHI",
+ 33, # StructureSize
+ info_class,
+ flags,
+ 0, # FileIndex
+ file_id,
+ name_offset,
+ len(pattern),
+ 65536, # OutputBufferLength
+ )
+ body += pattern
+
+ header = _smb_header(Command.QUERY_DIRECTORY, tree_id=1, session_id=1)
+ req = parse_request(header + body)
+ return _dispatch(session, req)
+
+ def test_list_directory(self, tmp_path):
+ (tmp_path / "file1.txt").write_text("a")
+ (tmp_path / "file2.txt").write_text("b")
+ (tmp_path / "subdir").mkdir()
+
+ session = self._setup_session(tmp_path)
+ dir_id = self._open_dir(session)
+
+ response = self._query_dir(session, dir_id)
+ assert _get_status(response) == STATUS_SUCCESS
+
+ # Should contain entries (at least ., .., file1.txt, file2.txt, subdir)
+ output_length = struct.unpack_from("<I", response, 64 + 4)[0]
+ assert output_length > 0
+
+ def test_filenames_correct_class3(self, tmp_path):
+ """Verify filenames are correctly encoded in FileBothDirectoryInformation."""
+ (tmp_path / "README.md").write_text("hello")
+ (tmp_path / "LICENSE").write_text("MIT")
+ (tmp_path / ".github").mkdir()
+
+ session = self._setup_session(tmp_path)
+ dir_id = self._open_dir(session)
+
+ # Collect all entries across multiple responses
+ all_names: list[str] = []
+ while True:
+ response = self._query_dir(session, dir_id)
+ if _get_status(response) == STATUS_NO_MORE_FILES:
+ break
+ all_names.extend(self._parse_dir_entries(response, info_class=3))
+
+ assert "." in all_names
+ assert ".." in all_names
+ assert "README.md" in all_names
+ assert "LICENSE" in all_names
+ assert ".github" in all_names
+
+ def test_filenames_correct_class37(self, tmp_path):
+ """Verify filenames are correctly encoded in FileIdBothDirectoryInformation."""
+ (tmp_path / "README.md").write_text("hello")
+ (tmp_path / "LICENSE").write_text("MIT")
+ (tmp_path / ".github").mkdir()
+
+ session = self._setup_session(tmp_path)
+ dir_id = self._open_dir(session)
+
+ # Collect all entries using info class 37
+ all_names: list[str] = []
+ while True:
+ response = self._query_dir_with_class(session, dir_id, info_class=37)
+ if _get_status(response) == STATUS_NO_MORE_FILES:
+ break
+ all_names.extend(self._parse_dir_entries(response, info_class=37))
+
+ assert "." in all_names
+ assert ".." in all_names
+ assert "README.md" in all_names
+ assert "LICENSE" in all_names
+ assert ".github" in all_names
+
+ def test_filenames_correct_class38(self, tmp_path):
+ """Verify filenames are correctly encoded in FileIdFullDirectoryInformation.
+
+ This is the info class the Linux kernel SMB3 client actually uses for readdir.
+ Regression: a missing 4-byte Reserved field before FileId caused filenames
+ to lose their first 2 characters (e.g. README.md -> ADME.md).
+ """
+ (tmp_path / "README.md").write_text("hello")
+ (tmp_path / "LICENSE").write_text("MIT")
+ (tmp_path / ".github").mkdir()
+
+ session = self._setup_session(tmp_path)
+ dir_id = self._open_dir(session)
+
+ # Collect all entries using info class 38
+ all_names: list[str] = []
+ while True:
+ response = self._query_dir_with_class(session, dir_id, info_class=38)
+ if _get_status(response) == STATUS_NO_MORE_FILES:
+ break
+ all_names.extend(self._parse_dir_entries(response, info_class=38))
+
+ assert "." in all_names
+ assert ".." in all_names
+ assert "README.md" in all_names
+ assert "LICENSE" in all_names
+ assert ".github" in all_names
+
+ def test_empty_directory(self, tmp_path):
+ session = self._setup_session(tmp_path)
+ dir_id = self._open_dir(session)
+
+ # First call should return . and ..
+ response = self._query_dir(session, dir_id)
+ assert _get_status(response) == STATUS_SUCCESS
+
+ # Eventually should return NO_MORE_FILES
+ for _ in range(10):
+ response = self._query_dir(session, dir_id)
+ if _get_status(response) == STATUS_NO_MORE_FILES:
+ break
+ assert _get_status(response) == STATUS_NO_MORE_FILES
+
+ def test_restart_scans(self, tmp_path):
+ (tmp_path / "file.txt").write_text("data")
+ session = self._setup_session(tmp_path)
+ dir_id = self._open_dir(session)
+
+ # Read all entries
+ self._query_dir(session, dir_id)
+ while _get_status(self._query_dir(session, dir_id)) != STATUS_NO_MORE_FILES:
+ pass
+
+ # Restart and read again
+ response = self._query_dir(session, dir_id, flags=0x01) # SMB2_RESTART_SCANS
+ assert _get_status(response) == STATUS_SUCCESS
+
+
+class TestSubprocessIntegration:
+ """Test the server as a subprocess (simulating QEMU guestfwd invocation)."""
+
+ def test_server_starts_and_handles_negotiate(self, tmp_path):
+ """Start server as subprocess, send NEGOTIATE, verify response."""
+ share_dir = tmp_path / "share"
+ share_dir.mkdir()
+ (share_dir / "test.txt").write_text("hello")
+
+ config = {"shares": {"TEST": {"host_path": str(share_dir), "readonly": False}}}
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(config))
+
+ # Build NEGOTIATE request
+ dialects = struct.pack("<H", 0x0300)
+ negotiate_body = struct.pack("<HHHHI16sIHH", 36, 1, 0, 0, 0, os.urandom(16), 0, 0, 0)
+ negotiate_body = negotiate_body[:36] + dialects
+ negotiate_header = _smb_header(Command.NEGOTIATE)
+ negotiate_msg = negotiate_header + negotiate_body
+ framed_input = _frame(negotiate_msg)
+
+ proc = subprocess.run(
+ [sys.executable, "-m", "quicksand_smb", "--config", str(config_path)],
+ input=framed_input,
+ capture_output=True,
+ timeout=5,
+ )
+
+ # Server should have written a response
+ assert len(proc.stdout) > 4, f"No response from server. stderr: {proc.stderr.decode()}"
+
+ # Parse the response
+ resp_payload, _ = _read_response(proc.stdout)
+ assert resp_payload[:4] == SMB2_MAGIC
+ assert _get_status(resp_payload) == STATUS_SUCCESS
+
+ def test_no_tcp_port_opened(self, tmp_path):
+ """Server must not open any TCP ports (guestfwd uses stdin/stdout)."""
+ share_dir = tmp_path / "share"
+ share_dir.mkdir()
+
+ config = {"shares": {"TEST": {"host_path": str(share_dir), "readonly": False}}}
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(config))
+
+ # Send a NEGOTIATE so the server starts processing
+ dialects = struct.pack("<H", 0x0300)
+ negotiate_body = struct.pack("<HHHHI16sIHH", 36, 1, 0, 0, 0, os.urandom(16), 0, 0, 0)
+ negotiate_body = negotiate_body[:36] + dialects
+ negotiate_header = _smb_header(Command.NEGOTIATE)
+ framed_input = _frame(negotiate_header + negotiate_body)
+
+ if not shutil.which("lsof"):
+ pytest.skip("lsof not available")
+
+ proc = subprocess.Popen(
+ [sys.executable, "-m", "quicksand_smb", "--config", str(config_path)],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ assert proc.stdin is not None
+ try:
+ proc.stdin.write(framed_input)
+ proc.stdin.flush()
+ time.sleep(0.2)
+
+ lsof = subprocess.run(
+ ["lsof", "-a", "-i", "-P", "-n", "-p", str(proc.pid)],
+ capture_output=True,
+ text=True,
+ timeout=3,
+ )
+ listening = [
+ line for line in lsof.stdout.strip().split("\n") if line and "LISTEN" in line
+ ]
+ assert not listening, f"Server opened TCP ports: {listening}"
+ finally:
+ proc.stdin.close()
+ proc.wait(timeout=3)
+
+
+class TestDynamicConfig:
+ """Test dynamic share configuration changes."""
+
+ def test_dynamic_share_addition(self, tmp_path):
+ """Shares added after session creation should be accessible."""
+ share1 = tmp_path / "share1"
+ share1.mkdir()
+ (share1 / "file1.txt").write_text("from share1")
+
+ share2 = tmp_path / "share2"
+ share2.mkdir()
+ (share2 / "file2.txt").write_text("from share2")
+
+ config = SMBConfig(shares={"SHARE1": ShareConfig(host_path=str(share1))})
+ session = SMBSession(config=config)
+ session.session_id = 1
+ session.tree_map[1] = "SHARE1"
+ session.next_tree_id = 2
+
+ # Access first share
+ name_bytes = "file1.txt".encode("utf-16-le")
+ name_offset = 64 + 56
+ body = struct.pack(
+ "<HBBIqQIIIIIHHII",
+ 57,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0x12019F,
+ 0x80,
+ 0x07,
+ 0x01,
+ 0,
+ name_offset,
+ len(name_bytes),
+ 0,
+ 0,
+ )
+ body += name_bytes
+ header = _smb_header(Command.CREATE, tree_id=1, session_id=1)
+ response = _dispatch(session, parse_request(header + body))
+ assert _get_status(response) == STATUS_SUCCESS
+ file_id = response[64 + 64 : 64 + 80]
+ # Close
+ close_body = struct.pack("<HH4x", 24, 0) + file_id
+ close_header = _smb_header(Command.CLOSE, tree_id=1, session_id=1)
+ _dispatch(session, parse_request(close_header + close_body))
+
+ # Dynamically add second share
+ session.config.shares["SHARE2"] = ShareConfig(host_path=str(share2))
+ session.tree_map[2] = "SHARE2"
+
+ # Access second share
+ name_bytes = "file2.txt".encode("utf-16-le")
+ body = struct.pack(
+ "<HBBIqQIIIIIHHII",
+ 57,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0x12019F,
+ 0x80,
+ 0x07,
+ 0x01,
+ 0,
+ name_offset,
+ len(name_bytes),
+ 0,
+ 0,
+ )
+ body += name_bytes
+ header = _smb_header(Command.CREATE, tree_id=2, session_id=1)
+ response = _dispatch(session, parse_request(header + body))
+ assert _get_status(response) == STATUS_SUCCESS
diff --git a/tests/unit/test_checkpoint_ops.py b/tests/unit/test_checkpoint_ops.py
new file mode 100644
index 0000000..9547b8a
--- /dev/null
+++ b/tests/unit/test_checkpoint_ops.py
@@ -0,0 +1,429 @@
+"""Unit tests for checkpoint_ops module."""
+
+from __future__ import annotations
+
+import json
+import tarfile
+from pathlib import Path
+from typing import ClassVar
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from quicksand_core._types import (
+ FilePatterns,
+ ResolvedAccelerator,
+ ResolvedImage,
+ SandboxConfig,
+ SaveManifest,
+)
+from quicksand_core.qemu.save import SaveWriter
+
+
+class TestCreateSave:
+ """Tests for SaveWriter."""
+
+ def test_creates_save_directory(self, tmp_dir):
+ """Test creating a save directory."""
+ # Set up fake files
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.write_bytes(b"overlay-data")
+
+ manifest = SaveManifest(
+ version=5,
+ config=SandboxConfig(image="test"),
+ )
+
+ writer = SaveWriter("my-save", workspace=tmp_dir)
+ writer.write(overlay_chain=[overlay], manifest=manifest)
+
+ save_path = tmp_dir / "my-save"
+ assert save_path.is_dir()
+ assert save_path.exists()
+
+ # Verify directory contents
+ manifest_path = save_path / FilePatterns.MANIFEST
+ assert manifest_path.exists()
+ overlay_path = save_path / "overlays" / "0.qcow2"
+ assert overlay_path.exists()
+
+ # Check manifest
+ manifest_data = json.loads(manifest_path.read_text())
+ assert manifest_data["config"]["image"] == "test"
+
+ def test_save_path_is_directory(self, tmp_dir):
+ """Test that save creates a directory at the given path."""
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.write_bytes(b"data")
+
+ manifest = SaveManifest(
+ version=5,
+ config=SandboxConfig(image="test"),
+ )
+
+ writer = SaveWriter("my-save", workspace=tmp_dir)
+ writer.write(overlay_chain=[overlay], manifest=manifest)
+
+ save_path = tmp_dir / "my-save"
+ assert save_path == tmp_dir / "my-save"
+ assert save_path.is_dir()
+
+ def test_overwrites_existing_save(self, tmp_dir):
+ """Test that SaveWriter atomically replaces an existing save."""
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.write_bytes(b"data")
+
+ existing = tmp_dir / "my-save"
+ existing.mkdir()
+ (existing / "old-file.txt").write_text("should be replaced")
+
+ manifest = SaveManifest(
+ version=5,
+ config=SandboxConfig(image="test"),
+ )
+
+ writer = SaveWriter("my-save", workspace=tmp_dir)
+ writer.write(overlay_chain=[overlay], manifest=manifest)
+
+ assert existing.is_dir()
+ assert not (existing / "old-file.txt").exists()
+
+ def test_does_not_call_graceful_shutdown(self, tmp_dir):
+ """Test that create does not perform graceful shutdown (caller's responsibility)."""
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.write_bytes(b"data")
+
+ manifest = SaveManifest(
+ version=5,
+ config=SandboxConfig(image="test"),
+ )
+
+ # Should succeed without any shutdown machinery
+ writer = SaveWriter("cp", workspace=tmp_dir)
+ writer.write(overlay_chain=[overlay], manifest=manifest)
+ save_path = tmp_dir / "cp"
+ assert save_path.exists()
+
+
+class TestLegacyTarSupport:
+ """Tests that uncompressed .tar saves (pre-gzip) can still be read."""
+
+ def test_load_manifest_from_legacy_uncompressed_tar(self, tmp_dir):
+ """load_manifest can read an uncompressed .tar file (legacy format)."""
+ # Legacy tar support is gone -- saves are now directories only.
+ # This test verifies that the ImageResolver rejects tar files
+ # with a clear error message.
+ from quicksand_core.qemu.image_resolver import ImageResolver
+
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.write_bytes(b"overlay-data")
+
+ # Create an uncompressed .tar manually (simulating legacy format)
+ import io
+
+ legacy_tar = tmp_dir / "legacy.tar"
+ manifest = {
+ "version": 5,
+ "config": {"image": "ubuntu"},
+ }
+ manifest_json = json.dumps(manifest).encode()
+
+ with tarfile.open(legacy_tar, "w") as tar:
+ info = tarfile.TarInfo(name="manifest.json")
+ info.size = len(manifest_json)
+ tar.addfile(info, io.BytesIO(manifest_json))
+ tar.add(overlay, arcname="overlays/0.qcow2")
+
+ # Tar files are no longer supported -- should fail to resolve
+ with pytest.raises(RuntimeError, match="Tar save files are no longer supported"):
+ ImageResolver().resolve(str(legacy_tar))
+
+
+class TestHotSave:
+ """Tests for _SaveMixin._hot_save() -- QMP pivot, no rebase."""
+
+ def _make_mock_sandbox(self, tmp_dir: Path):
+ """Create a minimal _SaveMixin sandbox for hot-save testing."""
+ from quicksand_core.sandbox._saves import _SaveMixin
+
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.write_bytes(b"overlay-data")
+ image = tmp_dir / "image.qcow2"
+ image.write_bytes(b"base-data")
+
+ class _MockSandbox(_SaveMixin):
+ config = SandboxConfig(image="ubuntu")
+ _smb_server = None
+ _progress_callback = None
+ _save_name = None
+ _workspace = None
+ _dynamic_mounts: ClassVar[list] = []
+
+ def __init__(self) -> None:
+ from quicksand_core.host import Accelerator
+
+ self._is_running = True
+ self._image = ResolvedImage(
+ name="ubuntu",
+ chain=[image],
+ )
+ self._accel = ResolvedAccelerator(
+ accel=Accelerator.HVF,
+ )
+ self._overlay_path = overlay
+ self._temp_dir = tmp_dir
+ self._agent_client = None
+ self._agent_port = None
+ self._agent_token = None
+ self._qmp_client = AsyncMock()
+ self._qmp_port = 12345
+ self._qmp_checkpoints: list[str] = []
+ self._vnc_port = None
+ self._overlay_manager = MagicMock()
+ self._process_manager = MagicMock()
+ self._runtime_info = None
+
+ @property
+ def is_running(self) -> bool:
+ return self._is_running
+
+ async def _graceful_shutdown(self) -> None:
+ self._is_running = False
+
+ async def _send_request(self, method, params, timeout=30):
+ raise NotImplementedError
+
+ async def _mount_shares(self):
+ raise NotImplementedError
+
+ async def _cleanup_mounts(self):
+ raise NotImplementedError
+
+ async def execute(
+ self,
+ command,
+ timeout=30,
+ cwd=None,
+ shell="",
+ on_stdout=None,
+ on_stderr=None,
+ exclusive=False,
+ ):
+ return MagicMock(stdout="", stderr="", exit_code=0)
+
+ return _MockSandbox(), overlay, image
+
+ @pytest.mark.asyncio
+ async def test_qmp_snapshot_called(self, tmp_dir):
+ """save() calls blockdev-snapshot-sync via QMP."""
+ sb, overlay, _image = self._make_mock_sandbox(tmp_dir)
+ sb._overlay_manager.get_overlay_chain.return_value = [overlay]
+
+ with patch("quicksand_core.qemu.save.SaveWriter") as MockWriter:
+ MockWriter.return_value.write.return_value = MagicMock()
+ await sb.save("cp", workspace=tmp_dir)
+
+ calls = sb._qmp_client.execute.call_args_list
+ snapshot_calls = [c for c in calls if c[0][0] == "blockdev-snapshot-sync"]
+ assert len(snapshot_calls) == 1
+
+ @pytest.mark.asyncio
+ async def test_flush_called_before_snapshot(self, tmp_dir):
+ """save() flushes QEMU block layer before blockdev-snapshot-sync."""
+ sb, overlay, _image = self._make_mock_sandbox(tmp_dir)
+ sb._overlay_manager.get_overlay_chain.return_value = [overlay]
+
+ with patch("quicksand_core.qemu.save.SaveWriter") as MockWriter:
+ MockWriter.return_value.write.return_value = MagicMock()
+ await sb.save("cp", workspace=tmp_dir)
+
+ calls = sb._qmp_client.execute.call_args_list
+ call_strs = [str(c) for c in calls]
+ flush_idx = next(i for i, c in enumerate(call_strs) if "flush" in c)
+ snapshot_idx = next(i for i, c in enumerate(call_strs) if "blockdev-snapshot-sync" in c)
+ assert flush_idx < snapshot_idx
+
+ @pytest.mark.asyncio
+ async def test_snapshot_overlay_chain_contains_original(self, tmp_dir):
+ """SaveWriter.write receives overlay_chain containing the frozen overlay."""
+ sb, overlay, _image = self._make_mock_sandbox(tmp_dir)
+ sb._overlay_manager.get_overlay_chain.return_value = [overlay]
+
+ with patch("quicksand_core.qemu.save.SaveWriter") as MockWriter:
+ MockWriter.return_value.write.return_value = MagicMock()
+ await sb.save("cp", workspace=tmp_dir)
+ passed_chain = MockWriter.return_value.write.call_args.kwargs["overlay_chain"]
+
+ assert passed_chain == [overlay]
+
+ @pytest.mark.asyncio
+ async def test_disk_paths_updated_after_save(self, tmp_dir):
+ """After save, VM overlay_path points to the new overlay file."""
+ sb, overlay, _image = self._make_mock_sandbox(tmp_dir)
+ sb._overlay_manager.get_overlay_chain.return_value = [overlay]
+
+ with patch("quicksand_core.qemu.save.SaveWriter") as MockWriter:
+ MockWriter.return_value.write.return_value = MagicMock()
+ await sb.save("cp", workspace=tmp_dir)
+
+ assert sb._overlay_path != overlay # pivoted to new overlay
+
+ @pytest.mark.asyncio
+ async def test_get_overlay_chain_called(self, tmp_dir):
+ """save() walks the overlay chain via get_overlay_chain."""
+ sb, overlay, image = self._make_mock_sandbox(tmp_dir)
+ sb._overlay_manager.get_overlay_chain.return_value = [overlay]
+
+ with patch("quicksand_core.qemu.save.SaveWriter") as MockWriter:
+ MockWriter.return_value.write.return_value = MagicMock()
+ await sb.save("cp", workspace=tmp_dir)
+
+ sb._overlay_manager.get_overlay_chain.assert_called_once_with(overlay, image)
+
+ @pytest.mark.asyncio
+ async def test_save_raises_with_checkpoints_by_default(self, tmp_dir):
+ """save() raises RuntimeError if checkpoint tags exist and delete_checkpoints=False."""
+ sb, _overlay, _image = self._make_mock_sandbox(tmp_dir)
+ sb._qmp_checkpoints = ["v1", "v2"]
+
+ with pytest.raises(RuntimeError, match="active checkpoint snapshots"):
+ await sb.save("cp", workspace=tmp_dir)
+
+ @pytest.mark.asyncio
+ async def test_save_deletes_checkpoints_when_opted_in(self, tmp_dir):
+ """save(delete_checkpoints=True) calls delvm for each tag before freezing."""
+ sb, overlay, _image = self._make_mock_sandbox(tmp_dir)
+ sb._qmp_checkpoints = ["v1", "v2"]
+ sb._overlay_manager.get_overlay_chain.return_value = [overlay]
+
+ with patch("quicksand_core.qemu.save.SaveWriter") as MockWriter:
+ MockWriter.return_value.write.return_value = MagicMock()
+ await sb.save("cp", workspace=tmp_dir, delete_checkpoints=True)
+
+ calls = [str(c) for c in sb._qmp_client.execute.call_args_list]
+ assert any("delvm v1" in c for c in calls)
+ assert any("delvm v2" in c for c in calls)
+ assert sb._qmp_checkpoints == []
+
+
+class TestCheckpointRevert:
+ """Tests for checkpoint() and revert()."""
+
+ def _make_mock_sandbox(self, tmp_dir: Path):
+ from quicksand_core.sandbox._checkpoints import _CheckpointMixin
+
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.write_bytes(b"overlay-data")
+ image = tmp_dir / "image.qcow2"
+ image.write_bytes(b"base-data")
+
+ class _MockSandbox(_CheckpointMixin):
+ config = SandboxConfig(image="ubuntu")
+ _smb_server = None
+ _progress_callback = None
+ _save_name = None
+ _workspace = None
+ _dynamic_mounts: ClassVar[list] = []
+
+ def __init__(self) -> None:
+ from quicksand_core.host import Accelerator
+
+ self._is_running = True
+ self._image = ResolvedImage(
+ name="ubuntu",
+ chain=[image],
+ )
+ self._accel = ResolvedAccelerator(
+ accel=Accelerator.HVF,
+ )
+ self._overlay_path = overlay
+ self._temp_dir = tmp_dir
+ self._agent_client = None
+ self._agent_port = None
+ self._agent_token = None
+ self._qmp_client = AsyncMock()
+ self._qmp_port = 12345
+ self._qmp_checkpoints: list[str] = []
+ self._vnc_port = None
+ self._overlay_manager = MagicMock()
+ self._process_manager = MagicMock()
+ self._runtime_info = None
+
+ @property
+ def is_running(self) -> bool:
+ return self._is_running
+
+ async def _graceful_shutdown(self) -> None:
+ self._is_running = False
+
+ async def _send_request(self, method, params, timeout=30):
+ raise NotImplementedError
+
+ async def _mount_shares(self):
+ raise NotImplementedError
+
+ async def _cleanup_mounts(self):
+ raise NotImplementedError
+
+ async def execute(
+ self,
+ command,
+ timeout=30,
+ cwd=None,
+ shell="",
+ on_stdout=None,
+ on_stderr=None,
+ exclusive=False,
+ ):
+ return MagicMock(stdout="", stderr="", exit_code=0)
+
+ return _MockSandbox()
+
+ @pytest.mark.asyncio
+ async def test_checkpoint_tracks_tag(self, tmp_dir):
+ """checkpoint() appends the tag to checkpoints."""
+ sb = self._make_mock_sandbox(tmp_dir)
+ await sb.checkpoint("before-install")
+ assert "before-install" in sb._qmp_checkpoints
+
+ @pytest.mark.asyncio
+ async def test_checkpoint_no_duplicates(self, tmp_dir):
+ """checkpoint() with the same tag doesn't duplicate it."""
+ sb = self._make_mock_sandbox(tmp_dir)
+ await sb.checkpoint("v1")
+ await sb.checkpoint("v1")
+ assert sb._qmp_checkpoints.count("v1") == 1
+
+ @pytest.mark.asyncio
+ async def test_checkpoint_calls_qmp(self, tmp_dir):
+ """checkpoint() sends human-monitor-command savevm <tag> via QMP."""
+ sb = self._make_mock_sandbox(tmp_dir)
+ await sb.checkpoint("v1")
+ call_kwargs = sb._qmp_client.execute.call_args
+ assert call_kwargs[0][0] == "human-monitor-command"
+ assert call_kwargs[1]["command-line"] == "savevm v1"
+
+ @pytest.mark.asyncio
+ async def test_revert_calls_qmp(self, tmp_dir):
+ """revert() sends human-monitor-command loadvm <tag> via QMP."""
+ sb = self._make_mock_sandbox(tmp_dir)
+ await sb.checkpoint("v1")
+ sb._qmp_client.reset_mock()
+ await sb.revert("v1")
+ call_kwargs = sb._qmp_client.execute.call_args
+ assert call_kwargs[0][0] == "human-monitor-command"
+ assert call_kwargs[1]["command-line"] == "loadvm v1"
+
+ @pytest.mark.asyncio
+ async def test_revert_unknown_tag_raises(self, tmp_dir):
+ """revert() raises ValueError for an untracked tag."""
+ sb = self._make_mock_sandbox(tmp_dir)
+ with pytest.raises(ValueError, match="No checkpoint 'v1'"):
+ await sb.revert("v1")
+
+ @pytest.mark.asyncio
+ async def test_revert_not_running_raises(self, tmp_dir):
+ """revert() raises RuntimeError if sandbox is not running."""
+ sb = self._make_mock_sandbox(tmp_dir)
+ sb._is_running = False
+ with pytest.raises(RuntimeError, match="non-running"):
+ await sb.revert("v1")
diff --git a/tests/unit/test_core_checkpoint.py b/tests/unit/test_core_checkpoint.py
new file mode 100644
index 0000000..ad39cd1
--- /dev/null
+++ b/tests/unit/test_core_checkpoint.py
@@ -0,0 +1,209 @@
+"""Unit tests for save module."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from quicksand_core._types import SandboxConfig, SaveManifest
+from quicksand_core.qemu.image_resolver import SAVE_VERSION, ImageResolver
+from quicksand_core.utils import compute_file_sha256
+
+
+class TestSaveManifest:
+ """Tests for SaveManifest model."""
+
+ def test_create_save_manifest(self, tmp_dir):
+ """Test creating SaveManifest."""
+ config = SandboxConfig(image="test")
+ manifest = SaveManifest(
+ version=6,
+ config=config,
+ arch="x86_64",
+ )
+ assert manifest.version == 6
+ assert manifest.config.image == "test"
+ assert manifest.arch == "x86_64"
+
+ def test_save_manifest_default_arch(self):
+ """Test that SaveManifest arch defaults to None."""
+ config = SandboxConfig(image="test")
+ manifest = SaveManifest(version=6, config=config)
+ assert manifest.arch is None
+
+
+class TestComputeFileSha256:
+ """Tests for compute_file_sha256 function."""
+
+ def test_compute_hash(self, tmp_dir):
+ """Test computing file hash."""
+ test_file = tmp_dir / "test.txt"
+ test_file.write_text("hello world")
+
+ hash_result = compute_file_sha256(test_file)
+
+ # Known SHA-256 of "hello world"
+ assert hash_result == "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
+
+ def test_compute_hash_binary(self, tmp_dir):
+ """Test computing hash of binary file."""
+ test_file = tmp_dir / "test.bin"
+ test_file.write_bytes(b"\x00\x01\x02\x03")
+
+ hash_result = compute_file_sha256(test_file)
+
+ # Should return valid hex string
+ assert len(hash_result) == 64
+ assert all(c in "0123456789abcdef" for c in hash_result)
+
+
+class TestLoadManifest:
+ """Tests for loading manifest from save directories."""
+
+ def _create_save_dir(self, tmp_dir, manifest_data, overlay_content=b"fake overlay"):
+ """Helper to create a save directory structure."""
+ save_dir = tmp_dir / "test-save"
+ save_dir.mkdir(exist_ok=True)
+ (save_dir / "manifest.json").write_text(json.dumps(manifest_data))
+ overlays_dir = save_dir / "overlays"
+ overlays_dir.mkdir(exist_ok=True)
+ (overlays_dir / "0.qcow2").write_bytes(overlay_content)
+ return save_dir
+
+ def test_load_valid_manifest(self, tmp_dir):
+ """Test loading a valid manifest from save directory."""
+ manifest_data = {
+ "version": 6,
+ "config": {"image": "ubuntu"},
+ }
+ save_dir = self._create_save_dir(tmp_dir, manifest_data)
+
+ result = SaveManifest.model_validate_json((save_dir / "manifest.json").read_text())
+
+ assert result.version == 6
+ assert result.config.image == "ubuntu"
+
+ def test_missing_manifest(self, tmp_dir):
+ """Test error when manifest is missing from save directory."""
+ save_dir = tmp_dir / "empty-save"
+ save_dir.mkdir()
+ overlays_dir = save_dir / "overlays"
+ overlays_dir.mkdir()
+ (overlays_dir / "0.qcow2").write_bytes(b"fake")
+
+ with pytest.raises(ValueError, match=r"Missing manifest\.json"):
+ ImageResolver().validate_save(save_dir)
+
+ def test_invalid_json(self, tmp_dir):
+ """Test error when manifest is invalid JSON."""
+ save_dir = tmp_dir / "bad-json-save"
+ save_dir.mkdir()
+ (save_dir / "manifest.json").write_text("not valid json")
+ overlays_dir = save_dir / "overlays"
+ overlays_dir.mkdir()
+ (overlays_dir / "0.qcow2").write_bytes(b"fake")
+
+ with pytest.raises(ValueError):
+ SaveManifest.model_validate_json((save_dir / "manifest.json").read_text())
+
+
+class TestValidateSave:
+ """Tests for ImageResolver.validate_save."""
+
+ @pytest.fixture
+ def valid_save(self, tmp_dir):
+ """Create a valid save directory that can be validated."""
+ save_dir = tmp_dir / "my-save"
+ save_dir.mkdir()
+ manifest = {
+ "version": SAVE_VERSION,
+ "config": {"image": "test-image"},
+ }
+ (save_dir / "manifest.json").write_text(json.dumps(manifest))
+ overlays_dir = save_dir / "overlays"
+ overlays_dir.mkdir()
+ (overlays_dir / "0.qcow2").write_bytes(b"fake overlay content")
+ return save_dir
+
+ def test_valid_save_passes_validation(self, valid_save):
+ """Test that a valid save directory passes validation."""
+ result = ImageResolver().validate_save(valid_save)
+ assert result.version == SAVE_VERSION
+ assert result.config.image == "test-image"
+
+ def test_not_a_directory(self, tmp_dir):
+ """Test error when path is not a directory."""
+ file_path = tmp_dir / "not-a-dir.txt"
+ file_path.write_text("not a directory")
+
+ with pytest.raises(ValueError, match="not a directory"):
+ ImageResolver().validate_save(file_path)
+
+ def test_missing_overlays_dir(self, tmp_dir):
+ """Test error when overlays directory is missing."""
+ save_dir = tmp_dir / "no-overlays"
+ save_dir.mkdir()
+ manifest = {
+ "version": SAVE_VERSION,
+ "config": {"image": "test"},
+ }
+ (save_dir / "manifest.json").write_text(json.dumps(manifest))
+
+ with pytest.raises(ValueError, match="Missing overlays"):
+ ImageResolver().validate_save(save_dir)
+
+ def test_version_too_new(self, tmp_dir):
+ """Test error when save version is too new."""
+ save_dir = tmp_dir / "new-version"
+ save_dir.mkdir()
+ manifest = {
+ "version": SAVE_VERSION + 1,
+ "config": {"image": "test"},
+ }
+ (save_dir / "manifest.json").write_text(json.dumps(manifest))
+ overlays_dir = save_dir / "overlays"
+ overlays_dir.mkdir()
+ (overlays_dir / "0.qcow2").write_bytes(b"fake")
+
+ with pytest.raises(ValueError, match="newer than supported"):
+ ImageResolver().validate_save(save_dir)
+
+ def test_empty_overlays_dir(self, tmp_dir):
+ """Test error when overlays directory is empty."""
+ save_dir = tmp_dir / "empty-overlays"
+ save_dir.mkdir()
+ manifest = {
+ "version": SAVE_VERSION,
+ "config": {"image": "test"},
+ }
+ (save_dir / "manifest.json").write_text(json.dumps(manifest))
+ overlays_dir = save_dir / "overlays"
+ overlays_dir.mkdir()
+
+ with pytest.raises(ValueError, match="No overlay files found"):
+ ImageResolver().validate_save(save_dir)
+
+
+class TestSandboxSaveMethod:
+ """Tests for Sandbox.save() method."""
+
+ @pytest.mark.asyncio
+ async def test_save_requires_running(self, tmp_dir):
+ """Test that save() raises when sandbox is not running."""
+ from quicksand_core import Sandbox
+
+ sandbox = Sandbox(image="ubuntu")
+
+ with pytest.raises(RuntimeError, match="non-running"):
+ await sandbox.save("my-save", workspace=tmp_dir)
+
+
+class TestSandboxValidateSaveMethod:
+ """Tests for Sandbox.validate_save() method."""
+
+ def test_validate_missing_save(self, tmp_dir):
+ """Test that validate_save() raises when save doesn't exist."""
+ from quicksand_core import Sandbox
+
+ with pytest.raises(FileNotFoundError, match="Save not found"):
+ Sandbox.validate_save(tmp_dir / "nonexistent")
diff --git a/tests/unit/test_core_config.py b/tests/unit/test_core_config.py
new file mode 100644
index 0000000..9bd711f
--- /dev/null
+++ b/tests/unit/test_core_config.py
@@ -0,0 +1,109 @@
+"""Unit tests for quicksand_core configuration classes."""
+
+from __future__ import annotations
+
+import pytest
+from quicksand_core import Mount, PortForward, SandboxConfig
+from quicksand_core._types import NetworkMode
+from pydantic import ValidationError
+
+
+class TestMount:
+ """Tests for Mount dataclass."""
+
+ def test_create_mount(self):
+ """Test creating a basic mount."""
+ mount = Mount(host="/host/path", guest="/guest/path")
+ assert mount.host == "/host/path"
+ assert mount.guest == "/guest/path"
+ assert mount.readonly is False
+
+ def test_create_readonly_mount(self):
+ """Test creating a readonly mount."""
+ mount = Mount(host="/host", guest="/guest", readonly=True)
+ assert mount.readonly is True
+
+ def test_mount_equality(self):
+ """Test Mount equality."""
+ mount1 = Mount("/a", "/b", False)
+ mount2 = Mount("/a", "/b", False)
+ mount3 = Mount("/a", "/b", True)
+
+ assert mount1 == mount2
+ assert mount1 != mount3
+
+
+class TestSandboxConfig:
+ """Tests for SandboxConfig dataclass."""
+
+ def test_create_minimal_config(self):
+ """Test creating config with only required fields."""
+ config = SandboxConfig(image="ubuntu")
+ assert config.image == "ubuntu"
+ assert config.memory == "512M"
+ assert config.cpus == 1
+ assert config.mounts == []
+ assert config.port_forwards == []
+ assert config.network_mode is NetworkMode.MOUNTS_ONLY
+ assert config.extra_qemu_args == []
+ assert config.boot_timeout == 60.0
+
+ def test_create_full_config(self):
+ """Test creating config with all fields (image is str only)."""
+ mounts = [Mount("/host", "/guest")]
+ config = SandboxConfig(
+ image="ubuntu",
+ memory="2G",
+ cpus=4,
+ mounts=mounts,
+ port_forwards=[PortForward(host=8080, guest=80)],
+ network_mode=NetworkMode.FULL,
+ extra_qemu_args=["-cpu", "host"],
+ boot_timeout=120.0,
+ )
+
+ assert config.image == "ubuntu"
+ assert config.memory == "2G"
+ assert config.cpus == 4
+ assert len(config.mounts) == 1
+ assert config.port_forwards == [PortForward(host=8080, guest=80)]
+ assert config.network_mode is NetworkMode.FULL
+ assert config.extra_qemu_args == ["-cpu", "host"]
+ assert config.boot_timeout == 120.0
+
+ def test_config_requires_image(self):
+ """Test that image is required."""
+ with pytest.raises((TypeError, ValidationError)):
+ SandboxConfig() # type: ignore
+
+ def test_config_with_string_image(self):
+ """Test config with string image name."""
+ config = SandboxConfig(image="ubuntu")
+ assert config.image == "ubuntu"
+
+ def test_config_is_frozen(self):
+ """Test that SandboxConfig is frozen (immutable)."""
+ config = SandboxConfig(image="ubuntu")
+ with pytest.raises(ValidationError):
+ config.image = "alpine"
+
+
+class TestExecuteResult:
+ """Tests for ExecuteResult dataclass."""
+
+ def test_create_execute_result(self):
+ """Test creating an ExecuteResult."""
+ from quicksand_core import ExecuteResult
+
+ result = ExecuteResult(stdout="hello", stderr="", exit_code=0)
+ assert result.stdout == "hello"
+ assert result.stderr == ""
+ assert result.exit_code == 0
+
+ def test_execute_result_with_error(self):
+ """Test ExecuteResult with non-zero exit code."""
+ from quicksand_core import ExecuteResult
+
+ result = ExecuteResult(stdout="", stderr="error message", exit_code=1)
+ assert result.exit_code == 1
+ assert result.stderr == "error message"
diff --git a/tests/unit/test_core_runtime.py b/tests/unit/test_core_runtime.py
new file mode 100644
index 0000000..a4061a2
--- /dev/null
+++ b/tests/unit/test_core_runtime.py
@@ -0,0 +1,246 @@
+"""Unit tests for quicksand_core runtime and platform modules."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+from quicksand_core.host import (
+ Accelerator,
+ AcceleratorStatus,
+ Architecture,
+ DarwinConfig,
+ LinuxConfig,
+ WindowsConfig,
+)
+from quicksand_core.qemu.arch import ARM64Config, X86_64Config
+from quicksand_core.qemu.platform import (
+ PlatformConfig,
+ RuntimeInfo,
+ get_machine_type,
+ get_platform_config,
+)
+
+
+def _clear_platform_caches():
+ """Clear all platform-related caches for testing."""
+ get_platform_config.cache_clear()
+
+
+class TestGetPlatformConfig:
+ """Tests for get_platform_config function."""
+
+ def test_linux_x86_64(self):
+ """Test Linux x86_64 platform config."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Linux"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="x86_64"),
+ ):
+ _clear_platform_caches()
+ config = get_platform_config()
+ assert config.platform_key == "linux-x86_64"
+ assert config.arch.arch_type == Architecture.X86_64
+
+ def test_linux_aarch64(self):
+ """Test Linux ARM64 platform config."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Linux"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="aarch64"),
+ ):
+ _clear_platform_caches()
+ config = get_platform_config()
+ # Architecture is normalized to arm64
+ assert config.platform_key == "linux-arm64"
+ assert config.arch.arch_type == Architecture.ARM64
+
+ def test_darwin_x86_64(self):
+ """Test macOS Intel platform config."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Darwin"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="x86_64"),
+ ):
+ _clear_platform_caches()
+ config = get_platform_config()
+ assert config.platform_key == "darwin-x86_64"
+
+ def test_darwin_arm64(self):
+ """Test macOS Apple Silicon platform config."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Darwin"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="arm64"),
+ ):
+ _clear_platform_caches()
+ config = get_platform_config()
+ assert config.platform_key == "darwin-arm64"
+
+ def test_windows_x86_64(self):
+ """Test Windows x86_64 platform config."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Windows"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="AMD64"),
+ patch("quicksand_core.host.arch._detect_native_windows_arch", return_value=None),
+ ):
+ _clear_platform_caches()
+ config = get_platform_config()
+ assert config.platform_key == "windows-x86_64"
+
+ def test_windows_arm64_native(self):
+ """Test native ARM64 Windows platform config."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Windows"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="ARM64"),
+ patch("quicksand_core.host.arch._detect_native_windows_arch", return_value="ARM64"),
+ ):
+ _clear_platform_caches()
+ config = get_platform_config()
+ assert config.platform_key == "windows-arm64"
+ assert config.arch.arch_type == Architecture.ARM64
+
+ def test_windows_arm64_emulated(self):
+ """Test Windows ARM64 with x86_64 Python (transparent emulation).
+
+ platform.machine() returns AMD64, but registry detects ARM64.
+ """
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Windows"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="AMD64"),
+ patch("quicksand_core.host.arch._detect_native_windows_arch", return_value="ARM64"),
+ ):
+ _clear_platform_caches()
+ config = get_platform_config()
+ assert config.platform_key == "windows-arm64"
+ assert config.arch.arch_type == Architecture.ARM64
+
+
+class TestPlatformConfigProperties:
+ """Test PlatformConfig derived properties."""
+
+ def test_arm64_darwin_properties(self):
+ """Test ARM64 macOS derived properties."""
+ config = PlatformConfig(arch=ARM64Config(), os=DarwinConfig())
+ assert config.machine_type == "virt"
+ assert config.qemu_system_binary() == "qemu-system-aarch64"
+ assert config.console_device == "ttyAMA0"
+
+ def test_x86_64_linux_properties(self):
+ """Test x86_64 Linux derived properties."""
+ config = PlatformConfig(arch=X86_64Config(), os=LinuxConfig())
+ assert config.machine_type == "q35"
+ assert config.qemu_system_binary() == "qemu-system-x86_64"
+ assert config.console_device == "ttyS0"
+
+ def test_windows_x86_64_properties(self):
+ """Test Windows x86_64 derived properties."""
+ config = PlatformConfig(arch=X86_64Config(), os=WindowsConfig())
+ assert config.qemu_system_binary() == "qemu-system-x86_64.exe"
+ assert config.qemu_img_binary() == "qemu-img.exe"
+
+
+class TestAcceleratorStatus:
+ """Tests for AcceleratorStatus."""
+
+ def test_accelerator_property_returns_available(self):
+ """Test accelerator returns available when set."""
+ status = AcceleratorStatus(available=Accelerator.KVM, fallback=Accelerator.TCG)
+ assert status.accelerator == Accelerator.KVM
+
+ def test_accelerator_property_returns_fallback(self):
+ """Test accelerator returns fallback when available is None."""
+ status = AcceleratorStatus(available=None, fallback=Accelerator.TCG)
+ assert status.accelerator == Accelerator.TCG
+
+
+class TestDetectKvm:
+ """Tests for Linux KVM detection."""
+
+ def test_kvm_not_available(self):
+ """Test KVM detection when /dev/kvm doesn't exist."""
+ linux_config = LinuxConfig()
+
+ with patch.object(
+ type(linux_config), "kvm_device", new_callable=lambda: property(lambda self: None)
+ ):
+ result = linux_config.detect_accelerator()
+ assert result.available is None
+ assert result.fallback == Accelerator.TCG
+ assert result.error is not None
+ assert "/dev/kvm" in result.error
+
+ def test_kvm_exists_but_no_permission(self):
+ """Test KVM detection when /dev/kvm exists but no permission."""
+ mock_path = MagicMock()
+ mock_path.exists.return_value = True
+
+ linux_config = LinuxConfig()
+
+ with (
+ patch.object(
+ type(linux_config),
+ "kvm_device",
+ new_callable=lambda: property(lambda self: mock_path),
+ ),
+ patch("os.access", return_value=False),
+ ):
+ result = linux_config.detect_accelerator()
+ assert result.available is None
+ assert result.fallback == Accelerator.TCG
+ assert result.error is not None
+ assert "Permission denied" in result.error
+
+ def test_kvm_available(self):
+ """Test KVM detection when /dev/kvm is available."""
+ mock_path = MagicMock()
+ mock_path.exists.return_value = True
+
+ linux_config = LinuxConfig()
+
+ with (
+ patch.object(
+ type(linux_config),
+ "kvm_device",
+ new_callable=lambda: property(lambda self: mock_path),
+ ),
+ patch("os.access", return_value=True),
+ ):
+ result = linux_config.detect_accelerator()
+ assert result.available == Accelerator.KVM
+ assert result.error is None
+
+
+class TestGetMachineType:
+ """Tests for get_machine_type function."""
+
+ def test_x86_64_returns_q35(self):
+ """Test x86_64 returns q35 machine type."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Linux"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="x86_64"),
+ ):
+ _clear_platform_caches()
+ assert get_machine_type() == "q35"
+
+ def test_arm64_returns_virt(self):
+ """Test ARM64 returns virt machine type."""
+ with (
+ patch("quicksand_core.host.os_._platform.system", return_value="Linux"),
+ patch("quicksand_core.host.arch._platform.machine", return_value="arm64"),
+ ):
+ _clear_platform_caches()
+ assert get_machine_type() == "virt"
+
+
+class TestRuntimeInfo:
+ """Tests for RuntimeInfo dataclass."""
+
+ def test_create_runtime_info(self, tmp_dir):
+ """Test creating RuntimeInfo."""
+ qemu = tmp_dir / "qemu"
+ qemu_img = tmp_dir / "qemu-img"
+ runtime_dir = tmp_dir / "runtime"
+ qemu.touch()
+ qemu_img.touch()
+ runtime_dir.mkdir()
+
+ info = RuntimeInfo(qemu_binary=qemu, qemu_img=qemu_img, runtime_dir=runtime_dir)
+ assert info.qemu_binary == qemu
+ assert info.qemu_img == qemu_img
+ assert info.runtime_dir == runtime_dir
diff --git a/tests/unit/test_core_sandbox.py b/tests/unit/test_core_sandbox.py
new file mode 100644
index 0000000..cd4dc7f
--- /dev/null
+++ b/tests/unit/test_core_sandbox.py
@@ -0,0 +1,346 @@
+"""Unit tests for quicksand_core Sandbox class."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import httpx
+import pytest
+from quicksand_core import PortForward, Sandbox, SandboxConfig
+from quicksand_core._types import NetworkMode
+from quicksand_core.host import LinuxConfig
+from quicksand_core.host.quicksand_guest_agent_client import _retry_on_transient_error
+from quicksand_core.qemu.arch import X86_64Config
+from quicksand_core.qemu.platform import PlatformConfig, RuntimeInfo
+
+
+class TestSandboxInit:
+ """Tests for Sandbox initialization."""
+
+ def test_create_sandbox_with_config(self, fake_qcow2):
+ """Test creating a Sandbox with a config."""
+ sandbox = Sandbox(image="ubuntu")
+
+ assert sandbox.config.image == "ubuntu"
+ assert sandbox.is_running is False
+
+ def test_sandbox_requires_image(self):
+ """Test that Sandbox requires an image kwarg."""
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError, match="image"):
+ Sandbox()
+
+ def test_sandbox_with_progress_callback(self, fake_qcow2):
+ """Test Sandbox with progress callback."""
+ callback = MagicMock()
+ sandbox = Sandbox(image="ubuntu", progress_callback=callback)
+
+ assert sandbox._progress_callback == callback
+
+
+class TestSandboxVMCommand:
+ """Tests for VM command building."""
+
+ def test_build_basic_command(self, fake_image_set, mock_runtime):
+ """Test building basic VM command."""
+ from quicksand_core._types import ResolvedAccelerator, ResolvedImage
+ from quicksand_core.host import Accelerator
+
+ sandbox = Sandbox(image="ubuntu")
+ sandbox._runtime_info = mock_runtime
+ sandbox._image = ResolvedImage(
+ name="ubuntu",
+ chain=[fake_image_set["qcow2"]],
+ )
+ sandbox._accel = ResolvedAccelerator(accel=Accelerator.HVF)
+ sandbox._overlay_path = Path("/tmp/overlay.qcow2")
+ sandbox._agent_port = 12345
+ sandbox._agent_token = "testtoken123"
+
+ cmd = sandbox._build_vm_command()
+
+ assert str(mock_runtime.qemu_binary) in cmd
+ assert "-m" in cmd
+ assert "512M" in cmd
+ assert "-smp" in cmd
+ assert "1" in cmd
+
+ def test_command_includes_kernel(self, fake_image_set, mock_runtime):
+ """Test that command includes -kernel when kernel is available."""
+ from quicksand_core._types import ResolvedAccelerator, ResolvedImage
+ from quicksand_core.host import Accelerator
+
+ sandbox = Sandbox(image="ubuntu")
+ sandbox._runtime_info = mock_runtime
+ sandbox._image = ResolvedImage(
+ name="ubuntu",
+ chain=[fake_image_set["qcow2"]],
+ kernel=fake_image_set["kernel"],
+ initrd=fake_image_set["initrd"],
+ )
+ sandbox._accel = ResolvedAccelerator(accel=Accelerator.HVF)
+ sandbox._overlay_path = Path("/tmp/overlay.qcow2")
+ sandbox._agent_port = 12345
+ sandbox._agent_token = "testtoken123"
+
+ cmd = sandbox._build_vm_command()
+
+ assert "-kernel" in cmd
+ assert str(fake_image_set["kernel"]) in cmd
+ assert "-initrd" in cmd
+ assert str(fake_image_set["initrd"]) in cmd
+ assert "-append" in cmd
+
+
+def _create_test_platform_config() -> PlatformConfig:
+ """Helper to create a PlatformConfig for testing (x86_64 Linux)."""
+ return PlatformConfig(arch=X86_64Config(), os=LinuxConfig())
+
+
+class TestSandboxNetworkArgs:
+ """Tests for network argument building."""
+
+ def test_network_disabled(self, fake_qcow2):
+ """Test network disabled config."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.NONE,
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345)
+ assert args == ["-nic", "none"]
+
+ def test_network_restricted(self, fake_qcow2):
+ """Test restricted network (default)."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.MOUNTS_ONLY,
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345)
+ assert "restrict=on" in args[1]
+
+ def test_network_unrestricted(self, fake_qcow2):
+ """Test unrestricted network."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.FULL,
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345)
+ assert "restrict=off" in args[1]
+
+ def test_network_mounts_only_without_smb(self, fake_qcow2):
+ """Test MOUNTS_ONLY mode without SMB port (no guestfwd)."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.MOUNTS_ONLY,
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345)
+ assert "restrict=on" in args[1]
+ assert "guestfwd" not in args[1]
+
+ def test_network_mounts_only_with_smb(self, fake_qcow2):
+ """Test MOUNTS_ONLY mode with SMB port adds guestfwd tunnel."""
+ config = SandboxConfig(
+ image="ubuntu",
+ network_mode=NetworkMode.MOUNTS_ONLY,
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345, smb_port=4450)
+ assert "restrict=on" in args[1]
+ assert "guestfwd=tcp:10.0.2.100:445-cmd:" in args[1]
+ assert "_tcp_relay.py" in args[1]
+ assert "127.0.0.1 4450" in args[1]
+
+ def test_port_forwards(self, fake_qcow2):
+ """Test port forwarding configuration."""
+ config = SandboxConfig(
+ image="ubuntu",
+ port_forwards=[PortForward(host=8080, guest=80), PortForward(host=8443, guest=443)],
+ )
+ platform_config = _create_test_platform_config()
+
+ args = platform_config._build_network_args(config, 12345)
+ assert "hostfwd=tcp:127.0.0.1:8080-:80" in args[1]
+ assert "hostfwd=tcp:127.0.0.1:8443-:443" in args[1]
+
+
+class TestSandboxMountConfig:
+ """Tests for mount configuration validation."""
+
+ def test_no_mounts_no_qemu_args(self, fake_qcow2):
+ """Test that mounts don't add QEMU args (CIFS is handled at runtime)."""
+ config = SandboxConfig(image="ubuntu")
+ platform_config = _create_test_platform_config()
+ # CIFS mounts don't require any QEMU-level args
+ cmd = platform_config.build_qemu_command(
+ config=config,
+ runtime_info=RuntimeInfo(
+ qemu_binary=Path("/usr/bin/qemu-system-aarch64"),
+ qemu_img=Path("/usr/bin/qemu-img"),
+ runtime_dir=Path("/usr"),
+ ),
+ kernel_path=None,
+ initrd_path=None,
+ overlay_path=Path(str(fake_qcow2)),
+ agent_port=12345,
+ agent_token="test_token",
+ accelerator=None,
+ )
+ # No -fsdev or virtio-9p args should be present
+ assert "-fsdev" not in cmd
+ assert "virtio-9p" not in str(cmd)
+
+
+class TestSandboxContextManager:
+ """Tests for async context manager interface."""
+
+ @pytest.mark.asyncio
+ async def test_context_manager_calls_start_stop(self, fake_qcow2):
+ """Test that context manager calls start and stop."""
+ sandbox = Sandbox(image="ubuntu")
+
+ with (
+ patch.object(sandbox, "start", new_callable=AsyncMock) as mock_start,
+ patch.object(sandbox, "stop", new_callable=AsyncMock) as mock_stop,
+ ):
+ async with sandbox:
+ mock_start.assert_called_once()
+ mock_stop.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_context_manager_stops_on_exception(self, fake_qcow2):
+ """Test that context manager stops even on exception."""
+ sandbox = Sandbox(image="ubuntu")
+
+ with (
+ patch.object(sandbox, "start", new_callable=AsyncMock),
+ patch.object(sandbox, "stop", new_callable=AsyncMock) as mock_stop,
+ ):
+ with pytest.raises(ValueError):
+ async with sandbox:
+ raise ValueError("test error")
+ mock_stop.assert_called_once()
+
+
+class TestRetryLogic:
+ """Tests for transient error retry logic."""
+
+ @pytest.mark.asyncio
+ async def test_retry_on_connection_reset(self):
+ """Test that ConnectionResetError triggers retry."""
+ call_count = 0
+
+ async def flaky_func():
+ nonlocal call_count
+ call_count += 1
+ if call_count < 3:
+ raise ConnectionResetError(54, "Connection reset by peer")
+ return "success"
+
+ result = await _retry_on_transient_error(flaky_func, max_retries=3, base_delay=0.01)
+ assert result == "success"
+ assert call_count == 3
+
+ @pytest.mark.asyncio
+ async def test_retry_on_read_error(self):
+ """Test that httpx.ReadError triggers retry."""
+ call_count = 0
+
+ async def flaky_func():
+ nonlocal call_count
+ call_count += 1
+ if call_count < 2:
+ raise httpx.ReadError("Connection reset")
+ return "success"
+
+ result = await _retry_on_transient_error(flaky_func, max_retries=3, base_delay=0.01)
+ assert result == "success"
+ assert call_count == 2
+
+ @pytest.mark.asyncio
+ async def test_retry_on_connect_error(self):
+ """Test that httpx.ConnectError triggers retry."""
+ call_count = 0
+
+ async def flaky_func():
+ nonlocal call_count
+ call_count += 1
+ if call_count < 2:
+ raise httpx.ConnectError("Connection refused")
+ return "success"
+
+ result = await _retry_on_transient_error(flaky_func, max_retries=3, base_delay=0.01)
+ assert result == "success"
+ assert call_count == 2
+
+ @pytest.mark.asyncio
+ async def test_no_retry_on_http_status_error(self):
+ """Test that HTTPStatusError does NOT trigger retry."""
+ call_count = 0
+
+ async def auth_error():
+ nonlocal call_count
+ call_count += 1
+ request = httpx.Request("POST", "http://test")
+ response = httpx.Response(401, request=request)
+ raise httpx.HTTPStatusError("Unauthorized", request=request, response=response)
+
+ with pytest.raises(httpx.HTTPStatusError):
+ await _retry_on_transient_error(auth_error, max_retries=3, base_delay=0.01)
+
+ assert call_count == 1 # No retries
+
+ @pytest.mark.asyncio
+ async def test_max_retries_exhausted(self):
+ """Test that exception is raised after max retries."""
+ call_count = 0
+
+ async def always_fails():
+ nonlocal call_count
+ call_count += 1
+ raise httpx.ConnectError("Connection refused")
+
+ with pytest.raises(httpx.ConnectError):
+ await _retry_on_transient_error(always_fails, max_retries=2, base_delay=0.01)
+
+ assert call_count == 3 # Initial + 2 retries
+
+ @pytest.mark.asyncio
+ async def test_success_on_first_try(self):
+ """Test that successful first try returns immediately."""
+ call_count = 0
+
+ async def success_func():
+ nonlocal call_count
+ call_count += 1
+ return "success"
+
+ result = await _retry_on_transient_error(success_func, max_retries=3, base_delay=0.01)
+ assert result == "success"
+ assert call_count == 1
+
+ @pytest.mark.asyncio
+ async def test_retry_on_broken_pipe(self):
+ """Test that BrokenPipeError triggers retry."""
+ call_count = 0
+
+ async def flaky_func():
+ nonlocal call_count
+ call_count += 1
+ if call_count < 2:
+ raise BrokenPipeError("Broken pipe")
+ return "success"
+
+ result = await _retry_on_transient_error(flaky_func, max_retries=3, base_delay=0.01)
+ assert result == "success"
+ assert call_count == 2
diff --git a/tests/unit/test_dev_build.py b/tests/unit/test_dev_build.py
new file mode 100644
index 0000000..6247b96
--- /dev/null
+++ b/tests/unit/test_dev_build.py
@@ -0,0 +1,140 @@
+"""Unit tests for quicksand_dev build module."""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+from quicksand_image_tools.build import (
+ _find_initrd,
+ _find_kernel,
+ _get_dir_size,
+ build_image,
+)
+
+
+class TestFindKernel:
+ """Tests for _find_kernel function."""
+
+ def test_find_vmlinuz_versioned(self, tmp_dir):
+ """Test finding versioned vmlinuz."""
+ boot = tmp_dir / "boot"
+ boot.mkdir()
+ (boot / "vmlinuz-5.15.0-generic").touch()
+ (boot / "vmlinuz-6.1.0-generic").touch()
+
+ kernel = _find_kernel(tmp_dir)
+ # Should return newest version
+ assert kernel is not None
+ assert "6.1.0" in kernel.name
+
+ def test_find_vmlinuz_unversioned(self, tmp_dir):
+ """Test finding unversioned vmlinuz."""
+ boot = tmp_dir / "boot"
+ boot.mkdir()
+ (boot / "vmlinuz").touch()
+
+ kernel = _find_kernel(tmp_dir)
+ assert kernel is not None
+ assert kernel.name == "vmlinuz"
+
+ def test_no_kernel_found(self, tmp_dir):
+ """Test when no kernel is found."""
+ boot = tmp_dir / "boot"
+ boot.mkdir()
+ # No kernel files
+
+ kernel = _find_kernel(tmp_dir)
+ assert kernel is None
+
+ def test_no_boot_dir(self, tmp_dir):
+ """Test when boot directory doesn't exist."""
+ kernel = _find_kernel(tmp_dir)
+ assert kernel is None
+
+
+class TestFindInitrd:
+ """Tests for _find_initrd function."""
+
+ def test_find_initrd_img_versioned(self, tmp_dir):
+ """Test finding versioned initrd.img."""
+ boot = tmp_dir / "boot"
+ boot.mkdir()
+ (boot / "initrd.img-5.15.0-generic").touch()
+ (boot / "initrd.img-6.1.0-generic").touch()
+
+ initrd = _find_initrd(tmp_dir)
+ assert initrd is not None
+ assert "6.1.0" in initrd.name
+
+ def test_find_initramfs(self, tmp_dir):
+ """Test finding initramfs (Alpine style)."""
+ boot = tmp_dir / "boot"
+ boot.mkdir()
+ (boot / "initramfs-virt").touch()
+
+ initrd = _find_initrd(tmp_dir)
+ assert initrd is not None
+ assert "initramfs" in initrd.name
+
+ def test_no_initrd_found(self, tmp_dir):
+ """Test when no initrd is found."""
+ boot = tmp_dir / "boot"
+ boot.mkdir()
+
+ initrd = _find_initrd(tmp_dir)
+ assert initrd is None
+
+
+class TestGetDirSize:
+ """Tests for _get_dir_size function."""
+
+ def test_empty_dir(self, tmp_dir):
+ """Test size of empty directory."""
+ size = _get_dir_size(tmp_dir)
+ assert size == 0
+
+ def test_dir_with_files(self, tmp_dir):
+ """Test size of directory with files."""
+ (tmp_dir / "file1").write_bytes(b"a" * 100)
+ (tmp_dir / "file2").write_bytes(b"b" * 200)
+
+ size = _get_dir_size(tmp_dir)
+ assert size == 300
+
+ def test_nested_dirs(self, tmp_dir):
+ """Test size includes nested directories."""
+ subdir = tmp_dir / "subdir"
+ subdir.mkdir()
+ (tmp_dir / "file1").write_bytes(b"a" * 100)
+ (subdir / "file2").write_bytes(b"b" * 200)
+
+ size = _get_dir_size(tmp_dir)
+ assert size == 300
+
+ def test_ignores_symlinks(self, tmp_dir):
+ """Test that symlinks are not counted."""
+ (tmp_dir / "file").write_bytes(b"a" * 100)
+ (tmp_dir / "link").symlink_to(tmp_dir / "file")
+
+ size = _get_dir_size(tmp_dir)
+ assert size == 100
+
+
+class TestBuildImage:
+ """Tests for build_image function."""
+
+ def test_dockerfile_path_input(self, tmp_dir, cache_dir):
+ """Test using Dockerfile path as input."""
+ dockerfile_path = tmp_dir / "Dockerfile"
+ dockerfile_path.write_text("FROM alpine:3.20\n")
+
+ # Create cached image
+ import hashlib
+
+ content_hash = hashlib.sha256(b"FROM alpine:3.20\n").hexdigest()[:16]
+ cached_image = cache_dir / f"custom-{content_hash}.qcow2"
+ cached_image.touch()
+
+ with patch("shutil.which", return_value="/usr/bin/docker"):
+ result = build_image(dockerfile_path, cache_dir=cache_dir)
+ assert result == cached_image
diff --git a/tests/unit/test_dev_cli.py b/tests/unit/test_dev_cli.py
new file mode 100644
index 0000000..7102b1b
--- /dev/null
+++ b/tests/unit/test_dev_cli.py
@@ -0,0 +1,531 @@
+"""Unit tests for quicksand_dev CLI module."""
+
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+from quicksand_core import BaseImageInfo
+from quicksand_image_tools.cli import (
+ cmd_build_base,
+ cmd_build_image,
+ cmd_init,
+ discover_bases,
+ main,
+)
+
+# ============================================================================
+# Tests for helper functions
+# ============================================================================
+
+
+class TestDiscoverBases:
+ """Tests for discover_bases function."""
+
+ def test_discovers_bases_from_entry_points(self, tmp_dir):
+ """Test discovering bases via entry points."""
+ docker_dir = tmp_dir / "docker"
+ docker_dir.mkdir()
+
+ mock_provider = MagicMock()
+ mock_provider.name = "test"
+ mock_provider.type = "base"
+
+ mock_module = MagicMock()
+ mock_module._DOCKER_DIR = docker_dir
+ mock_module.DISTRO_VERSION = "1.0.0"
+
+ mock_ep = MagicMock()
+ mock_ep.name = "test"
+ mock_ep.value = "test_pkg:image"
+ mock_ep.load.return_value = mock_provider
+
+ with (
+ patch("quicksand_image_tools.cli.entry_points", return_value=[mock_ep]),
+ patch("importlib.import_module", return_value=mock_module),
+ ):
+ result = discover_bases()
+ assert "test" in result
+ assert result["test"].name == "test"
+ assert result["test"].version == "1.0.0"
+
+ def test_returns_empty_dict_when_no_bases(self):
+ """Test returns empty dict when no entry points found."""
+ with patch("quicksand_image_tools.cli.entry_points", return_value=[]):
+ result = discover_bases()
+ assert result == {}
+
+ def test_handles_entry_point_load_error(self):
+ """Test handles errors loading entry points gracefully."""
+ mock_ep = MagicMock()
+ mock_ep.name = "bad"
+ mock_ep.value = "bad_pkg:image"
+ mock_ep.load.side_effect = ImportError("Failed to load")
+
+ with patch("quicksand_image_tools.cli.entry_points", return_value=[mock_ep]):
+ result = discover_bases()
+ assert result == {}
+
+ def test_discovers_multiple_bases(self, tmp_dir):
+ """Test discovering multiple bases."""
+ ubuntu_dir = tmp_dir / "ubuntu"
+ alpine_dir = tmp_dir / "alpine"
+ ubuntu_dir.mkdir()
+ alpine_dir.mkdir()
+
+ ubuntu_provider = MagicMock(name="ubuntu", type="base")
+ ubuntu_provider.name = "ubuntu"
+ alpine_provider = MagicMock(name="alpine", type="base")
+ alpine_provider.name = "alpine"
+
+ mock_eps = [
+ MagicMock(name="ubuntu", value="quicksand_ubuntu:image"),
+ MagicMock(name="alpine", value="quicksand_alpine:image"),
+ ]
+ mock_eps[0].load.return_value = ubuntu_provider
+ mock_eps[1].load.return_value = alpine_provider
+
+ ubuntu_mod = MagicMock(_DOCKER_DIR=ubuntu_dir, DISTRO_VERSION="24.04.0")
+ alpine_mod = MagicMock(_DOCKER_DIR=alpine_dir, DISTRO_VERSION="3.21.0")
+
+ def _import(name):
+ return {"quicksand_ubuntu": ubuntu_mod, "quicksand_alpine": alpine_mod}[name]
+
+ with (
+ patch("quicksand_image_tools.cli.entry_points", return_value=mock_eps),
+ patch("importlib.import_module", side_effect=_import),
+ ):
+ result = discover_bases()
+ assert len(result) == 2
+ assert "ubuntu" in result
+ assert "alpine" in result
+
+
+# ============================================================================
+# Tests for cmd_init
+# ============================================================================
+
+
+def _mock_bases(tmp_dir):
+ """Create mock BaseImageInfo objects for testing."""
+ ubuntu_dir = tmp_dir / "ubuntu_docker"
+ alpine_dir = tmp_dir / "alpine_docker"
+ ubuntu_dir.mkdir(exist_ok=True)
+ alpine_dir.mkdir(exist_ok=True)
+
+ return {
+ "ubuntu": BaseImageInfo(name="ubuntu", docker_dir=ubuntu_dir, version="24.04.0"),
+ "alpine": BaseImageInfo(name="alpine", docker_dir=alpine_dir, version="3.21.0"),
+ }
+
+
+class TestCmdInit:
+ """Tests for cmd_init function."""
+
+ def test_creates_directory_if_not_exists(self, tmp_dir):
+ """Test that init creates the target directory."""
+ target_dir = tmp_dir / "new_dir"
+ args = argparse.Namespace(directory=target_dir, base="ubuntu")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value=_mock_bases(tmp_dir)),
+ patch("subprocess.run") as mock_run,
+ patch("quicksand_image_tools.cli.cmd_build_base", return_value=0),
+ ):
+ mock_run.return_value = MagicMock(returncode=1)
+
+ result = cmd_init(args)
+
+ assert result == 0
+ assert target_dir.exists()
+
+ def test_creates_dockerfile_with_versioned_tag(self, tmp_dir):
+ """Test that init creates Dockerfile with versioned tag."""
+ args = argparse.Namespace(directory=tmp_dir, base="ubuntu")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value=_mock_bases(tmp_dir)),
+ patch("subprocess.run") as mock_run,
+ ):
+ mock_run.return_value = MagicMock(returncode=0)
+
+ result = cmd_init(args)
+
+ assert result == 0
+ dockerfile = tmp_dir / "Dockerfile"
+ assert dockerfile.exists()
+ content = dockerfile.read_text()
+ assert "FROM quicksand/ubuntu-base:24.04.0" in content
+
+ def test_builds_base_if_image_not_found(self, tmp_dir):
+ """Test that init builds base image if not found."""
+ args = argparse.Namespace(directory=tmp_dir, base="alpine")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value=_mock_bases(tmp_dir)),
+ patch("subprocess.run") as mock_run,
+ patch("quicksand_image_tools.cli.cmd_build_base", return_value=0) as mock_build,
+ ):
+ mock_run.return_value = MagicMock(returncode=1)
+
+ result = cmd_init(args)
+
+ assert result == 0
+ mock_build.assert_called_once()
+
+ def test_error_when_no_dockerfile_and_no_base(self, tmp_dir, capsys):
+ """Test error when no Dockerfile exists and no base specified."""
+ args = argparse.Namespace(directory=tmp_dir, base=None)
+
+ result = cmd_init(args)
+
+ assert result == 1
+ captured = capsys.readouterr()
+ assert "No Dockerfile found" in captured.err
+ assert "ubuntu|alpine" in captured.err
+
+ def test_skips_dockerfile_creation_if_exists(self, tmp_dir):
+ """Test that init doesn't overwrite existing Dockerfile."""
+ dockerfile = tmp_dir / "Dockerfile"
+ dockerfile.write_text("FROM existing:image\n")
+
+ args = argparse.Namespace(directory=tmp_dir, base="ubuntu")
+
+ result = cmd_init(args)
+
+ assert result == 0
+ # Dockerfile should be unchanged
+ assert dockerfile.read_text() == "FROM existing:image\n"
+
+ def test_uses_latest_when_version_not_found(self, tmp_dir, capsys):
+ """Test falls back to 'latest' when base not discovered."""
+ args = argparse.Namespace(directory=tmp_dir, base="ubuntu")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value={}),
+ patch("subprocess.run") as mock_run,
+ ):
+ mock_run.return_value = MagicMock(returncode=0)
+
+ result = cmd_init(args)
+
+ assert result == 0
+ dockerfile = tmp_dir / "Dockerfile"
+ content = dockerfile.read_text()
+ assert "FROM quicksand/ubuntu-base:latest" in content
+ captured = capsys.readouterr()
+ assert "using 'latest'" in captured.err
+
+ def test_returns_error_when_build_base_fails(self, tmp_dir):
+ """Test returns error when build-base fails."""
+ args = argparse.Namespace(directory=tmp_dir, base="ubuntu")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value=_mock_bases(tmp_dir)),
+ patch("subprocess.run") as mock_run,
+ patch("quicksand_image_tools.cli.cmd_build_base", return_value=1),
+ ):
+ mock_run.return_value = MagicMock(returncode=1)
+
+ result = cmd_init(args)
+
+ assert result == 1
+
+
+# ============================================================================
+# Tests for cmd_build_base
+# ============================================================================
+
+
+class TestCmdBuildBase:
+ """Tests for cmd_build_base function.
+
+ The Rust agent is compiled during Docker build via multi-stage build,
+ so we no longer copy agent.py to the build context.
+ """
+
+ def test_builds_single_base_image(self, tmp_dir):
+ """Test building a single base image."""
+ docker_dir = tmp_dir / "ubuntu_docker"
+ docker_dir.mkdir()
+ (docker_dir / "Dockerfile").write_text("FROM ubuntu:24.04\n")
+
+ bases = {"ubuntu": BaseImageInfo(name="ubuntu", docker_dir=docker_dir, version="24.04.0")}
+ args = argparse.Namespace(base="ubuntu")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value=bases),
+ patch("subprocess.run") as mock_run,
+ ):
+ mock_run.return_value = MagicMock(returncode=0)
+
+ result = cmd_build_base(args)
+
+ assert result == 0
+ call_args = mock_run.call_args
+ cmd = call_args[0][0]
+ assert "docker" in cmd
+ assert "build" in cmd
+ assert "-t" in cmd
+ assert "quicksand/ubuntu-base:24.04.0" in cmd
+ assert "quicksand/ubuntu-base:latest" in cmd
+ # Build should run in the docker_dir directly (no temp dir)
+ assert call_args[1]["cwd"] == docker_dir
+
+ def test_builds_all_base_images(self, tmp_dir):
+ """Test building all base images."""
+ ubuntu_dir = tmp_dir / "ubuntu_docker"
+ alpine_dir = tmp_dir / "alpine_docker"
+ ubuntu_dir.mkdir()
+ alpine_dir.mkdir()
+ (ubuntu_dir / "Dockerfile").write_text("FROM ubuntu:24.04\n")
+ (alpine_dir / "Dockerfile").write_text("FROM alpine:3.21\n")
+
+ bases = {
+ "ubuntu": BaseImageInfo(name="ubuntu", docker_dir=ubuntu_dir, version="24.04.0"),
+ "alpine": BaseImageInfo(name="alpine", docker_dir=alpine_dir, version="3.21.0"),
+ }
+ args = argparse.Namespace(base="all")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value=bases),
+ patch("subprocess.run") as mock_run,
+ ):
+ mock_run.return_value = MagicMock(returncode=0)
+
+ result = cmd_build_base(args)
+
+ assert result == 0
+ assert mock_run.call_count == 2
+
+ def test_warns_when_package_not_found(self, capsys):
+ """Test warns when base package not installed."""
+ args = argparse.Namespace(base="ubuntu")
+
+ with patch("quicksand_image_tools.cli.discover_bases", return_value={}):
+ result = cmd_build_base(args)
+
+ assert result == 0 # Still returns 0, just warns
+ captured = capsys.readouterr()
+ assert "ubuntu base not found" in captured.err
+ assert "install quicksand[ubuntu]" in captured.err
+
+ def test_returns_error_on_docker_build_failure(self, tmp_dir, capsys):
+ """Test returns error when docker build fails."""
+ docker_dir = tmp_dir / "docker"
+ docker_dir.mkdir()
+ (docker_dir / "Dockerfile").write_text("FROM ubuntu:24.04\n")
+
+ bases = {"ubuntu": BaseImageInfo(name="ubuntu", docker_dir=docker_dir, version="24.04.0")}
+ args = argparse.Namespace(base="ubuntu")
+
+ with (
+ patch("quicksand_image_tools.cli.discover_bases", return_value=bases),
+ patch("subprocess.run") as mock_run,
+ ):
+ mock_run.return_value = MagicMock(returncode=1, stderr="build failed")
+
+ result = cmd_build_base(args)
+
+ assert result == 1
+ captured = capsys.readouterr()
+ assert "Error building" in captured.err
+
+
+# ============================================================================
+# Tests for cmd_build_image
+# ============================================================================
+
+
+class TestCmdBuildImage:
+ """Tests for cmd_build_image function.
+
+ The Dockerfile should use multi-stage build to compile the Rust agent.
+ We no longer copy agent.py to the build context.
+ """
+
+ def test_builds_image_successfully(self, tmp_dir):
+ """Test successful image build."""
+ dockerfile = tmp_dir / "Dockerfile"
+ dockerfile.write_text("FROM quicksand/ubuntu-base:24.04.0\n")
+
+ args = argparse.Namespace(dockerfile=dockerfile, output=None, cache_dir=tmp_dir / "cache")
+
+ with patch("quicksand_image_tools.cli.build_image") as mock_build:
+ mock_build.return_value = tmp_dir / "output.qcow2"
+
+ result = cmd_build_image(args)
+
+ assert result == 0
+ mock_build.assert_called_once_with(
+ dockerfile,
+ output_path=None,
+ cache_dir=tmp_dir / "cache",
+ )
+
+ def test_error_when_dockerfile_not_found(self, tmp_dir, capsys):
+ """Test error when Dockerfile doesn't exist."""
+ dockerfile = tmp_dir / "nonexistent" / "Dockerfile"
+ args = argparse.Namespace(dockerfile=dockerfile, output=None, cache_dir=None)
+
+ result = cmd_build_image(args)
+
+ assert result == 1
+ captured = capsys.readouterr()
+ assert "Dockerfile not found" in captured.err
+
+ def test_returns_error_on_build_failure(self, tmp_dir, capsys):
+ """Test returns error when build fails."""
+ dockerfile = tmp_dir / "Dockerfile"
+ dockerfile.write_text("FROM quicksand/ubuntu-base:24.04.0\n")
+
+ args = argparse.Namespace(dockerfile=dockerfile, output=None, cache_dir=tmp_dir / "cache")
+
+ with patch("quicksand_image_tools.cli.build_image", side_effect=Exception("Build failed")):
+ result = cmd_build_image(args)
+
+ assert result == 1
+ captured = capsys.readouterr()
+ assert "Build failed" in captured.err
+
+ def test_passes_output_path(self, tmp_dir):
+ """Test that output path is passed to build_image."""
+ dockerfile = tmp_dir / "Dockerfile"
+ dockerfile.write_text("FROM quicksand/ubuntu-base:24.04.0\n")
+ output = tmp_dir / "custom.qcow2"
+
+ args = argparse.Namespace(dockerfile=dockerfile, output=output, cache_dir=None)
+
+ with patch("quicksand_image_tools.cli.build_image") as mock_build:
+ mock_build.return_value = output
+
+ cmd_build_image(args)
+
+ mock_build.assert_called_once_with(
+ dockerfile,
+ output_path=output,
+ cache_dir=None,
+ )
+
+
+# ============================================================================
+# Tests for main() argument parsing
+# ============================================================================
+
+
+class TestMainArgumentParsing:
+ """Tests for main() CLI argument parsing."""
+
+ def test_init_with_directory_and_base(self):
+ """Test parsing init command with directory and base."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_init", return_value=0) as mock_init,
+ patch("sys.argv", ["quicksand-image-tools", "init", "./my-image", "ubuntu"]),
+ ):
+ result = main()
+
+ assert result == 0
+ args = mock_init.call_args[0][0]
+ assert args.directory == Path("./my-image")
+ assert args.base == "ubuntu"
+
+ def test_init_default_directory(self):
+ """Test init command defaults to current directory."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_init", return_value=0) as mock_init,
+ patch("sys.argv", ["quicksand-image-tools", "init"]),
+ ):
+ main()
+
+ args = mock_init.call_args[0][0]
+ assert args.directory == Path(".")
+ assert args.base is None
+
+ def test_build_base_single(self):
+ """Test parsing build-base with single base."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_build_base", return_value=0) as mock_build,
+ patch("sys.argv", ["quicksand-image-tools", "build-base", "alpine"]),
+ ):
+ main()
+
+ args = mock_build.call_args[0][0]
+ assert args.base == "alpine"
+
+ def test_build_base_defaults_to_all(self):
+ """Test build-base defaults to 'all'."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_build_base", return_value=0) as mock_build,
+ patch("sys.argv", ["quicksand-image-tools", "build-base"]),
+ ):
+ main()
+
+ args = mock_build.call_args[0][0]
+ assert args.base == "all"
+
+ def test_build_image_with_output(self):
+ """Test parsing build-image with output option."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_build_image", return_value=0) as mock_build,
+ patch(
+ "sys.argv",
+ ["quicksand-image-tools", "build-image", "Dockerfile", "-o", "out.qcow2"],
+ ),
+ ):
+ main()
+
+ args = mock_build.call_args[0][0]
+ assert args.dockerfile == Path("Dockerfile")
+ assert args.output == Path("out.qcow2")
+
+ def test_verbose_flag(self):
+ """Test verbose flag is parsed."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_init", return_value=0),
+ patch("quicksand_image_tools.cli._setup_logging") as mock_logging,
+ patch("sys.argv", ["quicksand-image-tools", "-v", "init", ".", "ubuntu"]),
+ ):
+ main()
+
+ # Verbose should be True
+ mock_logging.assert_called_with(True)
+
+ def test_package_init_parsed(self):
+ """Test parsing package init command."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_package_init", return_value=0) as mock_pkg_init,
+ patch("sys.argv", ["quicksand-image-tools", "package", "init", "mylinux", "ubuntu"]),
+ ):
+ result = main()
+
+ assert result == 0
+ args = mock_pkg_init.call_args[0][0]
+ assert args.name == "mylinux"
+ assert args.base == "ubuntu"
+ assert args.output_dir is None
+
+ def test_package_init_with_output_dir(self):
+ """Test parsing package init with --output-dir."""
+ with (
+ patch("quicksand_image_tools.cli.cmd_package_init", return_value=0) as mock_pkg_init,
+ patch(
+ "sys.argv",
+ [
+ "quicksand-image-tools",
+ "package",
+ "init",
+ "mylinux",
+ "ubuntu",
+ "--output-dir",
+ "/tmp/pkg",
+ ],
+ ),
+ ):
+ main()
+
+ args = mock_pkg_init.call_args[0][0]
+ assert args.output_dir == Path("/tmp/pkg")
+
+
+# ============================================================================
diff --git a/tests/unit/test_disk.py b/tests/unit/test_disk.py
new file mode 100644
index 0000000..a6f9c68
--- /dev/null
+++ b/tests/unit/test_disk.py
@@ -0,0 +1,340 @@
+"""Unit tests for OverlayManager."""
+
+from __future__ import annotations
+
+import json
+from typing import ClassVar
+from unittest.mock import MagicMock, patch
+
+import pytest
+from quicksand_core._types import GuestCommands
+from quicksand_core.qemu.overlay import OverlayManager
+from quicksand_core.sandbox import ExecuteResult
+from quicksand_core.sandbox._lifecycle import _LifecycleMixin
+
+
+class _MockSandbox(_LifecycleMixin):
+ """Minimal concrete sandbox for testing _LifecycleMixin filesystem expansion."""
+
+ def __init__(self, execute_fn):
+ self._execute_fn = execute_fn
+
+ # Protocol requirements (flat fields)
+ config = None
+ _is_running = True
+ _process_manager = None
+ _smb_server = None
+ _progress_callback = None
+ _overlay_manager = None
+ _runtime_info = None
+ _image = None
+ _accel = None
+ _overlay_path = None
+ _temp_dir = None
+ _agent_client = None
+ _agent_port = None
+ _agent_token = None
+ _qmp_client = None
+ _qmp_port = None
+ _qmp_checkpoints: ClassVar[list[str]] = []
+ _vnc_port = None
+ _save_name = None
+ _workspace = None
+ _dynamic_mounts: ClassVar[list] = []
+
+ @property
+ def is_running(self) -> bool:
+ return True
+
+ async def execute(
+ self,
+ command,
+ timeout=30,
+ cwd=None,
+ shell="",
+ on_stdout=None,
+ on_stderr=None,
+ exclusive=False,
+ ):
+ return self._execute_fn(command, timeout)
+
+ async def _send_request(self, method, params, timeout=30):
+ raise NotImplementedError
+
+ async def _graceful_shutdown(self):
+ raise NotImplementedError
+
+ async def _mount_shares(self):
+ raise NotImplementedError
+
+ async def _cleanup_mounts(self):
+ raise NotImplementedError
+
+ async def save(self, name, *, workspace=None, compress=False, delete_checkpoints=False):
+ raise NotImplementedError
+
+
+class TestCreateOverlay:
+ """Tests for OverlayManager.create_overlay."""
+
+ def test_creates_overlay_from_base(self, tmp_dir):
+ """Test creating a basic overlay backed by a base image."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ image_path = tmp_dir / "base.qcow2"
+ image_path.write_bytes(b"fake-image")
+ overlay_path = tmp_dir / "overlay.qcow2"
+
+ dm = OverlayManager(qemu_img)
+ with patch("subprocess.run") as mock_run:
+ dm.create_overlay(image_path, overlay_path)
+
+ mock_run.assert_called_once()
+ args = mock_run.call_args[0][0]
+ assert str(qemu_img) in args
+ assert "create" in args
+ assert str(overlay_path) in args
+
+ def test_creates_overlay_with_disk_size(self, tmp_dir):
+ """Test creating an overlay and resizing it."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ image_path = tmp_dir / "base.qcow2"
+ image_path.write_bytes(b"fake-image")
+ overlay_path = tmp_dir / "overlay.qcow2"
+
+ dm = OverlayManager(qemu_img)
+ with patch("subprocess.run") as mock_run:
+ dm.create_overlay(image_path, overlay_path, disk_size="4G")
+
+ # Should be called twice: create + resize
+ assert mock_run.call_count == 2
+ resize_args = mock_run.call_args_list[1][0][0]
+ assert "resize" in resize_args
+ assert "4G" in resize_args
+
+ def test_creates_overlay_from_restore_chain(self, tmp_dir):
+ """Test creating overlay from restore chain creates fresh overlay on top."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ image_path = tmp_dir / "base.qcow2"
+ image_path.write_bytes(b"fake-image")
+ overlay_path = tmp_dir / "overlay.qcow2"
+
+ chain_overlay = tmp_dir / "restored.qcow2"
+ chain_overlay.write_bytes(b"checkpoint-data")
+
+ dm = OverlayManager(qemu_img)
+
+ # Mock get_backing_file to return base image (chain already correct)
+ def mock_run_side_effect(cmd, **kwargs):
+ if "info" in cmd:
+ mock_result = MagicMock()
+ mock_result.stdout = json.dumps({"backing-filename": str(image_path.absolute())})
+ return mock_result
+ return MagicMock()
+
+ with patch("subprocess.run", side_effect=mock_run_side_effect) as mock_run:
+ dm.create_overlay(
+ image_path,
+ overlay_path,
+ restore_chain=[chain_overlay],
+ )
+
+ # Should call qemu-img info (get_backing_file) then qemu-img create
+ create_calls = [c for c in mock_run.call_args_list if "create" in c[0][0]]
+ assert len(create_calls) == 1
+ create_args = create_calls[0][0][0]
+ assert "-b" in create_args
+ assert str(chain_overlay.absolute()) in create_args
+
+
+class TestGetBackingFile:
+ """Tests for OverlayManager.get_backing_file."""
+
+ def test_returns_backing_filename(self, tmp_dir):
+ """Test parsing backing filename from qemu-img info output."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.touch()
+
+ dm = OverlayManager(qemu_img)
+ mock_result = MagicMock()
+ mock_result.stdout = json.dumps({"backing-filename": "/path/to/base.qcow2"})
+
+ with patch("subprocess.run", return_value=mock_result):
+ result = dm.get_backing_file(overlay)
+
+ assert result == "/path/to/base.qcow2"
+
+ def test_returns_none_when_no_backing(self, tmp_dir):
+ """Test returns None for overlays without a backing file."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.touch()
+
+ dm = OverlayManager(qemu_img)
+ mock_result = MagicMock()
+ mock_result.stdout = json.dumps({"format": "qcow2"})
+
+ with patch("subprocess.run", return_value=mock_result):
+ result = dm.get_backing_file(overlay)
+
+ assert result is None
+
+
+class TestGetOverlayChain:
+ """Tests for OverlayManager.get_overlay_chain."""
+
+ def test_single_overlay_chain(self, tmp_dir):
+ """Chain with one overlay directly backed by base."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ base = tmp_dir / "base.qcow2"
+ base.touch()
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.touch()
+
+ dm = OverlayManager(qemu_img)
+ with patch.object(dm, "get_backing_file", return_value=str(base)):
+ chain = dm.get_overlay_chain(overlay, base)
+
+ assert chain == [overlay]
+
+ def test_multi_overlay_chain(self, tmp_dir):
+ """Chain with multiple overlays returns bottom-to-top order."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ base = tmp_dir / "base.qcow2"
+ base.touch()
+ overlay_0 = tmp_dir / "overlay-0.qcow2"
+ overlay_0.touch()
+ overlay_1 = tmp_dir / "overlay-1.qcow2"
+ overlay_1.touch()
+
+ dm = OverlayManager(qemu_img)
+
+ def mock_backing(path):
+ if path == overlay_1:
+ return str(overlay_0)
+ if path == overlay_0:
+ return str(base)
+ return None
+
+ with patch.object(dm, "get_backing_file", side_effect=mock_backing):
+ chain = dm.get_overlay_chain(overlay_1, base)
+
+ assert chain == [overlay_0, overlay_1]
+
+
+class TestPrepareRestoredChain:
+ """Tests for OverlayManager._prepare_restored_chain."""
+
+ def test_rebases_when_paths_differ(self, tmp_dir):
+ """Calls qemu-img rebase -u when backing path doesn't match."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ base = tmp_dir / "base.qcow2"
+ base.touch()
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.touch()
+
+ dm = OverlayManager(qemu_img)
+
+ def mock_run_side_effect(cmd, **kwargs):
+ mock_result = MagicMock()
+ if "info" in cmd:
+ mock_result.stdout = json.dumps({"backing-filename": "/old/tmp/base.qcow2"})
+ return mock_result
+
+ with patch("subprocess.run", side_effect=mock_run_side_effect) as mock_run:
+ dm._prepare_restored_chain([overlay], base)
+
+ rebase_calls = [c for c in mock_run.call_args_list if "rebase" in c[0][0]]
+ assert len(rebase_calls) == 1
+ assert "-u" in rebase_calls[0][0][0]
+
+ def test_skips_rebase_when_path_matches(self, tmp_dir):
+ """Does not rebase when backing path already matches."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ base = tmp_dir / "base.qcow2"
+ base.touch()
+ overlay = tmp_dir / "overlay.qcow2"
+ overlay.touch()
+
+ dm = OverlayManager(qemu_img)
+
+ def mock_run_side_effect(cmd, **kwargs):
+ mock_result = MagicMock()
+ if "info" in cmd:
+ mock_result.stdout = json.dumps({"backing-filename": str(base.absolute())})
+ return mock_result
+
+ with patch("subprocess.run", side_effect=mock_run_side_effect) as mock_run:
+ dm._prepare_restored_chain([overlay], base)
+
+ rebase_calls = [c for c in mock_run.call_args_list if "rebase" in c[0][0]]
+ assert len(rebase_calls) == 0
+
+
+class TestResizeOverlay:
+ """Tests for OverlayManager.resize_overlay."""
+
+ def test_resize_overlay(self, tmp_dir):
+ """Test resizing an overlay."""
+ qemu_img = tmp_dir / "qemu-img"
+ qemu_img.touch()
+ overlay_path = tmp_dir / "overlay.qcow2"
+ overlay_path.touch()
+
+ dm = OverlayManager(qemu_img)
+ with patch("subprocess.run") as mock_run:
+ dm.resize_overlay(overlay_path, "8G")
+
+ mock_run.assert_called_once()
+ args = mock_run.call_args[0][0]
+ assert "resize" in args
+ assert "8G" in args
+
+
+class TestExpandGuestFilesystem:
+ """Tests for _LifecycleMixin._expand_guest_filesystem."""
+
+ @pytest.mark.asyncio
+ async def test_expands_partitioned_disk(self):
+ """Test expanding a partitioned disk layout."""
+ calls = []
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ calls.append(cmd)
+ if cmd == GuestCommands.DETECT_DISK_LAYOUT:
+ return ExecuteResult(stdout="partitioned\n", stderr="", exit_code=0)
+ return ExecuteResult(stdout="ok", stderr="", exit_code=0)
+
+ sb = _MockSandbox(mock_execute)
+ await sb._expand_guest_filesystem()
+
+ assert GuestCommands.DETECT_DISK_LAYOUT in calls
+ assert GuestCommands.GROWPART in calls
+ assert GuestCommands.RESIZE_PARTITION in calls
+
+ @pytest.mark.asyncio
+ async def test_expands_whole_disk(self):
+ """Test expanding a whole-disk filesystem."""
+ calls = []
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ calls.append(cmd)
+ if cmd == GuestCommands.DETECT_DISK_LAYOUT:
+ return ExecuteResult(stdout="whole\n", stderr="", exit_code=0)
+ return ExecuteResult(stdout="ok", stderr="", exit_code=0)
+
+ sb = _MockSandbox(mock_execute)
+ await sb._expand_guest_filesystem()
+
+ assert GuestCommands.DETECT_DISK_LAYOUT in calls
+ assert GuestCommands.RESIZE_WHOLE_DISK in calls
+ assert GuestCommands.GROWPART not in calls
diff --git a/tests/unit/test_mounts.py b/tests/unit/test_mounts.py
new file mode 100644
index 0000000..d150467
--- /dev/null
+++ b/tests/unit/test_mounts.py
@@ -0,0 +1,371 @@
+"""Unit tests for _MountMixin (CIFS-based mounts)."""
+
+from __future__ import annotations
+
+import contextlib
+from typing import ClassVar
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from quicksand_core._types import Mount, MountHandle, MountOptions, NetworkMode
+from quicksand_core.sandbox import ExecuteResult, SandboxConfig
+from quicksand_core.sandbox._mounts import _MountMixin
+
+
+class _MockSandbox(_MountMixin):
+ """Minimal concrete sandbox for testing _MountMixin in isolation."""
+
+ def __init__(self, execute_fn, mounts, *, network_mode=NetworkMode.FULL):
+ self.config = SandboxConfig(
+ image="ubuntu",
+ mounts=mounts,
+ network_mode=network_mode,
+ )
+ self._smb_server = None
+ self._dynamic_mounts: list[MountHandle] = []
+ self._execute_fn = execute_fn
+
+ # Protocol requirements (flat fields)
+ _is_running = True
+ _process_manager = None
+ _progress_callback = None
+ _overlay_manager = None
+ _runtime_info = None
+ _image = None
+ _accel = None
+ _overlay_path = None
+ _temp_dir = None
+ _agent_client = None
+ _agent_port = None
+ _agent_token = None
+ _qmp_client = None
+ _qmp_port = None
+ _qmp_checkpoints: ClassVar[list[str]] = []
+ _vnc_port = None
+ _save_name = None
+ _workspace = None
+
+ @property
+ def is_running(self) -> bool:
+ return True
+
+ async def execute(
+ self,
+ command,
+ timeout=30,
+ cwd=None,
+ shell="",
+ on_stdout=None,
+ on_stderr=None,
+ exclusive=False,
+ ):
+ return self._execute_fn(command, timeout)
+
+ async def _send_request(self, method, params, timeout=30):
+ raise NotImplementedError
+
+ async def _graceful_shutdown(self):
+ raise NotImplementedError
+
+ async def save(self, name, *, workspace=None, compress=False, delete_checkpoints=False):
+ raise NotImplementedError
+
+ @property
+ def vnc_port(self):
+ return None
+
+ async def type_text(self, text):
+ raise NotImplementedError
+
+ async def press_key(self, *keys):
+ raise NotImplementedError
+
+ async def mouse_move(self, x, y):
+ raise NotImplementedError
+
+ async def mouse_click(self, button="left", *, double=False):
+ raise NotImplementedError
+
+ async def screenshot(self, path):
+ raise NotImplementedError
+
+ async def query_display_size(self):
+ raise NotImplementedError
+
+ async def query_mouse_position(self):
+ raise NotImplementedError
+
+
+class TestMountShares:
+ """Tests for _MountMixin._mount_shares (boot-time CIFS mounts)."""
+
+ @pytest.mark.asyncio
+ @patch("quicksand_core.sandbox._mounts.create_smb_server")
+ @patch("quicksand_core.sandbox._mounts.asyncio.sleep", new_callable=AsyncMock)
+ async def test_mounts_single_share(self, mock_sleep, mock_create_server):
+ """Test mounting a single share via CIFS."""
+ commands = []
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ commands.append(cmd)
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mock_server = MagicMock()
+ mock_server.add_share.return_value = "QUICKSAND0"
+ mock_server.credentials = ("guest", "")
+ mock_create_server.return_value = mock_server
+
+ mounts = [Mount(host="/host/data", guest="/mnt/data")]
+ sb = _MockSandbox(mock_execute, mounts)
+ await sb._mount_shares()
+
+ # Should have called add_share on the SMB server
+ mock_server.add_share.assert_called_once_with("/host/data", False)
+ # Should have mkdir + CIFS mount commands
+ assert any("mkdir -p /mnt/data" in c for c in commands)
+ assert any("mount -t cifs" in c and "QUICKSAND0" in c for c in commands)
+
+ @pytest.mark.asyncio
+ @patch("quicksand_core.sandbox._mounts.create_smb_server")
+ @patch("quicksand_core.sandbox._mounts.asyncio.sleep", new_callable=AsyncMock)
+ async def test_mounts_readonly_share(self, mock_sleep, mock_create_server):
+ """Test mounting a readonly share via CIFS."""
+ commands = []
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ commands.append(cmd)
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mock_server = MagicMock()
+ mock_server.add_share.return_value = "QUICKSAND0"
+ mock_server.credentials = ("guest", "")
+ mock_create_server.return_value = mock_server
+
+ mounts = [Mount(host="/host/data", guest="/mnt/data", readonly=True)]
+ sb = _MockSandbox(mock_execute, mounts)
+ await sb._mount_shares()
+
+ mock_server.add_share.assert_called_once_with("/host/data", True)
+ mount_cmd = next(c for c in commands if "mount -t cifs" in c)
+ assert ",ro" in mount_cmd
+
+ @pytest.mark.asyncio
+ @patch("quicksand_core.sandbox._mounts.create_smb_server")
+ @patch("quicksand_core.sandbox._mounts.asyncio.sleep", new_callable=AsyncMock)
+ async def test_retries_on_failure(self, mock_sleep, mock_create_server):
+ """Test that mount retries on transient failures."""
+ attempt = [0]
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ if "mount -t cifs" in cmd:
+ attempt[0] += 1
+ if attempt[0] < 3:
+ return ExecuteResult(stdout="", stderr="mount error", exit_code=1)
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mock_server = MagicMock()
+ mock_server.add_share.return_value = "QUICKSAND0"
+ mock_server.credentials = ("guest", "")
+ mock_create_server.return_value = mock_server
+
+ mounts = [Mount(host="/host/data", guest="/mnt/data")]
+ sb = _MockSandbox(mock_execute, mounts)
+ await sb._mount_shares()
+
+ assert attempt[0] == 3 # Succeeded on third attempt
+
+ @pytest.mark.asyncio
+ @patch("quicksand_core.sandbox._mounts.create_smb_server")
+ @patch("quicksand_core.sandbox._mounts.asyncio.sleep", new_callable=AsyncMock)
+ async def test_raises_after_max_retries(self, mock_sleep, mock_create_server):
+ """Test that mount raises after exhausting retries."""
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ if "mount -t cifs" in cmd:
+ return ExecuteResult(stdout="", stderr="mount error", exit_code=1)
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mock_server = MagicMock()
+ mock_server.add_share.return_value = "QUICKSAND0"
+ mock_server.credentials = ("guest", "")
+ mock_create_server.return_value = mock_server
+
+ mounts = [Mount(host="/host/data", guest="/mnt/data")]
+ sb = _MockSandbox(mock_execute, mounts)
+
+ with pytest.raises(RuntimeError, match="Failed to mount CIFS share"):
+ await sb._mount_shares()
+
+ @pytest.mark.asyncio
+ @patch("quicksand_core.sandbox._mounts.create_smb_server")
+ @patch("quicksand_core.sandbox._mounts.asyncio.sleep", new_callable=AsyncMock)
+ async def test_unmounts_on_failure(self, mock_sleep, mock_create_server):
+ """Test that successful mounts are rolled back on failure."""
+ commands = []
+ share_counter = [0]
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ commands.append(cmd)
+ # Second CIFS mount always fails
+ if "mount -t cifs" in cmd and "QUICKSAND1" in cmd:
+ return ExecuteResult(stdout="", stderr="error", exit_code=1)
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mock_server = MagicMock()
+ mock_server.credentials = ("guest", "")
+
+ def add_share(host_path, readonly):
+ name = f"QUICKSAND{share_counter[0]}"
+ share_counter[0] += 1
+ return name
+
+ mock_server.add_share.side_effect = add_share
+ mock_create_server.return_value = mock_server
+
+ mounts = [
+ Mount(host="/host/a", guest="/mnt/a"),
+ Mount(host="/host/b", guest="/mnt/b"),
+ ]
+ sb = _MockSandbox(mock_execute, mounts)
+
+ with contextlib.suppress(RuntimeError):
+ await sb._mount_shares()
+
+ # First mount should have been unmounted during rollback
+ assert any("umount /mnt/a" in c for c in commands)
+ # SMB share should also be removed
+ mock_server.remove_share.assert_any_call("QUICKSAND0")
+
+ @pytest.mark.asyncio
+ async def test_raises_without_full_network(self):
+ """Test that mounts raise without network_mode=FULL or MOUNTS_ONLY."""
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mounts = [Mount(host="/host/data", guest="/mnt/data")]
+ sb = _MockSandbox(mock_execute, mounts, network_mode=NetworkMode.NONE)
+
+ with pytest.raises(ValueError, match="network_mode=FULL or MOUNTS_ONLY"):
+ await sb._mount_shares()
+
+
+class TestDynamicMount:
+ """Tests for _MountMixin.mount() and unmount()."""
+
+ @pytest.mark.asyncio
+ @patch("quicksand_core.sandbox._mounts.create_smb_server")
+ async def test_mount_returns_handle(self, mock_create_server):
+ """Test that mount() returns a MountHandle."""
+ commands = []
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ commands.append(cmd)
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mock_server = MagicMock()
+ mock_server.add_share.return_value = "QUICKSAND0"
+ mock_server.credentials = ("guest", "")
+ mock_create_server.return_value = mock_server
+
+ sb = _MockSandbox(mock_execute, [])
+ handle = await sb.mount("/host/data", "/mnt/data")
+
+ assert isinstance(handle, MountHandle)
+ assert handle.host == "/host/data"
+ assert handle.guest == "/mnt/data"
+ assert handle.readonly is False
+ assert handle in sb.active_mounts
+
+ @pytest.mark.asyncio
+ @patch("quicksand_core.sandbox._mounts.create_smb_server")
+ async def test_unmount_removes_handle(self, mock_create_server):
+ """Test that unmount() removes the handle from active_mounts."""
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ mock_server = MagicMock()
+ mock_server.add_share.return_value = "QUICKSAND0"
+ mock_server.credentials = ("guest", "")
+ mock_create_server.return_value = mock_server
+
+ sb = _MockSandbox(mock_execute, [])
+ handle = await sb.mount("/host/data", "/mnt/data")
+ await sb.unmount(handle)
+
+ assert handle not in sb.active_mounts
+ mock_server.remove_share.assert_called_once_with("QUICKSAND0")
+
+ @pytest.mark.asyncio
+ async def test_mount_raises_with_network_none(self):
+ """Test that mount() raises with network_mode=NONE."""
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ sb = _MockSandbox(mock_execute, [], network_mode=NetworkMode.NONE)
+
+ with pytest.raises(RuntimeError, match="network_mode=FULL or MOUNTS_ONLY"):
+ await sb.mount("/host/data", "/mnt/data")
+
+
+class TestCleanupMounts:
+ """Tests for _MountMixin._cleanup_mounts."""
+
+ @pytest.mark.asyncio
+ async def test_cleanup_no_smb(self):
+ """Test cleanup when no SMB server is running."""
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ sb = _MockSandbox(mock_execute, [])
+ errors = await _MountMixin._cleanup_mounts(sb)
+ assert errors == []
+
+ @pytest.mark.asyncio
+ async def test_cleanup_stops_smb_server(self):
+ """Test cleanup stops the SMB server."""
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ sb = _MockSandbox(mock_execute, [])
+ mock_smb = MagicMock()
+ sb._smb_server = mock_smb
+
+ errors = await _MountMixin._cleanup_mounts(sb)
+ assert errors == []
+ mock_smb.stop.assert_called_once()
+ assert sb._smb_server is None
+
+ @pytest.mark.asyncio
+ async def test_cleanup_returns_errors(self):
+ """Test cleanup returns errors from SMB server stop."""
+
+ def mock_execute(cmd: str, timeout: float) -> ExecuteResult:
+ return ExecuteResult(stdout="", stderr="", exit_code=0)
+
+ sb = _MockSandbox(mock_execute, [])
+ mock_smb = MagicMock()
+ sb._smb_server = mock_smb
+ mock_smb.stop.side_effect = RuntimeError("stop failed")
+
+ errors = await _MountMixin._cleanup_mounts(sb)
+ assert len(errors) == 1
+ assert errors[0][0] == "SMB server"
+
+
+class TestCifsOpts:
+ """Tests for MountOptions.cifs_opts static method."""
+
+ def test_cifs_opts_authenticated(self):
+ """Test that cifs_opts produces NTLMSSP options when password is set."""
+ result = MountOptions.cifs_opts("myuser", "mypass")
+ assert result == "username=myuser,password=mypass,sec=ntlmssp,vers=3.0"
+
+ def test_cifs_opts_anonymous(self):
+ """Test that cifs_opts produces sec=none for empty password."""
+ result = MountOptions.cifs_opts("guest", "")
+ assert result == "username=guest,password=,sec=none,vers=3.0"
diff --git a/tests/unit/test_quicksand_exports.py b/tests/unit/test_quicksand_exports.py
new file mode 100644
index 0000000..c01ea12
--- /dev/null
+++ b/tests/unit/test_quicksand_exports.py
@@ -0,0 +1,68 @@
+"""Unit tests for quicksand package exports."""
+
+from __future__ import annotations
+
+
+class TestQuicksandExports:
+ """Tests for quicksand package exports."""
+
+ def test_core_exports(self):
+ """Test core classes are exported."""
+ from quicksand import (
+ ExecuteResult,
+ Mount,
+ Sandbox,
+ SandboxConfig,
+ )
+
+ assert Sandbox is not None
+ assert SandboxConfig is not None
+ assert Mount is not None
+ assert ExecuteResult is not None
+
+ def test_runtime_exports(self):
+ """Test runtime functions are exported."""
+ from quicksand import (
+ RuntimeInfo,
+ get_accelerator,
+ get_machine_type,
+ get_runtime,
+ is_runtime_available,
+ )
+
+ assert get_runtime is not None
+ assert RuntimeInfo is not None
+ assert is_runtime_available is not None
+ assert get_accelerator is not None
+ assert get_machine_type is not None
+
+ def test_platform_exports(self):
+ """Test platform functions are exported."""
+ from quicksand import (
+ PlatformConfig,
+ get_platform_config,
+ )
+
+ assert get_platform_config is not None
+ assert PlatformConfig is not None
+
+ def test_accelerator_exports(self):
+ """Test accelerator functions are exported."""
+ from quicksand import AcceleratorStatus, detect_accelerator
+
+ assert detect_accelerator is not None
+ assert AcceleratorStatus is not None
+
+ def test_ubuntu_exports_when_installed(self):
+ """Test Ubuntu exports are available when installed."""
+ from quicksand import UbuntuSandbox
+
+ # These should not be None since quicksand-ubuntu is installed
+ assert UbuntuSandbox is not None
+
+ def test_version(self):
+ """Test version is available."""
+ import quicksand
+
+ assert hasattr(quicksand, "__version__")
+ assert quicksand.__version__ == "0.1.0"
diff --git a/tests/unit/test_ubuntu.py b/tests/unit/test_ubuntu.py
new file mode 100644
index 0000000..32e2ae2
--- /dev/null
+++ b/tests/unit/test_ubuntu.py
@@ -0,0 +1,75 @@
+"""Unit tests for quicksand_ubuntu package."""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from quicksand_core.sandbox import Sandbox
+from quicksand_ubuntu import UbuntuSandbox
+
+
+class TestUbuntuImageProvider:
+ """Tests for the _UbuntuImageProvider.resolve() method."""
+
+ def test_resolve_raises_when_no_image(self):
+ """Test that resolve raises FileNotFoundError when image is not built."""
+ from quicksand_ubuntu import _UbuntuImageProvider
+
+ provider = _UbuntuImageProvider()
+ # Use an architecture that will never have an image built
+ with pytest.raises(FileNotFoundError):
+ provider.resolve(arch="i386")
+
+ def test_resolve_returns_resolved_image(self):
+ """Test that resolve returns a ResolvedImage with correct fields."""
+ from quicksand_core._types import ResolvedImage
+ from quicksand_ubuntu import _UbuntuImageProvider
+
+ provider = _UbuntuImageProvider()
+ # This will raise if no image is installed, so we test the type
+ try:
+ result = provider.resolve()
+ assert isinstance(result, ResolvedImage)
+ assert result.name == "ubuntu"
+ assert result.chain is not None and len(result.chain) > 0
+ except FileNotFoundError:
+ pytest.skip("Ubuntu image not built/installed")
+
+
+class TestUbuntuSandbox:
+ """Tests for UbuntuSandbox class."""
+
+ def test_is_sandbox_subclass(self):
+ """Test that UbuntuSandbox is a Sandbox subclass."""
+ assert issubclass(UbuntuSandbox, Sandbox)
+
+ def test_creates_sandbox_with_default_config(self):
+ """Test that UbuntuSandbox creates a Sandbox with default config."""
+ sandbox = UbuntuSandbox()
+ assert isinstance(sandbox, Sandbox)
+ assert sandbox.config is not None
+ assert sandbox.config.image == "ubuntu"
+
+ def test_creates_sandbox_with_custom_kwargs(self):
+ """Test that UbuntuSandbox accepts custom kwargs."""
+ sandbox = UbuntuSandbox(memory="4G", cpus=2)
+ assert sandbox.config.memory == "4G"
+ assert sandbox.config.cpus == 2
+
+ def test_is_running_property(self):
+ """Test is_running property."""
+ sandbox = UbuntuSandbox()
+ assert sandbox.is_running is False
+
+ @pytest.mark.asyncio
+ async def test_context_manager(self):
+ """Test context manager interface."""
+ sandbox = UbuntuSandbox()
+ with (
+ patch.object(sandbox, "start", new_callable=AsyncMock) as mock_start,
+ patch.object(sandbox, "stop", new_callable=AsyncMock) as mock_stop,
+ ):
+ async with sandbox:
+ mock_start.assert_called_once()
+ mock_stop.assert_called_once()
diff --git a/uv.lock b/uv.lock
new file mode 100644
index 0000000..a2438ef
--- /dev/null
+++ b/uv.lock
@@ -0,0 +1,1540 @@
+version = 1
+revision = 3
+requires-python = ">=3.11"
+
+[manifest]
+members = [
+ "aif-agent-sandbox",
+ "aif-cua-agent-sandbox",
+ "quicksand",
+ "quicksand-alpine",
+ "quicksand-alpine-desktop",
+ "quicksand-base-scaffold",
+ "quicksand-build-tools",
+ "quicksand-core",
+ "quicksand-gh-runners",
+ "quicksand-image-tools",
+ "quicksand-overlay-scaffold",
+ "quicksand-qemu",
+ "quicksand-smb",
+ "quicksand-ubuntu",
+ "quicksand-ubuntu-desktop",
+]
+constraints = [{ name = "setuptools", specifier = ">=78.1.1" }]
+overrides = [{ name = "httpx", specifier = ">=0.27,<1" }]
+
+[manifest.dependency-groups]
+dev = [
+ { name = "hatchling" },
+ { name = "keyring" },
+ { name = "keyrings-artifacts" },
+ { name = "poethepoet" },
+ { name = "pytest" },
+ { name = "pytest-asyncio" },
+ { name = "pytest-timeout" },
+ { name = "ruff" },
+ { name = "twine" },
+ { name = "ty" },
+ { name = "uv-release", specifier = "==0.28.1" },
+]
+
+[[package]]
+name = "aif-agent-sandbox"
+version = "0.3.4"
+source = { editable = "packages/contrib/aif-agent-sandbox" }
+dependencies = [
+ { name = "quicksand-core" },
+ { name = "quicksand-ubuntu" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "quicksand-core", editable = "packages/quicksand-core" },
+ { name = "quicksand-ubuntu", editable = "packages/quicksand-ubuntu" },
+]
+
+[[package]]
+name = "aif-cua-agent-sandbox"
+version = "0.2.4"
+source = { editable = "packages/contrib/aif-cua-agent-sandbox" }
+dependencies = [
+ { name = "aif-agent-sandbox" },
+ { name = "quicksand-core" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "aif-agent-sandbox", editable = "packages/contrib/aif-agent-sandbox" },
+ { name = "quicksand-core", editable = "packages/quicksand-core" },
+]
+
+[[package]]
+name = "annotated-types"
+version = "0.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081, upload-time = "2024-05-20T21:33:25.928Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" },
+]
+
+[[package]]
+name = "anyio"
+version = "4.13.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "idna" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/19/14/2c5dd9f512b66549ae92767a9c7b330ae88e1932ca57876909410251fe13/anyio-4.13.0.tar.gz", hash = "sha256:334b70e641fd2221c1505b3890c69882fe4a2df910cba14d97019b90b24439dc", size = 231622, upload-time = "2026-03-24T12:59:09.671Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" },
+]
+
+[[package]]
+name = "azure-core"
+version = "1.39.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "requests" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/34/83/bbde3faa84ddcb8eb0eca4b3ffb3221252281db4ce351300fe248c5c70b1/azure_core-1.39.0.tar.gz", hash = "sha256:8a90a562998dd44ce84597590fff6249701b98c0e8797c95fcdd695b54c35d74", size = 367531, upload-time = "2026-03-19T01:31:29.461Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/d6/8ebcd05b01a580f086ac9a97fb9fac65c09a4b012161cc97c21a336e880b/azure_core-1.39.0-py3-none-any.whl", hash = "sha256:4ac7b70fab5438c3f68770649a78daf97833caa83827f91df9c14e0e0ea7d34f", size = 218318, upload-time = "2026-03-19T01:31:31.25Z" },
+]
+
+[[package]]
+name = "azure-identity"
+version = "1.25.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "azure-core" },
+ { name = "cryptography" },
+ { name = "msal" },
+ { name = "msal-extensions" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c5/0e/3a63efb48aa4a5ae2cfca61ee152fbcb668092134d3eb8bfda472dd5c617/azure_identity-1.25.3.tar.gz", hash = "sha256:ab23c0d63015f50b630ef6c6cf395e7262f439ce06e5d07a64e874c724f8d9e6", size = 286304, upload-time = "2026-03-13T01:12:20.892Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/49/9a/417b3a533e01953a7c618884df2cb05a71e7b68bdbce4fbdb62349d2a2e8/azure_identity-1.25.3-py3-none-any.whl", hash = "sha256:f4d0b956a8146f30333e071374171f3cfa7bdb8073adb8c3814b65567aa7447c", size = 192138, upload-time = "2026-03-13T01:12:22.951Z" },
+]
+
+[[package]]
+name = "azure-mgmt-compute"
+version = "37.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "azure-mgmt-core" },
+ { name = "isodate" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e2/e3/c887e27260754014dc63fc33bf612f1c7f1751f74e80d1aaa32491af3ffa/azure_mgmt_compute-37.2.0.tar.gz", hash = "sha256:23499d4d5ad2b2bf40a4c59df2684cc4c9cef0f9672a4e842bb9a1cf6b62f628", size = 534068, upload-time = "2026-01-27T06:39:05.39Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/be/78/8dcdb92dd9f716d08a3ac6b31c31a12cfcf8c430b2c312cbf9cc6e4695e8/azure_mgmt_compute-37.2.0-py3-none-any.whl", hash = "sha256:70741c26ac94c30408a3b20f4fdfe93e6481e308b3c14a6dbefdfd4794028616", size = 686212, upload-time = "2026-01-27T06:39:07.016Z" },
+]
+
+[[package]]
+name = "azure-mgmt-core"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "azure-core" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3e/99/fa9e7551313d8c7099c89ebf3b03cd31beb12e1b498d575aa19bb59a5d04/azure_mgmt_core-1.6.0.tar.gz", hash = "sha256:b26232af857b021e61d813d9f4ae530465255cb10b3dde945ad3743f7a58e79c", size = 30818, upload-time = "2025-07-03T02:02:24.093Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a0/26/c79f962fd3172b577b6f38685724de58b6b4337a51d3aad316a43a4558c6/azure_mgmt_core-1.6.0-py3-none-any.whl", hash = "sha256:0460d11e85c408b71c727ee1981f74432bc641bb25dfcf1bb4e90a49e776dbc4", size = 29310, upload-time = "2025-07-03T02:02:25.203Z" },
+]
+
+[[package]]
+name = "backports-tarfile"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/86/72/cd9b395f25e290e633655a100af28cb253e4393396264a98bd5f5951d50f/backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991", size = 86406, upload-time = "2024-05-28T17:01:54.731Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", size = 30181, upload-time = "2024-05-28T17:01:53.112Z" },
+]
+
+[[package]]
+name = "certifi"
+version = "2026.2.25"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/af/2d/7bf41579a8986e348fa033a31cdd0e4121114f6bce2457e8876010b092dd/certifi-2026.2.25.tar.gz", hash = "sha256:e887ab5cee78ea814d3472169153c2d12cd43b14bd03329a39a9c6e2e80bfba7", size = 155029, upload-time = "2026-02-25T02:54:17.342Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9a/3c/c17fb3ca2d9c3acff52e30b309f538586f9f5b9c9cf454f3845fc9af4881/certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa", size = 153684, upload-time = "2026-02-25T02:54:15.766Z" },
+]
+
+[[package]]
+name = "cffi"
+version = "2.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pycparser", marker = "implementation_name != 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/12/4a/3dfd5f7850cbf0d06dc84ba9aa00db766b52ca38d8b86e3a38314d52498c/cffi-2.0.0-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:b4c854ef3adc177950a8dfc81a86f5115d2abd545751a304c5bcf2c2c7283cfe", size = 184344, upload-time = "2025-09-08T23:22:26.456Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/8b/f0e4c441227ba756aafbe78f117485b25bb26b1c059d01f137fa6d14896b/cffi-2.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2de9a304e27f7596cd03d16f1b7c72219bd944e99cc52b84d0145aefb07cbd3c", size = 180560, upload-time = "2025-09-08T23:22:28.197Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/b7/1200d354378ef52ec227395d95c2576330fd22a869f7a70e88e1447eb234/cffi-2.0.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:baf5215e0ab74c16e2dd324e8ec067ef59e41125d3eade2b863d294fd5035c92", size = 209613, upload-time = "2025-09-08T23:22:29.475Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/56/6033f5e86e8cc9bb629f0077ba71679508bdf54a9a5e112a3c0b91870332/cffi-2.0.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:730cacb21e1bdff3ce90babf007d0a0917cc3e6492f336c2f0134101e0944f93", size = 216476, upload-time = "2025-09-08T23:22:31.063Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/7f/55fecd70f7ece178db2f26128ec41430d8720f2d12ca97bf8f0a628207d5/cffi-2.0.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6824f87845e3396029f3820c206e459ccc91760e8fa24422f8b0c3d1731cbec5", size = 203374, upload-time = "2025-09-08T23:22:32.507Z" },
+ { url = "https://files.pythonhosted.org/packages/84/ef/a7b77c8bdc0f77adc3b46888f1ad54be8f3b7821697a7b89126e829e676a/cffi-2.0.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:9de40a7b0323d889cf8d23d1ef214f565ab154443c42737dfe52ff82cf857664", size = 202597, upload-time = "2025-09-08T23:22:34.132Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/91/500d892b2bf36529a75b77958edfcd5ad8e2ce4064ce2ecfeab2125d72d1/cffi-2.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8941aaadaf67246224cee8c3803777eed332a19d909b47e29c9842ef1e79ac26", size = 215574, upload-time = "2025-09-08T23:22:35.443Z" },
+ { url = "https://files.pythonhosted.org/packages/44/64/58f6255b62b101093d5df22dcb752596066c7e89dd725e0afaed242a61be/cffi-2.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a05d0c237b3349096d3981b727493e22147f934b20f6f125a3eba8f994bec4a9", size = 218971, upload-time = "2025-09-08T23:22:36.805Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/49/fa72cebe2fd8a55fbe14956f9970fe8eb1ac59e5df042f603ef7c8ba0adc/cffi-2.0.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:94698a9c5f91f9d138526b48fe26a199609544591f859c870d477351dc7b2414", size = 211972, upload-time = "2025-09-08T23:22:38.436Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/28/dd0967a76aab36731b6ebfe64dec4e981aff7e0608f60c2d46b46982607d/cffi-2.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5fed36fccc0612a53f1d4d9a816b50a36702c28a2aa880cb8a122b3466638743", size = 217078, upload-time = "2025-09-08T23:22:39.776Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/c0/015b25184413d7ab0a410775fdb4a50fca20f5589b5dab1dbbfa3baad8ce/cffi-2.0.0-cp311-cp311-win32.whl", hash = "sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5", size = 172076, upload-time = "2025-09-08T23:22:40.95Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/8f/dc5531155e7070361eb1b7e4c1a9d896d0cb21c49f807a6c03fd63fc877e/cffi-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5", size = 182820, upload-time = "2025-09-08T23:22:42.463Z" },
+ { url = "https://files.pythonhosted.org/packages/95/5c/1b493356429f9aecfd56bc171285a4c4ac8697f76e9bbbbb105e537853a1/cffi-2.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d", size = 177635, upload-time = "2025-09-08T23:22:43.623Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" },
+ { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" },
+ { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" },
+ { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" },
+ { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" },
+ { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" },
+ { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" },
+ { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/8d/a0a47a0c9e413a658623d014e91e74a50cdd2c423f7ccfd44086ef767f90/cffi-2.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", size = 185230, upload-time = "2025-09-08T23:23:00.879Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", size = 181043, upload-time = "2025-09-08T23:23:02.231Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/1e/d22cc63332bd59b06481ceaac49d6c507598642e2230f201649058a7e704/cffi-2.0.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", size = 212446, upload-time = "2025-09-08T23:23:03.472Z" },
+ { url = "https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", size = 220101, upload-time = "2025-09-08T23:23:04.792Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/7f/e6647792fc5850d634695bc0e6ab4111ae88e89981d35ac269956605feba/cffi-2.0.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", size = 207948, upload-time = "2025-09-08T23:23:06.127Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/1e/a5a1bd6f1fb30f22573f76533de12a00bf274abcdc55c8edab639078abb6/cffi-2.0.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", size = 206422, upload-time = "2025-09-08T23:23:07.753Z" },
+ { url = "https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", size = 219499, upload-time = "2025-09-08T23:23:09.648Z" },
+ { url = "https://files.pythonhosted.org/packages/50/e1/a969e687fcf9ea58e6e2a928ad5e2dd88cc12f6f0ab477e9971f2309b57c/cffi-2.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", size = 222928, upload-time = "2025-09-08T23:23:10.928Z" },
+ { url = "https://files.pythonhosted.org/packages/36/54/0362578dd2c9e557a28ac77698ed67323ed5b9775ca9d3fe73fe191bb5d8/cffi-2.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", size = 221302, upload-time = "2025-09-08T23:23:12.42Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909, upload-time = "2025-09-08T23:23:14.32Z" },
+ { url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402, upload-time = "2025-09-08T23:23:15.535Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780, upload-time = "2025-09-08T23:23:16.761Z" },
+ { url = "https://files.pythonhosted.org/packages/92/c4/3ce07396253a83250ee98564f8d7e9789fab8e58858f35d07a9a2c78de9f/cffi-2.0.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", size = 185320, upload-time = "2025-09-08T23:23:18.087Z" },
+ { url = "https://files.pythonhosted.org/packages/59/dd/27e9fa567a23931c838c6b02d0764611c62290062a6d4e8ff7863daf9730/cffi-2.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", size = 181487, upload-time = "2025-09-08T23:23:19.622Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/43/0e822876f87ea8a4ef95442c3d766a06a51fc5298823f884ef87aaad168c/cffi-2.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", size = 220049, upload-time = "2025-09-08T23:23:20.853Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/89/76799151d9c2d2d1ead63c2429da9ea9d7aac304603de0c6e8764e6e8e70/cffi-2.0.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", size = 207793, upload-time = "2025-09-08T23:23:22.08Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/dd/3465b14bb9e24ee24cb88c9e3730f6de63111fffe513492bf8c808a3547e/cffi-2.0.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", size = 206300, upload-time = "2025-09-08T23:23:23.314Z" },
+ { url = "https://files.pythonhosted.org/packages/47/d9/d83e293854571c877a92da46fdec39158f8d7e68da75bf73581225d28e90/cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", size = 219244, upload-time = "2025-09-08T23:23:24.541Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/0f/1f177e3683aead2bb00f7679a16451d302c436b5cbf2505f0ea8146ef59e/cffi-2.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", size = 222828, upload-time = "2025-09-08T23:23:26.143Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/0f/cafacebd4b040e3119dcb32fed8bdef8dfe94da653155f9d0b9dc660166e/cffi-2.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", size = 220926, upload-time = "2025-09-08T23:23:27.873Z" },
+ { url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328, upload-time = "2025-09-08T23:23:44.61Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650, upload-time = "2025-09-08T23:23:45.848Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687, upload-time = "2025-09-08T23:23:47.105Z" },
+ { url = "https://files.pythonhosted.org/packages/3e/61/c768e4d548bfa607abcda77423448df8c471f25dbe64fb2ef6d555eae006/cffi-2.0.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", size = 188773, upload-time = "2025-09-08T23:23:29.347Z" },
+ { url = "https://files.pythonhosted.org/packages/2c/ea/5f76bce7cf6fcd0ab1a1058b5af899bfbef198bea4d5686da88471ea0336/cffi-2.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", size = 185013, upload-time = "2025-09-08T23:23:30.63Z" },
+ { url = "https://files.pythonhosted.org/packages/be/b4/c56878d0d1755cf9caa54ba71e5d049479c52f9e4afc230f06822162ab2f/cffi-2.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", size = 221593, upload-time = "2025-09-08T23:23:31.91Z" },
+ { url = "https://files.pythonhosted.org/packages/e0/0d/eb704606dfe8033e7128df5e90fee946bbcb64a04fcdaa97321309004000/cffi-2.0.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", size = 209354, upload-time = "2025-09-08T23:23:33.214Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/19/3c435d727b368ca475fb8742ab97c9cb13a0de600ce86f62eab7fa3eea60/cffi-2.0.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", size = 208480, upload-time = "2025-09-08T23:23:34.495Z" },
+ { url = "https://files.pythonhosted.org/packages/d0/44/681604464ed9541673e486521497406fadcc15b5217c3e326b061696899a/cffi-2.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", size = 221584, upload-time = "2025-09-08T23:23:36.096Z" },
+ { url = "https://files.pythonhosted.org/packages/25/8e/342a504ff018a2825d395d44d63a767dd8ebc927ebda557fecdaca3ac33a/cffi-2.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", size = 224443, upload-time = "2025-09-08T23:23:37.328Z" },
+ { url = "https://files.pythonhosted.org/packages/e1/5e/b666bacbbc60fbf415ba9988324a132c9a7a0448a9a8f125074671c0f2c3/cffi-2.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", size = 223437, upload-time = "2025-09-08T23:23:38.945Z" },
+ { url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487, upload-time = "2025-09-08T23:23:40.423Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726, upload-time = "2025-09-08T23:23:41.742Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" },
+]
+
+[[package]]
+name = "charset-normalizer"
+version = "3.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7b/60/e3bec1881450851b087e301bedc3daa9377a4d45f1c26aa90b0b235e38aa/charset_normalizer-3.4.6.tar.gz", hash = "sha256:1ae6b62897110aa7c79ea2f5dd38d1abca6db663687c0b1ad9aed6f6bae3d9d6", size = 143363, upload-time = "2026-03-15T18:53:25.478Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/62/28/ff6f234e628a2de61c458be2779cb182bc03f6eec12200d4a525bbfc9741/charset_normalizer-3.4.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:82060f995ab5003a2d6e0f4ad29065b7672b6593c8c63559beefe5b443242c3e", size = 293582, upload-time = "2026-03-15T18:50:25.454Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/b7/b1a117e5385cbdb3205f6055403c2a2a220c5ea80b8716c324eaf75c5c95/charset_normalizer-3.4.6-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:60c74963d8350241a79cb8feea80e54d518f72c26db618862a8f53e5023deaf9", size = 197240, upload-time = "2026-03-15T18:50:27.196Z" },
+ { url = "https://files.pythonhosted.org/packages/a1/5f/2574f0f09f3c3bc1b2f992e20bce6546cb1f17e111c5be07308dc5427956/charset_normalizer-3.4.6-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6e4333fb15c83f7d1482a76d45a0818897b3d33f00efd215528ff7c51b8e35d", size = 217363, upload-time = "2026-03-15T18:50:28.601Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/d1/0ae20ad77bc949ddd39b51bf383b6ca932f2916074c95cad34ae465ab71f/charset_normalizer-3.4.6-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bc72863f4d9aba2e8fd9085e63548a324ba706d2ea2c83b260da08a59b9482de", size = 212994, upload-time = "2026-03-15T18:50:30.102Z" },
+ { url = "https://files.pythonhosted.org/packages/60/ac/3233d262a310c1b12633536a07cde5ddd16985e6e7e238e9f3f9423d8eb9/charset_normalizer-3.4.6-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9cc4fc6c196d6a8b76629a70ddfcd4635a6898756e2d9cac5565cf0654605d73", size = 204697, upload-time = "2026-03-15T18:50:31.654Z" },
+ { url = "https://files.pythonhosted.org/packages/25/3c/8a18fc411f085b82303cfb7154eed5bd49c77035eb7608d049468b53f87c/charset_normalizer-3.4.6-cp311-cp311-manylinux_2_31_armv7l.whl", hash = "sha256:0c173ce3a681f309f31b87125fecec7a5d1347261ea11ebbb856fa6006b23c8c", size = 191673, upload-time = "2026-03-15T18:50:33.433Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/a7/11cfe61d6c5c5c7438d6ba40919d0306ed83c9ab957f3d4da2277ff67836/charset_normalizer-3.4.6-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c907cdc8109f6c619e6254212e794d6548373cc40e1ec75e6e3823d9135d29cc", size = 201120, upload-time = "2026-03-15T18:50:35.105Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/10/cf491fa1abd47c02f69687046b896c950b92b6cd7337a27e6548adbec8e4/charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:404a1e552cf5b675a87f0651f8b79f5f1e6fd100ee88dc612f89aa16abd4486f", size = 200911, upload-time = "2026-03-15T18:50:36.819Z" },
+ { url = "https://files.pythonhosted.org/packages/28/70/039796160b48b18ed466fde0af84c1b090c4e288fae26cd674ad04a2d703/charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:e3c701e954abf6fc03a49f7c579cc80c2c6cc52525340ca3186c41d3f33482ef", size = 192516, upload-time = "2026-03-15T18:50:38.228Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/34/c56f3223393d6ff3124b9e78f7de738047c2d6bc40a4f16ac0c9d7a1cb3c/charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:7a6967aaf043bceabab5412ed6bd6bd26603dae84d5cb75bf8d9a74a4959d398", size = 218795, upload-time = "2026-03-15T18:50:39.664Z" },
+ { url = "https://files.pythonhosted.org/packages/e8/3b/ce2d4f86c5282191a041fdc5a4ce18f1c6bd40a5bd1f74cf8625f08d51c1/charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:5feb91325bbceade6afab43eb3b508c63ee53579fe896c77137ded51c6b6958e", size = 201833, upload-time = "2026-03-15T18:50:41.552Z" },
+ { url = "https://files.pythonhosted.org/packages/3b/9b/b6a9f76b0fd7c5b5ec58b228ff7e85095370282150f0bd50b3126f5506d6/charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:f820f24b09e3e779fe84c3c456cb4108a7aa639b0d1f02c28046e11bfcd088ed", size = 213920, upload-time = "2026-03-15T18:50:43.33Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/98/7bc23513a33d8172365ed30ee3a3b3fe1ece14a395e5fc94129541fc6003/charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b35b200d6a71b9839a46b9b7fff66b6638bb52fc9658aa58796b0326595d3021", size = 206951, upload-time = "2026-03-15T18:50:44.789Z" },
+ { url = "https://files.pythonhosted.org/packages/32/73/c0b86f3d1458468e11aec870e6b3feac931facbe105a894b552b0e518e79/charset_normalizer-3.4.6-cp311-cp311-win32.whl", hash = "sha256:9ca4c0b502ab399ef89248a2c84c54954f77a070f28e546a85e91da627d1301e", size = 143703, upload-time = "2026-03-15T18:50:46.103Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/e3/76f2facfe8eddee0bbd38d2594e709033338eae44ebf1738bcefe0a06185/charset_normalizer-3.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:a9e68c9d88823b274cf1e72f28cb5dc89c990edf430b0bfd3e2fb0785bfeabf4", size = 153857, upload-time = "2026-03-15T18:50:47.563Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/dc/9abe19c9b27e6cd3636036b9d1b387b78c40dedbf0b47f9366737684b4b0/charset_normalizer-3.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:97d0235baafca5f2b09cf332cc275f021e694e8362c6bb9c96fc9a0eb74fc316", size = 142751, upload-time = "2026-03-15T18:50:49.234Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/62/c0815c992c9545347aeea7859b50dc9044d147e2e7278329c6e02ac9a616/charset_normalizer-3.4.6-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2ef7fedc7a6ecbe99969cd09632516738a97eeb8bd7258bf8a0f23114c057dab", size = 295154, upload-time = "2026-03-15T18:50:50.88Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/37/bdca6613c2e3c58c7421891d80cc3efa1d32e882f7c4a7ee6039c3fc951a/charset_normalizer-3.4.6-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a4ea868bc28109052790eb2b52a9ab33f3aa7adc02f96673526ff47419490e21", size = 199191, upload-time = "2026-03-15T18:50:52.658Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/92/9934d1bbd69f7f398b38c5dae1cbf9cc672e7c34a4adf7b17c0a9c17d15d/charset_normalizer-3.4.6-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:836ab36280f21fc1a03c99cd05c6b7af70d2697e374c7af0b61ed271401a72a2", size = 218674, upload-time = "2026-03-15T18:50:54.102Z" },
+ { url = "https://files.pythonhosted.org/packages/af/90/25f6ab406659286be929fd89ab0e78e38aa183fc374e03aa3c12d730af8a/charset_normalizer-3.4.6-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f1ce721c8a7dfec21fcbdfe04e8f68174183cf4e8188e0645e92aa23985c57ff", size = 215259, upload-time = "2026-03-15T18:50:55.616Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/ef/79a463eb0fff7f96afa04c1d4c51f8fc85426f918db467854bfb6a569ce3/charset_normalizer-3.4.6-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e28d62a8fc7a1fa411c43bd65e346f3bce9716dc51b897fbe930c5987b402d5", size = 207276, upload-time = "2026-03-15T18:50:57.054Z" },
+ { url = "https://files.pythonhosted.org/packages/f7/72/d0426afec4b71dc159fa6b4e68f868cd5a3ecd918fec5813a15d292a7d10/charset_normalizer-3.4.6-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:530d548084c4a9f7a16ed4a294d459b4f229db50df689bfe92027452452943a0", size = 195161, upload-time = "2026-03-15T18:50:58.686Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/18/c82b06a68bfcb6ce55e508225d210c7e6a4ea122bfc0748892f3dc4e8e11/charset_normalizer-3.4.6-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:30f445ae60aad5e1f8bdbb3108e39f6fbc09f4ea16c815c66578878325f8f15a", size = 203452, upload-time = "2026-03-15T18:51:00.196Z" },
+ { url = "https://files.pythonhosted.org/packages/44/d6/0c25979b92f8adafdbb946160348d8d44aa60ce99afdc27df524379875cb/charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ac2393c73378fea4e52aa56285a3d64be50f1a12395afef9cce47772f60334c2", size = 202272, upload-time = "2026-03-15T18:51:01.703Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/3d/7fea3e8fe84136bebbac715dd1221cc25c173c57a699c030ab9b8900cbb7/charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:90ca27cd8da8118b18a52d5f547859cc1f8354a00cd1e8e5120df3e30d6279e5", size = 195622, upload-time = "2026-03-15T18:51:03.526Z" },
+ { url = "https://files.pythonhosted.org/packages/57/8a/d6f7fd5cb96c58ef2f681424fbca01264461336d2a7fc875e4446b1f1346/charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8e5a94886bedca0f9b78fecd6afb6629142fd2605aa70a125d49f4edc6037ee6", size = 220056, upload-time = "2026-03-15T18:51:05.269Z" },
+ { url = "https://files.pythonhosted.org/packages/16/50/478cdda782c8c9c3fb5da3cc72dd7f331f031e7f1363a893cdd6ca0f8de0/charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:695f5c2823691a25f17bc5d5ffe79fa90972cc34b002ac6c843bb8a1720e950d", size = 203751, upload-time = "2026-03-15T18:51:06.858Z" },
+ { url = "https://files.pythonhosted.org/packages/75/fc/cc2fcac943939c8e4d8791abfa139f685e5150cae9f94b60f12520feaa9b/charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:231d4da14bcd9301310faf492051bee27df11f2bc7549bc0bb41fef11b82daa2", size = 216563, upload-time = "2026-03-15T18:51:08.564Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/b7/a4add1d9a5f68f3d037261aecca83abdb0ab15960a3591d340e829b37298/charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a056d1ad2633548ca18ffa2f85c202cfb48b68615129143915b8dc72a806a923", size = 209265, upload-time = "2026-03-15T18:51:10.312Z" },
+ { url = "https://files.pythonhosted.org/packages/6c/18/c094561b5d64a24277707698e54b7f67bd17a4f857bbfbb1072bba07c8bf/charset_normalizer-3.4.6-cp312-cp312-win32.whl", hash = "sha256:c2274ca724536f173122f36c98ce188fd24ce3dad886ec2b7af859518ce008a4", size = 144229, upload-time = "2026-03-15T18:51:11.694Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/20/0567efb3a8fd481b8f34f739ebddc098ed062a59fed41a8d193a61939e8f/charset_normalizer-3.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:c8ae56368f8cc97c7e40a7ee18e1cedaf8e780cd8bc5ed5ac8b81f238614facb", size = 154277, upload-time = "2026-03-15T18:51:13.004Z" },
+ { url = "https://files.pythonhosted.org/packages/15/57/28d79b44b51933119e21f65479d0864a8d5893e494cf5daab15df0247c17/charset_normalizer-3.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:899d28f422116b08be5118ef350c292b36fc15ec2daeb9ea987c89281c7bb5c4", size = 142817, upload-time = "2026-03-15T18:51:14.408Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/1d/4fdabeef4e231153b6ed7567602f3b68265ec4e5b76d6024cf647d43d981/charset_normalizer-3.4.6-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:11afb56037cbc4b1555a34dd69151e8e069bee82e613a73bef6e714ce733585f", size = 294823, upload-time = "2026-03-15T18:51:15.755Z" },
+ { url = "https://files.pythonhosted.org/packages/47/7b/20e809b89c69d37be748d98e84dce6820bf663cf19cf6b942c951a3e8f41/charset_normalizer-3.4.6-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:423fb7e748a08f854a08a222b983f4df1912b1daedce51a72bd24fe8f26a1843", size = 198527, upload-time = "2026-03-15T18:51:17.177Z" },
+ { url = "https://files.pythonhosted.org/packages/37/a6/4f8d27527d59c039dce6f7622593cdcd3d70a8504d87d09eb11e9fdc6062/charset_normalizer-3.4.6-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d73beaac5e90173ac3deb9928a74763a6d230f494e4bfb422c217a0ad8e629bf", size = 218388, upload-time = "2026-03-15T18:51:18.934Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/9b/4770ccb3e491a9bacf1c46cc8b812214fe367c86a96353ccc6daf87b01ec/charset_normalizer-3.4.6-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d60377dce4511655582e300dc1e5a5f24ba0cb229005a1d5c8d0cb72bb758ab8", size = 214563, upload-time = "2026-03-15T18:51:20.374Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/58/a199d245894b12db0b957d627516c78e055adc3a0d978bc7f65ddaf7c399/charset_normalizer-3.4.6-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:530e8cebeea0d76bdcf93357aa5e41336f48c3dc709ac52da2bb167c5b8271d9", size = 206587, upload-time = "2026-03-15T18:51:21.807Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/70/3def227f1ec56f5c69dfc8392b8bd63b11a18ca8178d9211d7cc5e5e4f27/charset_normalizer-3.4.6-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:a26611d9987b230566f24a0a125f17fe0de6a6aff9f25c9f564aaa2721a5fb88", size = 194724, upload-time = "2026-03-15T18:51:23.508Z" },
+ { url = "https://files.pythonhosted.org/packages/58/ab/9318352e220c05efd31c2779a23b50969dc94b985a2efa643ed9077bfca5/charset_normalizer-3.4.6-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:34315ff4fc374b285ad7f4a0bf7dcbfe769e1b104230d40f49f700d4ab6bbd84", size = 202956, upload-time = "2026-03-15T18:51:25.239Z" },
+ { url = "https://files.pythonhosted.org/packages/75/13/f3550a3ac25b70f87ac98c40d3199a8503676c2f1620efbf8d42095cfc40/charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5f8ddd609f9e1af8c7bd6e2aca279c931aefecd148a14402d4e368f3171769fd", size = 201923, upload-time = "2026-03-15T18:51:26.682Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/db/c5c643b912740b45e8eec21de1bbab8e7fc085944d37e1e709d3dcd9d72f/charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:80d0a5615143c0b3225e5e3ef22c8d5d51f3f72ce0ea6fb84c943546c7b25b6c", size = 195366, upload-time = "2026-03-15T18:51:28.129Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/67/3b1c62744f9b2448443e0eb160d8b001c849ec3fef591e012eda6484787c/charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:92734d4d8d187a354a556626c221cd1a892a4e0802ccb2af432a1d85ec012194", size = 219752, upload-time = "2026-03-15T18:51:29.556Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/98/32ffbaf7f0366ffb0445930b87d103f6b406bc2c271563644bde8a2b1093/charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:613f19aa6e082cf96e17e3ffd89383343d0d589abda756b7764cf78361fd41dc", size = 203296, upload-time = "2026-03-15T18:51:30.921Z" },
+ { url = "https://files.pythonhosted.org/packages/41/12/5d308c1bbe60cabb0c5ef511574a647067e2a1f631bc8634fcafaccd8293/charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2b1a63e8224e401cafe7739f77efd3f9e7f5f2026bda4aead8e59afab537784f", size = 215956, upload-time = "2026-03-15T18:51:32.399Z" },
+ { url = "https://files.pythonhosted.org/packages/53/e9/5f85f6c5e20669dbe56b165c67b0260547dea97dba7e187938833d791687/charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6cceb5473417d28edd20c6c984ab6fee6c6267d38d906823ebfe20b03d607dc2", size = 208652, upload-time = "2026-03-15T18:51:34.214Z" },
+ { url = "https://files.pythonhosted.org/packages/f1/11/897052ea6af56df3eef3ca94edafee410ca699ca0c7b87960ad19932c55e/charset_normalizer-3.4.6-cp313-cp313-win32.whl", hash = "sha256:d7de2637729c67d67cf87614b566626057e95c303bc0a55ffe391f5205e7003d", size = 143940, upload-time = "2026-03-15T18:51:36.15Z" },
+ { url = "https://files.pythonhosted.org/packages/a1/5c/724b6b363603e419829f561c854b87ed7c7e31231a7908708ac086cdf3e2/charset_normalizer-3.4.6-cp313-cp313-win_amd64.whl", hash = "sha256:572d7c822caf521f0525ba1bce1a622a0b85cf47ffbdae6c9c19e3b5ac3c4389", size = 154101, upload-time = "2026-03-15T18:51:37.876Z" },
+ { url = "https://files.pythonhosted.org/packages/01/a5/7abf15b4c0968e47020f9ca0935fb3274deb87cb288cd187cad92e8cdffd/charset_normalizer-3.4.6-cp313-cp313-win_arm64.whl", hash = "sha256:a4474d924a47185a06411e0064b803c68be044be2d60e50e8bddcc2649957c1f", size = 143109, upload-time = "2026-03-15T18:51:39.565Z" },
+ { url = "https://files.pythonhosted.org/packages/25/6f/ffe1e1259f384594063ea1869bfb6be5cdb8bc81020fc36c3636bc8302a1/charset_normalizer-3.4.6-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:9cc6e6d9e571d2f863fa77700701dae73ed5f78881efc8b3f9a4398772ff53e8", size = 294458, upload-time = "2026-03-15T18:51:41.134Z" },
+ { url = "https://files.pythonhosted.org/packages/56/60/09bb6c13a8c1016c2ed5c6a6488e4ffef506461aa5161662bd7636936fb1/charset_normalizer-3.4.6-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef5960d965e67165d75b7c7ffc60a83ec5abfc5c11b764ec13ea54fbef8b4421", size = 199277, upload-time = "2026-03-15T18:51:42.953Z" },
+ { url = "https://files.pythonhosted.org/packages/00/50/dcfbb72a5138bbefdc3332e8d81a23494bf67998b4b100703fd15fa52d81/charset_normalizer-3.4.6-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b3694e3f87f8ac7ce279d4355645b3c878d24d1424581b46282f24b92f5a4ae2", size = 218758, upload-time = "2026-03-15T18:51:44.339Z" },
+ { url = "https://files.pythonhosted.org/packages/03/b3/d79a9a191bb75f5aa81f3aaaa387ef29ce7cb7a9e5074ba8ea095cc073c2/charset_normalizer-3.4.6-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5d11595abf8dd942a77883a39d81433739b287b6aa71620f15164f8096221b30", size = 215299, upload-time = "2026-03-15T18:51:45.871Z" },
+ { url = "https://files.pythonhosted.org/packages/76/7e/bc8911719f7084f72fd545f647601ea3532363927f807d296a8c88a62c0d/charset_normalizer-3.4.6-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7bda6eebafd42133efdca535b04ccb338ab29467b3f7bf79569883676fc628db", size = 206811, upload-time = "2026-03-15T18:51:47.308Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/40/c430b969d41dda0c465aa36cc7c2c068afb67177bef50905ac371b28ccc7/charset_normalizer-3.4.6-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:bbc8c8650c6e51041ad1be191742b8b421d05bbd3410f43fa2a00c8db87678e8", size = 193706, upload-time = "2026-03-15T18:51:48.849Z" },
+ { url = "https://files.pythonhosted.org/packages/48/15/e35e0590af254f7df984de1323640ef375df5761f615b6225ba8deb9799a/charset_normalizer-3.4.6-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:22c6f0c2fbc31e76c3b8a86fba1a56eda6166e238c29cdd3d14befdb4a4e4815", size = 202706, upload-time = "2026-03-15T18:51:50.257Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/bd/f736f7b9cc5e93a18b794a50346bb16fbfd6b37f99e8f306f7951d27c17c/charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7edbed096e4a4798710ed6bc75dcaa2a21b68b6c356553ac4823c3658d53743a", size = 202497, upload-time = "2026-03-15T18:51:52.012Z" },
+ { url = "https://files.pythonhosted.org/packages/9d/ba/2cc9e3e7dfdf7760a6ed8da7446d22536f3d0ce114ac63dee2a5a3599e62/charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:7f9019c9cb613f084481bd6a100b12e1547cf2efe362d873c2e31e4035a6fa43", size = 193511, upload-time = "2026-03-15T18:51:53.723Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/cb/5be49b5f776e5613be07298c80e1b02a2d900f7a7de807230595c85a8b2e/charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:58c948d0d086229efc484fe2f30c2d382c86720f55cd9bc33591774348ad44e0", size = 220133, upload-time = "2026-03-15T18:51:55.333Z" },
+ { url = "https://files.pythonhosted.org/packages/83/43/99f1b5dad345accb322c80c7821071554f791a95ee50c1c90041c157ae99/charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:419a9d91bd238052642a51938af8ac05da5b3343becde08d5cdeab9046df9ee1", size = 203035, upload-time = "2026-03-15T18:51:56.736Z" },
+ { url = "https://files.pythonhosted.org/packages/87/9a/62c2cb6a531483b55dddff1a68b3d891a8b498f3ca555fbcf2978e804d9d/charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:5273b9f0b5835ff0350c0828faea623c68bfa65b792720c453e22b25cc72930f", size = 216321, upload-time = "2026-03-15T18:51:58.17Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/79/94a010ff81e3aec7c293eb82c28f930918e517bc144c9906a060844462eb/charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0e901eb1049fdb80f5bd11ed5ea1e498ec423102f7a9b9e4645d5b8204ff2815", size = 208973, upload-time = "2026-03-15T18:51:59.998Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/57/4ecff6d4ec8585342f0c71bc03efaa99cb7468f7c91a57b105bcd561cea8/charset_normalizer-3.4.6-cp314-cp314-win32.whl", hash = "sha256:b4ff1d35e8c5bd078be89349b6f3a845128e685e751b6ea1169cf2160b344c4d", size = 144610, upload-time = "2026-03-15T18:52:02.213Z" },
+ { url = "https://files.pythonhosted.org/packages/80/94/8434a02d9d7f168c25767c64671fead8d599744a05d6a6c877144c754246/charset_normalizer-3.4.6-cp314-cp314-win_amd64.whl", hash = "sha256:74119174722c4349af9708993118581686f343adc1c8c9c007d59be90d077f3f", size = 154962, upload-time = "2026-03-15T18:52:03.658Z" },
+ { url = "https://files.pythonhosted.org/packages/46/4c/48f2cdbfd923026503dfd67ccea45c94fd8fe988d9056b468579c66ed62b/charset_normalizer-3.4.6-cp314-cp314-win_arm64.whl", hash = "sha256:e5bcc1a1ae744e0bb59641171ae53743760130600da8db48cbb6e4918e186e4e", size = 143595, upload-time = "2026-03-15T18:52:05.123Z" },
+ { url = "https://files.pythonhosted.org/packages/31/93/8878be7569f87b14f1d52032946131bcb6ebbd8af3e20446bc04053dc3f1/charset_normalizer-3.4.6-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ad8faf8df23f0378c6d527d8b0b15ea4a2e23c89376877c598c4870d1b2c7866", size = 314828, upload-time = "2026-03-15T18:52:06.831Z" },
+ { url = "https://files.pythonhosted.org/packages/06/b6/fae511ca98aac69ecc35cde828b0a3d146325dd03d99655ad38fc2cc3293/charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f5ea69428fa1b49573eef0cc44a1d43bebd45ad0c611eb7d7eac760c7ae771bc", size = 208138, upload-time = "2026-03-15T18:52:08.239Z" },
+ { url = "https://files.pythonhosted.org/packages/54/57/64caf6e1bf07274a1e0b7c160a55ee9e8c9ec32c46846ce59b9c333f7008/charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:06a7e86163334edfc5d20fe104db92fcd666e5a5df0977cb5680a506fe26cc8e", size = 224679, upload-time = "2026-03-15T18:52:10.043Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/cb/9ff5a25b9273ef160861b41f6937f86fae18b0792fe0a8e75e06acb08f1d/charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e1f6e2f00a6b8edb562826e4632e26d063ac10307e80f7461f7de3ad8ef3f077", size = 223475, upload-time = "2026-03-15T18:52:11.854Z" },
+ { url = "https://files.pythonhosted.org/packages/fc/97/440635fc093b8d7347502a377031f9605a1039c958f3cd18dcacffb37743/charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:95b52c68d64c1878818687a473a10547b3292e82b6f6fe483808fb1468e2f52f", size = 215230, upload-time = "2026-03-15T18:52:13.325Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/24/afff630feb571a13f07c8539fbb502d2ab494019492aaffc78ef41f1d1d0/charset_normalizer-3.4.6-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:7504e9b7dc05f99a9bbb4525c67a2c155073b44d720470a148b34166a69c054e", size = 199045, upload-time = "2026-03-15T18:52:14.752Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/17/d1399ecdaf7e0498c327433e7eefdd862b41236a7e484355b8e0e5ebd64b/charset_normalizer-3.4.6-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:172985e4ff804a7ad08eebec0a1640ece87ba5041d565fff23c8f99c1f389484", size = 211658, upload-time = "2026-03-15T18:52:16.278Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/38/16baa0affb957b3d880e5ac2144caf3f9d7de7bc4a91842e447fbb5e8b67/charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:4be9f4830ba8741527693848403e2c457c16e499100963ec711b1c6f2049b7c7", size = 210769, upload-time = "2026-03-15T18:52:17.782Z" },
+ { url = "https://files.pythonhosted.org/packages/05/34/c531bc6ac4c21da9ddfddb3107be2287188b3ea4b53b70fc58f2a77ac8d8/charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:79090741d842f564b1b2827c0b82d846405b744d31e84f18d7a7b41c20e473ff", size = 201328, upload-time = "2026-03-15T18:52:19.553Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/73/a5a1e9ca5f234519c1953608a03fe109c306b97fdfb25f09182babad51a7/charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:87725cfb1a4f1f8c2fc9890ae2f42094120f4b44db9360be5d99a4c6b0e03a9e", size = 225302, upload-time = "2026-03-15T18:52:21.043Z" },
+ { url = "https://files.pythonhosted.org/packages/ba/f6/cd782923d112d296294dea4bcc7af5a7ae0f86ab79f8fefbda5526b6cfc0/charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:fcce033e4021347d80ed9c66dcf1e7b1546319834b74445f561d2e2221de5659", size = 211127, upload-time = "2026-03-15T18:52:22.491Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/c5/0b6898950627af7d6103a449b22320372c24c6feda91aa24e201a478d161/charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:ca0276464d148c72defa8bb4390cce01b4a0e425f3b50d1435aa6d7a18107602", size = 222840, upload-time = "2026-03-15T18:52:24.113Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/25/c4bba773bef442cbdc06111d40daa3de5050a676fa26e85090fc54dd12f0/charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:197c1a244a274bb016dd8b79204850144ef77fe81c5b797dc389327adb552407", size = 216890, upload-time = "2026-03-15T18:52:25.541Z" },
+ { url = "https://files.pythonhosted.org/packages/35/1a/05dacadb0978da72ee287b0143097db12f2e7e8d3ffc4647da07a383b0b7/charset_normalizer-3.4.6-cp314-cp314t-win32.whl", hash = "sha256:2a24157fa36980478dd1770b585c0f30d19e18f4fb0c47c13aa568f871718579", size = 155379, upload-time = "2026-03-15T18:52:27.05Z" },
+ { url = "https://files.pythonhosted.org/packages/5d/7a/d269d834cb3a76291651256f3b9a5945e81d0a49ab9f4a498964e83c0416/charset_normalizer-3.4.6-cp314-cp314t-win_amd64.whl", hash = "sha256:cd5e2801c89992ed8c0a3f0293ae83c159a60d9a5d685005383ef4caca77f2c4", size = 169043, upload-time = "2026-03-15T18:52:28.502Z" },
+ { url = "https://files.pythonhosted.org/packages/23/06/28b29fba521a37a8932c6a84192175c34d49f84a6d4773fa63d05f9aff22/charset_normalizer-3.4.6-cp314-cp314t-win_arm64.whl", hash = "sha256:47955475ac79cc504ef2704b192364e51d0d473ad452caedd0002605f780101c", size = 148523, upload-time = "2026-03-15T18:52:29.956Z" },
+ { url = "https://files.pythonhosted.org/packages/2a/68/687187c7e26cb24ccbd88e5069f5ef00eba804d36dde11d99aad0838ab45/charset_normalizer-3.4.6-py3-none-any.whl", hash = "sha256:947cf925bc916d90adba35a64c82aace04fa39b46b52d4630ece166655905a69", size = 61455, upload-time = "2026-03-15T18:53:23.833Z" },
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
+]
+
+[[package]]
+name = "cryptography"
+version = "46.0.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a4/ba/04b1bd4218cbc58dc90ce967106d51582371b898690f3ae0402876cc4f34/cryptography-46.0.6.tar.gz", hash = "sha256:27550628a518c5c6c903d84f637fbecf287f6cb9ced3804838a1295dc1fd0759", size = 750542, upload-time = "2026-03-25T23:34:53.396Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/47/23/9285e15e3bc57325b0a72e592921983a701efc1ee8f91c06c5f0235d86d9/cryptography-46.0.6-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:64235194bad039a10bb6d2d930ab3323baaec67e2ce36215fd0952fad0930ca8", size = 7176401, upload-time = "2026-03-25T23:33:22.096Z" },
+ { url = "https://files.pythonhosted.org/packages/60/f8/e61f8f13950ab6195b31913b42d39f0f9afc7d93f76710f299b5ec286ae6/cryptography-46.0.6-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:26031f1e5ca62fcb9d1fcb34b2b60b390d1aacaa15dc8b895a9ed00968b97b30", size = 4275275, upload-time = "2026-03-25T23:33:23.844Z" },
+ { url = "https://files.pythonhosted.org/packages/19/69/732a736d12c2631e140be2348b4ad3d226302df63ef64d30dfdb8db7ad1c/cryptography-46.0.6-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9a693028b9cbe51b5a1136232ee8f2bc242e4e19d456ded3fa7c86e43c713b4a", size = 4425320, upload-time = "2026-03-25T23:33:25.703Z" },
+ { url = "https://files.pythonhosted.org/packages/d4/12/123be7292674abf76b21ac1fc0e1af50661f0e5b8f0ec8285faac18eb99e/cryptography-46.0.6-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:67177e8a9f421aa2d3a170c3e56eca4e0128883cf52a071a7cbf53297f18b175", size = 4278082, upload-time = "2026-03-25T23:33:27.423Z" },
+ { url = "https://files.pythonhosted.org/packages/5b/ba/d5e27f8d68c24951b0a484924a84c7cdaed7502bac9f18601cd357f8b1d2/cryptography-46.0.6-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d9528b535a6c4f8ff37847144b8986a9a143585f0540fbcb1a98115b543aa463", size = 4926514, upload-time = "2026-03-25T23:33:29.206Z" },
+ { url = "https://files.pythonhosted.org/packages/34/71/1ea5a7352ae516d5512d17babe7e1b87d9db5150b21f794b1377eac1edc0/cryptography-46.0.6-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:22259338084d6ae497a19bae5d4c66b7ca1387d3264d1c2c0e72d9e9b6a77b97", size = 4457766, upload-time = "2026-03-25T23:33:30.834Z" },
+ { url = "https://files.pythonhosted.org/packages/01/59/562be1e653accee4fdad92c7a2e88fced26b3fdfce144047519bbebc299e/cryptography-46.0.6-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:760997a4b950ff00d418398ad73fbc91aa2894b5c1db7ccb45b4f68b42a63b3c", size = 3986535, upload-time = "2026-03-25T23:33:33.02Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/8b/b1ebfeb788bf4624d36e45ed2662b8bd43a05ff62157093c1539c1288a18/cryptography-46.0.6-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:3dfa6567f2e9e4c5dceb8ccb5a708158a2a871052fa75c8b78cb0977063f1507", size = 4277618, upload-time = "2026-03-25T23:33:34.567Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/52/a005f8eabdb28df57c20f84c44d397a755782d6ff6d455f05baa2785bd91/cryptography-46.0.6-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:cdcd3edcbc5d55757e5f5f3d330dd00007ae463a7e7aa5bf132d1f22a4b62b19", size = 4890802, upload-time = "2026-03-25T23:33:37.034Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/4d/8e7d7245c79c617d08724e2efa397737715ca0ec830ecb3c91e547302555/cryptography-46.0.6-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:d4e4aadb7fc1f88687f47ca20bb7227981b03afaae69287029da08096853b738", size = 4457425, upload-time = "2026-03-25T23:33:38.904Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/5c/f6c3596a1430cec6f949085f0e1a970638d76f81c3ea56d93d564d04c340/cryptography-46.0.6-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:2b417edbe8877cda9022dde3a008e2deb50be9c407eef034aeeb3a8b11d9db3c", size = 4405530, upload-time = "2026-03-25T23:33:40.842Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/c9/9f9cea13ee2dbde070424e0c4f621c091a91ffcc504ffea5e74f0e1daeff/cryptography-46.0.6-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:380343e0653b1c9d7e1f55b52aaa2dbb2fdf2730088d48c43ca1c7c0abb7cc2f", size = 4667896, upload-time = "2026-03-25T23:33:42.781Z" },
+ { url = "https://files.pythonhosted.org/packages/ad/b5/1895bc0821226f129bc74d00eccfc6a5969e2028f8617c09790bf89c185e/cryptography-46.0.6-cp311-abi3-win32.whl", hash = "sha256:bcb87663e1f7b075e48c3be3ecb5f0b46c8fc50b50a97cf264e7f60242dca3f2", size = 3026348, upload-time = "2026-03-25T23:33:45.021Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/f8/c9bcbf0d3e6ad288b9d9aa0b1dee04b063d19e8c4f871855a03ab3a297ab/cryptography-46.0.6-cp311-abi3-win_amd64.whl", hash = "sha256:6739d56300662c468fddb0e5e291f9b4d084bead381667b9e654c7dd81705124", size = 3483896, upload-time = "2026-03-25T23:33:46.649Z" },
+ { url = "https://files.pythonhosted.org/packages/01/41/3a578f7fd5c70611c0aacba52cd13cb364a5dee895a5c1d467208a9380b0/cryptography-46.0.6-cp314-cp314t-macosx_10_9_universal2.whl", hash = "sha256:2ef9e69886cbb137c2aef9772c2e7138dc581fad4fcbcf13cc181eb5a3ab6275", size = 7117147, upload-time = "2026-03-25T23:33:48.249Z" },
+ { url = "https://files.pythonhosted.org/packages/fa/87/887f35a6fca9dde90cad08e0de0c89263a8e59b2d2ff904fd9fcd8025b6f/cryptography-46.0.6-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7f417f034f91dcec1cb6c5c35b07cdbb2ef262557f701b4ecd803ee8cefed4f4", size = 4266221, upload-time = "2026-03-25T23:33:49.874Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/a8/0a90c4f0b0871e0e3d1ed126aed101328a8a57fd9fd17f00fb67e82a51ca/cryptography-46.0.6-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d24c13369e856b94892a89ddf70b332e0b70ad4a5c43cf3e9cb71d6d7ffa1f7b", size = 4408952, upload-time = "2026-03-25T23:33:52.128Z" },
+ { url = "https://files.pythonhosted.org/packages/16/0b/b239701eb946523e4e9f329336e4ff32b1247e109cbab32d1a7b61da8ed7/cryptography-46.0.6-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:aad75154a7ac9039936d50cf431719a2f8d4ed3d3c277ac03f3339ded1a5e707", size = 4270141, upload-time = "2026-03-25T23:33:54.11Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/a8/976acdd4f0f30df7b25605f4b9d3d89295351665c2091d18224f7ad5cdbf/cryptography-46.0.6-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:3c21d92ed15e9cfc6eb64c1f5a0326db22ca9c2566ca46d845119b45b4400361", size = 4904178, upload-time = "2026-03-25T23:33:55.725Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/1b/bf0e01a88efd0e59679b69f42d4afd5bced8700bb5e80617b2d63a3741af/cryptography-46.0.6-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:4668298aef7cddeaf5c6ecc244c2302a2b8e40f384255505c22875eebb47888b", size = 4441812, upload-time = "2026-03-25T23:33:57.364Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/8b/11df86de2ea389c65aa1806f331cae145f2ed18011f30234cc10ca253de8/cryptography-46.0.6-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:8ce35b77aaf02f3b59c90b2c8a05c73bac12cea5b4e8f3fbece1f5fddea5f0ca", size = 3963923, upload-time = "2026-03-25T23:33:59.361Z" },
+ { url = "https://files.pythonhosted.org/packages/91/e0/207fb177c3a9ef6a8108f234208c3e9e76a6aa8cf20d51932916bd43bda0/cryptography-46.0.6-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:c89eb37fae9216985d8734c1afd172ba4927f5a05cfd9bf0e4863c6d5465b013", size = 4269695, upload-time = "2026-03-25T23:34:00.909Z" },
+ { url = "https://files.pythonhosted.org/packages/21/5e/19f3260ed1e95bced52ace7501fabcd266df67077eeb382b79c81729d2d3/cryptography-46.0.6-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:ed418c37d095aeddf5336898a132fba01091f0ac5844e3e8018506f014b6d2c4", size = 4869785, upload-time = "2026-03-25T23:34:02.796Z" },
+ { url = "https://files.pythonhosted.org/packages/10/38/cd7864d79aa1d92ef6f1a584281433419b955ad5a5ba8d1eb6c872165bcb/cryptography-46.0.6-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:69cf0056d6947edc6e6760e5f17afe4bea06b56a9ac8a06de9d2bd6b532d4f3a", size = 4441404, upload-time = "2026-03-25T23:34:04.35Z" },
+ { url = "https://files.pythonhosted.org/packages/09/0a/4fe7a8d25fed74419f91835cf5829ade6408fd1963c9eae9c4bce390ecbb/cryptography-46.0.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8e7304c4f4e9490e11efe56af6713983460ee0780f16c63f219984dab3af9d2d", size = 4397549, upload-time = "2026-03-25T23:34:06.342Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/a0/7d738944eac6513cd60a8da98b65951f4a3b279b93479a7e8926d9cd730b/cryptography-46.0.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b928a3ca837c77a10e81a814a693f2295200adb3352395fad024559b7be7a736", size = 4651874, upload-time = "2026-03-25T23:34:07.916Z" },
+ { url = "https://files.pythonhosted.org/packages/cb/f1/c2326781ca05208845efca38bf714f76939ae446cd492d7613808badedf1/cryptography-46.0.6-cp314-cp314t-win32.whl", hash = "sha256:97c8115b27e19e592a05c45d0dd89c57f81f841cc9880e353e0d3bf25b2139ed", size = 3001511, upload-time = "2026-03-25T23:34:09.892Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/57/fe4a23eb549ac9d903bd4698ffda13383808ef0876cc912bcb2838799ece/cryptography-46.0.6-cp314-cp314t-win_amd64.whl", hash = "sha256:c797e2517cb7880f8297e2c0f43bb910e91381339336f75d2c1c2cbf811b70b4", size = 3471692, upload-time = "2026-03-25T23:34:11.613Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/cc/f330e982852403da79008552de9906804568ae9230da8432f7496ce02b71/cryptography-46.0.6-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:12cae594e9473bca1a7aceb90536060643128bb274fcea0fc459ab90f7d1ae7a", size = 7162776, upload-time = "2026-03-25T23:34:13.308Z" },
+ { url = "https://files.pythonhosted.org/packages/49/b3/dc27efd8dcc4bff583b3f01d4a3943cd8b5821777a58b3a6a5f054d61b79/cryptography-46.0.6-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:639301950939d844a9e1c4464d7e07f902fe9a7f6b215bb0d4f28584729935d8", size = 4270529, upload-time = "2026-03-25T23:34:15.019Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/05/e8d0e6eb4f0d83365b3cb0e00eb3c484f7348db0266652ccd84632a3d58d/cryptography-46.0.6-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ed3775295fb91f70b4027aeba878d79b3e55c0b3e97eaa4de71f8f23a9f2eb77", size = 4414827, upload-time = "2026-03-25T23:34:16.604Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/97/daba0f5d2dc6d855e2dcb70733c812558a7977a55dd4a6722756628c44d1/cryptography-46.0.6-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8927ccfbe967c7df312ade694f987e7e9e22b2425976ddbf28271d7e58845290", size = 4271265, upload-time = "2026-03-25T23:34:18.586Z" },
+ { url = "https://files.pythonhosted.org/packages/89/06/fe1fce39a37ac452e58d04b43b0855261dac320a2ebf8f5260dd55b201a9/cryptography-46.0.6-cp38-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:b12c6b1e1651e42ab5de8b1e00dc3b6354fdfd778e7fa60541ddacc27cd21410", size = 4916800, upload-time = "2026-03-25T23:34:20.561Z" },
+ { url = "https://files.pythonhosted.org/packages/ff/8a/b14f3101fe9c3592603339eb5d94046c3ce5f7fc76d6512a2d40efd9724e/cryptography-46.0.6-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:063b67749f338ca9c5a0b7fe438a52c25f9526b851e24e6c9310e7195aad3b4d", size = 4448771, upload-time = "2026-03-25T23:34:22.406Z" },
+ { url = "https://files.pythonhosted.org/packages/01/b3/0796998056a66d1973fd52ee89dc1bb3b6581960a91ad4ac705f182d398f/cryptography-46.0.6-cp38-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:02fad249cb0e090b574e30b276a3da6a149e04ee2f049725b1f69e7b8351ec70", size = 3978333, upload-time = "2026-03-25T23:34:24.281Z" },
+ { url = "https://files.pythonhosted.org/packages/c5/3d/db200af5a4ffd08918cd55c08399dc6c9c50b0bc72c00a3246e099d3a849/cryptography-46.0.6-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:7e6142674f2a9291463e5e150090b95a8519b2fb6e6aaec8917dd8d094ce750d", size = 4271069, upload-time = "2026-03-25T23:34:25.895Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/18/61acfd5b414309d74ee838be321c636fe71815436f53c9f0334bf19064fa/cryptography-46.0.6-cp38-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:456b3215172aeefb9284550b162801d62f5f264a081049a3e94307fe20792cfa", size = 4878358, upload-time = "2026-03-25T23:34:27.67Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/65/5bf43286d566f8171917cae23ac6add941654ccf085d739195a4eacf1674/cryptography-46.0.6-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:341359d6c9e68834e204ceaf25936dffeafea3829ab80e9503860dcc4f4dac58", size = 4448061, upload-time = "2026-03-25T23:34:29.375Z" },
+ { url = "https://files.pythonhosted.org/packages/e0/25/7e49c0fa7205cf3597e525d156a6bce5b5c9de1fd7e8cb01120e459f205a/cryptography-46.0.6-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:9a9c42a2723999a710445bc0d974e345c32adfd8d2fac6d8a251fa829ad31cfb", size = 4399103, upload-time = "2026-03-25T23:34:32.036Z" },
+ { url = "https://files.pythonhosted.org/packages/44/46/466269e833f1c4718d6cd496ffe20c56c9c8d013486ff66b4f69c302a68d/cryptography-46.0.6-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6617f67b1606dfd9fe4dbfa354a9508d4a6d37afe30306fe6c101b7ce3274b72", size = 4659255, upload-time = "2026-03-25T23:34:33.679Z" },
+ { url = "https://files.pythonhosted.org/packages/0a/09/ddc5f630cc32287d2c953fc5d32705e63ec73e37308e5120955316f53827/cryptography-46.0.6-cp38-abi3-win32.whl", hash = "sha256:7f6690b6c55e9c5332c0b59b9c8a3fb232ebf059094c17f9019a51e9827df91c", size = 3010660, upload-time = "2026-03-25T23:34:35.418Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/82/ca4893968aeb2709aacfb57a30dec6fa2ab25b10fa9f064b8882ce33f599/cryptography-46.0.6-cp38-abi3-win_amd64.whl", hash = "sha256:79e865c642cfc5c0b3eb12af83c35c5aeff4fa5c672dc28c43721c2c9fdd2f0f", size = 3471160, upload-time = "2026-03-25T23:34:37.191Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/84/7ccff00ced5bac74b775ce0beb7d1be4e8637536b522b5df9b73ada42da2/cryptography-46.0.6-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:2ea0f37e9a9cf0df2952893ad145fd9627d326a59daec9b0802480fa3bcd2ead", size = 3475444, upload-time = "2026-03-25T23:34:38.944Z" },
+ { url = "https://files.pythonhosted.org/packages/bc/1f/4c926f50df7749f000f20eede0c896769509895e2648db5da0ed55db711d/cryptography-46.0.6-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:a3e84d5ec9ba01f8fd03802b2147ba77f0c8f2617b2aff254cedd551844209c8", size = 4218227, upload-time = "2026-03-25T23:34:40.871Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/65/707be3ffbd5f786028665c3223e86e11c4cda86023adbc56bd72b1b6bab5/cryptography-46.0.6-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:12f0fa16cc247b13c43d56d7b35287ff1569b5b1f4c5e87e92cc4fcc00cd10c0", size = 4381399, upload-time = "2026-03-25T23:34:42.609Z" },
+ { url = "https://files.pythonhosted.org/packages/f3/6d/73557ed0ef7d73d04d9aba745d2c8e95218213687ee5e76b7d236a5030fc/cryptography-46.0.6-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:50575a76e2951fe7dbd1f56d181f8c5ceeeb075e9ff88e7ad997d2f42af06e7b", size = 4217595, upload-time = "2026-03-25T23:34:44.205Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/c5/e1594c4eec66a567c3ac4400008108a415808be2ce13dcb9a9045c92f1a0/cryptography-46.0.6-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:90e5f0a7b3be5f40c3a0a0eafb32c681d8d2c181fc2a1bdabe9b3f611d9f6b1a", size = 4380912, upload-time = "2026-03-25T23:34:46.328Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/89/843b53614b47f97fe1abc13f9a86efa5ec9e275292c457af1d4a60dc80e0/cryptography-46.0.6-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:6728c49e3b2c180ef26f8e9f0a883a2c585638db64cf265b49c9ba10652d430e", size = 3409955, upload-time = "2026-03-25T23:34:48.465Z" },
+]
+
+[[package]]
+name = "docutils"
+version = "0.22.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ae/b6/03bb70946330e88ffec97aefd3ea75ba575cb2e762061e0e62a213befee8/docutils-0.22.4.tar.gz", hash = "sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968", size = 2291750, upload-time = "2025-12-18T19:00:26.443Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/02/10/5da547df7a391dcde17f59520a231527b8571e6f46fc8efb02ccb370ab12/docutils-0.22.4-py3-none-any.whl", hash = "sha256:d0013f540772d1420576855455d050a2180186c91c15779301ac2ccb3eeb68de", size = 633196, upload-time = "2025-12-18T19:00:18.077Z" },
+]
+
+[[package]]
+name = "h11"
+version = "0.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
+]
+
+[[package]]
+name = "hatchling"
+version = "1.29.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "packaging" },
+ { name = "pathspec" },
+ { name = "pluggy" },
+ { name = "trove-classifiers" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/cf/9c/b4cfe330cd4f49cff17fd771154730555fa4123beb7f292cf0098b4e6c20/hatchling-1.29.0.tar.gz", hash = "sha256:793c31816d952cee405b83488ce001c719f325d9cda69f1fc4cd750527640ea6", size = 55656, upload-time = "2026-02-23T19:42:06.539Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d3/8a/44032265776062a89171285ede55a0bdaadc8ac00f27f0512a71a9e3e1c8/hatchling-1.29.0-py3-none-any.whl", hash = "sha256:50af9343281f34785fab12da82e445ed987a6efb34fd8c2fc0f6e6630dbcc1b0", size = 76356, upload-time = "2026-02-23T19:42:05.197Z" },
+]
+
+[[package]]
+name = "httpcore"
+version = "1.0.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "h11" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
+]
+
+[[package]]
+name = "httpx"
+version = "0.28.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "certifi" },
+ { name = "httpcore" },
+ { name = "idna" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
+]
+
+[[package]]
+name = "id"
+version = "1.6.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/6d/04/c2156091427636080787aac190019dc64096e56a23b7364d3c1764ee3a06/id-1.6.1.tar.gz", hash = "sha256:d0732d624fb46fd4e7bc4e5152f00214450953b9e772c182c1c22964def1a069", size = 18088, upload-time = "2026-02-04T16:19:41.26Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/42/77/de194443bf38daed9452139e960c632b0ef9f9a5dd9ce605fdf18ca9f1b1/id-1.6.1-py3-none-any.whl", hash = "sha256:f5ec41ed2629a508f5d0988eda142e190c9c6da971100612c4de9ad9f9b237ca", size = 14689, upload-time = "2026-02-04T16:19:40.051Z" },
+]
+
+[[package]]
+name = "idna"
+version = "3.11"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/0703ccc57f3a7233505399edb88de3cbd678da106337b9fcde432b65ed60/idna-3.11.tar.gz", hash = "sha256:795dafcc9c04ed0c1fb032c2aa73654d8e8c5023a7df64a53f39190ada629902", size = 194582, upload-time = "2025-10-12T14:55:20.501Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },
+]
+
+[[package]]
+name = "importlib-metadata"
+version = "9.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "zipp" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a9/01/15bb152d77b21318514a96f43af312635eb2500c96b55398d020c93d86ea/importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc", size = 56405, upload-time = "2026-03-20T06:42:56.999Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/38/3d/2d244233ac4f76e38533cfcb2991c9eb4c7bf688ae0a036d30725b8faafe/importlib_metadata-9.0.0-py3-none-any.whl", hash = "sha256:2d21d1cc5a017bd0559e36150c21c830ab1dc304dedd1b7ea85d20f45ef3edd7", size = 27789, upload-time = "2026-03-20T06:42:55.665Z" },
+]
+
+[[package]]
+name = "iniconfig"
+version = "2.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
+]
+
+[[package]]
+name = "isodate"
+version = "0.7.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/54/4d/e940025e2ce31a8ce1202635910747e5a87cc3a6a6bb2d00973375014749/isodate-0.7.2.tar.gz", hash = "sha256:4cd1aa0f43ca76f4a6c6c0292a85f40b35ec2e43e315b59f06e6d32171a953e6", size = 29705, upload-time = "2024-10-08T23:04:11.5Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/15/aa/0aca39a37d3c7eb941ba736ede56d689e7be91cab5d9ca846bde3999eba6/isodate-0.7.2-py3-none-any.whl", hash = "sha256:28009937d8031054830160fce6d409ed342816b543597cece116d966c6d99e15", size = 22320, upload-time = "2024-10-08T23:04:09.501Z" },
+]
+
+[[package]]
+name = "jaraco-classes"
+version = "3.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "more-itertools" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/c0/ed4a27bc5571b99e3cff68f8a9fa5b56ff7df1c2251cc715a652ddd26402/jaraco.classes-3.4.0.tar.gz", hash = "sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd", size = 11780, upload-time = "2024-03-31T07:27:36.643Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7f/66/b15ce62552d84bbfcec9a4873ab79d993a1dd4edb922cbfccae192bd5b5f/jaraco.classes-3.4.0-py3-none-any.whl", hash = "sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790", size = 6777, upload-time = "2024-03-31T07:27:34.792Z" },
+]
+
+[[package]]
+name = "jaraco-context"
+version = "6.1.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "backports-tarfile", marker = "python_full_version < '3.12'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/af/50/4763cd07e722bb6285316d390a164bc7e479db9d90daa769f22578f698b4/jaraco_context-6.1.2.tar.gz", hash = "sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3", size = 16801, upload-time = "2026-03-20T22:13:33.922Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f2/58/bc8954bda5fcda97bd7c19be11b85f91973d67a706ed4a3aec33e7de22db/jaraco_context-6.1.2-py3-none-any.whl", hash = "sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535", size = 7871, upload-time = "2026-03-20T22:13:32.808Z" },
+]
+
+[[package]]
+name = "jaraco-functools"
+version = "4.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "more-itertools" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0f/27/056e0638a86749374d6f57d0b0db39f29509cce9313cf91bdc0ac4d91084/jaraco_functools-4.4.0.tar.gz", hash = "sha256:da21933b0417b89515562656547a77b4931f98176eb173644c0d35032a33d6bb", size = 19943, upload-time = "2025-12-21T09:29:43.6Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fd/c4/813bb09f0985cb21e959f21f2464169eca882656849adf727ac7bb7e1767/jaraco_functools-4.4.0-py3-none-any.whl", hash = "sha256:9eec1e36f45c818d9bf307c8948eb03b2b56cd44087b3cdc989abca1f20b9176", size = 10481, upload-time = "2025-12-21T09:29:42.27Z" },
+]
+
+[[package]]
+name = "jeepney"
+version = "0.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758, upload-time = "2025-02-27T18:51:01.684Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010, upload-time = "2025-02-27T18:51:00.104Z" },
+]
+
+[[package]]
+name = "keyring"
+version = "25.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "importlib-metadata", marker = "python_full_version < '3.12'" },
+ { name = "jaraco-classes" },
+ { name = "jaraco-context" },
+ { name = "jaraco-functools" },
+ { name = "jeepney", marker = "sys_platform == 'linux'" },
+ { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" },
+ { name = "secretstorage", marker = "sys_platform == 'linux'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/43/4b/674af6ef2f97d56f0ab5153bf0bfa28ccb6c3ed4d1babf4305449668807b/keyring-25.7.0.tar.gz", hash = "sha256:fe01bd85eb3f8fb3dd0405defdeac9a5b4f6f0439edbb3149577f244a2e8245b", size = 63516, upload-time = "2025-11-16T16:26:09.482Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/81/db/e655086b7f3a705df045bf0933bdd9c2f79bb3c97bfef1384598bb79a217/keyring-25.7.0-py3-none-any.whl", hash = "sha256:be4a0b195f149690c166e850609a477c532ddbfbaed96a404d4e43f8d5e2689f", size = 39160, upload-time = "2025-11-16T16:26:08.402Z" },
+]
+
+[[package]]
+name = "keyrings-alt"
+version = "5.0.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "jaraco-classes" },
+ { name = "jaraco-context" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/5c/7b/e3bf53326e0753bee11813337b1391179582ba5c6851b13e0d9502d15a50/keyrings_alt-5.0.2.tar.gz", hash = "sha256:8f097ebe9dc8b185106502b8cdb066c926d2180e13b4689fd4771a3eab7d69fb", size = 29229, upload-time = "2024-08-14T01:09:28.12Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4a/0d/9c59313ab43d0858a9a665e80763bd830dc78d5f379afc3815e123c486c2/keyrings.alt-5.0.2-py3-none-any.whl", hash = "sha256:6be74693192f3f37bbb752bfac9b86e6177076b17d2ac12a390f1d6abff8ac7c", size = 17930, upload-time = "2024-08-14T01:09:26.785Z" },
+]
+
+[[package]]
+name = "keyrings-artifacts"
+version = "0.4.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "azure-identity" },
+ { name = "keyring" },
+ { name = "keyrings-alt" },
+ { name = "pycryptodomex" },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/57/19/4c55465ff5f4bfab69199f5d7d60d506133148f6902690e5cbf81b0a0e92/keyrings_artifacts-0.4.4.tar.gz", hash = "sha256:fbe796bc0ec7eed6c14ea7dac5fefe086429b81f338ed632000221f24b0a782a", size = 14414, upload-time = "2024-08-26T14:04:46.177Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2d/ef/22ff0c2abefa211c4aa677871cbac31935ba166a88960c0ad3ca4e70af7f/keyrings_artifacts-0.4.4-py3-none-any.whl", hash = "sha256:599af967a539e13321f574da8fc2e7f98dab398a80f3696cd8c4e2d6de7e8601", size = 15592, upload-time = "2024-08-26T14:04:44.695Z" },
+]
+
+[[package]]
+name = "markdown-it-py"
+version = "4.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/5b/f5/4ec618ed16cc4f8fb3b701563655a69816155e79e24a17b651541804721d/markdown_it_py-4.0.0.tar.gz", hash = "sha256:cb0a2b4aa34f932c007117b194e945bd74e0ec24133ceb5bac59009cda1cb9f3", size = 73070, upload-time = "2025-08-11T12:57:52.854Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },
+]
+
+[[package]]
+name = "more-itertools"
+version = "10.8.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ea/5d/38b681d3fce7a266dd9ab73c66959406d565b3e85f21d5e66e1181d93721/more_itertools-10.8.0.tar.gz", hash = "sha256:f638ddf8a1a0d134181275fb5d58b086ead7c6a72429ad725c67503f13ba30bd", size = 137431, upload-time = "2025-09-02T15:23:11.018Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a4/8e/469e5a4a2f5855992e425f3cb33804cc07bf18d48f2db061aec61ce50270/more_itertools-10.8.0-py3-none-any.whl", hash = "sha256:52d4362373dcf7c52546bc4af9a86ee7c4579df9a8dc268be0a2f949d376cc9b", size = 69667, upload-time = "2025-09-02T15:23:09.635Z" },
+]
+
+[[package]]
+name = "msal"
+version = "1.35.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+ { name = "pyjwt", extra = ["crypto"] },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3c/aa/5a646093ac218e4a329391d5a31e5092a89db7d2ef1637a90b82cd0b6f94/msal-1.35.1.tar.gz", hash = "sha256:70cac18ab80a053bff86219ba64cfe3da1f307c74b009e2da57ef040eb1b5656", size = 165658, upload-time = "2026-03-04T23:38:51.812Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/96/86/16815fddf056ca998853c6dc525397edf0b43559bb4073a80d2bc7fe8009/msal-1.35.1-py3-none-any.whl", hash = "sha256:8f4e82f34b10c19e326ec69f44dc6b30171f2f7098f3720ea8a9f0c11832caa3", size = 119909, upload-time = "2026-03-04T23:38:50.452Z" },
+]
+
+[[package]]
+name = "msal-extensions"
+version = "1.3.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "msal" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/01/99/5d239b6156eddf761a636bded1118414d161bd6b7b37a9335549ed159396/msal_extensions-1.3.1.tar.gz", hash = "sha256:c5b0fd10f65ef62b5f1d62f4251d51cbcaf003fcedae8c91b040a488614be1a4", size = 23315, upload-time = "2025-03-14T23:51:03.902Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5e/75/bd9b7bb966668920f06b200e84454c8f3566b102183bc55c5473d96cb2b9/msal_extensions-1.3.1-py3-none-any.whl", hash = "sha256:96d3de4d034504e969ac5e85bae8106c8373b5c6568e4c8fa7af2eca9dbe6bca", size = 20583, upload-time = "2025-03-14T23:51:03.016Z" },
+]
+
+[[package]]
+name = "nh3"
+version = "0.3.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/4e/86/f8d3a7c9bd1bbaa181f6312c757e0b74d25f71ecf84ea3c0dc5e0f01840d/nh3-0.3.4.tar.gz", hash = "sha256:96709a379997c1b28c8974146ca660b0dcd3794f4f6d50c1ea549bab39ac6ade", size = 19520, upload-time = "2026-03-25T10:57:30.789Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fd/5e/c400663d14be2216bc084ed2befc871b7b12563f85d40904f2a4bf0dd2b7/nh3-0.3.4-cp314-cp314t-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:8b61058f34c2105d44d2a4d4241bacf603a1ef5c143b08766bbd0cf23830118f", size = 1417991, upload-time = "2026-03-25T10:56:59.13Z" },
+ { url = "https://files.pythonhosted.org/packages/36/f5/109526f5002ec41322ac8cafd50f0f154bae0c26b9607c0fcb708bdca8ec/nh3-0.3.4-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:554cc2bab281758e94d770c3fb0bf2d8be5fb403ef6b2e8841dd7c1615df7a0f", size = 790566, upload-time = "2026-03-25T10:57:00.445Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/66/38950f2b4b316ffd82ee51ed8f9143d1f56fdd620312cacc91613b77b3e7/nh3-0.3.4-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:dbe76feaa44e2ef9436f345016012a591550e77818876a8de5c8bc2a248e08df", size = 837538, upload-time = "2026-03-25T10:57:01.848Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/9f/9d6da970e9524fe360ea02a2082856390c2c8ba540409d1be6e5851887b3/nh3-0.3.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:87dac8d611b4a478400e0821a13b35770e88c266582f065e7249d6a37b0f86e8", size = 1012154, upload-time = "2026-03-25T10:57:03.592Z" },
+ { url = "https://files.pythonhosted.org/packages/54/92/7c85c33c241e9dd51dda115bd3f765e940446588cdaaca62ef8edffe675f/nh3-0.3.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:8d697e19f2995b337f648204848ac3a528eaafffc39e7ce4ac6b7a2fbe6c84af", size = 1092516, upload-time = "2026-03-25T10:57:04.726Z" },
+ { url = "https://files.pythonhosted.org/packages/16/0f/597842bdb2890999a3faa2f3fcb02db8aa6ad09320d3d843ff6d0a1f737b/nh3-0.3.4-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:7cae217f031809321db962cd7e092bda8d4e95a87f78c0226628fa6c2ea8ebc5", size = 1053793, upload-time = "2026-03-25T10:57:06.171Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/32/669da65147bc10746d2e1d7a8a3dbfbffe0315f419e74b559e2ee3471a01/nh3-0.3.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:07999b998bf89692738f15c0eac76a416382932f855709e0b7488b595c30ec89", size = 1035975, upload-time = "2026-03-25T10:57:07.292Z" },
+ { url = "https://files.pythonhosted.org/packages/a1/7e/9e97a8b3c5161c79b4bf21cc54e9334860a52cc54ede15bf2239ef494b73/nh3-0.3.4-cp314-cp314t-win32.whl", hash = "sha256:ca90397c8d36c1535bf1988b2bed006597337843a164c7ec269dc8813f37536b", size = 600419, upload-time = "2026-03-25T10:57:08.342Z" },
+ { url = "https://files.pythonhosted.org/packages/e0/c7/6849d8d4295d3997d148eacb2d4b1c9faada4895ee3c1b1e12e72f4611e2/nh3-0.3.4-cp314-cp314t-win_amd64.whl", hash = "sha256:41e46b3499918ab6128b6421677b316e79869d0c140da24069d220a94f4e72d1", size = 613342, upload-time = "2026-03-25T10:57:09.593Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/0e/14a3f510f36c20b922c123a2730f071f938d006fb513aacfd46d6cbc03a7/nh3-0.3.4-cp314-cp314t-win_arm64.whl", hash = "sha256:80b955d802bf365bd42e09f6c3d64567dce777d20e97968d94b3e9d9e99b265e", size = 607025, upload-time = "2026-03-25T10:57:10.959Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/57/a97955bc95960cfb1f0517043d60a121f4ba93fde252d4d9ffd3c2a9eead/nh3-0.3.4-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:d8bebcb20ab4b91858385cd98fe58046ec4a624275b45ef9b976475604f45b49", size = 1439519, upload-time = "2026-03-25T10:57:12.019Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/60/c9a33361da8cde7c7760f091cd10467bc470634e4eea31c8bb70935b00a4/nh3-0.3.4-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0d825722a1e8cbc87d7ca1e47ffb1d2a6cf343ad4c1b8465becf7cadcabcdfd0", size = 833798, upload-time = "2026-03-25T10:57:13.264Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/19/9487790780b8c94eacca37866c1270b747a4af8e244d43b3b550fddbbf62/nh3-0.3.4-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4aa8b43e68c26b68069a3b6cef09de166d1d7fa140cf8d77e409a46cbf742e44", size = 820414, upload-time = "2026-03-25T10:57:14.236Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/b4/c6a340dd321d20b1e4a663307032741da045685c87403926c43656f6f5ec/nh3-0.3.4-cp38-abi3-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:f5f214618ad5eff4f2a6b13a8d4da4d9e7f37c569d90a13fb9f0caaf7d04fe21", size = 1061531, upload-time = "2026-03-25T10:57:15.384Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/49/f6b4b474e0032e4bcbb7174b44e4cf6915670e09c62421deb06ccfcb88b8/nh3-0.3.4-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3390e4333883673a684ce16c1716b481e91782d6f56dec5c85fed9feedb23382", size = 1021889, upload-time = "2026-03-25T10:57:16.454Z" },
+ { url = "https://files.pythonhosted.org/packages/43/da/e52a6941746d1f974752af3fc8591f1dbcdcf7fd8c726c7d99f444ba820e/nh3-0.3.4-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:18a2e44ccb29cbb45071b8f3f2dab9ebfb41a6516f328f91f1f1fd18196239a4", size = 912965, upload-time = "2026-03-25T10:57:17.624Z" },
+ { url = "https://files.pythonhosted.org/packages/d6/b7/ec1cbc6b297a808c513f59f501656389623fc09ad6a58c640851289c7854/nh3-0.3.4-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0961a27dc2057c38d0364cb05880e1997ae1c80220cbc847db63213720b8f304", size = 804975, upload-time = "2026-03-25T10:57:18.994Z" },
+ { url = "https://files.pythonhosted.org/packages/a9/56/b1275aa2c6510191eed76178da4626b0900402439cb9f27d6b9bf7c6d5e9/nh3-0.3.4-cp38-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:9337517edb7c10228252cce2898e20fb3d77e32ffaccbb3c66897927d74215a0", size = 833400, upload-time = "2026-03-25T10:57:20.086Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/a5/5d574ffa3c6e49a5364d1b25ebad165501c055340056671493beb467a15e/nh3-0.3.4-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d866701affe67a5171b916b5c076e767a74c6a9efb7fb2006eb8d3c5f9a293d5", size = 854277, upload-time = "2026-03-25T10:57:21.433Z" },
+ { url = "https://files.pythonhosted.org/packages/79/36/8aeb2ab21517cefa212db109e41024e02650716cb42bf293d0a88437a92d/nh3-0.3.4-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:47d749d99ae005ab19517224140b280dd56e77b33afb82f9b600e106d0458003", size = 1022021, upload-time = "2026-03-25T10:57:22.433Z" },
+ { url = "https://files.pythonhosted.org/packages/9c/95/9fd860997685e64abe2d5a995ca2eb5004c0fb6d6585429612a7871548b9/nh3-0.3.4-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:f987cb56458323405e8e5ea827e1befcf141ffa0c0ac797d6d02e6b646056d9a", size = 1103526, upload-time = "2026-03-25T10:57:23.487Z" },
+ { url = "https://files.pythonhosted.org/packages/7d/0d/df545070614c1007f0109bb004230226c9000e7857c9785583ec25cda9d7/nh3-0.3.4-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:883d5a6d6ee8078c4afc8e96e022fe579c4c265775ff6ee21e39b8c542cabab3", size = 1068050, upload-time = "2026-03-25T10:57:24.624Z" },
+ { url = "https://files.pythonhosted.org/packages/94/d5/17b016df52df052f714c53be71df26a1943551d9931e9383b92c998b88f8/nh3-0.3.4-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:75643c22f5092d8e209f766ee8108c400bc1e44760fc94d2d638eb138d18f853", size = 1046037, upload-time = "2026-03-25T10:57:25.799Z" },
+ { url = "https://files.pythonhosted.org/packages/51/39/49f737907e6ab2b4ca71855d3bd63dd7958862e9c8b94fb4e5b18ccf6988/nh3-0.3.4-cp38-abi3-win32.whl", hash = "sha256:72e4e9ca1c4bd41b4a28b0190edc2e21e3f71496acd36a0162858e1a28db3d7e", size = 609542, upload-time = "2026-03-25T10:57:27.112Z" },
+ { url = "https://files.pythonhosted.org/packages/73/4f/af8e9071d7464575a7316831938237ffc9d92d27f163dbdd964b1309cd9b/nh3-0.3.4-cp38-abi3-win_amd64.whl", hash = "sha256:c10b1f0c741e257a5cb2978d6bac86e7c784ab20572724b20c6402c2e24bce75", size = 624244, upload-time = "2026-03-25T10:57:28.302Z" },
+ { url = "https://files.pythonhosted.org/packages/44/0c/37695d6b0168f6714b5c492331636a9e6123d6ec22d25876c68d06eab1b8/nh3-0.3.4-cp38-abi3-win_arm64.whl", hash = "sha256:43ad4eedee7e049b9069bc015b7b095d320ed6d167ecec111f877de1540656e9", size = 616649, upload-time = "2026-03-25T10:57:29.623Z" },
+]
+
+[[package]]
+name = "packaging"
+version = "26.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/65/ee/299d360cdc32edc7d2cf530f3accf79c4fca01e96ffc950d8a52213bd8e4/packaging-26.0.tar.gz", hash = "sha256:00243ae351a257117b6a241061796684b084ed1c516a08c48a3f7e147a9d80b4", size = 143416, upload-time = "2026-01-21T20:50:39.064Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b7/b9/c538f279a4e237a006a2c98387d081e9eb060d203d8ed34467cc0f0b9b53/packaging-26.0-py3-none-any.whl", hash = "sha256:b36f1fef9334a5588b4166f8bcd26a14e521f2b55e6b9de3aaa80d3ff7a37529", size = 74366, upload-time = "2026-01-21T20:50:37.788Z" },
+]
+
+[[package]]
+name = "pastel"
+version = "0.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/76/f1/4594f5e0fcddb6953e5b8fe00da8c317b8b41b547e2b3ae2da7512943c62/pastel-0.2.1.tar.gz", hash = "sha256:e6581ac04e973cac858828c6202c1e1e81fee1dc7de7683f3e1ffe0bfd8a573d", size = 7555, upload-time = "2020-09-16T19:21:12.43Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/aa/18/a8444036c6dd65ba3624c63b734d3ba95ba63ace513078e1580590075d21/pastel-0.2.1-py2.py3-none-any.whl", hash = "sha256:4349225fcdf6c2bb34d483e523475de5bb04a5c10ef711263452cb37d7dd4364", size = 5955, upload-time = "2020-09-16T19:21:11.409Z" },
+]
+
+[[package]]
+name = "pathspec"
+version = "1.0.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/fa/36/e27608899f9b8d4dff0617b2d9ab17ca5608956ca44461ac14ac48b44015/pathspec-1.0.4.tar.gz", hash = "sha256:0210e2ae8a21a9137c0d470578cb0e595af87edaa6ebf12ff176f14a02e0e645", size = 131200, upload-time = "2026-01-27T03:59:46.938Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ef/3c/2c197d226f9ea224a9ab8d197933f9da0ae0aac5b6e0f884e2b8d9c8e9f7/pathspec-1.0.4-py3-none-any.whl", hash = "sha256:fb6ae2fd4e7c921a165808a552060e722767cfa526f99ca5156ed2ce45a5c723", size = 55206, upload-time = "2026-01-27T03:59:45.137Z" },
+]
+
+[[package]]
+name = "pluggy"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
+]
+
+[[package]]
+name = "poethepoet"
+version = "0.42.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pastel" },
+ { name = "pyyaml" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/05/9b/e717572686bbf23e17483389c1bf3a381ca2427c84c7e0af0cdc0f23fccc/poethepoet-0.42.1.tar.gz", hash = "sha256:205747e276062c2aaba8afd8a98838f8a3a0237b7ab94715fab8d82718aac14f", size = 93209, upload-time = "2026-02-26T22:57:50.883Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c8/68/75fa0a5ef39718ea6ba7ab6a3d031fa93640e57585580cec85539540bb65/poethepoet-0.42.1-py3-none-any.whl", hash = "sha256:d8d1345a5ca521be9255e7c13bc2c4c8698ed5e5ac5e9e94890d239fcd423d0a", size = 119967, upload-time = "2026-02-26T22:57:49.467Z" },
+]
+
+[[package]]
+name = "quicksand"
+version = "0.10.3.dev0"
+source = { editable = "packages/quicksand" }
+dependencies = [
+ { name = "quicksand-core" },
+]
+
+[package.optional-dependencies]
+all = [
+ { name = "quicksand-alpine" },
+ { name = "quicksand-alpine-desktop" },
+ { name = "quicksand-image-tools" },
+ { name = "quicksand-qemu" },
+ { name = "quicksand-ubuntu" },
+ { name = "quicksand-ubuntu-desktop" },
+]
+alpine = [
+ { name = "quicksand-alpine" },
+]
+alpine-desktop = [
+ { name = "quicksand-alpine-desktop" },
+]
+dev = [
+ { name = "quicksand-base-scaffold" },
+ { name = "quicksand-image-tools" },
+ { name = "quicksand-overlay-scaffold" },
+]
+qemu = [
+ { name = "quicksand-qemu" },
+]
+ubuntu = [
+ { name = "quicksand-ubuntu" },
+]
+ubuntu-desktop = [
+ { name = "quicksand-ubuntu-desktop" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "quicksand-alpine", marker = "extra == 'all'", editable = "packages/quicksand-alpine" },
+ { name = "quicksand-alpine", marker = "extra == 'alpine'", editable = "packages/quicksand-alpine" },
+ { name = "quicksand-alpine-desktop", marker = "extra == 'all'", editable = "packages/quicksand-alpine-desktop" },
+ { name = "quicksand-alpine-desktop", marker = "extra == 'alpine-desktop'", editable = "packages/quicksand-alpine-desktop" },
+ { name = "quicksand-base-scaffold", marker = "extra == 'dev'", editable = "packages/dev/quicksand-base-scaffold" },
+ { name = "quicksand-core", editable = "packages/quicksand-core" },
+ { name = "quicksand-image-tools", marker = "extra == 'all'", editable = "packages/dev/quicksand-image-tools" },
+ { name = "quicksand-image-tools", marker = "extra == 'dev'", editable = "packages/dev/quicksand-image-tools" },
+ { name = "quicksand-overlay-scaffold", marker = "extra == 'dev'", editable = "packages/dev/quicksand-overlay-scaffold" },
+ { name = "quicksand-qemu", marker = "extra == 'all'", editable = "packages/quicksand-qemu" },
+ { name = "quicksand-qemu", marker = "extra == 'qemu'", editable = "packages/quicksand-qemu" },
+ { name = "quicksand-ubuntu", marker = "extra == 'all'", editable = "packages/quicksand-ubuntu" },
+ { name = "quicksand-ubuntu", marker = "extra == 'ubuntu'", editable = "packages/quicksand-ubuntu" },
+ { name = "quicksand-ubuntu-desktop", marker = "extra == 'all'", editable = "packages/quicksand-ubuntu-desktop" },
+ { name = "quicksand-ubuntu-desktop", marker = "extra == 'ubuntu-desktop'", editable = "packages/quicksand-ubuntu-desktop" },
+]
+provides-extras = ["qemu", "ubuntu", "alpine", "alpine-desktop", "ubuntu-desktop", "dev", "all"]
+
+[[package]]
+name = "quicksand-alpine"
+version = "0.8.4"
+source = { editable = "packages/quicksand-alpine" }
+dependencies = [
+ { name = "quicksand-core" },
+]
+
+[package.dev-dependencies]
+dev = [
+ { name = "quicksand-image-tools" },
+]
+
+[package.metadata]
+requires-dist = [{ name = "quicksand-core", editable = "packages/quicksand-core" }]
+
+[package.metadata.requires-dev]
+dev = [{ name = "quicksand-image-tools", editable = "packages/dev/quicksand-image-tools" }]
+
+[[package]]
+name = "quicksand-alpine-desktop"
+version = "0.8.4"
+source = { editable = "packages/quicksand-alpine-desktop" }
+dependencies = [
+ { name = "quicksand-alpine" },
+ { name = "quicksand-core" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "quicksand-alpine", editable = "packages/quicksand-alpine" },
+ { name = "quicksand-core", editable = "packages/quicksand-core" },
+]
+
+[package.metadata.requires-dev]
+dev = []
+
+[[package]]
+name = "quicksand-base-scaffold"
+version = "0.2.4"
+source = { editable = "packages/dev/quicksand-base-scaffold" }
+dependencies = [
+ { name = "quicksand-core" },
+ { name = "tomlkit" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "quicksand-core", editable = "packages/quicksand-core" },
+ { name = "tomlkit", specifier = ">=0.13" },
+]
+
+[[package]]
+name = "quicksand-build-tools"
+version = "0.4.4.dev0"
+source = { editable = "packages/dev/quicksand-build-tools" }
+
+[[package]]
+name = "quicksand-core"
+version = "0.10.3.dev0"
+source = { editable = "packages/quicksand-core" }
+dependencies = [
+ { name = "httpx" },
+ { name = "quicksand-smb" },
+ { name = "pydantic" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "httpx", specifier = ">=0.27,<1.0" },
+ { name = "quicksand-smb", editable = "packages/quicksand-smb" },
+ { name = "pydantic", specifier = ">=2.0" },
+]
+
+[[package]]
+name = "quicksand-gh-runners"
+version = "0.1.0"
+source = { editable = "packages/dev/quicksand-gh-runners" }
+dependencies = [
+ { name = "azure-identity" },
+ { name = "azure-mgmt-compute" },
+ { name = "requests" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "azure-identity" },
+ { name = "azure-mgmt-compute" },
+ { name = "requests" },
+]
+
+[[package]]
+name = "quicksand-image-tools"
+version = "0.4.4.dev0"
+source = { editable = "packages/dev/quicksand-image-tools" }
+dependencies = [
+ { name = "quicksand-core" },
+]
+
+[package.metadata]
+requires-dist = [{ name = "quicksand-core", editable = "packages/quicksand-core" }]
+
+[[package]]
+name = "quicksand-overlay-scaffold"
+version = "0.2.4"
+source = { editable = "packages/dev/quicksand-overlay-scaffold" }
+dependencies = [
+ { name = "quicksand-core" },
+ { name = "quicksand-ubuntu" },
+ { name = "tomlkit" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "quicksand-core", editable = "packages/quicksand-core" },
+ { name = "quicksand-ubuntu", editable = "packages/quicksand-ubuntu" },
+ { name = "tomlkit", specifier = ">=0.13" },
+]
+
+[[package]]
+name = "quicksand-qemu"
+version = "0.4.8"
+source = { editable = "packages/quicksand-qemu" }
+
+[[package]]
+name = "quicksand-smb"
+version = "0.3.4.dev0"
+source = { editable = "packages/quicksand-smb" }
+
+[[package]]
+name = "quicksand-ubuntu"
+version = "0.8.4"
+source = { editable = "packages/quicksand-ubuntu" }
+dependencies = [
+ { name = "quicksand-core" },
+]
+
+[package.dev-dependencies]
+dev = [
+ { name = "quicksand-image-tools" },
+]
+
+[package.metadata]
+requires-dist = [{ name = "quicksand-core", editable = "packages/quicksand-core" }]
+
+[package.metadata.requires-dev]
+dev = [{ name = "quicksand-image-tools", editable = "packages/dev/quicksand-image-tools" }]
+
+[[package]]
+name = "quicksand-ubuntu-desktop"
+version = "0.8.4"
+source = { editable = "packages/quicksand-ubuntu-desktop" }
+dependencies = [
+ { name = "quicksand-core" },
+ { name = "quicksand-ubuntu" },
+]
+
+[package.metadata]
+requires-dist = [
+ { name = "quicksand-core", editable = "packages/quicksand-core" },
+ { name = "quicksand-ubuntu", editable = "packages/quicksand-ubuntu" },
+]
+
+[package.metadata.requires-dev]
+dev = []
+
+[[package]]
+name = "pycparser"
+version = "3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" },
+]
+
+[[package]]
+name = "pycryptodomex"
+version = "3.23.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c9/85/e24bf90972a30b0fcd16c73009add1d7d7cd9140c2498a68252028899e41/pycryptodomex-3.23.0.tar.gz", hash = "sha256:71909758f010c82bc99b0abf4ea12012c98962fbf0583c2164f8b84533c2e4da", size = 4922157, upload-time = "2025-05-17T17:23:41.434Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/00/10edb04777069a42490a38c137099d4b17ba6e36a4e6e28bdc7470e9e853/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:7b37e08e3871efe2187bc1fd9320cc81d87caf19816c648f24443483005ff886", size = 2498764, upload-time = "2025-05-17T17:22:21.453Z" },
+ { url = "https://files.pythonhosted.org/packages/6b/3f/2872a9c2d3a27eac094f9ceaa5a8a483b774ae69018040ea3240d5b11154/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:91979028227543010d7b2ba2471cf1d1e398b3f183cb105ac584df0c36dac28d", size = 1643012, upload-time = "2025-05-17T17:22:23.702Z" },
+ { url = "https://files.pythonhosted.org/packages/70/af/774c2e2b4f6570fbf6a4972161adbb183aeeaa1863bde31e8706f123bf92/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b8962204c47464d5c1c4038abeadd4514a133b28748bcd9fa5b6d62e3cec6fa", size = 2187643, upload-time = "2025-05-17T17:22:26.37Z" },
+ { url = "https://files.pythonhosted.org/packages/de/a3/71065b24cb889d537954cedc3ae5466af00a2cabcff8e29b73be047e9a19/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a33986a0066860f7fcf7c7bd2bc804fa90e434183645595ae7b33d01f3c91ed8", size = 2273762, upload-time = "2025-05-17T17:22:28.313Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/0b/ff6f43b7fbef4d302c8b981fe58467b8871902cdc3eb28896b52421422cc/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7947ab8d589e3178da3d7cdeabe14f841b391e17046954f2fbcd941705762b5", size = 2313012, upload-time = "2025-05-17T17:22:30.57Z" },
+ { url = "https://files.pythonhosted.org/packages/02/de/9d4772c0506ab6da10b41159493657105d3f8bb5c53615d19452afc6b315/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c25e30a20e1b426e1f0fa00131c516f16e474204eee1139d1603e132acffc314", size = 2186856, upload-time = "2025-05-17T17:22:32.819Z" },
+ { url = "https://files.pythonhosted.org/packages/28/ad/8b30efcd6341707a234e5eba5493700a17852ca1ac7a75daa7945fcf6427/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:da4fa650cef02db88c2b98acc5434461e027dce0ae8c22dd5a69013eaf510006", size = 2347523, upload-time = "2025-05-17T17:22:35.386Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/02/16868e9f655b7670dbb0ac4f2844145cbc42251f916fc35c414ad2359849/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:58b851b9effd0d072d4ca2e4542bf2a4abcf13c82a29fd2c93ce27ee2a2e9462", size = 2272825, upload-time = "2025-05-17T17:22:37.632Z" },
+ { url = "https://files.pythonhosted.org/packages/ca/18/4ca89ac737230b52ac8ffaca42f9c6f1fd07c81a6cd821e91af79db60632/pycryptodomex-3.23.0-cp313-cp313t-win32.whl", hash = "sha256:a9d446e844f08299236780f2efa9898c818fe7e02f17263866b8550c7d5fb328", size = 1772078, upload-time = "2025-05-17T17:22:40Z" },
+ { url = "https://files.pythonhosted.org/packages/73/34/13e01c322db027682e00986873eca803f11c56ade9ba5bbf3225841ea2d4/pycryptodomex-3.23.0-cp313-cp313t-win_amd64.whl", hash = "sha256:bc65bdd9fc8de7a35a74cab1c898cab391a4add33a8fe740bda00f5976ca4708", size = 1803656, upload-time = "2025-05-17T17:22:42.139Z" },
+ { url = "https://files.pythonhosted.org/packages/54/68/9504c8796b1805d58f4425002bcca20f12880e6fa4dc2fc9a668705c7a08/pycryptodomex-3.23.0-cp313-cp313t-win_arm64.whl", hash = "sha256:c885da45e70139464f082018ac527fdaad26f1657a99ee13eecdce0f0ca24ab4", size = 1707172, upload-time = "2025-05-17T17:22:44.704Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/9c/1a8f35daa39784ed8adf93a694e7e5dc15c23c741bbda06e1d45f8979e9e/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:06698f957fe1ab229a99ba2defeeae1c09af185baa909a31a5d1f9d42b1aaed6", size = 2499240, upload-time = "2025-05-17T17:22:46.953Z" },
+ { url = "https://files.pythonhosted.org/packages/7a/62/f5221a191a97157d240cf6643747558759126c76ee92f29a3f4aee3197a5/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b2c2537863eccef2d41061e82a881dcabb04944c5c06c5aa7110b577cc487545", size = 1644042, upload-time = "2025-05-17T17:22:49.098Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/fd/5a054543c8988d4ed7b612721d7e78a4b9bf36bc3c5ad45ef45c22d0060e/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:43c446e2ba8df8889e0e16f02211c25b4934898384c1ec1ec04d7889c0333587", size = 2186227, upload-time = "2025-05-17T17:22:51.139Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/a9/8862616a85cf450d2822dbd4fff1fcaba90877907a6ff5bc2672cafe42f8/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f489c4765093fb60e2edafdf223397bc716491b2b69fe74367b70d6999257a5c", size = 2272578, upload-time = "2025-05-17T17:22:53.676Z" },
+ { url = "https://files.pythonhosted.org/packages/46/9f/bda9c49a7c1842820de674ab36c79f4fbeeee03f8ff0e4f3546c3889076b/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bdc69d0d3d989a1029df0eed67cc5e8e5d968f3724f4519bd03e0ec68df7543c", size = 2312166, upload-time = "2025-05-17T17:22:56.585Z" },
+ { url = "https://files.pythonhosted.org/packages/03/cc/870b9bf8ca92866ca0186534801cf8d20554ad2a76ca959538041b7a7cf4/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6bbcb1dd0f646484939e142462d9e532482bc74475cecf9c4903d4e1cd21f003", size = 2185467, upload-time = "2025-05-17T17:22:59.237Z" },
+ { url = "https://files.pythonhosted.org/packages/96/e3/ce9348236d8e669fea5dd82a90e86be48b9c341210f44e25443162aba187/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_i686.whl", hash = "sha256:8a4fcd42ccb04c31268d1efeecfccfd1249612b4de6374205376b8f280321744", size = 2346104, upload-time = "2025-05-17T17:23:02.112Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/e9/e869bcee87beb89040263c416a8a50204f7f7a83ac11897646c9e71e0daf/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:55ccbe27f049743a4caf4f4221b166560d3438d0b1e5ab929e07ae1702a4d6fd", size = 2271038, upload-time = "2025-05-17T17:23:04.872Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/67/09ee8500dd22614af5fbaa51a4aee6e342b5fa8aecf0a6cb9cbf52fa6d45/pycryptodomex-3.23.0-cp37-abi3-win32.whl", hash = "sha256:189afbc87f0b9f158386bf051f720e20fa6145975f1e76369303d0f31d1a8d7c", size = 1771969, upload-time = "2025-05-17T17:23:07.115Z" },
+ { url = "https://files.pythonhosted.org/packages/69/96/11f36f71a865dd6df03716d33bd07a67e9d20f6b8d39820470b766af323c/pycryptodomex-3.23.0-cp37-abi3-win_amd64.whl", hash = "sha256:52e5ca58c3a0b0bd5e100a9fbc8015059b05cffc6c66ce9d98b4b45e023443b9", size = 1803124, upload-time = "2025-05-17T17:23:09.267Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/93/45c1cdcbeb182ccd2e144c693eaa097763b08b38cded279f0053ed53c553/pycryptodomex-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:02d87b80778c171445d67e23d1caef279bf4b25c3597050ccd2e13970b57fd51", size = 1707161, upload-time = "2025-05-17T17:23:11.414Z" },
+]
+
+[[package]]
+name = "pydantic"
+version = "2.12.5"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "annotated-types" },
+ { name = "pydantic-core" },
+ { name = "typing-extensions" },
+ { name = "typing-inspection" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/69/44/36f1a6e523abc58ae5f928898e4aca2e0ea509b5aa6f6f392a5d882be928/pydantic-2.12.5.tar.gz", hash = "sha256:4d351024c75c0f085a9febbb665ce8c0c6ec5d30e903bdb6394b7ede26aebb49", size = 821591, upload-time = "2025-11-26T15:11:46.471Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5a/87/b70ad306ebb6f9b585f114d0ac2137d792b48be34d732d60e597c2f8465a/pydantic-2.12.5-py3-none-any.whl", hash = "sha256:e561593fccf61e8a20fc46dfc2dfe075b8be7d0188df33f221ad1f0139180f9d", size = 463580, upload-time = "2025-11-26T15:11:44.605Z" },
+]
+
+[[package]]
+name = "pydantic-core"
+version = "2.41.5"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/71/70/23b021c950c2addd24ec408e9ab05d59b035b39d97cdc1130e1bce647bb6/pydantic_core-2.41.5.tar.gz", hash = "sha256:08daa51ea16ad373ffd5e7606252cc32f07bc72b28284b6bc9c6df804816476e", size = 460952, upload-time = "2025-11-04T13:43:49.098Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e8/72/74a989dd9f2084b3d9530b0915fdda64ac48831c30dbf7c72a41a5232db8/pydantic_core-2.41.5-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:a3a52f6156e73e7ccb0f8cced536adccb7042be67cb45f9562e12b319c119da6", size = 2105873, upload-time = "2025-11-04T13:39:31.373Z" },
+ { url = "https://files.pythonhosted.org/packages/12/44/37e403fd9455708b3b942949e1d7febc02167662bf1a7da5b78ee1ea2842/pydantic_core-2.41.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7f3bf998340c6d4b0c9a2f02d6a400e51f123b59565d74dc60d252ce888c260b", size = 1899826, upload-time = "2025-11-04T13:39:32.897Z" },
+ { url = "https://files.pythonhosted.org/packages/33/7f/1d5cab3ccf44c1935a359d51a8a2a9e1a654b744b5e7f80d41b88d501eec/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:378bec5c66998815d224c9ca994f1e14c0c21cb95d2f52b6021cc0b2a58f2a5a", size = 1917869, upload-time = "2025-11-04T13:39:34.469Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/6a/30d94a9674a7fe4f4744052ed6c5e083424510be1e93da5bc47569d11810/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e7b576130c69225432866fe2f4a469a85a54ade141d96fd396dffcf607b558f8", size = 2063890, upload-time = "2025-11-04T13:39:36.053Z" },
+ { url = "https://files.pythonhosted.org/packages/50/be/76e5d46203fcb2750e542f32e6c371ffa9b8ad17364cf94bb0818dbfb50c/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6cb58b9c66f7e4179a2d5e0f849c48eff5c1fca560994d6eb6543abf955a149e", size = 2229740, upload-time = "2025-11-04T13:39:37.753Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/ee/fed784df0144793489f87db310a6bbf8118d7b630ed07aa180d6067e653a/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:88942d3a3dff3afc8288c21e565e476fc278902ae4d6d134f1eeda118cc830b1", size = 2350021, upload-time = "2025-11-04T13:39:40.94Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/be/8fed28dd0a180dca19e72c233cbf58efa36df055e5b9d90d64fd1740b828/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f31d95a179f8d64d90f6831d71fa93290893a33148d890ba15de25642c5d075b", size = 2066378, upload-time = "2025-11-04T13:39:42.523Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/3b/698cf8ae1d536a010e05121b4958b1257f0b5522085e335360e53a6b1c8b/pydantic_core-2.41.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c1df3d34aced70add6f867a8cf413e299177e0c22660cc767218373d0779487b", size = 2175761, upload-time = "2025-11-04T13:39:44.553Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/ba/15d537423939553116dea94ce02f9c31be0fa9d0b806d427e0308ec17145/pydantic_core-2.41.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:4009935984bd36bd2c774e13f9a09563ce8de4abaa7226f5108262fa3e637284", size = 2146303, upload-time = "2025-11-04T13:39:46.238Z" },
+ { url = "https://files.pythonhosted.org/packages/58/7f/0de669bf37d206723795f9c90c82966726a2ab06c336deba4735b55af431/pydantic_core-2.41.5-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:34a64bc3441dc1213096a20fe27e8e128bd3ff89921706e83c0b1ac971276594", size = 2340355, upload-time = "2025-11-04T13:39:48.002Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/de/e7482c435b83d7e3c3ee5ee4451f6e8973cff0eb6007d2872ce6383f6398/pydantic_core-2.41.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:c9e19dd6e28fdcaa5a1de679aec4141f691023916427ef9bae8584f9c2fb3b0e", size = 2319875, upload-time = "2025-11-04T13:39:49.705Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/e6/8c9e81bb6dd7560e33b9053351c29f30c8194b72f2d6932888581f503482/pydantic_core-2.41.5-cp311-cp311-win32.whl", hash = "sha256:2c010c6ded393148374c0f6f0bf89d206bf3217f201faa0635dcd56bd1520f6b", size = 1987549, upload-time = "2025-11-04T13:39:51.842Z" },
+ { url = "https://files.pythonhosted.org/packages/11/66/f14d1d978ea94d1bc21fc98fcf570f9542fe55bfcc40269d4e1a21c19bf7/pydantic_core-2.41.5-cp311-cp311-win_amd64.whl", hash = "sha256:76ee27c6e9c7f16f47db7a94157112a2f3a00e958bc626e2f4ee8bec5c328fbe", size = 2011305, upload-time = "2025-11-04T13:39:53.485Z" },
+ { url = "https://files.pythonhosted.org/packages/56/d8/0e271434e8efd03186c5386671328154ee349ff0354d83c74f5caaf096ed/pydantic_core-2.41.5-cp311-cp311-win_arm64.whl", hash = "sha256:4bc36bbc0b7584de96561184ad7f012478987882ebf9f9c389b23f432ea3d90f", size = 1972902, upload-time = "2025-11-04T13:39:56.488Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/5d/5f6c63eebb5afee93bcaae4ce9a898f3373ca23df3ccaef086d0233a35a7/pydantic_core-2.41.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:f41a7489d32336dbf2199c8c0a215390a751c5b014c2c1c5366e817202e9cdf7", size = 2110990, upload-time = "2025-11-04T13:39:58.079Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/32/9c2e8ccb57c01111e0fd091f236c7b371c1bccea0fa85247ac55b1e2b6b6/pydantic_core-2.41.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:070259a8818988b9a84a449a2a7337c7f430a22acc0859c6b110aa7212a6d9c0", size = 1896003, upload-time = "2025-11-04T13:39:59.956Z" },
+ { url = "https://files.pythonhosted.org/packages/68/b8/a01b53cb0e59139fbc9e4fda3e9724ede8de279097179be4ff31f1abb65a/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e96cea19e34778f8d59fe40775a7a574d95816eb150850a85a7a4c8f4b94ac69", size = 1919200, upload-time = "2025-11-04T13:40:02.241Z" },
+ { url = "https://files.pythonhosted.org/packages/38/de/8c36b5198a29bdaade07b5985e80a233a5ac27137846f3bc2d3b40a47360/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ed2e99c456e3fadd05c991f8f437ef902e00eedf34320ba2b0842bd1c3ca3a75", size = 2052578, upload-time = "2025-11-04T13:40:04.401Z" },
+ { url = "https://files.pythonhosted.org/packages/00/b5/0e8e4b5b081eac6cb3dbb7e60a65907549a1ce035a724368c330112adfdd/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:65840751b72fbfd82c3c640cff9284545342a4f1eb1586ad0636955b261b0b05", size = 2208504, upload-time = "2025-11-04T13:40:06.072Z" },
+ { url = "https://files.pythonhosted.org/packages/77/56/87a61aad59c7c5b9dc8caad5a41a5545cba3810c3e828708b3d7404f6cef/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e536c98a7626a98feb2d3eaf75944ef6f3dbee447e1f841eae16f2f0a72d8ddc", size = 2335816, upload-time = "2025-11-04T13:40:07.835Z" },
+ { url = "https://files.pythonhosted.org/packages/0d/76/941cc9f73529988688a665a5c0ecff1112b3d95ab48f81db5f7606f522d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eceb81a8d74f9267ef4081e246ffd6d129da5d87e37a77c9bde550cb04870c1c", size = 2075366, upload-time = "2025-11-04T13:40:09.804Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/43/ebef01f69baa07a482844faaa0a591bad1ef129253ffd0cdaa9d8a7f72d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d38548150c39b74aeeb0ce8ee1d8e82696f4a4e16ddc6de7b1d8823f7de4b9b5", size = 2171698, upload-time = "2025-11-04T13:40:12.004Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/87/41f3202e4193e3bacfc2c065fab7706ebe81af46a83d3e27605029c1f5a6/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c23e27686783f60290e36827f9c626e63154b82b116d7fe9adba1fda36da706c", size = 2132603, upload-time = "2025-11-04T13:40:13.868Z" },
+ { url = "https://files.pythonhosted.org/packages/49/7d/4c00df99cb12070b6bccdef4a195255e6020a550d572768d92cc54dba91a/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:482c982f814460eabe1d3bb0adfdc583387bd4691ef00b90575ca0d2b6fe2294", size = 2329591, upload-time = "2025-11-04T13:40:15.672Z" },
+ { url = "https://files.pythonhosted.org/packages/cc/6a/ebf4b1d65d458f3cda6a7335d141305dfa19bdc61140a884d165a8a1bbc7/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:bfea2a5f0b4d8d43adf9d7b8bf019fb46fdd10a2e5cde477fbcb9d1fa08c68e1", size = 2319068, upload-time = "2025-11-04T13:40:17.532Z" },
+ { url = "https://files.pythonhosted.org/packages/49/3b/774f2b5cd4192d5ab75870ce4381fd89cf218af999515baf07e7206753f0/pydantic_core-2.41.5-cp312-cp312-win32.whl", hash = "sha256:b74557b16e390ec12dca509bce9264c3bbd128f8a2c376eaa68003d7f327276d", size = 1985908, upload-time = "2025-11-04T13:40:19.309Z" },
+ { url = "https://files.pythonhosted.org/packages/86/45/00173a033c801cacf67c190fef088789394feaf88a98a7035b0e40d53dc9/pydantic_core-2.41.5-cp312-cp312-win_amd64.whl", hash = "sha256:1962293292865bca8e54702b08a4f26da73adc83dd1fcf26fbc875b35d81c815", size = 2020145, upload-time = "2025-11-04T13:40:21.548Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/22/91fbc821fa6d261b376a3f73809f907cec5ca6025642c463d3488aad22fb/pydantic_core-2.41.5-cp312-cp312-win_arm64.whl", hash = "sha256:1746d4a3d9a794cacae06a5eaaccb4b8643a131d45fbc9af23e353dc0a5ba5c3", size = 1976179, upload-time = "2025-11-04T13:40:23.393Z" },
+ { url = "https://files.pythonhosted.org/packages/87/06/8806241ff1f70d9939f9af039c6c35f2360cf16e93c2ca76f184e76b1564/pydantic_core-2.41.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:941103c9be18ac8daf7b7adca8228f8ed6bb7a1849020f643b3a14d15b1924d9", size = 2120403, upload-time = "2025-11-04T13:40:25.248Z" },
+ { url = "https://files.pythonhosted.org/packages/94/02/abfa0e0bda67faa65fef1c84971c7e45928e108fe24333c81f3bfe35d5f5/pydantic_core-2.41.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:112e305c3314f40c93998e567879e887a3160bb8689ef3d2c04b6cc62c33ac34", size = 1896206, upload-time = "2025-11-04T13:40:27.099Z" },
+ { url = "https://files.pythonhosted.org/packages/15/df/a4c740c0943e93e6500f9eb23f4ca7ec9bf71b19e608ae5b579678c8d02f/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0cbaad15cb0c90aa221d43c00e77bb33c93e8d36e0bf74760cd00e732d10a6a0", size = 1919307, upload-time = "2025-11-04T13:40:29.806Z" },
+ { url = "https://files.pythonhosted.org/packages/9a/e3/6324802931ae1d123528988e0e86587c2072ac2e5394b4bc2bc34b61ff6e/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:03ca43e12fab6023fc79d28ca6b39b05f794ad08ec2feccc59a339b02f2b3d33", size = 2063258, upload-time = "2025-11-04T13:40:33.544Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/d4/2230d7151d4957dd79c3044ea26346c148c98fbf0ee6ebd41056f2d62ab5/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dc799088c08fa04e43144b164feb0c13f9a0bc40503f8df3e9fde58a3c0c101e", size = 2214917, upload-time = "2025-11-04T13:40:35.479Z" },
+ { url = "https://files.pythonhosted.org/packages/e6/9f/eaac5df17a3672fef0081b6c1bb0b82b33ee89aa5cec0d7b05f52fd4a1fa/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:97aeba56665b4c3235a0e52b2c2f5ae9cd071b8a8310ad27bddb3f7fb30e9aa2", size = 2332186, upload-time = "2025-11-04T13:40:37.436Z" },
+ { url = "https://files.pythonhosted.org/packages/cf/4e/35a80cae583a37cf15604b44240e45c05e04e86f9cfd766623149297e971/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:406bf18d345822d6c21366031003612b9c77b3e29ffdb0f612367352aab7d586", size = 2073164, upload-time = "2025-11-04T13:40:40.289Z" },
+ { url = "https://files.pythonhosted.org/packages/bf/e3/f6e262673c6140dd3305d144d032f7bd5f7497d3871c1428521f19f9efa2/pydantic_core-2.41.5-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b93590ae81f7010dbe380cdeab6f515902ebcbefe0b9327cc4804d74e93ae69d", size = 2179146, upload-time = "2025-11-04T13:40:42.809Z" },
+ { url = "https://files.pythonhosted.org/packages/75/c7/20bd7fc05f0c6ea2056a4565c6f36f8968c0924f19b7d97bbfea55780e73/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:01a3d0ab748ee531f4ea6c3e48ad9dac84ddba4b0d82291f87248f2f9de8d740", size = 2137788, upload-time = "2025-11-04T13:40:44.752Z" },
+ { url = "https://files.pythonhosted.org/packages/3a/8d/34318ef985c45196e004bc46c6eab2eda437e744c124ef0dbe1ff2c9d06b/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:6561e94ba9dacc9c61bce40e2d6bdc3bfaa0259d3ff36ace3b1e6901936d2e3e", size = 2340133, upload-time = "2025-11-04T13:40:46.66Z" },
+ { url = "https://files.pythonhosted.org/packages/9c/59/013626bf8c78a5a5d9350d12e7697d3d4de951a75565496abd40ccd46bee/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:915c3d10f81bec3a74fbd4faebe8391013ba61e5a1a8d48c4455b923bdda7858", size = 2324852, upload-time = "2025-11-04T13:40:48.575Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/d9/c248c103856f807ef70c18a4f986693a46a8ffe1602e5d361485da502d20/pydantic_core-2.41.5-cp313-cp313-win32.whl", hash = "sha256:650ae77860b45cfa6e2cdafc42618ceafab3a2d9a3811fcfbd3bbf8ac3c40d36", size = 1994679, upload-time = "2025-11-04T13:40:50.619Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/8b/341991b158ddab181cff136acd2552c9f35bd30380422a639c0671e99a91/pydantic_core-2.41.5-cp313-cp313-win_amd64.whl", hash = "sha256:79ec52ec461e99e13791ec6508c722742ad745571f234ea6255bed38c6480f11", size = 2019766, upload-time = "2025-11-04T13:40:52.631Z" },
+ { url = "https://files.pythonhosted.org/packages/73/7d/f2f9db34af103bea3e09735bb40b021788a5e834c81eedb541991badf8f5/pydantic_core-2.41.5-cp313-cp313-win_arm64.whl", hash = "sha256:3f84d5c1b4ab906093bdc1ff10484838aca54ef08de4afa9de0f5f14d69639cd", size = 1981005, upload-time = "2025-11-04T13:40:54.734Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/28/46b7c5c9635ae96ea0fbb779e271a38129df2550f763937659ee6c5dbc65/pydantic_core-2.41.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:3f37a19d7ebcdd20b96485056ba9e8b304e27d9904d233d7b1015db320e51f0a", size = 2119622, upload-time = "2025-11-04T13:40:56.68Z" },
+ { url = "https://files.pythonhosted.org/packages/74/1a/145646e5687e8d9a1e8d09acb278c8535ebe9e972e1f162ed338a622f193/pydantic_core-2.41.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1d1d9764366c73f996edd17abb6d9d7649a7eb690006ab6adbda117717099b14", size = 1891725, upload-time = "2025-11-04T13:40:58.807Z" },
+ { url = "https://files.pythonhosted.org/packages/23/04/e89c29e267b8060b40dca97bfc64a19b2a3cf99018167ea1677d96368273/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25e1c2af0fce638d5f1988b686f3b3ea8cd7de5f244ca147c777769e798a9cd1", size = 1915040, upload-time = "2025-11-04T13:41:00.853Z" },
+ { url = "https://files.pythonhosted.org/packages/84/a3/15a82ac7bd97992a82257f777b3583d3e84bdb06ba6858f745daa2ec8a85/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:506d766a8727beef16b7adaeb8ee6217c64fc813646b424d0804d67c16eddb66", size = 2063691, upload-time = "2025-11-04T13:41:03.504Z" },
+ { url = "https://files.pythonhosted.org/packages/74/9b/0046701313c6ef08c0c1cf0e028c67c770a4e1275ca73131563c5f2a310a/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4819fa52133c9aa3c387b3328f25c1facc356491e6135b459f1de698ff64d869", size = 2213897, upload-time = "2025-11-04T13:41:05.804Z" },
+ { url = "https://files.pythonhosted.org/packages/8a/cd/6bac76ecd1b27e75a95ca3a9a559c643b3afcd2dd62086d4b7a32a18b169/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2b761d210c9ea91feda40d25b4efe82a1707da2ef62901466a42492c028553a2", size = 2333302, upload-time = "2025-11-04T13:41:07.809Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/d2/ef2074dc020dd6e109611a8be4449b98cd25e1b9b8a303c2f0fca2f2bcf7/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:22f0fb8c1c583a3b6f24df2470833b40207e907b90c928cc8d3594b76f874375", size = 2064877, upload-time = "2025-11-04T13:41:09.827Z" },
+ { url = "https://files.pythonhosted.org/packages/18/66/e9db17a9a763d72f03de903883c057b2592c09509ccfe468187f2a2eef29/pydantic_core-2.41.5-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2782c870e99878c634505236d81e5443092fba820f0373997ff75f90f68cd553", size = 2180680, upload-time = "2025-11-04T13:41:12.379Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/9e/3ce66cebb929f3ced22be85d4c2399b8e85b622db77dad36b73c5387f8f8/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:0177272f88ab8312479336e1d777f6b124537d47f2123f89cb37e0accea97f90", size = 2138960, upload-time = "2025-11-04T13:41:14.627Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/62/205a998f4327d2079326b01abee48e502ea739d174f0a89295c481a2272e/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:63510af5e38f8955b8ee5687740d6ebf7c2a0886d15a6d65c32814613681bc07", size = 2339102, upload-time = "2025-11-04T13:41:16.868Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/0d/f05e79471e889d74d3d88f5bd20d0ed189ad94c2423d81ff8d0000aab4ff/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:e56ba91f47764cc14f1daacd723e3e82d1a89d783f0f5afe9c364b8bb491ccdb", size = 2326039, upload-time = "2025-11-04T13:41:18.934Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/e1/e08a6208bb100da7e0c4b288eed624a703f4d129bde2da475721a80cab32/pydantic_core-2.41.5-cp314-cp314-win32.whl", hash = "sha256:aec5cf2fd867b4ff45b9959f8b20ea3993fc93e63c7363fe6851424c8a7e7c23", size = 1995126, upload-time = "2025-11-04T13:41:21.418Z" },
+ { url = "https://files.pythonhosted.org/packages/48/5d/56ba7b24e9557f99c9237e29f5c09913c81eeb2f3217e40e922353668092/pydantic_core-2.41.5-cp314-cp314-win_amd64.whl", hash = "sha256:8e7c86f27c585ef37c35e56a96363ab8de4e549a95512445b85c96d3e2f7c1bf", size = 2015489, upload-time = "2025-11-04T13:41:24.076Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/bb/f7a190991ec9e3e0ba22e4993d8755bbc4a32925c0b5b42775c03e8148f9/pydantic_core-2.41.5-cp314-cp314-win_arm64.whl", hash = "sha256:e672ba74fbc2dc8eea59fb6d4aed6845e6905fc2a8afe93175d94a83ba2a01a0", size = 1977288, upload-time = "2025-11-04T13:41:26.33Z" },
+ { url = "https://files.pythonhosted.org/packages/92/ed/77542d0c51538e32e15afe7899d79efce4b81eee631d99850edc2f5e9349/pydantic_core-2.41.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8566def80554c3faa0e65ac30ab0932b9e3a5cd7f8323764303d468e5c37595a", size = 2120255, upload-time = "2025-11-04T13:41:28.569Z" },
+ { url = "https://files.pythonhosted.org/packages/bb/3d/6913dde84d5be21e284439676168b28d8bbba5600d838b9dca99de0fad71/pydantic_core-2.41.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b80aa5095cd3109962a298ce14110ae16b8c1aece8b72f9dafe81cf597ad80b3", size = 1863760, upload-time = "2025-11-04T13:41:31.055Z" },
+ { url = "https://files.pythonhosted.org/packages/5a/f0/e5e6b99d4191da102f2b0eb9687aaa7f5bea5d9964071a84effc3e40f997/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3006c3dd9ba34b0c094c544c6006cc79e87d8612999f1a5d43b769b89181f23c", size = 1878092, upload-time = "2025-11-04T13:41:33.21Z" },
+ { url = "https://files.pythonhosted.org/packages/71/48/36fb760642d568925953bcc8116455513d6e34c4beaa37544118c36aba6d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:72f6c8b11857a856bcfa48c86f5368439f74453563f951e473514579d44aa612", size = 2053385, upload-time = "2025-11-04T13:41:35.508Z" },
+ { url = "https://files.pythonhosted.org/packages/20/25/92dc684dd8eb75a234bc1c764b4210cf2646479d54b47bf46061657292a8/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5cb1b2f9742240e4bb26b652a5aeb840aa4b417c7748b6f8387927bc6e45e40d", size = 2218832, upload-time = "2025-11-04T13:41:37.732Z" },
+ { url = "https://files.pythonhosted.org/packages/e2/09/f53e0b05023d3e30357d82eb35835d0f6340ca344720a4599cd663dca599/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bd3d54f38609ff308209bd43acea66061494157703364ae40c951f83ba99a1a9", size = 2327585, upload-time = "2025-11-04T13:41:40Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/4e/2ae1aa85d6af35a39b236b1b1641de73f5a6ac4d5a7509f77b814885760c/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2ff4321e56e879ee8d2a879501c8e469414d948f4aba74a2d4593184eb326660", size = 2041078, upload-time = "2025-11-04T13:41:42.323Z" },
+ { url = "https://files.pythonhosted.org/packages/cd/13/2e215f17f0ef326fc72afe94776edb77525142c693767fc347ed6288728d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d0d2568a8c11bf8225044aa94409e21da0cb09dcdafe9ecd10250b2baad531a9", size = 2173914, upload-time = "2025-11-04T13:41:45.221Z" },
+ { url = "https://files.pythonhosted.org/packages/02/7a/f999a6dcbcd0e5660bc348a3991c8915ce6599f4f2c6ac22f01d7a10816c/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:a39455728aabd58ceabb03c90e12f71fd30fa69615760a075b9fec596456ccc3", size = 2129560, upload-time = "2025-11-04T13:41:47.474Z" },
+ { url = "https://files.pythonhosted.org/packages/3a/b1/6c990ac65e3b4c079a4fb9f5b05f5b013afa0f4ed6780a3dd236d2cbdc64/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:239edca560d05757817c13dc17c50766136d21f7cd0fac50295499ae24f90fdf", size = 2329244, upload-time = "2025-11-04T13:41:49.992Z" },
+ { url = "https://files.pythonhosted.org/packages/d9/02/3c562f3a51afd4d88fff8dffb1771b30cfdfd79befd9883ee094f5b6c0d8/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:2a5e06546e19f24c6a96a129142a75cee553cc018ffee48a460059b1185f4470", size = 2331955, upload-time = "2025-11-04T13:41:54.079Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/96/5fb7d8c3c17bc8c62fdb031c47d77a1af698f1d7a406b0f79aaa1338f9ad/pydantic_core-2.41.5-cp314-cp314t-win32.whl", hash = "sha256:b4ececa40ac28afa90871c2cc2b9ffd2ff0bf749380fbdf57d165fd23da353aa", size = 1988906, upload-time = "2025-11-04T13:41:56.606Z" },
+ { url = "https://files.pythonhosted.org/packages/22/ed/182129d83032702912c2e2d8bbe33c036f342cc735737064668585dac28f/pydantic_core-2.41.5-cp314-cp314t-win_amd64.whl", hash = "sha256:80aa89cad80b32a912a65332f64a4450ed00966111b6615ca6816153d3585a8c", size = 1981607, upload-time = "2025-11-04T13:41:58.889Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/ed/068e41660b832bb0b1aa5b58011dea2a3fe0ba7861ff38c4d4904c1c1a99/pydantic_core-2.41.5-cp314-cp314t-win_arm64.whl", hash = "sha256:35b44f37a3199f771c3eaa53051bc8a70cd7b54f333531c59e29fd4db5d15008", size = 1974769, upload-time = "2025-11-04T13:42:01.186Z" },
+ { url = "https://files.pythonhosted.org/packages/11/72/90fda5ee3b97e51c494938a4a44c3a35a9c96c19bba12372fb9c634d6f57/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-macosx_10_12_x86_64.whl", hash = "sha256:b96d5f26b05d03cc60f11a7761a5ded1741da411e7fe0909e27a5e6a0cb7b034", size = 2115441, upload-time = "2025-11-04T13:42:39.557Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/53/8942f884fa33f50794f119012dc6a1a02ac43a56407adaac20463df8e98f/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-macosx_11_0_arm64.whl", hash = "sha256:634e8609e89ceecea15e2d61bc9ac3718caaaa71963717bf3c8f38bfde64242c", size = 1930291, upload-time = "2025-11-04T13:42:42.169Z" },
+ { url = "https://files.pythonhosted.org/packages/79/c8/ecb9ed9cd942bce09fc888ee960b52654fbdbede4ba6c2d6e0d3b1d8b49c/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:93e8740d7503eb008aa2df04d3b9735f845d43ae845e6dcd2be0b55a2da43cd2", size = 1948632, upload-time = "2025-11-04T13:42:44.564Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/1b/687711069de7efa6af934e74f601e2a4307365e8fdc404703afc453eab26/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f15489ba13d61f670dcc96772e733aad1a6f9c429cc27574c6cdaed82d0146ad", size = 2138905, upload-time = "2025-11-04T13:42:47.156Z" },
+ { url = "https://files.pythonhosted.org/packages/09/32/59b0c7e63e277fa7911c2fc70ccfb45ce4b98991e7ef37110663437005af/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:7da7087d756b19037bc2c06edc6c170eeef3c3bafcb8f532ff17d64dc427adfd", size = 2110495, upload-time = "2025-11-04T13:42:49.689Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/81/05e400037eaf55ad400bcd318c05bb345b57e708887f07ddb2d20e3f0e98/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:aabf5777b5c8ca26f7824cb4a120a740c9588ed58df9b2d196ce92fba42ff8dc", size = 1915388, upload-time = "2025-11-04T13:42:52.215Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/0d/e3549b2399f71d56476b77dbf3cf8937cec5cd70536bdc0e374a421d0599/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c007fe8a43d43b3969e8469004e9845944f1a80e6acd47c150856bb87f230c56", size = 1942879, upload-time = "2025-11-04T13:42:56.483Z" },
+ { url = "https://files.pythonhosted.org/packages/f7/07/34573da085946b6a313d7c42f82f16e8920bfd730665de2d11c0c37a74b5/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76d0819de158cd855d1cbb8fcafdf6f5cf1eb8e470abe056d5d161106e38062b", size = 2139017, upload-time = "2025-11-04T13:42:59.471Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/9b/1b3f0e9f9305839d7e84912f9e8bfbd191ed1b1ef48083609f0dabde978c/pydantic_core-2.41.5-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:b2379fa7ed44ddecb5bfe4e48577d752db9fc10be00a6b7446e9663ba143de26", size = 2101980, upload-time = "2025-11-04T13:43:25.97Z" },
+ { url = "https://files.pythonhosted.org/packages/a4/ed/d71fefcb4263df0da6a85b5d8a7508360f2f2e9b3bf5814be9c8bccdccc1/pydantic_core-2.41.5-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:266fb4cbf5e3cbd0b53669a6d1b039c45e3ce651fd5442eff4d07c2cc8d66808", size = 1923865, upload-time = "2025-11-04T13:43:28.763Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/3a/626b38db460d675f873e4444b4bb030453bbe7b4ba55df821d026a0493c4/pydantic_core-2.41.5-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58133647260ea01e4d0500089a8c4f07bd7aa6ce109682b1426394988d8aaacc", size = 2134256, upload-time = "2025-11-04T13:43:31.71Z" },
+ { url = "https://files.pythonhosted.org/packages/83/d9/8412d7f06f616bbc053d30cb4e5f76786af3221462ad5eee1f202021eb4e/pydantic_core-2.41.5-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:287dad91cfb551c363dc62899a80e9e14da1f0e2b6ebde82c806612ca2a13ef1", size = 2174762, upload-time = "2025-11-04T13:43:34.744Z" },
+ { url = "https://files.pythonhosted.org/packages/55/4c/162d906b8e3ba3a99354e20faa1b49a85206c47de97a639510a0e673f5da/pydantic_core-2.41.5-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:03b77d184b9eb40240ae9fd676ca364ce1085f203e1b1256f8ab9984dca80a84", size = 2143141, upload-time = "2025-11-04T13:43:37.701Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/f2/f11dd73284122713f5f89fc940f370d035fa8e1e078d446b3313955157fe/pydantic_core-2.41.5-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:a668ce24de96165bb239160b3d854943128f4334822900534f2fe947930e5770", size = 2330317, upload-time = "2025-11-04T13:43:40.406Z" },
+ { url = "https://files.pythonhosted.org/packages/88/9d/b06ca6acfe4abb296110fb1273a4d848a0bfb2ff65f3ee92127b3244e16b/pydantic_core-2.41.5-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:f14f8f046c14563f8eb3f45f499cc658ab8d10072961e07225e507adb700e93f", size = 2316992, upload-time = "2025-11-04T13:43:43.602Z" },
+ { url = "https://files.pythonhosted.org/packages/36/c7/cfc8e811f061c841d7990b0201912c3556bfeb99cdcb7ed24adc8d6f8704/pydantic_core-2.41.5-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:56121965f7a4dc965bff783d70b907ddf3d57f6eba29b6d2e5dabfaf07799c51", size = 2145302, upload-time = "2025-11-04T13:43:46.64Z" },
+]
+
+[[package]]
+name = "pygit2"
+version = "1.19.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3a/a4/10ce00feef5c43eddacab19ae6610c4d4ef3ab77e544e9ee938772cd1c17/pygit2-1.19.2.tar.gz", hash = "sha256:cbeb3dbca9ca6ee3d5ea5d02f5e844c2d6084a2d5d6621e3e06aa2b11c645bfd", size = 803448, upload-time = "2026-03-29T14:57:27.565Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/9c/388648963f4be4bde89e32ca1a6f60adabb5f782c0e78598790b56e41967/pygit2-1.19.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:70c7efc426bdae6b67465a03729b79277e7757a29a7d6550b40c18ed36cb7232", size = 5706937, upload-time = "2026-03-29T14:56:02.061Z" },
+ { url = "https://files.pythonhosted.org/packages/02/4c/e89013ff45350affac11f5893b3b7b555be35d5f279ff89c1d9310872378/pygit2-1.19.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7b96d6ed7251eef70cfd4126269f1044fa47bc6da6367300027c5e5d74789f7f", size = 5695668, upload-time = "2026-03-29T14:56:03.92Z" },
+ { url = "https://files.pythonhosted.org/packages/6f/84/db7281407c4481b64559f400f87f60190cc59615637bbc6f0afb8681dd7d/pygit2-1.19.2-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f3235db6b553b8fb4d3c1dc86af9be1eab445f1d6c42f4ade5cf5f60efd333", size = 6034309, upload-time = "2026-03-29T14:56:05.282Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/06/d8623933341e79220ab0c14c1e2bc5a78645738ce62699f942065e8699c4/pygit2-1.19.2-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:02a35d56126f82a303668f4198c138627b3e9820f9f1eec38fff0409be274b9e", size = 4637953, upload-time = "2026-03-29T14:56:06.589Z" },
+ { url = "https://files.pythonhosted.org/packages/42/27/6b20c5d424297623b22737f54a5c67ea00d498b5d2ebb98d3175d01de10c/pygit2-1.19.2-cp311-cp311-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e59a2e9eddd59edf999403c266c891dfc171eb95939d229ed614bc21e0c95804", size = 5794511, upload-time = "2026-03-29T14:56:07.953Z" },
+ { url = "https://files.pythonhosted.org/packages/ec/cb/75a09f2319dc8798d80085b059506462af95b576d782c447f502dc807553/pygit2-1.19.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d0d2437bd5f8dbd652e8a6c318cbcaa245c0528ee48f6d64f4aaef8fd9b36b93", size = 6039969, upload-time = "2026-03-29T14:56:09.441Z" },
+ { url = "https://files.pythonhosted.org/packages/34/20/fd2ac2f397fed5fab1f2838f2460226734f5a616371a388d8b0d7c995b7f/pygit2-1.19.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:60d011496e57436b0c8e3fbd4d12745777427b3f33a60710ec3d94d2f76304b7", size = 5764242, upload-time = "2026-03-29T14:56:10.947Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/c0/bee8c2fce9d577cdc167e82d8999a57f997c213b5226fbaa9b977e3ce95f/pygit2-1.19.2-cp311-cp311-win32.whl", hash = "sha256:9b0d5a44ca6d77a8c0e2526f6556d9b37cc85d44983ff3549bf5adbf95d289c4", size = 945852, upload-time = "2026-03-29T14:56:12.209Z" },
+ { url = "https://files.pythonhosted.org/packages/e0/e9/9ecafac82a8729ebfc948636147235770354ee48956ad43ed628b8396a68/pygit2-1.19.2-cp311-cp311-win_amd64.whl", hash = "sha256:0d9c795155086c95ef890c87b50e02792146cfaede2c715698e6988a122373e7", size = 1163883, upload-time = "2026-03-29T14:56:13.28Z" },
+ { url = "https://files.pythonhosted.org/packages/02/09/24f3f55ebda489755d757dd254a612caa19e6a2bd2cbc5ccf7127e4caa30/pygit2-1.19.2-cp311-cp311-win_arm64.whl", hash = "sha256:837f0a9a0093cbb213176284d29f0ab754ded3e5af967e7ec6419d590a7da92a", size = 969221, upload-time = "2026-03-29T14:56:14.441Z" },
+ { url = "https://files.pythonhosted.org/packages/d5/2d/4fdeb7c6e044588cef9f0fca8b93fbc40fcdb2dfc64367999f45e88c0e7e/pygit2-1.19.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cf479077d48a60b09569a5bb50866d8609f434f8982058594b0d2e2950bd6fce", size = 5704810, upload-time = "2026-03-29T14:56:15.671Z" },
+ { url = "https://files.pythonhosted.org/packages/c7/d8/926415c996ca283c4f7ccf63322ea23135ff17ecd1d2faaba704f6b4d883/pygit2-1.19.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6e6e7eb5fb49203735627b8e1d410afe19e7d610c9a9733c11084fabd17f0920", size = 5696366, upload-time = "2026-03-29T14:56:17.241Z" },
+ { url = "https://files.pythonhosted.org/packages/8c/5e/c0329db9c980552c5c853dc1e429d13d55c691749db0540ef6bc77c04a98/pygit2-1.19.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1a810da2d108d6bd16115c72a1c3d69fa1528ef927719bdfc94d2cdbc4198288", size = 6035334, upload-time = "2026-03-29T14:56:19.555Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/39/e08003a59a4d58bbba923d1c2be683a84b7b30c7270a19ff3ea02f9558df/pygit2-1.19.2-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d0b8ae5a822afb2771cbacf7c75140e663bc801c44eaaf2e4017f850cb27227c", size = 4636920, upload-time = "2026-03-29T14:56:20.93Z" },
+ { url = "https://files.pythonhosted.org/packages/c9/3c/d3a9ed478add4cd77403416897459750ef2f6a06d8febe452ba03f5b7a27/pygit2-1.19.2-cp312-cp312-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:330430b6c1a3e6d45d1f5f950734d37d849c07924b5b0475cd995a7e541e6ab1", size = 5798652, upload-time = "2026-03-29T14:56:22.773Z" },
+ { url = "https://files.pythonhosted.org/packages/d4/15/5440f00005db1769062ecc9fab7059ac7ae89217a06e1976734f53c2d040/pygit2-1.19.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7b7f165d1ddfa1e0f205c1115ee10f5fea700fd3584c727b0d61a57192238449", size = 6041142, upload-time = "2026-03-29T14:56:24.618Z" },
+ { url = "https://files.pythonhosted.org/packages/9d/5b/b9f9979a56606a661c0cff24c7aa6f5b1ad34118e116b7d67295be42aaad/pygit2-1.19.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e46ec6a97a5c43704473e42a926f7f20f9934ceef4f4891660313f573c4f0ab8", size = 5769220, upload-time = "2026-03-29T14:56:26.423Z" },
+ { url = "https://files.pythonhosted.org/packages/30/81/9594e604eb19ae02f6a2023840e25574b0abcfc8d58c03cf96c59dd4ba72/pygit2-1.19.2-cp312-cp312-win32.whl", hash = "sha256:6b4de5469e88e7b069143f7a5d6336a4b3e7d911de4633ef18c113e416feb948", size = 946691, upload-time = "2026-03-29T14:56:27.813Z" },
+ { url = "https://files.pythonhosted.org/packages/35/2d/c9bcdaef8f57ba0cdf129a6823f95cadd8ead002f38fba3465732c7517a8/pygit2-1.19.2-cp312-cp312-win_amd64.whl", hash = "sha256:f064748202928f4e882501521229e378e0b7b69b0e7c433cdb2626d007745973", size = 1164290, upload-time = "2026-03-29T14:56:29.13Z" },
+ { url = "https://files.pythonhosted.org/packages/b8/d4/6e9c98d227a8e816e2ffc7304f733e8b924afd8198b16888972fedbe05bd/pygit2-1.19.2-cp312-cp312-win_arm64.whl", hash = "sha256:222f439d751799dc74c3fa75f187abdbc415d12f9a091efa66f0c9ff51893d32", size = 969330, upload-time = "2026-03-29T14:56:30.363Z" },
+ { url = "https://files.pythonhosted.org/packages/c1/77/c925eee8496961729f029a4edda67485c7637248c0e730e0b41122357be5/pygit2-1.19.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:df207f93a33851a110dec70108e3f2a1c69578932919fd356303eda83a5624db", size = 5704802, upload-time = "2026-03-29T14:56:31.635Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/fc/d46428b7ea0ce7bd3cac73b73206a2cba50580f54b58bd704d8755d5658c/pygit2-1.19.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:ae884cd53e29b3d831f5261f36048a8d5db5642dc98cd63530810e7fd9c9e60d", size = 5696329, upload-time = "2026-03-29T14:56:33.343Z" },
+ { url = "https://files.pythonhosted.org/packages/35/05/a3bb39095ef31e140cbeb30abbd08fafb13ed70b656a9de095fac74a1ff5/pygit2-1.19.2-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0bd4059964531d20aaf4577b3761590df9cc7c9e2395df5d33f0552224331b76", size = 6036095, upload-time = "2026-03-29T14:56:34.836Z" },
+ { url = "https://files.pythonhosted.org/packages/4c/cb/36ebd241351bd1ced1f126bf0b21fbb6c0d48ce36122512cc51cde83d10b/pygit2-1.19.2-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c3befcccc7b3b62e45da2cc1ce4095964f7606d3d15b43dc667c6ef2a2ada20d", size = 4637435, upload-time = "2026-03-29T14:56:36.292Z" },
+ { url = "https://files.pythonhosted.org/packages/36/35/779d6b8e9df0cc3236f675af5fc37e4047e1a6ab96f9c72ef5b5ed8d888b/pygit2-1.19.2-cp313-cp313-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1cf08b54553f997f6f60a7918504e22e7baa4ba2fbb11d1e1cb6c0a45ac7e04b", size = 5799881, upload-time = "2026-03-29T14:56:38.04Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/fa/cb361f4bd5342fa01a0f83b04eff8873a09771183bcb6e29947078577119/pygit2-1.19.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d7f630e5a763f01b4be6e2374c487086229c8f7392a2e5591d29095c5e481da4", size = 6042342, upload-time = "2026-03-29T14:56:39.523Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/6f/b9ea61266eb7d568ea17d8fec63dc766ebecec23860b4e5ac5bcfbbe15d7/pygit2-1.19.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6166845f41d4f6be3353997022d64035fe3df348c8e34d7d30c5f95817fbcab4", size = 5770452, upload-time = "2026-03-29T14:56:41.306Z" },
+ { url = "https://files.pythonhosted.org/packages/fb/bb/403532429072a61d5498d17ddf6be3258953e73b6499f70a2b4e1345bb84/pygit2-1.19.2-cp313-cp313-win32.whl", hash = "sha256:5bebea045102e87dea142242298d4dd668d0227f76042f98efb1c5d5dd3db21e", size = 946658, upload-time = "2026-03-29T14:56:42.613Z" },
+ { url = "https://files.pythonhosted.org/packages/01/08/6f37fb23514da02345889d7be7cea899d2a348fa4871492ea9a8837e70e4/pygit2-1.19.2-cp313-cp313-win_amd64.whl", hash = "sha256:7bbfeb680821001a5c1b6959da1eae906806c90c9992ae4564d3ea83a27bb19f", size = 1164264, upload-time = "2026-03-29T14:56:43.753Z" },
+ { url = "https://files.pythonhosted.org/packages/90/b9/d11220d5f0cfc92895b02814ab36ac94edbf46ae1b9dc3077c457d03d718/pygit2-1.19.2-cp313-cp313-win_arm64.whl", hash = "sha256:033d489186145cf67b2c60840d2a308f6b1e9d641de12417c447f9829dacde70", size = 969348, upload-time = "2026-03-29T14:56:44.892Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/1b/1a935baeb29958d7e50a52c7a963ce5963f24fa8a5024e1082d43b07a770/pygit2-1.19.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:f5effee3f4ad0d9c89b34ebecf1acee26f6b117ef3c51345ad022bd521fd8dca", size = 5706909, upload-time = "2026-03-29T14:56:46.249Z" },
+ { url = "https://files.pythonhosted.org/packages/a7/86/4bb6f196b13bd7ed825f4e931fb7152a36d01e8de24c8de44425702ad18c/pygit2-1.19.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1ed09804dc6b6de0be07a71443122fd7b6458f8466d1134003c2dea55af886fc", size = 5696293, upload-time = "2026-03-29T14:56:48.173Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/64/d674b3f854cecf53bccbc21a095734759cd3599624578ed3c78602eb22a3/pygit2-1.19.2-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2d114aa066e718d5ef3401b366dcb0b37b549c3b3b139f5f0042bd7059a4b0f7", size = 6038057, upload-time = "2026-03-29T14:56:50.118Z" },
+ { url = "https://files.pythonhosted.org/packages/64/eb/2ce41735e27ee0f28f786aae62ea371f3beec0ef38d1712a2910421386c4/pygit2-1.19.2-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c1becc06071acfdd5ae8523aaeab6d4b0930b2bcb08f5eb878e052e61275000b", size = 4641475, upload-time = "2026-03-29T14:56:51.581Z" },
+ { url = "https://files.pythonhosted.org/packages/e5/8d/35f6096c42caefb715ca29e991279b493275c0051a3c83081099644d3f4a/pygit2-1.19.2-cp314-cp314-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:06d2db3bdbf2906eb17112adb14a2fe6e34c1b2bce39c91819f59208d4e56665", size = 5801738, upload-time = "2026-03-29T14:56:53.043Z" },
+ { url = "https://files.pythonhosted.org/packages/fc/31/dbbaa7a433008fec9046cc293c012ae5d5a31e66321e1fb05d64ae131e54/pygit2-1.19.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8a7e99e5dfc8d3ed8f849b9688bc3fb1bdc86f34af28159140a8d1e18b703dd8", size = 6043074, upload-time = "2026-03-29T14:56:54.774Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/33/b34266efba6917081dafb50976155c2d31cd377f277e67348a810245c4b4/pygit2-1.19.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:7659d59eba6c4a706978237d02e8d719f960843df749256f1656c938c1f4142b", size = 5770986, upload-time = "2026-03-29T14:56:56.796Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/ab/813f3af50987020cd90e810da147ebef16a61003b9af995070ec338634ba/pygit2-1.19.2-cp314-cp314-win32.whl", hash = "sha256:e551908dfd93d471c0b08cfcddbe4924417865aae6ac90d20f3815c9483b0a82", size = 967943, upload-time = "2026-03-29T14:56:58.196Z" },
+ { url = "https://files.pythonhosted.org/packages/22/00/24df5ac51a316e36a07bbf9e4c91fade523b9e80a84d5c9e7acd10b22248/pygit2-1.19.2-cp314-cp314-win_amd64.whl", hash = "sha256:eb1fd8538372230f8a471a5f3629901bc2fc7df992853d97bedc8fa269a9caf3", size = 1194774, upload-time = "2026-03-29T14:56:59.721Z" },
+ { url = "https://files.pythonhosted.org/packages/a7/ee/274a91b28864fd9c5cdd2949b4d7e0909fd6a89785a46308de098d3a22cd/pygit2-1.19.2-cp314-cp314-win_arm64.whl", hash = "sha256:3cc461245b70be45a936e925744e67a45f6b0ee970aeb8e7a385dd7fe9f40877", size = 996677, upload-time = "2026-03-29T14:57:01.013Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/22/3c05a56918e6fda5deb53aeb7436959a8880f4cc436a76771771479693de/pygit2-1.19.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:cb686bc81dfe5b13937047643fddb1dd253dae33b4a9ca62858c49ed294e05be", size = 5710172, upload-time = "2026-03-29T14:57:02.672Z" },
+ { url = "https://files.pythonhosted.org/packages/59/eb/2fdd485c01b478c77dd2e949b424a61c70a8750ffb13c5035fe3edf6a8f6/pygit2-1.19.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5ec3538d81963bd05dd16c0de75938a9173966e1c853ad7848ebcb60bcfe21b0", size = 5699256, upload-time = "2026-03-29T14:57:04.401Z" },
+ { url = "https://files.pythonhosted.org/packages/51/f4/f0608bb369da15f2973dfb33e7b7cba4c9bc8164e6a01e3f15e65e85efef/pygit2-1.19.2-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d02ebb50ea082d9631bbfda12787eb5324b8880a72cb8e3b9f11e9b323ad5781", size = 6096321, upload-time = "2026-03-29T14:57:06.33Z" },
+ { url = "https://files.pythonhosted.org/packages/6e/1b/816d3700dc8bcc9028c5f81b190f2d770d1cb9cd2ccdd39939d0b6730718/pygit2-1.19.2-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8a3643e4dd569c2909e88586659f617f70315680ca3c619cd8ff9e9c28726c25", size = 4696179, upload-time = "2026-03-29T14:57:08.552Z" },
+ { url = "https://files.pythonhosted.org/packages/ee/a6/0fc82f07c4dfee5856626c5d4b422c32e14cac0204eb1e9558ac0d717b07/pygit2-1.19.2-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:697e3684cb4ef2bfc084623c3f680d5ae8b4c8afca31a35a731b7b70204d9f83", size = 5853368, upload-time = "2026-03-29T14:57:10.449Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/60/0393786d7810b7f83def3738cb9be1a735cf6b555dc219d90f46010b87b1/pygit2-1.19.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:173165b54a2affed918302193f12dd369bec981b1d77904cdcd76b966a824e15", size = 6099319, upload-time = "2026-03-29T14:57:12.166Z" },
+ { url = "https://files.pythonhosted.org/packages/13/ad/22e30e630a147e10a912e085c4cb816a0dc39bee8d39493b40101f3da4c7/pygit2-1.19.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ff32adce1a48d76b10e790b36784f6cb5ef40699b758c8b84f7f53f13b13d237", size = 5822074, upload-time = "2026-03-29T14:57:13.84Z" },
+ { url = "https://files.pythonhosted.org/packages/4b/08/71ea683386887a1aab8f9b8c282b6df7ce7fae45fc7c9959719c78baebba/pygit2-1.19.2-cp314-cp314t-win32.whl", hash = "sha256:637d7c023f6623da35cf02cd1091f260c709730dd615367f4524ec8d771d0898", size = 972866, upload-time = "2026-03-29T14:57:15.26Z" },
+ { url = "https://files.pythonhosted.org/packages/da/67/efbde3954bdcbadfb61d183badd9a3e730c4ad94ed10966abe0b177abe0c/pygit2-1.19.2-cp314-cp314t-win_amd64.whl", hash = "sha256:2805a8abd546e38298ce5daf33e444960e483acce68cbfb5d338e72ad5bc3503", size = 1201537, upload-time = "2026-03-29T14:57:16.72Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/0c/28ae2c74038d1c51092f525658986a261f1963ec96528e7b41e721387343/pygit2-1.19.2-cp314-cp314t-win_arm64.whl", hash = "sha256:376a0d2c27c082f6bd8b97fd8ffc1939f16dfe8374ec846deee9b11151b37b8a", size = 997795, upload-time = "2026-03-29T14:57:17.878Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/47/8ca340fc8f0f5ec8ab9f8e96bb814a64a95f3836034fac00bb733c1f357c/pygit2-1.19.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:4c2d397c887ff5a26b48ebd1bb9c66d2195ad377f0a44e05b79c462fff4040cd", size = 5649264, upload-time = "2026-03-29T14:57:19.193Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/c4/8d26b20cb09ae862302b7b023e9089c70946cbdaf4f3cb8c1d4c7ba94a09/pygit2-1.19.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:69a0d377ee46110bbeea9e4191edee05132d1e7ac84b7cdebc640bc45868a2ec", size = 5646929, upload-time = "2026-03-29T14:57:20.717Z" },
+ { url = "https://files.pythonhosted.org/packages/d3/35/b71ac88cda21ad440577543a317052eca9ab4f0119e9c2d74baa135731c4/pygit2-1.19.2-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:57d113a3eb61621ce16ceaa4bae7a93ffe525fd69da905445a0cf798d3601815", size = 5562858, upload-time = "2026-03-29T14:57:22.962Z" },
+ { url = "https://files.pythonhosted.org/packages/08/d9/c419105e997031a34a1a7d87e832a3a0e5a4c1501bc2784250d000b1c044/pygit2-1.19.2-pp311-pypy311_pp73-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9e0bc207abbef4d3be3bd37e0711e6974a148d41806fdc932aef9bb244b157c4", size = 5315754, upload-time = "2026-03-29T14:57:24.956Z" },
+ { url = "https://files.pythonhosted.org/packages/e8/20/b52bc0ef2c5358d08e20e2d9fa8ae911283f3d20a7b9e52ec4a338b94983/pygit2-1.19.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:219c03bdbca59bd1df12b8bc7974b429872f4267aa2287ec0237c268593c0c5e", size = 1132796, upload-time = "2026-03-29T14:57:26.411Z" },
+]
+
+[[package]]
+name = "pygments"
+version = "2.20.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
+]
+
+[[package]]
+name = "pyjwt"
+version = "2.12.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c2/27/a3b6e5bf6ff856d2509292e95c8f57f0df7017cf5394921fc4e4ef40308a/pyjwt-2.12.1.tar.gz", hash = "sha256:c74a7a2adf861c04d002db713dd85f84beb242228e671280bf709d765b03672b", size = 102564, upload-time = "2026-03-13T19:27:37.25Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e5/7a/8dd906bd22e79e47397a61742927f6747fe93242ef86645ee9092e610244/pyjwt-2.12.1-py3-none-any.whl", hash = "sha256:28ca37c070cad8ba8cd9790cd940535d40274d22f80ab87f3ac6a713e6e8454c", size = 29726, upload-time = "2026-03-13T19:27:35.677Z" },
+]
+
+[package.optional-dependencies]
+crypto = [
+ { name = "cryptography" },
+]
+
+[[package]]
+name = "pytest"
+version = "9.0.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "iniconfig" },
+ { name = "packaging" },
+ { name = "pluggy" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d1/db/7ef3487e0fb0049ddb5ce41d3a49c235bf9ad299b6a25d5780a89f19230f/pytest-9.0.2.tar.gz", hash = "sha256:75186651a92bd89611d1d9fc20f0b4345fd827c41ccd5c299a868a05d70edf11", size = 1568901, upload-time = "2025-12-06T21:30:51.014Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3b/ab/b3226f0bd7cdcf710fbede2b3548584366da3b19b5021e74f5bde2a8fa3f/pytest-9.0.2-py3-none-any.whl", hash = "sha256:711ffd45bf766d5264d487b917733b453d917afd2b0ad65223959f59089f875b", size = 374801, upload-time = "2025-12-06T21:30:49.154Z" },
+]
+
+[[package]]
+name = "pytest-asyncio"
+version = "1.3.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pytest" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/90/2c/8af215c0f776415f3590cac4f9086ccefd6fd463befeae41cd4d3f193e5a/pytest_asyncio-1.3.0.tar.gz", hash = "sha256:d7f52f36d231b80ee124cd216ffb19369aa168fc10095013c6b014a34d3ee9e5", size = 50087, upload-time = "2025-11-10T16:07:47.256Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e5/35/f8b19922b6a25bc0880171a2f1a003eaeb93657475193ab516fd87cac9da/pytest_asyncio-1.3.0-py3-none-any.whl", hash = "sha256:611e26147c7f77640e6d0a92a38ed17c3e9848063698d5c93d5aa7aa11cebff5", size = 15075, upload-time = "2025-11-10T16:07:45.537Z" },
+]
+
+[[package]]
+name = "pytest-timeout"
+version = "2.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pytest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ac/82/4c9ecabab13363e72d880f2fb504c5f750433b2b6f16e99f4ec21ada284c/pytest_timeout-2.4.0.tar.gz", hash = "sha256:7e68e90b01f9eff71332b25001f85c75495fc4e3a836701876183c4bcfd0540a", size = 17973, upload-time = "2025-05-05T19:44:34.99Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fa/b6/3127540ecdf1464a00e5a01ee60a1b09175f6913f0644ac748494d9c4b21/pytest_timeout-2.4.0-py3-none-any.whl", hash = "sha256:c42667e5cdadb151aeb5b26d114aff6bdf5a907f176a007a30b940d3d865b5c2", size = 14382, upload-time = "2025-05-05T19:44:33.502Z" },
+]
+
+[[package]]
+name = "pywin32-ctypes"
+version = "0.2.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" },
+]
+
+[[package]]
+name = "pyyaml"
+version = "6.0.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" },
+ { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" },
+ { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114, upload-time = "2025-09-25T21:32:03.376Z" },
+ { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638, upload-time = "2025-09-25T21:32:04.553Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463, upload-time = "2025-09-25T21:32:06.152Z" },
+ { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986, upload-time = "2025-09-25T21:32:07.367Z" },
+ { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543, upload-time = "2025-09-25T21:32:08.95Z" },
+ { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763, upload-time = "2025-09-25T21:32:09.96Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063, upload-time = "2025-09-25T21:32:11.445Z" },
+ { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973, upload-time = "2025-09-25T21:32:12.492Z" },
+ { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116, upload-time = "2025-09-25T21:32:13.652Z" },
+ { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011, upload-time = "2025-09-25T21:32:15.21Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870, upload-time = "2025-09-25T21:32:16.431Z" },
+ { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089, upload-time = "2025-09-25T21:32:17.56Z" },
+ { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181, upload-time = "2025-09-25T21:32:18.834Z" },
+ { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658, upload-time = "2025-09-25T21:32:20.209Z" },
+ { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003, upload-time = "2025-09-25T21:32:21.167Z" },
+ { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344, upload-time = "2025-09-25T21:32:22.617Z" },
+ { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" },
+ { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" },
+ { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" },
+ { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" },
+ { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" },
+ { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" },
+ { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" },
+ { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" },
+ { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" },
+ { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" },
+ { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" },
+ { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" },
+ { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" },
+ { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" },
+ { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" },
+ { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" },
+ { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" },
+ { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" },
+ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },
+]
+
+[[package]]
+name = "readme-renderer"
+version = "44.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "docutils" },
+ { name = "nh3" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/5a/a9/104ec9234c8448c4379768221ea6df01260cd6c2ce13182d4eac531c8342/readme_renderer-44.0.tar.gz", hash = "sha256:8712034eabbfa6805cacf1402b4eeb2a73028f72d1166d6f5cb7f9c047c5d1e1", size = 32056, upload-time = "2024-07-08T15:00:57.805Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e1/67/921ec3024056483db83953ae8e48079ad62b92db7880013ca77632921dd0/readme_renderer-44.0-py3-none-any.whl", hash = "sha256:2fbca89b81a08526aadf1357a8c2ae889ec05fb03f5da67f9769c9a592166151", size = 13310, upload-time = "2024-07-08T15:00:56.577Z" },
+]
+
+[[package]]
+name = "requests"
+version = "2.33.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "charset-normalizer" },
+ { name = "idna" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/5f/a4/98b9c7c6428a668bf7e42ebb7c79d576a1c3c1e3ae2d47e674b468388871/requests-2.33.1.tar.gz", hash = "sha256:18817f8c57c6263968bc123d237e3b8b08ac046f5456bd1e307ee8f4250d3517", size = 134120, upload-time = "2026-03-30T16:09:15.531Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d7/8e/7540e8a2036f79a125c1d2ebadf69ed7901608859186c856fa0388ef4197/requests-2.33.1-py3-none-any.whl", hash = "sha256:4e6d1ef462f3626a1f0a0a9c42dd93c63bad33f9f1c1937509b8c5c8718ab56a", size = 64947, upload-time = "2026-03-30T16:09:13.83Z" },
+]
+
+[[package]]
+name = "requests-toolbelt"
+version = "1.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f3/61/d7545dafb7ac2230c70d38d31cbfe4cc64f7144dc41f6e4e4b78ecd9f5bb/requests-toolbelt-1.0.0.tar.gz", hash = "sha256:7681a0a3d047012b5bdc0ee37d7f8f07ebe76ab08caeccfc3921ce23c88d5bc6", size = 206888, upload-time = "2023-05-01T04:11:33.229Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3f/51/d4db610ef29373b879047326cbf6fa98b6c1969d6f6dc423279de2b1be2c/requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06", size = 54481, upload-time = "2023-05-01T04:11:28.427Z" },
+]
+
+[[package]]
+name = "rfc3986"
+version = "2.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/85/40/1520d68bfa07ab5a6f065a186815fb6610c86fe957bc065754e47f7b0840/rfc3986-2.0.0.tar.gz", hash = "sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c", size = 49026, upload-time = "2022-01-10T00:52:30.832Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ff/9a/9afaade874b2fa6c752c36f1548f718b5b83af81ed9b76628329dab81c1b/rfc3986-2.0.0-py2.py3-none-any.whl", hash = "sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd", size = 31326, upload-time = "2022-01-10T00:52:29.594Z" },
+]
+
+[[package]]
+name = "rich"
+version = "14.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b3/c6/f3b320c27991c46f43ee9d856302c70dc2d0fb2dba4842ff739d5f46b393/rich-14.3.3.tar.gz", hash = "sha256:b8daa0b9e4eef54dd8cf7c86c03713f53241884e814f4e2f5fb342fe520f639b", size = 230582, upload-time = "2026-02-19T17:23:12.474Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/14/25/b208c5683343959b670dc001595f2f3737e051da617f66c31f7c4fa93abc/rich-14.3.3-py3-none-any.whl", hash = "sha256:793431c1f8619afa7d3b52b2cdec859562b950ea0d4b6b505397612db8d5362d", size = 310458, upload-time = "2026-02-19T17:23:13.732Z" },
+]
+
+[[package]]
+name = "ruamel-yaml"
+version = "0.19.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c7/3b/ebda527b56beb90cb7652cb1c7e4f91f48649fbcd8d2eb2fb6e77cd3329b/ruamel_yaml-0.19.1.tar.gz", hash = "sha256:53eb66cd27849eff968ebf8f0bf61f46cdac2da1d1f3576dd4ccee9b25c31993", size = 142709, upload-time = "2026-01-02T16:50:31.84Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b8/0c/51f6841f1d84f404f92463fc2b1ba0da357ca1e3db6b7fbda26956c3b82a/ruamel_yaml-0.19.1-py3-none-any.whl", hash = "sha256:27592957fedf6e0b62f281e96effd28043345e0e66001f97683aa9a40c667c93", size = 118102, upload-time = "2026-01-02T16:50:29.201Z" },
+]
+
+[[package]]
+name = "ruff"
+version = "0.15.8"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/14/b0/73cf7550861e2b4824950b8b52eebdcc5adc792a00c514406556c5b80817/ruff-0.15.8.tar.gz", hash = "sha256:995f11f63597ee362130d1d5a327a87cb6f3f5eae3094c620bcc632329a4d26e", size = 4610921, upload-time = "2026-03-26T18:39:38.675Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4a/92/c445b0cd6da6e7ae51e954939cb69f97e008dbe750cfca89b8cedc081be7/ruff-0.15.8-py3-none-linux_armv6l.whl", hash = "sha256:cbe05adeba76d58162762d6b239c9056f1a15a55bd4b346cfd21e26cd6ad7bc7", size = 10527394, upload-time = "2026-03-26T18:39:41.566Z" },
+ { url = "https://files.pythonhosted.org/packages/eb/92/f1c662784d149ad1414cae450b082cf736430c12ca78367f20f5ed569d65/ruff-0.15.8-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:d3e3d0b6ba8dca1b7ef9ab80a28e840a20070c4b62e56d675c24f366ef330570", size = 10905693, upload-time = "2026-03-26T18:39:30.364Z" },
+ { url = "https://files.pythonhosted.org/packages/ca/f2/7a631a8af6d88bcef997eb1bf87cc3da158294c57044aafd3e17030613de/ruff-0.15.8-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6ee3ae5c65a42f273f126686353f2e08ff29927b7b7e203b711514370d500de3", size = 10323044, upload-time = "2026-03-26T18:39:33.37Z" },
+ { url = "https://files.pythonhosted.org/packages/67/18/1bf38e20914a05e72ef3b9569b1d5c70a7ef26cd188d69e9ca8ef588d5bf/ruff-0.15.8-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fdce027ada77baa448077ccc6ebb2fa9c3c62fd110d8659d601cf2f475858d94", size = 10629135, upload-time = "2026-03-26T18:39:44.142Z" },
+ { url = "https://files.pythonhosted.org/packages/d2/e9/138c150ff9af60556121623d41aba18b7b57d95ac032e177b6a53789d279/ruff-0.15.8-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:12e617fc01a95e5821648a6df341d80456bd627bfab8a829f7cfc26a14a4b4a3", size = 10348041, upload-time = "2026-03-26T18:39:52.178Z" },
+ { url = "https://files.pythonhosted.org/packages/02/f1/5bfb9298d9c323f842c5ddeb85f1f10ef51516ac7a34ba446c9347d898df/ruff-0.15.8-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:432701303b26416d22ba696c39f2c6f12499b89093b61360abc34bcc9bf07762", size = 11121987, upload-time = "2026-03-26T18:39:55.195Z" },
+ { url = "https://files.pythonhosted.org/packages/10/11/6da2e538704e753c04e8d86b1fc55712fdbdcc266af1a1ece7a51fff0d10/ruff-0.15.8-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d910ae974b7a06a33a057cb87d2a10792a3b2b3b35e33d2699fdf63ec8f6b17a", size = 11951057, upload-time = "2026-03-26T18:39:19.18Z" },
+ { url = "https://files.pythonhosted.org/packages/83/f0/c9208c5fd5101bf87002fed774ff25a96eea313d305f1e5d5744698dc314/ruff-0.15.8-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2033f963c43949d51e6fdccd3946633c6b37c484f5f98c3035f49c27395a8ab8", size = 11464613, upload-time = "2026-03-26T18:40:06.301Z" },
+ { url = "https://files.pythonhosted.org/packages/f8/22/d7f2fabdba4fae9f3b570e5605d5eb4500dcb7b770d3217dca4428484b17/ruff-0.15.8-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f29b989a55572fb885b77464cf24af05500806ab4edf9a0fd8977f9759d85b1", size = 11257557, upload-time = "2026-03-26T18:39:57.972Z" },
+ { url = "https://files.pythonhosted.org/packages/71/8c/382a9620038cf6906446b23ce8632ab8c0811b8f9d3e764f58bedd0c9a6f/ruff-0.15.8-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:ac51d486bf457cdc985a412fb1801b2dfd1bd8838372fc55de64b1510eff4bec", size = 11169440, upload-time = "2026-03-26T18:39:22.205Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/0d/0994c802a7eaaf99380085e4e40c845f8e32a562e20a38ec06174b52ef24/ruff-0.15.8-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:c9861eb959edab053c10ad62c278835ee69ca527b6dcd72b47d5c1e5648964f6", size = 10605963, upload-time = "2026-03-26T18:39:46.682Z" },
+ { url = "https://files.pythonhosted.org/packages/19/aa/d624b86f5b0aad7cef6bbf9cd47a6a02dfdc4f72c92a337d724e39c9d14b/ruff-0.15.8-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8d9a5b8ea13f26ae90838afc33f91b547e61b794865374f114f349e9036835fb", size = 10357484, upload-time = "2026-03-26T18:39:49.176Z" },
+ { url = "https://files.pythonhosted.org/packages/35/c3/e0b7835d23001f7d999f3895c6b569927c4d39912286897f625736e1fd04/ruff-0.15.8-py3-none-musllinux_1_2_i686.whl", hash = "sha256:c2a33a529fb3cbc23a7124b5c6ff121e4d6228029cba374777bd7649cc8598b8", size = 10830426, upload-time = "2026-03-26T18:40:03.702Z" },
+ { url = "https://files.pythonhosted.org/packages/f0/51/ab20b322f637b369383adc341d761eaaa0f0203d6b9a7421cd6e783d81b9/ruff-0.15.8-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:75e5cd06b1cf3f47a3996cfc999226b19aa92e7cce682dcd62f80d7035f98f49", size = 11345125, upload-time = "2026-03-26T18:39:27.799Z" },
+ { url = "https://files.pythonhosted.org/packages/37/e6/90b2b33419f59d0f2c4c8a48a4b74b460709a557e8e0064cf33ad894f983/ruff-0.15.8-py3-none-win32.whl", hash = "sha256:bc1f0a51254ba21767bfa9a8b5013ca8149dcf38092e6a9eb704d876de94dc34", size = 10571959, upload-time = "2026-03-26T18:39:36.117Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/a2/ef467cb77099062317154c63f234b8a7baf7cb690b99af760c5b68b9ee7f/ruff-0.15.8-py3-none-win_amd64.whl", hash = "sha256:04f79eff02a72db209d47d665ba7ebcad609d8918a134f86cb13dd132159fc89", size = 11743893, upload-time = "2026-03-26T18:39:25.01Z" },
+ { url = "https://files.pythonhosted.org/packages/15/e2/77be4fff062fa78d9b2a4dea85d14785dac5f1d0c1fb58ed52331f0ebe28/ruff-0.15.8-py3-none-win_arm64.whl", hash = "sha256:cf891fa8e3bb430c0e7fac93851a5978fc99c8fa2c053b57b118972866f8e5f2", size = 11048175, upload-time = "2026-03-26T18:40:01.06Z" },
+]
+
+[[package]]
+name = "secretstorage"
+version = "3.5.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+ { name = "jeepney" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" },
+]
+
+[[package]]
+name = "semver"
+version = "3.0.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/72/d1/d3159231aec234a59dd7d601e9dd9fe96f3afff15efd33c1070019b26132/semver-3.0.4.tar.gz", hash = "sha256:afc7d8c584a5ed0a11033af086e8af226a9c0b206f313e0301f8dd7b6b589602", size = 269730, upload-time = "2025-01-24T13:19:27.617Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a6/24/4d91e05817e92e3a61c8a21e08fd0f390f5301f1c448b137c57c4bc6e543/semver-3.0.4-py3-none-any.whl", hash = "sha256:9c824d87ba7f7ab4a1890799cec8596f15c1241cb473404ea1cb0c55e4b04746", size = 17912, upload-time = "2025-01-24T13:19:24.949Z" },
+]
+
+[[package]]
+name = "tomlkit"
+version = "0.14.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c3/af/14b24e41977adb296d6bd1fb59402cf7d60ce364f90c890bd2ec65c43b5a/tomlkit-0.14.0.tar.gz", hash = "sha256:cf00efca415dbd57575befb1f6634c4f42d2d87dbba376128adb42c121b87064", size = 187167, upload-time = "2026-01-13T01:14:53.304Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b5/11/87d6d29fb5d237229d67973a6c9e06e048f01cf4994dee194ab0ea841814/tomlkit-0.14.0-py3-none-any.whl", hash = "sha256:592064ed85b40fa213469f81ac584f67a4f2992509a7c3ea2d632208623a3680", size = 39310, upload-time = "2026-01-13T01:14:51.965Z" },
+]
+
+[[package]]
+name = "trove-classifiers"
+version = "2026.1.14.14"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/43/7935f8ea93fcb6680bc10a6fdbf534075c198eeead59150dd5ed68449642/trove_classifiers-2026.1.14.14.tar.gz", hash = "sha256:00492545a1402b09d4858605ba190ea33243d361e2b01c9c296ce06b5c3325f3", size = 16997, upload-time = "2026-01-14T14:54:50.526Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bb/4a/2e5583e544bc437d5e8e54b47db87430df9031b29b48d17f26d129fa60c0/trove_classifiers-2026.1.14.14-py3-none-any.whl", hash = "sha256:1f9553927f18d0513d8e5ff80ab8980b8202ce37ecae0e3274ed2ef11880e74d", size = 14197, upload-time = "2026-01-14T14:54:49.067Z" },
+]
+
+[[package]]
+name = "twine"
+version = "6.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "id" },
+ { name = "keyring", marker = "platform_machine != 'ppc64le' and platform_machine != 's390x'" },
+ { name = "packaging" },
+ { name = "readme-renderer" },
+ { name = "requests" },
+ { name = "requests-toolbelt" },
+ { name = "rfc3986" },
+ { name = "rich" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e0/a8/949edebe3a82774c1ec34f637f5dd82d1cf22c25e963b7d63771083bbee5/twine-6.2.0.tar.gz", hash = "sha256:e5ed0d2fd70c9959770dce51c8f39c8945c574e18173a7b81802dab51b4b75cf", size = 172262, upload-time = "2025-09-04T15:43:17.255Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3a/7a/882d99539b19b1490cac5d77c67338d126e4122c8276bf640e411650c830/twine-6.2.0-py3-none-any.whl", hash = "sha256:418ebf08ccda9a8caaebe414433b0ba5e25eb5e4a927667122fbe8f829f985d8", size = 42727, upload-time = "2025-09-04T15:43:15.994Z" },
+]
+
+[[package]]
+name = "ty"
+version = "0.0.27"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f4/de/e5cf1f151cf52fe1189e42d03d90909d7d1354fdc0c1847cbb63a0baa3da/ty-0.0.27.tar.gz", hash = "sha256:d7a8de3421d92420b40c94fe7e7d4816037560621903964dd035cf9bd0204a73", size = 5424130, upload-time = "2026-03-31T19:07:20.806Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fa/20/2a9ea661758bd67f2bfd54ce9daacb5a26c56c5f8b49fbd9a43b365a8a7d/ty-0.0.27-py3-none-linux_armv6l.whl", hash = "sha256:eb14456b8611c9e8287aa9b633f4d2a0d9f3082a31796969e0b50bdda8930281", size = 10571211, upload-time = "2026-03-31T19:07:23.28Z" },
+ { url = "https://files.pythonhosted.org/packages/da/b2/8887a51f705d075ddbe78ae7f0d4755ef48d0a90235f67aee289e9cee950/ty-0.0.27-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:02e662184703db7586118df611cf24a000d35dae38d950053d1dd7b6736fd2c4", size = 10427576, upload-time = "2026-03-31T19:07:15.499Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/c3/79d88163f508fb709ce19bc0b0a66c7c64b53d372d4caa56172c3d9b3ae8/ty-0.0.27-py3-none-macosx_11_0_arm64.whl", hash = "sha256:be5fc2899441f7f8f7ef40f9ffd006075a5ff6b06c44e8d2aa30e1b900c12f51", size = 9870359, upload-time = "2026-03-31T19:07:36.852Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/4d/ed1b0db0e1e46b5ed4976bbfe0d1825faf003b4e3774ef28c785ed73e4bb/ty-0.0.27-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:30231e652b14742a76b64755e54bf0cb1cd4c128bcaf625222e0ca92a2094887", size = 10380488, upload-time = "2026-03-31T19:07:31.268Z" },
+ { url = "https://files.pythonhosted.org/packages/b1/f2/20372f6d510b01570028433064880adec2f8abe68bf0c4603be61a560bef/ty-0.0.27-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5a119b1168f64261b3205a37e40b5b6c4aac8fd58e4587988f4e4b22c3c79847", size = 10390248, upload-time = "2026-03-31T19:07:28.345Z" },
+ { url = "https://files.pythonhosted.org/packages/45/4b/46b31a7311306be1a560f7f20fdc37b5bf718787f60626cd265d9b637554/ty-0.0.27-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e38f4e187b6975d2cbebf0f1eb1221f8f64f6e509bad14d7bb2a91afc97e4956", size = 10878479, upload-time = "2026-03-31T19:07:39.393Z" },
+ { url = "https://files.pythonhosted.org/packages/42/ba/5231a2a1fb1cebe053a25de8fded95e1a30a1e77d3628a9e58487297bafc/ty-0.0.27-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a07b1a8fbb23844f6d22091275430d9ac617175f34aa99159b268193de210389", size = 11461232, upload-time = "2026-03-31T19:07:02.518Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/37/558abab3e1f6670493524f61280b4dfcc3219555f13889223e733381dfab/ty-0.0.27-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d3ec4033031f240836bb0337274bac5c49dde312c7c6d7575451ed719bf8ffa3", size = 11133002, upload-time = "2026-03-31T19:07:18.371Z" },
+ { url = "https://files.pythonhosted.org/packages/32/38/188c14a57f52160407ce62c6abb556011718fd0bcbe1dca690529ce84c46/ty-0.0.27-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:924a8849afd500d260bf5b7296165a05b7424fbb6b19113f30f3b999d682873f", size = 10986624, upload-time = "2026-03-31T19:07:13.066Z" },
+ { url = "https://files.pythonhosted.org/packages/9f/f1/667a71393f47d2cd6ba9ed07541b8df3eb63aab1f2ee658e77d91b8362fa/ty-0.0.27-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:d8270026c07e7423a1b3a3fd065b46ed1478748f0662518b523b57744f3fa025", size = 10366721, upload-time = "2026-03-31T19:07:00.131Z" },
+ { url = "https://files.pythonhosted.org/packages/8b/aa/8edafe41be898bda774249abc5be6edd733e53fb1777d59ea9331e38537d/ty-0.0.27-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:e26e9735d3bdfd95d881111ad1cf570eab8188d8c3be36d6bcaad044d38984d8", size = 10412239, upload-time = "2026-03-31T19:07:05.297Z" },
+ { url = "https://files.pythonhosted.org/packages/53/ff/8bafaed4a18d38264f46bdfc427de7ea2974cf9064e4e0bdb1b6e6c724e3/ty-0.0.27-py3-none-musllinux_1_2_i686.whl", hash = "sha256:7c09cc9a699810609acc0090af8d0db68adaee6e60a7c3e05ab80cc954a83db7", size = 10573507, upload-time = "2026-03-31T19:06:57.064Z" },
+ { url = "https://files.pythonhosted.org/packages/16/2e/63a8284a2fefd08ab56ecbad0fde7dd4b2d4045a31cf24c1d1fcd9643227/ty-0.0.27-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:2d3e02853bb037221a456e034b1898aaa573e6374fbb53884e33cb7513ccb85a", size = 11090233, upload-time = "2026-03-31T19:07:34.139Z" },
+ { url = "https://files.pythonhosted.org/packages/14/d3/d6fa1cafdfa2b34dbfa304fc6833af8e1669fc34e24d214fa76d2a2e5a25/ty-0.0.27-py3-none-win32.whl", hash = "sha256:34e7377f2047c14dbbb7bf5322e84114db7a5f2cb470db6bee63f8f3550cfc1e", size = 9984415, upload-time = "2026-03-31T19:07:07.98Z" },
+ { url = "https://files.pythonhosted.org/packages/85/e6/dd4e27da9632b3472d5711ca49dbd3709dbd3e8c73f3af6db9c254235ca9/ty-0.0.27-py3-none-win_amd64.whl", hash = "sha256:3f7e4145aad8b815ed69b324c93b5b773eb864dda366ca16ab8693ff88ce6f36", size = 10961535, upload-time = "2026-03-31T19:07:10.566Z" },
+ { url = "https://files.pythonhosted.org/packages/0e/1a/824b3496d66852ed7d5d68d9787711131552b68dce8835ce9410db32e618/ty-0.0.27-py3-none-win_arm64.whl", hash = "sha256:95bf8d01eb96bb2ba3ffc39faff19da595176448e80871a7b362f4d2de58476c", size = 10376689, upload-time = "2026-03-31T19:07:25.732Z" },
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.15.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
+]
+
+[[package]]
+name = "typing-inspection"
+version = "0.4.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac53367ae42139cf4b1ca5f36bb3dc6c9d33acdb43655/typing_inspection-0.4.2.tar.gz", hash = "sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464", size = 75949, upload-time = "2025-10-01T02:14:41.687Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" },
+]
+
+[[package]]
+name = "urllib3"
+version = "2.6.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c7/24/5f1b3bdffd70275f6661c76461e25f024d5a38a46f04aaca912426a2b1d3/urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed", size = 435556, upload-time = "2026-01-07T16:24:43.925Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/39/08/aaaad47bc4e9dc8c725e68f9d04865dbcb2052843ff09c97b08904852d84/urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4", size = 131584, upload-time = "2026-01-07T16:24:42.685Z" },
+]
+
+[[package]]
+name = "uv-release"
+version = "0.28.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "httpx" },
+ { name = "packaging" },
+ { name = "pydantic" },
+ { name = "pygit2" },
+ { name = "ruamel-yaml" },
+ { name = "semver" },
+ { name = "tomlkit" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/03/53/219297d39098ee6075dda93a881c6ff3b02d8a8bd867e3654dc09f16a12e/uv_release-0.28.1-py3-none-any.whl", hash = "sha256:4c5bc69003a03bbf2ed861a544201bb27376bb5ae950524ecf6273c90c06afda", size = 116003, upload-time = "2026-04-14T19:14:39.23Z" },
+]
+
+[[package]]
+name = "zipp"
+version = "3.23.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547, upload-time = "2025-06-08T17:06:39.4Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276, upload-time = "2025-06-08T17:06:38.034Z" },
+]
diff --git a/uvr_hooks.py b/uvr_hooks.py
new file mode 100644
index 0000000..0eb70f1
--- /dev/null
+++ b/uvr_hooks.py
@@ -0,0 +1,188 @@
+"""UVR release hooks for quicksand."""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+from uv_release_monorepo.shared.hooks import ReleaseHook
+from uv_release_monorepo.shared.models import BuildStage, ReleasePlan
+
+# Canonical runner per architecture — retag only runs on these.
+# x64 images are built natively on Linux; arm64 images are built on
+# macOS because the Linux arm64 runners lack KVM for overlay builds.
+RETAG_RUNNERS: list[list[str]] = [
+ ["self-hosted", "linux", "x64"],
+ ["self-hosted", "macos", "arm64"],
+]
+
+_WHEEL_RE = re.compile(
+ r"^(?P<name>.+?)-(?P<version>.+?)-(?P<python>\w+)-(?P<abi>\w+)-(?P<platform>.+)\.whl$"
+)
+_ARCH_RE = re.compile(r"(?:x86_64|aarch64|arm64|amd64)$")
+
+# Architecture -> all platform tags the wheel should be available for.
+_ARCH_TARGETS: dict[str, list[str]] = {
+ "x86_64": ["linux_x86_64", "macosx_10_13_x86_64", "win_amd64"],
+ "amd64": ["linux_x86_64", "macosx_10_13_x86_64", "win_amd64"],
+ "aarch64": ["linux_aarch64", "macosx_11_0_arm64", "win_arm64"],
+ "arm64": ["linux_aarch64", "macosx_11_0_arm64", "win_arm64"],
+}
+
+# Packages that are natively built per-platform (not retagged).
+_SKIP = {"quicksand_qemu"}
+
+
+def _retag_wheels(dist: Path) -> None:
+ """Copy each image wheel into variants for every supported host platform."""
+ for whl in sorted(dist.glob("*.whl")):
+ m = _WHEEL_RE.match(whl.name)
+ if not m:
+ continue
+ parts = m.groupdict()
+ if parts["name"] in _SKIP:
+ continue
+ arch_m = _ARCH_RE.search(parts["platform"])
+ if not arch_m:
+ continue
+
+ for target in _ARCH_TARGETS[arch_m.group()]:
+ new_name = f"{parts['name']}-{parts['version']}-py3-none-{target}.whl"
+ dest = dist / new_name
+ if dest.resolve() != whl.resolve() and not dest.exists():
+ shutil.copy2(whl, dest)
+ print(f" {whl.name} -> {new_name}")
+
+
+# Packages whose changes require integration tests.
+_TEST_PACKAGES = {
+ "quicksand",
+ "quicksand-ubuntu",
+ "quicksand-alpine",
+ "quicksand-core",
+ "quicksand-qemu",
+ "quicksand-smb",
+}
+
+
+def _latest_release_tag(pkg: str) -> str | None:
+ """Find the latest release tag for a package using git tags."""
+ result = subprocess.run(
+ ["git", "tag", "-l", f"{pkg}/v*", "--sort=-v:refname"],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ return None
+ for line in result.stdout.strip().split("\n"):
+ tag = line.strip()
+ if tag and ".dev" not in tag and not tag.endswith("-dev"):
+ return tag
+ return None
+
+
+class Hook(ReleaseHook):
+ def post_plan(self, plan: ReleasePlan) -> ReleasePlan:
+ """Skip jobs whose packages didn't change, and serialize build stages."""
+ changed = plan.changed.keys()
+ if "test" not in plan.skip and not (changed & _TEST_PACKAGES):
+ plan.skip.append("test")
+ if "verify-licenses" not in plan.skip and "quicksand-qemu" not in changed:
+ plan.skip.append("verify-licenses")
+
+ # Inject per-VM test install commands into the plan.
+ # The workflow downloads built wheels into dist/ via download-artifact.
+ # For unchanged packages we fetch their latest release wheels too.
+ changed = plan.changed.keys()
+ install_lines = [
+ "uv venv --seed",
+ "uv pip install --reinstall pytest pytest-timeout pytest-asyncio",
+ ]
+ for pkg in sorted(_TEST_PACKAGES):
+ if pkg in changed:
+ continue
+ tag = _latest_release_tag(pkg)
+ if not tag:
+ continue
+ dist_name = pkg.replace("-", "_")
+ install_lines.append(
+ f"gh release download {tag} --repo $GITHUB_REPOSITORY"
+ f" --dir dist/"
+ f" --pattern '{dist_name}-*linux_x86_64.whl'"
+ f" --pattern '{dist_name}-*any.whl'"
+ f" --clobber || true"
+ )
+ install_lines.append(
+ "uv pip install --reinstall --find-links dist/ quicksand quicksand-ubuntu quicksand-alpine"
+ )
+ install = "\n".join(install_lines)
+ plan.test_install = { # ty: ignore[unresolved-attribute]
+ vm: install for vm in ("ubuntu", "alpine")
+ }
+
+ # Serialize build stages: split multi-package stages into one stage
+ # per package so only one VM runs at a time per runner, preventing
+ # host disk exhaustion from concurrent overlay builds.
+ for runner_key, stages in plan.build_commands.items():
+ serialized: list[BuildStage] = []
+ for stage in stages:
+ if len(stage.packages) <= 1:
+ serialized.append(stage)
+ continue
+ first = True
+ for pkg_name, cmds in stage.packages.items():
+ serialized.append(
+ BuildStage(
+ setup=stage.setup if first else [],
+ packages={pkg_name: cmds},
+ cleanup=[],
+ )
+ )
+ first = False
+ if stage.cleanup and serialized:
+ serialized[-1].cleanup = stage.cleanup
+ plan.build_commands[runner_key] = serialized
+
+ return plan
+
+ def pre_build(self, plan: ReleasePlan, runner: list[str] | None = None) -> None:
+ """Install gh CLI on Windows runners (not pre-installed on self-hosted)."""
+ import os
+ import platform
+ import urllib.request
+
+ if platform.system() != "Windows":
+ return
+ if shutil.which("gh"):
+ return
+
+ print("Installing gh CLI for Windows...")
+ machine = platform.machine().lower()
+ arch = "arm64" if machine in ("arm64", "aarch64") else "amd64"
+ url = f"https://github.com/cli/cli/releases/download/v2.74.0/gh_2.74.0_windows_{arch}.zip"
+ zip_path = Path("gh_cli.zip")
+ gh_dir = Path("gh_cli")
+ try:
+ urllib.request.urlretrieve(url, zip_path)
+ import zipfile
+
+ with zipfile.ZipFile(zip_path, "r") as zf:
+ zf.extractall(gh_dir)
+ zip_path.unlink(missing_ok=True)
+ # Find the bin directory inside the extracted archive
+ for candidate in gh_dir.rglob("gh.exe"):
+ os.environ["PATH"] = str(candidate.parent) + os.pathsep + os.environ.get("PATH", "")
+ print(f"Installed gh CLI: {candidate}")
+ return
+ print("Warning: gh.exe not found in zip archive")
+ except Exception as e:
+ print(f"Warning: failed to install gh CLI: {e}")
+ print("Build may fail if dependency wheels need to be fetched")
+
+ def post_build(self, plan: ReleasePlan, runner: list[str] | None = None) -> None:
+ if runner is None or runner not in RETAG_RUNNERS:
+ return
+ print(f"Retagging wheels for cross-platform (runner: {runner})")
+ _retag_wheels(Path("dist"))