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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(opencode): do not rewrite an OpenCode config that fails to parse (#4424)
HetCreep0fe0a597c192
diff --git a/headroom/providers/opencode/config.py b/headroom/providers/opencode/config.pyindex c1bbe6fcc..ca59a7900 100644--- a/headroom/providers/opencode/config.py+++ b/headroom/providers/opencode/config.py@@ -196,23 +196,48 @@ def _strip_jsonc_trailing_commas(text: str) -> str:return "".join(output)-def _parse_json_loose(text: str) -> dict[str, Any]:+def _try_parse_json_loose(text: str) -> dict[str, Any] | None:"""Parse JSON text and JSONC comments/trailing commas.Standard JSON is tried first so URLs containing ``//`` remain untouched.+ A leading UTF-8 BOM (written by some Windows editors) is ignored.+ Returns ``None`` when the text is not a JSON object."""+ text = text.lstrip("\ufeff")try:parsed = json.loads(text)- return parsed if isinstance(parsed, dict) else {}+ return parsed if isinstance(parsed, dict) else Noneexcept json.JSONDecodeError:passcleaned = _strip_jsonc_comments(text)cleaned = _strip_jsonc_trailing_commas(cleaned)try:parsed = json.loads(cleaned)- return parsed if isinstance(parsed, dict) else {}+ return parsed if isinstance(parsed, dict) else Noneexcept json.JSONDecodeError:+ return None+++def _parse_json_loose(text: str) -> dict[str, Any]:+ """Like :func:`_try_parse_json_loose`, but returns ``{}`` on failure."""+ return _try_parse_json_loose(text) or {}+++def load_user_opencode_config(content: str, config_file: Path) -> dict[str, Any]:+ """Parse the user's OpenCode config, refusing to treat unparseable text as empty.++ Callers rewrite the whole file from the result, so ``{}`` for a non-empty+ file we could not read would delete every user setting.+ """+ data = _try_parse_json_loose(content)+ if data is None:+ if content.lstrip("\ufeff").strip():+ raise click.ClickException(+ f"could not parse OpenCode config at {config_file}; "+ "leaving it unchanged. Fix the JSON/JSONC syntax and retry."+ )return {}+ return datadef _inject_key_into_json(data: dict[str, Any], key: str, value: Any) -> dict[str, Any]:@@ -248,7 +273,7 @@ def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = Falsif config_file.exists():content = fsutil.read_text(config_file)- data = _parse_json_loose(content)+ data = load_user_opencode_config(content, config_file)else:content = ""data = {}@@ -256,7 +281,7 @@ def inject_opencode_provider_config(port: int, *, keep_user_entries: bool = Fals# 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)+ data = load_user_opencode_config(content, config_file)# Merge provider into the JSON data structure.entry = headroom_provider_entry(port)diff --git a/headroom/providers/opencode/install.py b/headroom/providers/opencode/install.pyindex 9563317f2..c22e9bc57 100644--- a/headroom/providers/opencode/install.py+++ b/headroom/providers/opencode/install.py@@ -13,6 +13,7 @@ from headroom.install.paths import opencode_config_pathfrom .config import (_inject_key_into_json,_parse_json_loose,+ load_user_opencode_config,migrate_legacy_opencode_jsonc_backup,snapshot_opencode_config_if_unwrapped,strip_opencode_headroom_blocks,@@ -40,7 +41,7 @@ def apply_provider_scope(manifest: DeploymentManifest) -> ManagedMutation | Noneif config_file.exists():content = fsutil.read_text(config_file)- data = _parse_json_loose(content)+ data = load_user_opencode_config(content, config_file)else:data = {}diff --git a/tests/test_providers_opencode_config.py b/tests/test_providers_opencode_config.pyindex 142c7c185..e558c4518 100644--- a/tests/test_providers_opencode_config.py+++ b/tests/test_providers_opencode_config.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+import clickimport pytestfrom headroom.providers.opencode.config import (@@ -748,3 +749,90 @@ def test_jsonc_migration_treats_dangling_conflict_as_ambiguous(migrate_legacy_opencode_jsonc_backup(config, canonical)assert not canonical.exists()assert legacy.read_bytes() == original+++# ---------------------------------------------------------------------------+# Unparseable user config must not be rewritten+# ---------------------------------------------------------------------------+++def test_inject_provider_config_keeps_user_keys_with_bom(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A config saved with a UTF-8 BOM keeps its user keys when the provider is injected."""+ _set_test_home(monkeypatch, tmp_path)+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True)+ bom = chr(0xFEFF)+ config_file.write_text(bom + '{"model": "gpt-4o", "mcp": {"x": {}}}', encoding="utf-8")++ inject_opencode_provider_config(port=8787)++ config = json.loads(config_file.read_text(encoding="utf-8"))+ assert config["model"] == "gpt-4o"+ assert config["mcp"] == {"x": {}}+ assert "headroom" in config["provider"]+++def test_inject_provider_config_leaves_unparseable_config_untouched(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A non-empty config that cannot be parsed is reported, not replaced."""+ _set_test_home(monkeypatch, tmp_path)+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True)+ original = '{"model": "gpt-4o" "oops": 1}'+ config_file.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match="could not parse"):+ inject_opencode_provider_config(port=8787)++ assert config_file.read_text(encoding="utf-8") == original++[email protected]("suffix", ["", " \n"])+def test_inject_provider_config_treats_bom_only_config_as_empty(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, suffix: str+) -> None:+ """A config holding only a BOM (and whitespace) is empty, not unparseable."""+ _set_test_home(monkeypatch, tmp_path)+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True)+ config_file.write_text(chr(0xFEFF) + suffix, encoding="utf-8")++ inject_opencode_provider_config(port=8787)++ config = json.loads(config_file.read_text(encoding="utf-8"))+ assert "headroom" in config["provider"]+++def test_inject_provider_config_reparses_config_with_legacy_marker_block(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A config holding a comment-marked Headroom block is re-parsed after the strip.++ The marker comments are what older writers left in the file; the strip runs+ before the provider is merged, and the user's keys outside the block survive.+ """+ _set_test_home(monkeypatch, tmp_path)+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True)+ config_file.write_text(+ "{\n"+ ' "model": "gpt-4o",\n'+ " // --- Headroom proxy provider ---\n"+ ' "provider": {"headroom": {"options": {"baseURL": "http://127.0.0.1:1"}}},\n'+ " // --- end Headroom proxy provider ---\n"+ ' "theme": "dark"\n'+ "}\n",+ encoding="utf-8",+ )++ inject_opencode_provider_config(port=8787)++ config = json.loads(config_file.read_text(encoding="utf-8"))+ assert config["model"] == "gpt-4o"+ assert config["theme"] == "dark"+ headroom = config["provider"]["headroom"]+ assert "8787" in json.dumps(headroom)+ assert headroom.get("options", {}).get("baseURL") != "http://127.0.0.1:1"diff --git a/tests/test_providers_opencode_install.py b/tests/test_providers_opencode_install.pyindex cfe236902..7760d8698 100644--- a/tests/test_providers_opencode_install.py+++ b/tests/test_providers_opencode_install.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+import clickimport pytestfrom headroom.install.models import ConfigScope, DeploymentManifest@@ -762,3 +763,22 @@ def test_unambiguous_legacy_backup_still_migrates_and_restores(revert_provider_scope(mutation, manifest)assert config.read_bytes() == originalassert not canonical.exists()+++def test_apply_provider_scope_leaves_unparseable_config_untouched(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """apply_provider_scope reports an unparseable config instead of replacing it."""+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ monkeypatch.delenv("OPENCODE_HOME", raising=False)+ monkeypatch.delenv("OPENCODE_CONFIG", raising=False)+ config_file = tmp_path / ".config" / "opencode" / "opencode.json"+ config_file.parent.mkdir(parents=True)+ original = '{"model": "gpt-4o" "oops": 1}'+ config_file.write_text(original, encoding="utf-8")++ with pytest.raises(click.ClickException, match="could not parse"):+ apply_provider_scope(_manifest())++ assert config_file.read_text(encoding="utf-8") == original