mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-11-29 00:38:33 +00:00
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
* 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.
131 lines
5.3 KiB
Python
131 lines
5.3 KiB
Python
"""Container startup and health checks using ReMe's existing CLI contract."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import stat
|
|
from pathlib import Path
|
|
import sys
|
|
from urllib.request import ProxyHandler, Request, build_opener
|
|
|
|
HEALTH_STATE_PATH = Path("/tmp/reme-health.json")
|
|
STATE_DIRECTORY = Path("/state")
|
|
_ENV_OVERRIDES = {
|
|
"REME_CONFIG": "config",
|
|
"REME_WORKSPACE_DIR": "workspace_dir",
|
|
"REME_HOST": "service.host",
|
|
"REME_PORT": "service.port",
|
|
}
|
|
|
|
|
|
def start_command(arguments: list[str], environment: dict[str, str]) -> list[str]:
|
|
"""Add container defaults only to `start`; explicit CLI arguments win."""
|
|
from reme.config import deep_merge_config, parse_kwargs
|
|
|
|
defaults = parse_kwargs(
|
|
"log_to_file=false",
|
|
*[f"{key}={json.dumps(environment[name])}" for name, key in _ENV_OVERRIDES.items() if environment.get(name)],
|
|
)
|
|
# Docker environment values are strings; the HTTP service expects an integer port.
|
|
if environment.get("REME_PORT"):
|
|
defaults["service"]["port"] = int(environment["REME_PORT"])
|
|
overrides = deep_merge_config(defaults, parse_kwargs(*arguments))
|
|
return ["reme", "start", *[f"{key}={json.dumps(value, ensure_ascii=False)}" for key, value in overrides.items()]]
|
|
|
|
|
|
def write_health_state(command: list[str], state_path: Path = HEALTH_STATE_PATH) -> None:
|
|
"""Record only the effective HTTP address, never credentials or user data."""
|
|
from reme.components.service.cli_service import prepare_start_service
|
|
from reme.config import parse_kwargs
|
|
from reme.constants import REME_DEFAULT_HOST, REME_DEFAULT_PORT, normalize_connect_host
|
|
|
|
service = prepare_start_service(parse_kwargs(*command[2:]))
|
|
if service.get("backend") != "http":
|
|
return
|
|
host = normalize_connect_host(service.get("host") or REME_DEFAULT_HOST)
|
|
if host == "::":
|
|
host = "::1"
|
|
port = int(service.get("port", REME_DEFAULT_PORT))
|
|
if not 1 <= port <= 65535:
|
|
raise ValueError("service.port must be between 1 and 65535")
|
|
host = f"[{host}]" if ":" in host else host
|
|
with state_path.open("w", encoding="utf-8") as state_file:
|
|
os.chmod(state_path, 0o600)
|
|
json.dump({"url": f"http://{host}:{port}/health_check"}, state_file)
|
|
|
|
|
|
def healthcheck(state_path: Path = HEALTH_STATE_PATH) -> int:
|
|
"""Require both a successful Job and a healthy component snapshot."""
|
|
try:
|
|
state = json.loads(state_path.read_text(encoding="utf-8"))
|
|
request = Request(state["url"], data=b"{}", headers={"Content-Type": "application/json"}, method="POST")
|
|
# A deployment's outbound proxy must not intercept its local probe.
|
|
with build_opener(ProxyHandler({})).open(request, timeout=4) as response:
|
|
payload = json.load(response)
|
|
healthy = payload.get("metadata", {}).get("health", {}).get("healthy")
|
|
if payload.get("success") is True and healthy is True:
|
|
return 0
|
|
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
|
pass
|
|
print("ReMe HTTP health check failed; inspect the container logs and POST /health_check", file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
def drop_privileges(*, prepare_state: bool) -> None:
|
|
"""Assign the private volume to the configured account before running any command."""
|
|
if os.name != "posix" or os.geteuid() != 0:
|
|
return
|
|
uid = int(os.getenv("REME_UID", "1000"))
|
|
gid = int(os.getenv("REME_GID", "1000"))
|
|
if uid <= 0 or gid <= 0:
|
|
raise ValueError("REME_UID and REME_GID must be positive")
|
|
if prepare_state:
|
|
directory = os.open(STATE_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
try:
|
|
os.fchown(directory, uid, gid)
|
|
os.fchmod(directory, 0o700)
|
|
for name in ("lock", "admin-token", "settings.json", "state.json"):
|
|
for entry in (name, name + ".tmp"):
|
|
try:
|
|
mode = os.stat(entry, dir_fd=directory, follow_symlinks=False).st_mode
|
|
except FileNotFoundError:
|
|
continue
|
|
if stat.S_ISREG(mode):
|
|
os.chown(entry, uid, gid, dir_fd=directory, follow_symlinks=False)
|
|
finally:
|
|
os.close(directory)
|
|
os.setgroups([])
|
|
os.setgid(gid)
|
|
os.setuid(uid)
|
|
|
|
|
|
def main() -> int:
|
|
"""Prepare startup, then replace this process so signals reach ReMe."""
|
|
arguments = sys.argv[1:]
|
|
drop_privileges(prepare_state=arguments != ["--healthcheck"])
|
|
if arguments == ["--healthcheck"]:
|
|
return healthcheck()
|
|
|
|
HEALTH_STATE_PATH.unlink(missing_ok=True)
|
|
Path(os.environ.get("HOME", "/tmp/reme-home")).mkdir(parents=True, exist_ok=True)
|
|
if not arguments:
|
|
arguments = ["start"]
|
|
start_actions = {"start", "-start", "--start"}
|
|
if len(arguments) >= 2 and arguments[0] == "reme" and arguments[1] in start_actions:
|
|
arguments = arguments[1:]
|
|
if arguments[0] in start_actions:
|
|
from reme.utils.env_utils import load_env
|
|
|
|
inherited = dict(os.environ)
|
|
load_env()
|
|
arguments = start_command(arguments[1:], dict(os.environ))
|
|
write_health_state(arguments)
|
|
os.execvpe(arguments[0], arguments, inherited)
|
|
else:
|
|
os.execvp(arguments[0], arguments)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|