8414c59557
Five rounds of sweep across the tree. Net ~544 lines removed. Removed: - Section-divider banners and one-line section labels (# Display utilities, # ----- list_requests -----, # CVSS breakdown, etc.). - Module-level prose docstrings on internal modules. Kept one-line summaries; trimmed multi-paragraph narration about SDK/Strix responsibility splits, cache strategies, three-source precedence. - Internal-helper docstrings that just restate the function name — caido_api helpers (caido_url, get_client, view_request, etc.), settings-class one-liners (LLMSettings, RuntimeSettings, ...), UI helper docstrings. - Args/Returns blocks on non-LLM-facing internal helpers (build_strix_agent, render_system_prompt, create_or_reuse, bootstrap_caido) — kept only the genuinely non-obvious params. - Internal-history phrasing — "Mirrors main-branch shape", "pre-SDK harness", "previous lookup matched no attribute". - Narrative comments inside function bodies that explained what the next line does, design rationale obvious from the surrounding code, or "we used to..." asides. - Trailing periods on every error-string literal across the tool tree. - Duplicated roundtripTime quirk comment (kept the LLM-facing copy in tools/proxy/tools.py). Kept (every one names an upstream bug, vendored-code provenance, or non-obvious data quirk): - core/runner.py: SDK replay-with-empty-initial-input + on_agent_end lifecycle gap. - runtime/docker_client.py: VERBATIM COPY block of the upstream _create_container body, pinned to SDK v0.14.6. - runtime/session_manager.py: NO_PROXY for agent-browser CDP loopback. - tools/proxy/caido_api.py: generated-pydantic Request.raw quirk, replay double-history pitfall. - tools/proxy/tools.py: Caido roundtripTime=0 quirk for proxy captures. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
127 lines
4.0 KiB
Python
127 lines
4.0 KiB
Python
"""Settings loader, override switch, and disk persistence."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import json
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
from pydantic import AliasChoices, BaseModel
|
|
|
|
from strix.config.settings import Settings
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
from pydantic.fields import FieldInfo
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
_DEFAULT_PATH: Path = Path.home() / ".strix" / "cli-config.json"
|
|
_override: Path | None = None
|
|
_cached: Settings | None = None
|
|
|
|
|
|
def load_settings() -> Settings:
|
|
"""Resolve settings from env + JSON file + defaults. Memoized.
|
|
|
|
Precedence: env vars win, then the JSON file, then field defaults.
|
|
"""
|
|
global _cached # noqa: PLW0603
|
|
if _cached is None:
|
|
source_path = _override or _DEFAULT_PATH
|
|
init_kwargs: dict[str, Any] = _read_json_overrides(source_path)
|
|
_cached = Settings(**init_kwargs)
|
|
logger.debug(
|
|
"load_settings: resolved (override=%s, file_used=%s, json_keys=%d)",
|
|
_override is not None,
|
|
source_path.exists(),
|
|
sum(len(v) for v in init_kwargs.values()),
|
|
)
|
|
return _cached
|
|
|
|
|
|
def apply_config_override(path: Path) -> None:
|
|
"""Switch the JSON source to ``path`` and invalidate the cache."""
|
|
global _override, _cached # noqa: PLW0603
|
|
_override = path
|
|
_cached = None
|
|
logger.info("config override applied: %s", path)
|
|
|
|
|
|
def persist_current() -> None:
|
|
"""Write currently-set env vars to the active config file (0o600)."""
|
|
s = load_settings()
|
|
target = _override or _DEFAULT_PATH
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
env_block: dict[str, str] = {}
|
|
for sub_name in s.model_fields:
|
|
sub_model = getattr(s, sub_name)
|
|
if not isinstance(sub_model, BaseModel):
|
|
continue
|
|
for finfo in type(sub_model).model_fields.values():
|
|
for alias in _aliases_for(finfo):
|
|
value = os.environ.get(alias.upper())
|
|
if value:
|
|
env_block[alias.upper()] = value
|
|
break
|
|
|
|
target.write_text(json.dumps({"env": env_block}, indent=2), encoding="utf-8")
|
|
with contextlib.suppress(OSError):
|
|
target.chmod(0o600)
|
|
|
|
|
|
def _aliases_for(finfo: FieldInfo) -> list[str]:
|
|
"""Collect every env-var name that should populate ``finfo``."""
|
|
aliases: list[str] = []
|
|
if finfo.alias:
|
|
aliases.append(finfo.alias)
|
|
va = finfo.validation_alias
|
|
if isinstance(va, AliasChoices):
|
|
aliases.extend(c for c in va.choices if isinstance(c, str))
|
|
elif isinstance(va, str):
|
|
aliases.append(va)
|
|
return aliases
|
|
|
|
|
|
def _read_json_overrides(path: Path) -> dict[str, dict[str, Any]]:
|
|
"""Read ``{"env": {...}}`` from ``path`` and remap to nested kwargs.
|
|
|
|
Only includes keys whose env var is NOT already set, so env always
|
|
wins over the persisted file.
|
|
"""
|
|
if not path.exists():
|
|
return {}
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
except (json.JSONDecodeError, OSError):
|
|
return {}
|
|
env_block = data.get("env", {}) if isinstance(data, dict) else {}
|
|
if not isinstance(env_block, dict):
|
|
return {}
|
|
|
|
env_block_upper = {str(k).upper(): v for k, v in env_block.items()}
|
|
|
|
nested: dict[str, dict[str, Any]] = {}
|
|
for sub_name, sub_finfo in Settings.model_fields.items():
|
|
sub_cls = sub_finfo.annotation
|
|
if not (isinstance(sub_cls, type) and issubclass(sub_cls, BaseModel)):
|
|
continue
|
|
sub_data: dict[str, Any] = {}
|
|
for fname, finfo in sub_cls.model_fields.items():
|
|
for alias in _aliases_for(finfo):
|
|
key = alias.upper()
|
|
if key in os.environ:
|
|
break # env wins; skip JSON for this field
|
|
if key in env_block_upper:
|
|
sub_data[fname] = env_block_upper[key]
|
|
break
|
|
if sub_data:
|
|
nested[sub_name] = sub_data
|
|
return nested
|