Skip to content

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.

fix: harden persistent install wrappers and review gaps

JerrettDavis865bef221689
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2ec9b0772..d89e38cb8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -121,6 +121,31 @@ jobs:
run: |
bash e2e/docker-native-install.sh
+ - name: Run Docker-native compose smoke test
+ env:
+ HEADROOM_IMAGE: headroom-native-e2e:latest
+ HEADROOM_HOST_HOME: ${{ github.workspace }}
+ HEADROOM_WORKSPACE: ${{ github.workspace }}
+ run: |
+ mkdir -p .headroom .claude .codex .gemini
+ trap 'docker compose -f docker/docker-compose.native.yml down -v' EXIT
+ docker compose -f docker/docker-compose.native.yml up -d proxy
+ for attempt in $(seq 1 30); do
+ if curl --fail --silent http://127.0.0.1:8787/readyz >/dev/null; then
+ break
+ fi
+ if [ "$attempt" -eq 30 ]; then
+ docker compose -f docker/docker-compose.native.yml logs proxy
+ exit 1
+ fi
+ sleep 1
+ done
+
+ - name: Run Docker-native wrap e2e
+ run: |
+ docker build -f e2e/wrap/Dockerfile -t headroom-wrap-e2e .
+ docker run --rm headroom-wrap-e2e
+
windows-native-wrapper:
runs-on: windows-latest
steps:
diff --git a/README.md b/README.md
index 3fa15f337..5823bb855 100644
--- a/README.md
+++ b/README.md
@@ -87,16 +87,23 @@ npm install headroom-ai
curl -fsSL https://raw.githubusercontent.com/chopratejas/headroom/main/scripts/install.sh | bash
```
+macOS uses Bash 4.3+, so run the installer with a newer Bash such as Homebrew's `bash`.
+
PowerShell:
```powershell
irm https://raw.githubusercontent.com/chopratejas/headroom/main/scripts/install.ps1 | iex
```
-**Persistent local runtime:**
+**Persistent local runtime (Python-native service/task flow):**
```bash
headroom install apply --preset persistent-service --providers auto
```
+**Persistent local runtime (Docker-native wrapper / compose flow):**
+```bash
+headroom install apply --preset persistent-docker
+```
+
### Any agent — one function
**Python:**
@@ -149,7 +156,7 @@ Prefer Docker as the runtime provider? See **[Docker-native install](docs/docker
```bash
headroom wrap claude # Starts proxy + launches Claude Code
headroom wrap copilot -- --model claude-sonnet-4-20250514
- # Starts proxy + launches GitHub Copilot CLI
+ # Starts proxy + launches GitHub Copilot CLI
headroom wrap codex # Starts proxy + launches OpenAI Codex CLI
headroom wrap aider # Starts proxy + launches Aider
headroom wrap cursor # Starts proxy + prints Cursor config
@@ -159,7 +166,7 @@ headroom wrap codex --memory # Shares the same memory store
headroom wrap claude --code-graph # With code graph intelligence (codebase-memory-mcp)
```
-Headroom starts a proxy, points your tool at it, and compresses everything automatically. Add `--memory` for persistent memory that's shared across agents. Add `--code-graph` for code intelligence via [codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp) — indexes your codebase into a knowledge graph for call-chain traversal, impact analysis, and architectural queries.
+Headroom starts a proxy, points your tool at it, and compresses everything automatically. Add `--memory` for persistent memory that's shared across agents. Add `--code-graph` for code intelligence via [codebase-memory-mcp](https://github.com/DeusData/codebase-memory-mcp) — indexes your codebase into a knowledge graph for call-chain traversal, impact analysis, and architectural queries. `wrap copilot` is part of the Python-native CLI; the Docker-native wrapper currently supports `claude`, `codex`, `aider`, `cursor`, and `openclaw`.
In Docker-native mode, Headroom still runs in Docker while wrapped tools run on the host. `wrap claude`, `wrap codex`, `wrap aider`, `wrap cursor`, and OpenClaw plugin setup (`wrap openclaw` / `unwrap openclaw`) are host-managed through the installed wrapper.
@@ -519,6 +526,9 @@ Python 3.10+
| [MCP](docs/mcp.md) | Context engineering toolkit (compress, retrieve, stats) |
| [SharedContext](docs/shared-context.md) | Compressed inter-agent context sharing |
| [Learn](docs/learn.md) | Plugin-based failure learning (Claude, Codex, Gemini, extensible) |
+| [CLI Reference](docs/cli.md) | Complete command surface, help output, and Docker parity matrix |
+| [Docker-Native Install](docs/docker-install.md) | Host wrapper install, compose support, and Docker runtime behavior |
+| [Persistent Installs](docs/persistent-installs.md) | Service/task/docker deployment models and provider scopes |
| [Configuration](docs/configuration.md) | All options |
---
diff --git a/docs/docker-install.md b/docs/docker-install.md
index c1ac3c4f7..7aa3fedd2 100644
--- a/docs/docker-install.md
+++ b/docs/docker-install.md
@@ -108,6 +108,8 @@ In Docker-native mode this surface is intentionally scoped to **persistent-docke
Those broader lifecycle and config-mutation flows still belong to the Python-native `headroom install ...` command.
+Persistent Docker deployments launched by the wrapper also tag the proxy process with deployment metadata, so `/health` reports the active `profile`, `preset`, `runtime`, `supervisor`, and `scope` the same way the Python install subsystem does.
+
## Docker Compose support
Use `docker/docker-compose.native.yml` when you want an explicit compose-managed proxy or CLI shell, or when you prefer compose over the native wrapper's `headroom install ...` surface.
diff --git a/e2e/docker-native-install.sh b/e2e/docker-native-install.sh
index fe06134ec..42297e09a 100755
--- a/e2e/docker-native-install.sh
+++ b/e2e/docker-native-install.sh
@@ -24,6 +24,7 @@ trap cleanup EXIT
mkdir -p "${TMP_HOME}/.local"
export HOME="${TMP_HOME}"
export PATH="${HOME}/.local/bin:${PATH}"
+export HEADROOM_DOCKER_IMAGE="${IMAGE}"
bash "${ROOT_DIR}/scripts/install.sh"
@@ -42,8 +43,9 @@ status_output="$("${WRAPPER}" install status --profile "${PROFILE}")"
printf '%s\n' "${status_output}"
grep -Fq "Status: running" <<<"${status_output}"
curl --fail --silent "http://127.0.0.1:${PORT}/readyz" >/dev/null
+health_output="$(curl --fail --silent "http://127.0.0.1:${PORT}/health")"
-python3 - <<'PY' "${HOME}" "${PROFILE}" "${PORT}"
+python3 - <<'PY' "${HOME}" "${PROFILE}" "${PORT}" "${health_output}"
import json
import sys
from pathlib import Path
@@ -51,10 +53,14 @@ from pathlib import Path
home = Path(sys.argv[1])
profile = sys.argv[2]
port = int(sys.argv[3])
+health = json.loads(sys.argv[4])
manifest = json.loads((home / ".headroom" / "deploy" / profile / "manifest.json").read_text())
assert manifest["preset"] == "persistent-docker"
assert manifest["port"] == port
assert manifest["telemetry_enabled"] is False
+assert health["deployment"]["profile"] == profile
+assert health["deployment"]["preset"] == "persistent-docker"
+assert health["deployment"]["runtime"] == "docker"
PY
if apply_error="$("${WRAPPER}" install apply --scope user 2>&1)"; then
diff --git a/e2e/wrap/run.py b/e2e/wrap/run.py
index 1d8caed8c..9b914a765 100644
--- a/e2e/wrap/run.py
+++ b/e2e/wrap/run.py
@@ -261,6 +261,7 @@ def create_shims(shim_dir: Path) -> None:
raise SystemExit(0)
"""
)
+ write_executable(shim_dir / "claude", generic_shim)
write_executable(shim_dir / "codex", generic_shim)
write_executable(shim_dir / "aider", generic_shim)
write_executable(shim_dir / "rtk", rtk_shim)
@@ -466,6 +467,27 @@ def verify_codex_wrap(base_env: dict[str, str], project_dir: Path, log_dir: Path
)
+def verify_claude_wrap(base_env: dict[str, str], project_dir: Path, log_dir: Path) -> None:
+ port = PROXY_PORT + 10
+ run(
+ ["headroom", "wrap", "claude", "--port", str(port), "--", "--help"],
+ env=base_env,
+ cwd=project_dir,
+ timeout=120,
+ )
+ entries = read_jsonl(log_dir / "claude.jsonl")
+ assert_true(len(entries) > 0, "Claude shim should have been invoked")
+ env_vars = entries[-1]["env"]
+ assert_true(
+ env_vars.get("ANTHROPIC_BASE_URL") == f"http://127.0.0.1:{port}",
+ "Claude wrap should set ANTHROPIC_BASE_URL",
+ )
+ assert_true(
+ entries[-1]["probes"] == [{"url": f"http://127.0.0.1:{port}/health", "status": 200}],
+ "Claude shim should prove ANTHROPIC_BASE_URL points at a live proxy",
+ )
+
+
def verify_aider_wrap(base_env: dict[str, str], project_dir: Path, log_dir: Path) -> None:
port = AIDER_PORT
run(
@@ -624,6 +646,13 @@ def verify_openclaw_wrap(
stop_process(gateway_proc)
stop_openclaw_gateway(base_env, project_dir)
+ run(["headroom", "unwrap", "openclaw"], env=base_env, cwd=project_dir, timeout=120)
+ state = json.loads(config_path.read_text(encoding="utf-8"))
+ assert_true(
+ state["plugins"]["slots"]["contextEngine"] == "legacy",
+ "OpenClaw unwrap should restore the context engine slot",
+ )
+
def main() -> None:
verify_installs()
@@ -653,6 +682,7 @@ def main() -> None:
try:
verify_proxy_round_trip(base_env, mock_server)
+ verify_claude_wrap(base_env, project_dir, log_dir)
verify_codex_wrap(base_env, project_dir, log_dir)
verify_aider_wrap(base_env, project_dir, log_dir)
verify_cursor_wrap(base_env, project_dir)
diff --git a/headroom/cli/install.py b/headroom/cli/install.py
index d04e5d70a..c05ee9d75 100644
--- a/headroom/cli/install.py
+++ b/headroom/cli/install.py
@@ -1,305 +1,333 @@
-"""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)
-
-
- "--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]("--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]("--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]("--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]("--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.")
+"""Persistent install / deployment CLI commands."""
+
+from __future__ import annotations
+
+from copy import deepcopy
+
+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)
+
+
+def _remove_deployment(manifest: DeploymentManifest) -> None:
+ try:
+ _stop_deployment(manifest)
+ except Exception:
+ pass
+ try:
+ remove_supervisor(manifest)
+ except Exception:
+ pass
+ try:
+ revert_mutations(manifest)
+ except Exception:
+ pass
+ delete_manifest(manifest.profile)
+
+
+def _restore_deployment(manifest: DeploymentManifest) -> None:
+ restored = deepcopy(manifest)
+ restored.mutations = apply_mutations(restored)
+ restored.artifacts = install_supervisor(restored)
+ save_manifest(restored)
+ _start_deployment(restored)
+
+
+def _reject_task_lifecycle(manifest: DeploymentManifest, action: str) -> None:
+ if manifest.supervisor_kind == SupervisorKind.TASK.value:
+ raise click.ClickException(
+ f"Deployment '{manifest.profile}' uses persistent-task scheduling; "
+ f"`headroom install {action}` is not supported for task deployments."
+ )
+
+
+ "--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}'...")
+ _remove_deployment(existing)
+
+ try:
+ manifest.mutations = apply_mutations(manifest)
+ manifest.artifacts = install_supervisor(manifest)
+ save_manifest(manifest)
+ _start_deployment(manifest)
+ except Exception:
+ _remove_deployment(manifest)
+ if existing is not None:
+ click.echo(f"Restoring previous deployment '{profile}'...")
+ _restore_deployment(existing)
+ raise
+
+ 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]("--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]("--profile", default="default", show_default=True, help="Deployment profile name.")
+def install_start(profile: str) -> None:
+ """Start a persistent deployment."""
+
+ manifest = _require_manifest(profile)
+ _reject_task_lifecycle(manifest, "start")
+ _start_deployment(manifest)
+ click.echo(f"Started deployment '{profile}'.")
+
+
[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)
+ _reject_task_lifecycle(manifest, "stop")
+ _stop_deployment(manifest)
+ click.echo(f"Stopped deployment '{profile}'.")
+
+
[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)
+ _reject_task_lifecycle(manifest, "restart")
+ _stop_deployment(manifest)
+ _start_deployment(manifest)
+ click.echo(f"Restarted deployment '{profile}'.")
+
+
[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/wrap.py b/headroom/cli/wrap.py
index 88cbd43ce..a89c48a32 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -460,6 +460,12 @@ def _recover_persistent_proxy(port: int) -> bool:
click.echo(f" Reusing persistent deployment '{manifest.profile}' on port {port}")
return True
+ if manifest.supervisor_kind == SupervisorKind.TASK.value:
+ click.echo(
+ f" Warning: task-based deployment '{manifest.profile}' cannot be auto-recovered via wrap"
+ )
+ return False
+
click.echo(f" Recovering persistent deployment '{manifest.profile}' on port {port}...")
try:
if manifest.preset == InstallPreset.PERSISTENT_DOCKER.value:
@@ -517,6 +523,9 @@ def _ensure_proxy(
return None
if _recover_persistent_proxy(port):
return None
+ raise click.ClickException(
+ f"Persistent deployment '{manifest.profile}' on port {port} is not healthy."
+ )
if _check_proxy(port):
click.echo(f" Proxy already running on port {port}")
diff --git a/headroom/install/paths.py b/headroom/install/paths.py
index 7102c0d4f..500ce5e33 100644
--- a/headroom/install/paths.py
+++ b/headroom/install/paths.py
@@ -2,9 +2,22 @@
from __future__ import annotations
+import re
import sys
from pathlib import Path
+import click
+
+_PROFILE_RE = re.compile(r"^[A-Za-z0-9._-]+$")
+
+
+def validate_profile_name(profile: str) -> str:
+ """Validate and normalize a deployment profile name."""
+
+ if profile in {".", ".."} or not _PROFILE_RE.fullmatch(profile):
+ raise click.ClickException(f"Invalid profile name '{profile}'")
+ return profile
+
def deploy_root() -> Path:
"""Return the root directory for deployment state."""
@@ -15,7 +28,7 @@ def deploy_root() -> Path:
def profile_root(profile: str) -> Path:
"""Return the directory for a named deployment profile."""
- return deploy_root() / profile
+ return deploy_root() / validate_profile_name(profile)
def manifest_path(profile: str) -> Path:
diff --git a/headroom/install/planner.py b/headroom/install/planner.py
index bc8a6edbe..0d50c1c48 100644
--- a/headroom/install/planner.py
+++ b/headroom/install/planner.py
@@ -1,201 +1,228 @@
-"""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,
- )
+"""Planner for persistent deployment manifests."""
+
+from __future__ import annotations
+
+import shutil
+from collections.abc import Iterable
+from pathlib import Path
+
+import click
+
+from .models import (
+ ConfigScope,
+ DeploymentManifest,
+ InstallPreset,
+ ProviderSelectionMode,
+ SupervisorKind,
+ ToolTarget,
+)
+from .paths import validate_profile_name
+
+SUPPORTED_TARGETS = [
+ ToolTarget.CLAUDE,
+ ToolTarget.COPILOT,
+ ToolTarget.CODEX,
+ ToolTarget.AIDER,
+ ToolTarget.CURSOR,
+ ToolTarget.OPENCLAW,
+]
+PROVIDER_SCOPE_TARGETS = [
+ ToolTarget.CLAUDE,
+ ToolTarget.CODEX,
+ 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], *, scope: str = ConfigScope.USER.value
+) -> list[str]:
+ """Resolve target selection according to the requested provider mode."""
+
+ valid_targets = SUPPORTED_TARGETS
+ if scope == ConfigScope.PROVIDER.value:
+ valid_targets = PROVIDER_SCOPE_TARGETS
+
+ valid = {target.value for target in valid_targets}
+ requested = [target.strip().lower() for target in requested_targets]
+
+ if scope == ConfigScope.PROVIDER.value:
+ unsupported = [target for target in requested if target and target not in valid]
+ if unsupported:
+ unsupported_list = ", ".join(sorted(set(unsupported)))
+ raise click.ClickException(
+ "Provider scope supports only claude, codex, and openclaw; "
+ f"unsupported targets: {unsupported_list}"
+ )
+
+ if provider_mode == ProviderSelectionMode.ALL.value:
+ return [target.value for target in valid_targets]
+
+ if provider_mode == ProviderSelectionMode.AUTO.value:
+ detected = [target for target in detect_targets() if target in valid]
+ return detected or [
+ ToolTarget.CLAUDE.value,
+ ToolTarget.CODEX.value,
+ *([] if scope == ConfigScope.PROVIDER.value else [ToolTarget.COPILOT.value]),
+ ]
+
+ normalized = []
+ seen: set[str] = set()
+ for value in requested:
+ 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."""
+
+ normalized_profile = validate_profile_name(profile)
+
+ 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, scope=scope)
+ 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-{normalized_profile}"
+ return DeploymentManifest(
+ profile=normalized_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-{normalized_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.py
index 142535d99..7dffae4a0 100644
--- a/headroom/install/providers.py
+++ b/headroom/install/providers.py
@@ -1,277 +1,302 @@
-"""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()
+"""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 _powershell_literal(value: str) -> str:
+ return "'" + value.replace("'", "''") + "'"
+
+
+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():
+ previous = subprocess.run(
+ [
+ "powershell",
+ "-NoProfile",
+ "-Command",
+ f"$value = [Environment]::GetEnvironmentVariable({_powershell_literal(name)},{_powershell_literal(scope_name)}); "
+ "if ($null -eq $value) { '__HEADROOM_UNSET__' } else { $value }",
+ ],
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout.strip()
+ command = [
+ "powershell",
+ "-NoProfile",
+ "-Command",
+ f"[Environment]::SetEnvironmentVariable({_powershell_literal(name)},{_powershell_literal(value)},{_powershell_literal(scope_name)})",
+ ]
+ subprocess.run(command, check=True)
+ mutations.append(
+ ManagedMutation(
+ target="env",
+ kind="windows-env",
+ data={
+ "name": name,
+ "scope": scope_name,
+ "previous": None if previous == "__HEADROOM_UNSET__" else previous,
+ },
+ )
+ )
+ 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")
+ if not isinstance(name, str):
+ raise ValueError("Windows environment mutation is missing a variable name")
+ scope_name = mutation.data.get("scope", "User")
+ if not isinstance(scope_name, str):
+ raise ValueError("Windows environment mutation is missing a valid scope")
+ previous = mutation.data.get("previous")
+ if previous is None:
+ value_literal = "$null"
+ else:
+ value_literal = _powershell_literal(previous)
+ command = [
+ "powershell",
+ "-NoProfile",
+ "-Command",
+ f"[Environment]::SetEnvironmentVariable({_powershell_literal(name)},{value_literal},{_powershell_literal(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:
+ mutations.append(_apply_openclaw_provider_scope(manifest))
+ 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:
+ mutations.append(_apply_openclaw_provider_scope(manifest))
+ 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.py
index 841d3490a..40a7bc497 100644
--- a/headroom/install/runtime.py
+++ b/headroom/install/runtime.py
@@ -1,233 +1,270 @@
-"""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"
+"""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
+
+PASSTHROUGH_ENV_PREFIXES = (
+ "HEADROOM_",
+ "ANTHROPIC_",
+ "OPENAI_",
+ "GEMINI_",
+ "AWS_",
+ "AZURE_",
+ "VERTEX_",
+ "GOOGLE_",
+ "GOOGLE_CLOUD_",
+ "MISTRAL_",
+ "GROQ_",
+ "OPENROUTER_",
+ "XAI_",
+ "TOGETHER_",
+ "COHERE_",
+ "OLLAMA_",
+ "LITELLM_",
+ "OTEL_",
+ "SUPABASE_",
+ "QDRANT_",
+ "NEO4J_",
+ "LANGSMITH_",
+)
+
+
+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 _ensure_host_dirs() -> None:
+ for subdir in (".headroom", ".claude", ".codex", ".gemini"):
+ (Path.home() / subdir).mkdir(parents=True, exist_ok=True)
+
+
+def _mount_source(home: str, subdir: str) -> str:
+ if os.name == "nt":
+ return f"{home}\\{subdir}"
+ return f"{home}/{subdir}"
+
+
+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]
+
+ _ensure_host_dirs()
+ 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"{_mount_source(home, '.headroom')}:{container_home}/.headroom",
+ "--volume",
+ f"{_mount_source(home, '.claude')}:{container_home}/.claude",
+ "--volume",
+ f"{_mount_source(home, '.codex')}:{container_home}/.codex",
+ "--volume",
+ f"{_mount_source(home, '.gemini')}:{container_home}/.gemini",
+ ]
+ if os.name != "nt":
+ getuid = getattr(os, "getuid", None)
+ getgid = getattr(os, "getgid", None)
+ if callable(getuid) and callable(getgid):
+ command.extend(["--user", f"{getuid()}:{getgid()}"])
+ runtime_env = {**manifest.base_env, **_deployment_env(manifest)}
+ for name, value in runtime_env.items():
+ command.extend(["--env", f"{name}={value}"])
+ for name in sorted(os.environ):
+ if name.startswith(PASSTHROUGH_ENV_PREFIXES):
+ command.extend(["--env", name])
+ 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.py
index 6b3151ebc..e3882e288 100644
--- a/headroom/install/state.py
+++ b/headroom/install/state.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import shutil
from dataclasses import asdict
from .models import ArtifactRecord, DeploymentManifest, ManagedMutation, iso_utc_now
@@ -53,8 +54,8 @@ def list_manifests() -> list[DeploymentManifest]:
def delete_manifest(profile: str = "default") -> None:
- """Delete the deployment manifest if present."""
+ """Delete the full deployment profile state if present."""
- path = manifest_path(profile)
- if path.exists():
- path.unlink()
+ root = profile_root(profile)
+ if root.exists():
+ shutil.rmtree(root, ignore_errors=True)
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 8db3498ee..424491c2e 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -66,11 +66,12 @@ function Write-Wrapper {
$wrapperPath = Join-Path $TargetDir 'headroom.ps1'
$cmdPath = Join-Path $TargetDir 'headroom.cmd'
+ $resolvedInstallImage = $InstallImage.Replace("'", "''")
$wrapper = @'
$ErrorActionPreference = 'Stop'
-$HeadroomImage = if ($env:HEADROOM_DOCKER_IMAGE) { $env:HEADROOM_DOCKER_IMAGE } else { 'ghcr.io/chopratejas/headroom:latest' }
+$HeadroomImage = if ($env:HEADROOM_DOCKER_IMAGE) { $env:HEADROOM_DOCKER_IMAGE } else { '__HEADROOM_INSTALL_IMAGE__' }
$ContainerHome = if ($env:HEADROOM_CONTAINER_HOME) { $env:HEADROOM_CONTAINER_HOME } else { '/tmp/headroom-home' }
$HostHome = $HOME
@@ -306,6 +307,15 @@ function Require-OptionValue {
}
}
+function Write-Utf8NoBomFile {
+ param(
+ [string]$Path,
+ [string]$Content
+ )
+
+ [System.IO.File]::WriteAllText($Path, $Content, [System.Text.UTF8Encoding]::new($false))
+}
+
function Get-PersistentDockerArgs {
Ensure-HostDirs
$args = New-Object System.Collections.Generic.List[string]
@@ -388,7 +398,7 @@ function Write-PersistentState {
container_name = Get-PersistentContainerName -Profile $Profile
health_url = "http://127.0.0.1:$Port/readyz"
}
- $state | ConvertTo-Json -Depth 4 | Set-Content -Path (Get-PersistentStatePath -Profile $Profile) -Encoding utf8
+ Write-Utf8NoBomFile -Path (Get-PersistentStatePath -Profile $Profile) -Content ($state | ConvertTo-Json -Depth 4)
}
function Write-PersistentManifest {
@@ -443,7 +453,7 @@ function Write-PersistentManifest {
artifacts = @()
}
- $manifest | ConvertTo-Json -Depth 8 | Set-Content -Path (Get-PersistentManifestPath -Profile $Profile) -Encoding utf8
+ Write-Utf8NoBomFile -Path (Get-PersistentManifestPath -Profile $Profile) -Content ($manifest | ConvertTo-Json -Depth 8)
}
function Read-PersistentState {
@@ -479,6 +489,13 @@ function Start-PersistentDockerInstall {
$dockerArgs = New-Object System.Collections.Generic.List[string]
$dockerArgs.AddRange([string[]]@('run','-d','--restart','unless-stopped','--name',$containerName,'-p',"$Port`:$Port"))
$dockerArgs.AddRange((Get-PersistentDockerArgs))
+ $dockerArgs.AddRange([string[]]@(
+ '--env',"HEADROOM_DEPLOYMENT_PROFILE=$Profile",
+ '--env','HEADROOM_DEPLOYMENT_PRESET=persistent-docker',
+ '--env','HEADROOM_DEPLOYMENT_RUNTIME=docker',
+ '--env','HEADROOM_DEPLOYMENT_SUPERVISOR=none',
+ '--env','HEADROOM_DEPLOYMENT_SCOPE=user'
+ ))
$dockerArgs.Add($Image)
$dockerArgs.Add('--host')
$dockerArgs.Add('0.0.0.0')
@@ -595,6 +612,26 @@ function Show-InstallApplyHelp {
Write-Host ($lines -join [Environment]::NewLine)
}
+function Show-WrapHelp {
+ $lines = @(
+ 'Usage: headroom wrap <COMMAND> [OPTIONS] [-- ARGS...]',
+ '',
+ ' Launch supported host tools through a Docker-native Headroom proxy.',
+ '',
+ 'Supported commands:',
+ ' claude',
+ ' codex',
+ ' aider',
+ ' cursor',
+ ' openclaw',
+ '',
+ 'Notes:',
+ ' - GitHub Copilot CLI wrapping is not supported by the Docker-native wrapper.',
+ ' - Use the Python-native CLI for unsupported wrap targets.'
+ )
+ Write-Host ($lines -join [Environment]::NewLine)
+}
+
function Parse-InstallApplyArgs {
param([string[]]$Arguments)
@@ -723,7 +760,7 @@ function Parse-InstallApplyArgs {
$i += 1
continue
}
- '^(--help|-\\?)$' {
+ '^(--help|-\?)$' {
Show-InstallApplyHelp
exit 0
}
@@ -765,7 +802,7 @@ function Parse-InstallProfileArgs {
$i += 1
continue
}
- '^(--help|-\\?)$' {
+ '^(--help|-\?)$' {
Show-InstallHelp
exit 0
}
@@ -1527,7 +1564,7 @@ switch ($args[0]) {
}
'wrap' {
if ($args.Count -eq 1 -or $args[1] -eq '--help' -or $args[1] -eq '-?') {
- Invoke-HeadroomDocker -Arguments @('wrap','--help')
+ Show-WrapHelp
exit 0
}
@@ -1538,6 +1575,17 @@ switch ($args[0]) {
$tool = $args[1]
$wrapArgs = if ($args.Count -gt 2) { $args[2..($args.Count - 1)] } else { @() }
+ switch ($tool) {
+ 'claude' { }
+ 'codex' { }
+ 'aider' { }
+ 'cursor' { }
+ 'openclaw' { }
+ default {
+ Fail "Docker-native wrapper does not support 'wrap $tool'. Supported targets: claude, codex, aider, cursor, openclaw"
+ }
+ }
+
if ($tool -eq 'openclaw') {
if (Test-HelpFlag -Arguments $wrapArgs) {
$helpArgs = @('wrap','openclaw') + $wrapArgs
@@ -1562,14 +1610,6 @@ switch ($args[0]) {
if ($parsed.Anyllm) { $proxyArgs.AddRange([string[]]@('--anyllm-provider', $parsed.Anyllm)) }
if ($parsed.Region) { $proxyArgs.AddRange([string[]]@('--region', $parsed.Region)) }
- switch ($tool) {
- 'claude' { }
- 'codex' { }
- 'aider' { }
- 'cursor' { }
- default { Fail "Unsupported wrap target: $tool" }
- }
-
$containerName = $null
try {
if (-not $parsed.NoProxy) {
@@ -1672,6 +1712,8 @@ switch ($args[0]) {
}
'@
+ $wrapper = $wrapper.Replace('__HEADROOM_INSTALL_IMAGE__', $resolvedInstallImage)
+
$cmdWrapper = ([string][char]64) + "echo off`r`npowershell -NoLogo -NoProfile -ExecutionPolicy Bypass -File ""%~dp0headroom.ps1"" %*`r`n"
Set-Content -Path $wrapperPath -Value $wrapper -Encoding utf8
diff --git a/scripts/install.sh b/scripts/install.sh
index 24de7170d..4f9c0c9b2 100644
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -55,11 +55,12 @@ write_wrapper() {
{
printf '#!%s\n\n' "${BASH_PATH}"
+ printf 'HEADROOM_IMAGE_DEFAULT=%q\n' "${INSTALL_IMAGE}"
cat <<'WRAPPER'
set -euo pipefail
-HEADROOM_IMAGE="${HEADROOM_DOCKER_IMAGE:-ghcr.io/chopratejas/headroom:latest}"
+HEADROOM_IMAGE="${HEADROOM_DOCKER_IMAGE:-${HEADROOM_IMAGE_DEFAULT}}"
HEADROOM_CONTAINER_HOME="${HEADROOM_CONTAINER_HOME:-/tmp/headroom-home}"
HEADROOM_HOST_HOME="${HOME:?}"
@@ -487,6 +488,13 @@ start_persistent_docker_install() {
args=(docker run -d --restart unless-stopped --name "${container_name}" -p "${port}:${port}")
append_persistent_container_args args
+ args+=(
+ --env "HEADROOM_DEPLOYMENT_PROFILE=${profile}"
+ --env "HEADROOM_DEPLOYMENT_PRESET=persistent-docker"
+ --env "HEADROOM_DEPLOYMENT_RUNTIME=docker"
+ --env "HEADROOM_DEPLOYMENT_SUPERVISOR=none"
+ --env "HEADROOM_DEPLOYMENT_SCOPE=user"
+ )
args+=("${image}" --host 0.0.0.0 "${proxy_args[@]:2}")
"${args[@]}" >/dev/null
@@ -592,6 +600,25 @@ Options:
EOF
}
+print_wrap_help() {
+ cat <<'EOF'
+Usage: headroom wrap <COMMAND> [OPTIONS] [-- ARGS...]
+
+ Launch supported host tools through a Docker-native Headroom proxy.
+
+Supported commands:
+ claude
+ codex
+ aider
+ cursor
+ openclaw
+
+Notes:
+ - GitHub Copilot CLI wrapping is not supported by the Docker-native wrapper.
+ - Use the Python-native CLI for unsupported wrap targets.
+EOF
+}
+
parse_install_apply_args() {
local -n out_profile=$1
local -n out_port=$2
@@ -1406,7 +1433,7 @@ main() {
;;
wrap)
if (($# == 1)) || [[ "$2" == "--help" || "$2" == "-?" ]]; then
- run_headroom wrap --help
+ print_wrap_help
return
fi
@@ -1414,6 +1441,14 @@ main() {
local tool="$2"
shift 2
+ case "${tool}" in
+ claude|codex|aider|cursor|openclaw)
+ ;;
+ *)
+ die "Docker-native wrapper does not support 'wrap ${tool}'. Supported targets: claude, codex, aider, cursor, openclaw"
+ ;;
+ esac
+
if [[ "${tool}" == "openclaw" ]]; then
if contains_help_flag "$@"; then
run_headroom wrap openclaw "$@"
@@ -1445,14 +1480,6 @@ main() {
proxy_args+=(--region "${region}")
fi
- case "${tool}" in
- claude|codex|aider|cursor)
- ;;
- *)
- die "Unsupported wrap target: ${tool}"
- ;;
- esac
-
local container_name=""
if [[ "${no_proxy}" -eq 0 ]]; then
container_name="$(start_proxy_container "${port}" "${proxy_args[@]}")"
diff --git a/tests/test_cli/test_install_cli.py b/tests/test_cli/test_install_cli.py
index 6c0d749f9..b5df92c3c 100644
--- a/tests/test_cli/test_install_cli.py
+++ b/tests/test_cli/test_install_cli.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import click
from click.testing import CliRunner
from headroom.cli.main import main
@@ -111,3 +112,130 @@ def test_install_restart_uses_internal_helpers(monkeypatch) -> None:
assert result.exit_code == 0, result.output
assert "Restarted deployment 'default'." in result.output
assert calls == ["stop_supervisor", "stop_runtime", "start_supervisor"]
+
+
+def test_install_apply_rejects_invalid_profile() -> None:
+ runner = CliRunner()
+
+ result = runner.invoke(main, ["install", "apply", "--profile", "../bad"])
+
+ assert result.exit_code != 0
+ assert "Invalid profile name '../bad'" in result.output
+
+
+def test_install_apply_rejects_provider_scope_targets_without_support() -> None:
+ runner = CliRunner()
+
+ result = runner.invoke(
+ main,
+ ["install", "apply", "--scope", "provider", "--providers", "manual", "--target", "copilot"],
+ )
+
+ assert result.exit_code != 0
+ assert "Provider scope supports only claude, codex, and openclaw" in result.output
+
+
+def test_install_apply_restores_previous_deployment_after_failed_update(monkeypatch) -> None:
+ runner = CliRunner()
+ calls: list[str] = []
+
+ class Manifest:
+ def __init__(self, profile: str, targets: list[str]) -> None:
+ self.profile = profile
+ self.preset = "persistent-service"
+ self.runtime_kind = "python"
+ self.supervisor_kind = "service"
+ self.scope = "user"
+ self.health_url = "http://127.0.0.1:8787/readyz"
+ self.targets = targets
+ self.mutations = []
+ self.artifacts = []
+
+ new_manifest = Manifest("default", ["claude"])
+ existing_manifest = Manifest("default", ["codex"])
+
+ monkeypatch.setattr("headroom.cli.install.build_manifest", lambda **_: new_manifest)
+ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: existing_manifest)
+ monkeypatch.setattr(
+ "headroom.cli.install.apply_mutations",
+ lambda deployment: calls.append(f"apply:{','.join(deployment.targets)}") or [],
+ )
+ monkeypatch.setattr(
+ "headroom.cli.install.install_supervisor",
+ lambda deployment: calls.append(f"supervisor:{','.join(deployment.targets)}") or [],
+ )
+ monkeypatch.setattr(
+ "headroom.cli.install.save_manifest",
+ lambda deployment: calls.append(f"save:{','.join(deployment.targets)}"),
+ )
+ monkeypatch.setattr(
+ "headroom.cli.install.stop_supervisor",
+ lambda deployment: calls.append(f"stop-supervisor:{','.join(deployment.targets)}"),
+ )
+ monkeypatch.setattr(
+ "headroom.cli.install.stop_runtime",
+ lambda deployment: calls.append(f"stop-runtime:{','.join(deployment.targets)}"),
+ )
+ monkeypatch.setattr(
+ "headroom.cli.install.remove_supervisor",
+ lambda deployment: calls.append(f"remove-supervisor:{','.join(deployment.targets)}"),
+ )
+ monkeypatch.setattr(
+ "headroom.cli.install.revert_mutations",
+ lambda deployment: calls.append(f"revert:{','.join(deployment.targets)}"),
+ )
+ monkeypatch.setattr(
+ "headroom.cli.install.delete_manifest",
+ lambda profile: calls.append(f"delete:{profile}"),
+ )
+
+ def _start(deployment) -> None:
+ calls.append(f"start:{','.join(deployment.targets)}")
+ if deployment is new_manifest:
+ raise click.ClickException("boom")
+
+ monkeypatch.setattr("headroom.cli.install._start_deployment", _start)
+
+ result = runner.invoke(main, ["install", "apply"])
+
+ assert result.exit_code != 0
+ assert "Restoring previous deployment 'default'" in result.output
+ assert calls == [
+ "stop-supervisor:codex",
+ "stop-runtime:codex",
+ "remove-supervisor:codex",
+ "revert:codex",
+ "delete:default",
+ "apply:claude",
+ "supervisor:claude",
+ "save:claude",
+ "start:claude",
+ "stop-supervisor:claude",
+ "stop-runtime:claude",
+ "remove-supervisor:claude",
+ "revert:claude",
+ "delete:default",
+ "apply:codex",
+ "supervisor:codex",
+ "save:codex",
+ "start:codex",
+ ]
+
+
+def test_install_start_rejects_task_lifecycle(monkeypatch) -> None:
+ runner = CliRunner()
+
+ class Manifest:
+ profile = "default"
+ preset = "persistent-task"
+ runtime_kind = "python"
+ supervisor_kind = "task"
+ scope = "user"
+ health_url = "http://127.0.0.1:8787/readyz"
+
+ monkeypatch.setattr("headroom.cli.install.load_manifest", lambda profile: Manifest())
+
+ result = runner.invoke(main, ["install", "start"])
+
+ assert result.exit_code != 0
+ assert "headroom install start" in result.output
diff --git a/tests/test_cli/test_wrap_persistent.py b/tests/test_cli/test_wrap_persistent.py
index cf087d7ac..61143a353 100644
--- a/tests/test_cli/test_wrap_persistent.py
+++ b/tests/test_cli/test_wrap_persistent.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import click
+
from headroom.cli.wrap import _ensure_proxy
@@ -54,3 +56,17 @@ def test_ensure_proxy_recovers_persistent_deployment_when_socket_is_bound(monkey
assert result is None
assert calls == ["start:default"]
+
+
+def test_ensure_proxy_rejects_unhealthy_persistent_deployment(monkeypatch) -> None:
+ 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.cli.wrap._recover_persistent_proxy", lambda port: False)
+
+ try:
+ _ensure_proxy(8787, False)
+ except click.ClickException as exc:
+ assert "is not healthy" in str(exc)
+ else:
+ raise AssertionError("expected unhealthy persistent deployment to raise")
diff --git a/tests/test_install/test_native_installers.py b/tests/test_install/test_native_installers.py
index 8545fa8b4..b83265580 100644
--- a/tests/test_install/test_native_installers.py
+++ b/tests/test_install/test_native_installers.py
@@ -250,16 +250,28 @@ def test_bash_native_installer_supports_persistent_docker_lifecycle(tmp_path: Pa
home = tmp_path / "home"
(home / ".local").mkdir(parents=True)
env = _build_env(home, tmp_path)
+ env["HEADROOM_DOCKER_IMAGE"] = "headroom:test-image"
try:
_run(["bash", str(REPO_ROOT / "scripts" / "install.sh")], env=env, cwd=REPO_ROOT)
wrapper = home / ".local" / "bin" / "headroom"
assert wrapper.exists()
+ assert "HEADROOM_IMAGE_DEFAULT=headroom:test-image" in wrapper.read_text(encoding="utf-8")
help_result = _run([str(wrapper), "install", "-?"], env=env)
assert "persistent-docker preset only" in help_result.stdout
_run([str(wrapper), "--help"], env=env)
+ wrap_help = _run([str(wrapper), "wrap", "--help"], env=env)
+ assert "Supported commands:" in wrap_help.stdout
+ assert "copilot" not in wrap_help.stdout
+ unsupported_wrap = _run(
+ [str(wrapper), "wrap", "copilot", "--help"],
+ env=env,
+ check=False,
+ )
+ assert unsupported_wrap.returncode != 0
+ assert "does not support 'wrap copilot'" in unsupported_wrap.stderr
invalid_profile = _run(
[str(wrapper), "install", "status", "--profile", ".."],
@@ -418,6 +430,7 @@ def test_powershell_native_installer_supports_persistent_docker_lifecycle(tmp_pa
home = tmp_path / "home"
(home / ".local").mkdir(parents=True)
env = _build_env(home, tmp_path)
+ env["HEADROOM_DOCKER_IMAGE"] = "headroom:test-image"
try:
_run(
@@ -435,6 +448,8 @@ def test_powershell_native_installer_supports_persistent_docker_lifecycle(tmp_pa
wrapper = home / ".local" / "bin" / "headroom.ps1"
assert wrapper.exists()
+ assert "__HEADROOM_INSTALL_IMAGE__" not in wrapper.read_text(encoding="utf-8")
+ assert "headroom:test-image" in wrapper.read_text(encoding="utf-8")
cmd_wrapper = home / ".local" / "bin" / "headroom.cmd"
assert cmd_wrapper.exists()
@@ -482,6 +497,19 @@ def test_powershell_native_installer_supports_persistent_docker_lifecycle(tmp_pa
],
env=env,
)
+ wrap_help = _run(
+ ["cmd.exe", "/c", str(cmd_wrapper), "wrap", "--help"],
+ env=env,
+ )
+ assert "Supported commands:" in wrap_help.stdout
+ assert "copilot" not in wrap_help.stdout
+ unsupported_wrap = _run(
+ ["cmd.exe", "/c", str(cmd_wrapper), "wrap", "copilot", "--help"],
+ env=env,
+ check=False,
+ )
+ assert unsupported_wrap.returncode != 0
+ assert "does not support 'wrap copilot'" in unsupported_wrap.stderr
invalid_profile = _run(
["cmd.exe", "/c", str(cmd_wrapper), "install", "status", "--profile", ".."],
env=env,
@@ -569,8 +597,12 @@ def test_powershell_native_installer_supports_persistent_docker_lifecycle(tmp_pa
manifest_path = home / ".headroom" / "deploy" / "smoke" / "manifest.json"
state_path = home / ".headroom" / "deploy" / "smoke" / "docker-native.json"
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
- state = json.loads(state_path.read_text(encoding="utf-8"))
+ manifest_bytes = manifest_path.read_bytes()
+ state_bytes = state_path.read_bytes()
+ assert not manifest_bytes.startswith(b"\xef\xbb\xbf")
+ assert not state_bytes.startswith(b"\xef\xbb\xbf")
+ manifest = json.loads(manifest_bytes.decode("utf-8"))
+ state = json.loads(state_bytes.decode("utf-8"))
assert manifest["preset"] == "persistent-docker"
assert manifest["port"] == port
assert manifest["memory_enabled"] is True
diff --git a/tests/test_install/test_providers.py b/tests/test_install/test_providers.py
index 135f5e5be..d22971b93 100644
--- a/tests/test_install/test_providers.py
+++ b/tests/test_install/test_providers.py
@@ -7,6 +7,8 @@ from headroom.install.models import DeploymentManifest
from headroom.install.providers import (
_apply_claude_provider_scope,
_apply_codex_provider_scope,
+ _apply_windows_env_scope,
+ _remove_windows_env_scope,
_revert_claude_provider_scope,
_revert_codex_provider_scope,
)
@@ -91,3 +93,48 @@ def test_apply_openclaw_provider_scope_uses_manifest_port(monkeypatch, tmp_path:
_apply_openclaw_provider_scope(manifest)
assert recorded == [["headroom", "wrap", "openclaw", "--no-auto-start", "--proxy-port", "9999"]]
+
+
+def test_windows_env_scope_restores_previous_values(monkeypatch, tmp_path: Path) -> None:
+ manifest = _manifest(tmp_path)
+ manifest.scope = "user"
+ manifest.targets = ["claude"]
+ manifest.base_env = {"HEADROOM_PORT": "8787"}
+ manifest.tool_envs = {"claude": {"ANTHROPIC_BASE_URL": "http://127.0.0.1:8787"}}
+
+ calls: list[list[str]] = []
+ previous_values = {
+ "HEADROOM_PORT": "7777",
+ "ANTHROPIC_BASE_URL": "https://old",
+ }
+
+ class Result:
+ def __init__(self, stdout: str = "") -> None:
+ self.stdout = stdout
+
+ def fake_run(command: list[str], **kwargs):
+ calls.append(command)
+ script = command[-1]
+ if "GetEnvironmentVariable" in script:
+ name = script.split("GetEnvironmentVariable('", 1)[1].split("'", 1)[0]
+ value = previous_values.get(name, "__HEADROOM_UNSET__")
+ return Result(stdout=value)
+ return Result()
+
+ monkeypatch.setattr("headroom.install.providers.subprocess.run", fake_run)
+
+ mutations = _apply_windows_env_scope(manifest)
+ _remove_windows_env_scope(mutations)
+
+ previous_by_name = {mutation.data["name"]: mutation.data["previous"] for mutation in mutations}
+ assert previous_by_name["HEADROOM_PORT"] == "7777"
+ assert previous_by_name["ANTHROPIC_BASE_URL"] == "https://old"
+ assert any(
+ "[Environment]::SetEnvironmentVariable('HEADROOM_PORT','7777','User')" in command[-1]
+ for command in calls
+ )
+ assert any(
+ "[Environment]::SetEnvironmentVariable('ANTHROPIC_BASE_URL','https://old','User')"
+ in command[-1]
+ for command in calls
+ )
diff --git a/tests/test_install/test_runtime.py b/tests/test_install/test_runtime.py
index bf0d86267..e555f5c81 100644
--- a/tests/test_install/test_runtime.py
+++ b/tests/test_install/test_runtime.py
@@ -34,3 +34,37 @@ def test_build_runtime_command_for_docker_includes_deployment_env(
assert "HEADROOM_DEPLOYMENT_PRESET=persistent-docker" in joined
assert "127.0.0.1:8787:8787" in joined
assert "ghcr.io/chopratejas/headroom:latest" in command
+
+
+def test_build_runtime_command_for_docker_matches_wrapper_parity(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ monkeypatch.setenv("OPENAI_API_KEY", "test-openai")
+ 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)
+
+ assert (tmp_path / ".headroom").is_dir()
+ assert (tmp_path / ".claude").is_dir()
+ assert (tmp_path / ".codex").is_dir()
+ assert (tmp_path / ".gemini").is_dir()
+ assert "--env" in command
+ joined = " ".join(command)
+ assert "ANTHROPIC_API_KEY" in joined
+ assert "OPENAI_API_KEY" in joined