Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(config): add atomic agent.json channel-section writer

shadowinlife0ed47b589e7b
diff --git a/agent/src/channels/feishu.py b/agent/src/channels/feishu.py
index 0ad594f83..0f9f7bf31 100644
--- a/agent/src/channels/feishu.py
+++ b/agent/src/channels/feishu.py
@@ -7,7 +7,6 @@ import importlib.util
import json
import os
import re
-import tempfile
import threading
import time
import uuid
@@ -49,67 +48,27 @@ def _persist_login_credentials(
The QR flow creates a bot application and returns its secret only once, so
reporting a successful login without durably storing that secret leaves the
- channel unusable after the CLI process exits. Write through a private
- same-directory temporary file and atomically replace the config so readers
- never observe a partial credential record.
+ channel unusable after the CLI process exits. Credential persistence is
+ delegated to :func:`src.config.writer.update_channel_section`, which merges
+ into the raw JSON dict and atomically replaces the config so readers never
+ observe a partial credential record. The ``ValueError`` contract is kept
+ for callers that already handle a non-JSON config.
"""
- from src.config.loader import _read_config_file
- from src.config.paths import get_config_path
-
- path = config_path or get_config_path()
- if path.suffix.lower() != ".json":
- raise ValueError(
- "Feishu QR login requires a JSON agent config; use "
- "~/.vibe-trading/agent.json"
- )
-
- payload: dict[str, Any] = {}
- if path.exists():
- payload = _read_config_file(path)
- channels = payload.setdefault("channels", {})
- if not isinstance(channels, dict):
- raise ValueError("agent config 'channels' must be an object")
- section = channels.setdefault("feishu", {})
- if not isinstance(section, dict):
- raise ValueError("agent config 'channels.feishu' must be an object")
- section.update(
- {
- "enabled": True,
- "app_id": app_id,
- "app_secret": app_secret,
- "domain": domain,
- }
- )
+ from src.config.writer import ConfigNotWritableError, update_channel_section
- path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
- content = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
- fd, temporary = tempfile.mkstemp(
- dir=path.parent,
- prefix=f".{path.name}.",
- suffix=".tmp",
- )
try:
- try:
- with os.fdopen(fd, "wb") as handle:
- fd = -1
- handle.write(content)
- handle.flush()
- if hasattr(os, "fchmod"):
- os.fchmod(handle.fileno(), 0o600)
- os.fsync(handle.fileno())
- finally:
- if fd >= 0:
- os.close(fd)
- os.replace(temporary, path)
- except BaseException:
- with suppress(OSError):
- os.unlink(temporary)
- raise
- try:
- os.chmod(path, 0o600)
- except OSError:
- pass
- return path
+ return update_channel_section(
+ "feishu",
+ {
+ "enabled": True,
+ "app_id": app_id,
+ "app_secret": app_secret,
+ "domain": domain,
+ },
+ config_path=config_path,
+ )
+ except ConfigNotWritableError as exc:
+ raise ValueError(str(exc)) from exc
def _load_lark_runtime() -> tuple[Any, str, str]:
diff --git a/agent/src/config/writer.py b/agent/src/config/writer.py
new file mode 100644
index 000000000..34107842c
--- /dev/null
+++ b/agent/src/config/writer.py
@@ -0,0 +1,143 @@
+"""Atomic writer for the ``channels`` section of the raw agent JSON config.
+
+The web configuration surface and the Feishu QR-login flow both need to persist
+channel credentials into the operator's structured config without round-tripping
+unrelated sections through a pydantic model. This module owns that single
+responsibility: merge a channel section into the raw JSON dict and replace the
+file atomically so a reader never observes a partial record.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+from contextlib import suppress
+from pathlib import Path
+from typing import Any, Sequence
+
+from src.config.loader import _read_config_file
+from src.config.paths import get_config_path
+
+
+class ConfigNotWritableError(RuntimeError):
+ """Raised when the active agent config cannot be written as JSON."""
+
+
+def _resolve_config_path(config_path: Path | None) -> Path:
+ """Resolve the config file to update.
+
+ Args:
+ config_path: Explicit config path, or ``None`` to use discovery.
+
+ Returns:
+ The explicit path when one is provided, otherwise the active config
+ path from :func:`src.config.paths.get_config_path`. When no config
+ file exists yet, discovery yields the default ``agent.json`` under the
+ runtime root so the caller can create it.
+ """
+ if config_path is not None:
+ return config_path
+ return get_config_path()
+
+
+def update_channel_section(
+ channel: str,
+ updates: dict[str, Any],
+ *,
+ clears: Sequence[str] = (),
+ config_path: Path | None = None,
+) -> Path:
+ """Merge a channel section into the raw JSON agent config.
+
+ Operates on the raw decoded dict only: unknown top-level keys, sibling
+ channel sections, and key order/casing are preserved exactly. The file is
+ written through a private same-directory temporary file and atomically
+ replaced, so readers never observe a partial credential record.
+
+ Args:
+ channel: Channel section name, e.g. ``"feishu"``.
+ updates: Keys to merge into ``channels.<channel>``.
+ clears: Keys to remove from ``channels.<channel>`` if present; absent
+ keys are ignored.
+ config_path: Explicit config path. When omitted, the active config
+ path is resolved via :func:`src.config.paths.get_config_path`.
+
+ Returns:
+ The config file path that was written.
+
+ Raises:
+ ConfigNotWritableError: If the resolved config file is not JSON, cannot
+ be read, or holds a non-object ``channels``/``channels.<channel>``
+ section.
+ """
+ path = _resolve_config_path(config_path)
+ if path.suffix.lower() != ".json":
+ raise ConfigNotWritableError(
+ "Agent config is not writable as JSON: "
+ f"expected a .json file, got {path}. "
+ "Point the runtime at ~/.vibe-trading/agent.json to persist "
+ "channel credentials."
+ )
+
+ payload: dict[str, Any] = {}
+ if path.exists():
+ try:
+ payload = _read_config_file(path)
+ except (OSError, ValueError) as exc:
+ raise ConfigNotWritableError(
+ f"Agent config at {path} could not be read for update: {exc}"
+ ) from exc
+
+ channels = payload.setdefault("channels", {})
+ if not isinstance(channels, dict):
+ raise ConfigNotWritableError("agent config 'channels' must be an object")
+ section = channels.setdefault(channel, {})
+ if not isinstance(section, dict):
+ raise ConfigNotWritableError(
+ f"agent config 'channels.{channel}' must be an object"
+ )
+
+ section.update(updates)
+ for key in clears:
+ section.pop(key, None)
+
+ _write_json_atomically(path, payload)
+ return path
+
+
+def _write_json_atomically(path: Path, payload: dict[str, Any]) -> None:
+ """Write ``payload`` as pretty JSON via a private temp file + replace.
+
+ Args:
+ path: Destination config file.
+ payload: Raw config dict to serialize.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ content = (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
+ fd, temporary = tempfile.mkstemp(
+ dir=path.parent,
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ )
+ try:
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ fd = -1
+ handle.write(content)
+ handle.flush()
+ if hasattr(os, "fchmod"):
+ os.fchmod(handle.fileno(), 0o600)
+ os.fsync(handle.fileno())
+ finally:
+ if fd >= 0:
+ os.close(fd)
+ os.replace(temporary, path)
+ except BaseException:
+ with suppress(OSError):
+ os.unlink(temporary)
+ raise
+ try:
+ os.chmod(path, 0o600)
+ except OSError:
+ pass
diff --git a/agent/tests/test_config_writer.py b/agent/tests/test_config_writer.py
new file mode 100644
index 000000000..fd7565cc5
--- /dev/null
+++ b/agent/tests/test_config_writer.py
@@ -0,0 +1,128 @@
+from __future__ import annotations
+
+import json
+import os
+import stat
+from pathlib import Path
+
+import pytest
+
+from src.config.writer import ConfigNotWritableError, update_channel_section
+
+
+def _read(path: Path) -> dict:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_update_channel_section_preserves_unrelated_and_sibling_keys(tmp_path):
+ config_path = tmp_path / "agent.json"
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {"example": {"command": "example"}},
+ "customTopLevel": {"keep": [1, 2, 3]},
+ "channels": {
+ "replyTimeoutS": 1800,
+ "feishu": {"group_policy": "mention"},
+ "telegram": {"enabled": False},
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ saved = update_channel_section(
+ "feishu",
+ {"enabled": True, "app_id": "cli_app"},
+ config_path=config_path,
+ )
+
+ assert saved == config_path
+ payload = _read(saved)
+ assert payload["mcpServers"]["example"]["command"] == "example"
+ assert payload["customTopLevel"] == {"keep": [1, 2, 3]}
+ assert payload["channels"]["replyTimeoutS"] == 1800
+ assert payload["channels"]["telegram"] == {"enabled": False}
+ assert payload["channels"]["feishu"] == {
+ "group_policy": "mention",
+ "enabled": True,
+ "app_id": "cli_app",
+ }
+
+
+def test_update_channel_section_creates_file_and_parent_dirs(tmp_path):
+ config_path = tmp_path / "nested" / "deep" / "agent.json"
+ assert not config_path.exists()
+
+ saved = update_channel_section("slack", {"enabled": True}, config_path=config_path)
+
+ assert saved == config_path
+ assert config_path.exists()
+ assert _read(saved)["channels"]["slack"] == {"enabled": True}
+
+
+def test_update_channel_section_rejects_non_json_config(tmp_path):
+ config_path = tmp_path / "agent.yaml"
+ config_path.write_text("channels: {}\n", encoding="utf-8")
+
+ with pytest.raises(ConfigNotWritableError):
+ update_channel_section("feishu", {"enabled": True}, config_path=config_path)
+
+ missing = tmp_path / "agent.yml"
+ with pytest.raises(ConfigNotWritableError):
+ update_channel_section("feishu", {"enabled": True}, config_path=missing)
+
+
+def test_update_channel_section_clears_listed_keys(tmp_path):
+ config_path = tmp_path / "agent.json"
+ config_path.write_text(
+ json.dumps(
+ {
+ "channels": {
+ "feishu": {
+ "app_secret": "old-secret",
+ "app_id": "old-app",
+ "enabled": False,
+ }
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ update_channel_section(
+ "feishu",
+ {"enabled": True},
+ clears=("app_secret", "not_present"),
+ config_path=config_path,
+ )
+
+ section = _read(config_path)["channels"]["feishu"]
+ assert "app_secret" not in section
+ assert "not_present" not in section
+ assert section["app_id"] == "old-app"
+ assert section["enabled"] is True
+
+
[email protected](os.name != "posix", reason="POSIX file-mode semantics")
+def test_update_channel_section_writes_owner_only_file(tmp_path):
+ config_path = tmp_path / "agent.json"
+
+ update_channel_section("feishu", {"enabled": True}, config_path=config_path)
+
+ assert stat.S_IMODE(config_path.stat().st_mode) == 0o600
+
+
+def test_update_channel_section_sequential_writes_accumulate(tmp_path):
+ config_path = tmp_path / "agent.json"
+
+ update_channel_section(
+ "feishu", {"enabled": True, "app_id": "cli_app"}, config_path=config_path
+ )
+ update_channel_section(
+ "telegram", {"enabled": True, "token": "t"}, config_path=config_path
+ )
+
+ payload = _read(config_path)
+ assert payload["channels"]["feishu"] == {"enabled": True, "app_id": "cli_app"}
+ assert payload["channels"]["telegram"] == {"enabled": True, "token": "t"}