execution_identity.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """Which cron execution the current code runs inside, for plugins (``ctx.current_cron_execution()``).
  2. The scheduler binds it once it has won the execution's ``claimed`` → ``running`` transition (or a
  3. restart-safe worker adopted it) and resets it when the fire ends. It is a ContextVar, so it follows
  4. the agent onto the threads the scheduler already runs it on via ``contextvars.copy_context()`` and
  5. never leaks to another concurrently firing job or profile. Model output cannot reach it: tool
  6. subprocesses do not share the interpreter. Delegated children read ``None`` — they are not the
  7. scheduled occurrence.
  8. """
  9. from __future__ import annotations
  10. from contextvars import ContextVar, Token
  11. from dataclasses import dataclass
  12. from typing import Any, Mapping, Optional
  13. @dataclass(frozen=True)
  14. class CronExecution:
  15. job_id: str
  16. job_name: str
  17. execution_id: str
  18. source: str # "builtin" (ticker), "direct" (manual run / dashboard Run now), provider name...
  19. scheduled_instant: Optional[str] # the occurrence fired; None for an off-schedule run
  20. started_at: Optional[str]
  21. profile: str
  22. _CURRENT: ContextVar[Optional[CronExecution]] = ContextVar("hermes_cron_execution", default=None)
  23. def enter_cron_execution(job: Mapping[str, Any], execution_id: str, record: Mapping[str, Any]) -> Token:
  24. """Bind this fire's identity from *record*, the ledger row of the running transition."""
  25. from hermes_cli.profiles import current_profile_name
  26. return _CURRENT.set(CronExecution(
  27. job_id=str(job["id"]),
  28. job_name=str(job.get("name") or job["id"]),
  29. execution_id=str(execution_id),
  30. source=str(record.get("source") or ""),
  31. scheduled_instant=record.get("scheduled_instant"),
  32. started_at=record.get("started_at"),
  33. profile=current_profile_name("default") or "default",
  34. ))
  35. def exit_cron_execution(token: Optional[Token]) -> None:
  36. if token is not None:
  37. _CURRENT.reset(token)
  38. def current_cron_execution() -> Optional[CronExecution]:
  39. from agent.delegation_context import is_delegated_child_context
  40. return None if is_delegated_child_context() else _CURRENT.get()