feat(wrap): reduce-at-source — SAFE quiet-CLI env defaults for the launched agent (#2548)

## Description
Reduce-at-source, done **safely** in the wrap layer (not by rewriting
commands in-flight): `headroom wrap` injects conservative quiet-CLI env
defaults into the launched agent's environment so tools emit less noise
at the source (which the proxy would otherwise strip post-hoc).

Injected only when the user hasn't set them: `GIT_PAGER=cat`,
`PIP_QUIET=1`, `PIP_DISABLE_PIP_VERSION_CHECK=1`,
`npm_config_fund/audit/progress=false`; `PYTEST_ADDOPTS` **augmented**
with `-q` (existing value preserved). Single chokepoint
(`_launch_tool`), so it covers all wrapped tools. Opt out with
`HEADROOM_WRAP_QUIET=0`.

Closes #

## Type of Change
- [x] Performance improvement / [x] New feature (opt-out)

## Safety
Nothing that can suppress diffs, errors, summaries, or search results —
no blanket `--silent`/`--quiet`. User-set values always win.

## Testing
```text
pytest tests/test_wrap_quiet_cli.py → 5 passed (defaults injected; user value wins; PYTEST_ADDOPTS augmented; opt-out; on-by-default)
ruff + mypy → clean
```

## Scope note (honesty)
A JSONL analysis of real Claude Code traffic shows this is a **modest**
lever for that workload: non-TTY git already disables the pager (so
`GIT_PAGER` is largely a no-op there), and pip/npm are low-traffic;
`PYTEST_ADDOPTS=-q` is the clearest win. It's harmless and captures
modest savings where those tools *are* used — the larger levers are
post-output (the lossless-guard lossy tier) and the grep fold.

## Checklist
- [x] Self-reviewed; tests pass; no CHANGELOG edit
This commit is contained in:
Tejas Chopra 2026-07-24 20:40:52 -07:00 committed by GitHub
parent 7dc9a978ca
commit c990cfb803
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 117 additions and 0 deletions

View file

@ -308,6 +308,54 @@ def _configure_tool_search_env(env: dict[str, str], flag_value: str | None) -> s
_TOOL_SEARCH_FALSY = {"false", "0", "no", "off"}
# Reduce-at-source: CLI tools pad tool_result output with progress bars, pager
# framing, funding/telemetry banners, and version nags — all zero-signal tokens
# the agent never acts on. Setting conservative, SAFE env defaults in the
# launched agent's environment makes those tools emit less AT THE SOURCE, so the
# proxy never has to strip them. Only knobs that can't hide diffs, errors,
# summaries, or search results are set here (no blanket --silent/--quiet).
# Opt out entirely with HEADROOM_WRAP_QUIET=0 (or false/no/off).
_QUIET_CLI_ENV = "HEADROOM_WRAP_QUIET"
_QUIET_CLI_FALSY = {"0", "false", "no", "off"}
# name -> value, injected only when the user has not already set it.
_QUIET_CLI_DEFAULTS: dict[str, str] = {
"GIT_PAGER": "cat", # never page (keeps full content, drops pager framing)
"PIP_QUIET": "1", # drop "Requirement already satisfied"/download chatter
"PIP_DISABLE_PIP_VERSION_CHECK": "1", # drop the "new pip available" nag
"npm_config_fund": "false", # drop the funding banner
"npm_config_audit": "false", # drop the audit summary (not a security scan here)
"npm_config_progress": "false", # drop the install progress bar
}
def _quiet_cli_enabled() -> bool:
"""Quiet-CLI source defaults are on unless HEADROOM_WRAP_QUIET is falsy."""
return os.environ.get(_QUIET_CLI_ENV, "").strip().lower() not in _QUIET_CLI_FALSY
def _configure_quiet_cli_env(env: dict[str, str]) -> list[str]:
"""Inject SAFE quiet-CLI defaults into ``env`` in place; return names set.
No-op when ``HEADROOM_WRAP_QUIET`` is falsy. A value the user already set
always wins (defaults are only filled when absent). ``PYTEST_ADDOPTS`` is
*augmented* with ``-q`` rather than clobbered, so an existing value survives.
Nothing RISKY (anything that could suppress diffs/errors/summaries/search
output) is ever set here.
"""
if not _quiet_cli_enabled():
return []
written: list[str] = []
for name, value in _QUIET_CLI_DEFAULTS.items():
if name not in env:
env[name] = value
written.append(name)
existing = env.get("PYTEST_ADDOPTS", "")
if "-q" not in existing.split():
env["PYTEST_ADDOPTS"] = f"{existing} -q".strip()
written.append("PYTEST_ADDOPTS")
return written
def _resolved_tool_search_mode(flag_value: str | None) -> str:
"""Predict the ``ENABLE_TOOL_SEARCH`` value the launched process will get.
@ -4461,10 +4509,19 @@ def _launch_tool(
if configure_launch is not None:
args, env, env_vars_display = configure_launch(actual_port, args, env, env_vars_display)
# Reduce-at-source: fill in SAFE quiet-CLI env defaults for the launched
# agent (git/npm/pip/pytest emit less noise), unless the user opted out.
# Applies to every wrapped tool since they all launch through here.
_quiet_written = _configure_quiet_cli_env(env)
click.echo()
click.echo(f" Launching {tool_label} (API routed through Headroom)...")
for var in env_vars_display:
click.echo(f" {var}")
if _quiet_written:
click.echo(
f" Quiet CLI defaults: {', '.join(_quiet_written)} (opt out: {_QUIET_CLI_ENV}=0)"
)
if args:
click.echo(f" Extra args: {' '.join(args)}")
_print_telemetry_notice()

View file

@ -0,0 +1,60 @@
"""`headroom wrap` reduce-at-source: SAFE quiet-CLI env defaults for the launched
agent. They fill in only when the user hasn't set the value, augment (never
clobber) PYTEST_ADDOPTS, and are fully opt-out via HEADROOM_WRAP_QUIET."""
from __future__ import annotations
from headroom.cli.wrap import _configure_quiet_cli_env, _quiet_cli_enabled
def test_defaults_injected_into_empty_env(monkeypatch) -> None:
monkeypatch.delenv("HEADROOM_WRAP_QUIET", raising=False)
env: dict[str, str] = {}
written = _configure_quiet_cli_env(env)
assert env["GIT_PAGER"] == "cat"
assert env["PIP_QUIET"] == "1"
assert env["PIP_DISABLE_PIP_VERSION_CHECK"] == "1"
assert env["npm_config_fund"] == "false"
assert env["npm_config_audit"] == "false"
assert env["npm_config_progress"] == "false"
assert env["PYTEST_ADDOPTS"] == "-q"
assert "GIT_PAGER" in written and "PYTEST_ADDOPTS" in written
def test_user_value_always_wins(monkeypatch) -> None:
monkeypatch.delenv("HEADROOM_WRAP_QUIET", raising=False)
env = {"GIT_PAGER": "less -R", "PIP_QUIET": "0"}
written = _configure_quiet_cli_env(env)
assert env["GIT_PAGER"] == "less -R" # untouched
assert env["PIP_QUIET"] == "0" # untouched
assert "GIT_PAGER" not in written and "PIP_QUIET" not in written
# ...but absent ones are still filled.
assert env["npm_config_fund"] == "false"
def test_pytest_addopts_augmented_not_clobbered(monkeypatch) -> None:
monkeypatch.delenv("HEADROOM_WRAP_QUIET", raising=False)
env = {"PYTEST_ADDOPTS": "-p no:cacheprovider"}
_configure_quiet_cli_env(env)
assert env["PYTEST_ADDOPTS"] == "-p no:cacheprovider -q" # preserved + augmented
# already-quiet stays as-is (no duplicate -q)
env2 = {"PYTEST_ADDOPTS": "-q --tb=short"}
written = _configure_quiet_cli_env(env2)
assert env2["PYTEST_ADDOPTS"] == "-q --tb=short"
assert "PYTEST_ADDOPTS" not in written
def test_opt_out_disables_injection(monkeypatch) -> None:
for off in ("0", "false", "no", "OFF"):
monkeypatch.setenv("HEADROOM_WRAP_QUIET", off)
assert _quiet_cli_enabled() is False
env: dict[str, str] = {}
assert _configure_quiet_cli_env(env) == []
assert env == {} # nothing injected
def test_enabled_by_default_and_on_truthy(monkeypatch) -> None:
monkeypatch.delenv("HEADROOM_WRAP_QUIET", raising=False)
assert _quiet_cli_enabled() is True
monkeypatch.setenv("HEADROOM_WRAP_QUIET", "1")
assert _quiet_cli_enabled() is True