Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(opencode): support JSONC config loading

cyhabe96cf58b74
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 6c01fac63..33ba12037 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -17,6 +17,7 @@ from typing import Any, Dict, List, Optional
import aiohttp
from config import paths
+from vibe.opencode_config import load_first_opencode_user_config
logger = logging.getLogger(__name__)
@@ -644,29 +645,8 @@ class OpenCodeServerManager:
Returns:
Parsed config dict, or None if file doesn't exist or is invalid.
"""
-
- from pathlib import Path
-
- config_paths = [
- Path.home() / ".config" / "opencode" / "opencode.json",
- Path.home() / ".opencode" / "opencode.json",
- ]
-
- for config_path in config_paths:
- if not config_path.exists():
- continue
- try:
- with open(config_path, "r") as f:
- config = json.load(f)
- if not isinstance(config, dict):
- logger.warning(f"{config_path}: root is not a dict")
- continue
- return config
- except Exception as e:
- logger.warning(f"Failed to load {config_path}: {e}")
- continue
-
- return None
+ config, _ = load_first_opencode_user_config(logger_instance=logger)
+ return config
def _get_agent_config(self, config: Dict[str, Any], agent_name: Optional[str]) -> Dict[str, Any]:
"""Get agent-specific config from opencode.json with type safety."""
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index f0c4b278e..2ceb5d92c 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -1,10 +1,24 @@
+import importlib.util
import sys
+import tempfile
+import types
import unittest
from pathlib import Path
+from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from modules.agents.opencode.server import OpenCodeServerManager
+aiohttp_stub = types.ModuleType("aiohttp")
+aiohttp_stub.ClientSession = object
+aiohttp_stub.ClientTimeout = object
+sys.modules.setdefault("aiohttp", aiohttp_stub)
+
+MODULE_PATH = Path(__file__).resolve().parents[1] / "modules" / "agents" / "opencode" / "server.py"
+SPEC = importlib.util.spec_from_file_location("opencode_server_for_test", MODULE_PATH)
+assert SPEC and SPEC.loader
+SERVER_MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(SERVER_MODULE)
+OpenCodeServerManager = SERVER_MODULE.OpenCodeServerManager
class _FakeResponse:
@@ -52,6 +66,33 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):
body = fake_session.posts[0]["json"]
self.assertEqual(body["tools"], {"question": False})
+ async def test_load_opencode_user_config_supports_jsonc(self):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ tmp_home = Path(tmp_dir)
+ config_path = tmp_home / ".config" / "opencode" / "opencode.json"
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(
+ """{
+ // Preserve defaults from JSONC config.
+ "model": "openai/gpt-5",
+ "reasoningEffort": "high",
+}
+""",
+ encoding="utf-8",
+ )
+
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ with patch("vibe.opencode_config.Path.home", return_value=tmp_home):
+ config = manager._load_opencode_user_config()
+
+ self.assertEqual(
+ config,
+ {
+ "model": "openai/gpt-5",
+ "reasoningEffort": "high",
+ },
+ )
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index ab0f7c570..39d77f6a4 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1,3 +1,5 @@
+import json
+
from vibe import api
@@ -172,3 +174,61 @@ def test_install_codex_detects_binary_via_npm_prefix(monkeypatch, tmp_path):
assert result["path"] == str(codex_path)
assert calls[0][0] == [str(npm_path), "install", "-g", "@openai/codex"]
assert calls[0][1]["PATH"].split(api.os.pathsep)[0] == str(npm_path.parent)
+
+
+def test_setup_opencode_permission_preserves_existing_json_fields(monkeypatch, tmp_path):
+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(
+ json.dumps(
+ {
+ "model": "openai/gpt-5",
+ "agent": {"build": {"model": "anthropic/claude-sonnet-4-5"}},
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+
+ result = api.setup_opencode_permission()
+ updated = json.loads(config_path.read_text(encoding="utf-8"))
+
+ assert result["ok"] is True
+ assert result["config_path"] == str(config_path)
+ assert updated == {
+ "model": "openai/gpt-5",
+ "agent": {"build": {"model": "anthropic/claude-sonnet-4-5"}},
+ "permission": "allow",
+ }
+
+
+def test_setup_opencode_permission_accepts_jsonc_config(monkeypatch, tmp_path):
+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(
+ """{
+ // Global defaults should be preserved.
+ "model": "openai/gpt-5",
+ "agent": {
+ "build": {
+ "model": "anthropic/claude-sonnet-4-5",
+ },
+ },
+}
+""",
+ encoding="utf-8",
+ )
+
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+
+ result = api.setup_opencode_permission()
+ updated = json.loads(config_path.read_text(encoding="utf-8"))
+
+ assert result["ok"] is True
+ assert result["config_path"] == str(config_path)
+ assert updated == {
+ "model": "openai/gpt-5",
+ "agent": {"build": {"model": "anthropic/claude-sonnet-4-5"}},
+ "permission": "allow",
+ }
diff --git a/vibe/api.py b/vibe/api.py
index 3e52ab903..06e455f06 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -21,6 +21,7 @@ from config.v2_settings import (
_routing_to_dict,
)
from config.v2_sessions import SessionsStore
+from vibe.opencode_config import get_opencode_config_paths, load_first_opencode_user_config
from vibe.upgrade import build_upgrade_plan, get_latest_version_info, get_restart_shell_command, get_running_vibe_path
@@ -700,8 +701,8 @@ def setup_opencode_permission() -> dict:
"""Set OpenCode permission to 'allow' in config file.
Detection priority (aligned with _load_opencode_user_config):
- 1. ~/.config/opencode/opencode.json - if exists and valid, update it
- 2. ~/.opencode/opencode.json - if exists and valid, update it
+ 1. ~/.config/opencode/opencode.json - if exists and valid JSON/JSONC, update it
+ 2. ~/.opencode/opencode.json - if exists and valid JSON/JSONC, update it
3. Create new file at ~/.config/opencode/opencode.json (XDG standard)
Mirrors _load_opencode_user_config behavior: skips invalid files and tries next.
@@ -709,50 +710,24 @@ def setup_opencode_permission() -> dict:
Returns:
{"ok": bool, "message": str, "config_path": str}
"""
- from pathlib import Path
+ config_paths = get_opencode_config_paths(Path.home())
+ config, config_path = load_first_opencode_user_config(home=Path.home(), logger_instance=logger)
- config_paths = [
- Path.home() / ".config" / "opencode" / "opencode.json",
- Path.home() / ".opencode" / "opencode.json",
- ]
-
- # Try each path in priority order
- for config_path in config_paths:
- if not config_path.exists():
- continue
-
- try:
- content = config_path.read_text(encoding="utf-8").strip()
- if not content:
- # Empty file, treat as valid empty config
- config = {}
- else:
- config = json.loads(content)
- if not isinstance(config, dict):
- logger.warning(f"{config_path}: not a JSON object, skipping")
- continue
-
- # Found a valid config file, update it
- if config.get("permission") == "allow":
- return {
- "ok": True,
- "message": "Permission already set",
- "config_path": str(config_path),
- }
-
- config["permission"] = "allow"
- config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+ if config is not None and config_path is not None:
+ if config.get("permission") == "allow":
return {
"ok": True,
- "message": "Permission set to 'allow'",
+ "message": "Permission already set",
"config_path": str(config_path),
}
- except json.JSONDecodeError as e:
- logger.warning(f"{config_path}: invalid JSON ({e}), skipping")
- continue
- except Exception as e:
- logger.warning(f"{config_path}: failed to read ({e}), skipping")
- continue
+
+ config["permission"] = "allow"
+ config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
+ return {
+ "ok": True,
+ "message": "Permission set to 'allow'",
+ "config_path": str(config_path),
+ }
# No existing valid config found, create at XDG path (first in list)
config_path = config_paths[0]
diff --git a/vibe/opencode_config.py b/vibe/opencode_config.py
new file mode 100644
index 000000000..a80f67f47
--- /dev/null
+++ b/vibe/opencode_config.py
@@ -0,0 +1,152 @@
+"""Helpers for reading OpenCode user config files."""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+
+def get_opencode_config_paths(home: Path | None = None) -> list[Path]:
+ resolved_home = home or Path.home()
+ return [
+ resolved_home / ".config" / "opencode" / "opencode.json",
+ resolved_home / ".opencode" / "opencode.json",
+ ]
+
+
+def _strip_jsonc_comments(source: str) -> str:
+ result: list[str] = []
+ in_string = False
+ escaped = False
+ in_line_comment = False
+ in_block_comment = False
+
+ i = 0
+ while i < len(source):
+ char = source[i]
+ next_char = source[i + 1] if i + 1 < len(source) else ""
+
+ if in_line_comment:
+ if char == "\n":
+ in_line_comment = False
+ result.append(char)
+ i += 1
+ continue
+
+ if in_block_comment:
+ if char == "*" and next_char == "/":
+ in_block_comment = False
+ i += 2
+ continue
+ if char == "\n":
+ result.append(char)
+ i += 1
+ continue
+
+ if in_string:
+ result.append(char)
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == '"':
+ in_string = False
+ i += 1
+ continue
+
+ if char == '"':
+ in_string = True
+ result.append(char)
+ i += 1
+ continue
+
+ if char == "/" and next_char == "/":
+ in_line_comment = True
+ i += 2
+ continue
+
+ if char == "/" and next_char == "*":
+ in_block_comment = True
+ i += 2
+ continue
+
+ result.append(char)
+ i += 1
+
+ return "".join(result)
+
+
+def _strip_trailing_commas(source: str) -> str:
+ result: list[str] = []
+ in_string = False
+ escaped = False
+
+ i = 0
+ while i < len(source):
+ char = source[i]
+
+ if in_string:
+ result.append(char)
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == '"':
+ in_string = False
+ i += 1
+ continue
+
+ if char == '"':
+ in_string = True
+ result.append(char)
+ i += 1
+ continue
+
+ if char == ",":
+ j = i + 1
+ while j < len(source) and source[j] in " \t\r\n":
+ j += 1
+ if j < len(source) and source[j] in "}]":
+ i += 1
+ continue
+
+ result.append(char)
+ i += 1
+
+ return "".join(result)
+
+
+def parse_jsonc_object(content: str) -> Dict[str, Any]:
+ normalized = _strip_trailing_commas(_strip_jsonc_comments(content.lstrip("\ufeff"))).strip()
+ if not normalized:
+ return {}
+
+ parsed = json.loads(normalized)
+ if not isinstance(parsed, dict):
+ raise ValueError("root is not a JSON object")
+ return parsed
+
+
+def load_first_opencode_user_config(
+ *,
+ home: Path | None = None,
+ logger_instance: Optional[logging.Logger] = None,
+) -> tuple[Optional[Dict[str, Any]], Optional[Path]]:
+ active_logger = logger_instance or logger
+
+ for config_path in get_opencode_config_paths(home):
+ if not config_path.exists():
+ continue
+
+ try:
+ content = config_path.read_text(encoding="utf-8")
+ return parse_jsonc_object(content), config_path
+ except Exception as exc:
+ active_logger.warning(f"Failed to load {config_path}: {exc}")
+ continue
+
+ return None, None