Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 5 additions & 7 deletions cron/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2971,13 +2971,8 @@ def run_job(

agent = None

# Mark this as a cron session so the approval system can apply cron_mode.
# This env var is process-wide and persists for the lifetime of the
# scheduler process — every job this process runs is a cron job.
os.environ["HERMES_CRON_SESSION"] = "1"

# Use ContextVars for per-job session/delivery state so parallel jobs
# don't clobber each other's targets (os.environ is process-global).
# Use ContextVars for per-job session/delivery and approval state so
# parallel cron jobs cannot contaminate live gateway turns.
from gateway.session_context import set_session_vars, clear_session_vars, _VAR_MAP

# Cron execution is an internal scheduler context, not a live inbound
Expand Down Expand Up @@ -3019,6 +3014,9 @@ def run_job(
# inline/synchronous path, so results return within the job's own turn.
# See declare_stateless_channel(). Upstream: #53027, #63142.
async_delivery=False,
# Cron approval state must be task-local; a process-global env flag
# contaminates later Telegram/API turns hosted by the same gateway.
cron_session=True,
)
_cron_delivery_vars = (
"HERMES_CRON_AUTO_DELIVER_PLATFORM",
Expand Down
5 changes: 5 additions & 0 deletions gateway/session_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ def session_context_engaged() -> bool:
_CRON_AUTO_DELIVER_PLATFORM: ContextVar = ContextVar("HERMES_CRON_AUTO_DELIVER_PLATFORM", default=_UNSET)
_CRON_AUTO_DELIVER_CHAT_ID: ContextVar = ContextVar("HERMES_CRON_AUTO_DELIVER_CHAT_ID", default=_UNSET)
_CRON_AUTO_DELIVER_THREAD_ID: ContextVar = ContextVar("HERMES_CRON_AUTO_DELIVER_THREAD_ID", default=_UNSET)
_CRON_SESSION: ContextVar = ContextVar("HERMES_CRON_SESSION", default=_UNSET)

_VAR_MAP = {
"HERMES_SESSION_PLATFORM": _SESSION_PLATFORM,
Expand All @@ -135,6 +136,7 @@ def session_context_engaged() -> bool:
"HERMES_CRON_AUTO_DELIVER_PLATFORM": _CRON_AUTO_DELIVER_PLATFORM,
"HERMES_CRON_AUTO_DELIVER_CHAT_ID": _CRON_AUTO_DELIVER_CHAT_ID,
"HERMES_CRON_AUTO_DELIVER_THREAD_ID": _CRON_AUTO_DELIVER_THREAD_ID,
"HERMES_CRON_SESSION": _CRON_SESSION,
}


Expand Down Expand Up @@ -168,6 +170,7 @@ def set_session_vars(
cwd: str = "",
async_delivery: bool = True,
ui_session_id: str = "",
cron_session: bool = False,
) -> list:
"""Set all session context variables and return reset tokens.

Expand Down Expand Up @@ -203,6 +206,7 @@ def set_session_vars(
_SESSION_MESSAGE_ID.set(message_id),
_SESSION_PROFILE.set(profile),
_SESSION_ASYNC_DELIVERY.set(bool(async_delivery)),
_CRON_SESSION.set("1" if cron_session else ""),
]
try:
from agent.runtime_cwd import set_session_cwd
Expand Down Expand Up @@ -237,6 +241,7 @@ def clear_session_vars(tokens: list) -> None:
_SESSION_UI_SESSION_ID,
_SESSION_MESSAGE_ID,
_SESSION_PROFILE,
_CRON_SESSION,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding this marker to the generic clear list makes clear_session_vars() set it to "". get_session_env() treats that explicit empty value as authoritative, so a later legacy HERMES_CRON_SESSION=1 environment fallback in the same context is ignored. Keep a token from the job-local marker binding and reset it in run_job()'s finally instead.

):
var.set("")
# Reset async-delivery capability to the "never set" sentinel rather than a
Expand Down
6 changes: 3 additions & 3 deletions tests/tools/test_cron_approval_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ def test_cron_with_telegram_origin_uses_cron_mode_not_gateway(self, monkeypatch)
monkeypatch.delenv("HERMES_EXEC_ASK", raising=False)

from gateway.session_context import set_session_vars, clear_session_vars
tokens = set_session_vars(platform="telegram", chat_id="123")
tokens = set_session_vars(platform="telegram", chat_id="123", cron_session=True)
try:
from unittest.mock import patch as mock_patch
with mock_patch("tools.approval._get_cron_approval_mode", return_value="deny"):
Expand All @@ -402,7 +402,7 @@ def test_cron_with_telegram_origin_approve_mode_allows(self, monkeypatch):
monkeypatch.delenv("HERMES_EXEC_ASK", raising=False)

from gateway.session_context import set_session_vars, clear_session_vars
tokens = set_session_vars(platform="discord", chat_id="456")
tokens = set_session_vars(platform="discord", chat_id="456", cron_session=True)
try:
from unittest.mock import patch as mock_patch
with mock_patch("tools.approval._get_cron_approval_mode", return_value="approve"):
Expand All @@ -422,7 +422,7 @@ def test_cron_with_telegram_origin_combined_guard_uses_cron_mode(self, monkeypat
monkeypatch.delenv("HERMES_EXEC_ASK", raising=False)

from gateway.session_context import set_session_vars, clear_session_vars
tokens = set_session_vars(platform="telegram", chat_id="789")
tokens = set_session_vars(platform="telegram", chat_id="789", cron_session=True)
try:
from unittest.mock import patch as mock_patch
with mock_patch("tools.approval._get_cron_approval_mode", return_value="deny"):
Expand Down
30 changes: 30 additions & 0 deletions tests/tools/test_cron_context_isolation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Regression tests for cron approval state isolation in long-lived gateways."""

from gateway.session_context import clear_session_vars, reset_session_vars, set_session_vars
from tools.approval import _is_cron_session, _is_gateway_approval_context


def test_gateway_context_masks_stale_process_cron_flag(monkeypatch):
"""A cron run must not make later Telegram turns look non-interactive."""
monkeypatch.setenv("HERMES_CRON_SESSION", "1")
monkeypatch.setenv("HERMES_GATEWAY_SESSION", "1")
tokens = set_session_vars(platform="telegram", cron_session=False)
try:
assert _is_cron_session() is False
assert _is_gateway_approval_context() is True
finally:
clear_session_vars(tokens)
reset_session_vars()


def test_cron_context_is_task_local_without_process_env(monkeypatch):
"""Cron approval mode works without mutating process-global os.environ."""
monkeypatch.delenv("HERMES_CRON_SESSION", raising=False)
monkeypatch.setenv("HERMES_GATEWAY_SESSION", "1")
tokens = set_session_vars(platform="", cron_session=True)
try:
assert _is_cron_session() is True
assert _is_gateway_approval_context() is False
finally:
clear_session_vars(tokens)
reset_session_vars()
19 changes: 15 additions & 4 deletions tools/approval.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,17 @@ def _get_session_platform() -> str:
return os.getenv("HERMES_SESSION_PLATFORM", "") or ""


def _is_cron_session() -> bool:
"""Return task-local cron state, falling back to env for legacy entrypoints."""
try:
from gateway.session_context import get_session_env

value = get_session_env("HERMES_CRON_SESSION", "")
return str(value).lower() in {"1", "true", "yes", "on"}
except Exception:
return env_var_enabled("HERMES_CRON_SESSION")


def _is_gateway_approval_context() -> bool:
"""True when this call is inside a gateway/API session.

Expand All @@ -238,7 +249,7 @@ def _is_gateway_approval_context() -> bool:
fall through to the gateway branch would submit a pending approval
with no listener and block the job indefinitely.
"""
if env_var_enabled("HERMES_CRON_SESSION"):
if _is_cron_session():
return False
if env_var_enabled("HERMES_GATEWAY_SESSION"):
return True
Expand Down Expand Up @@ -2714,7 +2725,7 @@ def _run_approval_gate(

if not is_cli and not is_gateway:
# Cron sessions: respect cron_mode config
if env_var_enabled("HERMES_CRON_SESSION"):
if _is_cron_session():
if _get_cron_approval_mode() == "deny":
return {
"approved": False,
Expand Down Expand Up @@ -3242,7 +3253,7 @@ def check_all_command_guards(command: str, env_type: str,
# flows, we do not block on approvals and we skip external guard work.
if not is_cli and not is_gateway and not is_ask:
# Cron sessions: respect cron_mode config
if env_var_enabled("HERMES_CRON_SESSION"):
if _is_cron_session():
if _get_cron_approval_mode() == "deny":
# Run detection to get a description for the block message
is_dangerous, _pk, description = detect_dangerous_command(command)
Expand Down Expand Up @@ -3678,7 +3689,7 @@ def check_execute_code_guard(code: str, env_type: str,
is_ask = env_var_enabled("HERMES_EXEC_ASK")

# Cron: no user is present to approve arbitrary code.
if env_var_enabled("HERMES_CRON_SESSION"):
if _is_cron_session():
if _get_cron_approval_mode() == "deny":
return {
"approved": False,
Expand Down