Skip to content

The agent that grows with you

feat(plugins): ctx.current_cron_execution() tells a plugin which cron run it is in

Teknium61f8365da756
diff --git a/cron/execution_identity.py b/cron/execution_identity.py
new file mode 100644
index 00000000000..f13a61831ca
--- /dev/null
+++ b/cron/execution_identity.py
@@ -0,0 +1,54 @@
+"""Which cron execution the current code runs inside, for plugins (``ctx.current_cron_execution()``).
+
+The scheduler binds it once it has won the execution's ``claimed`` → ``running`` transition (or a
+restart-safe worker adopted it) and resets it when the fire ends. It is a ContextVar, so it follows
+the agent onto the threads the scheduler already runs it on via ``contextvars.copy_context()`` and
+never leaks to another concurrently firing job or profile. Model output cannot reach it: tool
+subprocesses do not share the interpreter. Delegated children read ``None`` — they are not the
+scheduled occurrence.
+"""
+from __future__ import annotations
+
+from contextvars import ContextVar, Token
+from dataclasses import dataclass
+from typing import Any, Mapping, Optional
+
+
+@dataclass(frozen=True)
+class CronExecution:
+ job_id: str
+ job_name: str
+ execution_id: str
+ source: str # "builtin" (ticker), "direct" (manual run / dashboard Run now), provider name...
+ scheduled_instant: Optional[str] # the occurrence fired; None for an off-schedule run
+ started_at: Optional[str]
+ profile: str
+
+
+_CURRENT: ContextVar[Optional[CronExecution]] = 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(
+ job_id=str(job["id"]),
+ job_name=str(job.get("name") or job["id"]),
+ execution_id=str(execution_id),
+ source=str(record.get("source") or ""),
+ scheduled_instant=record.get("scheduled_instant"),
+ started_at=record.get("started_at"),
+ profile=current_profile_name("default") or "default",
+ ))
+
+
+def exit_cron_execution(token: Optional[Token]) -> None:
+ if token is not None:
+ _CURRENT.reset(token)
+
+
+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()
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 4082d766f35..dcf8566e897 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -541,6 +541,7 @@ from cron.jobs import (
_ensure_cron_dir, advance_next_runs, claim_dispatch, claim_job_for_fire, fire_claim_fence,
clear_run_claim, get_due_jobs, heartbeat_fire_claim, heartbeat_run_claim, mark_job_run,
save_job_output, self_removal_delivery_allowed, self_removal_delivery_scope, use_cron_store)
+from cron.execution_identity import enter_cron_execution, exit_cron_execution
from cron.executions import (
_TERMINAL_STATES, HANDOFF_ADOPTION_GRACE_SECONDS, create_execution, finish_execution,
get_execution, mark_execution_handoff_pending, mark_execution_running,
@@ -3326,6 +3327,16 @@ def _fire_secret_scope():
_reset_fire_secret_scope(tokens)
+def _start_owned_run(job: dict, execution_id: str) -> "Optional[contextvars.Token]":
+ """Win the run's ``claimed`` → ``running`` CAS and bind its cron identity; ``None`` when the run
+ lost ownership first. A restart-safe worker already won it by adopting the row."""
+ if os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_id:
+ record = get_execution(execution_id)
+ elif (record := mark_execution_running(execution_id)) is None:
+ return None
+ return enter_cron_execution(job, execution_id, record or {})
+
+
def _run_one_job_body(
job: dict, *, adapters=None, loop=None, verbose: bool = False,
extra_prompt: Optional[str] = None, claim_lost: Optional[_CancelEventLike] = None,
@@ -3346,6 +3357,7 @@ def _run_one_job_body(
_fire_scope_tokens = None
_terminal_scope_token = None
+ _identity_token = None
try:
# get_secret() fails closed outside a scope; the ticker thread has none. Delivery adapters
# resolve credentials, so the scope must span delivery too (reset in the outer finally) —
@@ -3368,38 +3380,22 @@ def _run_one_job_body(
# Claimed durably before dispatch; becomes running only right before the actual run.
# Detached workers transition to running while adopting; in-process paths must win the
# claimed->running CAS here before any user script or agent side effect may begin.
- external_owner = os.environ.get("_HERMES_CRON_EXTERNAL_WORKER") == execution_id
- if not external_owner and mark_execution_running(execution_id) is None:
+ # The identity plugins read via ctx.current_cron_execution() is bound only on that win.
+ _identity_token = _start_owned_run(job, execution_id)
+ if _identity_token is None:
logger.warning("Cron job %s lost execution ownership before start; skipping", job["id"])
return True
- # Same for terminal policy (gateway/run.py _profile_runtime_scope): else the ticker reads
- # process-global TERMINAL_* env a concurrent profile pinned. Resolution failure installs a
- # refusal scope — terminal execution raises instead of using the launch process's policy.
- # Same isolation for terminal settings (third profile seam; see gateway/run.py
- # _profile_runtime_scope): installs the firing profile's COMPLETE terminal policy for this fire —
- # run, delivery, and bookkeeping — resetting in this function's finally alongside the secret scope.
- # See #68559.
- # Bind the profile's COMPLETE terminal policy for the agent build (fail-closed: malformed policy →
- # refusal scope) so _make_agent's terminal probing / cwd hints resolve the routed profile, never the
- # launch process (#98581 class).
- # Same authoritative terminal policy the gateway binds per turn (#68559): a docker-configured
- # dashboard profile must never resolve the launch process's pinned env.
- # Fourth profile seam: bind the session profile's COMPLETE terminal policy for this turn
- # (dashboard/TUI analogue of the gateway's per-turn scope). #98581's unified-desktop reproduction
- # ran a docker-configured profile on the host because terminal_tool read the launch process's pinned
- # env.
+ # Bind the firing profile's COMPLETE terminal policy for this fire — agent build, run, delivery
+ # and bookkeeping (gateway/run.py _profile_runtime_scope does the same per turn) — else the
+ # ticker reads process-global TERMINAL_* env another profile pinned (#68559, #98581). A
+ # malformed policy installs a refusal scope: terminal execution raises instead.
from tools.terminal_scope import (
install_profile_terminal_scope)
_terminal_scope_token = install_profile_terminal_scope(_get_hermes_home())
- # Defer agent teardown until AFTER delivery; closing first races the live send against a
- # torn-down async client. run_job hands the agent back via this list.
- # Defer the cron agent's async-resource teardown until AFTER delivery. run_job normally closes the
- # agent (and reaps stale async clients) in its finally block; doing that before _deliver_result runs
- # means the live send races a torn-down async client (#58720). Passing a holder list makes run_job
- # hand the agent back instead, and we tear it down below once delivery is done. Defense-in-depth
- # alongside the interpreter-shutdown guard in _deliver_result.
+ # Defer agent teardown until AFTER delivery: closing first races the live send against a
+ # torn-down async client (#58720). run_job hands the agent back via this list instead.
_deferred_agents: list = []
def _teardown_deferred() -> None:
@@ -3548,6 +3544,7 @@ def _run_one_job_body(
finally:
# Function-level on purpose: must scope delivery, deferred teardown, claim-loss handling and
# bookkeeping — not just run_job. Do not move into the run block's finally.
+ exit_cron_execution(_identity_token)
if _fire_scope_tokens is not None:
_reset_fire_secret_scope(_fire_scope_tokens)
if _terminal_scope_token is not None:
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 6d9a5e5214d..892a55fff20 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -249,10 +249,7 @@ class PluginContext:
def has_plugin(self, plugin_id: str) -> bool:
"""Return True when another plugin is loaded and enabled (runtime probe for advisory
- ``requires_plugins``). Matches on registry key or manifest name.
-
- See #64165.
- """
+ ``requires_plugins``, #64165). Matches on registry key or manifest name."""
return any(
loaded.enabled and (key == plugin_id or loaded.manifest.name == plugin_id)
for key, loaded in self._manager._plugins.items()
@@ -311,8 +308,7 @@ class PluginContext:
def _track(
self, kind: str, key: str, release: Callable[[], None], *, persistent: bool = False,
) -> PluginRegistration:
- """Record host-owned cleanup for a successful registration (see
- :meth:`PluginManager._track_registration` for ``persistent``)."""
+ """Record host-owned cleanup for a registration (``persistent``: see ``_track_registration``)."""
return self._manager._track_registration(self.manifest, kind, key, release, persistent=persistent)
def _track_replacement(
@@ -341,8 +337,7 @@ class PluginContext:
self, kind: str, key: str, mapping: Dict[str, Any], entry: Any, log_fmt: str, *log_args: Any,
previous: Any = _UNSET,
) -> PluginRegistration:
- """Shared tail of the manager-mapping registrars: store + lease the entry, then log
- ``log_fmt % (plugin name, *log_args)`` at debug."""
+ """Store + lease a manager-mapping entry, then debug-log ``log_fmt % (plugin name, *log_args)``."""
handle = self._track_mapping_entry(kind, key, mapping, entry, previous)
logger.debug(log_fmt, self.manifest.name, *log_args)
return handle
@@ -406,6 +401,11 @@ class PluginContext:
except Exception:
return "default"
+ def current_cron_execution(self) -> Any:
+ """The cron run executing now (``cron.execution_identity.CronExecution``), else ``None``."""
+ from cron.execution_identity import current_cron_execution
+ return current_cron_execution()
+
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_execution_identity.py b/tests/cron/test_cron_execution_identity.py
new file mode 100644
index 00000000000..a2082f6322d
--- /dev/null
+++ b/tests/cron/test_cron_execution_identity.py
@@ -0,0 +1,99 @@
+"""Plugins can tell which cron execution they run inside (#130722)."""
+import json
+import os
+import subprocess
+import sys
+from datetime import timedelta
+from pathlib import Path
+
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall, write_hermes_home
+
+_PLUGIN = '''
+import dataclasses, json, os
+from pathlib import Path
+
+CTX = None
+
+def _record(**kwargs):
+ ident = CTX.current_cron_execution()
+ out = Path(os.environ["HERMES_HOME"]) / "seen.json"
+ out.write_text(json.dumps({"tool": kwargs.get("tool_name"),
+ "identity": dataclasses.asdict(ident) if ident else None}))
+
+def register(ctx):
+ global CTX
+ CTX = ctx
+ ctx.register_hook("pre_tool_call", _record)
+'''
+
+_TICK = '''
+import json, sys
+from cron import scheduler
+from cron.executions import list_executions
+from hermes_cli.plugins import get_plugin_manager
+scheduler.tick(verbose=False, sync=True)
+ctx = get_plugin_manager()._plugins["cron-identity-probe"].module.CTX
+print(json.dumps({"outside": ctx.current_cron_execution(), "profile": ctx.profile_name,
+ "executions": list_executions(job_id="probe")}, default=str))
+'''
+
+
+def test_tool_hook_in_a_ticked_job_sees_its_execution_and_none_outside(tmp_path):
+ from hermes_time import now
+
+ home = tmp_path / "home"
+ plugin_dir = home / "plugins" / "cron-identity-probe"
+ plugin_dir.mkdir(parents=True)
+ (plugin_dir / "plugin.yaml").write_text("name: cron-identity-probe\nversion: 0.0.1\n")
+ (plugin_dir / "__init__.py").write_text(_PLUGIN)
+ note = home / "note.txt"
+ with FakeLLMServer([ToolCall("read_file", {"path": str(note)}), Text("done")]) as srv:
+ write_hermes_home(home, srv.base_url,
+ extra_config="plugins:\n enabled: [cron-identity-probe]\n")
+ note.write_text("hello\n")
+ (home / "cron").mkdir()
+ (home / "cron" / "jobs.json").write_text(json.dumps({"jobs": [{
+ "id": "probe", "name": "identity probe", "prompt": "read the note",
+ "schedule": {"kind": "interval", "minutes": 240},
+ "next_run_at": (now() - timedelta(minutes=1)).isoformat(),
+ "enabled": True, "state": "scheduled", "deliver": "local",
+ "repeat": {"times": None, "completed": 0}}]}))
+ env = {k: v for k, v in os.environ.items()
+ if not k.startswith(("HERMES_", "_HERMES_"))
+ and not k.endswith(("_API_KEY", "_TOKEN"))}
+ env.update(HERMES_HOME=str(home), PYTHONPATH=str(Path(__file__).resolve().parents[2]))
+ result = subprocess.run([sys.executable, "-c", _TICK], env=env, stdin=subprocess.DEVNULL,
+ capture_output=True, text=True, timeout=180)
+ assert result.returncode == 0, result.stdout + result.stderr
+ report = json.loads(result.stdout.strip().splitlines()[-1])
+ seen = json.loads((home / "seen.json").read_text())
+ (execution,) = report["executions"]
+
+ assert seen["tool"] == "read_file"
+ ident = seen["identity"]
+ assert ident is not None, "pre_tool_call fired inside a cron run saw no cron identity"
+ assert ident["job_id"] == "probe"
+ assert ident["job_name"] == "identity probe"
+ assert ident["execution_id"] == execution["id"]
+ assert ident["source"] == execution["source"] == "builtin"
+ assert ident["scheduled_instant"] == execution["scheduled_instant"] is not None
+ assert ident["started_at"] == execution["started_at"]
+ assert ident["profile"] == report["profile"]
+ assert report["outside"] is None
+
+
+def test_identity_is_scoped_and_not_inherited_by_delegated_children():
+ from agent.delegation_context import delegated_child_context
+ from cron.execution_identity import (
+ current_cron_execution, enter_cron_execution, exit_cron_execution)
+
+ record = {"source": "builtin", "scheduled_instant": None, "started_at": "2026-10-04T00:00:00"}
+ assert current_cron_execution() is None
+ token = enter_cron_execution({"id": "j", "name": "J"}, "exec-1", record)
+ try:
+ assert current_cron_execution().execution_id == "exec-1"
+ with delegated_child_context("child"):
+ assert current_cron_execution() is None
+ finally:
+ exit_cron_execution(token)
+ assert current_cron_execution() is None
diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md
index d35c2c422e7..f81f15384a0 100644
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@ -1463,6 +1463,30 @@ def register(ctx):
For running a full `hermes <subcommand>` (e.g. `hermes kanban show`), shell out with the `terminal` tool via `ctx.dispatch_tool("terminal", {"command": "hermes kanban show ..."})` — there is no in-process slash-command bridge for headless worker sessions, and tools are the supported way to drive Hermes from a hook.
+### Know which cron run you are in
+
+`ctx.current_cron_execution()` returns the scheduled run the current code executes inside, or `None` outside cron. It works from any hook that fires during the run (`pre_tool_call`, `post_tool_call`, `pre_llm_call`, ...) and from tool handlers. The value is a frozen `CronExecution`:
+
+| Field | Meaning |
+|---|---|
+| `job_id`, `job_name` | The cron job. |
+| `execution_id` | This run's row in the executions ledger (`hermes cron runs`). |
+| `source` | Which path fired the run: `"builtin"` (the built-in scheduler), `"direct"` (a run fired outside it, e.g. `hermes cron run`), or an external scheduler's name. |
+| `scheduled_instant` | The schedule occurrence this run fires. `None` for a manual or other off-schedule run, so check this field to tell a scheduled run from a manual one. |
+| `started_at` | When the run started. |
+| `profile` | The profile that owns the job. |
+
+The scheduler sets it only after the run has won its execution claim, and clears it when the run ends. It is per-run, so two jobs or profiles firing at the same time never see each other's value. The model cannot forge it: hook arguments come from Hermes, and tool subprocesses (terminal, `execute_code`) run in a separate interpreter. Subagents spawned with `delegate_task` get `None` because they are not the scheduled run itself.
+
+```python
+def register(ctx):
+ def guard(*, tool_name, args, **kw):
+ run = ctx.current_cron_execution()
+ if tool_name == "deploy" and (run is None or run.scheduled_instant is None):
+ return {"action": "block", "message": "deploy only runs from its scheduled cron job"}
+ ctx.register_hook("pre_tool_call", guard)
+```
+
### Handle Slack Block Kit button clicks
Plugins that post Block Kit messages with interactive elements (buttons, overflow menus, datepickers, etc.) can register the click handlers directly with the Slack adapter — no monkey-patching of `slack_bolt.AsyncApp` required.