From a5a7a0784da8f19fe5cfaf9b140ab8400cf09bb5 Mon Sep 17 00:00:00 2001 From: unsupportedpastels Date: Tue, 24 Nov 2026 14:27:07 +0000 Subject: [PATCH] fix(cron): use firing job settings in delivery_platforms and expose ctx.cron_delivery_platforms Capture a delivery-relevant snapshot of the firing job inside cron.execution_identity.enter_cron_execution so delivery_platforms() with job_id=None answers from the run that is actually firing even when the saved job is edited or deleted mid-run, while explicit job_id lookups remain previews of the stored job. Add PluginContext.cron_delivery_platforms(job_id=None) (and tuple preservation in RemotePluginContext) so hooks running under plugins.isolation: host read the firing run's delivery platforms in the gateway in the calling hook's context. Re-export CronSchedulerRegistrationError from cron.plugin_api so plugins can catch it without a private core import, and update the plugin guide example and tests accordingly. Addresses Greptile review feedback on PR #159657. --- cron/execution_identity.py | 46 +++++++- cron/plugin_api.py | 44 ++++--- hermes_cli/plugin_host_child.py | 4 + hermes_cli/plugins_context.py | 10 ++ tests/cron/test_cron_plugin_api.py | 107 ++++++++++++++++-- website/docs/developer-guide/plugins/index.md | 11 +- 6 files changed, 188 insertions(+), 34 deletions(-) diff --git a/cron/execution_identity.py b/cron/execution_identity.py index f13a61831c..895213552d 100644 --- a/cron/execution_identity.py +++ b/cron/execution_identity.py @@ -25,14 +25,37 @@ class CronExecution: profile: str -_CURRENT: ContextVar[Optional[CronExecution]] = ContextVar("hermes_cron_execution", default=None) +def _snapshot_firing_job(job: Mapping[str, Any]) -> dict[str, Any]: + """Capture the delivery-relevant fields of the firing job so mid-run edits or deletions in the + job store never change what hooks see for the run already in flight.""" + snapshot: dict[str, Any] = { + "id": str(job["id"]), + "name": str(job.get("name") or job["id"]), + } + if "deliver" in job: + deliver = job["deliver"] + snapshot["deliver"] = list(deliver) if isinstance(deliver, (list, tuple)) else deliver + if "failure_deliver" in job: + failure_deliver = job["failure_deliver"] + snapshot["failure_deliver"] = ( + list(failure_deliver) if isinstance(failure_deliver, (list, tuple)) else failure_deliver + ) + if "origin" in job: + origin = job["origin"] + snapshot["origin"] = dict(origin) if isinstance(origin, Mapping) else origin + return snapshot + + +_CURRENT: ContextVar[Optional[tuple[CronExecution, dict[str, Any]]]] = ContextVar( + "hermes_cron_execution", default=None, +) def enter_cron_execution(job: Mapping[str, Any], execution_id: str, record: Mapping[str, Any]) -> Token: """Bind this fire's identity from *record*, the ledger row of the running transition.""" from hermes_cli.profiles import current_profile_name - return _CURRENT.set(CronExecution( + execution = CronExecution( job_id=str(job["id"]), job_name=str(job.get("name") or job["id"]), execution_id=str(execution_id), @@ -40,7 +63,8 @@ def enter_cron_execution(job: Mapping[str, Any], execution_id: str, record: Mapp scheduled_instant=record.get("scheduled_instant"), started_at=record.get("started_at"), profile=current_profile_name("default") or "default", - )) + ) + return _CURRENT.set((execution, _snapshot_firing_job(job))) def exit_cron_execution(token: Optional[Token]) -> None: @@ -51,4 +75,18 @@ def exit_cron_execution(token: Optional[Token]) -> None: def current_cron_execution() -> Optional[CronExecution]: from agent.delegation_context import is_delegated_child_context - return None if is_delegated_child_context() else _CURRENT.get() + if is_delegated_child_context(): + return None + bound = _CURRENT.get() + return bound[0] if bound is not None else None + + +def _current_cron_execution_job() -> Optional[dict[str, Any]]: + """Delivery-relevant snapshot of the firing job bound in this context, or ``None`` outside a + cron run or inside a delegated child.""" + from agent.delegation_context import is_delegated_child_context + + if is_delegated_child_context(): + return None + bound = _CURRENT.get() + return bound[1] if bound is not None else None diff --git a/cron/plugin_api.py b/cron/plugin_api.py index 84dda0b8e1..61b5e10f66 100644 --- a/cron/plugin_api.py +++ b/cron/plugin_api.py @@ -9,11 +9,26 @@ from __future__ import annotations import contextlib as _contextlib from pathlib import Path as _Path -from typing import Any as _Any, Optional as _Optional +from typing import TYPE_CHECKING as _TYPE_CHECKING, Any as _Any, Optional as _Optional from cron.jobs import AmbiguousJobReference -__all__ = ["AmbiguousJobReference", "delivery_platforms", "ensure_named_job"] +if _TYPE_CHECKING: + from cron.scheduler import CronSchedulerRegistrationError + +__all__ = [ + "AmbiguousJobReference", + "CronSchedulerRegistrationError", + "delivery_platforms", + "ensure_named_job", +] + + +def __getattr__(name: str) -> _Any: + if name == "CronSchedulerRegistrationError": + from cron.scheduler import CronSchedulerRegistrationError + return CronSchedulerRegistrationError + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") @_contextlib.contextmanager @@ -107,31 +122,30 @@ def delivery_platforms( ) -> _Optional[tuple[str, ...]]: """The platforms cron would deliver a job's output to right now, lower-cased, in order. - ``job_id=None`` answers for the cron run bound in this process's calling context, and returns - ``None`` outside one: a hook in a plugin host has no such binding, so it passes - ``ctx.current_cron_execution().job_id``. ``None`` also when no stored job has that id. ``()`` for - a job that delivers nowhere. It reads the normal delivery lane; a ``failure_deliver`` override - is not consulted. The answer is the stored job's: an edit saved while a run is in - flight shows here, though that run delivers with the settings it started with. The + ``job_id=None`` answers for the cron run bound in this process's calling context using that + firing run's own delivery settings — edits or deletions saved to the job store mid-run do not + change the answer — and returns ``None`` outside one (or in a delegated child). A hook in a + plugin host has no cron run bound in its own process and calls ``ctx.cron_delivery_platforms()`` + instead so the lookup runs in the gateway. Passing an explicit ``job_id`` previews the saved job + in the store (returning ``None`` when no stored job has that id). ``()`` means the job delivers + nowhere. It reads the normal delivery lane; a ``failure_deliver`` override is not consulted. The targets come from cron's own resolver, so ``all``, the ``origin`` fallback, home channels and Bot Chat tokens follow cron's rules. Only platform names are returned, never chat or thread ids. ``home`` runs the call against that profile's home, cron store and secrets; ``None`` when it is not an existing directory, which is not created. """ - from cron.execution_identity import current_cron_execution + from cron.execution_identity import _current_cron_execution_job from cron.jobs import get_job from cron.scheduler_delivery import _resolve_delivery_targets home = _expanded(home) if home is not None and not home.is_dir(): return None - if job_id is None: - run = current_cron_execution() - if run is None: - return None - job_id = run.job_id + firing_job = _current_cron_execution_job() if job_id is None else None + if job_id is None and firing_job is None: + return None with _home_scope(home): - job = get_job(job_id) + job = firing_job if job_id is None else get_job(job_id) if job is None: return None platforms = [str(target["platform"]).lower() for target in _resolve_delivery_targets(job)] diff --git a/hermes_cli/plugin_host_child.py b/hermes_cli/plugin_host_child.py index 27e953f928..604d0ef21f 100644 --- a/hermes_cli/plugin_host_child.py +++ b/hermes_cli/plugin_host_child.py @@ -127,6 +127,10 @@ class RemotePluginContext: raise TypeError("on_unload() callback must be callable") self._runtime.unload_callbacks.setdefault(self._plugin_key, []).append(callback) + def cron_delivery_platforms(self, job_id: Optional[str] = None) -> Optional[tuple[str, ...]]: + result = self._runtime.ctx_call(self._plugin_key, "cron_delivery_platforms", job_id) + return None if result is None else tuple(result) + def spawn_task(self, coro: Any, *, name: Optional[str] = None) -> Any: return self._runtime.spawn(coro, name=name) diff --git a/hermes_cli/plugins_context.py b/hermes_cli/plugins_context.py index 452ce22779..709e1af38b 100644 --- a/hermes_cli/plugins_context.py +++ b/hermes_cli/plugins_context.py @@ -222,6 +222,16 @@ class PluginContext(PluginCapabilityCtxMixin, PluginIdleTaskCtxMixin): from cron.execution_identity import current_cron_execution return current_cron_execution() + def cron_delivery_platforms(self, job_id: Optional[str] = None) -> Optional[tuple[str, ...]]: + """The platforms cron delivers a job's output to, lower-cased, in order + (``cron.plugin_api.delivery_platforms``). With ``job_id=None``, answers for the firing cron + run using that run's own settings (or ``None`` outside one); with ``job_id``, previews the + saved job in this plugin's profile. Reads normal delivery (``deliver``), not + ``failure_deliver``. Under ``plugins.isolation: host`` this runs in the gateway, in the + calling hook's context.""" + from cron.plugin_api import delivery_platforms + return delivery_platforms(job_id) + def on_unload(self, callback: Callable[[], None]) -> PluginRegistration: """Register a cleanup callback for unload: runs in reverse acquisition order interleaved with registration teardown; exceptions are logged, never propagated.""" diff --git a/tests/cron/test_cron_plugin_api.py b/tests/cron/test_cron_plugin_api.py index e520b0ca2a..2eeb38247d 100644 --- a/tests/cron/test_cron_plugin_api.py +++ b/tests/cron/test_cron_plugin_api.py @@ -313,6 +313,44 @@ def test_no_job_id_inside_a_cron_run_answers_for_that_run(home_channels): assert delivery_platforms() is None +def test_no_job_id_uses_firing_job_settings_even_after_disk_edit_or_delete(home_channels): + from agent.delegation_context import delegated_child_context + + job = jobs.create_job(prompt="p", schedule="every 1h", name="run", deliver="telegram") + + token = enter_cron_execution(job, "exec-1", {"source": "direct"}) + try: + jobs.update_job(job["id"], {"deliver": "local"}) + assert delivery_platforms() == ("telegram",) + assert delivery_platforms(job["id"]) == () + + jobs.remove_job(job["id"]) + assert delivery_platforms() == ("telegram",) + assert delivery_platforms(job["id"]) is None + + with delegated_child_context("child"): + assert delivery_platforms() is None + finally: + exit_cron_execution(token) + assert delivery_platforms() is None + + +def test_no_job_id_uses_firing_origin_even_if_mutated_or_edited_mid_run(home_channels): + job = jobs.create_job( + prompt="p", schedule="every 1h", name="run", deliver="origin", + origin={"platform": "telegram", "chat_id": TELEGRAM_CHAT}, + ) + + token = enter_cron_execution(job, "exec-1", {"source": "direct"}) + try: + job["origin"]["platform"] = "discord" + jobs.update_job(job["id"], {"deliver": "discord"}) + assert delivery_platforms() == ("telegram",) + assert delivery_platforms(job["id"]) == ("discord",) + finally: + exit_cron_execution(token) + + HOSTED_HOOK_PLUGIN = ''' from cron.plugin_api import delivery_platforms @@ -320,27 +358,55 @@ from cron.plugin_api import delivery_platforms def register(ctx): def hook(**kwargs): run = ctx.current_cron_execution() - return {"no_id": delivery_platforms(), "by_id": delivery_platforms(run.job_id)} + firing = ctx.cron_delivery_platforms() + preview = ctx.cron_delivery_platforms(run.job_id) if run is not None else None + return { + "local_no_id": delivery_platforms(), + "firing": firing, + "firing_is_tuple": isinstance(firing, tuple), + "preview": preview, + "preview_is_tuple": isinstance(preview, tuple), + } ctx.register_hook("post_llm_call", hook) ''' @pytest.mark.platforms("any") # the host is a child process -def test_a_hook_in_a_plugin_host_names_the_running_job_through_ctx(tmp_path, monkeypatch): +def test_a_hook_in_a_plugin_host_reads_firing_delivery_platforms_through_ctx(tmp_path, monkeypatch): from hermes_cli.plugins import PluginManager from tests.hermes_cli.test_plugin_host import _home_with_plugins _home_with_plugins(tmp_path / "plugins", monkeypatch, {"hostedcron": HOSTED_HOOK_PLUGIN}, isolation="host") - job = jobs.create_job(prompt="p", schedule="every 1h", name="run", deliver="local", paused=True) + job = jobs.create_job( + prompt="p", schedule="every 1h", name="run", deliver="origin", + origin={"platform": "telegram", "chat_id": TELEGRAM_CHAT}, paused=True, + ) manager = PluginManager() manager.discover_and_load() - token = enter_cron_execution(job, "exec-1", {"source": "direct"}) try: assert manager._plugins["hostedcron"].error is None - # The host process has no run bound; the ctx call is answered by this process, which has. - assert manager.invoke_hook("post_llm_call", session_id="s") == [{"no_id": None, "by_id": []}] + token = enter_cron_execution(job, "exec-1", {"source": "direct"}) + try: + jobs.update_job(job["id"], {"deliver": "local"}) + # The host process has no run bound; ctx.cron_delivery_platforms() runs in the gateway + # and returns the firing run's platforms (as a tuple) even after the saved job was edited. + assert manager.invoke_hook("post_llm_call", session_id="s") == [{ + "local_no_id": None, + "firing": ["telegram"], + "firing_is_tuple": True, + "preview": [], + "preview_is_tuple": True, + }] + finally: + exit_cron_execution(token) + assert manager.invoke_hook("post_llm_call", session_id="s") == [{ + "local_no_id": None, + "firing": None, + "firing_is_tuple": False, + "preview": None, + "preview_is_tuple": False, + }] finally: - exit_cron_execution(token) manager.unload() manager._plugin_host().shutdown() @@ -371,17 +437,40 @@ def test_result_holds_only_platform_names(home_channels): def test_plugin_importing_the_module_gets_no_private_import_warning(tmp_path): + from cron.plugin_api import CronSchedulerRegistrationError as PublicRegError + + assert PublicRegError is CronSchedulerRegistrationError plugin = tmp_path / "follow_up" plugin.mkdir() (plugin / "plugin.yaml").write_text( yaml.safe_dump({"name": "follow_up", "version": "1.0.0", "description": "x"}), encoding="utf-8") Path(plugin / "__init__.py").write_text( - "from cron.plugin_api import ensure_named_job, delivery_platforms, AmbiguousJobReference\n" + "from cron.plugin_api import (\n" + " AmbiguousJobReference, CronSchedulerRegistrationError, delivery_platforms, ensure_named_job,\n" + ")\n" "def register(ctx):\n" - " return ensure_named_job, delivery_platforms, AmbiguousJobReference\n", + " return ensure_named_job, delivery_platforms, AmbiguousJobReference, CronSchedulerRegistrationError\n", encoding="utf-8") report = validate_plugin_dir(plugin) assert report.ok, report.failures assert not [w for w in report.warnings if w.startswith("private core imports")] + + +def test_ctx_cron_delivery_platforms_in_process(home_channels): + from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest + + ctx = PluginContext(PluginManifest(name="demo"), PluginManager()) + job = jobs.create_job(prompt="p", schedule="every 1h", name="run", deliver="telegram") + assert ctx.cron_delivery_platforms() is None + assert ctx.cron_delivery_platforms(job["id"]) == ("telegram",) + + token = enter_cron_execution(job, "exec-1", {"source": "direct"}) + try: + jobs.update_job(job["id"], {"deliver": "local"}) + assert ctx.cron_delivery_platforms() == ("telegram",) + assert ctx.cron_delivery_platforms(job["id"]) == () + finally: + exit_cron_execution(token) + assert ctx.cron_delivery_platforms() is None diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md index f116245abf..5ad7e798a2 100644 --- a/website/docs/developer-guide/plugins/index.md +++ b/website/docs/developer-guide/plugins/index.md @@ -2392,20 +2392,19 @@ def register(ctx): - `name` must be a non-empty string with no leading or trailing whitespace; cron could not find any other name again. Anything else raises `ValueError` and nothing is created. - Disabled jobs count. Two or more jobs with that name raise `AmbiguousJobReference` (importable from the same module) and nothing is created. - An existing enabled job has its trigger registered with the active scheduler provider again. Its prompt and schedule are not updated. -- A new job is created and registered the way `hermes cron add` does it. When registration fails, for a new job or an existing one, the call raises the error `hermes cron add` raises for it: a `RuntimeError` whose `.job` is the saved job and `.cause` the provider's error. The job is already saved: call `ensure_named_job` again and it registers that job instead of creating a second one. +- A new job is created and registered the way `hermes cron add` does it. When registration fails, for a new job or an existing one, the call raises `CronSchedulerRegistrationError` (importable from the same module): a `RuntimeError` whose `.job` is the saved job and `.cause` the provider's error. The job is already saved: call `ensure_named_job` again and it registers that job instead of creating a second one. - The lookup and the create are not atomic across processes. If your plugin can call it from two places at once, serialize those calls yourself (a file lock, for example). -`delivery_platforms(job_id=None, *, home=None)` returns the platforms cron would deliver the job's output to right now, as a tuple of lower-cased names in cron's order, each once. `()` means the job delivers nowhere (`local`). It answers for the job's normal delivery (`deliver`); a `failure_deliver` override, which routes failure notices, is not consulted. `None` means no stored job has that id, or, with no `job_id`, that no cron run is bound where the code runs (see `ctx.current_cron_execution()` above). A hook of a plugin running in a plugin host (`plugins.isolation: host`) has no run bound in its own process, so name the job there: `run = ctx.current_cron_execution()`, then `delivery_platforms(run.job_id)`, which works in both modes. The answer is the stored job's: an edit saved while a run is in flight shows up here, though that run still delivers with the settings it started with. It uses cron's own resolver, so `all`, the `origin` fallback to a home channel and `bot-chat` follow cron's rules. It returns no chat ids, thread ids or tokens. Use it to skip a notification of your own when cron already delivers the output to your platform. It does the work cron does when it delivers: for `all`, that reads the gateway config once for each platform whose home channel is not set in the environment. Call it once per run and keep the answer. +`ctx.cron_delivery_platforms(job_id=None)` and `delivery_platforms(job_id=None, *, home=None)` return the platforms cron would deliver the job's output to right now, as a tuple of lower-cased names in cron's order, each once. `()` means the job delivers nowhere (`local`). They answer for the job's normal delivery (`deliver`); a `failure_deliver` override, which routes failure notices, is not consulted. With `job_id=None`, they answer for the firing cron run using the settings that run started with — edits or deletions saved to the job store mid-run do not change the answer — and return `None` outside a cron run (or in a delegated child). Passing an explicit `job_id` previews the saved job currently in the store (returning `None` when no stored job has that id). Under `plugins.isolation: host`, a hook runs in the plugin host process where no cron run is bound, so hooks call `ctx.cron_delivery_platforms()` — which runs in the gateway in the calling hook's context and works in both isolation modes. Use `delivery_platforms(job_id, home=...)` when code has no `ctx` or targets another profile. They use cron's own resolver, so `all`, the `origin` fallback to a home channel and `bot-chat` follow cron's rules. They return no chat ids, thread ids or tokens. Use them to skip a notification of your own when cron already delivers the output to your platform. They do the work cron does when it delivers: for `all`, that reads the gateway config once for each platform whose home channel is not set in the environment. Call once per run and keep the answer. -Both take `home`: a profile's Hermes home, read the way Hermes reads a home path (`~` and environment variables are expanded). The call then runs with that profile's home, cron store, secrets (its `.env`, so its home channels too) and settings (its time zone for a schedule), and yours are restored afterwards, also when it raises. The secrets are read from that profile's own files, also when you name the profile that is already active. For a profile other than the process's own that configures an external secret source, the first call runs that source, as Hermes does when it starts work for that profile. For the process's own profile the call runs no source: it reads the profile's `.env` and the external values this process has already loaded, so a standalone process that has not loaded them does not see them. A `home` that is not an existing directory is never created: `ensure_named_job` raises `FileNotFoundError` and `delivery_platforms` returns `None`. A hosted activity cannot act for a profile, so a call that has to bind `home` raises there. `home=None` uses the active profile. +Both `cron.plugin_api` functions take `home`: a profile's Hermes home, read the way Hermes reads a home path (`~` and environment variables are expanded). The call then runs with that profile's home, cron store, secrets (its `.env`, so its home channels too) and settings (its time zone for a schedule), and yours are restored afterwards, also when it raises. The secrets are read from that profile's own files, also when you name the profile that is already active. For a profile other than the process's own that configures an external secret source, the first call runs that source, as Hermes does when it starts work for that profile. For the process's own profile the call runs no source: it reads the profile's `.env` and the external values this process has already loaded, so a standalone process that has not loaded them does not see them. A `home` that is not an existing directory is never created: `ensure_named_job` raises `FileNotFoundError` and `delivery_platforms` returns `None`. A hosted activity cannot act for a profile, so a call that has to bind `home` raises there. `home=None` uses the active profile. ```python -from cron.plugin_api import AmbiguousJobReference, delivery_platforms, ensure_named_job +from cron.plugin_api import AmbiguousJobReference, ensure_named_job def register(ctx): def on_post_llm_call(**kwargs): - run = ctx.current_cron_execution() # answers in a plugin host too - if run is not None and "push" in (delivery_platforms(run.job_id) or ()): + if "push" in (ctx.cron_delivery_platforms() or ()): return # cron delivers this run's output through push already try: ensure_named_job("follow-up", prompt="Check on the deploy.", schedule="in 30m")