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.

feat(wrap): add ZCode desktop app support (#1845)

David Wells2a954b69b435
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5e678940f..ccae2e360 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -706,6 +706,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+* **wrap:** add `headroom wrap zcode` / `headroom unwrap zcode` for the ZCode
+ desktop app (zcode.z.ai). Follows the Pattern-B (proxy-only watcher)
+ approach: starts the proxy, injects RTK guidance into `AGENTS.md` at the
+ project root, and prints the ZCode settings the user should configure
+ (OpenAI and Anthropic base URLs). Auto-detects the enabled provider from
+ `~/.zcode/v2/config.json` and configures the proxy upstream accordingly.
+ Unwrap removes the injected RTK instructions and stops the proxy.
* **kompress:** warn when `HEADROOM_KOMPRESS_BACKEND` is set to an unrecognized
value instead of silently falling back to `auto`, and document the backend
selection env var (`auto` / `onnx` / `onnx_cpu` / `onnx_coreml` / `pytorch` /
diff --git a/README.md b/README.md
index 14450d96d..933690958 100644
--- a/README.md
+++ b/README.md
@@ -49,7 +49,7 @@ Headroom compresses everything your AI agent reads — tool outputs, logs, RAG c
- **Library** — `compress(messages)` in Python or TypeScript, inline in any app
- **Proxy** — `headroom proxy --port 8787`, zero code changes, any language
-- **Agent wrap** — `headroom wrap claude|codex|copilot|cursor|aider|opencode|cline|continue|goose|openhands|openclaw|vibe` in one command; undo with `headroom unwrap <tool>`
+- **Agent wrap** — `headroom wrap claude|codex|copilot|cursor|aider|opencode|cline|continue|goose|openhands|openclaw|vibe|zcode` in one command; undo with `headroom unwrap <tool>`
- **MCP server** — `headroom_compress`, `headroom_retrieve`, `headroom_stats` for any MCP client
- **Cross-agent memory** — shared store across Claude, Codex, Gemini, auto-dedup
- **`headroom learn`** — mines failed sessions, writes corrections to `CLAUDE.local.md` (default, gitignored) or `CLAUDE.md` / `AGENTS.md` / `GEMINI.md`
@@ -237,9 +237,10 @@ shows an **Output Tokens Saved** card next to input compression, labelled
| OpenHands | ✅ | starts proxy + launches |
| Mistral Vibe | ✅ | starts proxy + launches |
| Cortex Code | Library only | 60–65% savings (library mode; no `wrap`) |
+| ZCode | ✅ | starts proxy and prints base URLs for ZCode settings |
Any OpenAI-compatible client works via `headroom proxy`. MCP-native: `headroom mcp install`.
-Undo durable wrapping with `headroom unwrap <tool>` (supports: `claude`, `copilot`, `codex`, `opencode`, `openclaw`).
+Undo durable wrapping with `headroom unwrap <tool>` (supports: `claude`, `copilot`, `codex`, `opencode`, `openclaw`, `zcode`).
Registry authors can use the canonical [`server.json`](server.json) in the repo root instead of reconstructing the `headroom mcp serve` contract from prose.
### GitHub Copilot CLI subscription mode
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index 614b32737..b4079ad8a 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -135,6 +135,15 @@ from headroom.providers.opencode.config import (
snapshot_opencode_config_if_unwrapped,
strip_opencode_headroom_blocks,
)
+from headroom.providers.zcode import (
+ detect_upstream as _detect_zcode_upstream,
+)
+from headroom.providers.zcode import (
+ render_setup_lines as _render_zcode_setup_lines,
+)
+from headroom.providers.zcode import (
+ upstream_to_proxy_urls as _zcode_upstream_to_urls,
+)
from headroom.proxy.project_context import with_project_prefix as _with_project_prefix
from .main import main
@@ -2270,6 +2279,8 @@ def _run_proxy_only_watcher(
memory: bool,
agent_type: str,
print_setup_lines: Callable[[int], None],
+ anthropic_api_url: str | None = None,
+ openai_api_url: str | None = None,
) -> None:
"""Shared scaffolding for proxy-only wrap subcommands (no child binary launch).
@@ -2292,7 +2303,13 @@ def _run_proxy_only_watcher(
_print_wrap_banner(agent_label)
_register_proxy_client(port)
proxy_holder[0], actual_port = _ensure_proxy(
- port, no_proxy, learn=learn, memory=memory, agent_type=agent_type
+ port,
+ no_proxy,
+ learn=learn,
+ memory=memory,
+ agent_type=agent_type,
+ anthropic_api_url=anthropic_api_url,
+ openai_api_url=openai_api_url,
)
if actual_port != port:
_unregister_proxy_client(port)
@@ -5530,6 +5547,101 @@ def cline(
)
+# =============================================================================
+# ZCode (zcode.z.ai desktop app)
+# =============================================================================
+
+
[email protected](context_settings={"ignore_unknown_options": True})
+ "--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
+)
+ "--no-context-tool",
+ "--no-rtk",
+ "no_rtk",
+ is_flag=True,
+ help="Skip CLI context-tool setup",
+)
[email protected]("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
[email protected]("--learn", is_flag=True, help="Enable live traffic learning")
[email protected]("--memory", is_flag=True, help="Enable persistent cross-session memory")
[email protected]("--verbose", "-v", is_flag=True, help="Verbose output")
[email protected]("--prepare-only", is_flag=True, hidden=True)
+def zcode(
+ port: int,
+ no_rtk: bool,
+ no_proxy: bool,
+ learn: bool,
+ memory: bool,
+ verbose: bool,
+ prepare_only: bool,
+) -> None:
+ """Start Headroom proxy for use with ZCode (zcode.z.ai desktop app).
+
+ \b
+ ZCode is a desktop Electron app that reads its API configuration from
+ the settings UI, not from environment variables. This command starts the
+ proxy, sets up the selected CLI context tool (injecting RTK guidance into
+ AGENTS.md at the project root), and prints the ZCode settings the user
+ should configure.
+
+ \b
+ After running this command, open ZCode and configure:
+ Settings > Model Settings > Add Provider
+ Set OpenAI Base URL and/or Anthropic Base URL to the proxy URLs.
+
+ \b
+ Example:
+ headroom wrap zcode # Start proxy + context-tool instructions
+ headroom wrap zcode --no-context-tool # Proxy only, no CLI context tool
+ headroom wrap zcode --port 9999 # Custom proxy port
+ """
+ agents_md: Path | None = Path.cwd() / "AGENTS.md" if not no_rtk else None
+ if not no_rtk:
+ _setup_context_tool_for_agent(
+ agent="zcode",
+ agent_display="ZCode",
+ marker_path=agents_md,
+ on_rtk_ready=lambda _rtk: _inject_rtk_instructions(
+ cast(Path, agents_md), verbose=verbose
+ ),
+ verbose=verbose,
+ )
+
+ if prepare_only:
+ return
+
+ upstream = _detect_zcode_upstream()
+ anthropic_url, openai_url = _zcode_upstream_to_urls(upstream)
+
+ def _print_zcode_setup(actual_port: int) -> None:
+ click.echo(f" Detected provider: {upstream.provider_name}")
+ click.echo(f" Upstream: {upstream.base_url}")
+ click.echo()
+ for line in _render_zcode_setup_lines(actual_port):
+ click.echo(line)
+ if not no_rtk:
+ click.echo()
+ if _selected_context_tool() == _CONTEXT_TOOL_LEAN_CTX:
+ click.echo(" lean-ctx configured for ZCode")
+ else:
+ click.echo(" rtk instructions injected into AGENTS.md")
+ click.echo(" ZCode will use token-optimized commands automatically.")
+
+ _run_proxy_only_watcher(
+ agent_label="zcode",
+ port=port,
+ no_proxy=no_proxy,
+ learn=learn,
+ memory=memory,
+ agent_type="zcode",
+ print_setup_lines=_print_zcode_setup,
+ anthropic_api_url=anthropic_url,
+ openai_api_url=openai_url,
+ )
+
+
# =============================================================================
# Continue (VS Code / JetBrains extension)
# =============================================================================
@@ -6644,3 +6756,41 @@ def unwrap_codex(port: int, no_stop_proxy: bool) -> None:
if not no_stop_proxy and status != "noop":
_echo_unwrap_proxy_stop_status(_stop_local_proxy_for_unwrap(port), port)
click.echo()
+
+
+# =============================================================================
+# ZCode (unwrap)
+# =============================================================================
+
+
+ "--port", "-p", default=8787, type=click.IntRange(1, 65535), help="Proxy port (default: 8787)"
+)
[email protected]("--no-stop-proxy", is_flag=True, help="Do not stop the local Headroom proxy")
+def unwrap_zcode(port: int, no_stop_proxy: bool) -> None:
+ """Undo ``headroom wrap zcode`` edits to AGENTS.md.
+
+ Removes RTK instructions injected into AGENTS.md at the project root.
+ If the file only contained RTK instructions, it is deleted entirely.
+ """
+ click.echo()
+ click.echo(" ╔═══════════════════════════════════════════════╗")
+ click.echo(" ║ HEADROOM UNWRAP: ZCODE ║")
+ click.echo(" ╚═══════════════════════════════════════════════╝")
+ click.echo()
+
+ agents_md = Path.cwd() / "AGENTS.md"
+ if _remove_rtk_instructions(agents_md):
+ click.echo(f" Removed Headroom rtk instructions from {agents_md}")
+ if agents_md.exists() and not agents_md.read_text().strip():
+ agents_md.unlink()
+ click.echo(f" Removed empty {agents_md}")
+ else:
+ click.echo(f" Nothing to undo: {agents_md} has no Headroom RTK markers.")
+
+ click.echo()
+ click.echo("✓ ZCode is no longer routed through the Headroom proxy.")
+ if not no_stop_proxy:
+ _echo_unwrap_proxy_stop_status(_stop_local_proxy_for_unwrap(port), port)
+ click.echo()
diff --git a/headroom/install/paths.py b/headroom/install/paths.py
index c7a89545b..985f705eb 100644
--- a/headroom/install/paths.py
+++ b/headroom/install/paths.py
@@ -132,3 +132,9 @@ def opencode_config_path() -> Path:
if env_path:
return Path(env_path).expanduser()
return Path.home() / ".config" / "opencode" / "opencode.json"
+
+
+def zcode_config_dir() -> Path:
+ """Return the ZCode user configuration directory."""
+
+ return Path.home() / ".zcode"
diff --git a/headroom/providers/zcode/__init__.py b/headroom/providers/zcode/__init__.py
new file mode 100644
index 000000000..f81a71e88
--- /dev/null
+++ b/headroom/providers/zcode/__init__.py
@@ -0,0 +1,19 @@
+"""ZCode (zcode.z.ai desktop app) provider helpers."""
+
+from .runtime import (
+ ZCodeProxyTargets,
+ ZCodeUpstream,
+ build_proxy_targets,
+ detect_upstream,
+ render_setup_lines,
+ upstream_to_proxy_urls,
+)
+
+__all__ = [
+ "ZCodeProxyTargets",
+ "ZCodeUpstream",
+ "build_proxy_targets",
+ "detect_upstream",
+ "render_setup_lines",
+ "upstream_to_proxy_urls",
+]
diff --git a/headroom/providers/zcode/runtime.py b/headroom/providers/zcode/runtime.py
new file mode 100644
index 000000000..32d921568
--- /dev/null
+++ b/headroom/providers/zcode/runtime.py
@@ -0,0 +1,127 @@
+"""Runtime helpers for ZCode (zcode.z.ai desktop app) integrations."""
+
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import dataclass
+from pathlib import Path
+
+from headroom.install.paths import zcode_config_dir
+from headroom.providers.claude import proxy_base_url as _claude_proxy_base_url
+
+_log = logging.getLogger(__name__)
+
+ZAI_ANTHROPIC_DEFAULT = "https://api.z.ai/api/anthropic"
+
+
+@dataclass(frozen=True)
+class ZCodeProxyTargets:
+ """Resolved local proxy targets shown in ZCode setup instructions."""
+
+ openai_base_url: str
+ anthropic_base_url: str
+
+
+@dataclass(frozen=True)
+class ZCodeUpstream:
+ """Detected upstream provider from ZCode config."""
+
+ provider_name: str
+ base_url: str
+ kind: str # "anthropic" or "openai-compatible"
+
+
+def build_proxy_targets(port: int) -> ZCodeProxyTargets:
+ """Build the local proxy URLs shown to ZCode users."""
+ return ZCodeProxyTargets(
+ openai_base_url=f"http://127.0.0.1:{port}/v1",
+ anthropic_base_url=_claude_proxy_base_url(port),
+ )
+
+
+def detect_upstream(config_path: Path | None = None) -> ZCodeUpstream:
+ """Read ZCode config.json and find the enabled provider's upstream URL.
+
+ Resolution order:
+ 1. First provider with ``enabled=True`` and a non-empty ``baseURL``.
+ 2. Fallback: Z.ai Anthropic endpoint.
+
+ Parameters
+ ----------
+ config_path:
+ Override for the config file path. When *None* the default
+ ``~/.zcode/v2/config.json`` is used.
+ """
+ if config_path is None:
+ config_path = zcode_config_dir() / "v2" / "config.json"
+
+ try:
+ raw = config_path.read_text(encoding="utf-8")
+ cfg = json.loads(raw)
+ except (OSError, json.JSONDecodeError) as exc:
+ _log.debug("Cannot read ZCode config %s: %s", config_path, exc)
+ return ZCodeUpstream(
+ provider_name="Z.ai (default)",
+ base_url=ZAI_ANTHROPIC_DEFAULT,
+ kind="anthropic",
+ )
+
+ providers = cfg.get("provider")
+ if not isinstance(providers, dict):
+ return ZCodeUpstream(
+ provider_name="Z.ai (default)",
+ base_url=ZAI_ANTHROPIC_DEFAULT,
+ kind="anthropic",
+ )
+
+ for _key, provider in providers.items():
+ if not isinstance(provider, dict):
+ continue
+ if not provider.get("enabled"):
+ continue
+ opts = provider.get("options", {})
+ if not isinstance(opts, dict):
+ continue
+ base_url = opts.get("baseURL", "").strip()
+ if not base_url:
+ continue
+ kind = provider.get("kind", "anthropic")
+ name = provider.get("name", "ZCode provider")
+ return ZCodeUpstream(provider_name=name, base_url=base_url, kind=kind)
+
+ return ZCodeUpstream(
+ provider_name="Z.ai (default)",
+ base_url=ZAI_ANTHROPIC_DEFAULT,
+ kind="anthropic",
+ )
+
+
+def upstream_to_proxy_urls(upstream: ZCodeUpstream) -> tuple[str | None, str | None]:
+ """Map :class:`ZCodeUpstream` to headroom proxy URL params.
+
+ Returns ``(anthropic_api_url, openai_api_url)`` — exactly one is set.
+ """
+ if upstream.kind == "anthropic":
+ return upstream.base_url, None
+ return None, upstream.base_url
+
+
+def render_setup_lines(port: int) -> list[str]:
+ """Render the ZCode setup instructions for the local proxy."""
+ targets = build_proxy_targets(port)
+ return [
+ " Headroom proxy is running. Configure ZCode:",
+ "",
+ " Open ZCode > Settings > Model Settings:",
+ "",
+ f" OpenAI Base URL: {targets.openai_base_url}",
+ f" Anthropic Base URL: {targets.anthropic_base_url}",
+ "",
+ " Select a model through the new provider in ZCode's model selector.",
+ "",
+ " To add the Headroom MCP server (optional):",
+ " Settings > MCP Servers > New MCP Server > Full configuration",
+ ' Paste: {"headroom": {"type": "stdio", "command": "headroom",',
+ ' "args": ["mcp", "serve"], "enabled": true}}',
+ ]
diff --git a/tests/test_cli/test_wrap_zcode.py b/tests/test_cli/test_wrap_zcode.py
new file mode 100644
index 000000000..be20cf9f4
--- /dev/null
+++ b/tests/test_cli/test_wrap_zcode.py
@@ -0,0 +1,504 @@
+"""Tests for `headroom wrap zcode` and `headroom unwrap zcode` commands.
+
+ZCode is a desktop Electron app (zcode.z.ai) with no CLI binary. The wrap
+command follows the Pattern-B (proxy-only watcher) approach: it starts the
+proxy, injects RTK guidance into AGENTS.md at the project root, and prints
+the ZCode settings the user should configure in the app's settings UI.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+from click.testing import CliRunner
+
+from headroom.cli import wrap as wrap_mod
+from headroom.cli.main import main
+
+
+def runner() -> CliRunner:
+ return CliRunner()
+
+
+# ---------------------------------------------------------------------------
+# Wrap: --prepare-only RTK injection into AGENTS.md
+# ---------------------------------------------------------------------------
+
+
+def test_prepare_only_injects_rtk_into_agents_md(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``wrap zcode --prepare-only`` writes the RTK block to AGENTS.md at cwd."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
+
+ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):
+ result = runner.invoke(main, ["wrap", "zcode", "--prepare-only"])
+
+ assert result.exit_code == 0, result.output
+ marker = tmp_path / "AGENTS.md"
+ assert marker.exists(), "AGENTS.md should be created"
+ content = marker.read_text(encoding="utf-8")
+ assert wrap_mod._RTK_MARKER in content
+ assert "RTK (Rust Token Killer)" in content
+
+
+def test_prepare_only_idempotent_no_duplicate_block(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Running prepare-only twice must not duplicate the RTK block in AGENTS.md."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
+
+ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):
+ runner.invoke(main, ["wrap", "zcode", "--prepare-only"])
+ runner.invoke(main, ["wrap", "zcode", "--prepare-only"])
+
+ content = (tmp_path / "AGENTS.md").read_text(encoding="utf-8")
+ assert content.count(wrap_mod._RTK_MARKER) == 1
+
+
+def test_no_context_tool_does_not_create_agents_md(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """--no-context-tool must not create AGENTS.md and must not invoke rtk."""
+ monkeypatch.chdir(tmp_path)
+
+ with patch.object(wrap_mod, "_ensure_rtk_binary") as ensure:
+ result = runner.invoke(main, ["wrap", "zcode", "--prepare-only", "--no-context-tool"])
+
+ assert result.exit_code == 0, result.output
+ assert not (tmp_path / "AGENTS.md").exists()
+ ensure.assert_not_called()
+
+
+def test_preserves_existing_agents_md_content(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Pre-existing AGENTS.md content must be preserved when RTK is appended."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
+ agents_md = tmp_path / "AGENTS.md"
+ original = "# Project conventions\n\nAlways use Python 3.12.\n"
+ agents_md.write_text(original, encoding="utf-8")
+
+ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):
+ result = runner.invoke(main, ["wrap", "zcode", "--prepare-only"])
+
+ assert result.exit_code == 0, result.output
+ content = agents_md.read_text(encoding="utf-8")
+ assert "Always use Python 3.12." in content
+ assert wrap_mod._RTK_MARKER in content
+
+
+# ---------------------------------------------------------------------------
+# Wrap: setup instructions output
+# ---------------------------------------------------------------------------
+
+
+def test_wrap_prints_proxy_urls(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The wrap command must print the proxy URLs for ZCode configuration."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
+
+ fake_rtk = Path("/tmp/rtk")
+
+ def fake_watcher(**kwargs): # noqa: ANN003
+ print_fn = kwargs.get("print_setup_lines")
+ if callable(print_fn):
+ print_fn()
+
+ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=fake_rtk):
+ with patch.object(wrap_mod, "_run_proxy_only_watcher", side_effect=fake_watcher):
+ result = runner.invoke(main, ["wrap", "zcode", "--port", "9000"])
+
+ assert result.exit_code == 0, result.output
+ assert "http://127.0.0.1:9000/v1" in result.output
+ assert "http://127.0.0.1:9000" in result.output
+ assert "Settings > Model Settings" in result.output
+
+
+# ---------------------------------------------------------------------------
+# Unwrap: RTK removal from AGENTS.md
+# ---------------------------------------------------------------------------
+
+
+def test_unwrap_removes_rtk_from_agents_md(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``unwrap zcode`` removes RTK instructions from AGENTS.md."""
+ monkeypatch.chdir(tmp_path)
+ agents_md = tmp_path / "AGENTS.md"
+ agents_md.write_text(
+ "# Project\n\nSome content.\n\n" + wrap_mod.RTK_INSTRUCTIONS_BLOCK + "\n",
+ encoding="utf-8",
+ )
+
+ with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
+ result = runner.invoke(main, ["unwrap", "zcode"])
+
+ assert result.exit_code == 0, result.output
+ assert "Removed Headroom rtk instructions" in result.output
+ content = agents_md.read_text(encoding="utf-8")
+ assert wrap_mod._RTK_MARKER not in content
+ assert "Some content." in content
+
+
+def test_unwrap_deletes_empty_agents_md(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``unwrap zcode`` deletes AGENTS.md if it only contained RTK instructions."""
+ monkeypatch.chdir(tmp_path)
+ agents_md = tmp_path / "AGENTS.md"
+ agents_md.write_text(wrap_mod.RTK_INSTRUCTIONS_BLOCK + "\n", encoding="utf-8")
+
+ with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
+ result = runner.invoke(main, ["unwrap", "zcode"])
+
+ assert result.exit_code == 0, result.output
+ assert not agents_md.exists(), "AGENTS.md should be deleted when only RTK content"
+
+
+def test_unwrap_noop_when_no_markers(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``unwrap zcode`` is a safe no-op when AGENTS.md has no Headroom markers."""
+ monkeypatch.chdir(tmp_path)
+ agents_md = tmp_path / "AGENTS.md"
+ agents_md.write_text("# Project\n\nSome content.\n", encoding="utf-8")
+
+ with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
+ result = runner.invoke(main, ["unwrap", "zcode"])
+
+ assert result.exit_code == 0, result.output
+ assert "Nothing to undo" in result.output
+ content = agents_md.read_text(encoding="utf-8")
+ assert content == "# Project\n\nSome content.\n"
+
+
+def test_unwrap_noop_when_no_agents_md(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``unwrap zcode`` is a safe no-op when AGENTS.md does not exist."""
+ monkeypatch.chdir(tmp_path)
+
+ with patch.object(wrap_mod, "_stop_local_proxy_for_unwrap", return_value="stopped"):
+ result = runner.invoke(main, ["unwrap", "zcode"])
+
+ assert result.exit_code == 0, result.output
+ assert "Nothing to undo" in result.output
+
+
+# ---------------------------------------------------------------------------
+# Runtime: proxy targets
+# ---------------------------------------------------------------------------
+
+
+def test_build_proxy_targets() -> None:
+ """build_proxy_targets returns correct OpenAI and Anthropic URLs."""
+ from headroom.providers.zcode.runtime import build_proxy_targets
+
+ targets = build_proxy_targets(8787)
+ assert targets.openai_base_url == "http://127.0.0.1:8787/v1"
+ assert targets.anthropic_base_url == "http://127.0.0.1:8787"
+
+
+def test_build_proxy_targets_custom_port() -> None:
+ """build_proxy_targets respects custom port."""
+ from headroom.providers.zcode.runtime import build_proxy_targets
+
+ targets = build_proxy_targets(9999)
+ assert targets.openai_base_url == "http://127.0.0.1:9999/v1"
+ assert targets.anthropic_base_url == "http://127.0.0.1:9999"
+
+
+def test_render_setup_lines_includes_mcp_instruction() -> None:
+ """render_setup_lines includes the MCP paste JSON for user convenience."""
+ from headroom.providers.zcode.runtime import render_setup_lines
+
+ lines = render_setup_lines(8787)
+ joined = "\n".join(lines)
+ assert "headroom" in joined.lower()
+ assert "MCP" in joined
+ assert '"stdio"' in joined
+
+
+# ---------------------------------------------------------------------------
+# Runtime: upstream detection
+# ---------------------------------------------------------------------------
+
+
+def test_detect_upstream_from_config(tmp_path: Path) -> None:
+ """detect_upstream reads config.json and returns the enabled provider."""
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "config.json"
+ config.write_text(
+ '{"provider": {"zai": {"name": "Z.ai", "kind": "anthropic", '
+ '"enabled": true, "options": {"baseURL": "https://api.z.ai/api/anthropic"}}}}',
+ encoding="utf-8",
+ )
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+ assert upstream.kind == "anthropic"
+
+
+def test_detect_upstream_openai_compatible(tmp_path: Path) -> None:
+ """detect_upstream handles OpenAI-compatible providers."""
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "config.json"
+ config.write_text(
+ '{"provider": {"custom": {"name": "Custom", "kind": "openai", '
+ '"enabled": true, "options": {"baseURL": "https://my-api.example.com/v1"}}}}',
+ encoding="utf-8",
+ )
+ upstream = detect_upstream(config)
+ assert upstream.kind == "openai"
+ assert upstream.base_url == "https://my-api.example.com/v1"
+
+
+def test_detect_upstream_disabled_provider_ignored(tmp_path: Path) -> None:
+ """detect_upstream skips disabled providers."""
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "config.json"
+ config.write_text(
+ '{"provider": {"zai": {"name": "Z.ai", "kind": "anthropic", '
+ '"enabled": false, "options": {"baseURL": "https://api.z.ai/api/anthropic"}}}}',
+ encoding="utf-8",
+ )
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai (default)"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+
+
+def test_detect_upstream_no_baseurl_skips(tmp_path: Path) -> None:
+ """detect_upstream skips providers with empty or missing baseURL."""
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "config.json"
+ config.write_text(
+ '{"provider": {"zai": {"name": "Z.ai", "kind": "anthropic", '
+ '"enabled": true, "options": {"baseURL": ""}}}}',
+ encoding="utf-8",
+ )
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai (default)"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+
+
+ "bad_options",
+ [
+ None,
+ [],
+ 42,
+ "just a string",
+ ],
+ ids=["null", "list", "int", "string"],
+)
+def test_detect_upstream_malformed_options_skips(tmp_path: Path, bad_options: object) -> None:
+ """detect_upstream falls back when provider options is not a dict."""
+ import json as _json
+
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "config.json"
+ config.write_text(
+ _json.dumps(
+ {
+ "provider": {
+ "bad": {
+ "name": "Bad Provider",
+ "kind": "anthropic",
+ "enabled": True,
+ "options": bad_options,
+ }
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai (default)"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+
+
+def test_detect_upstream_missing_file_fallback(tmp_path: Path) -> None:
+ """detect_upstream falls back to default when config file is missing."""
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "nonexistent.json"
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai (default)"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+ assert upstream.kind == "anthropic"
+
+
+def test_detect_upstream_invalid_json_fallback(tmp_path: Path) -> None:
+ """detect_upstream falls back to default on malformed JSON."""
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "config.json"
+ config.write_text("not json at all", encoding="utf-8")
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai (default)"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+
+
+def test_detect_upstream_no_providers_fallback(tmp_path: Path) -> None:
+ """detect_upstream falls back when config has no provider section."""
+ from headroom.providers.zcode.runtime import detect_upstream
+
+ config = tmp_path / "config.json"
+ config.write_text('{"settings": {}}', encoding="utf-8")
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai (default)"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+
+
+# ---------------------------------------------------------------------------
+# Runtime: upstream to proxy URLs
+# ---------------------------------------------------------------------------
+
+
+def test_upstream_to_proxy_urls_anthropic() -> None:
+ """upstream_to_proxy_urls returns (url, None) for anthropic upstream."""
+ from headroom.providers.zcode.runtime import ZCodeUpstream, upstream_to_proxy_urls
+
+ upstream = ZCodeUpstream(
+ provider_name="Z.ai", base_url="https://api.z.ai/api/anthropic", kind="anthropic"
+ )
+ anthropic_url, openai_url = upstream_to_proxy_urls(upstream)
+ assert anthropic_url == "https://api.z.ai/api/anthropic"
+ assert openai_url is None
+
+
+def test_upstream_to_proxy_urls_openai() -> None:
+ """upstream_to_proxy_urls returns (None, url) for openai-compatible upstream."""
+ from headroom.providers.zcode.runtime import ZCodeUpstream, upstream_to_proxy_urls
+
+ upstream = ZCodeUpstream(
+ provider_name="Custom",
+ base_url="https://my-api.example.com/v1",
+ kind="openai",
+ )
+ anthropic_url, openai_url = upstream_to_proxy_urls(upstream)
+ assert anthropic_url is None
+ assert openai_url == "https://my-api.example.com/v1"
+
+
+# ---------------------------------------------------------------------------
+# Wrap: upstream detection integration
+# ---------------------------------------------------------------------------
+
+
+def test_wrap_zcode_detects_upstream(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """wrap zcode detects upstream and prints detected provider in setup."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
+
+ config = tmp_path / "config.json"
+ config.write_text(
+ '{"provider": {"zai": {"name": "Z.ai Coding", "kind": "anthropic", '
+ '"enabled": true, "options": {"baseURL": "https://api.z.ai/api/anthropic"}}}}',
+ encoding="utf-8",
+ )
+
+ from headroom.providers.zcode.runtime import detect_upstream, upstream_to_proxy_urls
+
+ upstream = detect_upstream(config)
+ assert upstream.provider_name == "Z.ai Coding"
+ assert upstream.base_url == "https://api.z.ai/api/anthropic"
+
+ anthropic_url, openai_url = upstream_to_proxy_urls(upstream)
+ assert anthropic_url == "https://api.z.ai/api/anthropic"
+ assert openai_url is None
+
+
+def test_wrap_zcode_passes_upstream_to_watcher(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """wrap zcode forwards detected upstream URLs to _run_proxy_only_watcher."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
+
+ from headroom.providers.zcode.runtime import ZCodeUpstream
+
+ captured: dict[str, object] = {}
+
+ def fake_watcher(**kwargs): # noqa: ANN003
+ captured.update(kwargs)
+
+ fake_upstream = ZCodeUpstream(
+ provider_name="Z.ai", base_url="https://api.z.ai/api/anthropic", kind="anthropic"
+ )
+
+ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):
+ with patch.object(wrap_mod, "_detect_zcode_upstream", return_value=fake_upstream):
+ with patch.object(wrap_mod, "_run_proxy_only_watcher", side_effect=fake_watcher):
+ runner.invoke(main, ["wrap", "zcode", "--port", "9000"])
+
+ assert captured.get("anthropic_api_url") == "https://api.z.ai/api/anthropic"
+ assert captured.get("openai_api_url") is None
+ assert captured.get("port") == 9000
+
+
+def test_wrap_zcode_passes_openai_upstream(
+ runner: CliRunner,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """wrap zcode forwards OpenAI-compatible upstream URLs correctly."""
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
+
+ from headroom.providers.zcode.runtime import ZCodeUpstream
+
+ captured: dict[str, object] = {}
+
+ def fake_watcher(**kwargs): # noqa: ANN003
+ captured.update(kwargs)
+
+ fake_upstream = ZCodeUpstream(
+ provider_name="Custom", base_url="https://my-api.example.com/v1", kind="openai"
+ )
+
+ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):
+ with patch.object(wrap_mod, "_detect_zcode_upstream", return_value=fake_upstream):
+ with patch.object(wrap_mod, "_run_proxy_only_watcher", side_effect=fake_watcher):
+ runner.invoke(main, ["wrap", "zcode", "--port", "9000"])
+
+ assert captured.get("anthropic_api_url") is None
+ assert captured.get("openai_api_url") == "https://my-api.example.com/v1"