Skip to content

Commit c831081

Browse files
ngpestelosGrok 4.5Nestor G Pestelos JrJD Davis
authored
fix(wrap): set xAI upstream for grok-build proxy (#2772)
## Description `headroom wrap grok-build` injected the client hop into `~/.grok/config.toml` but started the local proxy **without** setting the OpenAI-compatible upstream to xAI. The proxy defaulted to `api.openai.com`, so Grok session auth returned **401** on every chat completion even though compression still ran. `wrap grok` already passes `openai_api_url` → xAI. This PR aligns `wrap grok-build` and the Grok-only persistent `install` path on the shared `DEFAULT_API_URL` (`https://api.x.ai`). Closes # (none — discovered in live Grok Build pilot) ## Type of Change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Pass `openai_api_url=_GROK_DEFAULT_API_URL` into `_run_proxy_only_watcher` from `wrap grok-build` - Use shared `DEFAULT_API_URL` from `wrap grok` (no hard-coded string drift) - Print proxy upstream in Grok Build setup lines - Persistent install: when targets are Grok-only, set `OPENAI_TARGET_API_URL` + `--openai-api-url` (skip when Codex/Copilot/Aider/OpenCode share the proxy; explicit env still wins) - Regression tests for wrap kwargs, setup lines, and install planner ## Testing - [x] Unit tests pass (`pytest` targeted suite) - [ ] Linting passes (`ruff check .`) — not run in this environment (no native editable build) - [ ] Type checking passes (`mypy headroom`) — not run - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ PYTHONPATH=$PWD python -m pytest \ tests/test_cli/test_wrap_bridge.py::test_wrap_grok_build_passes_xai_openai_api_url \ tests/test_cli/test_wrap_bridge.py::test_wrap_grok_build_uses_actual_proxy_port \ tests/test_install/test_planner.py::test_build_manifest_grok_build_only_sets_xai_upstream \ tests/test_install/test_planner.py::test_build_manifest_grok_with_codex_does_not_force_xai \ tests/test_install/test_planner.py::test_build_manifest_extra_env_wins_over_grok_xai_default \ tests/test_provider_grok_build.py::test_grok_build_setup_lines_include_proxy_url -q ...... 6 passed in 0.33s ``` ## Real Behavior Proof - Environment: macOS (darwin), Headroom 0.33.0 via `uv tool install "headroom-ai[proxy,mcp,code]==0.33.0"`, Grok Build CLI, models `grok-build` and `grok-4.5`, proxy on `127.0.0.1:8787`, upstream must be xAI - Exact command / steps: (1) Before: stock `headroom wrap grok-build` then `grok -m grok-build` one-shot prompt. (2) After: same wrap path with this branch (`openai_api_url=DEFAULT_API_URL` into `_run_proxy_only_watcher`) then `grok -m grok-build -p '…HEADROOM_XAI_OK…'`. Also exercised `grok-4.5` via `[model."grok-4.5"] base_url` → same proxy. - Observed result: Before — proxy log outbound `api.openai.com` → HTTP 401; client failed while local compression still ran. After — setup line prints Proxy upstream `https://api.x.ai`; proxy log `POST https://api.x.ai/v1/chat/completions` (and `/v1/responses` for grok-4.5) → status=200; dashboard shows 0 failed requests and accumulating token savings on live traffic. - Not tested: full `uv run` editable/maturin native build on this host; multi-tool install matrix beyond planner unit tests; Windows; ruff/mypy full tree ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I commented my code, particularly in hard-to-understand areas - [ ] I made corresponding changes to the documentation (CLI help text / setup lines only) - [x] My changes generate no new warnings - [x] I added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — generated by release-please from Conventional Commit PR title (a CI guard enforces this) ## Additional Notes - Intentional non-goal: changing default model, savings %, or Grok Build context-tool defaults - Mixed-target install (e.g. `grok_build` + `codex`) does **not** force xAI — operator must set upstream explicitly if they share one proxy - Related live routing: manual `[model."grok-4.5"] base_url` through the same proxy works once upstream is xAI (`/v1/responses`) --------- Co-authored-by: Grok 4.5 <noreply@x.ai> Co-authored-by: Nestor G Pestelos Jr <ngpestelos@me.com> Co-authored-by: JD Davis <jd@jds-macbook-air.tail2a279.ts.net>
1 parent 6d87825 commit c831081

6 files changed

Lines changed: 110 additions & 5 deletions

File tree

headroom/cli/wrap.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,12 @@
136136
validate_configuration as _validate_copilot_configuration,
137137
)
138138
from headroom.providers.cursor import render_setup_lines as _render_cursor_setup_lines
139-
from headroom.providers.grok import build_launch_env as _build_grok_launch_env
139+
from headroom.providers.grok import (
140+
DEFAULT_API_URL as _GROK_DEFAULT_API_URL,
141+
)
142+
from headroom.providers.grok import (
143+
build_launch_env as _build_grok_launch_env,
144+
)
140145
from headroom.providers.grok_build import render_setup_lines as _render_grok_build_setup_lines
141146
from headroom.providers.grok_build.config import (
142147
inject_grok_provider_config,
@@ -6417,7 +6422,7 @@ def grok(
64176422
backend=backend,
64186423
anyllm_provider=anyllm_provider,
64196424
region=region,
6420-
openai_api_url="https://api.x.ai",
6425+
openai_api_url=_GROK_DEFAULT_API_URL,
64216426
)
64226427

64236428

@@ -6507,9 +6512,9 @@ def grok_build(
65076512
65086513
\b
65096514
Grok Build reads model endpoints from ``~/.grok/config.toml``. This
6510-
command starts the proxy, optionally sets up the selected CLI context
6511-
tool, injects a Headroom-managed ``[model.grok-build]`` override, and
6512-
prints next steps.
6515+
command starts the proxy (upstream ``https://api.x.ai``, same as
6516+
``wrap grok``), injects a Headroom-managed ``[model.grok-build]``
6517+
override, and prints next steps.
65136518
65146519
\b
65156520
Example:
@@ -6536,6 +6541,8 @@ def _print_grok_build_setup(actual_port: int) -> None:
65366541
for line in _render_grok_build_setup_lines(actual_port, project=project):
65376542
click.echo(line)
65386543

6544+
# Client hop is local proxy via config.toml; upstream must be xAI (not
6545+
# the OpenAI default). Omitting this caused 401s with Grok auth headers.
65396546
_run_proxy_only_watcher(
65406547
agent_label="grok-build",
65416548
port=port,
@@ -6544,6 +6551,7 @@ def _print_grok_build_setup(actual_port: int) -> None:
65446551
memory=memory,
65456552
agent_type="grok_build",
65466553
print_setup_lines=_print_grok_build_setup,
6554+
openai_api_url=_GROK_DEFAULT_API_URL,
65476555
)
65486556

65496557

headroom/install/planner.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import click
1010

1111
from headroom import paths as _paths
12+
from headroom.providers.grok.runtime import DEFAULT_API_URL as _GROK_DEFAULT_API_URL
1213
from headroom.providers.install_registry import build_install_target_envs
1314
from headroom.rollout import RolloutChannel
1415

@@ -177,6 +178,19 @@ def build_manifest(
177178
base_env["HEADROOM_TELEMETRY"] = "on" if telemetry_enabled else "off"
178179
if memory_enabled:
179180
base_env["HEADROOM_MEMORY_ENABLED"] = "1"
181+
# Grok / Grok Build need proxy upstream = xAI. Only auto-set when no other
182+
# OpenAI-compatible tools share this proxy (those may need api.openai.com /
183+
# Copilot). Explicit OPENAI_TARGET_API_URL in extra_env still wins below.
184+
_openai_native = {
185+
ToolTarget.CODEX.value,
186+
ToolTarget.COPILOT.value,
187+
ToolTarget.AIDER.value,
188+
ToolTarget.OPENCODE.value,
189+
}
190+
_grok_targets = {ToolTarget.GROK.value, ToolTarget.GROK_BUILD.value}
191+
target_set = set(resolved_targets)
192+
if target_set & _grok_targets and not (target_set & _openai_native):
193+
base_env.setdefault("OPENAI_TARGET_API_URL", _GROK_DEFAULT_API_URL)
180194
# Applied last so explicit --env overrides win over the auto-derived
181195
# defaults above (e.g. a custom HEADROOM_WORKSPACE_DIR).
182196
if extra_env:
@@ -241,6 +255,9 @@ def build_manifest(
241255
proxy_args.extend(["--protect-tool-results", protect_tool_results])
242256
if bedrock_profile:
243257
proxy_args.extend(["--bedrock-profile", bedrock_profile])
258+
openai_target = base_env.get("OPENAI_TARGET_API_URL")
259+
if openai_target:
260+
proxy_args.extend(["--openai-api-url", openai_target])
244261

245262
container_name = f"headroom-{normalized_profile}"
246263
return DeploymentManifest(

headroom/providers/grok_build/runtime.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from dataclasses import dataclass
66

7+
from headroom.providers.grok.runtime import DEFAULT_API_URL
78
from headroom.proxy.project_context import with_project_prefix
89

910

@@ -41,6 +42,8 @@ def render_setup_lines(port: int, project: str | None = None) -> list[str]:
4142
" [model.grok-build]",
4243
f' base_url = "{target.base_url}"',
4344
"",
45+
f" Proxy upstream (OpenAI-compatible): {DEFAULT_API_URL}",
46+
"",
4447
" Start Grok Build in this project directory:",
4548
" grok",
4649
"",

tests/test_cli/test_wrap_bridge.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,40 @@ def fake_watcher(**kwargs) -> None:
7474
assert "http://127.0.0.1:8787/" not in result.output
7575

7676

77+
def test_wrap_grok_build_passes_xai_openai_api_url(monkeypatch, tmp_path: Path) -> None:
78+
"""Grok Build must set proxy upstream to xAI (same as wrap grok).
79+
80+
Without openai_api_url, the proxy defaults to api.openai.com and Grok
81+
session auth returns 401 on every chat completion.
82+
"""
83+
from headroom.providers.grok import DEFAULT_API_URL
84+
85+
_set_test_home(monkeypatch, tmp_path)
86+
runner = CliRunner()
87+
captured: dict = {}
88+
89+
def fake_watcher(**kwargs) -> None:
90+
captured.update(kwargs)
91+
kwargs["print_setup_lines"](kwargs["port"])
92+
93+
monkeypatch.setattr("headroom.cli.wrap._run_proxy_only_watcher", fake_watcher)
94+
95+
result = runner.invoke(main, ["wrap", "grok-build", "--port", "8787"])
96+
97+
assert result.exit_code == 0, result.output
98+
assert captured.get("openai_api_url") == DEFAULT_API_URL
99+
# Equality on the constant (not substring containment) keeps CodeQL
100+
# incomplete-url-substring-sanitization quiet while pinning the host.
101+
assert DEFAULT_API_URL == "https://api.x.ai"
102+
expected_upstream = f" Proxy upstream (OpenAI-compatible): {DEFAULT_API_URL}"
103+
upstream_lines = [
104+
line
105+
for line in result.output.splitlines()
106+
if line.startswith(" Proxy upstream (OpenAI-compatible): ")
107+
]
108+
assert upstream_lines == [expected_upstream]
109+
110+
77111
def test_wrap_rejects_retired_context_tool_flag(monkeypatch, tmp_path: Path) -> None:
78112
"""A surviving --context-tool must fail loudly, not be silently ignored.
79113

tests/test_install/test_planner.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,3 +330,38 @@ def test_build_manifest_extra_env_overrides_derived_defaults() -> None:
330330
# telemetry_enabled=False in _base_manifest_kwargs would normally set "off";
331331
# an explicit --env must win.
332332
assert manifest.base_env["HEADROOM_TELEMETRY"] == "on"
333+
334+
335+
def test_build_manifest_grok_build_only_sets_xai_upstream() -> None:
336+
"""Persistent install for Grok Build alone must route proxy upstream to xAI."""
337+
from headroom.providers.grok import DEFAULT_API_URL
338+
339+
manifest = build_manifest(**_base_manifest_kwargs(targets=["grok_build"], backend="openai"))
340+
341+
assert manifest.base_env.get("OPENAI_TARGET_API_URL") == DEFAULT_API_URL
342+
idx = manifest.proxy_args.index("--openai-api-url")
343+
assert manifest.proxy_args[idx + 1] == DEFAULT_API_URL
344+
345+
346+
def test_build_manifest_grok_with_codex_does_not_force_xai() -> None:
347+
"""Do not override OpenAI upstream when OpenAI-native tools share the proxy."""
348+
manifest = build_manifest(
349+
**_base_manifest_kwargs(targets=["grok_build", "codex"], backend="openai")
350+
)
351+
352+
assert "OPENAI_TARGET_API_URL" not in manifest.base_env
353+
assert "--openai-api-url" not in manifest.proxy_args
354+
355+
356+
def test_build_manifest_extra_env_wins_over_grok_xai_default() -> None:
357+
manifest = build_manifest(
358+
**_base_manifest_kwargs(
359+
targets=["grok_build"],
360+
backend="openai",
361+
extra_env={"OPENAI_TARGET_API_URL": "https://gateway.example/v1"},
362+
)
363+
)
364+
365+
assert manifest.base_env["OPENAI_TARGET_API_URL"] == "https://gateway.example/v1"
366+
idx = manifest.proxy_args.index("--openai-api-url")
367+
assert manifest.proxy_args[idx + 1] == "https://gateway.example/v1"

tests/test_provider_grok_build.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import pytest
77

8+
from headroom.providers.grok import DEFAULT_API_URL
89
from headroom.providers.grok_build import build_proxy_targets, render_setup_lines
910
from headroom.providers.grok_build.config import (
1011
inject_grok_provider_config,
@@ -46,6 +47,13 @@ def test_grok_build_setup_lines_include_proxy_url() -> None:
4647

4748
assert "http://127.0.0.1:8787/v1" in joined
4849
assert "[model.grok-build]" in joined
50+
# Exact labeled line equality (not bare host substring containment) so
51+
# CodeQL does not flag incomplete URL substring sanitization.
52+
expected_upstream = f" Proxy upstream (OpenAI-compatible): {DEFAULT_API_URL}"
53+
upstream_lines = [
54+
line for line in lines if line.startswith(" Proxy upstream (OpenAI-compatible): ")
55+
]
56+
assert upstream_lines == [expected_upstream]
4957

5058

5159
def test_grok_build_build_install_env_returns_proxy_url() -> None:

0 commit comments

Comments
 (0)