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(backends): preserve quoted keys and deep nesting in codex TOML emitter

cyh205f7ab162b1
diff --git a/tests/test_codex_config.py b/tests/test_codex_config.py
new file mode 100644
index 000000000..d00b55dd9
--- /dev/null
+++ b/tests/test_codex_config.py
@@ -0,0 +1,125 @@
+"""Regression tests for ``vibe/codex_config.py`` TOML round-tripping.
+
+The Codex CLI's ``config.toml`` carries arbitrary user-owned blocks
+(``[projects."/abs/path"]`` scopes, deeply nested settings, arrays of
+tables). When we save Codex auth state we must preserve those unrelated
+sections rather than silently dropping them. These tests pin the
+round-trip behavior of the emitter.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+try:
+ import tomllib
+except ModuleNotFoundError: # pragma: no cover - py<3.11
+ import tomli as tomllib # type: ignore[no-redef]
+
+from vibe import codex_config
+
+
+def _round_trip(data: dict) -> dict:
+ return tomllib.loads(codex_config._dump_toml(data))
+
+
+def test_round_trip_quoted_keys() -> None:
+ """Keys outside the bare-key character class must be emitted quoted."""
+ data = {
+ "model_provider": "openai",
+ "projects": {
+ "/Users/alex/code/vibe-remote": {"trust_level": "trusted"},
+ "/tmp/another path": {"trust_level": "ask"},
+ },
+ }
+ rendered = codex_config._dump_toml(data)
+ assert '"/Users/alex/code/vibe-remote"' in rendered
+ assert '"/tmp/another path"' in rendered
+ assert _round_trip(data) == data
+
+
+def test_round_trip_deep_nesting() -> None:
+ """Nesting deeper than two levels must survive the rewrite."""
+ data = {
+ "a": {"b": {"c": {"x": 1, "y": "hello", "z": True}}},
+ "top_level": "kept",
+ }
+ assert _round_trip(data) == data
+
+
+def test_round_trip_arrays_of_tables() -> None:
+ """``[[plugin]]`` array-of-tables entries must round-trip intact."""
+ data = {
+ "plugin": [
+ {"name": "first", "enabled": True},
+ {"name": "second", "settings": {"timeout": 30}},
+ ],
+ }
+ assert _round_trip(data) == data
+
+
+def test_apply_api_key_mode_preserves_unrelated_blocks(tmp_path: Path) -> None:
+ """Switching to api_key mode must not drop user-owned config blocks."""
+ home = tmp_path
+ codex_home = home / ".codex"
+ codex_home.mkdir()
+ seed = (
+ 'model = "gpt-5"\n'
+ "\n"
+ '[projects."/Users/alex/code/vibe-remote"]\n'
+ 'trust_level = "trusted"\n'
+ "\n"
+ "[a.b.c]\n"
+ "x = 1\n"
+ )
+ (codex_home / "config.toml").write_text(seed, encoding="utf-8")
+
+ codex_config.apply_codex_auth(
+ auth_mode="api_key",
+ api_key="sk-test-1234567890",
+ base_url="https://api.example.com/v1",
+ home=home,
+ )
+
+ parsed = tomllib.loads((codex_home / "config.toml").read_text(encoding="utf-8"))
+ assert parsed["model"] == "gpt-5"
+ assert parsed["model_provider"] == codex_config.MANAGED_PROVIDER_ID
+ assert parsed["model_providers"]["openai"]["base_url"] == "https://api.example.com/v1"
+ assert parsed["projects"]["/Users/alex/code/vibe-remote"]["trust_level"] == "trusted"
+ assert parsed["a"]["b"]["c"]["x"] == 1
+
+ auth = json.loads((codex_home / "auth.json").read_text(encoding="utf-8"))
+ assert auth["OPENAI_API_KEY"] == "sk-test-1234567890"
+
+
+def test_apply_oauth_mode_clears_managed_base_url(tmp_path: Path) -> None:
+ """Switching back to oauth strips the managed base_url and api_key."""
+ home = tmp_path
+ codex_home = home / ".codex"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(
+ json.dumps({"OPENAI_API_KEY": "sk-old", "tokens": {"id_token": "abc"}}),
+ encoding="utf-8",
+ )
+ (codex_home / "config.toml").write_text(
+ '[model_providers.openai]\nbase_url = "https://api.example.com/v1"\n',
+ encoding="utf-8",
+ )
+
+ codex_config.apply_codex_auth(
+ auth_mode="oauth",
+ api_key=None,
+ base_url=None,
+ home=home,
+ )
+
+ auth = json.loads((codex_home / "auth.json").read_text(encoding="utf-8"))
+ assert "OPENAI_API_KEY" not in auth
+ assert auth["tokens"] == {"id_token": "abc"}
+
+ parsed = tomllib.loads((codex_home / "config.toml").read_text(encoding="utf-8"))
+ assert "model_providers" not in parsed
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
index f01c6a4ab..ab72d2797 100644
--- a/vibe/codex_config.py
+++ b/vibe/codex_config.py
@@ -19,11 +19,18 @@ from __future__ import annotations
import json
import logging
import os
+import re
from pathlib import Path
-from typing import Any, Dict, Optional
+from typing import Any, Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
+# A TOML "bare key" is the unquoted form — anything outside this character
+# set must be emitted as a quoted key. Codex specifically uses quoted keys
+# under ``[projects."/absolute/path"]`` to scope per-directory settings,
+# so the emitter has to round-trip those correctly.
+_BARE_KEY_RE = re.compile(r"^[A-Za-z0-9_-]+$")
+
# Provider id we manage in ``[model_providers.<id>]``. Codex ships with a
# built-in ``openai`` provider; if the user has hand-edited that block we
# leave their fields alone except for ``base_url`` when one is supplied.
@@ -66,6 +73,32 @@ def _load_auth(path: Path) -> Dict[str, Any]:
return {}
+def _format_toml_key(key: str) -> str:
+ """Quote a TOML key when it falls outside the bare-key character class.
+
+ Plain identifier keys like ``model_provider`` round-trip as-is; keys
+ that contain dots, slashes, or other characters (most notably the
+ absolute paths Codex uses under ``[projects.<...>]``) must be emitted
+ as quoted strings so the resulting TOML stays parseable.
+ """
+ if _BARE_KEY_RE.match(key):
+ return key
+ return '"' + key.replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def _format_toml_header(path: Tuple[str, ...]) -> str:
+ return "[" + ".".join(_format_toml_key(part) for part in path) + "]"
+
+
+def _format_toml_array_header(path: Tuple[str, ...]) -> str:
+ return "[[" + ".".join(_format_toml_key(part) for part in path) + "]]"
+
+
+def _is_table_array(value: Any) -> bool:
+ """A non-empty list whose items are all dicts is a TOML array-of-tables."""
+ return isinstance(value, list) and bool(value) and all(isinstance(item, dict) for item in value)
+
+
def _dump_toml_value(value: Any) -> str:
"""Serialize a single scalar value back to TOML. Tables handled separately."""
if isinstance(value, bool):
@@ -82,48 +115,79 @@ def _dump_toml_value(value: Any) -> str:
return _dump_toml_value(json.dumps(value))
-def _dump_toml(data: Dict[str, Any]) -> str:
- """Minimal TOML emitter for the Codex config shape we manage.
+def _dump_toml_table(data: Dict[str, Any], path: Tuple[str, ...], lines: List[str]) -> None:
+ """Render *data* as a TOML table rooted at *path*, recursing into subtables.
+
+ The split between scalars / subtables / array-of-tables mirrors what
+ ``tomllib`` parses, so the rewrite is loss-less for arbitrary
+ Codex-shaped configs:
- Handles top-level scalars and one level of nested tables
- (``[a.b]``). Comments and original ordering are lost — acceptable
- here because the file is typically generated by ``codex login`` and
- re-rendered round-trip with our managed fields.
+ - scalar leaves under this path are emitted first, under the
+ ``[path]`` header (or at the top of the file when ``path`` is empty);
+ - dict children become standalone ``[path.subkey]`` tables, recursed
+ into so deeper nesting like ``[a.b.c]`` round-trips;
+ - lists of dicts become ``[[path.subkey]]`` array-of-tables entries.
"""
- lines: list[str] = []
- nested: list[tuple[str, Dict[str, Any]]] = []
+ scalars: List[Tuple[str, Any]] = []
+ subtables: List[Tuple[str, Dict[str, Any]]] = []
+ table_arrays: List[Tuple[str, List[Dict[str, Any]]]] = []
for key, value in data.items():
if isinstance(value, dict):
- nested.append((key, value))
- continue
- lines.append(f"{key} = {_dump_toml_value(value)}")
- for parent, subtree in nested:
- # ``subtree`` may itself be either scalars (one ``[parent]`` table)
- # or a dict of named subtables (``[parent.child]``).
- scalar_children: list[tuple[str, Any]] = []
- table_children: list[tuple[str, Dict[str, Any]]] = []
- for child_key, child_value in subtree.items():
- if isinstance(child_value, dict):
- table_children.append((child_key, child_value))
- else:
- scalar_children.append((child_key, child_value))
- if scalar_children:
- lines.append("")
- lines.append(f"[{parent}]")
- for child_key, child_value in scalar_children:
- lines.append(f"{child_key} = {_dump_toml_value(child_value)}")
- for child_key, grandchildren in table_children:
- lines.append("")
- lines.append(f"[{parent}.{child_key}]")
- for grand_key, grand_value in grandchildren.items():
- if isinstance(grand_value, dict):
- # Codex doesn't currently nest deeper than two levels in
- # the surface we manage; punt on deeper nesting.
- logger.debug(
- "Skipping deeply-nested TOML entry %s.%s.%s", parent, child_key, grand_key
- )
- continue
- lines.append(f"{grand_key} = {_dump_toml_value(grand_value)}")
+ subtables.append((key, value))
+ elif _is_table_array(value):
+ table_arrays.append((key, value))
+ else:
+ scalars.append((key, value))
+
+ if path:
+ # Emit ``[path]`` when this table has its own scalars, or when it
+ # is otherwise empty (no children) — without the header, an empty
+ # leaf disappears entirely from the round-trip. Pure container
+ # tables (no scalars, but with subtables) are implicit in TOML:
+ # ``[a.b]`` is enough to introduce ``a``.
+ if scalars or (not subtables and not table_arrays):
+ if lines:
+ lines.append("")
+ lines.append(_format_toml_header(path))
+ for key, value in scalars:
+ lines.append(f"{_format_toml_key(key)} = {_dump_toml_value(value)}")
+ else:
+ for key, value in scalars:
+ lines.append(f"{_format_toml_key(key)} = {_dump_toml_value(value)}")
+
+ for key, value in subtables:
+ _dump_toml_table(value, path + (key,), lines)
+
+ for key, items in table_arrays:
+ sub_path = path + (key,)
+ for item in items:
+ if lines:
+ lines.append("")
+ lines.append(_format_toml_array_header(sub_path))
+ item_scalars: List[Tuple[str, Any]] = []
+ item_subtables: List[Tuple[str, Dict[str, Any]]] = []
+ for ik, iv in item.items():
+ if isinstance(iv, dict):
+ item_subtables.append((ik, iv))
+ else:
+ item_scalars.append((ik, iv))
+ for ik, iv in item_scalars:
+ lines.append(f"{_format_toml_key(ik)} = {_dump_toml_value(iv)}")
+ for ik, iv in item_subtables:
+ _dump_toml_table(iv, sub_path + (ik,), lines)
+
+
+def _dump_toml(data: Dict[str, Any]) -> str:
+ """Emit *data* as TOML.
+
+ Comments and original key ordering are lost (Python dicts preserve
+ insertion order, so the rewrite is stable round-trip for a single
+ parse → mutate → re-emit cycle). Everything else — quoted keys,
+ arbitrary nesting depth, arrays of tables — is preserved so saving
+ Codex auth never silently drops unrelated config blocks.
+ """
+ lines: List[str] = []
+ _dump_toml_table(data, (), lines)
return "\n".join(lines) + ("\n" if lines else "")