Skip to content

The agent that grows with you

fix(cron): hand a primary-routed satellite's manual run to the gateway ticker

Denis Dresvyanskiy7e849e5548dd
diff --git a/tests/tools/test_cronjob_run_primary_routed.py b/tests/tools/test_cronjob_run_primary_routed.py
new file mode 100644
index 00000000000..1350fc76c9e
--- /dev/null
+++ b/tests/tools/test_cronjob_run_primary_routed.py
@@ -0,0 +1,90 @@
+"""Manual runs of a satellite job that delivers through the primary gateway's profile route.
+
+Regression for #120330. A multiplexed satellite profile with no ``platforms.<p>`` credential of
+its own posts through the primary's bot via a root ``gateway.profile_routes`` entry, so only the
+gateway process holding that bot can deliver its jobs. ``hermes -p <profile> cron run`` used to
+run the whole agent turn in the CLI process anyway, fail delivery with ``platform 'telegram' not
+configured/enabled`` and overwrite the job's ``last_status`` with ``delivery_failed``.
+"""
+
+import json
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+import yaml
+
+from hermes_cli.cron import _run_outcome
+
+ROUTED_TARGET = "telegram:-1004306455751:14"
+
+
+def keeper_job(tmp_path, monkeypatch):
+ """A ``keeper`` satellite home whose primary routes one Telegram topic to it, plus one job there."""
+ root = tmp_path / "root"
+ keeper_home = root / "profiles" / "keeper"
+ keeper_home.mkdir(parents=True)
+ (root / "config.yaml").write_text(yaml.safe_dump({"gateway": {
+ "multiplex_profiles": True,
+ "profile_routes": [{"name": "ops", "platform": "telegram", "chat_id": "-1004306455751",
+ "thread_id": "14", "profile": "keeper"}],
+ }}), encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(keeper_home)) # what `hermes -p keeper` sets
+ from cron.jobs import create_job
+ return create_job(prompt="infra report", schedule="0 9 * * *", name="infra", deliver=ROUTED_TARGET)
+
+
+def _run(job_id, *, gateway_serves_profile):
+ from tools.cronjob_tools import cronjob
+ with patch("hermes_cli.cron._builtin_gateway_liveness", return_value=gateway_serves_profile), \
+ patch("cron.scheduler.run_one_job", return_value=True) as m_run:
+ out = json.loads(cronjob(action="run", job_id=job_id))
+ return out, m_run
+
+
+def test_routed_run_is_queued_for_the_gateway_that_serves_the_profile(keeper_job):
+ from cron.jobs import get_job
+ out, m_run = _run(keeper_job["id"], gateway_serves_profile=True)
+
+ assert out["success"] is True
+ m_run.assert_not_called() # no agent turn in a process that cannot deliver its result
+ stored = get_job(keeper_job["id"])
+ assert stored["next_run_at"] == stored["manual_run_at"] # due on the gateway's next tick
+ assert stored.get("last_status") is None # the manual run does not rewrite the job's status
+ assert _run_outcome(out["job"]) == "It will run on the next scheduler tick."
+
+
+def test_routed_run_without_a_serving_gateway_fails_before_the_turn(keeper_job):
+ from cron.jobs import get_job
+ out, m_run = _run(keeper_job["id"], gateway_serves_profile=False)
+
+ assert out["success"] is False
+ assert "profile route" in out["error"]
+ m_run.assert_not_called()
+ stored = get_job(keeper_job["id"])
+ assert stored["next_run_at"] == keeper_job["next_run_at"]
+ assert "manual_run_at" not in stored
+
+
[email protected]("case", ["local delivery", "own credential", "inside the gateway", "paused"])
+def test_run_keeps_the_in_process_path_when_not_routed_only(keeper_job, monkeypatch, case):
+ """Everything but a runnable job reachable only through the primary route runs as before."""
+ from cron.jobs import get_job, pause_job, update_job
+ from tools import cronjob_tools
+ if case == "local delivery":
+ update_job(keeper_job["id"], {"deliver": "local"})
+ elif case == "own credential":
+ monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "123456:keeper-own-bot")
+ elif case == "inside the gateway":
+ runner = SimpleNamespace(adapters={}, _gateway_loop=None)
+ monkeypatch.setattr("gateway.run._gateway_runner_ref", lambda: runner)
+ else:
+ pause_job(keeper_job["id"])
+
+ with patch.object(cronjob_tools, "claim_job_for_fire",
+ wraps=cronjob_tools.claim_job_for_fire) as m_claim:
+ _run(keeper_job["id"], gateway_serves_profile=True)
+
+ m_claim.assert_called_once() # the in-process claim -> run_one_job path, unchanged
+ assert "manual_run_at" not in get_job(keeper_job["id"])
diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.py
index e1595fab45d..064ff952a7e 100644
--- a/tools/cronjob_tools.py
+++ b/tools/cronjob_tools.py
@@ -42,6 +42,7 @@ from cron.jobs import (
remove_job,
resolve_job_ref,
resume_job,
+ trigger_job,
update_job)
from tools.cronjob_prompt_scan import _scan_cron_prompt
from tools.cronjob_job_args import (
@@ -155,6 +156,55 @@ def _forward_relay_fronted_run(job: Dict[str, Any], extra_prompt: Optional[str]
})
+def _primary_routed_delivery_platforms(job: Dict[str, Any]) -> set:
+ """Delivery-platform names this satellite profile reaches only through the primary gateway's
+ ``profile_routes``: routed here, with no credential of its own to send standalone."""
+ try:
+ from cron.scheduler import _resolve_delivery_targets
+ from cron.scheduler_preflight import _delivery_platform_routed_from_primary_gateway
+ routed = {t["platform"] for t in _resolve_delivery_targets(job) or []
+ if t.get("platform") and _delivery_platform_routed_from_primary_gateway(t["platform"])}
+ if not routed:
+ return set()
+ from gateway.config import load_gateway_config
+ return routed - {p.value for p in load_gateway_config().get_connected_platforms()}
+ except Exception:
+ return set()
+
+
+def _hand_off_primary_routed_run(job: Dict[str, Any], extra_prompt: Optional[str] = None) -> Optional[str]:
+ """Queue a manual run for the gateway ticker when the job delivers through the primary gateway's
+ profile route: only the gateway process holding the primary's bot can send it, so an in-process
+ run would spend the whole turn and then record ``delivery_failed`` (#120330). Returns a JSON
+ result string when the hand-off engages, else None (normal in-process run)."""
+ runner_ref = getattr(sys.modules.get("gateway.run"), "_gateway_runner_ref", None)
+ if callable(runner_ref) and runner_ref() is not None:
+ return None # inside the gateway: its live adapter delivers (#89302)
+ if not is_job_runnable(job):
+ return None # keep the normal paused refusal; trigger_job would resume the job
+ routed = _primary_routed_delivery_platforms(job)
+ if not routed:
+ return None
+ from hermes_cli.cron import _builtin_gateway_liveness
+ if _builtin_gateway_liveness() is False:
+ return _dumps({
+ "success": False,
+ "error": (
+ f"This job delivers to {', '.join(sorted(routed))} through the primary "
+ "gateway's profile route, which has no standalone sender. Start the "
+ "gateway — its ticker will deliver the job on schedule."),
+ })
+ updated = trigger_job(job["id"], extra_prompt=extra_prompt)
+ _notify_provider_jobs_changed_safe()
+ return _dumps({
+ "success": True,
+ "job": _format_job(updated),
+ "note": (
+ "This job delivers through the primary gateway's profile route; it was "
+ "queued for that gateway's next scheduler tick, which runs and delivers it."),
+ })
+
+
def _manual_run_delivery_note(deliver: str, refreshed: Dict[str, Any]) -> str:
"""Parenthetical delivery note for a manual run's summary; follows the refreshed record's
``last_delivery_error`` so the summary never claims success over a failed delivery.
@@ -689,6 +739,10 @@ def _action_run(job: Dict[str, Any], a: Dict[str, Any]) -> str:
scan_error = _scan_cron_prompt(extra_prompt)
if scan_error:
return tool_error(scan_error, success=False)
+ # Primary-routed satellite delivery has no sender outside the gateway: hand the run to its ticker.
+ handed_off = _hand_off_primary_routed_run(job, extra_prompt=extra_prompt)
+ if handed_off is not None:
+ return handed_off
# A manual run must actually run even with no ticker active. Preferred: background
# dispatch (handle now, outcome as a completion event); inline fallback otherwise.
bg = _try_dispatch_background_run(job, session_id=a["session_id"], extra_prompt=extra_prompt)