ReMe/reme/daemon/storage.py
jinliyl ae55e2e570
Some checks are pending
CI / Python packages / Build and verify distributions (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python tests / Hermes embedded - ubuntu-latest (push) Waiting to run
CI / Python tests / Hermes embedded - windows-latest (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / ReMe Studio / Studio checks (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
Deploy / Documentation / Build documentation (push) Waiting to run
Deploy / Documentation / deploy (push) Blocked by required conditions
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
feat!: split proactive runtimes and add Studio backend management (#776)
* refactor(proactive)!: separate runtime ownership and unify delivery

* refactor(proactive): finish runtime and Studio migration

* test(proactive): make scheduled skip coverage deterministic

* refactor(studio): unify navigation and notebook resource loading

* feat(studio): edit workspace documents and update proactive task names

* refactor(studio): simplify task settings and navigation

* feat(studio): secure and supervise backend settings

* feat(studio): unify workbench timelines and refine desktop updates

Use shared timeline panes for notebook, memory, and resources. Add Todo creation ordering, persist companion visibility, and align desktop update handling and release artifacts.

Recheck editor file versions at read and publication boundaries. Retry reminder detail requests from the resource view.

* fix(studio): support unsigned GitHub preview releases

* fix: verify container state and isolate proactive view errors

Mount private supervisor state in Docker smoke tests and verify token and settings persistence. Exercise Studio startup with a loopback-only model fixture, and exclude packaged desktop output from Docker contexts.

Keep Remy subscriptions and healthy tasks available when an individual task has an invalid workspace path or session history.

* fix(home): align candidate Docker context exclusions

* chore(deps): update openai-codex dependency to v0.172.0

- Bump openai-codex from version 0.169.0 to 0.172.0 in pyproject.toml
- Keep other dependencies unchanged
- Ensure compatibility with latest openai-codex features and fixes

* fix(daemon): discover parent dotenv and isolate listeners

Restore parent-directory environment discovery in workers while retaining system precedence. Partition the default supervisor profile and lock by the configured bind address and port.
2026-11-25 21:33:16 +08:00

132 lines
4.9 KiB
Python

"""Atomic instance settings with credentials encrypted at rest."""
import json
import os
import sys
from pathlib import Path
from typing import Literal
from uuid import uuid4
from cryptography.fernet import Fernet, InvalidToken
from pydantic import BaseModel, Field
from .config import Profile, SECRET_FIELDS, Settings
class StoredProfile(BaseModel):
"""Validate the envelope before looking up or decrypting its credentials."""
revision: int = Field(ge=0)
key_id: str | None
settings: dict
class OperationRecord(BaseModel):
"""One operation in the persisted history."""
id: str
phase: Literal["accepted", "restarting", "succeeded", "failed"]
error: str | None
class OperationHistory(BaseModel):
"""Validate the operation log independently of the active profile."""
operations: dict[str, OperationRecord]
def write_private(path: Path, content: str) -> None:
"""Publish a private file atomically after flushing its contents."""
temporary = path.with_name(path.name + ".tmp")
descriptor = os.open(temporary, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o600)
try:
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
os.chmod(temporary, 0o600)
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
temporary.replace(path)
finally:
temporary.unlink(missing_ok=True)
class SettingsStore:
"""Keep ordinary values readable and encrypt API keys with a separate master key."""
def __init__(self, directory: Path):
self.path = directory / "settings.json"
self.key_id: str | None = None
self._cipher: Fernet | None = None
def _fernet(self, create: bool) -> Fernet:
if self._cipher is not None:
return self._cipher
key = os.getenv("REME_ENCRYPTION_KEY")
if not key:
try:
if sys.platform == "darwin":
from keyring.backends.macOS import Keyring
backend = Keyring()
elif sys.platform == "win32":
from keyring.backends.Windows import WinVaultKeyring
backend = WinVaultKeyring()
else:
from keyring.backends.SecretService import Keyring
backend = Keyring()
if self.key_id is None:
self.key_id = uuid4().hex
key = backend.get_password("ReMe", self.key_id)
if not key and create:
key = Fernet.generate_key().decode("ascii")
backend.set_password("ReMe", self.key_id, key)
except Exception as error: # pylint: disable=broad-except
raise ValueError(
"Cannot access the system credential store. Server deployments can set REME_ENCRYPTION_KEY.",
) from error
if not key:
raise ValueError("The saved settings encryption key is unavailable")
try:
self._cipher = Fernet(key.encode("ascii"))
except (ValueError, UnicodeError) as error:
raise ValueError("REME_ENCRYPTION_KEY must be a Fernet key") from error
return self._cipher
def load(self) -> Profile | None:
"""Read one committed generation without exposing decrypted keys in errors."""
if not self.path.exists():
return None
try:
payload = StoredProfile.model_validate_json(self.path.read_text(encoding="utf-8"))
self.key_id = payload.key_id
values = payload.settings
for field in SECRET_FIELDS:
encrypted = values.get(field)
if encrypted is not None and not isinstance(encrypted, str):
raise ValueError("Invalid encrypted credential")
if encrypted:
values[field] = self._fernet(create=False).decrypt(encrypted.encode("ascii")).decode("utf-8")
return Profile(revision=payload.revision, settings=Settings.model_validate(values))
except (OSError, ValueError, InvalidToken) as error:
raise ValueError("Cannot read saved settings. Restore settings.json and its encryption key.") from error
def prepare(self, profile: Profile) -> str:
"""Encrypt a candidate before stopping the running worker."""
values = profile.settings.private_values()
for field in SECRET_FIELDS:
if values[field]:
values[field] = self._fernet(create=True).encrypt(values[field].encode("utf-8")).decode("ascii")
return (
json.dumps(
{"revision": profile.revision, "key_id": self.key_id, "settings": values},
ensure_ascii=False,
indent=2,
)
+ "\n"
)
def commit(self, prepared: str) -> None:
"""Replace the saved generation only after the new worker is ready."""
write_private(self.path, prepared)