feat: support ${VAR} env var interpolation in config secrets

Allow config.json to reference environment variables via ${VAR_NAME}
syntax. Variables are resolved at runtime by resolve_config_env_vars(),
keeping the raw templates in the Pydantic model so save_config()
preserves them. This lets secrets live in a separate env file
(e.g. loaded by systemd EnvironmentFile=) instead of plain text
in config.json.
This commit is contained in:
Ben Lenarts
2026-04-06 13:43:26 +08:00
committed by Xubin Ren
parent 7ffd93f48d
commit 202938ae73
6 changed files with 161 additions and 4 deletions
+6 -2
View File
@@ -453,7 +453,7 @@ def _make_provider(config: Config):
def _load_runtime_config(config: str | None = None, workspace: str | None = None) -> Config:
"""Load config and optionally override the active workspace."""
from nanobot.config.loader import load_config, set_config_path
from nanobot.config.loader import load_config, resolve_config_env_vars, set_config_path
config_path = None
if config:
@@ -464,7 +464,11 @@ def _load_runtime_config(config: str | None = None, workspace: str | None = None
set_config_path(config_path)
console.print(f"[dim]Using config: {config_path}[/dim]")
loaded = load_config(config_path)
try:
loaded = resolve_config_env_vars(load_config(config_path))
except ValueError as e:
console.print(f"[red]Error: {e}[/red]")
raise typer.Exit(1)
_warn_deprecated_config_keys(config_path)
if workspace:
loaded.agents.defaults.workspace = workspace
+34
View File
@@ -1,6 +1,8 @@
"""Configuration loading utilities."""
import json
import os
import re
from pathlib import Path
import pydantic
@@ -76,6 +78,38 @@ def save_config(config: Config, config_path: Path | None = None) -> None:
json.dump(data, f, indent=2, ensure_ascii=False)
def resolve_config_env_vars(config: Config) -> Config:
"""Return a copy of *config* with ``${VAR}`` env-var references resolved.
Only string values are affected; other types pass through unchanged.
Raises :class:`ValueError` if a referenced variable is not set.
"""
data = config.model_dump(mode="json", by_alias=True)
data = _resolve_env_vars(data)
return Config.model_validate(data)
def _resolve_env_vars(obj: object) -> object:
"""Recursively resolve ``${VAR}`` patterns in string values."""
if isinstance(obj, str):
return re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}", _env_replace, obj)
if isinstance(obj, dict):
return {k: _resolve_env_vars(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_resolve_env_vars(v) for v in obj]
return obj
def _env_replace(match: re.Match[str]) -> str:
name = match.group(1)
value = os.environ.get(name)
if value is None:
raise ValueError(
f"Environment variable '{name}' referenced in config is not set"
)
return value
def _migrate_config(data: dict) -> dict:
"""Migrate old config formats to current."""
# Move tools.exec.restrictToWorkspace → tools.restrictToWorkspace
+2 -2
View File
@@ -47,7 +47,7 @@ class Nanobot:
``~/.nanobot/config.json``.
workspace: Override the workspace directory from config.
"""
from nanobot.config.loader import load_config
from nanobot.config.loader import load_config, resolve_config_env_vars
from nanobot.config.schema import Config
resolved: Path | None = None
@@ -56,7 +56,7 @@ class Nanobot:
if not resolved.exists():
raise FileNotFoundError(f"Config not found: {resolved}")
config: Config = load_config(resolved)
config: Config = resolve_config_env_vars(load_config(resolved))
if workspace is not None:
config.agents.defaults.workspace = str(
Path(workspace).expanduser().resolve()