{"owner":"mozilla-ai","repo":"llamafile","hasSkills":true,"totalSkillsCount":14,"totalTokensCount":9578,"categories":["plugin-manifest","root-instruction","command-prompt","marketplace","anthropic-skill"],"hasMcp":false,"mcpConfig":null,"found":[".llamafile_plugin/.claude-plugin/plugin.json","docs/AGENTS.md","docs/commands/check.md",".llamafile_plugin/.claude-plugin/marketplace.json","docs/commands/build.md","docs/skills/llamafile/SKILL.md","docs/commands/generate-patches.md","docs/commands/clean.md","docs/commands/verify-clean.md","docs/skills/llamafile/development.md","docs/skills/llamafile/architecture.md","docs/skills/llamafile/building.md","docs/skills/llamafile/testing.md","docs/skills/llamafile/update_llamacpp.md"],"skills":{".llamafile_plugin/.claude-plugin/plugin.json":"{\n  \"name\": \"llamafile\",\n  \"version\": \"0.1.7\",\n  \"description\": \"Build guidance and commands for the llamafile project\"\n}\n","docs/AGENTS.md":"# AGENTS.md\n\nThis file provides guidance to Claude Code when working with this repository.\n\n## Project Overview\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Quick Reference\n\n```sh\n# Initial setup (run once after clone)\nmake setup\n\n# Build (always use cosmocc make, not system make)\n# Adapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Run tests\n.cosmocc/4.0.2/bin/make check\n\n# Clean build outputs\n.cosmocc/4.0.2/bin/make clean\n\n# Reset all submodules (warning: removes local changes)\nmake reset-repo\n```\n\n## Key Directories\n\n| Directory | Purpose |\n|-----------|---------|\n| `llamafile/` | Core library (edit directly) |\n| `llama.cpp/` | LLM inference (submodule, edit directly then convert to patches) |\n| `whisper.cpp/` | Speech-to-text (submodule, edit directly then convert to patches) |\n| `stable-diffusion.cpp/` | Image generation (submodule, edit directly then convert to patches) |\n| `*.patches/` | Patch directories for submodules |\n| `o/` | Build outputs |\n\n## Important Notes\n\n- Always use `.cosmocc/4.0.2/bin/make`, not system make\n- Run `make setup` after cloning or updating submodules\n- Submodule changes require patch files (see skill for workflow)\n\n## Detailed Documentation\n\nFor comprehensive build, architecture, development, and testing documentation, ask Claude about \"how to build llamafile\" or \"llamafile development workflow\" to load the llamafile skill.\n","docs/commands/check.md":"---\ndescription: Run llamafile unit tests\n---\n\n# Run Llamafile Tests\n\nRun the unit test suite using the Cosmopolitan toolchain.\n\n```bash\n.cosmocc/4.0.2/bin/make check\n```\n",".llamafile_plugin/.claude-plugin/marketplace.json":"{\n  \"name\": \"llamafile-local\",\n  \"description\": \"Local llamafile plugin marketplace\",\n  \"owner\": {\n    \"name\": \"Mozilla AI\",\n    \"email\": \"davide@mozilla.ai\"\n  },\n  \"plugins\": [\n    {\n      \"name\": \"llamafile\",\n      \"description\": \"Build guidance and commands for the llamafile project\",\n      \"version\": \"0.1.7\",\n      \"author\": {\n        \"name\": \"Mozilla AI\",\n        \"email\": \"davide@mozilla.ai\"\n      },\n      \"source\": \"./\"\n    }\n  ]\n}\n","docs/commands/build.md":"---\ndescription: Build llamafile using the cosmocc toolchain\n---\n\n# Build Llamafile\n\nBuild the project using the Cosmopolitan toolchain.\n\nFirst, ensure the toolchain is available:\n\n```bash\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\n```\n\nThen build:\n\n```bash\n.cosmocc/4.0.2/bin/make -j $(nproc)\n```\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\nBuild outputs will be in `o/$(MODE)/`.\n","docs/skills/llamafile/SKILL.md":"---\nname: llamafile\ndescription: This skill should be used when the user asks to \"build llamafile\", \"rebuild llamafile\", \"run llamafile\", \"run llamafile tests\", \"debug llamafile\", \"set up llamafile\", \"update patches\", \"fix patch conflict\", \"update llama.cpp\", \"pull latest llama.cpp\", \"sync upstream llama.cpp\", \"reset submodules\", \"write a test for llamafile\", \"how does llamafile work\", \"llamafile architecture\", or needs guidance on the llamafile build system, patch workflow, submodule integration, cosmocc toolchain, or development practices.\nversion: 0.1.6\n---\n\n# Llamafile Development Guide\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Version Disambiguation\n\n- **New llamafile** (or simply \"llamafile\"): The code in the `main` branch, used for releases >=0.10.0\n- **Old/Classic llamafile**: The legacy code, used for releases until 0.9.3 (see commit 7e7d33c).\n\nThis guide covers the **new llamafile** project.\n\n## Quick Reference\n\n### Initial Setup\n\n```sh\nmake setup\n```\n\nImmediately after cloning the repo (or after a reset done with `make reset-repo`), this command initializes git submodules and applies llamafile-specific patches.\n\n### Building\n\nRun `llamafile:build` to build all targets.\n\n### Testing\n\nRun `llamafile:check` to run the unit test suite.\n\n### Cleaning\n\nRun `llamafile:clean` to remove all build outputs.\n\n### Reset Submodules\n\nAfter `make setup`, submodules contain patches and are no longer in a clean state.\nTo reset them, run:\n\n```sh\nmake reset-repo  # Warning: removes all local changes\n```\n\nWARNING: this command removes all local changes. Do not run it without first generating patches from any modifications.\n\n### Patch & Upstream-Update Commands\n\nWhen changing submodule patches or bumping llama.cpp, use the dedicated commands\nrather than ad-hoc `git diff`/`git apply`:\n\n- `llamafile:generate-patches` — regenerate patches from in-place submodule edits\n  (the only sanctioned way to produce patches).\n- `llamafile:verify-clean` — clean round-trip (`reset-repo` → `setup` → clean\n  build → `check`); the verification after generating patches or any patch change.\n\nFor the full llama.cpp bump procedure, follow `update_llamacpp.md` step by step.\n\n\n## Core Workflows\n\n### Building from Scratch\n\nTo build llamafile from a fresh clone:\n\n1. Clone the repository\n2. Run `make setup` to initialize submodules and apply patches\n3. Build with `llamafile:build`\n\nBuild outputs appear in `o/$(MODE)/` directory.\n\n### Modifying Core Code\n\nFor changes to llamafile's own code (not submodules):\n\n1. Edit files in `llamafile/` directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\n### Modifying Submodule Code\n\nSubmodules (llama.cpp, whisper.cpp, stable-diffusion.cpp) require a patch-based workflow:\n\n1. Make changes directly in the submodule directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\nNOTE: never try to edit patches or generate them manually. This step is \ndone only after rebuild and tests (even manual ones) are successful. See\n`development.md` for detailed patch workflow.\n\n### Running Specific Tests\n\nTests use the `.runs` pattern in BUILD.mk files:\n\n```makefile\no/$(MODE)/llamafile/json_test.runs\n```\n\nTo run all tests: `llamafile:check`\n\n## Key Concepts\n\n### Cosmopolitan Toolchain\n\nThe project uses Cosmopolitan Libc (cosmocc) to create Actually Portable Executables (APE) - single files that run on multiple platforms without modification. Always use the `llamafile:build`, `llamafile:check`, and `llamafile:clean` commands (which use cosmocc's make), not system make.\n\n### Patch System\n\nEach submodule has a corresponding patches directory:\n- `llama.cpp.patches/`\n- `whisper.cpp.patches/`\n- `stable-diffusion.cpp.patches/`\n\nPatches include:\n- **Modifications** (.patch files): Changes to upstream code\n- **Additions** (llamafile-files/): New files for integration (BUILD.mk, utilities)\n\n### Build System\n\n- **build/config.mk**: Compiler and toolchain configuration\n- **build/rules.mk**: Generic build patterns (.c → .o, archives, asset bundling)\n- **BUILD.mk files**: Per-package build logic\n\nOutputs: `o/$(MODE)/package/file.o`\n\n### Multi-Architecture Support\n\nBinaries include both x86_64 and aarch64 code paths with runtime CPU feature detection (AVX, AVX2, AVX-512, ARM NEON).\n\n### GPU Backend Loaders\n\nDynamically-loaded backends that export the ggml C ABI — CUDA, ROCm, Vulkan — all go through the shared probe core in `llamafile/gpu_backend.c`. Each is just a `GpuBackendDesc` + a link thunk; the core does load → log-suppress → **device-count gate** (reject 0-device DSOs so AUTO falls back) → register, with a SIGSEGV/SIGABRT crash guard around the foreign probe call (driver init can fault across the cosmo/ms_abi boundary — issue #988). Metal stays separate by design (runtime-compiled, no ms_abi split, no device gate). When adding/changing a backend: route it through the core, keep the gate, and add a case to `tests/gpu_backend_test.cpp`. A more detailed design doc lives separately.\n\n## Main Executables\n\nAfter building, find binaries in `o/$(MODE)/`:\n\n| Binary | Purpose |\n|--------|---------|\n| `llamafile/llamafile` | Main llamafile executable |\n| `third_party/zipalign/zipalign` | Bundle assets into executables |\n| `whisperfile/whisperfile` | Main whisperfile executable |\n\n## Troubleshooting\n\n### Build Fails After Submodule Update\n\nRun `make setup` to reapply patches after any submodule changes.\n\n### Submodule Has Uncommitted Changes\n\nTo reset a single submodule:\n```sh\ncd <submodule> && git reset --hard && git clean -fdx\n```\n\nTo reset all submodules:\n```sh\nmake reset-repo\n```\n\n### Wrong Make Being Used\n\nEnsure using the `llamafile:build` command (which uses cosmocc's make), not system make.\n\n## Additional Resources\n\n### Reference Files\n\nFor detailed information, consult:\n- **`building.md`** - Complete build system documentation, toolchain details\n- **`architecture.md`** - Repository structure, component overview\n- **`development.md`** - Development workflow, patch management, submodule integration\n- **`testing.md`** - Test patterns, running and writing tests\n- **`update_llamacpp.md`** - Keeping llamafile updated with upstream llama.cpp\n\n### Project Documentation\n\n- **README.md** in repo: Project introduction\n- **docs/** directory: User documentation (quickstart, installation, troubleshooting)\n- **RELEASE.md**: Release process\n- Most executables support `--help`\n","docs/commands/generate-patches.md":"---\ndescription: Regenerate llamafile patches from in-place submodule edits\n---\n\n# Generate Patches\n\nCapture the current in-place edits of a submodule as patch files, using the\nproject's `generate_patches.sh` tool. This is the **only** sanctioned way to\nproduce patches — never hand-craft them with `git diff` (the tool rewrites the\n`a/`,`b/` paths to be repo-rooted, strips the volatile `index` line, names files\nby convention, and routes new/untracked files into `llamafile-files/`; a raw\n`git diff` gets all of that wrong).\n\nRun it for the `llama.cpp` submodule (the common case). The tool is general and\nworks for any submodule — swap the directory and output path for `whisper.cpp`\nor `stable-diffusion.cpp`.\n\nThe subshell keeps the working directory restored even if the tool fails, and\n`echo y` answers the script's confirmation prompt non-interactively:\n\n```bash\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nOutput lands in `llama.cpp.patches/patches/` (modified files) and\n`llama.cpp.patches/llamafile-files/` (new files, including `BUILD.mk`).\n\nThe tool **only writes/overwrites — it never deletes**. If you dropped a patch\nduring a bump (the file is no longer modified, e.g. upstream absorbed the\nchange), its old `.patch` will still be sitting in `patches/` and will keep\nbeing applied by `setup`. `git rm` each dropped patch by hand, and confirm the\nfinal count (`ls llama.cpp.patches/patches | wc -l`) matches your intent.\n\nIMPORTANT: only run this **after** the in-place edits are proven to work\n(a clean build succeeds and llamafile runs as expected). Generating patches\nfrom unproven edits bakes in breakage. After generating, verify the patch set\nround-trips with `llamafile:verify-clean`.\n","docs/commands/clean.md":"---\ndescription: Clean llamafile build outputs\n---\n\n# Clean Llamafile Build\n\nRemove all build outputs from the `o/` directory.\n\n```bash\n.cosmocc/4.0.2/bin/make clean\n```\n","docs/commands/verify-clean.md":"---\ndescription: Clean round-trip — reset, re-apply patches, clean build, and test\n---\n\n# Verify Clean\n\nVerify the repository from a clean slate: reset, re-pull submodules and\nre-apply patches, then do a **clean** build and run the tests. Use this:\n\n- as the final verification after `llamafile:generate-patches` (confirms the\n  regenerated patches re-apply cleanly and still build), and\n- any time patches or submodules change and you need a trustworthy result.\n\nWhy a clean build: after a `reset-repo`/`setup`, submodule sources change\nwithout their timestamps necessarily moving, so an incremental `make` can link\nstale objects. Always `make clean` first here — do not rebuild incrementally.\n\n`make setup` both pulls submodules and applies patches, and it cannot pull\nsubmodules onto a dirty tree — that is exactly why `reset-repo` runs first.\n\nNote: `reset-repo` is destructive (it `rm -rf`s the submodule dirs before\nrestoring them), so a permission-gated environment may prompt or block it. Run\nit through the `$MAKE` (`.cosmocc/.../make`) form below rather than raw\n`git clean`/`reset`; allowlist `make reset-repo` if round-trips keep stalling.\n\n```bash\n# ensure the toolchain is available\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\nMAKE=.cosmocc/4.0.2/bin/make\n\n$MAKE reset-repo     # clean: drop all local changes, reset submodules\n$MAKE setup          # pull submodules + apply patches (+ fetch UI assets)\n$MAKE clean          # drop stale build outputs\n$MAKE -j$(nproc)     # clean build; on mac use -j$(sysctl -n hw.physicalcpu)\n$MAKE check          # unit tests\n```\n\nA successful round-trip proves the committed patch set is internally\nconsistent. It does NOT cover GPU runtime backends, non-host platforms, the\nweb UI, or long-run stability — see the handoff checklist in\n`update_llamacpp.md`.\n","docs/skills/llamafile/development.md":"# Llamafile Development Workflow\n\nGuide to modifying code, managing patches, and working with submodules.\n\n## Development Overview\n\nLlamafile development involves two distinct workflows:\n\n1. **Core code changes**: Direct edits to root-level directories such as `llamafile/`, `whisperfile/`, etc.\n2. **Submodule changes**: Patch-based modifications to `llama.cpp`, `whisper.cpp`, `stable-diffusion.cpp`\n\n## Modifying Core Code\n\nFor changes which are not affecting submodules:\n\n### Workflow\n\n1. Edit files\n2. Rebuild: `llamafile:build`\n3. Test: `llamafile:check`\n4. Commit changes normally with git\n\n### Key Directories\n\n```\nllamafile/\n├── server/      # HTTP server, API endpoints\n├── highlight/   # Syntax highlighting\n├── tinyblas/    # Optimized BLAS kernels\n└── *.c, *.h     # Core utilities\n```\n\n## Modifying Submodule Code\n\nSubmodules require a patch-based workflow because:\n- Submodules point to specific upstream commits\n- Direct commits in submodules would be lost\n- Patches preserve modifications across submodule updates\n\n### Understanding the Patch System\n\nEach submodule has a patches directory. For instance, for `llama.cpp`:\n\n```\nllama.cpp.patches/\n├── README.md              # Patching info + list of all patches and their purpose\n├── apply-patches.sh       # Script to apply all patches to llama.cpp submodule\n├── renames.sh             # Script for file renames/moves (if any)\n├── llamafile-files/       # Additional files to copy into llama.cpp\n│   ├── BUILD.mk           # Makefile for building llama.cpp with cosmocc\n│   └── README.llamafile   # License and modification notes\n└── patches/               # Patch files for upstream sources\n```\n\nPatches are applied by `make setup`:\n1. Submodule is reset to clean state\n2. Each .patch file is applied in alphabetical order\n3. Files from llamafile-files/ are copied into the submodule\n\n### Making Changes to a Submodule\n\n#### Step 1: Make Changes\n\nEdit files directly in the submodule directory:\n\n```sh\ncd llama.cpp\n# Make your changes\nvim src/llama.cpp\n```\n\n#### Step 2: Generate Patches\n\nPatches are usually generated after the code has been thoroughly tested and is\nready to commit. To avoid manual errors, use the script `tools/generate_patches.sh`\n(or the `llamafile:generate-patches` skill that wraps it), which automatically\nsaves all new files and patches in the specified output directory.\n\n```sh\n# echo y answers the prompt; the subshell restores the cwd even on failure\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nAfter this operation, one can double check which files have been modified / added\nvia a `git diff`.\n\nNaming convention:\n- all patches have a `.patch` extension\n- patch filenames reflect the file path with underscores replacing slashes (e.g., `common_arg.cpp.patch` for `common/arg.cpp`).\n\n\n#### Step 3: Verify Patches\n\nOnce you are sure all patches have been saved, reset and reapply to verify:\n\n```sh\n# Reset everything\nmake reset-repo\n\n# Reapply patches\nmake setup\n\n# Rebuild and test\n# llamafile:build\n# llamafile:check\n```\n\n### Adding New Files to Submodules\n\nFor new files (not modifications), use llamafile-files/:\n\n```sh\n# Create directory structure matching submodule\nmkdir -p llama.cpp.patches/llamafile-files/src/\n\n# Add your new file\ncp new-utility.cpp llama.cpp.patches/llamafile-files/src/\n```\n\nThe file will be copied into the submodule during `make setup`.\n\n### Updating BUILD.mk for Submodules\n\nEach submodule needs a BUILD.mk in llamafile-files/:\n\n```makefile\n# llama.cpp.patches/llamafile-files/BUILD.mk\n\nLLAMA_SRCS = \\\n    llama.cpp/src/llama.cpp \\\n    llama.cpp/src/new-file.cpp    # Add new files here\n\nLLAMA_OBJS = $(LLAMA_SRCS:%.cpp=o/$(MODE)/%.o)\n\n# ... rest of build rules\n```\n\n## Submodule Management\n\n### Resetting a Single Submodule\n\nTo discard changes in one submodule:\n\n```sh\ncd llama.cpp\ngit reset --hard\ngit clean -fdx\n```\n\nThen reapply patches:\n\n```sh\ncd ..\nmake setup\n```\n\n### Resetting All Submodules\n\nTo reset everything (warning: loses all local changes):\n\n```sh\nmake reset-repo\nmake setup\n```\n\n\n## Git Workflow\n\n### Committing Changes\n\nFor core code changes:\n```sh\ngit add llamafile/modified-file.c\ngit commit -m \"Fix: description\"\n```\n\nFor submodule patches:\n```sh\ngit add llama.cpp.patches/patches/new-patch.patch\ngit commit -m \"llama.cpp: Add feature X\"\n```\n\n### Pull Request Checklist\n\nBefore submitting changes:\n\n1. [ ] Patches apply cleanly from fresh clone\n2. [ ] Build succeeds: `llamafile:build`\n3. [ ] Tests pass: `llamafile:check`\n4. [ ] Patches are focused and documented\n5. [ ] BUILD.mk updated if adding new files\n\n## Debugging Tips\n\n### Viewing Applied Patches\n\nTo see what patches are currently applied:\n\n```sh\ncd llama.cpp\ngit log --oneline HEAD...$(git rev-parse --short @{u} 2>/dev/null || echo \"origin/master\")\n```\n\n### Checking Submodule State\n\n```sh\ngit submodule status\n```\n\nOutput shows:\n- `-` : Not initialized\n- `+` : Different commit than recorded\n- ` ` : Clean, matches recorded commit\n\n### Finding Which Patch Changed a File\n\n```sh\ngrep -l \"filename\" llama.cpp.patches/patches/*.patch\n```\n","docs/skills/llamafile/architecture.md":"# Llamafile Architecture\n\nRepository structure and component overview.\n\n## Project Overview\n\nLlamafile creates single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation. It achieves this by:\n\n1. Combining multiple inference engines (llama.cpp, whisper.cpp, stable-diffusion.cpp)\n2. Using Cosmopolitan Libc for cross-platform portability\n3. Bundling models and assets into Actually Portable Executables (APE)\n\n## Repository Structure\n\n```\nllamafile/\n├── llamafile/              # Core library\n│   ├── server/             # HTTP server implementation\n│   └── highlight/          # Syntax highlighting\n├── llama.cpp/              # LLM inference (submodule)\n│   ├── ggml/               # Low-level tensor ops\n│   ├── src/                # Model implementations\n│   ├── common/             # Utilities\n│   └── tools/              # CLI applications\n├── whisper.cpp/            # Speech-to-text (submodule)\n├── stable-diffusion.cpp/   # Image generation (submodule)\n├── localscore/             # Benchmarking tool\n├── third_party/            # External dependencies\n├── build/                  # Build system\n├── docs/                   # User documentation\n├── *.patches/              # Patch directories\n└── o/                      # Build outputs\n```\n\n## Core Components\n\n### llamafile/ - Core Library\n\nThe heart of llamafile, containing:\n\n- **tinyblas**: BLAS kernels for CUDA support without cublas and optimized CPU inference\n- **GPU support**: Metal, CUDA and ROCm integration (dynamic loading)\n- **Multiplatform optimizations**: CPU feature detection, runtime dispatch\n- **TUI**: Chat interface running in the terminal\n\n#### llamafile/highlight/\n\nSyntax highlighting for code output in chat responses.\n\n### llama.cpp/ - LLM Inference Engine\n\nGit submodule providing:\n\n- **ggml/**: Low-level tensor library\n  - Matrix operations\n  - Quantization support\n  - Backend abstraction (CPU, CUDA, Metal, etc.)\n\n- **src/**: LLM implementations\n  - 100+ model architectures\n  - GGUF format handling\n  - KV cache management\n\n- **common/**: Shared utilities\n  - Argument parsing\n  - Sampling algorithms\n  - Chat templates\n\n- **tools/**: CLI applications\n  - main (inference)\n  - quantize (model quantization)\n  - imatrix (importance matrix)\n  - perplexity (model evaluation)\n  - llama-bench (benchmarking)\n\n### whisper.cpp/ - Speech-to-Text\n\nGit submodule for audio transcription:\n- Whisper model implementation\n- Audio processing utilities\n- Multiple model sizes (tiny to large)\n\n### stable-diffusion.cpp/ - Image Generation\n\nGit submodule for image synthesis:\n- Stable Diffusion implementation\n- Image encoding/decoding\n- Various SD model support\n\n### third_party/ - Dependencies\n\nExternal libraries:\n- **double-conversion**: Float-to-string conversion\n- **mbedtls**: TLS/SSL support\n- **sqlite**: Database support\n- **stb**: Image loading/saving\n- **zipalign**: Tool to bundle llamafile executables with model weights and configurations\n\n## Patch System\n\nEach submodule has a corresponding patches directory:\n\n```\nllama.cpp.patches/\n├── patches/           # .patch files modifying upstream\n└── llamafile-files/   # New files for integration\n\nwhisper.cpp.patches/\n├── patches/\n└── llamafile-files/\n\nstable-diffusion.cpp.patches/\n├── patches/\n└── llamafile-files/\n```\n\n### Patch Types\n\n1. **Modifications** (`.patch` files):\n   - Changes to existing upstream code\n   - Applied with `git apply`\n   - Track upstream file changes\n\n2. **Additions** (`llamafile-files/`):\n   - New files for llamafile integration\n   - Example: BUILD.mk for each submodule\n   - Utility scripts\n   - Additional documentation\n\n3. **Deletions**:\n   - Removal of upstream build systems (CMakeLists.txt, Makefiles)\n   - Replaced by llamafile's unified build\n   - NOTE: deletions were common in the original llamafile but are no longer used,\nas submodule code is pulled rather than redistributed\n\n### Patch Application\n\n`make setup` applies patches:\n1. Initialize/update git submodules\n2. Apply each .patch file in order\n3. Copy llamafile-files/ contents into submodule\n4. Remove conflicting build files\n\nFinally, if cosmocc is not present, it is automatically downloaded at the end of `make setup`.\n\n## Build Infrastructure\n\n### build/ Directory\n\n```\nbuild/\n├── config.mk              # Toolchain configuration\n├── rules.mk               # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download\n├── llamafile-convert      # Model conversion\n└── llamafile-upgrade-engine   # Engine updates\n```\n\n### BUILD.mk Pattern\n\nEach component has a BUILD.mk defining:\n\n```makefile\n# Source files\nCOMPONENT_SRCS = \\\n    component/file1.c \\\n    component/file2.c\n\n# Object files\nCOMPONENT_OBJS = $(COMPONENT_SRCS:%.c=o/$(MODE)/%.o)\n\n# Library target\no/$(MODE)/component/libcomponent.a: $(COMPONENT_OBJS)\n\n# Executable target\no/$(MODE)/component/binary: o/$(MODE)/component/libcomponent.a\n\n# Test targets\no/$(MODE)/component/test.runs: o/$(MODE)/component/test\n```\n\n### Output Organization\n\n```\no/$(MODE)/\n├── package/\n│   ├── file.o         # Object files\n│   ├── libpackage.a   # Static libraries\n│   └── binary         # Executables\n└── ...\n```\n\n## Key Technologies\n\n### Actually Portable Executable (APE)\n\nCosmopolitan's executable format:\n- Single file runs on Windows, macOS, Linux, BSD\n- Contains x86_64 and aarch64 code\n- Self-extracting when needed\n- No installation required\n\n### Asset Bundling\n\nFiles embedded into executables:\n- Models (.gguf)\n- Web assets (HTML, CSS, JS)\n- Shared libraries (.so, .dll)\n\nThe `zipalign` tool handles bundling, and files are accessible via Cosmopolitan's VFS.\n\n### Runtime CPU Dispatch\n\nBinaries detect CPU features and select optimal code:\n- x86_64: SSE, AVX, AVX2, AVX-512, FMA\n- aarch64: NEON, SVE\n\nThis happens transparently at runtime, no user configuration needed.\n\n### Dynamic GPU Loading\n\nGPU support loads at runtime:\n- CUDA: Loads from system or bundled .so/.dll\n- ROCm: Similar dynamic loading\n- Fallback to CPU if GPU unavailable\n\n## Licensing\n\n- **Llamafile project**: Apache 2.0\n- **Llamafile changes to llama.cpp**: MIT (upstream compatibility)\n- **Dependencies**: Retain original licenses\n","docs/skills/llamafile/building.md":"# Building Llamafile\n\nComplete guide to the llamafile build system and toolchain.\n\n## Prerequisites\n\n### Cosmopolitan Toolchain\n\nLlamafile uses Cosmopolitan C/C++ compiler (cosmocc) to create Actually Portable Executables (APE). The toolchain \nis downloaded automatically when `make setup` is called but can be fetched manually too with:\n\n```sh\nbuild/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\n```\n\nArguments:\n1. Destination directory (`.cosmocc/4.0.2`)\n2. Version (`4.0.2`)\n3. SHA256 checksum for verification\n\n### Git Submodules\n\nThree main dependencies are git submodules:\n- llama.cpp - LLM inference engine\n- whisper.cpp - Speech-to-text engine\n- stable-diffusion.cpp - Image generation engine\n\n## Initial Setup\n\nBefore first build, initialize and configure dependencies:\n\n```sh\nmake setup\n```\n\nThis command:\n1. Initializes git submodules (clones if needed)\n2. Applies llamafile-specific patches from `<submodule>.patches/` directories\n3. Modifies submodules in-place for llamafile integration\n\n**Important:** Run `make setup` after:\n- Fresh clone\n- Updating submodules\n- Pulling changes that modify patch files\n\n## Build Commands\n\n### Full Build\n\n```sh\n.cosmocc/4.0.2/bin/make -j $(nproc)  # or: llamafile:build\n```\n\nThe `-j $(nproc)` flag enables parallel compilation (adjust based on CPU cores).\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\n**Critical:** Always use `.cosmocc/4.0.2/bin/make`, not system make. The cosmocc toolchain includes its own make with Cosmopolitan-specific behavior. The only exceptions are `make setup` and `make reset-repo`, which use bare `make` — `setup` bootstraps cosmocc on a fresh clone, and both are exempt from the version check.\n\n### Clean Build\n\nRemove build outputs:\n\n```sh\n.cosmocc/4.0.2/bin/make clean  # or: llamafile:clean\n```\n\nThis removes the `o/` directory containing all compiled objects and binaries.\n\n### Install compiled binaries\n\n```sh\nsudo .cosmocc/4.0.2/bin/make install PREFIX=/usr/local\n```\n\nInstalls binaries and man pages.\n\n## Build System Architecture\n\n### Directory Structure\n\n```\nbuild/\n├── config.mk          # Compiler, flags, toolchain version\n├── rules.mk           # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download script\n├── llamafile-convert      # Model conversion script\n└── llamafile-upgrade-engine   # Engine update script\n```\n\n### Configuration (build/config.mk)\n\nDefines:\n- Compiler paths (CC, CXX pointing to cosmocc)\n- Compiler flags (optimization, warnings)\n- Toolchain version\n- Platform-specific settings\n\n### Build Rules (build/rules.mk)\n\nGeneric patterns for:\n- `.c` → `.o` compilation\n- `.a` archive creation\n- `.zip.o` asset bundling (embed files into executables)\n\n### BUILD.mk Files\n\nEach major component has a BUILD.mk file defining:\n- Source files to compile\n- Dependencies\n- Build targets\n- Test targets\n\nThe top-level Makefile includes all BUILD.mk files to orchestrate the build.\n\n## Build Outputs\n\nAll outputs go to `o/$(MODE)/`:\n\n```\no/\n└── $(MODE)/\n    ├── llamafile/\n    │   ├── llamafile          # Main executable\n    │   ├── *.o                # Object files\n    │   └── *.a                # Static libraries\n    ├── llama.cpp/\n    ├── whisper.cpp/\n    ├── stable-diffusion.cpp/\n    └── third_party/\n        └── zipalign/\n            └── zipalign       # Asset bundling tool\n```\n\n## Multi-Architecture Support\n\nThe build system creates universal binaries supporting:\n- x86_64 (Intel/AMD)\n- aarch64 (ARM64)\n\nBoth architectures are compiled simultaneously and combined into single APE binaries.\n\n### Runtime Dispatch\n\nBinaries detect CPU features at runtime and select optimal code paths:\n- AVX, AVX2, AVX-512 (x86_64)\n- ARM NEON (aarch64)\n\n## Asset Bundling\n\nFiles can be embedded into executables using the `.zip.o` pattern:\n\n```makefile\no/$(MODE)/path/to/asset.zip.o: path/to/asset\n```\n\nThe `zipalign` tool handles bundling. Embedded assets are accessible at runtime through the Cosmopolitan virtual filesystem.\n\n## GPU Support\n\nGPU acceleration (CUDA/ROCm/Vulkan) uses dynamic loading:\n- Shared libraries (.so/.dll) are not linked at compile time\n- Libraries are loaded at runtime if available\n- Can be bundled into executables using zipalign\n\n### Building the GPU dylibs\n\nThe host `make` does **not** build the GPU backends. They are separate,\nprebuilt shared libraries produced by per-backend scripts in `llamafile/`:\n\n- `llamafile/cuda.sh`   → `ggml-cuda.so`   (needs `nvcc`; `CUDA_PATH`, default `/usr/local/cuda`)\n- `llamafile/rocm.sh`   → `ggml-rocm.so`   (needs `hipcc`; `ROCM_PATH`, default `/opt/rocm`)\n- `llamafile/vulkan.sh` → `ggml-vulkan.so` (needs `glslc` + SPIR-V headers + libvulkan)\n- `.bat` / `*_parallel.bat` variants build the Windows DLLs.\n\n`make_dylibs.sh` (if present) just wraps these for a release (writes to a\nversioned `gpulibs/<VERSION>/`, passes `--clean`, and `--minimize-size` for\nCUDA). **Run the scripts one at a time**, always with `--clean` — a stale\n`~/.cache/llamafile-{cuda,rocm,vulkan}-build` is the usual \"first build fails\"\ncause (leftover objects that reference symbols upstream removed, e.g. the b10052\nCUDA split-buffer removal). `cuda.sh`/`rocm.sh` share `build-functions.sh`;\n`vulkan.sh` is standalone.\n\n### Verifying a GPU build actually succeeded (do not trust \"Successfully built\")\n\nThe parallel compile launches each `nvcc`/`hipcc`/`glslc` in the background.\n`compile_gpu_sources_parallel` (cuda/rocm) now reaps each job and fails loudly,\nbut `vulkan.sh`'s shader loops do **not** yet check per-job status — a single\nfailed source can still be dropped while the link proceeds and prints\n\"Successfully built\" with a silently incomplete `.so`. So always confirm, don't\nassume:\n\n```bash\nllamafile/cuda.sh --clean --output /tmp/ggml-cuda.so --minimize-size 2>&1 | tee /tmp/b.log\ngrep -c 'error:' /tmp/b.log          # must be 0\ngrep 'Linking'   /tmp/b.log          # object count should match the source count\n```\n\nIf a source fails to compile, fix the root cause (a new upstream cuBLAS call\nmissing from TinyBLAS is a recurring one — see `update_llamacpp.md`), never let\nthe \"success\" line stand in for a green build.\n\n### Vulkan speed paths depend on the glslc/SDK version\n\n`vulkan.sh` probes the build host's `glslc` for shader extensions\n(coopmat, coopmat2, integer-dot, bf16, fp4/fp8) — mirroring upstream's\n`ggml-vulkan/CMakeLists.txt` `test_shader_extension_support`. Each probe that\nfails drops that acceleration pipeline from the shipped dylib (correct output,\njust slower on hardware that supports it). Distro `shaderc` (Ubuntu, SteamOS)\nis typically **too old** — it doesn't know `GL_EXT_integer_dot_product`,\n`GL_EXT_bfloat16`, `GL_NV_cooperative_matrix2`, and can't target\n`--target-env=vulkan1.4`. For a full-featured release Vulkan dylib, build on a\nhost with a recent **LunarG Vulkan SDK** (1.4.x); after installing, `source`\nits `setup-env.sh` so `vulkan.sh` picks up the SDK's `glslc`, then re-run the\nbuild and confirm the probes now print \"supported\". Keep `vulkan.sh`'s probe\nlist in sync with the CMakeLists (it must probe all seven feature tests).\n\n### CUDA `--minimize-size` drops IQ-quant kernels (CPU fallback)\n\nThe release CUDA dylib is built with `--minimize-size`, which (among the size\noptions) passes `-DGGML_CUDA_NO_IQ_QUANTS`. That compiles out most IQ-quant\nCUDA paths — the MMQ/MMVQ matmul kernels in `mmq.cu`/`mmvq.cu`, the bf16/fp16\ndequant converters in `convert.cu`, and the `f32→iq4_nl` copy in `cpy.cu`\n(`ggml_get_to_fp32_cuda`'s IQ cases stay unguarded, so the `float` dequant\ninstantiations still compile — a minor size cost).\nThe payoff is a much smaller `.so`; the cost is that it cannot run IQ-quantized\ntensors on the GPU.\n\n`ggml_backend_cuda_device_supports_op` is guarded by the same macro: the IQ\ncases in the `MUL_MAT`/`MUL_MAT_ID` and `CPY` switches sit inside\n`#ifndef GGML_CUDA_NO_IQ_QUANTS`. So a minimized build honestly reports those\nops unsupported and the scheduler runs them on the CPU backend — correct\noutput, just slower for the IQ layers. **Without that guard the op is\ndispatched to a kernel that was never compiled and aborts at\n`GGML_ASSERT(convert_func != nullptr)` (`ggml-cuda.cu`)** — this is exactly\nwhat `backend_ops_test` hit on `iq2_xxs` MUL_MAT. If you add or bump IQ\nhandling, keep the `supports_op` cases and their kernels behind the same macro\nor the mismatch reappears. (ROCm shares `ggml-cuda.cu`, but its build does not\ndefine the macro, so IQ stays enabled there.)\n\nFor a CUDA dylib that runs IQ quants on the GPU, build without the flag — drop\n`--minimize-size` (or use its other pieces like `--minimal-archs`/`--strip`\nwithout `--no-iq-quants`) — at the cost of a larger library. The ROCm, Vulkan,\nand Metal builds are not size-minimized, so none of them strips IQ the way the\nCUDA build does: ROCm shares this file with the macro undefined, so it keeps the\nfull IQ mul_mat set; Metal and Vulkan keep whatever IQ ops their own backends\nimplement (Vulkan's `supports_op` still declines some IQ mul_mat/cpy shapes, but\nit declines cleanly and falls back to CPU rather than crashing — which, after\nthis fix, is exactly how CUDA behaves too).\n\n## Troubleshooting\n\n### \"make: command not found\" or Wrong Make\n\nEnsure using the cosmocc make:\n\n```sh\n# Wrong\nmake -j $(nproc)\n\n# Correct\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Or use the command directly:\n# llamafile:build\n```\n\n### Submodule Not Initialized\n\nIf build fails with missing files in llama.cpp/whisper.cpp/stable-diffusion.cpp:\n\n```sh\nmake setup\n```\n\n### Stale Object Files\n\nAfter significant changes, clean and rebuild:\n\n```sh\n.cosmocc/4.0.2/bin/make clean          # or: llamafile:clean\n.cosmocc/4.0.2/bin/make -j $(nproc)   # or: llamafile:build\n```\n\n### Toolchain Checksum Mismatch\n\nIf `download-cosmocc.sh` fails verification, check:\n1. Correct version specified\n2. Correct checksum for that version\n3. Network connectivity\n","docs/skills/llamafile/testing.md":"# Llamafile Skill\n\nPath: `docs/skills/llamafile/testing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/testing.md)","docs/skills/llamafile/update_llamacpp.md":"# Llamafile Skill\n\nPath: `docs/skills/llamafile/update_llamacpp.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/update_llamacpp.md)"},"files":{".llamafile_plugin/.claude-plugin/plugin.json":"{\n  \"name\": \"llamafile\",\n  \"version\": \"0.1.7\",\n  \"description\": \"Build guidance and commands for the llamafile project\"\n}\n","docs/AGENTS.md":"# AGENTS.md\n\nThis file provides guidance to Claude Code when working with this repository.\n\n## Project Overview\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Quick Reference\n\n```sh\n# Initial setup (run once after clone)\nmake setup\n\n# Build (always use cosmocc make, not system make)\n# Adapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Run tests\n.cosmocc/4.0.2/bin/make check\n\n# Clean build outputs\n.cosmocc/4.0.2/bin/make clean\n\n# Reset all submodules (warning: removes local changes)\nmake reset-repo\n```\n\n## Key Directories\n\n| Directory | Purpose |\n|-----------|---------|\n| `llamafile/` | Core library (edit directly) |\n| `llama.cpp/` | LLM inference (submodule, edit directly then convert to patches) |\n| `whisper.cpp/` | Speech-to-text (submodule, edit directly then convert to patches) |\n| `stable-diffusion.cpp/` | Image generation (submodule, edit directly then convert to patches) |\n| `*.patches/` | Patch directories for submodules |\n| `o/` | Build outputs |\n\n## Important Notes\n\n- Always use `.cosmocc/4.0.2/bin/make`, not system make\n- Run `make setup` after cloning or updating submodules\n- Submodule changes require patch files (see skill for workflow)\n\n## Detailed Documentation\n\nFor comprehensive build, architecture, development, and testing documentation, ask Claude about \"how to build llamafile\" or \"llamafile development workflow\" to load the llamafile skill.\n","docs/commands/check.md":"---\ndescription: Run llamafile unit tests\n---\n\n# Run Llamafile Tests\n\nRun the unit test suite using the Cosmopolitan toolchain.\n\n```bash\n.cosmocc/4.0.2/bin/make check\n```\n",".llamafile_plugin/.claude-plugin/marketplace.json":"{\n  \"name\": \"llamafile-local\",\n  \"description\": \"Local llamafile plugin marketplace\",\n  \"owner\": {\n    \"name\": \"Mozilla AI\",\n    \"email\": \"davide@mozilla.ai\"\n  },\n  \"plugins\": [\n    {\n      \"name\": \"llamafile\",\n      \"description\": \"Build guidance and commands for the llamafile project\",\n      \"version\": \"0.1.7\",\n      \"author\": {\n        \"name\": \"Mozilla AI\",\n        \"email\": \"davide@mozilla.ai\"\n      },\n      \"source\": \"./\"\n    }\n  ]\n}\n","docs/commands/build.md":"---\ndescription: Build llamafile using the cosmocc toolchain\n---\n\n# Build Llamafile\n\nBuild the project using the Cosmopolitan toolchain.\n\nFirst, ensure the toolchain is available:\n\n```bash\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\n```\n\nThen build:\n\n```bash\n.cosmocc/4.0.2/bin/make -j $(nproc)\n```\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\nBuild outputs will be in `o/$(MODE)/`.\n","docs/skills/llamafile/SKILL.md":"---\nname: llamafile\ndescription: This skill should be used when the user asks to \"build llamafile\", \"rebuild llamafile\", \"run llamafile\", \"run llamafile tests\", \"debug llamafile\", \"set up llamafile\", \"update patches\", \"fix patch conflict\", \"update llama.cpp\", \"pull latest llama.cpp\", \"sync upstream llama.cpp\", \"reset submodules\", \"write a test for llamafile\", \"how does llamafile work\", \"llamafile architecture\", or needs guidance on the llamafile build system, patch workflow, submodule integration, cosmocc toolchain, or development practices.\nversion: 0.1.6\n---\n\n# Llamafile Development Guide\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Version Disambiguation\n\n- **New llamafile** (or simply \"llamafile\"): The code in the `main` branch, used for releases >=0.10.0\n- **Old/Classic llamafile**: The legacy code, used for releases until 0.9.3 (see commit 7e7d33c).\n\nThis guide covers the **new llamafile** project.\n\n## Quick Reference\n\n### Initial Setup\n\n```sh\nmake setup\n```\n\nImmediately after cloning the repo (or after a reset done with `make reset-repo`), this command initializes git submodules and applies llamafile-specific patches.\n\n### Building\n\nRun `llamafile:build` to build all targets.\n\n### Testing\n\nRun `llamafile:check` to run the unit test suite.\n\n### Cleaning\n\nRun `llamafile:clean` to remove all build outputs.\n\n### Reset Submodules\n\nAfter `make setup`, submodules contain patches and are no longer in a clean state.\nTo reset them, run:\n\n```sh\nmake reset-repo  # Warning: removes all local changes\n```\n\nWARNING: this command removes all local changes. Do not run it without first generating patches from any modifications.\n\n### Patch & Upstream-Update Commands\n\nWhen changing submodule patches or bumping llama.cpp, use the dedicated commands\nrather than ad-hoc `git diff`/`git apply`:\n\n- `llamafile:generate-patches` — regenerate patches from in-place submodule edits\n  (the only sanctioned way to produce patches).\n- `llamafile:verify-clean` — clean round-trip (`reset-repo` → `setup` → clean\n  build → `check`); the verification after generating patches or any patch change.\n\nFor the full llama.cpp bump procedure, follow `update_llamacpp.md` step by step.\n\n\n## Core Workflows\n\n### Building from Scratch\n\nTo build llamafile from a fresh clone:\n\n1. Clone the repository\n2. Run `make setup` to initialize submodules and apply patches\n3. Build with `llamafile:build`\n\nBuild outputs appear in `o/$(MODE)/` directory.\n\n### Modifying Core Code\n\nFor changes to llamafile's own code (not submodules):\n\n1. Edit files in `llamafile/` directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\n### Modifying Submodule Code\n\nSubmodules (llama.cpp, whisper.cpp, stable-diffusion.cpp) require a patch-based workflow:\n\n1. Make changes directly in the submodule directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\nNOTE: never try to edit patches or generate them manually. This step is \ndone only after rebuild and tests (even manual ones) are successful. See\n`development.md` for detailed patch workflow.\n\n### Running Specific Tests\n\nTests use the `.runs` pattern in BUILD.mk files:\n\n```makefile\no/$(MODE)/llamafile/json_test.runs\n```\n\nTo run all tests: `llamafile:check`\n\n## Key Concepts\n\n### Cosmopolitan Toolchain\n\nThe project uses Cosmopolitan Libc (cosmocc) to create Actually Portable Executables (APE) - single files that run on multiple platforms without modification. Always use the `llamafile:build`, `llamafile:check`, and `llamafile:clean` commands (which use cosmocc's make), not system make.\n\n### Patch System\n\nEach submodule has a corresponding patches directory:\n- `llama.cpp.patches/`\n- `whisper.cpp.patches/`\n- `stable-diffusion.cpp.patches/`\n\nPatches include:\n- **Modifications** (.patch files): Changes to upstream code\n- **Additions** (llamafile-files/): New files for integration (BUILD.mk, utilities)\n\n### Build System\n\n- **build/config.mk**: Compiler and toolchain configuration\n- **build/rules.mk**: Generic build patterns (.c → .o, archives, asset bundling)\n- **BUILD.mk files**: Per-package build logic\n\nOutputs: `o/$(MODE)/package/file.o`\n\n### Multi-Architecture Support\n\nBinaries include both x86_64 and aarch64 code paths with runtime CPU feature detection (AVX, AVX2, AVX-512, ARM NEON).\n\n### GPU Backend Loaders\n\nDynamically-loaded backends that export the ggml C ABI — CUDA, ROCm, Vulkan — all go through the shared probe core in `llamafile/gpu_backend.c`. Each is just a `GpuBackendDesc` + a link thunk; the core does load → log-suppress → **device-count gate** (reject 0-device DSOs so AUTO falls back) → register, with a SIGSEGV/SIGABRT crash guard around the foreign probe call (driver init can fault across the cosmo/ms_abi boundary — issue #988). Metal stays separate by design (runtime-compiled, no ms_abi split, no device gate). When adding/changing a backend: route it through the core, keep the gate, and add a case to `tests/gpu_backend_test.cpp`. A more detailed design doc lives separately.\n\n## Main Executables\n\nAfter building, find binaries in `o/$(MODE)/`:\n\n| Binary | Purpose |\n|--------|---------|\n| `llamafile/llamafile` | Main llamafile executable |\n| `third_party/zipalign/zipalign` | Bundle assets into executables |\n| `whisperfile/whisperfile` | Main whisperfile executable |\n\n## Troubleshooting\n\n### Build Fails After Submodule Update\n\nRun `make setup` to reapply patches after any submodule changes.\n\n### Submodule Has Uncommitted Changes\n\nTo reset a single submodule:\n```sh\ncd <submodule> && git reset --hard && git clean -fdx\n```\n\nTo reset all submodules:\n```sh\nmake reset-repo\n```\n\n### Wrong Make Being Used\n\nEnsure using the `llamafile:build` command (which uses cosmocc's make), not system make.\n\n## Additional Resources\n\n### Reference Files\n\nFor detailed information, consult:\n- **`building.md`** - Complete build system documentation, toolchain details\n- **`architecture.md`** - Repository structure, component overview\n- **`development.md`** - Development workflow, patch management, submodule integration\n- **`testing.md`** - Test patterns, running and writing tests\n- **`update_llamacpp.md`** - Keeping llamafile updated with upstream llama.cpp\n\n### Project Documentation\n\n- **README.md** in repo: Project introduction\n- **docs/** directory: User documentation (quickstart, installation, troubleshooting)\n- **RELEASE.md**: Release process\n- Most executables support `--help`\n","docs/commands/generate-patches.md":"---\ndescription: Regenerate llamafile patches from in-place submodule edits\n---\n\n# Generate Patches\n\nCapture the current in-place edits of a submodule as patch files, using the\nproject's `generate_patches.sh` tool. This is the **only** sanctioned way to\nproduce patches — never hand-craft them with `git diff` (the tool rewrites the\n`a/`,`b/` paths to be repo-rooted, strips the volatile `index` line, names files\nby convention, and routes new/untracked files into `llamafile-files/`; a raw\n`git diff` gets all of that wrong).\n\nRun it for the `llama.cpp` submodule (the common case). The tool is general and\nworks for any submodule — swap the directory and output path for `whisper.cpp`\nor `stable-diffusion.cpp`.\n\nThe subshell keeps the working directory restored even if the tool fails, and\n`echo y` answers the script's confirmation prompt non-interactively:\n\n```bash\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nOutput lands in `llama.cpp.patches/patches/` (modified files) and\n`llama.cpp.patches/llamafile-files/` (new files, including `BUILD.mk`).\n\nThe tool **only writes/overwrites — it never deletes**. If you dropped a patch\nduring a bump (the file is no longer modified, e.g. upstream absorbed the\nchange), its old `.patch` will still be sitting in `patches/` and will keep\nbeing applied by `setup`. `git rm` each dropped patch by hand, and confirm the\nfinal count (`ls llama.cpp.patches/patches | wc -l`) matches your intent.\n\nIMPORTANT: only run this **after** the in-place edits are proven to work\n(a clean build succeeds and llamafile runs as expected). Generating patches\nfrom unproven edits bakes in breakage. After generating, verify the patch set\nround-trips with `llamafile:verify-clean`.\n","docs/commands/clean.md":"---\ndescription: Clean llamafile build outputs\n---\n\n# Clean Llamafile Build\n\nRemove all build outputs from the `o/` directory.\n\n```bash\n.cosmocc/4.0.2/bin/make clean\n```\n","docs/commands/verify-clean.md":"---\ndescription: Clean round-trip — reset, re-apply patches, clean build, and test\n---\n\n# Verify Clean\n\nVerify the repository from a clean slate: reset, re-pull submodules and\nre-apply patches, then do a **clean** build and run the tests. Use this:\n\n- as the final verification after `llamafile:generate-patches` (confirms the\n  regenerated patches re-apply cleanly and still build), and\n- any time patches or submodules change and you need a trustworthy result.\n\nWhy a clean build: after a `reset-repo`/`setup`, submodule sources change\nwithout their timestamps necessarily moving, so an incremental `make` can link\nstale objects. Always `make clean` first here — do not rebuild incrementally.\n\n`make setup` both pulls submodules and applies patches, and it cannot pull\nsubmodules onto a dirty tree — that is exactly why `reset-repo` runs first.\n\nNote: `reset-repo` is destructive (it `rm -rf`s the submodule dirs before\nrestoring them), so a permission-gated environment may prompt or block it. Run\nit through the `$MAKE` (`.cosmocc/.../make`) form below rather than raw\n`git clean`/`reset`; allowlist `make reset-repo` if round-trips keep stalling.\n\n```bash\n# ensure the toolchain is available\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\nMAKE=.cosmocc/4.0.2/bin/make\n\n$MAKE reset-repo     # clean: drop all local changes, reset submodules\n$MAKE setup          # pull submodules + apply patches (+ fetch UI assets)\n$MAKE clean          # drop stale build outputs\n$MAKE -j$(nproc)     # clean build; on mac use -j$(sysctl -n hw.physicalcpu)\n$MAKE check          # unit tests\n```\n\nA successful round-trip proves the committed patch set is internally\nconsistent. It does NOT cover GPU runtime backends, non-host platforms, the\nweb UI, or long-run stability — see the handoff checklist in\n`update_llamacpp.md`.\n","docs/skills/llamafile/development.md":"# Llamafile Development Workflow\n\nGuide to modifying code, managing patches, and working with submodules.\n\n## Development Overview\n\nLlamafile development involves two distinct workflows:\n\n1. **Core code changes**: Direct edits to root-level directories such as `llamafile/`, `whisperfile/`, etc.\n2. **Submodule changes**: Patch-based modifications to `llama.cpp`, `whisper.cpp`, `stable-diffusion.cpp`\n\n## Modifying Core Code\n\nFor changes which are not affecting submodules:\n\n### Workflow\n\n1. Edit files\n2. Rebuild: `llamafile:build`\n3. Test: `llamafile:check`\n4. Commit changes normally with git\n\n### Key Directories\n\n```\nllamafile/\n├── server/      # HTTP server, API endpoints\n├── highlight/   # Syntax highlighting\n├── tinyblas/    # Optimized BLAS kernels\n└── *.c, *.h     # Core utilities\n```\n\n## Modifying Submodule Code\n\nSubmodules require a patch-based workflow because:\n- Submodules point to specific upstream commits\n- Direct commits in submodules would be lost\n- Patches preserve modifications across submodule updates\n\n### Understanding the Patch System\n\nEach submodule has a patches directory. For instance, for `llama.cpp`:\n\n```\nllama.cpp.patches/\n├── README.md              # Patching info + list of all patches and their purpose\n├── apply-patches.sh       # Script to apply all patches to llama.cpp submodule\n├── renames.sh             # Script for file renames/moves (if any)\n├── llamafile-files/       # Additional files to copy into llama.cpp\n│   ├── BUILD.mk           # Makefile for building llama.cpp with cosmocc\n│   └── README.llamafile   # License and modification notes\n└── patches/               # Patch files for upstream sources\n```\n\nPatches are applied by `make setup`:\n1. Submodule is reset to clean state\n2. Each .patch file is applied in alphabetical order\n3. Files from llamafile-files/ are copied into the submodule\n\n### Making Changes to a Submodule\n\n#### Step 1: Make Changes\n\nEdit files directly in the submodule directory:\n\n```sh\ncd llama.cpp\n# Make your changes\nvim src/llama.cpp\n```\n\n#### Step 2: Generate Patches\n\nPatches are usually generated after the code has been thoroughly tested and is\nready to commit. To avoid manual errors, use the script `tools/generate_patches.sh`\n(or the `llamafile:generate-patches` skill that wraps it), which automatically\nsaves all new files and patches in the specified output directory.\n\n```sh\n# echo y answers the prompt; the subshell restores the cwd even on failure\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nAfter this operation, one can double check which files have been modified / added\nvia a `git diff`.\n\nNaming convention:\n- all patches have a `.patch` extension\n- patch filenames reflect the file path with underscores replacing slashes (e.g., `common_arg.cpp.patch` for `common/arg.cpp`).\n\n\n#### Step 3: Verify Patches\n\nOnce you are sure all patches have been saved, reset and reapply to verify:\n\n```sh\n# Reset everything\nmake reset-repo\n\n# Reapply patches\nmake setup\n\n# Rebuild and test\n# llamafile:build\n# llamafile:check\n```\n\n### Adding New Files to Submodules\n\nFor new files (not modifications), use llamafile-files/:\n\n```sh\n# Create directory structure matching submodule\nmkdir -p llama.cpp.patches/llamafile-files/src/\n\n# Add your new file\ncp new-utility.cpp llama.cpp.patches/llamafile-files/src/\n```\n\nThe file will be copied into the submodule during `make setup`.\n\n### Updating BUILD.mk for Submodules\n\nEach submodule needs a BUILD.mk in llamafile-files/:\n\n```makefile\n# llama.cpp.patches/llamafile-files/BUILD.mk\n\nLLAMA_SRCS = \\\n    llama.cpp/src/llama.cpp \\\n    llama.cpp/src/new-file.cpp    # Add new files here\n\nLLAMA_OBJS = $(LLAMA_SRCS:%.cpp=o/$(MODE)/%.o)\n\n# ... rest of build rules\n```\n\n## Submodule Management\n\n### Resetting a Single Submodule\n\nTo discard changes in one submodule:\n\n```sh\ncd llama.cpp\ngit reset --hard\ngit clean -fdx\n```\n\nThen reapply patches:\n\n```sh\ncd ..\nmake setup\n```\n\n### Resetting All Submodules\n\nTo reset everything (warning: loses all local changes):\n\n```sh\nmake reset-repo\nmake setup\n```\n\n\n## Git Workflow\n\n### Committing Changes\n\nFor core code changes:\n```sh\ngit add llamafile/modified-file.c\ngit commit -m \"Fix: description\"\n```\n\nFor submodule patches:\n```sh\ngit add llama.cpp.patches/patches/new-patch.patch\ngit commit -m \"llama.cpp: Add feature X\"\n```\n\n### Pull Request Checklist\n\nBefore submitting changes:\n\n1. [ ] Patches apply cleanly from fresh clone\n2. [ ] Build succeeds: `llamafile:build`\n3. [ ] Tests pass: `llamafile:check`\n4. [ ] Patches are focused and documented\n5. [ ] BUILD.mk updated if adding new files\n\n## Debugging Tips\n\n### Viewing Applied Patches\n\nTo see what patches are currently applied:\n\n```sh\ncd llama.cpp\ngit log --oneline HEAD...$(git rev-parse --short @{u} 2>/dev/null || echo \"origin/master\")\n```\n\n### Checking Submodule State\n\n```sh\ngit submodule status\n```\n\nOutput shows:\n- `-` : Not initialized\n- `+` : Different commit than recorded\n- ` ` : Clean, matches recorded commit\n\n### Finding Which Patch Changed a File\n\n```sh\ngrep -l \"filename\" llama.cpp.patches/patches/*.patch\n```\n","docs/skills/llamafile/architecture.md":"# Llamafile Architecture\n\nRepository structure and component overview.\n\n## Project Overview\n\nLlamafile creates single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation. It achieves this by:\n\n1. Combining multiple inference engines (llama.cpp, whisper.cpp, stable-diffusion.cpp)\n2. Using Cosmopolitan Libc for cross-platform portability\n3. Bundling models and assets into Actually Portable Executables (APE)\n\n## Repository Structure\n\n```\nllamafile/\n├── llamafile/              # Core library\n│   ├── server/             # HTTP server implementation\n│   └── highlight/          # Syntax highlighting\n├── llama.cpp/              # LLM inference (submodule)\n│   ├── ggml/               # Low-level tensor ops\n│   ├── src/                # Model implementations\n│   ├── common/             # Utilities\n│   └── tools/              # CLI applications\n├── whisper.cpp/            # Speech-to-text (submodule)\n├── stable-diffusion.cpp/   # Image generation (submodule)\n├── localscore/             # Benchmarking tool\n├── third_party/            # External dependencies\n├── build/                  # Build system\n├── docs/                   # User documentation\n├── *.patches/              # Patch directories\n└── o/                      # Build outputs\n```\n\n## Core Components\n\n### llamafile/ - Core Library\n\nThe heart of llamafile, containing:\n\n- **tinyblas**: BLAS kernels for CUDA support without cublas and optimized CPU inference\n- **GPU support**: Metal, CUDA and ROCm integration (dynamic loading)\n- **Multiplatform optimizations**: CPU feature detection, runtime dispatch\n- **TUI**: Chat interface running in the terminal\n\n#### llamafile/highlight/\n\nSyntax highlighting for code output in chat responses.\n\n### llama.cpp/ - LLM Inference Engine\n\nGit submodule providing:\n\n- **ggml/**: Low-level tensor library\n  - Matrix operations\n  - Quantization support\n  - Backend abstraction (CPU, CUDA, Metal, etc.)\n\n- **src/**: LLM implementations\n  - 100+ model architectures\n  - GGUF format handling\n  - KV cache management\n\n- **common/**: Shared utilities\n  - Argument parsing\n  - Sampling algorithms\n  - Chat templates\n\n- **tools/**: CLI applications\n  - main (inference)\n  - quantize (model quantization)\n  - imatrix (importance matrix)\n  - perplexity (model evaluation)\n  - llama-bench (benchmarking)\n\n### whisper.cpp/ - Speech-to-Text\n\nGit submodule for audio transcription:\n- Whisper model implementation\n- Audio processing utilities\n- Multiple model sizes (tiny to large)\n\n### stable-diffusion.cpp/ - Image Generation\n\nGit submodule for image synthesis:\n- Stable Diffusion implementation\n- Image encoding/decoding\n- Various SD model support\n\n### third_party/ - Dependencies\n\nExternal libraries:\n- **double-conversion**: Float-to-string conversion\n- **mbedtls**: TLS/SSL support\n- **sqlite**: Database support\n- **stb**: Image loading/saving\n- **zipalign**: Tool to bundle llamafile executables with model weights and configurations\n\n## Patch System\n\nEach submodule has a corresponding patches directory:\n\n```\nllama.cpp.patches/\n├── patches/           # .patch files modifying upstream\n└── llamafile-files/   # New files for integration\n\nwhisper.cpp.patches/\n├── patches/\n└── llamafile-files/\n\nstable-diffusion.cpp.patches/\n├── patches/\n└── llamafile-files/\n```\n\n### Patch Types\n\n1. **Modifications** (`.patch` files):\n   - Changes to existing upstream code\n   - Applied with `git apply`\n   - Track upstream file changes\n\n2. **Additions** (`llamafile-files/`):\n   - New files for llamafile integration\n   - Example: BUILD.mk for each submodule\n   - Utility scripts\n   - Additional documentation\n\n3. **Deletions**:\n   - Removal of upstream build systems (CMakeLists.txt, Makefiles)\n   - Replaced by llamafile's unified build\n   - NOTE: deletions were common in the original llamafile but are no longer used,\nas submodule code is pulled rather than redistributed\n\n### Patch Application\n\n`make setup` applies patches:\n1. Initialize/update git submodules\n2. Apply each .patch file in order\n3. Copy llamafile-files/ contents into submodule\n4. Remove conflicting build files\n\nFinally, if cosmocc is not present, it is automatically downloaded at the end of `make setup`.\n\n## Build Infrastructure\n\n### build/ Directory\n\n```\nbuild/\n├── config.mk              # Toolchain configuration\n├── rules.mk               # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download\n├── llamafile-convert      # Model conversion\n└── llamafile-upgrade-engine   # Engine updates\n```\n\n### BUILD.mk Pattern\n\nEach component has a BUILD.mk defining:\n\n```makefile\n# Source files\nCOMPONENT_SRCS = \\\n    component/file1.c \\\n    component/file2.c\n\n# Object files\nCOMPONENT_OBJS = $(COMPONENT_SRCS:%.c=o/$(MODE)/%.o)\n\n# Library target\no/$(MODE)/component/libcomponent.a: $(COMPONENT_OBJS)\n\n# Executable target\no/$(MODE)/component/binary: o/$(MODE)/component/libcomponent.a\n\n# Test targets\no/$(MODE)/component/test.runs: o/$(MODE)/component/test\n```\n\n### Output Organization\n\n```\no/$(MODE)/\n├── package/\n│   ├── file.o         # Object files\n│   ├── libpackage.a   # Static libraries\n│   └── binary         # Executables\n└── ...\n```\n\n## Key Technologies\n\n### Actually Portable Executable (APE)\n\nCosmopolitan's executable format:\n- Single file runs on Windows, macOS, Linux, BSD\n- Contains x86_64 and aarch64 code\n- Self-extracting when needed\n- No installation required\n\n### Asset Bundling\n\nFiles embedded into executables:\n- Models (.gguf)\n- Web assets (HTML, CSS, JS)\n- Shared libraries (.so, .dll)\n\nThe `zipalign` tool handles bundling, and files are accessible via Cosmopolitan's VFS.\n\n### Runtime CPU Dispatch\n\nBinaries detect CPU features and select optimal code:\n- x86_64: SSE, AVX, AVX2, AVX-512, FMA\n- aarch64: NEON, SVE\n\nThis happens transparently at runtime, no user configuration needed.\n\n### Dynamic GPU Loading\n\nGPU support loads at runtime:\n- CUDA: Loads from system or bundled .so/.dll\n- ROCm: Similar dynamic loading\n- Fallback to CPU if GPU unavailable\n\n## Licensing\n\n- **Llamafile project**: Apache 2.0\n- **Llamafile changes to llama.cpp**: MIT (upstream compatibility)\n- **Dependencies**: Retain original licenses\n","docs/skills/llamafile/building.md":"# Building Llamafile\n\nComplete guide to the llamafile build system and toolchain.\n\n## Prerequisites\n\n### Cosmopolitan Toolchain\n\nLlamafile uses Cosmopolitan C/C++ compiler (cosmocc) to create Actually Portable Executables (APE). The toolchain \nis downloaded automatically when `make setup` is called but can be fetched manually too with:\n\n```sh\nbuild/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\n```\n\nArguments:\n1. Destination directory (`.cosmocc/4.0.2`)\n2. Version (`4.0.2`)\n3. SHA256 checksum for verification\n\n### Git Submodules\n\nThree main dependencies are git submodules:\n- llama.cpp - LLM inference engine\n- whisper.cpp - Speech-to-text engine\n- stable-diffusion.cpp - Image generation engine\n\n## Initial Setup\n\nBefore first build, initialize and configure dependencies:\n\n```sh\nmake setup\n```\n\nThis command:\n1. Initializes git submodules (clones if needed)\n2. Applies llamafile-specific patches from `<submodule>.patches/` directories\n3. Modifies submodules in-place for llamafile integration\n\n**Important:** Run `make setup` after:\n- Fresh clone\n- Updating submodules\n- Pulling changes that modify patch files\n\n## Build Commands\n\n### Full Build\n\n```sh\n.cosmocc/4.0.2/bin/make -j $(nproc)  # or: llamafile:build\n```\n\nThe `-j $(nproc)` flag enables parallel compilation (adjust based on CPU cores).\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\n**Critical:** Always use `.cosmocc/4.0.2/bin/make`, not system make. The cosmocc toolchain includes its own make with Cosmopolitan-specific behavior. The only exceptions are `make setup` and `make reset-repo`, which use bare `make` — `setup` bootstraps cosmocc on a fresh clone, and both are exempt from the version check.\n\n### Clean Build\n\nRemove build outputs:\n\n```sh\n.cosmocc/4.0.2/bin/make clean  # or: llamafile:clean\n```\n\nThis removes the `o/` directory containing all compiled objects and binaries.\n\n### Install compiled binaries\n\n```sh\nsudo .cosmocc/4.0.2/bin/make install PREFIX=/usr/local\n```\n\nInstalls binaries and man pages.\n\n## Build System Architecture\n\n### Directory Structure\n\n```\nbuild/\n├── config.mk          # Compiler, flags, toolchain version\n├── rules.mk           # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download script\n├── llamafile-convert      # Model conversion script\n└── llamafile-upgrade-engine   # Engine update script\n```\n\n### Configuration (build/config.mk)\n\nDefines:\n- Compiler paths (CC, CXX pointing to cosmocc)\n- Compiler flags (optimization, warnings)\n- Toolchain version\n- Platform-specific settings\n\n### Build Rules (build/rules.mk)\n\nGeneric patterns for:\n- `.c` → `.o` compilation\n- `.a` archive creation\n- `.zip.o` asset bundling (embed files into executables)\n\n### BUILD.mk Files\n\nEach major component has a BUILD.mk file defining:\n- Source files to compile\n- Dependencies\n- Build targets\n- Test targets\n\nThe top-level Makefile includes all BUILD.mk files to orchestrate the build.\n\n## Build Outputs\n\nAll outputs go to `o/$(MODE)/`:\n\n```\no/\n└── $(MODE)/\n    ├── llamafile/\n    │   ├── llamafile          # Main executable\n    │   ├── *.o                # Object files\n    │   └── *.a                # Static libraries\n    ├── llama.cpp/\n    ├── whisper.cpp/\n    ├── stable-diffusion.cpp/\n    └── third_party/\n        └── zipalign/\n            └── zipalign       # Asset bundling tool\n```\n\n## Multi-Architecture Support\n\nThe build system creates universal binaries supporting:\n- x86_64 (Intel/AMD)\n- aarch64 (ARM64)\n\nBoth architectures are compiled simultaneously and combined into single APE binaries.\n\n### Runtime Dispatch\n\nBinaries detect CPU features at runtime and select optimal code paths:\n- AVX, AVX2, AVX-512 (x86_64)\n- ARM NEON (aarch64)\n\n## Asset Bundling\n\nFiles can be embedded into executables using the `.zip.o` pattern:\n\n```makefile\no/$(MODE)/path/to/asset.zip.o: path/to/asset\n```\n\nThe `zipalign` tool handles bundling. Embedded assets are accessible at runtime through the Cosmopolitan virtual filesystem.\n\n## GPU Support\n\nGPU acceleration (CUDA/ROCm/Vulkan) uses dynamic loading:\n- Shared libraries (.so/.dll) are not linked at compile time\n- Libraries are loaded at runtime if available\n- Can be bundled into executables using zipalign\n\n### Building the GPU dylibs\n\nThe host `make` does **not** build the GPU backends. They are separate,\nprebuilt shared libraries produced by per-backend scripts in `llamafile/`:\n\n- `llamafile/cuda.sh`   → `ggml-cuda.so`   (needs `nvcc`; `CUDA_PATH`, default `/usr/local/cuda`)\n- `llamafile/rocm.sh`   → `ggml-rocm.so`   (needs `hipcc`; `ROCM_PATH`, default `/opt/rocm`)\n- `llamafile/vulkan.sh` → `ggml-vulkan.so` (needs `glslc` + SPIR-V headers + libvulkan)\n- `.bat` / `*_parallel.bat` variants build the Windows DLLs.\n\n`make_dylibs.sh` (if present) just wraps these for a release (writes to a\nversioned `gpulibs/<VERSION>/`, passes `--clean`, and `--minimize-size` for\nCUDA). **Run the scripts one at a time**, always with `--clean` — a stale\n`~/.cache/llamafile-{cuda,rocm,vulkan}-build` is the usual \"first build fails\"\ncause (leftover objects that reference symbols upstream removed, e.g. the b10052\nCUDA split-buffer removal). `cuda.sh`/`rocm.sh` share `build-functions.sh`;\n`vulkan.sh` is standalone.\n\n### Verifying a GPU build actually succeeded (do not trust \"Successfully built\")\n\nThe parallel compile launches each `nvcc`/`hipcc`/`glslc` in the background.\n`compile_gpu_sources_parallel` (cuda/rocm) now reaps each job and fails loudly,\nbut `vulkan.sh`'s shader loops do **not** yet check per-job status — a single\nfailed source can still be dropped while the link proceeds and prints\n\"Successfully built\" with a silently incomplete `.so`. So always confirm, don't\nassume:\n\n```bash\nllamafile/cuda.sh --clean --output /tmp/ggml-cuda.so --minimize-size 2>&1 | tee /tmp/b.log\ngrep -c 'error:' /tmp/b.log          # must be 0\ngrep 'Linking'   /tmp/b.log          # object count should match the source count\n```\n\nIf a source fails to compile, fix the root cause (a new upstream cuBLAS call\nmissing from TinyBLAS is a recurring one — see `update_llamacpp.md`), never let\nthe \"success\" line stand in for a green build.\n\n### Vulkan speed paths depend on the glslc/SDK version\n\n`vulkan.sh` probes the build host's `glslc` for shader extensions\n(coopmat, coopmat2, integer-dot, bf16, fp4/fp8) — mirroring upstream's\n`ggml-vulkan/CMakeLists.txt` `test_shader_extension_support`. Each probe that\nfails drops that acceleration pipeline from the shipped dylib (correct output,\njust slower on hardware that supports it). Distro `shaderc` (Ubuntu, SteamOS)\nis typically **too old** — it doesn't know `GL_EXT_integer_dot_product`,\n`GL_EXT_bfloat16`, `GL_NV_cooperative_matrix2`, and can't target\n`--target-env=vulkan1.4`. For a full-featured release Vulkan dylib, build on a\nhost with a recent **LunarG Vulkan SDK** (1.4.x); after installing, `source`\nits `setup-env.sh` so `vulkan.sh` picks up the SDK's `glslc`, then re-run the\nbuild and confirm the probes now print \"supported\". Keep `vulkan.sh`'s probe\nlist in sync with the CMakeLists (it must probe all seven feature tests).\n\n### CUDA `--minimize-size` drops IQ-quant kernels (CPU fallback)\n\nThe release CUDA dylib is built with `--minimize-size`, which (among the size\noptions) passes `-DGGML_CUDA_NO_IQ_QUANTS`. That compiles out most IQ-quant\nCUDA paths — the MMQ/MMVQ matmul kernels in `mmq.cu`/`mmvq.cu`, the bf16/fp16\ndequant converters in `convert.cu`, and the `f32→iq4_nl` copy in `cpy.cu`\n(`ggml_get_to_fp32_cuda`'s IQ cases stay unguarded, so the `float` dequant\ninstantiations still compile — a minor size cost).\nThe payoff is a much smaller `.so`; the cost is that it cannot run IQ-quantized\ntensors on the GPU.\n\n`ggml_backend_cuda_device_supports_op` is guarded by the same macro: the IQ\ncases in the `MUL_MAT`/`MUL_MAT_ID` and `CPY` switches sit inside\n`#ifndef GGML_CUDA_NO_IQ_QUANTS`. So a minimized build honestly reports those\nops unsupported and the scheduler runs them on the CPU backend — correct\noutput, just slower for the IQ layers. **Without that guard the op is\ndispatched to a kernel that was never compiled and aborts at\n`GGML_ASSERT(convert_func != nullptr)` (`ggml-cuda.cu`)** — this is exactly\nwhat `backend_ops_test` hit on `iq2_xxs` MUL_MAT. If you add or bump IQ\nhandling, keep the `supports_op` cases and their kernels behind the same macro\nor the mismatch reappears. (ROCm shares `ggml-cuda.cu`, but its build does not\ndefine the macro, so IQ stays enabled there.)\n\nFor a CUDA dylib that runs IQ quants on the GPU, build without the flag — drop\n`--minimize-size` (or use its other pieces like `--minimal-archs`/`--strip`\nwithout `--no-iq-quants`) — at the cost of a larger library. The ROCm, Vulkan,\nand Metal builds are not size-minimized, so none of them strips IQ the way the\nCUDA build does: ROCm shares this file with the macro undefined, so it keeps the\nfull IQ mul_mat set; Metal and Vulkan keep whatever IQ ops their own backends\nimplement (Vulkan's `supports_op` still declines some IQ mul_mat/cpy shapes, but\nit declines cleanly and falls back to CPU rather than crashing — which, after\nthis fix, is exactly how CUDA behaves too).\n\n## Troubleshooting\n\n### \"make: command not found\" or Wrong Make\n\nEnsure using the cosmocc make:\n\n```sh\n# Wrong\nmake -j $(nproc)\n\n# Correct\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Or use the command directly:\n# llamafile:build\n```\n\n### Submodule Not Initialized\n\nIf build fails with missing files in llama.cpp/whisper.cpp/stable-diffusion.cpp:\n\n```sh\nmake setup\n```\n\n### Stale Object Files\n\nAfter significant changes, clean and rebuild:\n\n```sh\n.cosmocc/4.0.2/bin/make clean          # or: llamafile:clean\n.cosmocc/4.0.2/bin/make -j $(nproc)   # or: llamafile:build\n```\n\n### Toolchain Checksum Mismatch\n\nIf `download-cosmocc.sh` fails verification, check:\n1. Correct version specified\n2. Correct checksum for that version\n3. Network connectivity\n","docs/skills/llamafile/testing.md":"# Llamafile Skill\n\nPath: `docs/skills/llamafile/testing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/testing.md)","docs/skills/llamafile/update_llamacpp.md":"# Llamafile Skill\n\nPath: `docs/skills/llamafile/update_llamacpp.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/update_llamacpp.md)"},"items":[{"name":"AGENTS.md","path":"docs/AGENTS.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/AGENTS.md","title":"docs - AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"# AGENTS.md\n\nThis file provides guidance to Claude Code when working with this repository.\n\n## Project Overview\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Quick Reference\n\n```sh\n# Initial setup (run once after clone)\nmake setup\n\n# Build (always use cosmocc make, not system make)\n# Adapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Run tests\n.cosmocc/4.0.2/bin/make check\n\n# Clean build outputs\n.cosmocc/4.0.2/bin/make clean\n\n# Reset all submodules (warning: removes local changes)\nmake reset-repo\n```\n\n## Key Directories\n\n| Directory | Purpose |\n|-----------|---------|\n| `llamafile/` | Core library (edit directly) |\n| `llama.cpp/` | LLM inference (submodule, edit directly then convert to patches) |\n| `whisper.cpp/` | Speech-to-text (submodule, edit directly then convert to patches) |\n| `stable-diffusion.cpp/` | Image generation (submodule, edit directly then convert to patches) |\n| `*.patches/` | Patch directories for submodules |\n| `o/` | Build outputs |\n\n## Important Notes\n\n- Always use `.cosmocc/4.0.2/bin/make`, not system make\n- Run `make setup` after cloning or updating submodules\n- Submodule changes require patch files (see skill for workflow)\n\n## Detailed Documentation\n\nFor comprehensive build, architecture, development, and testing documentation, ask Claude about \"how to build llamafile\" or \"llamafile development workflow\" to load the llamafile skill.\n","isInternal":false,"tokens":419,"sizeBytes":1624},{"name":"architecture.md","path":"docs/skills/llamafile/architecture.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/architecture.md","title":"Llamafile Skill","category":"anthropic-skill","format":"markdown","content":"# Llamafile Architecture\n\nRepository structure and component overview.\n\n## Project Overview\n\nLlamafile creates single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation. It achieves this by:\n\n1. Combining multiple inference engines (llama.cpp, whisper.cpp, stable-diffusion.cpp)\n2. Using Cosmopolitan Libc for cross-platform portability\n3. Bundling models and assets into Actually Portable Executables (APE)\n\n## Repository Structure\n\n```\nllamafile/\n├── llamafile/              # Core library\n│   ├── server/             # HTTP server implementation\n│   └── highlight/          # Syntax highlighting\n├── llama.cpp/              # LLM inference (submodule)\n│   ├── ggml/               # Low-level tensor ops\n│   ├── src/                # Model implementations\n│   ├── common/             # Utilities\n│   └── tools/              # CLI applications\n├── whisper.cpp/            # Speech-to-text (submodule)\n├── stable-diffusion.cpp/   # Image generation (submodule)\n├── localscore/             # Benchmarking tool\n├── third_party/            # External dependencies\n├── build/                  # Build system\n├── docs/                   # User documentation\n├── *.patches/              # Patch directories\n└── o/                      # Build outputs\n```\n\n## Core Components\n\n### llamafile/ - Core Library\n\nThe heart of llamafile, containing:\n\n- **tinyblas**: BLAS kernels for CUDA support without cublas and optimized CPU inference\n- **GPU support**: Metal, CUDA and ROCm integration (dynamic loading)\n- **Multiplatform optimizations**: CPU feature detection, runtime dispatch\n- **TUI**: Chat interface running in the terminal\n\n#### llamafile/highlight/\n\nSyntax highlighting for code output in chat responses.\n\n### llama.cpp/ - LLM Inference Engine\n\nGit submodule providing:\n\n- **ggml/**: Low-level tensor library\n  - Matrix operations\n  - Quantization support\n  - Backend abstraction (CPU, CUDA, Metal, etc.)\n\n- **src/**: LLM implementations\n  - 100+ model architectures\n  - GGUF format handling\n  - KV cache management\n\n- **common/**: Shared utilities\n  - Argument parsing\n  - Sampling algorithms\n  - Chat templates\n\n- **tools/**: CLI applications\n  - main (inference)\n  - quantize (model quantization)\n  - imatrix (importance matrix)\n  - perplexity (model evaluation)\n  - llama-bench (benchmarking)\n\n### whisper.cpp/ - Speech-to-Text\n\nGit submodule for audio transcription:\n- Whisper model implementation\n- Audio processing utilities\n- Multiple model sizes (tiny to large)\n\n### stable-diffusion.cpp/ - Image Generation\n\nGit submodule for image synthesis:\n- Stable Diffusion implementation\n- Image encoding/decoding\n- Various SD model support\n\n### third_party/ - Dependencies\n\nExternal libraries:\n- **double-conversion**: Float-to-string conversion\n- **mbedtls**: TLS/SSL support\n- **sqlite**: Database support\n- **stb**: Image loading/saving\n- **zipalign**: Tool to bundle llamafile executables with model weights and configurations\n\n## Patch System\n\nEach submodule has a corresponding patches directory:\n\n```\nllama.cpp.patches/\n├── patches/           # .patch files modifying upstream\n└── llamafile-files/   # New files for integration\n\nwhisper.cpp.patches/\n├── patches/\n└── llamafile-files/\n\nstable-diffusion.cpp.patches/\n├── patches/\n└── llamafile-files/\n```\n\n### Patch Types\n\n1. **Modifications** (`.patch` files):\n   - Changes to existing upstream code\n   - Applied with `git apply`\n   - Track upstream file changes\n\n2. **Additions** (`llamafile-files/`):\n   - New files for llamafile integration\n   - Example: BUILD.mk for each submodule\n   - Utility scripts\n   - Additional documentation\n\n3. **Deletions**:\n   - Removal of upstream build systems (CMakeLists.txt, Makefiles)\n   - Replaced by llamafile's unified build\n   - NOTE: deletions were common in the original llamafile but are no longer used,\nas submodule code is pulled rather than redistributed\n\n### Patch Application\n\n`make setup` applies patches:\n1. Initialize/update git submodules\n2. Apply each .patch file in order\n3. Copy llamafile-files/ contents into submodule\n4. Remove conflicting build files\n\nFinally, if cosmocc is not present, it is automatically downloaded at the end of `make setup`.\n\n## Build Infrastructure\n\n### build/ Directory\n\n```\nbuild/\n├── config.mk              # Toolchain configuration\n├── rules.mk               # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download\n├── llamafile-convert      # Model conversion\n└── llamafile-upgrade-engine   # Engine updates\n```\n\n### BUILD.mk Pattern\n\nEach component has a BUILD.mk defining:\n\n```makefile\n# Source files\nCOMPONENT_SRCS = \\\n    component/file1.c \\\n    component/file2.c\n\n# Object files\nCOMPONENT_OBJS = $(COMPONENT_SRCS:%.c=o/$(MODE)/%.o)\n\n# Library target\no/$(MODE)/component/libcomponent.a: $(COMPONENT_OBJS)\n\n# Executable target\no/$(MODE)/component/binary: o/$(MODE)/component/libcomponent.a\n\n# Test targets\no/$(MODE)/component/test.runs: o/$(MODE)/component/test\n```\n\n### Output Organization\n\n```\no/$(MODE)/\n├── package/\n│   ├── file.o         # Object files\n│   ├── libpackage.a   # Static libraries\n│   └── binary         # Executables\n└── ...\n```\n\n## Key Technologies\n\n### Actually Portable Executable (APE)\n\nCosmopolitan's executable format:\n- Single file runs on Windows, macOS, Linux, BSD\n- Contains x86_64 and aarch64 code\n- Self-extracting when needed\n- No installation required\n\n### Asset Bundling\n\nFiles embedded into executables:\n- Models (.gguf)\n- Web assets (HTML, CSS, JS)\n- Shared libraries (.so, .dll)\n\nThe `zipalign` tool handles bundling, and files are accessible via Cosmopolitan's VFS.\n\n### Runtime CPU Dispatch\n\nBinaries detect CPU features and select optimal code:\n- x86_64: SSE, AVX, AVX2, AVX-512, FMA\n- aarch64: NEON, SVE\n\nThis happens transparently at runtime, no user configuration needed.\n\n### Dynamic GPU Loading\n\nGPU support loads at runtime:\n- CUDA: Loads from system or bundled .so/.dll\n- ROCm: Similar dynamic loading\n- Fallback to CPU if GPU unavailable\n\n## Licensing\n\n- **Llamafile project**: Apache 2.0\n- **Llamafile changes to llama.cpp**: MIT (upstream compatibility)\n- **Dependencies**: Retain original licenses\n","isInternal":false,"tokens":1509,"sizeBytes":6371},{"name":"building.md","path":"docs/skills/llamafile/building.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/building.md","title":"Llamafile Skill","category":"anthropic-skill","format":"markdown","content":"# Building Llamafile\n\nComplete guide to the llamafile build system and toolchain.\n\n## Prerequisites\n\n### Cosmopolitan Toolchain\n\nLlamafile uses Cosmopolitan C/C++ compiler (cosmocc) to create Actually Portable Executables (APE). The toolchain \nis downloaded automatically when `make setup` is called but can be fetched manually too with:\n\n```sh\nbuild/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\n```\n\nArguments:\n1. Destination directory (`.cosmocc/4.0.2`)\n2. Version (`4.0.2`)\n3. SHA256 checksum for verification\n\n### Git Submodules\n\nThree main dependencies are git submodules:\n- llama.cpp - LLM inference engine\n- whisper.cpp - Speech-to-text engine\n- stable-diffusion.cpp - Image generation engine\n\n## Initial Setup\n\nBefore first build, initialize and configure dependencies:\n\n```sh\nmake setup\n```\n\nThis command:\n1. Initializes git submodules (clones if needed)\n2. Applies llamafile-specific patches from `<submodule>.patches/` directories\n3. Modifies submodules in-place for llamafile integration\n\n**Important:** Run `make setup` after:\n- Fresh clone\n- Updating submodules\n- Pulling changes that modify patch files\n\n## Build Commands\n\n### Full Build\n\n```sh\n.cosmocc/4.0.2/bin/make -j $(nproc)  # or: llamafile:build\n```\n\nThe `-j $(nproc)` flag enables parallel compilation (adjust based on CPU cores).\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\n**Critical:** Always use `.cosmocc/4.0.2/bin/make`, not system make. The cosmocc toolchain includes its own make with Cosmopolitan-specific behavior. The only exceptions are `make setup` and `make reset-repo`, which use bare `make` — `setup` bootstraps cosmocc on a fresh clone, and both are exempt from the version check.\n\n### Clean Build\n\nRemove build outputs:\n\n```sh\n.cosmocc/4.0.2/bin/make clean  # or: llamafile:clean\n```\n\nThis removes the `o/` directory containing all compiled objects and binaries.\n\n### Install compiled binaries\n\n```sh\nsudo .cosmocc/4.0.2/bin/make install PREFIX=/usr/local\n```\n\nInstalls binaries and man pages.\n\n## Build System Architecture\n\n### Directory Structure\n\n```\nbuild/\n├── config.mk          # Compiler, flags, toolchain version\n├── rules.mk           # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download script\n├── llamafile-convert      # Model conversion script\n└── llamafile-upgrade-engine   # Engine update script\n```\n\n### Configuration (build/config.mk)\n\nDefines:\n- Compiler paths (CC, CXX pointing to cosmocc)\n- Compiler flags (optimization, warnings)\n- Toolchain version\n- Platform-specific settings\n\n### Build Rules (build/rules.mk)\n\nGeneric patterns for:\n- `.c` → `.o` compilation\n- `.a` archive creation\n- `.zip.o` asset bundling (embed files into executables)\n\n### BUILD.mk Files\n\nEach major component has a BUILD.mk file defining:\n- Source files to compile\n- Dependencies\n- Build targets\n- Test targets\n\nThe top-level Makefile includes all BUILD.mk files to orchestrate the build.\n\n## Build Outputs\n\nAll outputs go to `o/$(MODE)/`:\n\n```\no/\n└── $(MODE)/\n    ├── llamafile/\n    │   ├── llamafile          # Main executable\n    │   ├── *.o                # Object files\n    │   └── *.a                # Static libraries\n    ├── llama.cpp/\n    ├── whisper.cpp/\n    ├── stable-diffusion.cpp/\n    └── third_party/\n        └── zipalign/\n            └── zipalign       # Asset bundling tool\n```\n\n## Multi-Architecture Support\n\nThe build system creates universal binaries supporting:\n- x86_64 (Intel/AMD)\n- aarch64 (ARM64)\n\nBoth architectures are compiled simultaneously and combined into single APE binaries.\n\n### Runtime Dispatch\n\nBinaries detect CPU features at runtime and select optimal code paths:\n- AVX, AVX2, AVX-512 (x86_64)\n- ARM NEON (aarch64)\n\n## Asset Bundling\n\nFiles can be embedded into executables using the `.zip.o` pattern:\n\n```makefile\no/$(MODE)/path/to/asset.zip.o: path/to/asset\n```\n\nThe `zipalign` tool handles bundling. Embedded assets are accessible at runtime through the Cosmopolitan virtual filesystem.\n\n## GPU Support\n\nGPU acceleration (CUDA/ROCm/Vulkan) uses dynamic loading:\n- Shared libraries (.so/.dll) are not linked at compile time\n- Libraries are loaded at runtime if available\n- Can be bundled into executables using zipalign\n\n### Building the GPU dylibs\n\nThe host `make` does **not** build the GPU backends. They are separate,\nprebuilt shared libraries produced by per-backend scripts in `llamafile/`:\n\n- `llamafile/cuda.sh`   → `ggml-cuda.so`   (needs `nvcc`; `CUDA_PATH`, default `/usr/local/cuda`)\n- `llamafile/rocm.sh`   → `ggml-rocm.so`   (needs `hipcc`; `ROCM_PATH`, default `/opt/rocm`)\n- `llamafile/vulkan.sh` → `ggml-vulkan.so` (needs `glslc` + SPIR-V headers + libvulkan)\n- `.bat` / `*_parallel.bat` variants build the Windows DLLs.\n\n`make_dylibs.sh` (if present) just wraps these for a release (writes to a\nversioned `gpulibs/<VERSION>/`, passes `--clean`, and `--minimize-size` for\nCUDA). **Run the scripts one at a time**, always with `--clean` — a stale\n`~/.cache/llamafile-{cuda,rocm,vulkan}-build` is the usual \"first build fails\"\ncause (leftover objects that reference symbols upstream removed, e.g. the b10052\nCUDA split-buffer removal). `cuda.sh`/`rocm.sh` share `build-functions.sh`;\n`vulkan.sh` is standalone.\n\n### Verifying a GPU build actually succeeded (do not trust \"Successfully built\")\n\nThe parallel compile launches each `nvcc`/`hipcc`/`glslc` in the background.\n`compile_gpu_sources_parallel` (cuda/rocm) now reaps each job and fails loudly,\nbut `vulkan.sh`'s shader loops do **not** yet check per-job status — a single\nfailed source can still be dropped while the link proceeds and prints\n\"Successfully built\" with a silently incomplete `.so`. So always confirm, don't\nassume:\n\n```bash\nllamafile/cuda.sh --clean --output /tmp/ggml-cuda.so --minimize-size 2>&1 | tee /tmp/b.log\ngrep -c 'error:' /tmp/b.log          # must be 0\ngrep 'Linking'   /tmp/b.log          # object count should match the source count\n```\n\nIf a source fails to compile, fix the root cause (a new upstream cuBLAS call\nmissing from TinyBLAS is a recurring one — see `update_llamacpp.md`), never let\nthe \"success\" line stand in for a green build.\n\n### Vulkan speed paths depend on the glslc/SDK version\n\n`vulkan.sh` probes the build host's `glslc` for shader extensions\n(coopmat, coopmat2, integer-dot, bf16, fp4/fp8) — mirroring upstream's\n`ggml-vulkan/CMakeLists.txt` `test_shader_extension_support`. Each probe that\nfails drops that acceleration pipeline from the shipped dylib (correct output,\njust slower on hardware that supports it). Distro `shaderc` (Ubuntu, SteamOS)\nis typically **too old** — it doesn't know `GL_EXT_integer_dot_product`,\n`GL_EXT_bfloat16`, `GL_NV_cooperative_matrix2`, and can't target\n`--target-env=vulkan1.4`. For a full-featured release Vulkan dylib, build on a\nhost with a recent **LunarG Vulkan SDK** (1.4.x); after installing, `source`\nits `setup-env.sh` so `vulkan.sh` picks up the SDK's `glslc`, then re-run the\nbuild and confirm the probes now print \"supported\". Keep `vulkan.sh`'s probe\nlist in sync with the CMakeLists (it must probe all seven feature tests).\n\n### CUDA `--minimize-size` drops IQ-quant kernels (CPU fallback)\n\nThe release CUDA dylib is built with `--minimize-size`, which (among the size\noptions) passes `-DGGML_CUDA_NO_IQ_QUANTS`. That compiles out most IQ-quant\nCUDA paths — the MMQ/MMVQ matmul kernels in `mmq.cu`/`mmvq.cu`, the bf16/fp16\ndequant converters in `convert.cu`, and the `f32→iq4_nl` copy in `cpy.cu`\n(`ggml_get_to_fp32_cuda`'s IQ cases stay unguarded, so the `float` dequant\ninstantiations still compile — a minor size cost).\nThe payoff is a much smaller `.so`; the cost is that it cannot run IQ-quantized\ntensors on the GPU.\n\n`ggml_backend_cuda_device_supports_op` is guarded by the same macro: the IQ\ncases in the `MUL_MAT`/`MUL_MAT_ID` and `CPY` switches sit inside\n`#ifndef GGML_CUDA_NO_IQ_QUANTS`. So a minimized build honestly reports those\nops unsupported and the scheduler runs them on the CPU backend — correct\noutput, just slower for the IQ layers. **Without that guard the op is\ndispatched to a kernel that was never compiled and aborts at\n`GGML_ASSERT(convert_func != nullptr)` (`ggml-cuda.cu`)** — this is exactly\nwhat `backend_ops_test` hit on `iq2_xxs` MUL_MAT. If you add or bump IQ\nhandling, keep the `supports_op` cases and their kernels behind the same macro\nor the mismatch reappears. (ROCm shares `ggml-cuda.cu`, but its build does not\ndefine the macro, so IQ stays enabled there.)\n\nFor a CUDA dylib that runs IQ quants on the GPU, build without the flag — drop\n`--minimize-size` (or use its other pieces like `--minimal-archs`/`--strip`\nwithout `--no-iq-quants`) — at the cost of a larger library. The ROCm, Vulkan,\nand Metal builds are not size-minimized, so none of them strips IQ the way the\nCUDA build does: ROCm shares this file with the macro undefined, so it keeps the\nfull IQ mul_mat set; Metal and Vulkan keep whatever IQ ops their own backends\nimplement (Vulkan's `supports_op` still declines some IQ mul_mat/cpy shapes, but\nit declines cleanly and falls back to CPU rather than crashing — which, after\nthis fix, is exactly how CUDA behaves too).\n\n## Troubleshooting\n\n### \"make: command not found\" or Wrong Make\n\nEnsure using the cosmocc make:\n\n```sh\n# Wrong\nmake -j $(nproc)\n\n# Correct\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Or use the command directly:\n# llamafile:build\n```\n\n### Submodule Not Initialized\n\nIf build fails with missing files in llama.cpp/whisper.cpp/stable-diffusion.cpp:\n\n```sh\nmake setup\n```\n\n### Stale Object Files\n\nAfter significant changes, clean and rebuild:\n\n```sh\n.cosmocc/4.0.2/bin/make clean          # or: llamafile:clean\n.cosmocc/4.0.2/bin/make -j $(nproc)   # or: llamafile:build\n```\n\n### Toolchain Checksum Mismatch\n\nIf `download-cosmocc.sh` fails verification, check:\n1. Correct version specified\n2. Correct checksum for that version\n3. Network connectivity\n","isInternal":false,"tokens":2711,"sizeBytes":10085},{"name":"development.md","path":"docs/skills/llamafile/development.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/development.md","title":"Llamafile Skill","category":"anthropic-skill","format":"markdown","content":"# Llamafile Development Workflow\n\nGuide to modifying code, managing patches, and working with submodules.\n\n## Development Overview\n\nLlamafile development involves two distinct workflows:\n\n1. **Core code changes**: Direct edits to root-level directories such as `llamafile/`, `whisperfile/`, etc.\n2. **Submodule changes**: Patch-based modifications to `llama.cpp`, `whisper.cpp`, `stable-diffusion.cpp`\n\n## Modifying Core Code\n\nFor changes which are not affecting submodules:\n\n### Workflow\n\n1. Edit files\n2. Rebuild: `llamafile:build`\n3. Test: `llamafile:check`\n4. Commit changes normally with git\n\n### Key Directories\n\n```\nllamafile/\n├── server/      # HTTP server, API endpoints\n├── highlight/   # Syntax highlighting\n├── tinyblas/    # Optimized BLAS kernels\n└── *.c, *.h     # Core utilities\n```\n\n## Modifying Submodule Code\n\nSubmodules require a patch-based workflow because:\n- Submodules point to specific upstream commits\n- Direct commits in submodules would be lost\n- Patches preserve modifications across submodule updates\n\n### Understanding the Patch System\n\nEach submodule has a patches directory. For instance, for `llama.cpp`:\n\n```\nllama.cpp.patches/\n├── README.md              # Patching info + list of all patches and their purpose\n├── apply-patches.sh       # Script to apply all patches to llama.cpp submodule\n├── renames.sh             # Script for file renames/moves (if any)\n├── llamafile-files/       # Additional files to copy into llama.cpp\n│   ├── BUILD.mk           # Makefile for building llama.cpp with cosmocc\n│   └── README.llamafile   # License and modification notes\n└── patches/               # Patch files for upstream sources\n```\n\nPatches are applied by `make setup`:\n1. Submodule is reset to clean state\n2. Each .patch file is applied in alphabetical order\n3. Files from llamafile-files/ are copied into the submodule\n\n### Making Changes to a Submodule\n\n#### Step 1: Make Changes\n\nEdit files directly in the submodule directory:\n\n```sh\ncd llama.cpp\n# Make your changes\nvim src/llama.cpp\n```\n\n#### Step 2: Generate Patches\n\nPatches are usually generated after the code has been thoroughly tested and is\nready to commit. To avoid manual errors, use the script `tools/generate_patches.sh`\n(or the `llamafile:generate-patches` skill that wraps it), which automatically\nsaves all new files and patches in the specified output directory.\n\n```sh\n# echo y answers the prompt; the subshell restores the cwd even on failure\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nAfter this operation, one can double check which files have been modified / added\nvia a `git diff`.\n\nNaming convention:\n- all patches have a `.patch` extension\n- patch filenames reflect the file path with underscores replacing slashes (e.g., `common_arg.cpp.patch` for `common/arg.cpp`).\n\n\n#### Step 3: Verify Patches\n\nOnce you are sure all patches have been saved, reset and reapply to verify:\n\n```sh\n# Reset everything\nmake reset-repo\n\n# Reapply patches\nmake setup\n\n# Rebuild and test\n# llamafile:build\n# llamafile:check\n```\n\n### Adding New Files to Submodules\n\nFor new files (not modifications), use llamafile-files/:\n\n```sh\n# Create directory structure matching submodule\nmkdir -p llama.cpp.patches/llamafile-files/src/\n\n# Add your new file\ncp new-utility.cpp llama.cpp.patches/llamafile-files/src/\n```\n\nThe file will be copied into the submodule during `make setup`.\n\n### Updating BUILD.mk for Submodules\n\nEach submodule needs a BUILD.mk in llamafile-files/:\n\n```makefile\n# llama.cpp.patches/llamafile-files/BUILD.mk\n\nLLAMA_SRCS = \\\n    llama.cpp/src/llama.cpp \\\n    llama.cpp/src/new-file.cpp    # Add new files here\n\nLLAMA_OBJS = $(LLAMA_SRCS:%.cpp=o/$(MODE)/%.o)\n\n# ... rest of build rules\n```\n\n## Submodule Management\n\n### Resetting a Single Submodule\n\nTo discard changes in one submodule:\n\n```sh\ncd llama.cpp\ngit reset --hard\ngit clean -fdx\n```\n\nThen reapply patches:\n\n```sh\ncd ..\nmake setup\n```\n\n### Resetting All Submodules\n\nTo reset everything (warning: loses all local changes):\n\n```sh\nmake reset-repo\nmake setup\n```\n\n\n## Git Workflow\n\n### Committing Changes\n\nFor core code changes:\n```sh\ngit add llamafile/modified-file.c\ngit commit -m \"Fix: description\"\n```\n\nFor submodule patches:\n```sh\ngit add llama.cpp.patches/patches/new-patch.patch\ngit commit -m \"llama.cpp: Add feature X\"\n```\n\n### Pull Request Checklist\n\nBefore submitting changes:\n\n1. [ ] Patches apply cleanly from fresh clone\n2. [ ] Build succeeds: `llamafile:build`\n3. [ ] Tests pass: `llamafile:check`\n4. [ ] Patches are focused and documented\n5. [ ] BUILD.mk updated if adding new files\n\n## Debugging Tips\n\n### Viewing Applied Patches\n\nTo see what patches are currently applied:\n\n```sh\ncd llama.cpp\ngit log --oneline HEAD...$(git rev-parse --short @{u} 2>/dev/null || echo \"origin/master\")\n```\n\n### Checking Submodule State\n\n```sh\ngit submodule status\n```\n\nOutput shows:\n- `-` : Not initialized\n- `+` : Different commit than recorded\n- ` ` : Clean, matches recorded commit\n\n### Finding Which Patch Changed a File\n\n```sh\ngrep -l \"filename\" llama.cpp.patches/patches/*.patch\n```\n","isInternal":false,"tokens":1285,"sizeBytes":5171},{"name":"SKILL.md","path":"docs/skills/llamafile/SKILL.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/SKILL.md","title":"llamafile","category":"anthropic-skill","format":"markdown","content":"---\nname: llamafile\ndescription: This skill should be used when the user asks to \"build llamafile\", \"rebuild llamafile\", \"run llamafile\", \"run llamafile tests\", \"debug llamafile\", \"set up llamafile\", \"update patches\", \"fix patch conflict\", \"update llama.cpp\", \"pull latest llama.cpp\", \"sync upstream llama.cpp\", \"reset submodules\", \"write a test for llamafile\", \"how does llamafile work\", \"llamafile architecture\", or needs guidance on the llamafile build system, patch workflow, submodule integration, cosmocc toolchain, or development practices.\nversion: 0.1.6\n---\n\n# Llamafile Development Guide\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Version Disambiguation\n\n- **New llamafile** (or simply \"llamafile\"): The code in the `main` branch, used for releases >=0.10.0\n- **Old/Classic llamafile**: The legacy code, used for releases until 0.9.3 (see commit 7e7d33c).\n\nThis guide covers the **new llamafile** project.\n\n## Quick Reference\n\n### Initial Setup\n\n```sh\nmake setup\n```\n\nImmediately after cloning the repo (or after a reset done with `make reset-repo`), this command initializes git submodules and applies llamafile-specific patches.\n\n### Building\n\nRun `llamafile:build` to build all targets.\n\n### Testing\n\nRun `llamafile:check` to run the unit test suite.\n\n### Cleaning\n\nRun `llamafile:clean` to remove all build outputs.\n\n### Reset Submodules\n\nAfter `make setup`, submodules contain patches and are no longer in a clean state.\nTo reset them, run:\n\n```sh\nmake reset-repo  # Warning: removes all local changes\n```\n\nWARNING: this command removes all local changes. Do not run it without first generating patches from any modifications.\n\n### Patch & Upstream-Update Commands\n\nWhen changing submodule patches or bumping llama.cpp, use the dedicated commands\nrather than ad-hoc `git diff`/`git apply`:\n\n- `llamafile:generate-patches` — regenerate patches from in-place submodule edits\n  (the only sanctioned way to produce patches).\n- `llamafile:verify-clean` — clean round-trip (`reset-repo` → `setup` → clean\n  build → `check`); the verification after generating patches or any patch change.\n\nFor the full llama.cpp bump procedure, follow `update_llamacpp.md` step by step.\n\n\n## Core Workflows\n\n### Building from Scratch\n\nTo build llamafile from a fresh clone:\n\n1. Clone the repository\n2. Run `make setup` to initialize submodules and apply patches\n3. Build with `llamafile:build`\n\nBuild outputs appear in `o/$(MODE)/` directory.\n\n### Modifying Core Code\n\nFor changes to llamafile's own code (not submodules):\n\n1. Edit files in `llamafile/` directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\n### Modifying Submodule Code\n\nSubmodules (llama.cpp, whisper.cpp, stable-diffusion.cpp) require a patch-based workflow:\n\n1. Make changes directly in the submodule directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\nNOTE: never try to edit patches or generate them manually. This step is \ndone only after rebuild and tests (even manual ones) are successful. See\n`development.md` for detailed patch workflow.\n\n### Running Specific Tests\n\nTests use the `.runs` pattern in BUILD.mk files:\n\n```makefile\no/$(MODE)/llamafile/json_test.runs\n```\n\nTo run all tests: `llamafile:check`\n\n## Key Concepts\n\n### Cosmopolitan Toolchain\n\nThe project uses Cosmopolitan Libc (cosmocc) to create Actually Portable Executables (APE) - single files that run on multiple platforms without modification. Always use the `llamafile:build`, `llamafile:check`, and `llamafile:clean` commands (which use cosmocc's make), not system make.\n\n### Patch System\n\nEach submodule has a corresponding patches directory:\n- `llama.cpp.patches/`\n- `whisper.cpp.patches/`\n- `stable-diffusion.cpp.patches/`\n\nPatches include:\n- **Modifications** (.patch files): Changes to upstream code\n- **Additions** (llamafile-files/): New files for integration (BUILD.mk, utilities)\n\n### Build System\n\n- **build/config.mk**: Compiler and toolchain configuration\n- **build/rules.mk**: Generic build patterns (.c → .o, archives, asset bundling)\n- **BUILD.mk files**: Per-package build logic\n\nOutputs: `o/$(MODE)/package/file.o`\n\n### Multi-Architecture Support\n\nBinaries include both x86_64 and aarch64 code paths with runtime CPU feature detection (AVX, AVX2, AVX-512, ARM NEON).\n\n### GPU Backend Loaders\n\nDynamically-loaded backends that export the ggml C ABI — CUDA, ROCm, Vulkan — all go through the shared probe core in `llamafile/gpu_backend.c`. Each is just a `GpuBackendDesc` + a link thunk; the core does load → log-suppress → **device-count gate** (reject 0-device DSOs so AUTO falls back) → register, with a SIGSEGV/SIGABRT crash guard around the foreign probe call (driver init can fault across the cosmo/ms_abi boundary — issue #988). Metal stays separate by design (runtime-compiled, no ms_abi split, no device gate). When adding/changing a backend: route it through the core, keep the gate, and add a case to `tests/gpu_backend_test.cpp`. A more detailed design doc lives separately.\n\n## Main Executables\n\nAfter building, find binaries in `o/$(MODE)/`:\n\n| Binary | Purpose |\n|--------|---------|\n| `llamafile/llamafile` | Main llamafile executable |\n| `third_party/zipalign/zipalign` | Bundle assets into executables |\n| `whisperfile/whisperfile` | Main whisperfile executable |\n\n## Troubleshooting\n\n### Build Fails After Submodule Update\n\nRun `make setup` to reapply patches after any submodule changes.\n\n### Submodule Has Uncommitted Changes\n\nTo reset a single submodule:\n```sh\ncd <submodule> && git reset --hard && git clean -fdx\n```\n\nTo reset all submodules:\n```sh\nmake reset-repo\n```\n\n### Wrong Make Being Used\n\nEnsure using the `llamafile:build` command (which uses cosmocc's make), not system make.\n\n## Additional Resources\n\n### Reference Files\n\nFor detailed information, consult:\n- **`building.md`** - Complete build system documentation, toolchain details\n- **`architecture.md`** - Repository structure, component overview\n- **`development.md`** - Development workflow, patch management, submodule integration\n- **`testing.md`** - Test patterns, running and writing tests\n- **`update_llamacpp.md`** - Keeping llamafile updated with upstream llama.cpp\n\n### Project Documentation\n\n- **README.md** in repo: Project introduction\n- **docs/** directory: User documentation (quickstart, installation, troubleshooting)\n- **RELEASE.md**: Release process\n- Most executables support `--help`\n","frontmatter":{"name":"llamafile","description":"This skill should be used when the user asks to \"build llamafile\", \"rebuild llamafile\", \"run llamafile\", \"run llamafile tests\", \"debug llamafile\", \"set up llamafile\", \"update patches\", \"fix patch conflict\", \"update llama.cpp\", \"pull latest llama.cpp\", \"sync upstream llama.cpp\", \"reset submodules\", \"write a test for llamafile\", \"how does llamafile work\", \"llamafile architecture\", or needs guidance on the llamafile build system, patch workflow, submodule integration, cosmocc toolchain, or development practices.","version":"0.1.6"},"isInternal":false,"tokens":1630,"sizeBytes":6604},{"name":"testing.md","path":"docs/skills/llamafile/testing.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/testing.md","title":"Llamafile Skill","category":"anthropic-skill","format":"markdown","content":"# Llamafile Skill\n\nPath: `docs/skills/llamafile/testing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/testing.md)","tokens":300,"sizeBytes":183},{"name":"update_llamacpp.md","path":"docs/skills/llamafile/update_llamacpp.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/update_llamacpp.md","title":"Llamafile Skill","category":"anthropic-skill","format":"markdown","content":"# Llamafile Skill\n\nPath: `docs/skills/llamafile/update_llamacpp.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/update_llamacpp.md)","tokens":300,"sizeBytes":199},{"name":"marketplace.json","path":".llamafile_plugin/.claude-plugin/marketplace.json","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/.llamafile_plugin/.claude-plugin/marketplace.json","title":"llamafile-local","category":"marketplace","format":"json","content":"{\n  \"name\": \"llamafile-local\",\n  \"description\": \"Local llamafile plugin marketplace\",\n  \"owner\": {\n    \"name\": \"Mozilla AI\",\n    \"email\": \"davide@mozilla.ai\"\n  },\n  \"plugins\": [\n    {\n      \"name\": \"llamafile\",\n      \"description\": \"Build guidance and commands for the llamafile project\",\n      \"version\": \"0.1.7\",\n      \"author\": {\n        \"name\": \"Mozilla AI\",\n        \"email\": \"davide@mozilla.ai\"\n      },\n      \"source\": \"./\"\n    }\n  ]\n}\n","frontmatter":{"name":"llamafile-local","description":"Local llamafile plugin marketplace","owner":{"name":"Mozilla AI","email":"davide@mozilla.ai"},"plugins":[{"name":"llamafile","description":"Build guidance and commands for the llamafile project","version":"0.1.7","author":{"name":"Mozilla AI","email":"davide@mozilla.ai"},"source":"./"}]},"isInternal":false,"tokens":129,"sizeBytes":442},{"name":"plugin.json","path":".llamafile_plugin/.claude-plugin/plugin.json","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/.llamafile_plugin/.claude-plugin/plugin.json","title":"llamafile","category":"plugin-manifest","format":"json","content":"{\n  \"name\": \"llamafile\",\n  \"version\": \"0.1.7\",\n  \"description\": \"Build guidance and commands for the llamafile project\"\n}\n","frontmatter":{"name":"llamafile","version":"0.1.7","description":"Build guidance and commands for the llamafile project"},"isInternal":false,"tokens":37,"sizeBytes":122},{"name":"build.md","path":"docs/commands/build.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/commands/build.md","title":"Command: /build","category":"command-prompt","format":"markdown","content":"---\ndescription: Build llamafile using the cosmocc toolchain\n---\n\n# Build Llamafile\n\nBuild the project using the Cosmopolitan toolchain.\n\nFirst, ensure the toolchain is available:\n\n```bash\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\n```\n\nThen build:\n\n```bash\n.cosmocc/4.0.2/bin/make -j $(nproc)\n```\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\nBuild outputs will be in `o/$(MODE)/`.\n","frontmatter":{"description":"Build llamafile using the cosmocc toolchain"},"isInternal":false,"tokens":197,"sizeBytes":534},{"name":"check.md","path":"docs/commands/check.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/commands/check.md","title":"Command: /check","category":"command-prompt","format":"markdown","content":"---\ndescription: Run llamafile unit tests\n---\n\n# Run Llamafile Tests\n\nRun the unit test suite using the Cosmopolitan toolchain.\n\n```bash\n.cosmocc/4.0.2/bin/make check\n```\n","frontmatter":{"description":"Run llamafile unit tests"},"isInternal":false,"tokens":49,"sizeBytes":171},{"name":"clean.md","path":"docs/commands/clean.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/commands/clean.md","title":"Command: /clean","category":"command-prompt","format":"markdown","content":"---\ndescription: Clean llamafile build outputs\n---\n\n# Clean Llamafile Build\n\nRemove all build outputs from the `o/` directory.\n\n```bash\n.cosmocc/4.0.2/bin/make clean\n```\n","frontmatter":{"description":"Clean llamafile build outputs"},"isInternal":false,"tokens":48,"sizeBytes":170},{"name":"generate-patches.md","path":"docs/commands/generate-patches.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/commands/generate-patches.md","title":"Command: /generate-patches","category":"command-prompt","format":"markdown","content":"---\ndescription: Regenerate llamafile patches from in-place submodule edits\n---\n\n# Generate Patches\n\nCapture the current in-place edits of a submodule as patch files, using the\nproject's `generate_patches.sh` tool. This is the **only** sanctioned way to\nproduce patches — never hand-craft them with `git diff` (the tool rewrites the\n`a/`,`b/` paths to be repo-rooted, strips the volatile `index` line, names files\nby convention, and routes new/untracked files into `llamafile-files/`; a raw\n`git diff` gets all of that wrong).\n\nRun it for the `llama.cpp` submodule (the common case). The tool is general and\nworks for any submodule — swap the directory and output path for `whisper.cpp`\nor `stable-diffusion.cpp`.\n\nThe subshell keeps the working directory restored even if the tool fails, and\n`echo y` answers the script's confirmation prompt non-interactively:\n\n```bash\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nOutput lands in `llama.cpp.patches/patches/` (modified files) and\n`llama.cpp.patches/llamafile-files/` (new files, including `BUILD.mk`).\n\nThe tool **only writes/overwrites — it never deletes**. If you dropped a patch\nduring a bump (the file is no longer modified, e.g. upstream absorbed the\nchange), its old `.patch` will still be sitting in `patches/` and will keep\nbeing applied by `setup`. `git rm` each dropped patch by hand, and confirm the\nfinal count (`ls llama.cpp.patches/patches | wc -l`) matches your intent.\n\nIMPORTANT: only run this **after** the in-place edits are proven to work\n(a clean build succeeds and llamafile runs as expected). Generating patches\nfrom unproven edits bakes in breakage. After generating, verify the patch set\nround-trips with `llamafile:verify-clean`.\n","frontmatter":{"description":"Regenerate llamafile patches from in-place submodule edits"},"isInternal":false,"tokens":436,"sizeBytes":1766},{"name":"verify-clean.md","path":"docs/commands/verify-clean.md","rawUrl":"https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/commands/verify-clean.md","title":"Command: /verify-clean","category":"command-prompt","format":"markdown","content":"---\ndescription: Clean round-trip — reset, re-apply patches, clean build, and test\n---\n\n# Verify Clean\n\nVerify the repository from a clean slate: reset, re-pull submodules and\nre-apply patches, then do a **clean** build and run the tests. Use this:\n\n- as the final verification after `llamafile:generate-patches` (confirms the\n  regenerated patches re-apply cleanly and still build), and\n- any time patches or submodules change and you need a trustworthy result.\n\nWhy a clean build: after a `reset-repo`/`setup`, submodule sources change\nwithout their timestamps necessarily moving, so an incremental `make` can link\nstale objects. Always `make clean` first here — do not rebuild incrementally.\n\n`make setup` both pulls submodules and applies patches, and it cannot pull\nsubmodules onto a dirty tree — that is exactly why `reset-repo` runs first.\n\nNote: `reset-repo` is destructive (it `rm -rf`s the submodule dirs before\nrestoring them), so a permission-gated environment may prompt or block it. Run\nit through the `$MAKE` (`.cosmocc/.../make`) form below rather than raw\n`git clean`/`reset`; allowlist `make reset-repo` if round-trips keep stalling.\n\n```bash\n# ensure the toolchain is available\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\nMAKE=.cosmocc/4.0.2/bin/make\n\n$MAKE reset-repo     # clean: drop all local changes, reset submodules\n$MAKE setup          # pull submodules + apply patches (+ fetch UI assets)\n$MAKE clean          # drop stale build outputs\n$MAKE -j$(nproc)     # clean build; on mac use -j$(sysctl -n hw.physicalcpu)\n$MAKE check          # unit tests\n```\n\nA successful round-trip proves the committed patch set is internally\nconsistent. It does NOT cover GPU runtime backends, non-host platforms, the\nweb UI, or long-run stability — see the handoff checklist in\n`update_llamacpp.md`.\n","frontmatter":{"description":"Clean round-trip — reset, re-apply patches, clean build, and test"},"isInternal":false,"tokens":528,"sizeBytes":1923}],"systemPromptSnippet":"<yakaai_skills repo=\"mozilla-ai/llamafile\">\n<!-- File: docs/AGENTS.md (Tokens: ~419 | Category: root-instruction) -->\n# AGENTS.md\n\nThis file provides guidance to Claude Code when working with this repository.\n\n## Project Overview\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Quick Reference\n\n```sh\n# Initial setup (run once after clone)\nmake setup\n\n# Build (always use cosmocc make, not system make)\n# Adapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Run tests\n.cosmocc/4.0.2/bin/make check\n\n# Clean build outputs\n.cosmocc/4.0.2/bin/make clean\n\n# Reset all submodules (warning: removes local changes)\nmake reset-repo\n```\n\n## Key Directories\n\n| Directory | Purpose |\n|-----------|---------|\n| `llamafile/` | Core library (edit directly) |\n| `llama.cpp/` | LLM inference (submodule, edit directly then convert to patches) |\n| `whisper.cpp/` | Speech-to-text (submodule, edit directly then convert to patches) |\n| `stable-diffusion.cpp/` | Image generation (submodule, edit directly then convert to patches) |\n| `*.patches/` | Patch directories for submodules |\n| `o/` | Build outputs |\n\n## Important Notes\n\n- Always use `.cosmocc/4.0.2/bin/make`, not system make\n- Run `make setup` after cloning or updating submodules\n- Submodule changes require patch files (see skill for workflow)\n\n## Detailed Documentation\n\nFor comprehensive build, architecture, development, and testing documentation, ask Claude about \"how to build llamafile\" or \"llamafile development workflow\" to load the llamafile skill.\n\n<!-- File: docs/skills/llamafile/architecture.md (Tokens: ~1509 | Category: anthropic-skill) -->\n# Llamafile Architecture\n\nRepository structure and component overview.\n\n## Project Overview\n\nLlamafile creates single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation. It achieves this by:\n\n1. Combining multiple inference engines (llama.cpp, whisper.cpp, stable-diffusion.cpp)\n2. Using Cosmopolitan Libc for cross-platform portability\n3. Bundling models and assets into Actually Portable Executables (APE)\n\n## Repository Structure\n\n```\nllamafile/\n├── llamafile/              # Core library\n│   ├── server/             # HTTP server implementation\n│   └── highlight/          # Syntax highlighting\n├── llama.cpp/              # LLM inference (submodule)\n│   ├── ggml/               # Low-level tensor ops\n│   ├── src/                # Model implementations\n│   ├── common/             # Utilities\n│   └── tools/              # CLI applications\n├── whisper.cpp/            # Speech-to-text (submodule)\n├── stable-diffusion.cpp/   # Image generation (submodule)\n├── localscore/             # Benchmarking tool\n├── third_party/            # External dependencies\n├── build/                  # Build system\n├── docs/                   # User documentation\n├── *.patches/              # Patch directories\n└── o/                      # Build outputs\n```\n\n## Core Components\n\n### llamafile/ - Core Library\n\nThe heart of llamafile, containing:\n\n- **tinyblas**: BLAS kernels for CUDA support without cublas and optimized CPU inference\n- **GPU support**: Metal, CUDA and ROCm integration (dynamic loading)\n- **Multiplatform optimizations**: CPU feature detection, runtime dispatch\n- **TUI**: Chat interface running in the terminal\n\n#### llamafile/highlight/\n\nSyntax highlighting for code output in chat responses.\n\n### llama.cpp/ - LLM Inference Engine\n\nGit submodule providing:\n\n- **ggml/**: Low-level tensor library\n  - Matrix operations\n  - Quantization support\n  - Backend abstraction (CPU, CUDA, Metal, etc.)\n\n- **src/**: LLM implementations\n  - 100+ model architectures\n  - GGUF format handling\n  - KV cache management\n\n- **common/**: Shared utilities\n  - Argument parsing\n  - Sampling algorithms\n  - Chat templates\n\n- **tools/**: CLI applications\n  - main (inference)\n  - quantize (model quantization)\n  - imatrix (importance matrix)\n  - perplexity (model evaluation)\n  - llama-bench (benchmarking)\n\n### whisper.cpp/ - Speech-to-Text\n\nGit submodule for audio transcription:\n- Whisper model implementation\n- Audio processing utilities\n- Multiple model sizes (tiny to large)\n\n### stable-diffusion.cpp/ - Image Generation\n\nGit submodule for image synthesis:\n- Stable Diffusion implementation\n- Image encoding/decoding\n- Various SD model support\n\n### third_party/ - Dependencies\n\nExternal libraries:\n- **double-conversion**: Float-to-string conversion\n- **mbedtls**: TLS/SSL support\n- **sqlite**: Database support\n- **stb**: Image loading/saving\n- **zipalign**: Tool to bundle llamafile executables with model weights and configurations\n\n## Patch System\n\nEach submodule has a corresponding patches directory:\n\n```\nllama.cpp.patches/\n├── patches/           # .patch files modifying upstream\n└── llamafile-files/   # New files for integration\n\nwhisper.cpp.patches/\n├── patches/\n└── llamafile-files/\n\nstable-diffusion.cpp.patches/\n├── patches/\n└── llamafile-files/\n```\n\n### Patch Types\n\n1. **Modifications** (`.patch` files):\n   - Changes to existing upstream code\n   - Applied with `git apply`\n   - Track upstream file changes\n\n2. **Additions** (`llamafile-files/`):\n   - New files for llamafile integration\n   - Example: BUILD.mk for each submodule\n   - Utility scripts\n   - Additional documentation\n\n3. **Deletions**:\n   - Removal of upstream build systems (CMakeLists.txt, Makefiles)\n   - Replaced by llamafile's unified build\n   - NOTE: deletions were common in the original llamafile but are no longer used,\nas submodule code is pulled rather than redistributed\n\n### Patch Application\n\n`make setup` applies patches:\n1. Initialize/update git submodules\n2. Apply each .patch file in order\n3. Copy llamafile-files/ contents into submodule\n4. Remove conflicting build files\n\nFinally, if cosmocc is not present, it is automatically downloaded at the end of `make setup`.\n\n## Build Infrastructure\n\n### build/ Directory\n\n```\nbuild/\n├── config.mk              # Toolchain configuration\n├── rules.mk               # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download\n├── llamafile-convert      # Model conversion\n└── llamafile-upgrade-engine   # Engine updates\n```\n\n### BUILD.mk Pattern\n\nEach component has a BUILD.mk defining:\n\n```makefile\n# Source files\nCOMPONENT_SRCS = \\\n    component/file1.c \\\n    component/file2.c\n\n# Object files\nCOMPONENT_OBJS = $(COMPONENT_SRCS:%.c=o/$(MODE)/%.o)\n\n# Library target\no/$(MODE)/component/libcomponent.a: $(COMPONENT_OBJS)\n\n# Executable target\no/$(MODE)/component/binary: o/$(MODE)/component/libcomponent.a\n\n# Test targets\no/$(MODE)/component/test.runs: o/$(MODE)/component/test\n```\n\n### Output Organization\n\n```\no/$(MODE)/\n├── package/\n│   ├── file.o         # Object files\n│   ├── libpackage.a   # Static libraries\n│   └── binary         # Executables\n└── ...\n```\n\n## Key Technologies\n\n### Actually Portable Executable (APE)\n\nCosmopolitan's executable format:\n- Single file runs on Windows, macOS, Linux, BSD\n- Contains x86_64 and aarch64 code\n- Self-extracting when needed\n- No installation required\n\n### Asset Bundling\n\nFiles embedded into executables:\n- Models (.gguf)\n- Web assets (HTML, CSS, JS)\n- Shared libraries (.so, .dll)\n\nThe `zipalign` tool handles bundling, and files are accessible via Cosmopolitan's VFS.\n\n### Runtime CPU Dispatch\n\nBinaries detect CPU features and select optimal code:\n- x86_64: SSE, AVX, AVX2, AVX-512, FMA\n- aarch64: NEON, SVE\n\nThis happens transparently at runtime, no user configuration needed.\n\n### Dynamic GPU Loading\n\nGPU support loads at runtime:\n- CUDA: Loads from system or bundled .so/.dll\n- ROCm: Similar dynamic loading\n- Fallback to CPU if GPU unavailable\n\n## Licensing\n\n- **Llamafile project**: Apache 2.0\n- **Llamafile changes to llama.cpp**: MIT (upstream compatibility)\n- **Dependencies**: Retain original licenses\n\n<!-- File: docs/skills/llamafile/building.md (Tokens: ~2711 | Category: anthropic-skill) -->\n# Building Llamafile\n\nComplete guide to the llamafile build system and toolchain.\n\n## Prerequisites\n\n### Cosmopolitan Toolchain\n\nLlamafile uses Cosmopolitan C/C++ compiler (cosmocc) to create Actually Portable Executables (APE). The toolchain \nis downloaded automatically when `make setup` is called but can be fetched manually too with:\n\n```sh\nbuild/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\n```\n\nArguments:\n1. Destination directory (`.cosmocc/4.0.2`)\n2. Version (`4.0.2`)\n3. SHA256 checksum for verification\n\n### Git Submodules\n\nThree main dependencies are git submodules:\n- llama.cpp - LLM inference engine\n- whisper.cpp - Speech-to-text engine\n- stable-diffusion.cpp - Image generation engine\n\n## Initial Setup\n\nBefore first build, initialize and configure dependencies:\n\n```sh\nmake setup\n```\n\nThis command:\n1. Initializes git submodules (clones if needed)\n2. Applies llamafile-specific patches from `<submodule>.patches/` directories\n3. Modifies submodules in-place for llamafile integration\n\n**Important:** Run `make setup` after:\n- Fresh clone\n- Updating submodules\n- Pulling changes that modify patch files\n\n## Build Commands\n\n### Full Build\n\n```sh\n.cosmocc/4.0.2/bin/make -j $(nproc)  # or: llamafile:build\n```\n\nThe `-j $(nproc)` flag enables parallel compilation (adjust based on CPU cores).\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\n**Critical:** Always use `.cosmocc/4.0.2/bin/make`, not system make. The cosmocc toolchain includes its own make with Cosmopolitan-specific behavior. The only exceptions are `make setup` and `make reset-repo`, which use bare `make` — `setup` bootstraps cosmocc on a fresh clone, and both are exempt from the version check.\n\n### Clean Build\n\nRemove build outputs:\n\n```sh\n.cosmocc/4.0.2/bin/make clean  # or: llamafile:clean\n```\n\nThis removes the `o/` directory containing all compiled objects and binaries.\n\n### Install compiled binaries\n\n```sh\nsudo .cosmocc/4.0.2/bin/make install PREFIX=/usr/local\n```\n\nInstalls binaries and man pages.\n\n## Build System Architecture\n\n### Directory Structure\n\n```\nbuild/\n├── config.mk          # Compiler, flags, toolchain version\n├── rules.mk           # Generic build patterns\n├── download-cosmocc.sh    # Toolchain download script\n├── llamafile-convert      # Model conversion script\n└── llamafile-upgrade-engine   # Engine update script\n```\n\n### Configuration (build/config.mk)\n\nDefines:\n- Compiler paths (CC, CXX pointing to cosmocc)\n- Compiler flags (optimization, warnings)\n- Toolchain version\n- Platform-specific settings\n\n### Build Rules (build/rules.mk)\n\nGeneric patterns for:\n- `.c` → `.o` compilation\n- `.a` archive creation\n- `.zip.o` asset bundling (embed files into executables)\n\n### BUILD.mk Files\n\nEach major component has a BUILD.mk file defining:\n- Source files to compile\n- Dependencies\n- Build targets\n- Test targets\n\nThe top-level Makefile includes all BUILD.mk files to orchestrate the build.\n\n## Build Outputs\n\nAll outputs go to `o/$(MODE)/`:\n\n```\no/\n└── $(MODE)/\n    ├── llamafile/\n    │   ├── llamafile          # Main executable\n    │   ├── *.o                # Object files\n    │   └── *.a                # Static libraries\n    ├── llama.cpp/\n    ├── whisper.cpp/\n    ├── stable-diffusion.cpp/\n    └── third_party/\n        └── zipalign/\n            └── zipalign       # Asset bundling tool\n```\n\n## Multi-Architecture Support\n\nThe build system creates universal binaries supporting:\n- x86_64 (Intel/AMD)\n- aarch64 (ARM64)\n\nBoth architectures are compiled simultaneously and combined into single APE binaries.\n\n### Runtime Dispatch\n\nBinaries detect CPU features at runtime and select optimal code paths:\n- AVX, AVX2, AVX-512 (x86_64)\n- ARM NEON (aarch64)\n\n## Asset Bundling\n\nFiles can be embedded into executables using the `.zip.o` pattern:\n\n```makefile\no/$(MODE)/path/to/asset.zip.o: path/to/asset\n```\n\nThe `zipalign` tool handles bundling. Embedded assets are accessible at runtime through the Cosmopolitan virtual filesystem.\n\n## GPU Support\n\nGPU acceleration (CUDA/ROCm/Vulkan) uses dynamic loading:\n- Shared libraries (.so/.dll) are not linked at compile time\n- Libraries are loaded at runtime if available\n- Can be bundled into executables using zipalign\n\n### Building the GPU dylibs\n\nThe host `make` does **not** build the GPU backends. They are separate,\nprebuilt shared libraries produced by per-backend scripts in `llamafile/`:\n\n- `llamafile/cuda.sh`   → `ggml-cuda.so`   (needs `nvcc`; `CUDA_PATH`, default `/usr/local/cuda`)\n- `llamafile/rocm.sh`   → `ggml-rocm.so`   (needs `hipcc`; `ROCM_PATH`, default `/opt/rocm`)\n- `llamafile/vulkan.sh` → `ggml-vulkan.so` (needs `glslc` + SPIR-V headers + libvulkan)\n- `.bat` / `*_parallel.bat` variants build the Windows DLLs.\n\n`make_dylibs.sh` (if present) just wraps these for a release (writes to a\nversioned `gpulibs/<VERSION>/`, passes `--clean`, and `--minimize-size` for\nCUDA). **Run the scripts one at a time**, always with `--clean` — a stale\n`~/.cache/llamafile-{cuda,rocm,vulkan}-build` is the usual \"first build fails\"\ncause (leftover objects that reference symbols upstream removed, e.g. the b10052\nCUDA split-buffer removal). `cuda.sh`/`rocm.sh` share `build-functions.sh`;\n`vulkan.sh` is standalone.\n\n### Verifying a GPU build actually succeeded (do not trust \"Successfully built\")\n\nThe parallel compile launches each `nvcc`/`hipcc`/`glslc` in the background.\n`compile_gpu_sources_parallel` (cuda/rocm) now reaps each job and fails loudly,\nbut `vulkan.sh`'s shader loops do **not** yet check per-job status — a single\nfailed source can still be dropped while the link proceeds and prints\n\"Successfully built\" with a silently incomplete `.so`. So always confirm, don't\nassume:\n\n```bash\nllamafile/cuda.sh --clean --output /tmp/ggml-cuda.so --minimize-size 2>&1 | tee /tmp/b.log\ngrep -c 'error:' /tmp/b.log          # must be 0\ngrep 'Linking'   /tmp/b.log          # object count should match the source count\n```\n\nIf a source fails to compile, fix the root cause (a new upstream cuBLAS call\nmissing from TinyBLAS is a recurring one — see `update_llamacpp.md`), never let\nthe \"success\" line stand in for a green build.\n\n### Vulkan speed paths depend on the glslc/SDK version\n\n`vulkan.sh` probes the build host's `glslc` for shader extensions\n(coopmat, coopmat2, integer-dot, bf16, fp4/fp8) — mirroring upstream's\n`ggml-vulkan/CMakeLists.txt` `test_shader_extension_support`. Each probe that\nfails drops that acceleration pipeline from the shipped dylib (correct output,\njust slower on hardware that supports it). Distro `shaderc` (Ubuntu, SteamOS)\nis typically **too old** — it doesn't know `GL_EXT_integer_dot_product`,\n`GL_EXT_bfloat16`, `GL_NV_cooperative_matrix2`, and can't target\n`--target-env=vulkan1.4`. For a full-featured release Vulkan dylib, build on a\nhost with a recent **LunarG Vulkan SDK** (1.4.x); after installing, `source`\nits `setup-env.sh` so `vulkan.sh` picks up the SDK's `glslc`, then re-run the\nbuild and confirm the probes now print \"supported\". Keep `vulkan.sh`'s probe\nlist in sync with the CMakeLists (it must probe all seven feature tests).\n\n### CUDA `--minimize-size` drops IQ-quant kernels (CPU fallback)\n\nThe release CUDA dylib is built with `--minimize-size`, which (among the size\noptions) passes `-DGGML_CUDA_NO_IQ_QUANTS`. That compiles out most IQ-quant\nCUDA paths — the MMQ/MMVQ matmul kernels in `mmq.cu`/`mmvq.cu`, the bf16/fp16\ndequant converters in `convert.cu`, and the `f32→iq4_nl` copy in `cpy.cu`\n(`ggml_get_to_fp32_cuda`'s IQ cases stay unguarded, so the `float` dequant\ninstantiations still compile — a minor size cost).\nThe payoff is a much smaller `.so`; the cost is that it cannot run IQ-quantized\ntensors on the GPU.\n\n`ggml_backend_cuda_device_supports_op` is guarded by the same macro: the IQ\ncases in the `MUL_MAT`/`MUL_MAT_ID` and `CPY` switches sit inside\n`#ifndef GGML_CUDA_NO_IQ_QUANTS`. So a minimized build honestly reports those\nops unsupported and the scheduler runs them on the CPU backend — correct\noutput, just slower for the IQ layers. **Without that guard the op is\ndispatched to a kernel that was never compiled and aborts at\n`GGML_ASSERT(convert_func != nullptr)` (`ggml-cuda.cu`)** — this is exactly\nwhat `backend_ops_test` hit on `iq2_xxs` MUL_MAT. If you add or bump IQ\nhandling, keep the `supports_op` cases and their kernels behind the same macro\nor the mismatch reappears. (ROCm shares `ggml-cuda.cu`, but its build does not\ndefine the macro, so IQ stays enabled there.)\n\nFor a CUDA dylib that runs IQ quants on the GPU, build without the flag — drop\n`--minimize-size` (or use its other pieces like `--minimal-archs`/`--strip`\nwithout `--no-iq-quants`) — at the cost of a larger library. The ROCm, Vulkan,\nand Metal builds are not size-minimized, so none of them strips IQ the way the\nCUDA build does: ROCm shares this file with the macro undefined, so it keeps the\nfull IQ mul_mat set; Metal and Vulkan keep whatever IQ ops their own backends\nimplement (Vulkan's `supports_op` still declines some IQ mul_mat/cpy shapes, but\nit declines cleanly and falls back to CPU rather than crashing — which, after\nthis fix, is exactly how CUDA behaves too).\n\n## Troubleshooting\n\n### \"make: command not found\" or Wrong Make\n\nEnsure using the cosmocc make:\n\n```sh\n# Wrong\nmake -j $(nproc)\n\n# Correct\n.cosmocc/4.0.2/bin/make -j $(nproc)\n\n# Or use the command directly:\n# llamafile:build\n```\n\n### Submodule Not Initialized\n\nIf build fails with missing files in llama.cpp/whisper.cpp/stable-diffusion.cpp:\n\n```sh\nmake setup\n```\n\n### Stale Object Files\n\nAfter significant changes, clean and rebuild:\n\n```sh\n.cosmocc/4.0.2/bin/make clean          # or: llamafile:clean\n.cosmocc/4.0.2/bin/make -j $(nproc)   # or: llamafile:build\n```\n\n### Toolchain Checksum Mismatch\n\nIf `download-cosmocc.sh` fails verification, check:\n1. Correct version specified\n2. Correct checksum for that version\n3. Network connectivity\n\n<!-- File: docs/skills/llamafile/development.md (Tokens: ~1285 | Category: anthropic-skill) -->\n# Llamafile Development Workflow\n\nGuide to modifying code, managing patches, and working with submodules.\n\n## Development Overview\n\nLlamafile development involves two distinct workflows:\n\n1. **Core code changes**: Direct edits to root-level directories such as `llamafile/`, `whisperfile/`, etc.\n2. **Submodule changes**: Patch-based modifications to `llama.cpp`, `whisper.cpp`, `stable-diffusion.cpp`\n\n## Modifying Core Code\n\nFor changes which are not affecting submodules:\n\n### Workflow\n\n1. Edit files\n2. Rebuild: `llamafile:build`\n3. Test: `llamafile:check`\n4. Commit changes normally with git\n\n### Key Directories\n\n```\nllamafile/\n├── server/      # HTTP server, API endpoints\n├── highlight/   # Syntax highlighting\n├── tinyblas/    # Optimized BLAS kernels\n└── *.c, *.h     # Core utilities\n```\n\n## Modifying Submodule Code\n\nSubmodules require a patch-based workflow because:\n- Submodules point to specific upstream commits\n- Direct commits in submodules would be lost\n- Patches preserve modifications across submodule updates\n\n### Understanding the Patch System\n\nEach submodule has a patches directory. For instance, for `llama.cpp`:\n\n```\nllama.cpp.patches/\n├── README.md              # Patching info + list of all patches and their purpose\n├── apply-patches.sh       # Script to apply all patches to llama.cpp submodule\n├── renames.sh             # Script for file renames/moves (if any)\n├── llamafile-files/       # Additional files to copy into llama.cpp\n│   ├── BUILD.mk           # Makefile for building llama.cpp with cosmocc\n│   └── README.llamafile   # License and modification notes\n└── patches/               # Patch files for upstream sources\n```\n\nPatches are applied by `make setup`:\n1. Submodule is reset to clean state\n2. Each .patch file is applied in alphabetical order\n3. Files from llamafile-files/ are copied into the submodule\n\n### Making Changes to a Submodule\n\n#### Step 1: Make Changes\n\nEdit files directly in the submodule directory:\n\n```sh\ncd llama.cpp\n# Make your changes\nvim src/llama.cpp\n```\n\n#### Step 2: Generate Patches\n\nPatches are usually generated after the code has been thoroughly tested and is\nready to commit. To avoid manual errors, use the script `tools/generate_patches.sh`\n(or the `llamafile:generate-patches` skill that wraps it), which automatically\nsaves all new files and patches in the specified output directory.\n\n```sh\n# echo y answers the prompt; the subshell restores the cwd even on failure\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nAfter this operation, one can double check which files have been modified / added\nvia a `git diff`.\n\nNaming convention:\n- all patches have a `.patch` extension\n- patch filenames reflect the file path with underscores replacing slashes (e.g., `common_arg.cpp.patch` for `common/arg.cpp`).\n\n\n#### Step 3: Verify Patches\n\nOnce you are sure all patches have been saved, reset and reapply to verify:\n\n```sh\n# Reset everything\nmake reset-repo\n\n# Reapply patches\nmake setup\n\n# Rebuild and test\n# llamafile:build\n# llamafile:check\n```\n\n### Adding New Files to Submodules\n\nFor new files (not modifications), use llamafile-files/:\n\n```sh\n# Create directory structure matching submodule\nmkdir -p llama.cpp.patches/llamafile-files/src/\n\n# Add your new file\ncp new-utility.cpp llama.cpp.patches/llamafile-files/src/\n```\n\nThe file will be copied into the submodule during `make setup`.\n\n### Updating BUILD.mk for Submodules\n\nEach submodule needs a BUILD.mk in llamafile-files/:\n\n```makefile\n# llama.cpp.patches/llamafile-files/BUILD.mk\n\nLLAMA_SRCS = \\\n    llama.cpp/src/llama.cpp \\\n    llama.cpp/src/new-file.cpp    # Add new files here\n\nLLAMA_OBJS = $(LLAMA_SRCS:%.cpp=o/$(MODE)/%.o)\n\n# ... rest of build rules\n```\n\n## Submodule Management\n\n### Resetting a Single Submodule\n\nTo discard changes in one submodule:\n\n```sh\ncd llama.cpp\ngit reset --hard\ngit clean -fdx\n```\n\nThen reapply patches:\n\n```sh\ncd ..\nmake setup\n```\n\n### Resetting All Submodules\n\nTo reset everything (warning: loses all local changes):\n\n```sh\nmake reset-repo\nmake setup\n```\n\n\n## Git Workflow\n\n### Committing Changes\n\nFor core code changes:\n```sh\ngit add llamafile/modified-file.c\ngit commit -m \"Fix: description\"\n```\n\nFor submodule patches:\n```sh\ngit add llama.cpp.patches/patches/new-patch.patch\ngit commit -m \"llama.cpp: Add feature X\"\n```\n\n### Pull Request Checklist\n\nBefore submitting changes:\n\n1. [ ] Patches apply cleanly from fresh clone\n2. [ ] Build succeeds: `llamafile:build`\n3. [ ] Tests pass: `llamafile:check`\n4. [ ] Patches are focused and documented\n5. [ ] BUILD.mk updated if adding new files\n\n## Debugging Tips\n\n### Viewing Applied Patches\n\nTo see what patches are currently applied:\n\n```sh\ncd llama.cpp\ngit log --oneline HEAD...$(git rev-parse --short @{u} 2>/dev/null || echo \"origin/master\")\n```\n\n### Checking Submodule State\n\n```sh\ngit submodule status\n```\n\nOutput shows:\n- `-` : Not initialized\n- `+` : Different commit than recorded\n- ` ` : Clean, matches recorded commit\n\n### Finding Which Patch Changed a File\n\n```sh\ngrep -l \"filename\" llama.cpp.patches/patches/*.patch\n```\n\n<!-- File: docs/skills/llamafile/SKILL.md (Tokens: ~1630 | Category: anthropic-skill) -->\n---\nname: llamafile\ndescription: This skill should be used when the user asks to \"build llamafile\", \"rebuild llamafile\", \"run llamafile\", \"run llamafile tests\", \"debug llamafile\", \"set up llamafile\", \"update patches\", \"fix patch conflict\", \"update llama.cpp\", \"pull latest llama.cpp\", \"sync upstream llama.cpp\", \"reset submodules\", \"write a test for llamafile\", \"how does llamafile work\", \"llamafile architecture\", or needs guidance on the llamafile build system, patch workflow, submodule integration, cosmocc toolchain, or development practices.\nversion: 0.1.6\n---\n\n# Llamafile Development Guide\n\nLlamafile combines llama.cpp, whisper.cpp, and stable-diffusion.cpp with Cosmopolitan Libc to create single-file executables that run LLMs locally across Windows, macOS, Linux, and BSD without installation.\n\n## Version Disambiguation\n\n- **New llamafile** (or simply \"llamafile\"): The code in the `main` branch, used for releases >=0.10.0\n- **Old/Classic llamafile**: The legacy code, used for releases until 0.9.3 (see commit 7e7d33c).\n\nThis guide covers the **new llamafile** project.\n\n## Quick Reference\n\n### Initial Setup\n\n```sh\nmake setup\n```\n\nImmediately after cloning the repo (or after a reset done with `make reset-repo`), this command initializes git submodules and applies llamafile-specific patches.\n\n### Building\n\nRun `llamafile:build` to build all targets.\n\n### Testing\n\nRun `llamafile:check` to run the unit test suite.\n\n### Cleaning\n\nRun `llamafile:clean` to remove all build outputs.\n\n### Reset Submodules\n\nAfter `make setup`, submodules contain patches and are no longer in a clean state.\nTo reset them, run:\n\n```sh\nmake reset-repo  # Warning: removes all local changes\n```\n\nWARNING: this command removes all local changes. Do not run it without first generating patches from any modifications.\n\n### Patch & Upstream-Update Commands\n\nWhen changing submodule patches or bumping llama.cpp, use the dedicated commands\nrather than ad-hoc `git diff`/`git apply`:\n\n- `llamafile:generate-patches` — regenerate patches from in-place submodule edits\n  (the only sanctioned way to produce patches).\n- `llamafile:verify-clean` — clean round-trip (`reset-repo` → `setup` → clean\n  build → `check`); the verification after generating patches or any patch change.\n\nFor the full llama.cpp bump procedure, follow `update_llamacpp.md` step by step.\n\n\n## Core Workflows\n\n### Building from Scratch\n\nTo build llamafile from a fresh clone:\n\n1. Clone the repository\n2. Run `make setup` to initialize submodules and apply patches\n3. Build with `llamafile:build`\n\nBuild outputs appear in `o/$(MODE)/` directory.\n\n### Modifying Core Code\n\nFor changes to llamafile's own code (not submodules):\n\n1. Edit files in `llamafile/` directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\n### Modifying Submodule Code\n\nSubmodules (llama.cpp, whisper.cpp, stable-diffusion.cpp) require a patch-based workflow:\n\n1. Make changes directly in the submodule directory\n2. Rebuild with `llamafile:build`\n3. Run unit tests with `llamafile:check`\n\nNOTE: never try to edit patches or generate them manually. This step is \ndone only after rebuild and tests (even manual ones) are successful. See\n`development.md` for detailed patch workflow.\n\n### Running Specific Tests\n\nTests use the `.runs` pattern in BUILD.mk files:\n\n```makefile\no/$(MODE)/llamafile/json_test.runs\n```\n\nTo run all tests: `llamafile:check`\n\n## Key Concepts\n\n### Cosmopolitan Toolchain\n\nThe project uses Cosmopolitan Libc (cosmocc) to create Actually Portable Executables (APE) - single files that run on multiple platforms without modification. Always use the `llamafile:build`, `llamafile:check`, and `llamafile:clean` commands (which use cosmocc's make), not system make.\n\n### Patch System\n\nEach submodule has a corresponding patches directory:\n- `llama.cpp.patches/`\n- `whisper.cpp.patches/`\n- `stable-diffusion.cpp.patches/`\n\nPatches include:\n- **Modifications** (.patch files): Changes to upstream code\n- **Additions** (llamafile-files/): New files for integration (BUILD.mk, utilities)\n\n### Build System\n\n- **build/config.mk**: Compiler and toolchain configuration\n- **build/rules.mk**: Generic build patterns (.c → .o, archives, asset bundling)\n- **BUILD.mk files**: Per-package build logic\n\nOutputs: `o/$(MODE)/package/file.o`\n\n### Multi-Architecture Support\n\nBinaries include both x86_64 and aarch64 code paths with runtime CPU feature detection (AVX, AVX2, AVX-512, ARM NEON).\n\n### GPU Backend Loaders\n\nDynamically-loaded backends that export the ggml C ABI — CUDA, ROCm, Vulkan — all go through the shared probe core in `llamafile/gpu_backend.c`. Each is just a `GpuBackendDesc` + a link thunk; the core does load → log-suppress → **device-count gate** (reject 0-device DSOs so AUTO falls back) → register, with a SIGSEGV/SIGABRT crash guard around the foreign probe call (driver init can fault across the cosmo/ms_abi boundary — issue #988). Metal stays separate by design (runtime-compiled, no ms_abi split, no device gate). When adding/changing a backend: route it through the core, keep the gate, and add a case to `tests/gpu_backend_test.cpp`. A more detailed design doc lives separately.\n\n## Main Executables\n\nAfter building, find binaries in `o/$(MODE)/`:\n\n| Binary | Purpose |\n|--------|---------|\n| `llamafile/llamafile` | Main llamafile executable |\n| `third_party/zipalign/zipalign` | Bundle assets into executables |\n| `whisperfile/whisperfile` | Main whisperfile executable |\n\n## Troubleshooting\n\n### Build Fails After Submodule Update\n\nRun `make setup` to reapply patches after any submodule changes.\n\n### Submodule Has Uncommitted Changes\n\nTo reset a single submodule:\n```sh\ncd <submodule> && git reset --hard && git clean -fdx\n```\n\nTo reset all submodules:\n```sh\nmake reset-repo\n```\n\n### Wrong Make Being Used\n\nEnsure using the `llamafile:build` command (which uses cosmocc's make), not system make.\n\n## Additional Resources\n\n### Reference Files\n\nFor detailed information, consult:\n- **`building.md`** - Complete build system documentation, toolchain details\n- **`architecture.md`** - Repository structure, component overview\n- **`development.md`** - Development workflow, patch management, submodule integration\n- **`testing.md`** - Test patterns, running and writing tests\n- **`update_llamacpp.md`** - Keeping llamafile updated with upstream llama.cpp\n\n### Project Documentation\n\n- **README.md** in repo: Project introduction\n- **docs/** directory: User documentation (quickstart, installation, troubleshooting)\n- **RELEASE.md**: Release process\n- Most executables support `--help`\n\n<!-- File: docs/skills/llamafile/testing.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Llamafile Skill\n\nPath: `docs/skills/llamafile/testing.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/testing.md)\n\n<!-- File: docs/skills/llamafile/update_llamacpp.md (Tokens: ~300 | Category: anthropic-skill) -->\n# Llamafile Skill\n\nPath: `docs/skills/llamafile/update_llamacpp.md`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/mozilla-ai/llamafile/HEAD/docs/skills/llamafile/update_llamacpp.md)\n\n<!-- File: .llamafile_plugin/.claude-plugin/marketplace.json (Tokens: ~129 | Category: marketplace) -->\n{\n  \"name\": \"llamafile-local\",\n  \"description\": \"Local llamafile plugin marketplace\",\n  \"owner\": {\n    \"name\": \"Mozilla AI\",\n    \"email\": \"davide@mozilla.ai\"\n  },\n  \"plugins\": [\n    {\n      \"name\": \"llamafile\",\n      \"description\": \"Build guidance and commands for the llamafile project\",\n      \"version\": \"0.1.7\",\n      \"author\": {\n        \"name\": \"Mozilla AI\",\n        \"email\": \"davide@mozilla.ai\"\n      },\n      \"source\": \"./\"\n    }\n  ]\n}\n\n<!-- File: .llamafile_plugin/.claude-plugin/plugin.json (Tokens: ~37 | Category: plugin-manifest) -->\n{\n  \"name\": \"llamafile\",\n  \"version\": \"0.1.7\",\n  \"description\": \"Build guidance and commands for the llamafile project\"\n}\n\n<!-- File: docs/commands/build.md (Tokens: ~197 | Category: command-prompt) -->\n---\ndescription: Build llamafile using the cosmocc toolchain\n---\n\n# Build Llamafile\n\nBuild the project using the Cosmopolitan toolchain.\n\nFirst, ensure the toolchain is available:\n\n```bash\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\n```\n\nThen build:\n\n```bash\n.cosmocc/4.0.2/bin/make -j $(nproc)\n```\nAdapt `nproc` to the OS where you are building, (e.g. `sysctl -n hw.physicalcpu` on mac)\n\nBuild outputs will be in `o/$(MODE)/`.\n\n<!-- File: docs/commands/check.md (Tokens: ~49 | Category: command-prompt) -->\n---\ndescription: Run llamafile unit tests\n---\n\n# Run Llamafile Tests\n\nRun the unit test suite using the Cosmopolitan toolchain.\n\n```bash\n.cosmocc/4.0.2/bin/make check\n```\n\n<!-- File: docs/commands/clean.md (Tokens: ~48 | Category: command-prompt) -->\n---\ndescription: Clean llamafile build outputs\n---\n\n# Clean Llamafile Build\n\nRemove all build outputs from the `o/` directory.\n\n```bash\n.cosmocc/4.0.2/bin/make clean\n```\n\n<!-- File: docs/commands/generate-patches.md (Tokens: ~436 | Category: command-prompt) -->\n---\ndescription: Regenerate llamafile patches from in-place submodule edits\n---\n\n# Generate Patches\n\nCapture the current in-place edits of a submodule as patch files, using the\nproject's `generate_patches.sh` tool. This is the **only** sanctioned way to\nproduce patches — never hand-craft them with `git diff` (the tool rewrites the\n`a/`,`b/` paths to be repo-rooted, strips the volatile `index` line, names files\nby convention, and routes new/untracked files into `llamafile-files/`; a raw\n`git diff` gets all of that wrong).\n\nRun it for the `llama.cpp` submodule (the common case). The tool is general and\nworks for any submodule — swap the directory and output path for `whisper.cpp`\nor `stable-diffusion.cpp`.\n\nThe subshell keeps the working directory restored even if the tool fails, and\n`echo y` answers the script's confirmation prompt non-interactively:\n\n```bash\n( cd llama.cpp && echo y | ../tools/generate_patches.sh --output-dir ../llama.cpp.patches )\n```\n\nOutput lands in `llama.cpp.patches/patches/` (modified files) and\n`llama.cpp.patches/llamafile-files/` (new files, including `BUILD.mk`).\n\nThe tool **only writes/overwrites — it never deletes**. If you dropped a patch\nduring a bump (the file is no longer modified, e.g. upstream absorbed the\nchange), its old `.patch` will still be sitting in `patches/` and will keep\nbeing applied by `setup`. `git rm` each dropped patch by hand, and confirm the\nfinal count (`ls llama.cpp.patches/patches | wc -l`) matches your intent.\n\nIMPORTANT: only run this **after** the in-place edits are proven to work\n(a clean build succeeds and llamafile runs as expected). Generating patches\nfrom unproven edits bakes in breakage. After generating, verify the patch set\nround-trips with `llamafile:verify-clean`.\n\n<!-- File: docs/commands/verify-clean.md (Tokens: ~528 | Category: command-prompt) -->\n---\ndescription: Clean round-trip — reset, re-apply patches, clean build, and test\n---\n\n# Verify Clean\n\nVerify the repository from a clean slate: reset, re-pull submodules and\nre-apply patches, then do a **clean** build and run the tests. Use this:\n\n- as the final verification after `llamafile:generate-patches` (confirms the\n  regenerated patches re-apply cleanly and still build), and\n- any time patches or submodules change and you need a trustworthy result.\n\nWhy a clean build: after a `reset-repo`/`setup`, submodule sources change\nwithout their timestamps necessarily moving, so an incremental `make` can link\nstale objects. Always `make clean` first here — do not rebuild incrementally.\n\n`make setup` both pulls submodules and applies patches, and it cannot pull\nsubmodules onto a dirty tree — that is exactly why `reset-repo` runs first.\n\nNote: `reset-repo` is destructive (it `rm -rf`s the submodule dirs before\nrestoring them), so a permission-gated environment may prompt or block it. Run\nit through the `$MAKE` (`.cosmocc/.../make`) form below rather than raw\n`git clean`/`reset`; allowlist `make reset-repo` if round-trips keep stalling.\n\n```bash\n# ensure the toolchain is available\nif [ ! -d .cosmocc/4.0.2 ]; then\n  build/download-cosmocc.sh .cosmocc/4.0.2 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44\nfi\nMAKE=.cosmocc/4.0.2/bin/make\n\n$MAKE reset-repo     # clean: drop all local changes, reset submodules\n$MAKE setup          # pull submodules + apply patches (+ fetch UI assets)\n$MAKE clean          # drop stale build outputs\n$MAKE -j$(nproc)     # clean build; on mac use -j$(sysctl -n hw.physicalcpu)\n$MAKE check          # unit tests\n```\n\nA successful round-trip proves the committed patch set is internally\nconsistent. It does NOT cover GPU runtime backends, non-host platforms, the\nweb UI, or long-run stability — see the handoff checklist in\n`update_llamacpp.md`.\n</yakaai_skills>"}