Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cli-config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,12 @@ platform_toolsets:
teams: [hermes-teams]
google_chat: [hermes-google_chat]

# Exactly one long-running runtime should dispatch due jobs for a HERMES_HOME.
# auto (default) selects the gateway; desktop is an explicit Desktop-only fallback.
# Invalid values fail closed so competing runtimes cannot both start a ticker.
cron:
scheduler_owner: "auto" # auto | gateway | desktop

# =============================================================================
# Gateway Platform Settings
# =============================================================================
Expand Down
23 changes: 17 additions & 6 deletions cron/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,9 @@ def _is_token(line: str) -> bool:
_parallel_pool_max_workers: Optional[int] = None
_running_job_ids: set = set()
_running_lock = threading.Lock()
# Keep reset + reload atomic when multiple jobs start together. The loader
# publishes into process-global os.environ before child environments are built.
_cron_secret_refresh_lock = threading.RLock()

# Job IDs the gateway shutdown path force-killed the tool subprocess of
# while still in ``_running_job_ids`` (see ``mark_running_jobs_interrupted``
Expand Down Expand Up @@ -2587,6 +2590,15 @@ def _guard_job_credential_exfil(job: dict) -> None:
raise RuntimeError(f"Cron job '{job_id}' blocked for safety: {err}")


def _refresh_cron_runtime_secrets() -> None:
"""Refresh dotenv and configured external secrets for the active home."""
from hermes_cli.env_loader import load_hermes_dotenv, reset_secret_source_cache

with _cron_secret_refresh_lock:
reset_secret_source_cache()
load_hermes_dotenv(hermes_home=_get_hermes_home())


def run_job(
job: dict, *, defer_agent_teardown: Optional[list] = None
) -> tuple[bool, str, str, Optional[str]]:
Expand Down Expand Up @@ -2634,6 +2646,10 @@ def run_job(
logger.error("Job '%s': %s", job_id, err)
return False, "", "", err

# no_agent returns before the normal agent bootstrap below. Refresh
# external sources now, before _run_job_script constructs child env.
_refresh_cron_runtime_secrets()

# Apply workdir if configured — lets scripts use predictable relative
# paths. For no_agent jobs this is just the subprocess cwd (not an
# agent TERMINAL_CWD bridge).
Expand Down Expand Up @@ -2948,12 +2964,7 @@ def run_job(
# is set (mirrors startup), and the Bitwarden value-cache keeps the
# forced re-pull off the network. load_hermes_dotenv also handles the
# utf-8/latin-1 encoding fallback internally.
from hermes_cli.env_loader import (
load_hermes_dotenv,
reset_secret_source_cache,
)
reset_secret_source_cache()
load_hermes_dotenv(hermes_home=_get_hermes_home())
_refresh_cron_runtime_secrets()

delivery_target = _resolve_delivery_target(job)
if delivery_target:
Expand Down
104 changes: 100 additions & 4 deletions cron/scheduler_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,111 @@
"""
from __future__ import annotations

import io
import logging
import threading
from abc import ABC, abstractmethod
from typing import Any


logger = logging.getLogger("cron.scheduler_provider")

_CRON_SCHEDULER_RUNTIME_OWNERS = frozenset({"gateway", "desktop"})


def _read_scheduler_owner_config_strict() -> dict[str, Any] | None:
"""Read scheduler ownership without the normal tolerant config fallback."""
from hermes_cli import managed_scope
from hermes_cli.config import get_config_path
from utils import fast_safe_load

def _read_mapping(path) -> dict[str, Any]:
try:
with open(path, encoding="utf-8") as handle:
raw = handle.read()
except FileNotFoundError:
return {}
meaningful = [
line.split("#", 1)[0].strip()
for line in raw.splitlines()
if line.split("#", 1)[0].strip() not in {"", "---", "..."}
]
if not meaningful:
return {}
parsed = fast_safe_load(io.StringIO(raw))
if not isinstance(parsed, dict):
raise ValueError("config root must be a mapping")
return parsed

try:
user_config = _read_mapping(get_config_path())
managed_dir = managed_scope.get_managed_dir()
managed_config = (
_read_mapping(managed_dir / "config.yaml")
if managed_dir is not None
else {}
)
user_cron = user_config.get("cron", {})
managed_cron = managed_config.get("cron", {})
if "cron" in user_config and not isinstance(user_cron, dict):
raise ValueError("cron section must be a mapping")
if "cron" in managed_config and not isinstance(managed_cron, dict):
raise ValueError("managed cron section must be a mapping")
effective_cron = dict(user_cron)
effective_cron.update(managed_cron)
return {"cron": effective_cron}
except Exception:
logger.error(
"Unable to read a valid cron.scheduler_owner; scheduler startup disabled. "
"Set it to auto, gateway, or desktop in config.yaml."
)
return None


def resolve_cron_scheduler_owner(*, config: dict[str, Any] | None = None) -> str | None:
"""Resolve the single automatic scheduler owner, failing closed on errors."""
if config is None:
config = _read_scheduler_owner_config_strict()
if config is None:
return None
if not isinstance(config, dict):
logger.error("Invalid configuration root; scheduler startup disabled.")
return None
cron_config = config.get("cron", {})
if "cron" in config and not isinstance(cron_config, dict):
logger.error("Invalid cron configuration shape; scheduler startup disabled.")
return None
raw_owner = cron_config.get("scheduler_owner", "auto")
owner = raw_owner.strip().lower() if isinstance(raw_owner, str) else None
if owner == "auto":
return "gateway"
if owner in _CRON_SCHEDULER_RUNTIME_OWNERS:
return owner
logger.error(
"Invalid cron.scheduler_owner; scheduler startup disabled. "
"Use auto, gateway, or desktop in config.yaml."
)
return None


def should_start_cron_scheduler(
runtime_owner: str, *, config: dict[str, Any] | None = None
) -> bool:
"""Return whether this long-running runtime owns automatic dispatch."""
if runtime_owner not in _CRON_SCHEDULER_RUNTIME_OWNERS:
raise ValueError("Unknown cron scheduler runtime owner")
return resolve_cron_scheduler_owner(config=config) == runtime_owner


def resolve_owned_cron_scheduler(
runtime_owner: str, *, config: dict[str, Any] | None = None
) -> "CronScheduler | None":
"""Resolve the provider only after the shared ownership gate succeeds."""
if not should_start_cron_scheduler(runtime_owner, config=config):
return None
return resolve_cron_scheduler()


class CronScheduler(ABC):
"""Axis-B trigger provider. Decides WHEN a due cron job fires.

Expand Down Expand Up @@ -119,10 +219,6 @@ def resolve_cron_scheduler() -> "CronScheduler":
False`` falls back to the built-in with a warning — cron must never be left
without a trigger.
"""
import logging

logger = logging.getLogger("cron.scheduler_provider")

name = ""
try:
from hermes_cli.config import cfg_get, load_config
Expand Down
67 changes: 40 additions & 27 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -21092,6 +21092,34 @@ def _start_cron_ticker(stop_event: threading.Event, adapters=None, loop=None, in
InProcessCronScheduler().start(stop_event, adapters=adapters, loop=loop, interval=interval)


def _start_gateway_cron_scheduler_if_owned(runner, stop_event, loop):
"""Start cron only when the shared ownership policy selects this gateway."""
from cron.scheduler_provider import (
InProcessCronScheduler,
resolve_owned_cron_scheduler,
)

provider = resolve_owned_cron_scheduler("gateway")
if provider is None:
logger.info("Gateway cron scheduler not started by ownership policy")
return None, None

start_kwargs = {"adapters": runner.adapters, "loop": loop}
if isinstance(provider, InProcessCronScheduler):
start_kwargs["can_dispatch"] = lambda: not (
runner._draining or runner._external_drain_active
)
thread = threading.Thread(
target=provider.start,
args=(stop_event,),
kwargs=start_kwargs,
daemon=True,
name="cron-scheduler",
)
thread.start()
return provider, thread


# Upper bound for cooperatively draining the cron ticker on shutdown. The cron
# thread delivers via ``safe_schedule_threadsafe`` and blocks on
# ``future.result(timeout=60)`` (see cron/scheduler.py::_deliver_result), so a
Expand Down Expand Up @@ -21584,30 +21612,12 @@ def restart_signal_handler():
raise SystemExit(runner.exit_code)
return True

# Start the background cron scheduler via the resolved provider so
# scheduled jobs fire automatically. The built-in provider is the
# historical in-process 60s ticker; an external provider (e.g. chronos)
# may arm a schedule and return. Pass the event loop so cron delivery can
# use live adapters (E2EE support).
from cron.scheduler_provider import InProcessCronScheduler, resolve_cron_scheduler
# Both gateway and Desktop consult the same ownership helper so only one
# long-running runtime dispatches this profile's cron registry.
cron_stop = threading.Event()
cron_provider = resolve_cron_scheduler()
cron_start_kwargs = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}
# External cron providers own their remote scheduling contract. Only the
# in-process ticker polls local due jobs, so only it receives the local
# external-drain dispatch gate.
if isinstance(cron_provider, InProcessCronScheduler):
cron_start_kwargs["can_dispatch"] = lambda: not (
runner._draining or runner._external_drain_active
)
cron_thread = threading.Thread(
target=cron_provider.start,
args=(cron_stop,),
kwargs=cron_start_kwargs,
daemon=True,
name="cron-scheduler",
cron_provider, cron_thread = _start_gateway_cron_scheduler_if_owned(
runner, cron_stop, asyncio.get_running_loop()
)
cron_thread.start()

# Gateway-only periodic housekeeping (channel dir, cache cleanup, paste
# sweep, curator) — runs independently of which cron provider is active.
Expand Down Expand Up @@ -21646,11 +21656,14 @@ def restart_signal_handler():
# silently dropped (#58818). Awaiting keeps the loop alive so the in-flight
# delivery finishes before we tear down.
cron_stop.set()
try:
cron_provider.stop()
except Exception as e:
logger.debug("Cron provider stop() error: %s", e)
if not await _await_thread_exit(cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT):
if cron_provider is not None:
try:
cron_provider.stop()
except Exception as e:
logger.debug("Cron provider stop() error: %s", e)
if cron_thread is not None and not await _await_thread_exit(
cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT
):
logger.warning(
"Cron ticker did not exit within %.0fs of shutdown — an in-flight "
"delivery may have been dropped.", _CRON_SHUTDOWN_DRAIN_TIMEOUT,
Expand Down
4 changes: 4 additions & 0 deletions hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2706,6 +2706,10 @@ def _ensure_hermes_home_managed(home: Path):
},

"cron": {
# Exactly one long-running runtime may dispatch due jobs for a
# HERMES_HOME. "auto" deterministically selects the gateway; use
# "desktop" only for an intentional Desktop-only installation.
"scheduler_owner": "auto",
# Active cron SCHEDULER provider (Axis B — the trigger that decides
# WHEN a due job fires). Empty string = the built-in in-process 60s
# ticker (default). Name an installed provider (plugins/cron_providers/<name>/ or
Expand Down
66 changes: 36 additions & 30 deletions hermes_cli/web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,27 +138,44 @@
# when the same module is used across TestClient instances or uvicorn reloads.
# ---------------------------------------------------------------------------

def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60) -> None:
"""Tick the cron scheduler from inside the desktop dashboard backend.

The scheduler tick loop normally lives in ``hermes gateway run`` — but the
desktop app spawns a ``hermes dashboard`` backend, not a gateway, so a cron
a user creates in the app would never fire. We run the resolved cron
scheduler provider here (no live adapters; delivery falls back to the
per-platform send path).

Cross-process safe: the built-in provider's ``cron.scheduler.tick`` takes
the ``cron/.tick.lock`` file lock, so this never double-fires alongside a
real gateway on the same HERMES_HOME — whichever process grabs the lock
first wins the tick.
"""
from cron.scheduler_provider import resolve_cron_scheduler
def _start_desktop_cron_ticker(
stop_event: "threading.Event", interval: int = 60, *, provider: Any = None
) -> None:
"""Run the resolved provider for an explicitly owned Desktop ticker."""
if provider is None:
from cron.scheduler_provider import resolve_cron_scheduler

provider = resolve_cron_scheduler()
provider = resolve_cron_scheduler()
_log.info("Desktop cron scheduler started (provider=%s, interval=%ds)", provider.name, interval)
provider.start(stop_event, interval=interval)


def _start_desktop_cron_scheduler_if_owned() -> tuple[
"threading.Event | None", "threading.Thread | None"
]:
"""Start Desktop's fallback ticker only when it owns automatic dispatch."""
if os.getenv("HERMES_DESKTOP") != "1":
return None, None

from cron.scheduler_provider import resolve_owned_cron_scheduler

provider = resolve_owned_cron_scheduler("desktop")
if provider is None:
_log.info("Desktop cron scheduler not started by ownership policy")
return None, None

stop_event = threading.Event()
thread = threading.Thread(
target=_start_desktop_cron_ticker,
args=(stop_event,),
kwargs={"provider": provider},
daemon=True,
name="desktop-cron-ticker",
)
thread.start()
return stop_event, thread


def _warm_gateway_module() -> None:
try:
import hermes_cli.gateway # noqa: F401
Expand Down Expand Up @@ -194,20 +211,9 @@ async def _lifespan(app: "FastAPI"):
# the server socket is already open and accepting probes.
asyncio.get_event_loop().run_in_executor(None, _warm_gateway_module)

# Desktop-spawned backends (HERMES_DESKTOP=1) fire cron jobs themselves,
# since the app has no gateway running the scheduler. Server `hermes
# dashboard` is unaffected — it relies on its own gateway.
cron_stop: "threading.Event | None" = None
cron_thread: "threading.Thread | None" = None
if os.getenv("HERMES_DESKTOP") == "1":
cron_stop = threading.Event()
cron_thread = threading.Thread(
target=_start_desktop_cron_ticker,
args=(cron_stop,),
daemon=True,
name="desktop-cron-ticker",
)
cron_thread.start()
# Desktop remains available when the default gateway owns scheduling; an
# explicit desktop owner preserves the Desktop-only fallback.
cron_stop, cron_thread = _start_desktop_cron_scheduler_if_owned()

# Reap idle/dead keep-alive PTY sessions in the background (30-min TTL).
pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY))
Expand Down
Loading