chopratejas--headroom
0ef5fcb1c5
Security / Dependency audit (pip-audit) (push) Has been cancelled
Security / CodeQL (javascript-typescript) (push) Has been cancelled
Security / CodeQL (python) (push) Has been cancelled
Security / Secret scan (gitleaks) (push) Has been cancelled
rust / test (ubuntu) (push) Has been cancelled
rust / simulator e2e (macos-latest) (push) Has been cancelled
rust / simulator e2e (ubuntu-latest) (push) Has been cancelled
rust / simulator e2e (windows-latest) (push) Has been cancelled
rust / wheels (aarch64-apple-darwin) (push) Has been cancelled
rust / wheels (x86_64-unknown-linux-gnu) (push) Has been cancelled
rust / wheels (x86_64-apple-darwin) (push) Has been cancelled
rust / audit (push) Has been cancelled
rust / parity (nightly, allowed to fail during Phase 0) (push) Has been cancelled
CI / commitlint (push) Has been skipped
Dev Containers / validate (.devcontainer/devcontainer.json, default) (push) Failing after 0s
Dev Containers / validate (.devcontainer/memory-stack/devcontainer.json, memory-stack) (push) Failing after 0s
Dev Containers / validate-worktree (push) Failing after 0s
CI / changes (push) Failing after 4s
Deploy Documentation / validate (push) Has been skipped
Deploy Documentation / deploy (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, claude) (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, codex) (push) Failing after 1s
Install Native E2E / install-native (ubuntu-latest) (push) Failing after 1s
OpenCode Plugin / typecheck + build + test (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, copilot) (push) Failing after 1s
Release Please / release-please (push) Failing after 1s
Wrap E2E / docker-wrap-e2e (push) Failing after 1s
Wrap Native E2E / wrap-native (ubuntu-latest) (push) Failing after 1s
Init E2E / docker-init-e2e (push) Failing after 4s
Merge Conflicts / merge-conflicts (push) Failing after 4s
CI / lint (push) Has been cancelled
CI / build-wheel (push) Has been cancelled
CI / build-wheel-windows (push) Has been cancelled
CI / prefetch-model (push) Has been cancelled
CI / test-dashboard-ui (push) Has been cancelled
CI / test (1) (push) Has been cancelled
CI / test (2) (push) Has been cancelled
CI / test (3) (push) Has been cancelled
CI / test (4) (push) Has been cancelled
CI / test-extras (push) Has been cancelled
CI / test-agno (push) Has been cancelled
CI / build (push) Has been cancelled
CI / workflow-validation (push) Has been cancelled
CI / docker-native-e2e (push) Has been cancelled
CI / windows-native-wrapper (push) Has been cancelled
CI / macos-native-wrapper (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / promote-latest (push) Has been cancelled
Init Native E2E / init-native (macos-latest, claude) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, codex) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, copilot) (push) Has been cancelled
Install Native E2E / install-native (macos-latest) (push) Has been cancelled
Wrap Native E2E / wrap-native (macos-latest) (push) Has been cancelled
226 行
7.7 KiB
Python
226 行
7.7 KiB
Python
"""OpenCode config file helpers for wrap and persistent install."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import click
|
|
|
|
from headroom import fsutil
|
|
from headroom.install.paths import opencode_config_path
|
|
|
|
# Headroom-managed JSON marker comments for idempotent block injection.
|
|
_PROVIDER_MARKER_START = "// --- Headroom proxy provider ---"
|
|
_PROVIDER_MARKER_END = "// --- end Headroom proxy provider ---"
|
|
_MCP_MARKER_START = "// --- Headroom MCP server ---"
|
|
_MCP_MARKER_END = "// --- end Headroom MCP server ---"
|
|
|
|
# Regex to strip headroom blocks (including the marker comments).
|
|
_PROVIDER_BLOCK_RE = re.compile(
|
|
re.escape(_PROVIDER_MARKER_START) + r".*?" + re.escape(_PROVIDER_MARKER_END),
|
|
re.DOTALL,
|
|
)
|
|
_MCP_BLOCK_RE = re.compile(
|
|
re.escape(_MCP_MARKER_START) + r".*?" + re.escape(_MCP_MARKER_END),
|
|
re.DOTALL,
|
|
)
|
|
HEADROOM_OPENCODE_PLUGIN = "headroom-opencode"
|
|
|
|
# Models exposed by the injected `headroom` provider. OpenCode only resolves
|
|
# `headroom/<id>` for ids listed in the provider's `models` map, so an empty
|
|
# map means every documented `headroom/*` model fails with "Model not found".
|
|
# Keep in sync with DEFAULT_MODELS in plugins/opencode/src/provider.ts and the
|
|
# table in plugins/opencode/README.md.
|
|
HEADROOM_OPENCODE_MODELS: dict[str, Any] = {
|
|
"claude-sonnet-4-6": {
|
|
"name": "Claude Sonnet 4.6",
|
|
"limit": {"context": 200000, "output": 16384},
|
|
},
|
|
"claude-opus-4-6": {
|
|
"name": "Claude Opus 4.6",
|
|
"limit": {"context": 200000, "output": 16384},
|
|
},
|
|
"claude-haiku-4-5-20251001": {
|
|
"name": "Claude Haiku 4.5",
|
|
"limit": {"context": 200000, "output": 8192},
|
|
},
|
|
"gpt-4o": {
|
|
"name": "GPT-4o",
|
|
"limit": {"context": 128000, "output": 16384},
|
|
},
|
|
"gpt-4.1": {
|
|
"name": "GPT-4.1",
|
|
"limit": {"context": 1048576, "output": 32768},
|
|
},
|
|
}
|
|
|
|
|
|
def headroom_provider_entry(port: int) -> dict[str, Any]:
|
|
"""Return the `headroom` provider block pointed at the local proxy."""
|
|
return {
|
|
"npm": "@ai-sdk/openai-compatible",
|
|
"name": "Headroom Proxy",
|
|
"options": {"baseURL": f"http://127.0.0.1:{port}/v1"},
|
|
"models": HEADROOM_OPENCODE_MODELS,
|
|
}
|
|
|
|
|
|
def _opencode_home_dir() -> Path:
|
|
"""Return the OpenCode home/config directory."""
|
|
env_path = os.environ.get("OPENCODE_HOME", "").strip()
|
|
if env_path:
|
|
return Path(env_path).expanduser()
|
|
return Path.home() / ".config" / "opencode"
|
|
|
|
|
|
def opencode_config_paths() -> tuple[Path, Path]:
|
|
"""Return ``(config_file, backup_file)`` for OpenCode."""
|
|
config_file = opencode_config_path()
|
|
backup_file = config_file.with_suffix(".json.headroom-backup")
|
|
return config_file, backup_file
|
|
|
|
|
|
def snapshot_opencode_config_if_unwrapped(config_file: Path, backup_file: Path) -> None:
|
|
"""Snapshot ``opencode.json`` to ``backup_file`` before the first injection.
|
|
|
|
Guarantees that ``headroom unwrap opencode`` can restore the user's
|
|
original file byte-for-byte.
|
|
"""
|
|
if backup_file.exists():
|
|
return
|
|
if not config_file.exists():
|
|
return
|
|
try:
|
|
content = fsutil.read_text(config_file)
|
|
except OSError:
|
|
return
|
|
if _PROVIDER_MARKER_START in content or _MCP_MARKER_START in content:
|
|
return
|
|
backup_file.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(config_file, backup_file)
|
|
|
|
|
|
def strip_opencode_headroom_blocks(content: str, *, remove_mcp: bool = True) -> str:
|
|
"""Remove all Headroom-managed blocks from opencode JSON text.
|
|
|
|
Preserves user content. Returns the cleaned string.
|
|
"""
|
|
content = _PROVIDER_BLOCK_RE.sub("", content)
|
|
if remove_mcp:
|
|
content = _MCP_BLOCK_RE.sub("", content)
|
|
# Collapse multiple blank lines left behind by block removal.
|
|
content = re.sub(r"\n{3,}", "\n\n", content)
|
|
return content.strip()
|
|
|
|
|
|
def _render_provider_block(port: int) -> str:
|
|
"""Render a Headroom provider block as a JSON comment-wrapped snippet."""
|
|
provider = {"headroom": headroom_provider_entry(port)}
|
|
lines = [
|
|
_PROVIDER_MARKER_START,
|
|
f'"provider": {json.dumps(provider, indent=2)},',
|
|
_PROVIDER_MARKER_END,
|
|
]
|
|
return "\n".join(lines)
|
|
|
|
|
|
def _parse_json_loose(text: str) -> dict[str, Any]:
|
|
"""Parse JSON text, stripping line comments (// ...) when needed.
|
|
|
|
Tries standard JSON first to avoid corrupting URLs that contain ``//``.
|
|
Falls back to stripping ``//`` comments when standard parsing fails.
|
|
Two-pass: (1) remove comment-only lines, (2) strip inline trailing
|
|
comments that follow a comma.
|
|
"""
|
|
try:
|
|
parsed = json.loads(text)
|
|
return parsed if isinstance(parsed, dict) else {}
|
|
except json.JSONDecodeError:
|
|
pass
|
|
# Pass 1: remove lines that are ONLY a comment.
|
|
cleaned = re.sub(r"^\s*//[^\n]*\n", "", text, flags=re.MULTILINE)
|
|
# Pass 2: remove inline trailing comments (", // comment").
|
|
cleaned = re.sub(r",\s*//[^\n]*", ",", cleaned)
|
|
try:
|
|
parsed = json.loads(cleaned)
|
|
return parsed if isinstance(parsed, dict) else {}
|
|
except json.JSONDecodeError:
|
|
return {}
|
|
|
|
|
|
def _inject_key_into_json(data: dict[str, Any], key: str, value: Any) -> dict[str, Any]:
|
|
"""Merge ``value`` into ``data[key]`` idempotently."""
|
|
existing = data.get(key)
|
|
if isinstance(existing, dict) and isinstance(value, dict):
|
|
merged = {**existing, **value}
|
|
data[key] = merged
|
|
else:
|
|
data[key] = value
|
|
return data
|
|
|
|
|
|
def append_headroom_plugin(config: dict[str, object]) -> bool:
|
|
"""Append the optional OpenCode plugin entry if it is not already present."""
|
|
plugin = config.get("plugin")
|
|
if plugin is None:
|
|
config["plugin"] = [HEADROOM_OPENCODE_PLUGIN]
|
|
return True
|
|
|
|
if not isinstance(plugin, list):
|
|
return False
|
|
|
|
for entry in plugin:
|
|
if entry == HEADROOM_OPENCODE_PLUGIN:
|
|
return False
|
|
if isinstance(entry, list) and entry and entry[0] == HEADROOM_OPENCODE_PLUGIN:
|
|
return False
|
|
|
|
plugin.append(HEADROOM_OPENCODE_PLUGIN)
|
|
return True
|
|
|
|
|
|
def inject_opencode_provider_config(port: int) -> None:
|
|
"""Inject a Headroom model provider into OpenCode's config file.
|
|
|
|
Safe to call multiple times — the injected block is fully replaced on
|
|
each call, so re-running with a different ``port`` updates the config.
|
|
Before the first injection, the pre-wrap file is snapshotted to
|
|
``opencode.json.headroom-backup`` so ``headroom unwrap opencode``
|
|
can restore it byte-for-byte.
|
|
"""
|
|
config_file, backup_file = opencode_config_paths()
|
|
config_dir = config_file.parent
|
|
|
|
try:
|
|
config_dir.mkdir(parents=True, exist_ok=True)
|
|
snapshot_opencode_config_if_unwrapped(config_file, backup_file)
|
|
|
|
if config_file.exists():
|
|
content = fsutil.read_text(config_file)
|
|
data = _parse_json_loose(content)
|
|
else:
|
|
content = ""
|
|
data = {}
|
|
|
|
# Strip any prior Headroom-managed blocks before re-injecting.
|
|
if _PROVIDER_MARKER_START in content or _MCP_MARKER_START in content:
|
|
content = strip_opencode_headroom_blocks(content)
|
|
data = _parse_json_loose(content)
|
|
|
|
# Merge provider into the JSON data structure.
|
|
provider = {"headroom": headroom_provider_entry(port)}
|
|
data = _inject_key_into_json(data, "provider", provider)
|
|
|
|
# Write back as formatted JSON (opencode uses standard JSON with comments).
|
|
output = json.dumps(data, indent=2) + "\n"
|
|
config_file.write_text(output, encoding="utf-8")
|
|
except OSError as exc:
|
|
raise click.ClickException(
|
|
f"could not write OpenCode config at {config_file}: {exc}"
|
|
) from exc
|