Metadata-Version: 2.4
Name: alpielocal
Version: 10.10.16
Summary: AlpieLocal
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: huggingface_hub>=0.20.0
Requires-Dist: rich>=13.0
Requires-Dist: click>=8.0
Requires-Dist: httpx[http2]>=0.24.0
Requires-Dist: beautifulsoup4>=4.12.0
Requires-Dist: yt-dlp>=2024.0.0
Requires-Dist: prompt-toolkit>=3.0.0
Requires-Dist: packaging>=23.2
Requires-Dist: Pillow>=10.0.0
Provides-Extra: vision
Requires-Dist: Pillow>=10.0.0; extra == "vision"
Provides-Extra: browser
Requires-Dist: playwright>=1.48.0; extra == "browser"
Provides-Extra: server
Requires-Dist: fastapi>=0.100.0; extra == "server"
Requires-Dist: uvicorn>=0.20.0; extra == "server"
Requires-Dist: sse-starlette>=2.0.0; extra == "server"
Provides-Extra: ffmpeg
Requires-Dist: imageio-ffmpeg>=0.4.0; extra == "ffmpeg"

# AlpieLocal

From a source checkout, install into your active Python environment to register
the `alpielocal` command:

```sh
python -m pip install -e .
alpielocal
alpielocal run "Fix the bug in this project"
alpielocal "Explain this codebase"
```

`python -m alpielocal` runs the same CLI. Existing configuration and model
directories from earlier installations remain readable.

[![Python Version](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12-blue.svg)](https://www.python.org/)
[![Version](https://img.shields.io/badge/alpielocal-v10.0.2-emerald.svg)](https://github.com/169Pi/codeagent-poc)
[![VS Code Extension](https://img.shields.io/badge/vscode%20extension-v8.0.8-blueviolet.svg)](https://marketplace.visualstudio.com/)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.100%2B-009688.svg)](https://fastapi.tiangolo.com/)
[![Jupyter & Colab](https://img.shields.io/badge/Jupyter%20%7C%20Colab-Ready-f37726.svg)](https://colab.research.google.com/)
[![Platforms](https://img.shields.io/badge/platform-Linux%20%7C%20WSL2%20%7C%20macOS%20%7C%20Windows-lightgrey.svg)](https://github.com/169Pi/codeagent-poc)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

> **Powered by 169Pi Alpie Vision-Language-Action Models (Local GGUF & Remote Cloud API)**  
> *An enterprise-grade, autonomous software engineering agent seamlessly integrated across the Command Line (CLI), VS Code Extension, FastAPI Backend Server, Python SDK, Jupyter Notebooks, and Google Colab.*

---

## 📑 Table of Contents
1. [🌟 Overview & Capabilities](#-overview--capabilities)
2. [🏗️ Core Architecture & Hybrid Dual-Engine](#️-core-architecture--hybrid-dual-engine)
3. [⚡ System 1 (Jev Architecture) & Performance Engine](#-system-1-jev-architecture--performance-engine)
4. [📊 Performance & Optimization Benchmarks](#-performance--optimization-benchmarks)
5. [📦 Complete Installation Guide](#-complete-installation-guide)
6. [🚀 Backend API Server (`alpielocal serve`)](#-backend-api-server-alpielocal-serve)
7. [⌨️ Command-Line Interface (CLI) Full Reference](#️-command-line-interface-cli-full-reference)
8. [💻 VS Code Extension Deep-Dive](#-vs-code-extension-deep-dive)
9. [🐍 Python SDK Reference (Programmatic Usage)](#-python-sdk-reference-programmatic-usage)
10. [📓 Jupyter Notebooks, JupyterLab & Google Colab](#-jupyter-notebooks-jupyterlab--google-colab)
11. [🛠️ 15 Built-In Autonomous Agent Tools](#️-15-built-in-autonomous-agent-tools)
12. [🛡️ Safety Guardian, Git Checkpoints & Memory System](#️-safety-guardian-git-checkpoints--memory-system)
13. [⚙️ Configuration & Environment Variables](#️-configuration--environment-variables)
14. [❓ FAQ & Troubleshooting](#-faq--troubleshooting)

---

## 🌟 Overview & Capabilities

**AlpieLocal** is an autonomous software engineering assistant that acts as a principal developer in your repository. Rather than simply generating isolated snippets, AlpieLocal operates as a full-loop agent:
- **Discovers & Understands**: Recursively indexes codebases, reads files, and executes ripgrep regex searches.
- **Reasons & Plans**: Formulates implementation plans, manages checkpointed deliverables, and explains complex architectures.
- **Generates & Modifies**: Writes production code, applies surgical whitespace-accurate diff patches, and refactors existing components.
- **Executes & Self-Heals**: Executes commands in an isolated sandbox, automatically captures build/test errors, and iterates until tests pass.
- **Works Everywhere**: From the terminal and VS Code sidebar to automated Python scripts and interactive Google Colab notebooks.

### 🎯 Feature Matrix Across Interfaces
| Feature / Capability | CLI | VS Code Extension | Python SDK | Jupyter & Colab |
| :--- | :---: | :---: | :---: | :---: |
| **Autonomous Coding Loops (`run`)** | ✅ | ✅ | ✅ | ✅ |
| **Multi-Turn Interactive Chat** | ✅ | ✅ | ✅ | ✅ |
| **Architectural Planning (`plan`)** | ✅ | ✅ | ✅ | ✅ |
| **Deep Code Explanation (`explain`)** | ✅ | ✅ | ✅ | ✅ |
| **Interactive Diff / Plan-First Review** | — | ✅ (Accept/Reject/Edit) | — | — |
| **Inline Ghost-Text Code Autocomplete** | — | ✅ (Tab to accept) | — | — |
| **Live Token Speed & Counter Meter** | — | ✅ | — | ✅ |
| **Multimodal Vision (Images/Screenshots)** | ✅ (`--image`) | ✅ (Paste / Upload) | ✅ | ✅ |
| **Video & YouTube URL Analysis** | ✅ (`--video`, `--url`) | — | ✅ | — |
| **Autonomous GitHub Repo Analysis** | ✅ (`--github`) | ✅ | ✅ | — |
| **Proactive `.venv` & Dependency Setup** | ✅ | ✅ | ✅ | ✅ |
| **Persistent Project Memory** | ✅ | ✅ | ✅ | ✅ |
| **Zero-Crash Smart GGUF Fallback** | ✅ | ✅ | ✅ | ✅ |

---

## 🏗️ Core Architecture & Hybrid Dual-Engine

AlpieLocal employs an intelligent **Hybrid Dual-Engine** routing system that pairs the speed and depth of cloud Vision-Language-Action models with the resilience of completely offline local GGUF models.

```
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                                     CLIENT LAYER                                       │
│   VS Code Extension        Terminal CLI          Python SDK       Jupyter / Colab      │
│   (Sidebar & Ghost-Text)  (alpielocal run/chat)  (import alpielocal)   (%alpie / %%alpie)│
└──────────────────────────┬───────────────────────┬──────────────────────┬──────────────┘
                           │                       │                      │
                           ▼                       ▼                      ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                        FASTAPI BACKEND SERVER (`alpielocal serve`)                      │
│   • POST /chat (SSE Stream)   • POST /completion (Inline Ghost)   • GET /sessions      │
│   • POST /cancel/{id}         • GET /health                       • GET /metrics       │
└──────────────────────────────────────────┬─────────────────────────────────────────────┘
                                           │
                                           ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                                  AGENT ORCHESTRATOR                                    │
│   • 5-Layer Context Assembly (System + Summary + Anchors + Turns + Request)            │
│   • Rolling Compaction with Lazy-Cached Summaries                                      │
│   • Session State Isolation & Reentrancy Guards                                        │
│   • Persistent Cross-Session Memory (~/.alpielocal/memories/)                           │
└──────────────────────────────────────────┬─────────────────────────────────────────────┘
                                           │
                                           ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                               HYBRID DUAL-ENGINE ROUTER                                │
│                                                                                        │
│                   ┌──────────────────────────────────────────────┐                     │
│                   │        Active Internet Connectivity?         │                     │
│                   └──────────────┬────────────────┬──────────────┘                     │
│                                  │                │                                    │
│                            YES (Online)       NO (Offline)                             │
│                                  │                │                                    │
│                                  ▼                ▼                                    │
│                   ┌────────────────────────┐   ┌────────────────────────┐              │
│                   │      OpenAIBackend     │   │      LocalBackend      │              │
│                   │ (Remote 169Pi Cloud VLM│   │  (Local GGUF Engine)   │              │
│                   │   High-Throughput API) │   │  (Zero Internet Req.)  │              │
│                   └────────────────────────┘   └────────────────────────┘              │
└──────────────────────────────────────────┬─────────────────────────────────────────────┘
                                           │
                                           ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│                             15 AUTONOMOUS AGENT TOOLS                                  │
│   write_file  •  edit_file  •  read_file  •  apply_patch  •  bash  •  list_files       │
│   file_search •  view_image •  fetch_url  •  web_search   •  clone_repo • update_plan  │
│   extract_memories • compact_context • diagnostics                                     │
│                                          │                                             │
│                                          ▼                                             │
│                           SAFETY GUARDIAN & SANDBOX GATE                               │
│              (Blocks destructive commands, enforces paths, sandbox execution)          │
└────────────────────────────────────────────────────────────────────────────────────────┘
```

### ⚡ Smart Fallback Resilience
- **Network-Aware Routing**: Local GGUF fallback triggers **only when internet is genuinely unavailable**, preventing unnecessary model loading on brief cloud API delays or transient server timeouts (which are retried automatically).
- **Sanitized Chat Templates**: Converts complex multi-turn OpenAI tool schemas and system structures into sanitized templates compatible with local Jinja2 GGUF renderers.
- **Zero Crashes**: If network drops mid-session, the agent gracefully recovers or provides clear diagnostic feedback.

---

## ⚡ System 1 (Jev Architecture) & Performance Engine

AlpieLocal introduces a **Dual-Process Cognitive Architecture** inspired by TypeSafe AI's **Jev (System 1)** framework:
- **System 1 (Fast Reflex & Decision Plane)**: A sub-5ms non-autoregressive decision engine that handles routine routing, parameter validation, test parsing, loop prevention, and error triage.
- **System 2 (Deep Thought & Generative Engine)**: The heavy reasoning LLM (169Pi Cloud VLA / Claude / GPT-4o online, or local Qwen GGUF offline) dedicated purely to code synthesis and architectural reasoning.

```
                  ┌──────────────────────────────────────────────┐
                  │              User Coding Task                │
                  └──────────────────────┬───────────────────────┘
                                         │
┌────────────────────────────────────────▼──────────────────────────────────────────────────┐
│ SYSTEM 1: Jev Decision Plane (<5ms)                                                       │
│ • Tool Call Validation   • Repeated Loop Detection   • Test Result Triage                 │
│ • Surgical Diff Enforcement                          • Context Noise Filtering            │
└────────────────────────────────────────┬──────────────────────────────────────────────────┘
                                         │
                     ┌───────────────────┴───────────────────┐
                     ▼                                       ▼
       ┌───────────────────────────┐           ┌───────────────────────────┐
       │   Online Cloud Backend    │           │    Offline Local Engine   │
       │   (169Pi / Claude / GPT)  │           │   (llama.cpp Qwen GGUF)   │
       │  • Sub-12s Task Completion│           │  • Zero Context Overflow  │
       │  • >75% Token Savings     │           │  • Zero Syntax Crash Loops│
       └───────────────────────────┘           └───────────────────────────┘
```

### Key Capabilities

1. **⚡ TypeSafe System 1 Decision Loop (`src/codeagent/system1.py`)**:
   - **Loop & Oscillation Detection**: Tracks tool call signatures. If the agent fails an operation twice (e.g. repeated syntax errors), System 1 intercepts the turn and forces a targeted `edit_file` directive rather than an infinite full-file rewrite.
   - **Automated Test Health Parser**: Fast regex engine parsing pytest, unittest, and npm test outputs in <1ms to determine test success without burning LLM inference.
   - **Tool Parameter Validator**: Pre-execution validation preventing malformed or missing parameters.

2. **🚀 Multi-Tier Caching System (`src/codeagent/cache.py`)**:
   - **`FileReadCache`**: In-memory cache for repeated file reads keyed by `(path, mtime, size, line_range)`. Cuts read latency from 1.2ms to **<0.05ms** (24x speedup).
   - **`TestResultCache`**: Disk-persisted cache in `~/.alpielocal/cache/test_cache.json` keyed by a workspace file fingerprint (`hash(mtimes)`). Unchanged test suites re-run in **<1ms** with zero redundant execution.
   - **`ResponseCache`**: Disk-backed LRU cache for pure text explanations and Q&A.

3. **🗜️ Context Noise Filtering (`src/codeagent/context.py`)**:
   - Compresses 50+ lines of clean passing test noise down to a 2-line summary (`[Clean Test Output]`).
   - On test failures, preserves critical tracebacks and failure frames while stripping passing test dots, achieving **>75% token reduction**.

4. **📊 Real-Time Performance Observability (`src/codeagent/metrics.py`)**:
   - At the conclusion of every task, AlpieLocal renders an end-of-task summary:
   ```text
   ╭──────────────────────── 📊 Task Performance Summary ────────────────────────╮
   │ ⏱️  Latency: 12.22s  |  🧠 LLM Calls: 2 (5425ms)                           │
   │ 🛠️  Tools Time: 153.5ms (1 calls)  |  📦 Context Prep: 6253ms  |  ⚡ Cache: 1│
   ╰─────────────────────────────────────────────────────────────────────────────╯
   ```

5. **📜 Agent Operational Guidelines (`agents.md`)**:
   - Operational rules defining the **Investigate → Plan → Surgical Edit → Verify → Complete** cycle, enforcing surgical diffs for files >100 lines and zero stub implementations.

---

## 📊 Performance & Optimization Benchmarks

Comprehensive benchmarks comparing AlpieLocal before vs. after the System 1 Jev engine and caching upgrade:

| Benchmark Metric | Baseline (v9.0) | With System 1 & Caching (v10.0.2) | Improvement |
| :--- | :---: | :---: | :---: |
| **Simple Test & Verify Task Latency** | 45.57s | **12.22s** | **3.7x faster (73% drop)** |
| **Repeated File Read Latency** | 1.20 ms | **<0.05 ms** | **24x faster** (In-Memory Cache) |
| **Unchanged Test Suite Re-run** | 3,500 ms | **<1.0 ms** | **Instant (Zero-Latency Cache)** |
| **Test Output Context Token Footprint**| ~3,500 tokens (500 lines) | **~80 tokens (4 lines)** | **>75% Context Compression** |
| **Syntax Error Retry Recovery** | Infinite full-file loop | **Loop intercepted on Turn 2** | Self-healing surgical diff |
| **Full Regression Test Suite** | 52 passed | **96 passed (100% green)** | Complete reliability |

---

## 📦 Complete Installation Guide

### 1. Prerequisites
- **Python**: `>= 3.9` (Recommended: Python 3.10, 3.11, or 3.12)
- **Platforms**:
  - **Linux**: Ubuntu 20.04+, Debian 11+, Fedora, Arch Linux
  - **Windows**: Native Windows 10/11 or Windows Subsystem for Linux (WSL2 / Ubuntu)
  - **macOS**: Apple Silicon (M1/M2/M3/M4) & Intel
- **Dev Tools (Recommended)**: `git`, `curl`, `ripgrep` (optional, falls back automatically)

---

### 2. Python Package Installation

#### Option A: Quick Install via pip (Any Virtual Environment)
Activate any virtual environment of your choice (`venv`, `conda`, `uv`, `virtualenv`, `poetry`) and install directly:
```bash
# 1. Activate your preferred virtual environment (e.g. venv)
python3 -m venv myenv
source myenv/bin/activate       # On Windows: myenv\Scripts\activate

# Or using Conda:
# conda create -n alpie python=3.11 -y && conda activate alpie

# 2. Install AlpieLocal
pip install alpielocal
```

#### Option B: From Source / Editable Mode (Recommended for Developers)
```bash
# Clone the repository
git clone https://github.com/169Pi/codeagent-poc.git
cd codeagent-poc

# Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install in editable mode with all dependencies
pip install -e .
```

#### Option C: From Wheel (.whl)
```bash
# Build the distribution
python3 -m pip install --upgrade build
python3 -m build

# Install the wheel
pip install dist/alpielocal-9.0.1-py3-none-any.whl
```

#### Verify CLI Installation:
```bash
alpielocal version
# Output: alpielocal 10.0.2

alpielocal doctor
```

---

### 3. VS Code Extension Installation

The VS Code extension provides the AI sidebar, plan-first review, and inline ghost-text completions.

#### Automatic Installation (Zero Configuration)
Simply launch the AlpieLocal backend server from your terminal:
```bash
alpielocal serve
```
If the VS Code extension is not already installed, AlpieLocal **automatically packages and installs the `.vsix` into VS Code**!

#### Manual Installation via CLI:
```bash
# Using the pre-built VSIX file
code --install-extension vscode/alpielocal-8.0.8.vsix
```

#### Manual Packaging (For Extension Developers):
```bash
cd vscode
npm install
npm run compile
npx @vscode/vsce package
code --install-extension alpielocal-8.0.8.vsix
```

---

## 🚀 Backend API Server (`alpielocal serve`)

The AlpieLocal FastAPI server runs as a high-concurrency daemon connecting local development environments, VS Code sidebars, remote IDEs, and external scripts to the autonomous agent engine.

### Launching the Server
```bash
# Default: binds to 127.0.0.1 on port 7169
alpielocal serve

# Custom Host and Port:
alpielocal serve --host 0.0.0.0 --port 8080
```

```text
    _    _     _      ____            _      
   / \  | |_ _| | ___ / ___|___   __| | ___ 
  / _ \ | | '_ \ |/ _ \ |   / _ \ / _` |/ _ \
 / ___ \| | |_) | |  __/ |__| (_) | (_| |  __/
/_/   \_\_|_.__/|_|\___|\____\___/ \__,_|\___|

✅ AlpieLocal VS Code extension is installed.
🚀 Starting AlpieLocal Server on http://127.0.0.1:7169
INFO:     Uvicorn running on http://127.0.0.1:7169 (Press CTRL+C to quit)
```

### REST & SSE API Endpoints Reference

| Method | Endpoint | Description | Payload / Parameters |
| :--- | :--- | :--- | :--- |
| `POST` | `/chat` | Executes an agent task, streaming events in real time via **Server-Sent Events (SSE)**. | `{"task": str, "workdir": str, "session_id": Optional[str], "image": Optional[str], "reasoning_level": "thinking"\|"high"\|"low"}` |
| `POST` | `/completion` | Provides ultra-low-latency inline code completions (ghost text) ahead of cursor. | `{"prompt": str, "suffix": str, "language": str, "max_tokens": int}` |
| `GET` | `/health` | Health diagnostic check reporting server uptime, backend availability, and cache stats. | *None* |
| `GET` | `/sessions` | Lists active multi-turn sessions with token counts and workspace paths. | *None* |
| `DELETE`| `/sessions/{session_id}` | Deletes a session container and cleans up associated resources. | `session_id` in path |
| `POST` | `/cancel/{session_id}` | Gracefully cancels an in-progress agent task. | `session_id` in path |
| `GET` | `/metrics` | Returns token usage, speeds, and agent execution performance statistics. | *None* |

---

## ⌨️ Command-Line Interface (CLI) Full Reference

The `alpielocal` CLI provides a developer-friendly command suite:

```text
usage: alpielocal [-h] [-v] [--workdir WORKDIR] [--image IMAGE] [--video VIDEO]
                 [--url URL] [--github GITHUB] [--max-turns MAX_TURNS]
                 [--thinking] [--no-thinking] [--no-update] [--quiet] [--debug]
                 {version,init,serve,run,chat,plan,diff,undo,doctor,explain} ...
```

---

### 1. `alpielocal run "<task>"`
Executes an end-to-end autonomous software engineering task:
```bash
# Standard task in the current directory:
alpielocal run "Create a FastAPI app with SQLite auth and JWT tokens"

# Specify a target project directory:
alpielocal run "Fix all failing pytest tests" --workdir /path/to/project

# Multimodal image analysis (mockup to code, UI bug fix):
alpielocal run "Implement this dashboard layout in React and Tailwind" --image ./mockup.png

# Video walkthrough or screen recording analysis:
alpielocal run "Reproduce and fix the UI crash shown in this screen recording" --video ./bug_repro.mp4

# Analyze a YouTube tutorial or demonstration URL:
alpielocal run "Implement the architecture explained in this video" --url "https://youtube.com/watch?v=xyz"

# Analyze and clone an open-source GitHub repository:
alpielocal run "Analyze the plugin architecture of this repo and summarize it" --github "psf/requests"

# Force deep reasoning mode or fast execution mode:
alpielocal run "Audit the cryptographic security of auth.py" --thinking
alpielocal run "Add docstrings to all functions in utils.py" --no-thinking

# Show full agent discovery intelligence and tool arguments:
alpielocal run "Refactor database migrations" --debug
```

---

### 2. `alpielocal chat`
Starts a persistent, interactive terminal REPL with multi-turn memory:
```bash
alpielocal chat
```
*Features:*
- Retains context, variable names, and architectural decisions across turns.
- Rolling compaction prevents context window overflow.
- Checkpoints git state after each turn for easy rollback.
- Exit anytime by typing `exit`, `quit`, or pressing `Ctrl+C`.

---

### 3. `alpielocal plan "<task>"`
Generates an actionable architectural plan **without making file modifications**:
```bash
alpielocal plan "Migrate the frontend from JavaScript to TypeScript"
```
*Process:*
1. Explores existing files and types (`list_files`, `file_search`, `read_file`).
2. Synthesizes a structured checklist plan with milestones.
3. Outputs clear implementation steps and risk assessments.

---

### 4. `alpielocal explain "<target>"`
Deep-dives into a local file, function, or technical concept:
```bash
# Explain a local file:
alpielocal explain src/codeagent/orchestrator.py

# Explain a technical concept or codebase component:
alpielocal explain "How does the rolling context compaction work in AlpieLocal?"
```

---

### 5. `alpielocal diff`
Inspects all file changes and diffs made by AlpieLocal since the last git checkpoint:
```bash
alpielocal diff
```

---

### 6. `alpielocal undo`
Instantly rolls back all file edits made during the last AlpieLocal session:
```bash
alpielocal undo
```

---

### 7. `alpielocal doctor`
Runs an instant system and environment diagnostic suite:
```bash
alpielocal doctor
```
*Health Checks:*
- **Python Runtime**: Python version and active virtual environment status.
- **Hardware Acceleration**: CUDA availability, GPU device name, and VRAM.
- **Network & Latency**: DNS resolution, ping latency (ms), and remote API reachability.
- **Compilers & Dev Tools**: Presence of `gcc`, `g++`, `git`, `node`, `java`, etc.
- **VS Code Extension**: Installation verification and version check.

---

### 8. `alpielocal init`
Save model preferences, cache the model and vision projector, and install/check the local runtime:
```bash
alpielocal init
```

`alpielocal` and the legacy `alpiecode` command use the same entry point. Existing
`.alpiecode` caches are reused so renaming the command does not download the model
again. A successful cached setup does not prove a fresh machine can access the
private model repository.

Setup installs pinned, hash-checked runtime wheels into the running Python
environment. It shows progress and never falls back to compiling from source.
Apple Silicon uses an arm64 Metal wheel; an Intel/Rosetta Python environment
cannot use that wheel. The bundled runtime has no Intel Mac wheel: use native
arm64 Python on Apple Silicon, or manually install a compatible runtime on Intel.
Ctrl+C cancels setup cleanly; rerun `alpielocal init` to reuse completed downloads.
Failure exits nonzero and does not mark offline onboarding complete. Passing
setup confirms cached files and an available engine, not model accuracy or
sufficient memory for every task. Test generation with:

```sh
alpielocal run "Say hello" --offline
```

The default `169Pi/alpie_learn_gguf` model uses a built-in credential from
`src/codeagent/credentials.py`. Ordinary installations include it, so users can
run `alpielocal init` without creating `.env`, a token file, or setting `HF_TOKEN`.
The credential applies only to that model repository and is not written to
`config.json`. If an older configured token is rejected, the downloader retries
with the built-in credential for both the text model and vision projector.

**Anyone receiving the source or package can extract the embedded credential.**
If it expires or is revoked, replace it in the source and distribute an updated
package. Existing installations must upgrade to receive that change. Custom
private model repositories still require their own authorized Hugging Face
login or `HF_TOKEN`; public repositories can be accessed anonymously.

As an optional override for existing private distributions, the package owner can supply a dedicated
read-only token scoped to `169Pi/alpie_learn_gguf` through the build environment
variable `ALPIELOCAL_BUILD_HF_TOKEN`, then run:

```sh
ALPIELOCAL_PRIVATE_BUILD=1 python -m build --wheel --outdir dist/private
```

This optional override is generated into build output and replaces the built-in
credential for that repository. Automatic source updates are disabled only for
packages with this override to avoid removing it. The ordinary package needs no
special build flags and retains its normal update behavior.

For optional Chromium page-load verification of generated websites:

```sh
python -m pip install -e '.[browser]'
python -m playwright install chromium
```

The page-load probe serves local assets and blocks external page requests. It
detects initialization errors, including errors caught and logged by the app.
Without Chromium, verification reports the limits of its static checks and
JavaScript mock. A syntax check or page-load check does not establish that cart,
filter, modal, or checkout interactions work; those require interaction tests.
Completion summaries are held until the verification gate passes, and missing
or duplicate DOM IDs include source excerpts for targeted repairs.

---

## 💻 VS Code Extension Deep-Dive

The AlpieLocal VS Code extension integrates directly into your daily IDE workflow.

```
┌────────────────────────────────────────────────────────┐
│  ALPIELOCAL CHAT                       ⚡ 48 tok/s · 1.4k│
├────────────────────────────────────────────────────────┤
│ 🤖 Mode: [Online Cloud VLM]    Reasoning: [High (Thinking)▼]
│                                                        │
│ 👤 Create a login endpoint with rate limiting.         │
│                                                        │
│ 🤖 ── Proposed Changes: auth.py ─────────────────────  │
│ ┌────────────────────────────────────────────────────┐ │
│ │ 📋 Change Plan Card                                │ │
│ │ - from flask import Flask                          │ │
│ │ + from flask import Flask, request, jsonify        │ │
│ │ + from flask_limiter import Limiter                │ │
│ │                                                    │ │
│ │ [✅ Accept]      [❌ Reject]      [✏️ Edit Request]  │ │
│ └────────────────────────────────────────────────────┘ │
│                                                        │
│ 📦 'flask_limiter' required but not installed.         │
│ [Create .venv & Install]   [Install Globally]  [Skip]  │
├────────────────────────────────────────────────────────┤
│ > Type /plan, /explain, /doctor, or ask a question...  │
│ [📎 Image] [📋 Plan-First: ON]             [Send ❯]    │
└────────────────────────────────────────────────────────┘
```

### 1. 📋 Plan-First Review & Change Approval Workflow
- When modifying existing files, AlpieLocal presents an interactive **Change Plan Card** with side-by-side / unified diffs (`-` red / `+` green).
- **`✅ Accept`**: Commits the change, opens the file in your active editor, and runs verification.
- **`❌ Reject`**: Discards the modification cleanly.
- **`✏️ Edit Request`**: Opens an inline input box to provide steering instructions (e.g. *"Use Redis backend for rate limiting"*).

---

### 2. 🗂️ Persistent Multi-Turn Conversation History
- **Active Thread Context**: Each chat conversation maintains a persistent `sessionId`. The model retains all prior turns, files discussed, and tool results.
- **History Drawer**: Click the **History** button (`🕒`) in the sidebar header to view, reload, or delete up to **50 past conversations** saved in VS Code global storage.

---

### 3. 🧠 Reasoning Level Selector
Toggle model behavior directly in the sidebar dropdown:
- 🧠 **High (Thinking)**: Maximal chain-of-thought reasoning, multi-step problem solving, and complex architectural design.
- ⚡ **Low (Fast)**: Direct code generation with zero reasoning overhead for quick one-liners and docstring edits.

---

### 4. ⚡ Slash Commands (`/`)
Type **`/`** in the chat input to invoke quick commands:
- `📋 /plan <task>` — Creates a structured architectural plan without modifying code.
- `💡 /explain <file>` — Explains code, architecture, or algorithms step-by-step.
- `🩺 /doctor` — Executes full system diagnostic checks in the chat window.

---

### 5. 🖱️ Right-Click Context Menu Actions
Highlight any code in your editor, right-click, and choose:
- **Fix This Error**: Automatically aggregates language diagnostics (errors, warnings) and selected code to generate an instant fix.
- **Generate Tests**: Writes unit tests (pytest, jest, etc.) for the selected function or class.
- **Explain Code**: Explains the selected snippet line-by-line.
- **Refactor / Optimize**: Cleans, modernizes, and improves the performance of the highlighted block.
- **Ask About Selection**: Prompts for a custom question regarding the highlighted code.

---

### 6. 👻 Inline Ghost-Text Code Autocomplete
As you write code in any file, AlpieLocal streams inline suggestions ahead of your cursor:
- Non-intrusive gray ghost-text suggestions.
- Press **`Tab`** to accept the suggestion, or keep typing to ignore.
- Intelligent debounce and circuit breakers ensure zero editor lag.

---

### 7. 🐍 Proactive Virtual Environment (`.venv`) Auto-Prompt
When generated code requires external libraries (`numpy`, `pandas`, `fastapi`, etc.):
- AlpieLocal scans the AST imports before execution.
- If packages are missing, an interactive prompt appears:
  ```text
  📦 'fastapi' is required but not installed in your active environment.
  🐍 No virtual environment detected. Create one?

  [Create .venv & Install]   [Install Globally]   [Skip]
  ```
- Choosing **Create .venv & Install** automatically spins up `.venv`, installs the packages, and runs the script using `.venv/bin/python3`.

---

### 8. 📊 Live Token & Speed Meter
Displays real-time performance indicators in the sidebar header:
`🟢 Online API` ── `⚡ 46 tok/s · 📊 1,820 tokens`

---

### 9. 📎 Multimodal Image Attachment
- Drag-and-drop UI screenshots directly into the chat.
- Paste images directly from your clipboard (**`Ctrl+V`** / **`Cmd+V`**).
- Click **`📎 Image`** to browse and attach mockups, architecture diagrams, or error screenshots.

---

### 10. ⚙️ Extension Settings (`settings.json`)
Configure AlpieLocal in your VS Code settings:
```json
{
  "alpielocal.serverUrl": "http://127.0.0.1:7169",
  "alpielocal.showReasoning": true,
  "alpielocal.enableAutocomplete": true,
  "alpielocal.autoRunCode": true,
  "alpielocal.autoFixErrors": true,
  "alpielocal.planFirstReview": true,
  "alpielocal.githubUsername": "my-github-handle",
  "alpielocal.confirmGitPush": true
}
```

---

## 🐍 Python SDK Reference (Programmatic Usage)

Automate engineering workflows directly in Python scripts and CI/CD pipelines:

```python
import alpielocal

# 1. Execute an autonomous engineering task
alpielocal.run(
    task="Build a benchmark script comparing Polars vs Pandas on 10M rows",
    workdir="./benchmarks",
    reasoning_level="thinking"  # "thinking" | "high" | "low"
)

# 2. Generate an implementation plan
alpielocal.plan(
    task="Refactor authentication layer to use OAuth2 and JWT tokens",
    workdir="."
)

# 3. Explain a file or architecture
alpielocal.explain(
    target="src/codeagent/orchestrator.py",
    workdir="."
)

# 4. Run system health diagnostics
status_code = alpielocal.doctor()
```

---

## 📓 Jupyter Notebooks, JupyterLab & Google Colab

AlpieLocal delivers a first-class developer experience inside Jupyter Notebooks and Google Colab with reactive UI cards and live status badges.

```
┌─────────────────────────────────────────────────────────────┐
│ 🤖 AlpieLocal Agent  [RUNNING]                              │
│ Task: Train an XGBoost model on iris dataset                │
│                                                             │
│ ✓ $ python -m pip install xgboost scikit-learn              │
│ ✓ write_file train.py                                       │
│ ✓ $ python train.py                                         │
│                                                             │
│ ✨ Code block automatically populated in next cell.        │
│ Hit Shift+Enter to run.                                     │
└─────────────────────────────────────────────────────────────┘
```

### 1. Setup in Colab or Jupyter
In any notebook cell:
```python
# Install AlpieLocal (in Colab)
!pip install alpielocal

# Load the IPython magic extension
%load_ext alpielocal
```

---

### 2. Magic Commands

#### Single-Line Magic (`%alpie`)
```python
%alpie Create a function to calculate Fibonacci numbers using memoization
```

#### Multi-Line Cell Magic (`%%alpie`)
```python
%%alpie
Create an end-to-end data pipeline script data_pipeline.py:
1. Load dataset from https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv
2. Preprocess features with StandardScaler
3. Train an XGBoost classifier with 5-fold cross validation
4. Print the mean accuracy and confusion matrix
```

#### Auto-Insert Code into Next Cell (`--insert` / `--code`)
Use `--insert` to have AlpieLocal **automatically populate the generated code into the very next notebook cell**, ready for you to press **`Shift+Enter`**:
```python
%alpie --insert Build a PyTorch neural network for MNIST digit classification
```

#### Specialized Notebook Magics:
```python
# Plan without modifying files
%alpie_plan Build a custom PyTorch dataset loader for audio spectrograms

# Explain code or notebook variables
%alpie_explain model.py

# System diagnostic check
%alpie_doctor

# Reset conversation context between notebook sections
%alpie_reset
```

---

## 🛠️ 15 Built-In Autonomous Agent Tools

The AlpieLocal orchestrator autonomously selects and coordinates 15 specialized tools:

| # | Tool Name | Category | Description | Key Inputs |
| :-: | :--- | :--- | :--- | :--- |
| **1** | `write_file` | File System | Creates new files or completely overwrites existing files safely. | `path`, `content` |
| **2** | `edit_file` | File System | Replaces specific text blocks with surgical whitespace matching. | `path`, `old_str`, `new_str` |
| **3** | `read_file` | File System | Reads entire files or specific line ranges (`start_line`, `end_line`). | `path`, `start_line`, `end_line` |
| **4** | `apply_patch` | File System | Applies standard unified diff format patches. | `patch` |
| **5** | `bash` | Execution | Runs shell commands inside an isolated sandbox with safety gates. | `command`, `timeout` |
| **6** | `list_files` | Discovery | Recursively lists repository files with pattern matching & pruning. | `path`, `pattern`, `max_depth` |
| **7** | `file_search` | Discovery | High-speed ripgrep regex search across codebase contents. | `query`, `path`, `include` |
| **8** | `view_image` | Vision | Inspects and analyzes images, UI mockups, and screenshots. | `path` |
| **9** | `fetch_url` | Research | Fetches and extracts clean documentation and web pages. | `url` |
| **10**| `web_search` | Research | Queries DuckDuckGo for live API documentation and references. | `query`, `max_results` |
| **11**| `clone_repo` | Repository | Clones open-source repositories for local reference. | `repo_url`, `destination` |
| **12**| `update_plan` | Planning | Updates structured milestone checklists (`[x]` / `[ ]`). | `plan` |
| **13**| `extract_memories`| Memory | Extracts and persists project patterns and build commands. | `memories` |
| **14**| `compact_context` | Optimization| Compresses conversation history to prevent context overflow. | `summary` |
| **15**| `diagnostics` | Intelligence | Queries compiler and linter diagnostics for active files. | `path` |

---

## 🛡️ Safety Guardian, Git Checkpoints & Memory System

### 1. Safety Guardian Gate (`src/codeagent/guardian.py`)
- **Destructive Command Blocking**: Intercepts and blocks commands like `rm -rf /`, `mkfs`, raw disk partitioning, fork bombs, and system-level modifications.
- **Sandbox Boundary Enforcement**: Prohibits writes outside the active project root directory (`workdir`).
- **Rate-Limited Auto-Fix Loops**: Automatically stops recursive error-fixing loops after **3 attempts** to prevent token waste and infinite loops.

### 2. Git Checkpointing & Undo (`src/codeagent/git_ops.py`)
- **Automatic Checkpoints**: AlpieLocal automatically creates temporary git checkpoints before executing tasks and after each multi-turn step.
- **One-Click Rollback**: Run `alpielocal undo` or reject a proposed plan in VS Code to restore your workspace to its exact prior state.

### 3. Persistent Cross-Session Memory (`src/codeagent/memory.py`)
- Automatically captures project architecture patterns, build scripts, test conventions, and known quirks.
- Persisted locally in `~/.alpielocal/memories/` and injected into future sessions so the agent never asks the same question twice.

### 4. Cross-Platform WSL2 Path Normalization
- Automatically translates Windows UNC paths (`\\wsl.localhost\...` and `\\wsl$\...`) to native Linux paths (`/home/...`) and routes commands through `wsl -d Ubuntu -- bash -c "..."` seamlessly.

---

## ⚙️ Configuration & Environment Variables

Configure AlpieLocal globally via `alpielocal init` or by exporting environment variables:

| Environment Variable | Default Value | Description |
| :--- | :--- | :--- |
| `OPENAI_API_BASE` | `https://test.169pi.ai/v1` | URL for the high-throughput 169Pi cloud VLM endpoint. |
| `OPENAI_API_KEY` | `EMPTY` | API authentication key (if required). |
| `ALPIELOCAL_MODEL` | `alpie_9b` | Target model name. |
| `ALPIELOCAL_SERVER_URL` | `http://127.0.0.1:7169` | Default URL for backend API server. |
| `ALPIELOCAL_N_CTX` | `262144` (Online) / `32768` (Offline) | Maximum context window size in tokens. |
| `ALPIELOCAL_TEMPERATURE` | `0.6` (Thinking) / `0.0` (Fast) | Model sampling temperature. |

---

## ❓ FAQ & Troubleshooting

#### Q: How does the agent decide when to use Local GGUF vs. the Online API?
> **A:** AlpieLocal always prioritizes the high-throughput **Online Cloud API**. It only switches to the **Local GGUF Engine** if an internet check confirms the system is genuinely offline. Transient server delays or timeouts retry automatically rather than falling back.

#### Q: How do I reload the VS Code extension after updating the backend?
> **A:** In VS Code, press **`Ctrl+Shift+P`** (or **`Cmd+Shift+P`** on macOS) and select **`Developer: Reload Window`**.

#### Q: Port 7169 is already in use. How do I change the port?
> **A:** Start the server with a custom port:
> ```bash
> alpielocal serve --port 8080
> ```
> Then update the `alpielocal.serverUrl` setting in VS Code:
> ```json
> "alpielocal.serverUrl": "http://127.0.0.1:8080"
> ```

#### Q: Can I run AlpieLocal completely offline on an airplane or air-gapped machine?
> **A:** Yes! AlpieLocal includes full offline GGUF local model execution. Simply run any CLI command (`alpielocal run "..."`) or start the local server, and it will execute locally using CPU or CUDA hardware acceleration with zero internet access required.

---
