Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat: add persistent install lifecycle management
JerrettDavis21896a095c13
diff --git a/README.md b/README.mdindex 8754d8f78..3fa15f337 100644--- a/README.md+++ b/README.md@@ -92,6 +92,11 @@ PowerShell:irm https://raw.githubusercontent.com/chopratejas/headroom/main/scripts/install.ps1 | iex```+**Persistent local runtime:**+```bash+headroom install apply --preset persistent-service --providers auto+```+### Any agent — one function**Python:**@@ -137,7 +142,7 @@ Use `cache` mode for long-running chats where preserving prior-turn bytes improvWorks with any language, any tool, any framework. **[Proxy docs](docs/proxy.md)**-Prefer Docker as the runtime provider? See **[Docker-native install](docs/docker-install.md)**.+Prefer Docker as the runtime provider? See **[Docker-native install](docs/docker-install.md)**. Want Headroom to stay up in the background? See **[Persistent installs](docs/persistent-installs.md)**.### Coding agents — one command@@ -197,6 +202,7 @@ Gives your AI tool three MCP tools: `headroom_compress`, `headroom_retrieve`, `h| **Claude Code** | Wrap | `headroom wrap claude` || **GitHub Copilot CLI** | Wrap | `headroom wrap copilot -- --model claude-sonnet-4-20250514` || **Codex / Aider** | Wrap | `headroom wrap codex` or `headroom wrap aider` |+| **Always-on local proxy** | Persistent install | `headroom install apply --preset persistent-service --providers auto` |**[Full Integration Guide](docs/integration-guide.md)** | **[TypeScript SDK](docs/typescript-sdk.md)**diff --git a/docker/docker-compose.native.yml b/docker/docker-compose.native.ymlindex e3c6e208e..040eef07d 100644--- a/docker/docker-compose.native.yml+++ b/docker/docker-compose.native.yml@@ -19,6 +19,7 @@ services:image: ${HEADROOM_IMAGE:-ghcr.io/chopratejas/headroom:latest}entrypoint: ["headroom", "proxy"]working_dir: /workspace+ restart: unless-stoppedenvironment:HOME: /tmp/headroom-homeHEADROOM_HOST: 0.0.0.0diff --git a/docs/cli.md b/docs/cli.mdindex 5cc8fcdea..a35b67559 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -22,6 +22,7 @@ This page is the authoritative reference for the **Python Headroom CLI** exposed| Command | Purpose | Docker-native parity ||---|---|---|+| `headroom install ...` | Install and manage persistent deployments | **python-native / compose-managed Docker** || `headroom proxy` | Run the Headroom proxy server | **native in container** || `headroom learn` | Learn from past tool-call failures | **native in container** || `headroom perf` | Summarize recent proxy performance | **native in container** |@@ -29,6 +30,7 @@ This page is the authoritative reference for the **Python Headroom CLI** exposed| `headroom memory ...` | Inspect and manage stored memories | **native in container** || `headroom mcp ...` | Install, inspect, remove, or serve MCP integration | **native in container** || `headroom wrap claude` | Start proxy and launch Claude Code | **host-bridged** |+| `headroom wrap copilot` | Start proxy and launch GitHub Copilot CLI | **host-bridged** || `headroom wrap codex` | Start proxy and launch Codex CLI | **host-bridged** || `headroom wrap aider` | Start proxy and launch Aider | **host-bridged** || `headroom wrap cursor` | Start proxy and print Cursor config guidance | **host-bridged** |@@ -59,6 +61,7 @@ Options:Commands:evals Memory evaluation commands.+ install Install and manage persistent Headroom deployments.learn Learn from past tool call failures to prevent future ones.mcp MCP server for Claude Code integration.memory Manage memories stored in Headroom.@@ -168,6 +171,28 @@ Commands:</details>+<details>+<summary><code>headroom install --help</code></summary>++```text+Usage: headroom install [OPTIONS] COMMAND [ARGS]...++ Install and manage persistent Headroom deployments.++Options:+ -?, --help Show this message and exit.++Commands:+ apply Install a persistent Headroom deployment.+ remove Remove a persistent deployment and undo managed config.+ restart Restart a persistent deployment.+ start Start a persistent deployment.+ status Show persistent deployment status.+ stop Stop a persistent deployment.+```++</details>+<details><summary><code>headroom wrap --help</code></summary>@@ -179,6 +204,7 @@ Usage: headroom wrap [OPTIONS] COMMAND [ARGS]...Commands:aider Launch aider through Headroom proxy.claude Launch Claude Code through Headroom proxy.+ copilot Launch GitHub Copilot CLI through Headroom proxy.codex Launch OpenAI Codex CLI through Headroom proxy.cursor Start Headroom proxy for use with Cursor.openclaw Install and configure Headroom OpenClaw plugin in one command.@@ -536,6 +562,118 @@ headroom mcp serve --proxy-url http://127.0.0.1:9000 --debugSee also: [MCP Tools](mcp.md)+## `headroom install`++Install and manage persistent local Headroom deployments.++### `headroom install apply --help`++```text+Usage: headroom install apply [OPTIONS]++ Install a persistent Headroom deployment.++Options:+ --preset [persistent-service|persistent-task|persistent-docker]+ Persistent runtime preset to install.+ [default: persistent-service]+ --runtime [python|docker] Runtime used to execute Headroom for+ service/task modes. [default: python]+ --scope [provider|user|system] Where to apply persistent configuration.+ [default: user]+ --providers [auto|all|manual] Target selection mode for direct tool+ configuration. [default: auto]+ --target [claude|copilot|codex|aider|cursor|openclaw]+ Tool target to configure when --providers+ manual is used.+ --profile TEXT Deployment profile name. [default: default]+ -p, --port INTEGER Persistent proxy port. [default: 8787]+ --backend TEXT Proxy backend for the persistent runtime.+ [default: anthropic]+ --anyllm-provider TEXT Provider for any-llm backends when --backend+ anyllm is used.+ --region TEXT Cloud region for Bedrock / Vertex style+ backends.+ --mode TEXT Proxy optimization mode. [default: token]+ --memory Enable persistent memory in the proxy runtime.+ --no-telemetry Disable anonymous telemetry in the runtime.+ --image TEXT Docker image to use when runtime=docker or+ preset=persistent-docker. [default:+ ghcr.io/chopratejas/headroom:latest]+ -?, --help Show this message and exit.+```++### `headroom install apply`++```bash+headroom install apply --preset persistent-service --providers auto+headroom install apply --preset persistent-task --providers manual --target claude --target codex+headroom install apply --preset persistent-docker --scope user+```++| Option | Default | Meaning |+|---|---|---|+| `--preset` | `persistent-service` | Lifecycle preset: `persistent-service`, `persistent-task`, or `persistent-docker` |+| `--runtime` | `python` | Runtime used for service/task installs: `python` or `docker` |+| `--scope` | `user` | Config scope: `provider`, `user`, or `system` |+| `--providers` | `auto` | Target selection mode: `auto`, `all`, or `manual` |+| `--target` | repeatable | Tool target used with `--providers manual` |+| `--profile` | `default` | Deployment profile name |+| `--port`, `-p` | `8787` | Persistent proxy port |+| `--backend` | `anthropic` | Backend for the managed runtime |+| `--anyllm-provider` | unset | Provider name used with `--backend anyllm` |+| `--region` | unset | Cloud region override |+| `--mode` | `token` | Proxy optimization mode |+| `--memory` | off | Enable persistent memory in the managed runtime |+| `--no-telemetry` | off | Disable anonymous telemetry |+| `--image` | `ghcr.io/chopratejas/headroom:latest` | Docker image for Docker-backed installs |++`apply` stores a manifest under `~/.headroom/deploy/<profile>/manifest.json`, applies managed tool configuration, starts the chosen runtime, and waits for `readyz`.++### `headroom install status`++```bash+headroom install status+headroom install status --profile default+```++Shows the stored profile, preset, runtime, supervisor kind, scope, port, runtime status, readiness, and backend from `/health`.++### `headroom install start`++```bash+headroom install start+headroom install start --profile default+```++Starts a previously installed deployment profile without reapplying mutations.++### `headroom install stop`++```bash+headroom install stop+```++Stops the managed runtime for an installed deployment profile.++### `headroom install restart`++```bash+headroom install restart+```++Stops and starts the selected deployment profile.++### `headroom install remove`++```bash+headroom install remove+```++Stops the runtime, removes installed supervisor artifacts, reverts managed configuration changes, and deletes the stored manifest.++See also: [Persistent Installs](persistent-installs.md)+## `headroom wrap`Wrap external coding tools so their traffic flows through Headroom.@@ -589,6 +727,29 @@ headroom wrap codex --backend anyllm --anyllm-provider groqRequires the `codex` binary on the host.+### `headroom wrap copilot`++```bash+headroom wrap copilot -- --model claude-sonnet-4-20250514+headroom wrap copilot --backend anyllm --anyllm-provider groq -- --model gpt-4o+```++| Option / arg | Default | Meaning |+|---|---|---|+| `--port`, `-p` | `8787` | Proxy port |+| `--no-rtk` | off | Skip `rtk` installation and GitHub Copilot instructions injection |+| `--no-proxy` | off | Reuse an existing proxy |+| `--learn` | off | Enable live traffic learning |+| `--backend` | unset | Proxy backend override |+| `--anyllm-provider` | unset | `anyllm` provider override |+| `--region` | unset | Cloud region override |+| `--provider-type` | `auto` | Force Copilot BYOK provider type (`anthropic` or `openai`) |+| `--wire-api` | unset | OpenAI wire API override for OpenAI-style backends |+| `--verbose`, `-v` | off | Verbose output |+| `copilot_args...` | passthrough | Additional Copilot CLI arguments |++Requires the `copilot` binary on the host. When a matching persistent deployment exists on the requested port, `wrap copilot` reuses or recovers it before falling back to an ephemeral proxy.+### `headroom wrap aider````bash@@ -691,14 +852,16 @@ Legend:| `headroom mcp uninstall` | native | native in container | full || `headroom mcp status` | native | native in container | full || `headroom mcp serve` | native | native in container | full |+| `headroom install ...` | native | compose-managed persistent Docker path | partial || `headroom wrap claude` | native | host-bridged | partial |+| `headroom wrap copilot` | native | host-bridged | partial || `headroom wrap codex` | native | host-bridged | partial || `headroom wrap aider` | native | host-bridged | partial || `headroom wrap cursor` | native | host-bridged | partial || `headroom wrap openclaw` | native | host-bridged | partial || `headroom unwrap openclaw` | native | host-bridged | partial |-For the Docker-native execution model itself, see [Docker-Native Install](docker-install.md).+For the Docker-native execution model itself, see [Docker-Native Install](docker-install.md). For persistent service/task/docker lifecycle management, see [Persistent Installs](persistent-installs.md).## Hidden and compatibility-only command pathsdiff --git a/docs/docker-install.md b/docs/docker-install.mdindex 98bee18bf..02addaeb3 100644--- a/docs/docker-install.md+++ b/docs/docker-install.md@@ -85,6 +85,24 @@ OpenClaw remains host-native in Docker-native mode:Use `docker/docker-compose.native.yml` when you want an explicit compose-managed proxy or CLI shell.+### Persistent Docker runtime++The `proxy` service now uses `restart: unless-stopped`, so compose can act as the always-on Docker runtime for Headroom:++```bash+export HEADROOM_HOST_HOME="$HOME"+export HEADROOM_WORKSPACE="$PWD"+docker compose -f docker/docker-compose.native.yml up -d proxy+```++```powershell+$env:HEADROOM_HOST_HOME = $HOME+$env:HEADROOM_WORKSPACE = (Get-Location).Path+docker compose -f docker/docker-compose.native.yml up -d proxy+```++This is the recommended persistent-Docker path when you installed Headroom through the Docker-native host wrapper.+### macOS / Linux```bash@@ -128,3 +146,4 @@ That keeps provider auth and runtime config working without maintaining a separa- Docker is the only required Headroom runtime dependency on the host.- Wrapped tools like Claude Code, Codex CLI, Aider, and Cursor still run on the host when you use `headroom wrap ...`.- The install scripts are idempotent: rerunning them refreshes the wrapper and image without duplicating shell profile blocks.+- For persistent service and task installs, use the Python-native `headroom install ...` workflow described in [Persistent Installs](persistent-installs.md).diff --git a/docs/getting-started.md b/docs/getting-started.mdindex 7cb1d31c7..7fc9f9e3a 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -40,6 +40,12 @@ irm https://raw.githubusercontent.com/chopratejas/headroom/main/scripts/install.See [Docker-native install](docker-install.md) for wrapper behavior, compose usage, and host-integrated `wrap` flows.+If you want Headroom to stay up in the background and automatically serve supported tools, use [Persistent Installs](persistent-installs.md):++```bash+headroom install apply --preset persistent-service --providers auto+```+## Quick Start: Proxy Mode (Recommended)The easiest way to use Headroom is as a proxy server:diff --git a/docs/index.md b/docs/index.mdindex 14587dd49..516509d6c 100644--- a/docs/index.md+++ b/docs/index.md@@ -76,6 +76,8 @@ Headroom works as a **transparent proxy** (zero code changes), a **Python functiThat's it. Your existing code works unchanged, with 40-90% fewer tokens.+ Want an always-on local runtime instead? See [Persistent Installs →](persistent-installs.md).+=== "Python SDK"```python@@ -104,6 +106,8 @@ Headroom works as a **transparent proxy** (zero code changes), a **Python functiStarts the proxy, points your tool at it, compresses everything automatically.+ If you prefer an always-on proxy that `wrap` can reuse or recover, see [Persistent Installs →](persistent-installs.md).+=== "TypeScript SDK"```typescriptdiff --git a/docs/persistent-installs.md b/docs/persistent-installs.mdnew file mode 100644index 000000000..dca7cfd23--- /dev/null+++ b/docs/persistent-installs.md@@ -0,0 +1,152 @@+# Persistent Installs++Headroom can now be installed as a durable local runtime instead of only being started ad hoc with `headroom proxy` or `headroom wrap ...`.++Use `headroom install` when you want supported tools to keep talking to an always-on proxy at `http://127.0.0.1:8787` and have `wrap` reuse or recover that deployment instead of starting a second ephemeral proxy.++## Runtime matrix++| Mode | What stays running | Primary entrypoint |+|---|---|---|+| Persistent Service | Native background service | `headroom install apply --preset persistent-service` |+| Persistent Task | Scheduled watchdog + on-demand runner | `headroom install apply --preset persistent-task` |+| Persistent Docker | Restartable Docker container | `headroom install apply --preset persistent-docker` |+| On-Demand CLI (Python) | Nothing after command exits | `headroom proxy` |+| On-Demand CLI (Docker) | Nothing after container exits | Docker-native wrapper / compose CLI |+| Wrapped (Python) | Proxy lasts for wrapped session | `headroom wrap ...` |+| Wrapped (Docker) | Containerized proxy + host tool session | Docker-native wrapper |++## Quick examples++### Persistent service on the local machine++```bash+headroom install apply --preset persistent-service --providers auto+headroom install status+```++This installs a background service on the current machine, applies persistent tool wiring, and keeps the proxy healthy on port `8787`.++### Persistent watchdog task++```bash+headroom install apply --preset persistent-task --providers manual --target claude --target codex+```++This installs a scheduled recovery path instead of a traditional always-running service.++### Persistent Docker++```bash+headroom install apply --preset persistent-docker --scope user --providers auto+```++This uses Docker's restart policy instead of an OS supervisor.++If you are using the Docker-native host wrapper instead of a Python install, use the compose-managed path documented in [Docker-Native Install](docker-install.md).++## Command surface++```text+headroom install apply+headroom install status+headroom install start+headroom install stop+headroom install restart+headroom install remove+```++`apply` creates or updates a named deployment profile, stores its manifest under `~/.headroom/deploy/<profile>/manifest.json`, applies reversible configuration changes, and starts the selected runtime.++## Presets and runtime kinds++### Presets++- `persistent-service` -> native service supervisor+- `persistent-task` -> scheduled watchdog / recovery supervisor+- `persistent-docker` -> Docker restart policy with no extra OS supervisor++### Runtime kinds++- `--runtime python` runs `headroom proxy` directly+- `--runtime docker` runs Headroom inside Docker while keeping the deployment managed locally++For `persistent-docker`, the runtime is always Docker.++## Configuration scopes++| Scope | What changes |+|---|---|+| `provider` | Tool-specific config surfaces where Headroom can make a precise reversible edit |+| `user` | User-level shell or environment surfaces |+| `system` | Machine-wide shell or environment surfaces |++### Provider scope today++Provider scope is intentionally conservative. The current direct adapters are:++- Claude Code -> `~/.claude/settings.json` `env`+- Codex -> managed block in `~/.codex/config.toml`+- OpenClaw -> existing `wrap openclaw` / `unwrap openclaw` flow++For Copilot, Aider, Cursor, and broader env-driven setups, prefer `--scope user` or `--scope system`.++## Provider selection++| Option | Meaning |+|---|---|+| `--providers auto` | Detect supported tools on the host and configure the best available defaults |+| `--providers all` | Configure all known targets |+| `--providers manual --target ...` | Configure only the named tools |++Examples:++```bash+headroom install apply --providers auto+headroom install apply --providers all --scope user+headroom install apply --providers manual --target claude --target copilot+```++## Health and wrap behavior++Persistent deployments publish the same `readyz` and `health` endpoints as ad hoc proxy runs.++`/health` now also exposes deployment metadata when the proxy was launched through the install subsystem:++```json+{+ "deployment": {+ "profile": "default",+ "preset": "persistent-service",+ "runtime": "python",+ "supervisor": "service",+ "scope": "user"+ }+}+```++`headroom wrap ...` checks for a matching persistent deployment on the requested port before it starts a new ephemeral proxy. If an installed deployment exists but is stopped or unhealthy, `wrap` attempts to recover it first.++## Docker-native relationship++The Docker-native host wrapper and the Python install CLI solve different layers of the runtime story:++- [Docker-Native Install](docker-install.md) -> containerized on-demand CLI and wrapped host-tool flows+- `headroom install ...` -> persistent service, task, and native Docker lifecycle management++For a no-Python persistent Docker workflow, use the compose-managed proxy path from `docker/docker-compose.native.yml`:++```bash+export HEADROOM_HOST_HOME="$HOME"+export HEADROOM_WORKSPACE="$PWD"+docker compose -f docker/docker-compose.native.yml up -d proxy+```++That keeps `localhost:8787` stable and restarts the proxy automatically.++## Related guides++- [CLI Reference](cli.md)+- [Docker-Native Install](docker-install.md)+- [Proxy Server](proxy.md)+- [macOS LaunchAgent](macos-deployment.md)diff --git a/docs/plans/2026-04-11-persistent-installs-design.md b/docs/plans/2026-04-11-persistent-installs-design.mdnew file mode 100644index 000000000..e7ab5c037--- /dev/null+++ b/docs/plans/2026-04-11-persistent-installs-design.md@@ -0,0 +1,129 @@+# Persistent Deployments / Installs Design++## Problem++Headroom already supports session-oriented usage through `headroom proxy`, `headroom wrap ...`, and the Docker-native wrapper scripts, but there is no first-class way to install Headroom as a durable background runtime. That leaves users to hand-roll launch agents, services, scheduled tasks, or Docker restart policies, and it keeps direct tool usage (`claude`, `codex`, `copilot`, `openclaw`, etc.) tied to explicit `wrap` commands.++The new feature should make Headroom deployable as a persistent local runtime while keeping the existing on-demand and wrapped flows intact.++## Goals++- Support these runtime/install modes as one coherent system:+ - Persistent Service+ - Persistent Task+ - Persistent Docker+ - On-Demand CLI (Python)+ - On-Demand CLI (Docker)+ - Wrapped (Python)+ - Wrapped (Docker)+- Support install target selection modes:+ - Auto-Detect+ - All+ - Manual Select+- Support configuration scopes:+ - Provider+ - User+ - System+- Keep `wrap` idempotent and persistent-aware.+- Preserve local defaults such as `localhost:8787`.++## Architecture++Introduce a new shared deployment subsystem under `headroom.install`.++Core model:++- `execution_mode`: `persistent | on_demand | wrapped`+- `runtime_kind`: `python | docker`+- `supervisor_kind`: `service | task | none`++These three axes normalize all seven user-facing runtime modes without duplicating logic across CLI commands, install scripts, and platform-specific deployment adapters.++The subsystem centers on a persisted deployment manifest in `~/.headroom/deploy/` that records:++- resolved proxy configuration+- runtime type+- supervisor type+- configured tool targets+- applied config mutations+- generated artifact paths+- health URL and port++## Command model++Add a new public `headroom install` group:++- `headroom install apply`+- `headroom install status`+- `headroom install start`+- `headroom install stop`+- `headroom install restart`+- `headroom install remove`++Add hidden helper commands for artifact runners and health recovery:++- `headroom install agent run --profile <name>`+- `headroom install agent ensure --profile <name>`++Platform supervisors should register the hidden agent entrypoint rather than raw `headroom proxy ...` so restart, health polling, and manifest handling live in one place.++## Runtime adapters++- `PythonRuntimeAdapter`: launches `headroom proxy` directly.+- `DockerRuntimeAdapter`: launches a detached or foreground Docker container with the existing host mounts and loopback-only port publishing.++Persistent Docker uses the same deployment manifest and status semantics as service/task installs, but the child runtime is Docker-managed rather than OS-supervised.++## Supervisor adapters++- Linux+ - Service: systemd unit+ - Task: cron watchdog + reboot/start entry+- macOS+ - Service: LaunchDaemon / LaunchAgent variant+ - Task: launchd user agent or cron-style watchdog where appropriate+- Windows+ - Service: Windows Service wrapper+ - Task: Scheduled Task startup + periodic health-check task++Each adapter renders artifacts into `~/.headroom/deploy/` and stores enough metadata for clean removal.++## Tool target configuration++Provider-level configuration should be target-specific and reversible.++Initial target adapters:++- Claude Code+ - write `env` keys into Claude settings JSON where appropriate+- Codex+ - manage a marked block or targeted settings in `~/.codex/config.toml`+- Copilot CLI+ - configure BYOK environment surfaces using persistent env strategy+- OpenClaw+ - reuse existing OpenClaw config/plugin merge logic where possible+- Aider / Cursor+ - use env-based integration first, with tool-specific config only where a stable supported surface exists++All non-marker edits must store previous values in the deployment manifest so uninstall removes only Headroom-managed changes.++## Wrap behavior++`headroom wrap ...` should consult the active deployment manifest before starting a new proxy. If a compatible persistent deployment is present and healthy, `wrap` should reuse it and only perform any remaining tool-specific preparation. If the deployment exists but is unhealthy, `wrap` should attempt to recover it through the install subsystem before falling back to an ephemeral proxy.++## Docs strategy++The public docs should be reframed around:++- runtime mode+- lifecycle mode+- configuration scope+- direct-use vs `wrap`++Create a new top-level guide at `docs/persistent-installs.md` and update the existing Docker install, proxy, CLI, getting-started, quickstart, configuration, troubleshooting, and integration docs to reflect the broader runtime story.++## Risks++- Windows service installation is the highest-risk platform path and needs strong test isolation.+- Provider-specific config mutation must remain conservative and reversible.+- `/health` should gain deployment metadata without breaking the existing `config` payload shape expected by current tests and docs.diff --git a/docs/quickstart.md b/docs/quickstart.mdindex ffc6a5ecf..5ce5e9a98 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -33,6 +33,14 @@ curl -fsSL https://raw.githubusercontent.com/chopratejas/headroom/main/scripts/iSee [Docker-native install](docker-install.md) if you want Docker to provide the Headroom runtime while your agent CLIs stay on the host.+**Persistent background runtime:**++```bash+headroom install apply --preset persistent-service --providers auto+```++See [Persistent Installs](persistent-installs.md) if you want Headroom to stay up in the background and be reused by `wrap`.+---## Option 1: Proxy Server (Zero Code Changes)diff --git a/headroom/cli/install.py b/headroom/cli/install.pynew file mode 100644index 000000000..d04e5d70a--- /dev/null+++ b/headroom/cli/install.py@@ -0,0 +1,305 @@+"""Persistent install / deployment CLI commands."""++from __future__ import annotations++import click++from headroom.install.health import probe_json, probe_ready+from headroom.install.models import (+ ConfigScope,+ DeploymentManifest,+ InstallPreset,+ ProviderSelectionMode,+ RuntimeKind,+ SupervisorKind,+)+from headroom.install.planner import build_manifest+from headroom.install.providers import apply_mutations, revert_mutations+from headroom.install.runtime import (+ run_foreground,+ runtime_status,+ start_detached_agent,+ start_persistent_docker,+ stop_runtime,+ wait_ready,+)+from headroom.install.state import delete_manifest, load_manifest, save_manifest+from headroom.install.supervisors import (+ install_supervisor,+ remove_supervisor,+ start_supervisor,+ stop_supervisor,+)++from .main import main+++def install() -> None:+ """Install and manage persistent Headroom deployments."""+++def _require_manifest(profile: str) -> DeploymentManifest:+ manifest = load_manifest(profile)+ if manifest is None:+ raise click.ClickException(f"No deployment profile named '{profile}' is installed.")+ return manifest+++def _start_deployment(manifest: DeploymentManifest) -> None:+ if manifest.preset == InstallPreset.PERSISTENT_DOCKER.value:+ start_persistent_docker(manifest)+ elif manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ start_supervisor(manifest)+ else:+ start_detached_agent(manifest.profile)++ if not wait_ready(manifest, timeout_seconds=45):+ raise click.ClickException(+ f"Deployment '{manifest.profile}' did not become ready after start."+ )+++def _stop_deployment(manifest: DeploymentManifest) -> None:+ if manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ stop_supervisor(manifest)+ stop_runtime(manifest)++[email protected]("apply")+ "--preset",+ type=click.Choice([preset.value for preset in InstallPreset]),+ default=InstallPreset.PERSISTENT_SERVICE.value,+ show_default=True,+ help="Persistent runtime preset to install.",+)+ "--runtime",+ type=click.Choice([runtime.value for runtime in RuntimeKind]),+ default=RuntimeKind.PYTHON.value,+ show_default=True,+ help="Runtime used to execute Headroom for service/task modes.",+)+ "--scope",+ type=click.Choice([scope.value for scope in ConfigScope]),+ default=ConfigScope.USER.value,+ show_default=True,+ help="Where to apply persistent configuration.",+)+ "--providers",+ "provider_mode",+ type=click.Choice([mode.value for mode in ProviderSelectionMode]),+ default=ProviderSelectionMode.AUTO.value,+ show_default=True,+ help="Target selection mode for direct tool configuration.",+)+ "--target",+ "targets",+ multiple=True,+ type=click.Choice(["claude", "copilot", "codex", "aider", "cursor", "openclaw"]),+ help="Tool target to configure when --providers manual is used.",+)[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+ "--port", "-p", default=8787, type=int, show_default=True, help="Persistent proxy port."+)+ "--backend",+ default="anthropic",+ show_default=True,+ help="Proxy backend for the persistent runtime.",+)+ "--anyllm-provider",+ default=None,+ help="Provider for any-llm backends when --backend anyllm is used.",+)[email protected]("--region", default=None, help="Cloud region for Bedrock / Vertex style backends.")+ "--mode", "proxy_mode", default="token", show_default=True, help="Proxy optimization mode."+)[email protected]("--memory", is_flag=True, help="Enable persistent memory in the proxy runtime.")[email protected]("--no-telemetry", is_flag=True, help="Disable anonymous telemetry in the runtime.")+ "--image",+ default="ghcr.io/chopratejas/headroom:latest",+ show_default=True,+ help="Docker image to use when runtime=docker or preset=persistent-docker.",+)+def install_apply(+ preset: str,+ runtime: str,+ scope: str,+ provider_mode: str,+ targets: tuple[str, ...],+ profile: str,+ port: int,+ backend: str,+ anyllm_provider: str | None,+ region: str | None,+ proxy_mode: str,+ memory: bool,+ no_telemetry: bool,+ image: str,+) -> None:+ """Install a persistent Headroom deployment."""++ if preset == InstallPreset.PERSISTENT_DOCKER.value:+ runtime = RuntimeKind.DOCKER.value++ manifest = build_manifest(+ profile=profile,+ preset=preset,+ runtime_kind=runtime,+ scope=scope,+ provider_mode=provider_mode,+ targets=list(targets),+ port=port,+ backend=backend,+ anyllm_provider=anyllm_provider,+ region=region,+ proxy_mode=proxy_mode,+ memory_enabled=memory,+ telemetry_enabled=not no_telemetry,+ image=image,+ )++ existing = load_manifest(profile)+ if existing is not None:+ click.echo(f"Updating existing deployment profile '{profile}'...")+ revert_mutations(existing)+ try:+ remove_supervisor(existing)+ except Exception:+ pass+ stop_runtime(existing)++ manifest.mutations = apply_mutations(manifest)+ manifest.artifacts = install_supervisor(manifest)+ save_manifest(manifest)++ if manifest.preset == InstallPreset.PERSISTENT_DOCKER.value:+ start_persistent_docker(manifest)+ elif manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ start_supervisor(manifest)+ else:+ start_detached_agent(profile)++ if not wait_ready(manifest, timeout_seconds=45):+ raise click.ClickException(+ f"Persistent deployment '{profile}' did not become ready at {manifest.health_url}."+ )++ click.echo(+ f"Installed persistent deployment '{profile}' "+ f"({manifest.preset}, runtime={manifest.runtime_kind}, scope={manifest.scope})."+ )+ click.echo(f"Health: {manifest.health_url}")+ if manifest.targets:+ click.echo(f"Targets: {', '.join(manifest.targets)}")++[email protected]("status")[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+def install_status(profile: str) -> None:+ """Show persistent deployment status."""++ manifest = _require_manifest(profile)+ payload = probe_json(manifest.health_url.replace("/readyz", "/health"))+ click.echo(f"Profile: {manifest.profile}")+ click.echo(f"Preset: {manifest.preset}")+ click.echo(f"Runtime: {manifest.runtime_kind}")+ click.echo(f"Supervisor: {manifest.supervisor_kind}")+ click.echo(f"Scope: {manifest.scope}")+ click.echo(f"Port: {manifest.port}")+ click.echo(f"Status: {runtime_status(manifest)}")+ click.echo(f"Healthy: {'yes' if probe_ready(manifest.health_url) else 'no'}")+ if payload and isinstance(payload, dict):+ click.echo(f"Health URL: {manifest.health_url.replace('/readyz', '/health')}")+ click.echo(f"Backend: {payload.get('config', {}).get('backend', manifest.backend)}")++[email protected]("start")[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+def install_start(profile: str) -> None:+ """Start a persistent deployment."""++ manifest = _require_manifest(profile)+ _start_deployment(manifest)+ click.echo(f"Started deployment '{profile}'.")++[email protected]("stop")[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+def install_stop(profile: str) -> None:+ """Stop a persistent deployment."""++ manifest = _require_manifest(profile)+ _stop_deployment(manifest)+ click.echo(f"Stopped deployment '{profile}'.")++[email protected]("restart")[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+def install_restart(profile: str) -> None:+ """Restart a persistent deployment."""++ manifest = _require_manifest(profile)+ _stop_deployment(manifest)+ _start_deployment(manifest)+ click.echo(f"Restarted deployment '{profile}'.")++[email protected]("remove")[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+def install_remove(profile: str) -> None:+ """Remove a persistent deployment and undo managed config."""++ manifest = _require_manifest(profile)+ try:+ if manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ stop_supervisor(manifest)+ except Exception:+ pass+ try:+ stop_runtime(manifest)+ except Exception:+ pass+ try:+ remove_supervisor(manifest)+ except Exception:+ pass+ revert_mutations(manifest)+ delete_manifest(profile)+ click.echo(f"Removed deployment '{profile}'.")++[email protected]("agent", hidden=True)+def install_agent() -> None:+ """Hidden runtime helpers used by persistent supervisors."""+++@install_agent.command("run")[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+def install_agent_run(profile: str) -> None:+ """Run the persistent runtime in the foreground."""++ manifest = _require_manifest(profile)+ raise SystemExit(run_foreground(manifest))+++@install_agent.command("ensure")[email protected]("--profile", default="default", show_default=True, help="Deployment profile name.")+def install_agent_ensure(profile: str) -> None:+ """Ensure a persistent deployment is healthy, starting it when needed."""++ manifest = _require_manifest(profile)+ if probe_ready(manifest.health_url):+ click.echo(f"Deployment '{profile}' is already healthy.")+ return+ _start_deployment(manifest)+ click.echo(f"Deployment '{profile}' is healthy.")diff --git a/headroom/cli/main.py b/headroom/cli/main.pyindex 517906ded..2c86af806 100644--- a/headroom/cli/main.py+++ b/headroom/cli/main.py@@ -37,6 +37,7 @@ def _register_commands() -> None:"""Register all subcommand groups."""from . import (evals, # noqa: F401+ install, # noqa: F401learn, # noqa: F401mcp, # noqa: F401perf, # noqa: F401diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex 7240d86cd..88cbd43ce 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -436,6 +436,52 @@ def _detect_running_proxy_backend(port: int) -> str | None:return backend if isinstance(backend, str) else None+def _find_persistent_manifest(port: int) -> Any:+ """Return a matching persistent deployment manifest for the requested port."""+ from headroom.install.state import list_manifests++ manifests = [manifest for manifest in list_manifests() if manifest.port == port]+ manifests.sort(key=lambda manifest: (manifest.profile != "default", manifest.profile))+ return manifests[0] if manifests else None+++def _recover_persistent_proxy(port: int) -> bool:+ """Start or recover a matching persistent deployment for the requested port."""+ from headroom.install.health import probe_ready+ from headroom.install.models import InstallPreset, SupervisorKind+ from headroom.install.runtime import start_detached_agent, start_persistent_docker, wait_ready+ from headroom.install.supervisors import start_supervisor++ manifest = _find_persistent_manifest(port)+ if manifest is None:+ return False++ if probe_ready(manifest.health_url):+ click.echo(f" Reusing persistent deployment '{manifest.profile}' on port {port}")+ return True++ click.echo(f" Recovering persistent deployment '{manifest.profile}' on port {port}...")+ try:+ if manifest.preset == InstallPreset.PERSISTENT_DOCKER.value:+ start_persistent_docker(manifest)+ elif manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ start_supervisor(manifest)+ else:+ start_detached_agent(manifest.profile)+ except Exception as exc:+ click.echo(+ f" Warning: could not recover persistent deployment '{manifest.profile}': {exc}"+ )+ return False++ if wait_ready(manifest, timeout_seconds=45):+ click.echo(f" Recovered persistent deployment '{manifest.profile}' on port {port}")+ return True++ click.echo(f" Warning: persistent deployment '{manifest.profile}' did not become ready")+ return False++def _copilot_model_configured(copilot_args: tuple[str, ...], env: dict[str, str]) -> bool:"""Return True when Copilot BYOK model selection is configured."""if env.get("COPILOT_MODEL") or env.get("COPILOT_PROVIDER_MODEL_ID"):@@ -462,6 +508,16 @@ def _ensure_proxy() -> subprocess.Popen | None:"""Start or verify proxy. Returns process handle if we started it."""if not no_proxy:+ manifest = _find_persistent_manifest(port)+ if manifest is not None:+ from headroom.install.health import probe_ready++ if probe_ready(manifest.health_url):+ click.echo(f" Proxy already running on port {port}")+ return None+ if _recover_persistent_proxy(port):+ return None+if _check_proxy(port):click.echo(f" Proxy already running on port {port}")return Nonediff --git a/headroom/install/__init__.py b/headroom/install/__init__.pynew file mode 100644index 000000000..f2942a227--- /dev/null+++ b/headroom/install/__init__.py@@ -0,0 +1,19 @@+"""Persistent install / deployment helpers for Headroom."""++from .models import (+ ConfigScope,+ DeploymentManifest,+ InstallPreset,+ ProviderSelectionMode,+ SupervisorKind,+ ToolTarget,+)++__all__ = [+ "ConfigScope",+ "DeploymentManifest",+ "InstallPreset",+ "ProviderSelectionMode",+ "SupervisorKind",+ "ToolTarget",+]diff --git a/headroom/install/health.py b/headroom/install/health.pynew file mode 100644index 000000000..1b4ae2fed--- /dev/null+++ b/headroom/install/health.py@@ -0,0 +1,28 @@+"""Health helpers for persistent deployments."""++from __future__ import annotations++import json+import urllib.error+import urllib.request+from typing import Any+++def probe_json(url: str, timeout: float = 2.0) -> dict[str, Any] | None:+ """Return a JSON payload from the URL when reachable."""++ try:+ with urllib.request.urlopen(url, timeout=timeout) as response:+ payload = json.loads(response.read().decode("utf-8"))+ except (OSError, urllib.error.URLError, ValueError, json.JSONDecodeError):+ return None+ return payload if isinstance(payload, dict) else None+++def probe_ready(url: str, timeout: float = 2.0) -> bool:+ """Return True when the ready endpoint reports readiness."""++ payload = probe_json(url, timeout=timeout)+ if not isinstance(payload, dict):+ return False+ return bool(payload.get("ready", False) or payload.get("status") == "healthy")diff --git a/headroom/install/models.py b/headroom/install/models.pynew file mode 100644index 000000000..777027998--- /dev/null+++ b/headroom/install/models.py@@ -0,0 +1,116 @@+"""Models used by the install / deployment subsystem."""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime, timezone+from enum import Enum+from typing import Any+++class InstallPreset(str, Enum):+ """User-facing persistent runtime presets."""++ PERSISTENT_SERVICE = "persistent-service"+ PERSISTENT_TASK = "persistent-task"+ PERSISTENT_DOCKER = "persistent-docker"+++class RuntimeKind(str, Enum):+ """Runtime used to execute Headroom."""++ PYTHON = "python"+ DOCKER = "docker"+++class SupervisorKind(str, Enum):+ """How a persistent deployment is kept alive."""++ SERVICE = "service"+ TASK = "task"+ NONE = "none"+++class ProviderSelectionMode(str, Enum):+ """How tool targets are selected for configuration."""++ AUTO = "auto"+ ALL = "all"+ MANUAL = "manual"+++class ConfigScope(str, Enum):+ """Where persistent configuration should be applied."""++ PROVIDER = "provider"+ USER = "user"+ SYSTEM = "system"+++class ToolTarget(str, Enum):+ """Supported tool targets for persistent proxy wiring."""++ CLAUDE = "claude"+ COPILOT = "copilot"+ CODEX = "codex"+ AIDER = "aider"+ CURSOR = "cursor"+ OPENCLAW = "openclaw"+++def iso_utc_now() -> str:+ """Return the current UTC timestamp in ISO-8601 format."""++ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+++@dataclass+class ManagedMutation:+ """A reversible change applied by `headroom install`."""++ target: str+ kind: str+ path: str | None = None+ data: dict[str, Any] = field(default_factory=dict)+++@dataclass+class ArtifactRecord:+ """A rendered file or platform object owned by the deployment."""++ kind: str+ path: str+ metadata: dict[str, Any] = field(default_factory=dict)+++@dataclass+class DeploymentManifest:+ """Persisted deployment state for a named profile."""++ profile: str+ preset: str+ runtime_kind: str+ supervisor_kind: str+ scope: str+ provider_mode: str+ targets: list[str]+ port: int+ host: str+ backend: str+ anyllm_provider: str | None = None+ region: str | None = None+ proxy_mode: str = "token"+ memory_enabled: bool = False+ memory_db_path: str = ""+ telemetry_enabled: bool = True+ image: str = "ghcr.io/chopratejas/headroom:latest"+ service_name: str = "headroom"+ container_name: str = "headroom-persistent"+ health_url: str = "http://127.0.0.1:8787/readyz"+ base_env: dict[str, str] = field(default_factory=dict)+ tool_envs: dict[str, dict[str, str]] = field(default_factory=dict)+ proxy_args: list[str] = field(default_factory=list)+ mutations: list[ManagedMutation] = field(default_factory=list)+ artifacts: list[ArtifactRecord] = field(default_factory=list)+ created_at: str = field(default_factory=iso_utc_now)+ updated_at: str = field(default_factory=iso_utc_now)diff --git a/headroom/install/paths.py b/headroom/install/paths.pynew file mode 100644index 000000000..7102c0d4f--- /dev/null+++ b/headroom/install/paths.py@@ -0,0 +1,105 @@+"""Path helpers for persistent deployments."""++from __future__ import annotations++import sys+from pathlib import Path+++def deploy_root() -> Path:+ """Return the root directory for deployment state."""++ return Path.home() / ".headroom" / "deploy"+++def profile_root(profile: str) -> Path:+ """Return the directory for a named deployment profile."""++ return deploy_root() / profile+++def manifest_path(profile: str) -> Path:+ """Return the manifest path for a named profile."""++ return profile_root(profile) / "manifest.json"+++def log_path(profile: str) -> Path:+ """Return the log path used by persistent runner scripts."""++ return profile_root(profile) / "runner.log"+++def pid_path(profile: str) -> Path:+ """Return the pid file for the raw runtime process."""++ return profile_root(profile) / "runner.pid"+++def unix_run_script_path(profile: str) -> Path:+ """Return the foreground runner shell script path."""++ return profile_root(profile) / "run-headroom.sh"+++def unix_ensure_script_path(profile: str) -> Path:+ """Return the watchdog shell script path."""++ return profile_root(profile) / "ensure-headroom.sh"+++def windows_run_script_path(profile: str) -> Path:+ """Return the foreground runner PowerShell script path."""++ return profile_root(profile) / "run-headroom.ps1"+++def windows_run_cmd_path(profile: str) -> Path:+ """Return the foreground runner CMD shim path."""++ return profile_root(profile) / "run-headroom.cmd"+++def windows_ensure_script_path(profile: str) -> Path:+ """Return the watchdog PowerShell script path."""++ return profile_root(profile) / "ensure-headroom.ps1"+++def windows_ensure_cmd_path(profile: str) -> Path:+ """Return the watchdog CMD shim path."""++ return profile_root(profile) / "ensure-headroom.cmd"+++def unix_user_env_targets() -> list[Path]:+ """Return user shell files that can carry the persistent env block."""++ home = Path.home()+ return [home / ".bashrc", home / ".zshrc", home / ".profile"]+++def unix_system_env_targets() -> list[Path]:+ """Return system shell files that can carry the persistent env block."""++ if sys.platform == "darwin":+ return [Path("/etc/profile"), Path("/etc/zprofile"), Path("/etc/bashrc")]+ return [Path("/etc/profile.d/headroom.sh")]+++def claude_settings_path() -> Path:+ """Return the Claude user settings path."""++ return Path.home() / ".claude" / "settings.json"+++def codex_config_path() -> Path:+ """Return the Codex config path."""++ return Path.home() / ".codex" / "config.toml"+++def openclaw_config_path() -> Path:+ """Return the OpenClaw config path."""++ return Path.home() / ".openclaw" / "openclaw.json"diff --git a/headroom/install/planner.py b/headroom/install/planner.pynew file mode 100644index 000000000..bc8a6edbe--- /dev/null+++ b/headroom/install/planner.py@@ -0,0 +1,201 @@+"""Planner for persistent deployment manifests."""++from __future__ import annotations++import shutil+from collections.abc import Iterable+from pathlib import Path++from .models import (+ DeploymentManifest,+ InstallPreset,+ ProviderSelectionMode,+ SupervisorKind,+ ToolTarget,+)++SUPPORTED_TARGETS = [+ ToolTarget.CLAUDE,+ ToolTarget.COPILOT,+ ToolTarget.CODEX,+ ToolTarget.AIDER,+ ToolTarget.CURSOR,+ ToolTarget.OPENCLAW,+]+++def _binary_name(target: ToolTarget) -> str | None:+ if target == ToolTarget.CURSOR:+ return None+ return str(target.value)+++def detect_targets() -> list[str]:+ """Auto-detect available tool targets on the current host."""++ detected: list[str] = []+ for target in SUPPORTED_TARGETS:+ binary = _binary_name(target)+ if binary and shutil.which(binary):+ detected.append(target.value)+ continue+ if target == ToolTarget.CURSOR and shutil.which("cursor"):+ detected.append(target.value)+ return detected+++def resolve_targets(provider_mode: str, requested_targets: Iterable[str]) -> list[str]:+ """Resolve target selection according to the requested provider mode."""++ if provider_mode == ProviderSelectionMode.ALL.value:+ return [target.value for target in SUPPORTED_TARGETS]++ if provider_mode == ProviderSelectionMode.AUTO.value:+ detected = detect_targets()+ return detected or [+ ToolTarget.CLAUDE.value,+ ToolTarget.CODEX.value,+ ToolTarget.COPILOT.value,+ ]++ normalized = []+ seen: set[str] = set()+ valid = {target.value for target in SUPPORTED_TARGETS}+ for target in requested_targets:+ value = target.strip().lower()+ if value in valid and value not in seen:+ seen.add(value)+ normalized.append(value)+ return normalized+++def _copilot_env(port: int, backend: str) -> dict[str, str]:+ if backend == "anthropic":+ return {+ "COPILOT_PROVIDER_TYPE": "anthropic",+ "COPILOT_PROVIDER_BASE_URL": f"http://127.0.0.1:{port}",+ }+ return {+ "COPILOT_PROVIDER_TYPE": "openai",+ "COPILOT_PROVIDER_BASE_URL": f"http://127.0.0.1:{port}/v1",+ "COPILOT_PROVIDER_WIRE_API": "completions",+ }+++def build_tool_envs(port: int, backend: str, targets: list[str]) -> dict[str, dict[str, str]]:+ """Build per-target environment variables for the selected tools."""++ target_envs: dict[str, dict[str, str]] = {}+ if ToolTarget.CLAUDE.value in targets:+ target_envs[ToolTarget.CLAUDE.value] = {+ "ANTHROPIC_BASE_URL": f"http://127.0.0.1:{port}",+ }+ if ToolTarget.CODEX.value in targets:+ target_envs[ToolTarget.CODEX.value] = {+ "OPENAI_BASE_URL": f"http://127.0.0.1:{port}/v1",+ }+ if ToolTarget.AIDER.value in targets:+ target_envs[ToolTarget.AIDER.value] = {+ "OPENAI_API_BASE": f"http://127.0.0.1:{port}/v1",+ "ANTHROPIC_BASE_URL": f"http://127.0.0.1:{port}",+ }+ if ToolTarget.COPILOT.value in targets:+ target_envs[ToolTarget.COPILOT.value] = _copilot_env(port, backend)+ if ToolTarget.CURSOR.value in targets:+ target_envs[ToolTarget.CURSOR.value] = {+ "OPENAI_BASE_URL": f"http://127.0.0.1:{port}/v1",+ "ANTHROPIC_BASE_URL": f"http://127.0.0.1:{port}",+ }+ return target_envs+++def build_manifest(+ *,+ profile: str,+ preset: str,+ runtime_kind: str,+ scope: str,+ provider_mode: str,+ targets: list[str],+ port: int,+ backend: str,+ anyllm_provider: str | None,+ region: str | None,+ proxy_mode: str,+ memory_enabled: bool,+ telemetry_enabled: bool,+ image: str,+) -> DeploymentManifest:+ """Create a normalized deployment manifest."""++ if preset == InstallPreset.PERSISTENT_SERVICE.value:+ supervisor_kind = SupervisorKind.SERVICE.value+ elif preset == InstallPreset.PERSISTENT_TASK.value:+ supervisor_kind = SupervisorKind.TASK.value+ else:+ supervisor_kind = SupervisorKind.NONE.value++ resolved_targets = resolve_targets(provider_mode, targets)+ tool_envs = build_tool_envs(port, backend, resolved_targets)+ base_env = {+ "HEADROOM_PORT": str(port),+ "HEADROOM_HOST": "127.0.0.1",+ "HEADROOM_MODE": proxy_mode,+ "HEADROOM_BACKEND": backend,+ }+ if anyllm_provider:+ base_env["HEADROOM_ANYLLM_PROVIDER"] = anyllm_provider+ if region:+ base_env["HEADROOM_REGION"] = region+ if not telemetry_enabled:+ base_env["HEADROOM_TELEMETRY"] = "off"+ if memory_enabled:+ base_env["HEADROOM_MEMORY_ENABLED"] = "1"++ proxy_args = [+ "--host",+ "127.0.0.1",+ "--port",+ str(port),+ "--mode",+ proxy_mode,+ "--backend",+ backend,+ ]+ if not telemetry_enabled:+ proxy_args.append("--no-telemetry")+ if memory_enabled:+ proxy_args.extend(+ ["--memory", "--memory-db-path", str(Path.home() / ".headroom" / "memory.db")]+ )+ if anyllm_provider:+ proxy_args.extend(["--anyllm-provider", anyllm_provider])+ if region:+ proxy_args.extend(["--region", region])++ container_name = f"headroom-{profile}"+ return DeploymentManifest(+ profile=profile,+ preset=preset,+ runtime_kind=runtime_kind,+ supervisor_kind=supervisor_kind,+ scope=scope,+ provider_mode=provider_mode,+ targets=resolved_targets,+ port=port,+ host="127.0.0.1",+ backend=backend,+ anyllm_provider=anyllm_provider,+ region=region,+ proxy_mode=proxy_mode,+ memory_enabled=memory_enabled,+ memory_db_path=str(Path.home() / ".headroom" / "memory.db"),+ telemetry_enabled=telemetry_enabled,+ image=image,+ service_name=f"headroom-{profile}",+ container_name=container_name,+ health_url=f"http://127.0.0.1:{port}/readyz",+ base_env=base_env,+ tool_envs=tool_envs,+ proxy_args=proxy_args,+ )diff --git a/headroom/install/providers.py b/headroom/install/providers.pynew file mode 100644index 000000000..142535d99--- /dev/null+++ b/headroom/install/providers.py@@ -0,0 +1,277 @@+"""Tool-target configuration for persistent deployments."""++from __future__ import annotations++import json+import os+import re+import subprocess+from pathlib import Path++import click++from .models import ConfigScope, DeploymentManifest, ManagedMutation, ToolTarget+from .paths import (+ claude_settings_path,+ codex_config_path,+ openclaw_config_path,+ unix_system_env_targets,+ unix_user_env_targets,+)+from .runtime import resolve_headroom_command++_ENV_MARKER_START = "# >>> headroom persistent env >>>"+_ENV_MARKER_END = "# <<< headroom persistent env <<<"+_ENV_PATTERN = re.compile(+ re.escape(_ENV_MARKER_START) + r".*?" + re.escape(_ENV_MARKER_END),+ re.DOTALL,+)+_CODEX_MARKER_START = "# --- Headroom persistent provider ---"+_CODEX_MARKER_END = "# --- end Headroom persistent provider ---"+_CODEX_PATTERN = re.compile(+ re.escape(_CODEX_MARKER_START) + r".*?" + re.escape(_CODEX_MARKER_END),+ re.DOTALL,+)+++def _merge_marker_block(file_path: Path, block: str, pattern: re.Pattern[str], marker: str) -> str:+ if file_path.exists():+ existing = file_path.read_text()+ if marker in existing:+ return pattern.sub(block, existing)+ return existing.rstrip() + "\n\n" + block + "\n"+ return block + "\n"+++def _env_block(values: dict[str, str]) -> str:+ lines = [_ENV_MARKER_START]+ for name, value in values.items():+ lines.append(f'export {name}="{value}"')+ lines.append(_ENV_MARKER_END)+ return "\n".join(lines)+++def _unix_scope_values(manifest: DeploymentManifest) -> dict[str, str]:+ merged = dict(manifest.base_env)+ for env_map in manifest.tool_envs.values():+ merged.update(env_map)+ return merged+++def _apply_unix_env_scope(manifest: DeploymentManifest) -> list[ManagedMutation]:+ values = _unix_scope_values(manifest)+ block = _env_block(values)+ if manifest.scope == ConfigScope.USER.value:+ targets = unix_user_env_targets()+ else:+ targets = unix_system_env_targets()+ mutations: list[ManagedMutation] = []+ for path in targets:+ path.parent.mkdir(parents=True, exist_ok=True)+ merged = _merge_marker_block(path, block, _ENV_PATTERN, _ENV_MARKER_START)+ path.write_text(merged)+ mutations.append(ManagedMutation(target="env", kind="shell-block", path=str(path)))+ return mutations+++def _remove_unix_env_scope(mutations: list[ManagedMutation]) -> None:+ for mutation in mutations:+ if mutation.kind != "shell-block" or not mutation.path:+ continue+ path = Path(mutation.path)+ if not path.exists():+ continue+ content = path.read_text()+ if _ENV_MARKER_START not in content:+ continue+ path.write_text(_ENV_PATTERN.sub("", content).strip() + "\n")+++def _apply_windows_env_scope(manifest: DeploymentManifest) -> list[ManagedMutation]:+ scope_name = "Machine" if manifest.scope == ConfigScope.SYSTEM.value else "User"+ merged = _unix_scope_values(manifest)+ mutations: list[ManagedMutation] = []+ for name, value in merged.items():+ command = [+ "powershell",+ "-NoProfile",+ "-Command",+ f"[Environment]::SetEnvironmentVariable('{name}','{value}','{scope_name}')",+ ]+ subprocess.run(command, check=True)+ mutations.append(+ ManagedMutation(+ target="env", kind="windows-env", data={"name": name, "scope": scope_name}+ )+ )+ return mutations+++def _remove_windows_env_scope(mutations: list[ManagedMutation]) -> None:+ for mutation in mutations:+ if mutation.kind != "windows-env":+ continue+ name = mutation.data.get("name")+ scope_name = mutation.data.get("scope", "User")+ command = [+ "powershell",+ "-NoProfile",+ "-Command",+ f"[Environment]::SetEnvironmentVariable('{name}',$null,'{scope_name}')",+ ]+ subprocess.run(command, check=True)+++def _apply_claude_provider_scope(manifest: DeploymentManifest) -> ManagedMutation:+ path = claude_settings_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ payload: dict[str, object] = {}+ if path.exists():+ payload = json.loads(path.read_text())+ env = payload.get("env")+ env_map = dict(env) if isinstance(env, dict) else {}+ previous = {+ name: env_map.get(name) for name in manifest.tool_envs.get(ToolTarget.CLAUDE.value, {})+ }+ env_map.update(manifest.tool_envs[ToolTarget.CLAUDE.value])+ payload["env"] = env_map+ path.write_text(json.dumps(payload, indent=2) + "\n")+ return ManagedMutation(+ target=ToolTarget.CLAUDE.value,+ kind="json-env",+ path=str(path),+ data={"previous": previous},+ )+++def _revert_claude_provider_scope(mutation: ManagedMutation, values: dict[str, str]) -> None:+ if not mutation.path:+ return+ path = Path(mutation.path)+ if not path.exists():+ return+ payload = json.loads(path.read_text())+ env = payload.get("env")+ env_map = dict(env) if isinstance(env, dict) else {}+ previous: dict[str, object] = mutation.data.get("previous", {})+ for name in values:+ if previous.get(name) is None:+ env_map.pop(name, None)+ else:+ env_map[name] = previous[name]+ payload["env"] = env_map+ path.write_text(json.dumps(payload, indent=2) + "\n")+++def _apply_codex_provider_scope(manifest: DeploymentManifest) -> ManagedMutation:+ path = codex_config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ section = (+ f"{_CODEX_MARKER_START}\n"+ 'model_provider = "headroom"\n\n'+ "[model_providers.headroom]\n"+ 'name = "Headroom persistent proxy"\n'+ f'base_url = "http://127.0.0.1:{manifest.port}/v1"\n'+ 'env_key = "OPENAI_API_KEY"\n'+ "requires_openai_auth = true\n"+ "supports_websockets = true\n"+ f"{_CODEX_MARKER_END}\n"+ )+ merged = _merge_marker_block(path, section, _CODEX_PATTERN, _CODEX_MARKER_START)+ path.write_text(merged)+ return ManagedMutation(target=ToolTarget.CODEX.value, kind="toml-block", path=str(path))+++def _revert_codex_provider_scope(mutation: ManagedMutation) -> None:+ if not mutation.path:+ return+ path = Path(mutation.path)+ if not path.exists():+ return+ content = path.read_text()+ if _CODEX_MARKER_START not in content:+ return+ path.write_text(_CODEX_PATTERN.sub("", content).strip() + "\n")+++def _invoke_openclaw(command: list[str]) -> None:+ subprocess.run(command, check=True)+++def _apply_openclaw_provider_scope(manifest: DeploymentManifest) -> ManagedMutation:+ if not shutil_which("openclaw"):+ raise click.ClickException("openclaw not found in PATH; cannot apply provider scope.")+ command = [+ *resolve_headroom_command(),+ "wrap",+ "openclaw",+ "--no-auto-start",+ "--proxy-port",+ str(manifest.port),+ ]+ _invoke_openclaw(command)+ return ManagedMutation(+ target=ToolTarget.OPENCLAW.value, kind="openclaw-wrap", path=str(openclaw_config_path())+ )+++def _revert_openclaw_provider_scope() -> None:+ if not shutil_which("openclaw"):+ return+ command = [*resolve_headroom_command(), "unwrap", "openclaw"]+ _invoke_openclaw(command)+++def shutil_which(name: str) -> str | None:+ from shutil import which++ return which(name)+++def apply_mutations(manifest: DeploymentManifest) -> list[ManagedMutation]:+ """Apply provider/user/system configuration for a deployment."""++ mutations: list[ManagedMutation] = []+ if manifest.scope in {ConfigScope.USER.value, ConfigScope.SYSTEM.value}:+ if os.name == "nt":+ mutations.extend(_apply_windows_env_scope(manifest))+ else:+ mutations.extend(_apply_unix_env_scope(manifest))+ if ToolTarget.OPENCLAW.value in manifest.targets:+ try:+ mutations.append(_apply_openclaw_provider_scope(manifest))+ except click.ClickException:+ pass+ return mutations++ if ToolTarget.CLAUDE.value in manifest.targets:+ mutations.append(_apply_claude_provider_scope(manifest))+ if ToolTarget.CODEX.value in manifest.targets:+ mutations.append(_apply_codex_provider_scope(manifest))+ if ToolTarget.OPENCLAW.value in manifest.targets:+ try:+ mutations.append(_apply_openclaw_provider_scope(manifest))+ except click.ClickException:+ pass+ return mutations+++def revert_mutations(manifest: DeploymentManifest) -> None:+ """Undo the stored mutations for a deployment."""++ if manifest.scope in {ConfigScope.USER.value, ConfigScope.SYSTEM.value}:+ shell_mutations = [m for m in manifest.mutations if m.target == "env"]+ if os.name == "nt":+ _remove_windows_env_scope(shell_mutations)+ else:+ _remove_unix_env_scope(shell_mutations)++ for mutation in manifest.mutations:+ if mutation.target == ToolTarget.CLAUDE.value and mutation.kind == "json-env":+ _revert_claude_provider_scope(+ mutation, manifest.tool_envs.get(ToolTarget.CLAUDE.value, {})+ )+ elif mutation.target == ToolTarget.CODEX.value and mutation.kind == "toml-block":+ _revert_codex_provider_scope(mutation)+ elif mutation.target == ToolTarget.OPENCLAW.value and mutation.kind == "openclaw-wrap":+ _revert_openclaw_provider_scope()diff --git a/headroom/install/runtime.py b/headroom/install/runtime.pynew file mode 100644index 000000000..841d3490a--- /dev/null+++ b/headroom/install/runtime.py@@ -0,0 +1,233 @@+"""Runtime helpers for persistent deployments."""++from __future__ import annotations++import os+import shutil+import signal+import subprocess+import sys+import time+from pathlib import Path+from typing import Any++from .health import probe_ready+from .models import DeploymentManifest, InstallPreset, RuntimeKind+from .paths import log_path, pid_path+++def _deployment_env(manifest: DeploymentManifest) -> dict[str, str]:+ return {+ "HEADROOM_DEPLOYMENT_PROFILE": manifest.profile,+ "HEADROOM_DEPLOYMENT_PRESET": manifest.preset,+ "HEADROOM_DEPLOYMENT_RUNTIME": manifest.runtime_kind,+ "HEADROOM_DEPLOYMENT_SUPERVISOR": manifest.supervisor_kind,+ "HEADROOM_DEPLOYMENT_SCOPE": manifest.scope,+ }+++def resolve_headroom_command() -> list[str]:+ """Resolve the most reliable command to invoke headroom."""++ headroom_bin = shutil.which("headroom")+ if headroom_bin:+ return [headroom_bin]+ return [sys.executable, "-m", "headroom.cli"]+++def _runtime_env(manifest: DeploymentManifest) -> dict[str, str]:+ env = os.environ.copy()+ env.update(manifest.base_env)+ env.update(_deployment_env(manifest))+ return env+++def build_runtime_command(manifest: DeploymentManifest) -> list[str]:+ """Build the raw foreground command that runs the proxy."""++ if manifest.runtime_kind == RuntimeKind.PYTHON.value:+ return [sys.executable, "-m", "headroom.cli", "proxy", *manifest.proxy_args]++ home = str(Path.home())+ container_home = "/tmp/headroom-home"+ command = [+ "docker",+ "run",+ "--rm",+ "--name",+ manifest.container_name,+ "-p",+ f"127.0.0.1:{manifest.port}:{manifest.port}",+ "--workdir",+ container_home,+ "--env",+ f"HOME={container_home}",+ "--env",+ "PYTHONUNBUFFERED=1",+ "--volume",+ f"{home}\\.headroom:{container_home}/.headroom"+ if os.name == "nt"+ else f"{home}/.headroom:{container_home}/.headroom",+ "--volume",+ f"{home}\\.claude:{container_home}/.claude"+ if os.name == "nt"+ else f"{home}/.claude:{container_home}/.claude",+ "--volume",+ f"{home}\\.codex:{container_home}/.codex"+ if os.name == "nt"+ else f"{home}/.codex:{container_home}/.codex",+ "--volume",+ f"{home}\\.gemini:{container_home}/.gemini"+ if os.name == "nt"+ else f"{home}/.gemini:{container_home}/.gemini",+ ]+ runtime_env = {**manifest.base_env, **_deployment_env(manifest)}+ for name, value in runtime_env.items():+ command.extend(["--env", f"{name}={value}"])+ command.extend(+ [+ manifest.image,+ "headroom",+ "proxy",+ "--host",+ "0.0.0.0",+ *manifest.proxy_args[2:],+ ]+ )+ return command+++def _write_pid(profile: str, pid: int) -> None:+ path = pid_path(profile)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(str(pid))+++def _read_pid(profile: str) -> int | None:+ path = pid_path(profile)+ if not path.exists():+ return None+ try:+ return int(path.read_text().strip())+ except ValueError:+ return None+++def _clear_pid(profile: str) -> None:+ path = pid_path(profile)+ if path.exists():+ path.unlink()+++def run_foreground(manifest: DeploymentManifest) -> int:+ """Run the raw runtime command in the foreground."""++ command = build_runtime_command(manifest)+ env = _runtime_env(manifest)+ log_file_path = log_path(manifest.profile)+ log_file_path.parent.mkdir(parents=True, exist_ok=True)++ with open(log_file_path, "a", encoding="utf-8", errors="replace") as log_file:+ proc = subprocess.Popen(command, env=env, stdout=log_file, stderr=log_file)+ _write_pid(manifest.profile, proc.pid)++ def _cleanup(signum: int | None = None, frame: Any = None) -> None:+ if proc.poll() is None:+ proc.terminate()+ try:+ proc.wait(timeout=10)+ except subprocess.TimeoutExpired:+ proc.kill()++ signal.signal(signal.SIGINT, _cleanup)+ signal.signal(signal.SIGTERM, _cleanup)+ try:+ return proc.wait()+ finally:+ _clear_pid(manifest.profile)+++def start_detached_agent(profile: str) -> subprocess.Popen[str]:+ """Start `headroom install agent run` detached for the given profile."""++ command = [*resolve_headroom_command(), "install", "agent", "run", "--profile", profile]+ log_file_path = log_path(profile)+ log_file_path.parent.mkdir(parents=True, exist_ok=True)+ log_file = open(log_file_path, "a", encoding="utf-8", errors="replace") # noqa: SIM115++ kwargs: dict[str, Any] = {"stdout": log_file, "stderr": log_file}+ if os.name == "nt":+ kwargs["creationflags"] = getattr(subprocess, "DETACHED_PROCESS", 0) | getattr(+ subprocess, "CREATE_NEW_PROCESS_GROUP", 0+ )+ else:+ kwargs["start_new_session"] = True+ return subprocess.Popen(command, **kwargs)+++def start_persistent_docker(manifest: DeploymentManifest) -> None:+ """Start a persistent Docker container with restart policy."""++ command = build_runtime_command(manifest)+ docker_cmd = [+ "docker",+ "run",+ "-d",+ "--restart",+ "unless-stopped",+ "--name",+ manifest.container_name,+ *command[5:], # drop initial `docker run --rm --name ...`+ ]+ subprocess.run(["docker", "rm", "-f", manifest.container_name], capture_output=True, text=True)+ subprocess.run(docker_cmd, check=True)+++def stop_runtime(manifest: DeploymentManifest) -> None:+ """Stop the raw runtime for the deployment."""++ if manifest.preset == InstallPreset.PERSISTENT_DOCKER.value:+ subprocess.run(["docker", "stop", manifest.container_name], capture_output=True, text=True)+ subprocess.run(+ ["docker", "rm", "-f", manifest.container_name], capture_output=True, text=True+ )+ return++ pid = _read_pid(manifest.profile)+ if pid is None:+ return+ try:+ os.kill(pid, signal.SIGTERM)+ except OSError:+ pass+ _clear_pid(manifest.profile)+++def wait_ready(manifest: DeploymentManifest, timeout_seconds: int = 30) -> bool:+ """Wait for the deployment to report ready."""++ for _ in range(timeout_seconds):+ if probe_ready(manifest.health_url):+ return True+ time.sleep(1)+ return False+++def runtime_status(manifest: DeploymentManifest) -> str:+ """Return a short status string for the deployment runtime."""++ if manifest.preset == InstallPreset.PERSISTENT_DOCKER.value:+ result = subprocess.run(+ ["docker", "ps", "--format", "{{.Names}}"], capture_output=True, text=True+ )+ if manifest.container_name in result.stdout.splitlines():+ return "running"+ return "stopped"+ pid = _read_pid(manifest.profile)+ if pid is None:+ return "stopped"+ try:+ os.kill(pid, 0)+ except OSError:+ return "stopped"+ return "running"diff --git a/headroom/install/state.py b/headroom/install/state.pynew file mode 100644index 000000000..6b3151ebc--- /dev/null+++ b/headroom/install/state.py@@ -0,0 +1,60 @@+"""Persistence helpers for deployment manifests."""++from __future__ import annotations++import json+from dataclasses import asdict++from .models import ArtifactRecord, DeploymentManifest, ManagedMutation, iso_utc_now+from .paths import deploy_root, manifest_path, profile_root+++def save_manifest(manifest: DeploymentManifest) -> None:+ """Persist a deployment manifest to disk."""++ root = profile_root(manifest.profile)+ root.mkdir(parents=True, exist_ok=True)+ manifest.updated_at = iso_utc_now()+ path = manifest_path(manifest.profile)+ path.write_text(json.dumps(asdict(manifest), indent=2) + "\n")+++def load_manifest(profile: str = "default") -> DeploymentManifest | None:+ """Load a deployment manifest when present."""++ path = manifest_path(profile)+ if not path.exists():+ return None+ payload = json.loads(path.read_text())+ payload["mutations"] = [ManagedMutation(**item) for item in payload.get("mutations", [])]+ payload["artifacts"] = [ArtifactRecord(**item) for item in payload.get("artifacts", [])]+ return DeploymentManifest(**payload)+++def list_manifests() -> list[DeploymentManifest]:+ """Load all deployment manifests under the deployment root."""++ root = deploy_root()+ if not root.exists():+ return []++ manifests: list[DeploymentManifest] = []+ for candidate in sorted(root.glob("*/manifest.json")):+ try:+ payload = json.loads(candidate.read_text())+ payload["mutations"] = [+ ManagedMutation(**item) for item in payload.get("mutations", [])+ ]+ payload["artifacts"] = [ArtifactRecord(**item) for item in payload.get("artifacts", [])]+ manifests.append(DeploymentManifest(**payload))+ except (OSError, ValueError, TypeError):+ continue+ return manifests+++def delete_manifest(profile: str = "default") -> None:+ """Delete the deployment manifest if present."""++ path = manifest_path(profile)+ if path.exists():+ path.unlink()diff --git a/headroom/install/supervisors.py b/headroom/install/supervisors.pynew file mode 100644index 000000000..376f74596--- /dev/null+++ b/headroom/install/supervisors.py@@ -0,0 +1,413 @@+"""Supervisor installation helpers for persistent deployments."""++from __future__ import annotations++import os+import re+import shlex+import subprocess+import sys+from pathlib import Path++import click++from .models import ArtifactRecord, DeploymentManifest, SupervisorKind+from .paths import (+ unix_ensure_script_path,+ unix_run_script_path,+ windows_ensure_cmd_path,+ windows_ensure_script_path,+ windows_run_cmd_path,+ windows_run_script_path,+)+from .runtime import resolve_headroom_command+++def _command_for_script(*parts: str) -> list[str]:+ return [*resolve_headroom_command(), *parts]+++def _render_unix_runner(path: Path, command: list[str]) -> ArtifactRecord:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ "#!/usr/bin/env bash\nset -euo pipefail\nexec "+ + " ".join(shlex.quote(x) for x in command)+ + "\n"+ )+ path.chmod(0o755)+ return ArtifactRecord(kind="script", path=str(path))+++def _render_windows_runner(+ ps1_path: Path, cmd_path: Path, command: list[str]+) -> list[ArtifactRecord]:+ ps1_path.parent.mkdir(parents=True, exist_ok=True)+ escaped = " ".join(+ [f'"{item}"' if (" " in item or item.endswith(".cmd")) else item for item in command]+ )+ ps1_path.write_text(f"$ErrorActionPreference = 'Stop'\n& {escaped}\nexit $LASTEXITCODE\n")+ cmd_path.write_text(+ '@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0'+ + ps1_path.name+ + '" %*\r\n'+ )+ return [+ ArtifactRecord(kind="script", path=str(ps1_path)),+ ArtifactRecord(kind="script", path=str(cmd_path)),+ ]+++def render_runner_scripts(manifest: DeploymentManifest) -> list[ArtifactRecord]:+ """Render runner/watchdog scripts for the deployment profile."""++ if os.name == "nt":+ records = []+ records.extend(+ _render_windows_runner(+ windows_run_script_path(manifest.profile),+ windows_run_cmd_path(manifest.profile),+ _command_for_script("install", "agent", "run", "--profile", manifest.profile),+ )+ )+ records.extend(+ _render_windows_runner(+ windows_ensure_script_path(manifest.profile),+ windows_ensure_cmd_path(manifest.profile),+ _command_for_script("install", "agent", "ensure", "--profile", manifest.profile),+ )+ )+ return records++ return [+ _render_unix_runner(+ unix_run_script_path(manifest.profile),+ _command_for_script("install", "agent", "run", "--profile", manifest.profile),+ ),+ _render_unix_runner(+ unix_ensure_script_path(manifest.profile),+ _command_for_script("install", "agent", "ensure", "--profile", manifest.profile),+ ),+ ]+++def _linux_service_unit(manifest: DeploymentManifest, run_script: Path) -> tuple[Path, str]:+ if manifest.scope == "system":+ unit_path = Path("/etc/systemd/system") / f"{manifest.service_name}.service"+ else:+ unit_path = (+ Path.home() / ".config" / "systemd" / "user" / f"{manifest.service_name}.service"+ )+ content = f"""[Unit]+Description=Headroom ({manifest.profile})+After=network-online.target++[Service]+Type=simple+ExecStart={run_script}+Restart=on-failure+RestartSec=5++[Install]+WantedBy=default.target+"""+ return unit_path, content+++def _macos_launchd_plist(+ manifest: DeploymentManifest, command_path: Path, *, interval: int | None = None+) -> tuple[Path, str]:+ if manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ base_dir = (+ Path("/Library/LaunchDaemons")+ if manifest.scope == "system"+ else Path.home() / "Library" / "LaunchAgents"+ )+ else:+ base_dir = Path.home() / "Library" / "LaunchAgents"+ plist_path = base_dir / f"com.headroom.{manifest.profile}.plist"+ program = str(command_path)+ keys = [+ '<?xml version="1.0" encoding="UTF-8"?>',+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',+ '<plist version="1.0">',+ "<dict>",+ " <key>Label</key>",+ f" <string>com.headroom.{manifest.profile}</string>",+ " <key>ProgramArguments</key>",+ " <array>",+ f" <string>{program}</string>",+ " </array>",+ " <key>RunAtLoad</key>",+ " <true/>",+ ]+ if interval is not None:+ keys.extend([" <key>StartInterval</key>", f" <integer>{interval}</integer>"])+ else:+ keys.extend([" <key>KeepAlive</key>", " <true/>"])+ keys.extend(["</dict>", "</plist>"])+ return plist_path, "\n".join(keys) + "\n"+++def _linux_task_spec(manifest: DeploymentManifest, ensure_script: Path) -> tuple[Path | None, str]:+ if manifest.scope == "system":+ cron_path = Path("/etc/cron.d") / manifest.service_name+ content = f"@reboot root {ensure_script}\n*/5 * * * * root {ensure_script}\n"+ return cron_path, content++ marker_start = f"# >>> headroom {manifest.profile} >>>"+ marker_end = f"# <<< headroom {manifest.profile} <<<"+ content = (+ f"{marker_start}\n@reboot {ensure_script}\n*/5 * * * * {ensure_script}\n{marker_end}\n"+ )+ return None, content+++def install_supervisor(manifest: DeploymentManifest) -> list[ArtifactRecord]:+ """Install service/task artifacts for the deployment."""++ records = render_runner_scripts(manifest)+ artifact_paths = {Path(item.path).name: Path(item.path) for item in records}++ if manifest.supervisor_kind == SupervisorKind.NONE.value:+ return records++ if (+ sys.platform.startswith("linux")+ and manifest.supervisor_kind == SupervisorKind.SERVICE.value+ ):+ unit_path, content = _linux_service_unit(manifest, artifact_paths["run-headroom.sh"])+ unit_path.parent.mkdir(parents=True, exist_ok=True)+ unit_path.write_text(content)+ flags = [] if manifest.scope == "system" else ["--user"]+ subprocess.run(["systemctl", *flags, "daemon-reload"], check=True)+ subprocess.run(["systemctl", *flags, "enable", manifest.service_name], check=True)+ records.append(ArtifactRecord(kind="service-unit", path=str(unit_path)))+ return records++ if sys.platform.startswith("linux") and manifest.supervisor_kind == SupervisorKind.TASK.value:+ cron_path, content = _linux_task_spec(manifest, artifact_paths["ensure-headroom.sh"])+ if cron_path is not None:+ cron_path.parent.mkdir(parents=True, exist_ok=True)+ cron_path.write_text(content)+ records.append(ArtifactRecord(kind="cron", path=str(cron_path)))+ else:+ current = subprocess.run(["crontab", "-l"], capture_output=True, text=True)+ existing = current.stdout if current.returncode == 0 else ""+ marker_start = f"# >>> headroom {manifest.profile} >>>"+ marker_end = f"# <<< headroom {manifest.profile} <<<"+ pattern = re.compile(+ re.escape(marker_start) + r".*?" + re.escape(marker_end), re.DOTALL+ )+ merged = pattern.sub("", existing).strip()+ new_content = (merged + "\n\n" + content).strip() + "\n"+ subprocess.run(["crontab", "-"], input=new_content, text=True, check=True)+ records.append(ArtifactRecord(kind="crontab", path=f"user:{manifest.profile}"))+ return records++ if sys.platform == "darwin":+ if manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ plist_path, content = _macos_launchd_plist(manifest, artifact_paths["run-headroom.sh"])+ else:+ plist_path, content = _macos_launchd_plist(+ manifest, artifact_paths["ensure-headroom.sh"], interval=300+ )+ plist_path.parent.mkdir(parents=True, exist_ok=True)+ plist_path.write_text(content)+ domain = (+ f"system/{plist_path.stem}"+ if manifest.scope == "system"+ and manifest.supervisor_kind == SupervisorKind.SERVICE.value+ else f"gui/{os.getuid()}/{plist_path.stem}"+ )+ subprocess.run(["launchctl", "bootout", domain], capture_output=True, text=True)+ bootstrap_domain = (+ "system"+ if manifest.scope == "system"+ and manifest.supervisor_kind == SupervisorKind.SERVICE.value+ else f"gui/{os.getuid()}"+ )+ subprocess.run(["launchctl", "bootstrap", bootstrap_domain, str(plist_path)], check=True)+ records.append(ArtifactRecord(kind="plist", path=str(plist_path)))+ return records++ if os.name == "nt" and manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ service_bin = f'cmd.exe /c "{windows_run_cmd_path(manifest.profile)}"'+ subprocess.run(+ ["sc.exe", "create", manifest.service_name, f"binPath= {service_bin}", "start= auto"],+ check=True,+ )+ subprocess.run(+ ["sc.exe", "failure", manifest.service_name, "reset= 0", "actions= restart/5000"],+ check=True,+ )+ records.append(ArtifactRecord(kind="windows-service", path=manifest.service_name))+ return records++ if os.name == "nt" and manifest.supervisor_kind == SupervisorKind.TASK.value:+ startup_name = f"{manifest.service_name}-startup"+ health_name = f"{manifest.service_name}-health"+ startup_cmd = str(windows_ensure_cmd_path(manifest.profile))+ user_args = ["/RU", "SYSTEM"] if manifest.scope == "system" else []+ start_schedule = [+ "schtasks",+ "/Create",+ "/TN",+ startup_name,+ "/TR",+ startup_cmd,+ "/SC",+ "ONSTART",+ "/F",+ *user_args,+ ]+ health_schedule = [+ "schtasks",+ "/Create",+ "/TN",+ health_name,+ "/TR",+ startup_cmd,+ "/SC",+ "MINUTE",+ "/MO",+ "5",+ "/F",+ *user_args,+ ]+ subprocess.run(start_schedule, check=True)+ subprocess.run(health_schedule, check=True)+ records.extend(+ [+ ArtifactRecord(kind="windows-task", path=startup_name),+ ArtifactRecord(kind="windows-task", path=health_name),+ ]+ )+ return records++ raise click.ClickException(+ f"Persistent {manifest.supervisor_kind} mode is not supported on this platform."+ )+++def start_supervisor(manifest: DeploymentManifest) -> None:+ """Start the installed supervisor or runtime for a deployment."""++ if manifest.supervisor_kind == SupervisorKind.NONE.value:+ return+ if sys.platform.startswith("linux"):+ flags = [] if manifest.scope == "system" else ["--user"]+ subprocess.run(["systemctl", *flags, "restart", manifest.service_name], check=True)+ return+ if sys.platform == "darwin":+ label = f"com.headroom.{manifest.profile}"+ domain = (+ "system"+ if manifest.scope == "system"+ and manifest.supervisor_kind == SupervisorKind.SERVICE.value+ else f"gui/{os.getuid()}"+ )+ subprocess.run(["launchctl", "kickstart", "-k", f"{domain}/{label}"], check=True)+ return+ if os.name == "nt" and manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ subprocess.run(["sc.exe", "start", manifest.service_name], check=True)+++def stop_supervisor(manifest: DeploymentManifest) -> None:+ """Stop the installed supervisor for a deployment."""++ if manifest.supervisor_kind == SupervisorKind.NONE.value:+ return+ if sys.platform.startswith("linux"):+ flags = [] if manifest.scope == "system" else ["--user"]+ subprocess.run(["systemctl", *flags, "stop", manifest.service_name], check=True)+ return+ if sys.platform == "darwin":+ label = f"com.headroom.{manifest.profile}"+ domain = (+ "system"+ if manifest.scope == "system"+ and manifest.supervisor_kind == SupervisorKind.SERVICE.value+ else f"gui/{os.getuid()}"+ )+ subprocess.run(["launchctl", "bootout", f"{domain}/{label}"], check=True)+ return+ if os.name == "nt" and manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ subprocess.run(["sc.exe", "stop", manifest.service_name], check=True)+++def remove_supervisor(manifest: DeploymentManifest) -> None:+ """Remove installed service/task artifacts."""++ if manifest.supervisor_kind == SupervisorKind.NONE.value:+ return++ if sys.platform.startswith("linux"):+ if manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ flags = [] if manifest.scope == "system" else ["--user"]+ subprocess.run(+ ["systemctl", *flags, "disable", "--now", manifest.service_name],+ capture_output=True,+ text=True,+ )+ unit_path, _ = _linux_service_unit(manifest, unix_run_script_path(manifest.profile))+ if unit_path.exists():+ unit_path.unlink()+ subprocess.run(["systemctl", *flags, "daemon-reload"], capture_output=True, text=True)+ return+ cron_path, _ = _linux_task_spec(manifest, unix_ensure_script_path(manifest.profile))+ if cron_path and cron_path.exists():+ cron_path.unlink()+ return+ current = subprocess.run(["crontab", "-l"], capture_output=True, text=True)+ if current.returncode != 0:+ return+ marker_start = f"# >>> headroom {manifest.profile} >>>"+ marker_end = f"# <<< headroom {manifest.profile} <<<"+ pattern = re.compile(re.escape(marker_start) + r".*?" + re.escape(marker_end), re.DOTALL)+ content = pattern.sub("", current.stdout).strip()+ subprocess.run(+ ["crontab", "-"], input=(content + "\n") if content else "", text=True, check=True+ )+ return++ if sys.platform == "darwin":+ plist_path, _ = _macos_launchd_plist(+ manifest,+ unix_run_script_path(manifest.profile)+ if manifest.supervisor_kind == SupervisorKind.SERVICE.value+ else unix_ensure_script_path(manifest.profile),+ interval=300 if manifest.supervisor_kind == SupervisorKind.TASK.value else None,+ )+ label = f"com.headroom.{manifest.profile}"+ domain = (+ "system"+ if manifest.scope == "system"+ and manifest.supervisor_kind == SupervisorKind.SERVICE.value+ else f"gui/{os.getuid()}"+ )+ subprocess.run(+ ["launchctl", "bootout", f"{domain}/{label}"], capture_output=True, text=True+ )+ if plist_path.exists():+ plist_path.unlink()+ return++ if os.name == "nt":+ if manifest.supervisor_kind == SupervisorKind.SERVICE.value:+ subprocess.run(+ ["sc.exe", "stop", manifest.service_name], capture_output=True, text=True+ )+ subprocess.run(+ ["sc.exe", "delete", manifest.service_name], capture_output=True, text=True+ )+ return+ subprocess.run(+ ["schtasks", "/Delete", "/TN", f"{manifest.service_name}-startup", "/F"],+ capture_output=True,+ text=True,+ )+ subprocess.run(+ ["schtasks", "/Delete", "/TN", f"{manifest.service_name}-health", "/F"],+ capture_output=True,+ text=True,+ )diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex de216f832..036c1e980 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -1093,6 +1093,15 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:"uptime_seconds": _uptime_seconds(),"checks": checks,}+ deployment_profile = os.environ.get("HEADROOM_DEPLOYMENT_PROFILE")+ if deployment_profile:+ payload["deployment"] = {+ "profile": deployment_profile,+ "preset": os.environ.get("HEADROOM_DEPLOYMENT_PRESET"),+ "runtime": os.environ.get("HEADROOM_DEPLOYMENT_RUNTIME"),+ "supervisor": os.environ.get("HEADROOM_DEPLOYMENT_SUPERVISOR"),+ "scope": os.environ.get("HEADROOM_DEPLOYMENT_SCOPE"),+ }if include_config:payload["config"] = {"backend": config.backend,diff --git a/mkdocs.yml b/mkdocs.ymlindex b137bcb1f..221cf9413 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -87,6 +87,7 @@ nav:- Quickstart: quickstart.md- Installation: getting-started.md- Docker-Native Install: docker-install.md+ - Persistent Installs: persistent-installs.md- Configuration: configuration.md- User Guide:- Proxy Server: proxy.mddiff --git a/tests/test_cli/test_install_cli.py b/tests/test_cli/test_install_cli.pynew file mode 100644index 000000000..6c0d749f9--- /dev/null+++ b/tests/test_cli/test_install_cli.py@@ -0,0 +1,113 @@+from __future__ import annotations++from click.testing import CliRunner++from headroom.cli.main import main+++def test_install_apply_starts_service_supervisor(monkeypatch) -> None:+ runner = CliRunner()+ calls: list[str] = []++ class Manifest:+ profile = "default"+ preset = "persistent-service"+ runtime_kind = "python"+ supervisor_kind = "service"+ scope = "user"+ health_url = "http://127.0.0.1:8787/readyz"+ targets = ["claude", "codex"]+ mutations = []+ artifacts = []++ manifest = Manifest()++ monkeypatch.setattr("headroom.cli.install.build_manifest", lambda **_: manifest)+ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: None)+ monkeypatch.setattr("headroom.cli.install.apply_mutations", lambda deployment: [])+ monkeypatch.setattr("headroom.cli.install.install_supervisor", lambda deployment: [])+ monkeypatch.setattr(+ "headroom.cli.install.save_manifest", lambda deployment: calls.append("save")+ )+ monkeypatch.setattr(+ "headroom.cli.install.start_supervisor", lambda deployment: calls.append("start_service")+ )+ monkeypatch.setattr(+ "headroom.cli.install.start_detached_agent", lambda profile: calls.append("start_agent")+ )+ monkeypatch.setattr(+ "headroom.cli.install.start_persistent_docker",+ lambda deployment: calls.append("start_docker"),+ )+ monkeypatch.setattr(+ "headroom.cli.install.wait_ready", lambda deployment, timeout_seconds=45: True+ )++ result = runner.invoke(main, ["install", "apply"])++ assert result.exit_code == 0, result.output+ assert "Installed persistent deployment 'default'" in result.output+ assert "Targets: claude, codex" in result.output+ assert calls == ["save", "start_service"]+++def test_install_status_includes_backend_from_health_probe(monkeypatch) -> None:+ runner = CliRunner()++ class Manifest:+ profile = "default"+ preset = "persistent-service"+ runtime_kind = "python"+ supervisor_kind = "service"+ scope = "user"+ port = 8787+ backend = "anthropic"+ health_url = "http://127.0.0.1:8787/readyz"++ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())+ monkeypatch.setattr("headroom.cli.install.runtime_status", lambda manifest: "running")+ monkeypatch.setattr("headroom.cli.install.probe_ready", lambda url: True)+ monkeypatch.setattr(+ "headroom.cli.install.probe_json",+ lambda url: {"config": {"backend": "anthropic"}},+ )++ result = runner.invoke(main, ["install", "status"])++ assert result.exit_code == 0, result.output+ assert "Status: running" in result.output+ assert "Healthy: yes" in result.output+ assert "Backend: anthropic" in result.output+++def test_install_restart_uses_internal_helpers(monkeypatch) -> None:+ runner = CliRunner()+ calls: list[str] = []++ class Manifest:+ profile = "default"+ preset = "persistent-service"+ runtime_kind = "python"+ supervisor_kind = "service"+ scope = "user"+ health_url = "http://127.0.0.1:8787/readyz"++ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())+ monkeypatch.setattr(+ "headroom.cli.install.stop_supervisor", lambda manifest: calls.append("stop_supervisor")+ )+ monkeypatch.setattr(+ "headroom.cli.install.stop_runtime", lambda manifest: calls.append("stop_runtime")+ )+ monkeypatch.setattr(+ "headroom.cli.install.start_supervisor", lambda manifest: calls.append("start_supervisor")+ )+ monkeypatch.setattr(+ "headroom.cli.install.wait_ready", lambda manifest, timeout_seconds=45: True+ )++ result = runner.invoke(main, ["install", "restart"])++ assert result.exit_code == 0, result.output+ assert "Restarted deployment 'default'." in result.output+ assert calls == ["stop_supervisor", "stop_runtime", "start_supervisor"]diff --git a/tests/test_cli/test_wrap_persistent.py b/tests/test_cli/test_wrap_persistent.pynew file mode 100644index 000000000..cf087d7ac--- /dev/null+++ b/tests/test_cli/test_wrap_persistent.py@@ -0,0 +1,56 @@+from __future__ import annotations++from headroom.cli.wrap import _ensure_proxy+++class _Manifest:+ profile = "default"+ preset = "persistent-service"+ supervisor_kind = "service"+ health_url = "http://127.0.0.1:8787/readyz"+++def test_ensure_proxy_recovers_matching_persistent_deployment(monkeypatch) -> None:+ calls: list[str] = []++ monkeypatch.setattr("headroom.cli.wrap._check_proxy", lambda port: False)+ monkeypatch.setattr("headroom.cli.wrap._find_persistent_manifest", lambda port: _Manifest())+ monkeypatch.setattr("headroom.install.health.probe_ready", lambda url: False)+ monkeypatch.setattr(+ "headroom.install.supervisors.start_supervisor",+ lambda manifest: calls.append(f"start:{manifest.profile}"),+ )+ monkeypatch.setattr(+ "headroom.install.runtime.wait_ready", lambda manifest, timeout_seconds=45: True+ )+ monkeypatch.setattr(+ "headroom.cli.wrap._start_proxy",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ AssertionError("ephemeral proxy should not start")+ ),+ )++ result = _ensure_proxy(8787, False)++ assert result is None+ assert calls == ["start:default"]+++def test_ensure_proxy_recovers_persistent_deployment_when_socket_is_bound(monkeypatch) -> None:+ calls: list[str] = []++ monkeypatch.setattr("headroom.cli.wrap._check_proxy", lambda port: True)+ monkeypatch.setattr("headroom.cli.wrap._find_persistent_manifest", lambda port: _Manifest())+ monkeypatch.setattr("headroom.install.health.probe_ready", lambda url: False)+ monkeypatch.setattr(+ "headroom.install.supervisors.start_supervisor",+ lambda manifest: calls.append(f"start:{manifest.profile}"),+ )+ monkeypatch.setattr(+ "headroom.install.runtime.wait_ready", lambda manifest, timeout_seconds=45: True+ )++ result = _ensure_proxy(8787, False)++ assert result is None+ assert calls == ["start:default"]diff --git a/tests/test_install/test_planner.py b/tests/test_install/test_planner.pynew file mode 100644index 000000000..9bbe3c449--- /dev/null+++ b/tests/test_install/test_planner.py@@ -0,0 +1,44 @@+from __future__ import annotations++from headroom.install.models import InstallPreset, ProviderSelectionMode, ToolTarget+from headroom.install.planner import build_manifest, resolve_targets+++def test_resolve_targets_auto_falls_back_when_detection_empty(monkeypatch) -> None:+ monkeypatch.setattr("headroom.install.planner.detect_targets", lambda: [])++ targets = resolve_targets(ProviderSelectionMode.AUTO.value, [])++ assert targets == [+ ToolTarget.CLAUDE.value,+ ToolTarget.CODEX.value,+ ToolTarget.COPILOT.value,+ ]+++def test_build_manifest_for_persistent_docker_sets_expected_defaults() -> None:+ manifest = build_manifest(+ profile="default",+ preset=InstallPreset.PERSISTENT_DOCKER.value,+ runtime_kind="docker",+ scope="user",+ provider_mode="manual",+ targets=["claude", "copilot"],+ port=8787,+ backend="anthropic",+ anyllm_provider=None,+ region=None,+ proxy_mode="token",+ memory_enabled=True,+ telemetry_enabled=False,+ image="ghcr.io/chopratejas/headroom:latest",+ )++ assert manifest.supervisor_kind == "none"+ assert manifest.runtime_kind == "docker"+ assert manifest.health_url == "http://127.0.0.1:8787/readyz"+ assert manifest.base_env["HEADROOM_PORT"] == "8787"+ assert manifest.base_env["HEADROOM_TELEMETRY"] == "off"+ assert manifest.tool_envs["claude"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8787"+ assert manifest.tool_envs["copilot"]["COPILOT_PROVIDER_TYPE"] == "anthropic"+ assert "--memory" in manifest.proxy_argsdiff --git a/tests/test_install/test_providers.py b/tests/test_install/test_providers.pynew file mode 100644index 000000000..135f5e5be--- /dev/null+++ b/tests/test_install/test_providers.py@@ -0,0 +1,93 @@+from __future__ import annotations++import json+from pathlib import Path++from headroom.install.models import DeploymentManifest+from headroom.install.providers import (+ _apply_claude_provider_scope,+ _apply_codex_provider_scope,+ _revert_claude_provider_scope,+ _revert_codex_provider_scope,+)+++def _manifest(tmp_path: Path) -> DeploymentManifest:+ return DeploymentManifest(+ profile="default",+ preset="persistent-service",+ runtime_kind="python",+ supervisor_kind="service",+ scope="provider",+ provider_mode="manual",+ targets=["claude", "codex"],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ memory_db_path=str(tmp_path / "memory.db"),+ tool_envs={+ "claude": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"},+ "codex": {"OPENAI_BASE_URL": "http://127.0.0.1:8787/v1"},+ },+ )+++def test_apply_and_revert_claude_provider_scope(monkeypatch, tmp_path: Path) -> None:+ settings_path = tmp_path / "settings.json"+ settings_path.write_text(+ json.dumps({"env": {"ANTHROPIC_API_KEY": "keep", "ANTHROPIC_BASE_URL": "https://old"}})+ )+ monkeypatch.setattr("headroom.install.providers.claude_settings_path", lambda: settings_path)+ manifest = _manifest(tmp_path)++ mutation = _apply_claude_provider_scope(manifest)+ payload = json.loads(settings_path.read_text())+ assert payload["env"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8787"+ assert payload["env"]["ANTHROPIC_API_KEY"] == "keep"++ _revert_claude_provider_scope(mutation, manifest.tool_envs["claude"])+ reverted = json.loads(settings_path.read_text())+ assert reverted["env"]["ANTHROPIC_BASE_URL"] == "https://old"+ assert reverted["env"]["ANTHROPIC_API_KEY"] == "keep"+++def test_apply_and_revert_codex_provider_scope(monkeypatch, tmp_path: Path) -> None:+ config_path = tmp_path / "config.toml"+ config_path.write_text('model = "gpt-4o"\n')+ monkeypatch.setattr("headroom.install.providers.codex_config_path", lambda: config_path)+ manifest = _manifest(tmp_path)++ mutation = _apply_codex_provider_scope(manifest)+ content = config_path.read_text()+ assert 'model_provider = "headroom"' in content+ assert 'base_url = "http://127.0.0.1:8787/v1"' in content++ _revert_codex_provider_scope(mutation)+ reverted = config_path.read_text()+ assert 'model_provider = "headroom"' not in reverted+ assert reverted.strip() == 'model = "gpt-4o"'+++def test_apply_openclaw_provider_scope_uses_manifest_port(monkeypatch, tmp_path: Path) -> None:+ recorded: list[list[str]] = []+ monkeypatch.setattr("headroom.install.providers.shutil_which", lambda name: "openclaw")+ monkeypatch.setattr(+ "headroom.install.providers.resolve_headroom_command",+ lambda: ["headroom"],+ )+ monkeypatch.setattr(+ "headroom.install.providers._invoke_openclaw",+ lambda command: recorded.append(command),+ )+ monkeypatch.setattr(+ "headroom.install.providers.openclaw_config_path",+ lambda: tmp_path / "openclaw.json",+ )+ manifest = _manifest(tmp_path)+ manifest.port = 9999++ from headroom.install.providers import _apply_openclaw_provider_scope++ _apply_openclaw_provider_scope(manifest)++ assert recorded == [["headroom", "wrap", "openclaw", "--no-auto-start", "--proxy-port", "9999"]]diff --git a/tests/test_install/test_runtime.py b/tests/test_install/test_runtime.pynew file mode 100644index 000000000..bf0d86267--- /dev/null+++ b/tests/test_install/test_runtime.py@@ -0,0 +1,36 @@+from __future__ import annotations++from pathlib import Path++from headroom.install.models import DeploymentManifest+from headroom.install.runtime import build_runtime_command+++def test_build_runtime_command_for_docker_includes_deployment_env(+ monkeypatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ manifest = DeploymentManifest(+ profile="default",+ preset="persistent-docker",+ runtime_kind="docker",+ supervisor_kind="none",+ scope="user",+ provider_mode="manual",+ targets=["claude"],+ port=8787,+ host="127.0.0.1",+ backend="anthropic",+ image="ghcr.io/chopratejas/headroom:latest",+ base_env={"HEADROOM_PORT": "8787"},+ proxy_args=["--host", "127.0.0.1", "--port", "8787"],+ )++ command = build_runtime_command(manifest)++ joined = " ".join(command)+ assert command[:3] == ["docker", "run", "--rm"]+ assert "HEADROOM_DEPLOYMENT_PROFILE=default" in joined+ assert "HEADROOM_DEPLOYMENT_PRESET=persistent-docker" in joined+ assert "127.0.0.1:8787:8787" in joined+ assert "ghcr.io/chopratejas/headroom:latest" in commanddiff --git a/tests/test_proxy_healthchecks.py b/tests/test_proxy_healthchecks.pyindex 2cfc99e85..bbe93c7fb 100644--- a/tests/test_proxy_healthchecks.py+++ b/tests/test_proxy_healthchecks.py@@ -64,6 +64,34 @@ def test_health_preserves_backwards_compatible_config_payload(client):}+def test_health_includes_deployment_metadata_when_present(monkeypatch):+ monkeypatch.setenv("HEADROOM_DEPLOYMENT_PROFILE", "default")+ monkeypatch.setenv("HEADROOM_DEPLOYMENT_PRESET", "persistent-service")+ monkeypatch.setenv("HEADROOM_DEPLOYMENT_RUNTIME", "python")+ monkeypatch.setenv("HEADROOM_DEPLOYMENT_SUPERVISOR", "service")+ monkeypatch.setenv("HEADROOM_DEPLOYMENT_SCOPE", "user")++ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ )+ app = create_app(config)++ with TestClient(app) as client:+ response = client.get("/health")++ assert response.status_code == 200+ assert response.json()["deployment"] == {+ "profile": "default",+ "preset": "persistent-service",+ "runtime": "python",+ "supervisor": "service",+ "scope": "user",+ }++def test_health_remains_200_when_proxy_is_not_ready(client):client.app.state.ready = False