Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Let OpenClaw app setup read valid JSON5 (#15029)

Nilay213118f1e4fc
diff --git a/pyproject.toml b/pyproject.toml
index 2aa193a6b3d..8868ca55a57 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -34,6 +34,7 @@ dependencies = [
"rich",
"pydantic",
"pyyaml",
+ "json5>=0.9.25",
"nest-asyncio",
"huggingface-hub>=0.34.0",
# Every CLI command imports studio.backend.*, which reaches structlog at
@@ -177,6 +178,7 @@ studio = [
"jinja2>=3.1.0",
"structlog>=24.1.0",
"diceware==1.0.1",
+ "json5>=0.9.25",
"ddgs==9.14.4 ; python_version >= '3.10'",
"ddgs==9.8.0 ; python_version < '3.10'",
"cryptography>=42.0.0; sys_platform != 'win32' or platform_machine != 'ARM64'",
diff --git a/studio/backend/requirements/no-torch-runtime.txt b/studio/backend/requirements/no-torch-runtime.txt
index e7a424eb4a6..5d9a4f2b0f6 100644
--- a/studio/backend/requirements/no-torch-runtime.txt
+++ b/studio/backend/requirements/no-torch-runtime.txt
@@ -24,6 +24,7 @@ pygments>=2.0
# to the exact version pydantic's _ensure_pydantic_core_version check
# expects. Pinning both under --no-deps used to drift them apart.
pyyaml==6.0.3
+json5>=0.9.25
nest-asyncio==1.6.0
# HF ecosystem (from [huggingfacenotorch] extras in pyproject.toml)
diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txt
index 6381a9f7c0c..2667a697c9a 100644
--- a/studio/backend/requirements/studio.txt
+++ b/studio/backend/requirements/studio.txt
@@ -39,6 +39,7 @@ urllib3>=2.3.0; python_version < "3.10"
# arrives there, and Hermes-3's tool_use branch fails to compile below it.
jinja2>=3.1.0
structlog>=24.1.0
+json5>=0.9.25
diceware==1.0.1
ddgs==9.14.4; python_version >= "3.10"
ddgs==9.8.0; python_version < "3.10"
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 6a0dd5f668b..96963ee92f7 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -6240,10 +6240,21 @@ _JSONC_COMMENT = re.compile(r'("(?:\\.|[^"\\])*")|//[^\n]*|/\*.*?\*/', re.S)
_JSONC_TRAILING_COMMA = re.compile(r'("(?:\\.|[^"\\])*")|,(?=\s*[\]}])')
-def _load_app_config(path: Path, text: Optional[str]) -> Optional[dict]:
+def _load_app_config(
+ path: Path,
+ text: Optional[str],
+ *,
+ allow_json5: bool = False,
+) -> Optional[dict]:
if text is None or not text.strip():
return {}
- if path.suffix == ".toml":
+ if allow_json5:
+ import json5
+
+ # Raw text: the JSONC stripper below misreads // inside single-quoted JSON5 strings.
+ # The json round trip joins surrogate pairs json5 leaves split (UTF-8 can't write them).
+ data = json.loads(json.dumps(json5.loads(text)))
+ elif path.suffix == ".toml":
try:
import tomllib # novermin
except ImportError:
@@ -6256,7 +6267,6 @@ def _load_app_config(path: Path, text: Optional[str]) -> Optional[dict]:
import yaml
data = yaml.safe_load(text)
else:
- # OpenCode reads JSONC and OpenClaw JSON5, so accept comments and trailing commas in either.
text = _JSONC_COMMENT.sub(lambda m: m.group(1) or "", text)
data = json.loads(_JSONC_TRAILING_COMMA.sub(lambda m: m.group(1) or "", text))
if not isinstance(data, dict):
@@ -6264,9 +6274,14 @@ def _load_app_config(path: Path, text: Optional[str]) -> Optional[dict]:
return data
-def _parse_app_config(path: Path, text: Optional[str]) -> Optional[dict]:
+def _parse_app_config(
+ path: Path,
+ text: Optional[str],
+ *,
+ allow_json5: bool = False,
+) -> Optional[dict]:
try:
- return _load_app_config(path, text)
+ return _load_app_config(path, text, allow_json5 = allow_json5)
except Exception:
_fail(f"Couldn't parse {path}, so it was left as is. Fix it and re-run.")
@@ -6321,8 +6336,14 @@ def _splice_jsonc(text: str, keys: tuple, value) -> str:
return text[:last] + f"\n{indent}{member}\n" + " " * depth + text[close:]
-def _set_app_values(text: Optional[str], path: Path, updates: list) -> Optional[str]:
- config = _parse_app_config(path, text)
+def _set_app_values(
+ text: Optional[str],
+ path: Path,
+ updates: list,
+ *,
+ allow_json5: bool = False,
+) -> Optional[str]:
+ config = _parse_app_config(path, text, allow_json5 = allow_json5)
before = json.dumps(config, sort_keys = True)
for keys, value in updates:
if value is _APP_DELETE:
@@ -6346,13 +6367,13 @@ def _set_app_values(text: Optional[str], path: Path, updates: list) -> Optional[
parent[keys[-1]] = value
if json.dumps(config, sort_keys = True) == before:
return text
- if path.suffix != ".yaml":
+ if allow_json5 or path.suffix != ".yaml":
candidate = text
with contextlib.suppress(Exception):
if candidate and candidate.strip():
for keys, value in updates:
candidate = _splice_jsonc(candidate, keys, value)
- if _load_app_config(path, candidate) == config:
+ if _load_app_config(path, candidate, allow_json5 = allow_json5) == config:
return candidate
return json.dumps(config, indent = 2, ensure_ascii = False) + "\n"
import yaml
@@ -6459,6 +6480,8 @@ def _open_app_config(
if state.get("path") != str(target.path):
state = {}
text = _read_app_file(target.path)
+ if target.agent == "openclaw":
+ parse = functools.partial(_parse_app_config, allow_json5 = True)
parse(target.path, text)
key, key_id = _app_api_key(target, base, explicit_key, state)
return state_path, state, text, key, key_id
@@ -6505,7 +6528,10 @@ def _add_app_provider(
try:
state_path, state, text, key, key_id = _open_app_config(target, base, explicit_key)
new_text = _set_app_values(
- text, target.path, target.updates(text, target.path, base, key, entry)
+ text,
+ target.path,
+ target.updates(text, target.path, base, key, entry),
+ allow_json5 = target.agent == "openclaw",
)
new_state = {"path": str(target.path), "base": base, "key": key, "key_id": key_id}
_save_app_config(target, state_path, state, new_state, text, new_text)
@@ -6781,7 +6807,7 @@ def _openclaw_app_updates(
entry,
max_tokens = None,
) -> list:
- config = _parse_app_config(path, text) or {}
+ config = _parse_app_config(path, text, allow_json5 = True) or {}
agents = config.get("agents")
defaults = agents.get("defaults") if isinstance(agents, dict) else None
defaults = defaults if isinstance(defaults, dict) else {}
diff --git a/unsloth_cli/tests/test_start_app.py b/unsloth_cli/tests/test_start_app.py
index 104d8580d5e..b88235c9e99 100644
--- a/unsloth_cli/tests/test_start_app.py
+++ b/unsloth_cli/tests/test_start_app.py
@@ -557,6 +557,74 @@ def test_opencode_app_reenables_a_disabled_unsloth(studio, monkeypatch):
assert "unsloth-studio" in data["provider"]
+ "original",
+ [
+ "{ agents: { defaults: { workspace: '~/work' } }, marker: 'keep me' }",
+ "{ 'agents': { 'defaults': { 'workspace': '~/work' } }, 'marker': 'keep me' }",
+ "{ agents: { defaults: { workspace: '~/work' } }, marker: 'https://example.test/a//b' }",
+ "{ /* mine */ agents: { defaults: { workspace: '~/work', }, }, marker: '/* literal */', }",
+ ],
+)
+def test_openclaw_app_preserves_json5_values_and_original_backup(studio, original):
+ import json5
+
+ config = studio["home"] / ".openclaw" / "openclaw.json"
+ config.parent.mkdir()
+ config.write_text(original)
+ expected = json5.loads(original)
+
+ result = CliRunner().invoke(start.start_app, ["openclaw", "--app"])
+
+ assert result.exit_code == 0, result.output
+ data = json5.loads(config.read_text())
+ assert data["agents"] == expected["agents"]
+ assert data["marker"] == expected["marker"]
+ assert data["models"]["providers"]["unsloth"]["apiKey"] == APP_KEY
+ assert config.with_name("openclaw.json.unsloth-backup").read_text() == original
+ updated = config.read_text()
+ assert CliRunner().invoke(start.start_app, ["openclaw", "--app"]).exit_code == 0
+ assert config.read_text() == updated
+
+
+def test_openclaw_app_writes_an_escaped_surrogate_pair(studio):
+ config = studio["home"] / ".openclaw" / "openclaw.json"
+ config.parent.mkdir()
+ config.write_text("{ agents: { defaults: { workspace: '~/\\ud83d\\ude80' } } }")
+
+ result = CliRunner().invoke(start.start_app, ["openclaw", "--app"])
+
+ assert result.exit_code == 0, result.output
+ data = json.loads(config.read_text(encoding = "utf-8"))
+ assert data["agents"]["defaults"]["workspace"] == "~/\U0001f680"
+
+
[email protected]("name", ["custom.settings", "custom.yaml", "custom.toml"])
+def test_openclaw_json5_format_is_selected_by_agent(studio, tmp_path, name):
+ import json5
+
+ config = tmp_path / name
+ config.write_text("{ marker: 'keep', agents: { defaults: {} } }")
+ target = start._AppTarget("openclaw", "OpenClaw app", config, start._openclaw_app_updates)
+ start._add_app_provider(target, BASE, APP_KEY, MODEL)
+ data = json5.loads(config.read_text())
+ assert data["marker"] == "keep"
+ assert "unsloth" in data["models"]["providers"]
+
+
+def test_opencode_app_does_not_accept_json5_as_jsonc(studio, monkeypatch):
+ monkeypatch.delenv("XDG_CONFIG_HOME", raising = False)
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode", False))
+ config = studio["home"] / ".config/opencode/opencode.json"
+ config.parent.mkdir(parents = True)
+ original = "{ theme: 'dark' }"
+ config.write_text(original)
+ result = CliRunner().invoke(start.start_app, ["opencode", "--app"])
+ assert result.exit_code == 1
+ assert "Couldn't parse" in result.output
+ assert config.read_text() == original
+
+
def test_openclaw_app_reads_a_commented_config(studio):
config = studio["home"] / ".openclaw" / "openclaw.json"
config.parent.mkdir()
@@ -658,13 +726,14 @@ def test_hermes_app_adds_unsloth_to_the_active_profile(studio):
def test_app_refuses_a_config_it_cannot_parse(studio):
config = studio["home"] / ".openclaw" / "openclaw.json"
config.parent.mkdir()
- config.write_text("{ // json5 comment\n agents: {} }\n")
+ original = "{ // json5 comment\n agents: { broken } }\n"
+ config.write_text(original)
result = CliRunner().invoke(start.start_app, ["openclaw", "--app"])
assert result.exit_code == 1
assert "Couldn't parse" in result.output
- assert config.read_text() == "{ // json5 comment\n agents: {} }\n"
+ assert config.read_text() == original
assert studio["minted"] == 0