From 76a1ebdb4c14c5cb33e651f604daae21626058b7 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 19:31:14 -0700 Subject: [PATCH] refactor(cron): extract per-target delivery prologue, unify timeout/env/skill-name helpers in scheduler_* modules --- cron/scheduler_delivery.py | 906 ++++++++++++++---------------------- cron/scheduler_preflight.py | 90 ++-- cron/scheduler_prompt.py | 166 +++---- cron/scheduler_script.py | 324 ++++++------- 4 files changed, 580 insertions(+), 906 deletions(-) diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py index ef89a328ba..c2b87e9db3 100644 --- a/cron/scheduler_delivery.py +++ b/cron/scheduler_delivery.py @@ -1,8 +1,8 @@ """Cron delivery: target resolution (origin/home/explicit/bot-chat), transcript mirroring and session seeding, live-adapter / relay / standalone send lanes, and ``_deliver_result``. -Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident -helpers are reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. +Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident helpers are +reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. """ from __future__ import annotations @@ -13,6 +13,7 @@ import contextlib import contextvars import logging import os +import shutil import subprocess import sys from dataclasses import dataclass @@ -32,7 +33,6 @@ _KNOWN_DELIVERY_PLATFORMS = frozenset({ "qqbot", "yuanbao", }) - # Platforms supporting a cron/notification home target -> env var used by gateway config. _HOME_TARGET_ENV_VARS = { "matrix": "MATRIX_HOME_ROOM", @@ -53,9 +53,7 @@ _HOME_TARGET_ENV_VARS = { "whatsapp_cloud": "WHATSAPP_CLOUD_HOME_CHANNEL", } - -# Back-compat: primary env var -> previous name; _get_home_target_chat_id falls back to the legacy -# name when the primary is unset. +# Back-compat: primary env var -> previous name, consulted when the primary is unset. _LEGACY_HOME_TARGET_ENV_VARS = {"QQBOT_HOME_CHANNEL": "QQ_HOME_CHANNEL"} @@ -94,10 +92,9 @@ def _resolve_origin(job: dict) -> Optional[dict]: def _cron_mirror_delivery_enabled(job: dict, cfg: Optional[dict] = None) -> bool: """Whether a cron delivery is also mirrored into the target chat's session transcript. - Default OFF (cron deliveries live only in the job's own session unless opted in). Precedence: - per-job ``attach_to_session`` (bool) → global ``cron.mirror_delivery`` → False. - CARVE-OUT: the ``in_channel`` surface seeds its target session independently of this knob - (the seed IS that feature; in_channel is itself opt-in) — this knob governs only the + Default OFF. Precedence: per-job ``attach_to_session`` (bool) → global ``cron.mirror_delivery`` + → False. CARVE-OUT: the ``in_channel`` surface seeds its target session independently of this + knob (the seed IS that feature; in_channel is itself opt-in) — this knob governs only the default/thread-surface mirror. The mirror uses ``mirror_to_session`` at a turn boundary, so it is alternation- and cache-safe. """ @@ -114,18 +111,15 @@ def _cron_mirror_delivery_enabled(job: dict, cfg: Optional[dict] = None) -> bool def _target_matches_origin(origin: dict, platform_name: str, chat_id: str, thread_id: Optional[str]) -> bool: - """True when a delivery target is the job's own origin conversation. - - Mirroring is scoped to the origin session (guaranteed to exist — the job was created there). - Fan-out targets (``all``, explicit other chats) are broadcasts and deliberately NOT mirrored. - """ + """True when a delivery target is the job's own origin conversation. Mirroring is scoped to + the origin session (guaranteed to exist); fan-out targets are broadcasts, deliberately NOT + mirrored. A pinned origin thread_id must match — a target without it is a different lane.""" if not origin: return False if str(origin.get("platform", "")).lower() != str(platform_name).lower(): return False if str(origin.get("chat_id", "")) != str(chat_id): return False - # A pinned origin thread_id must match — a target without it is a different lane. origin_thread = origin.get("thread_id") return origin_thread is None or str(origin_thread) == str(thread_id or "") @@ -154,8 +148,7 @@ def _target_mirror_eligible( if origin_match is None: origin = _sched._resolve_origin(job) or {} origin_match = _target_matches_origin( - origin, target.get("platform", ""), target.get("chat_id", ""), - target.get("thread_id"), + origin, target.get("platform", ""), target.get("chat_id", ""), target.get("thread_id"), ) if origin_match: return True @@ -164,24 +157,23 @@ def _target_mirror_eligible( # Same precedence as _cron_mirror_delivery_enabled (keep in sync): a per-job False must # beat a global True even for callers that don't pre-merge `global_mirror`. per_job = job.get("attach_to_session") - if isinstance(per_job, bool): - return per_job - return bool(global_mirror) + return per_job if isinstance(per_job, bool) else bool(global_mirror) if resolved_from == "explicit": return job.get("attach_to_session") is True return False def _inchannel_seed_allowed(*, is_dm: bool, user_id: Optional[str]) -> bool: - """Whether the flat in_channel seed may run. - - Group keys are user-isolated (``…:group::``): seeding without a real user_id - creates an orphan session no reply resolves to — worse than no seed. DM keys omit user_id, so - DMs are always seedable; origin-less group targets fall back to the plain mirror. - """ + """Whether the flat in_channel seed may run. Group keys are user-isolated + (``…:group::``): seeding without a real user_id creates an orphan session no + reply resolves to — worse than no seed. DM keys omit user_id, so DMs are always seedable.""" return bool(is_dm or user_id) +def _cron_mirror_message(job: dict, text: str) -> str: + return f"[Cron delivery: {job.get('name') or job.get('id', 'cron')}]\n{text}" + + def _maybe_mirror_cron_delivery( job: dict, platform_name: str, @@ -192,13 +184,11 @@ def _maybe_mirror_cron_delivery( *, enabled: bool = False, ) -> None: - """Best-effort mirror of a cron delivery into the origin chat's session. - - No-op unless ``enabled`` (caller resolves it, scoped to the origin target). Rides the same + """Best-effort mirror of a cron delivery into the origin chat's session. No-op unless + ``enabled`` (caller resolves it, scoped to the origin target). Rides the same ``mirror_to_session`` path as ``send_message``, passing ``user_id`` so user-isolated group chats resolve to the scheduling member. All failures swallowed — a successful delivery must - never be reported failed because the mirror broke. - """ + never be reported failed because the mirror broke.""" if not enabled: return text = (mirror_text or "").strip() @@ -210,13 +200,8 @@ def _maybe_mirror_cron_delivery( # USER role + labelled prefix, NOT assistant: an assistant-role mirror lands # assistant→assistant and breaks strict alternation; consecutive user turns merge safely. ok = mirror_to_session( - platform_name, - str(chat_id), - f"[Cron delivery: {job.get('name') or job.get('id', 'cron')}]\n{text}", - source_label="cron", - thread_id=thread_id, - user_id=user_id, - role="user", + platform_name, str(chat_id), _cron_mirror_message(job, text), + source_label="cron", thread_id=thread_id, user_id=user_id, role="user", ) if ok: logger.info( @@ -225,43 +210,33 @@ def _maybe_mirror_cron_delivery( ) else: logger.debug( - "Job '%s': delivery mirror skipped for %s:%s " - "(no matching gateway session — cold start)", + "Job '%s': delivery mirror skipped for %s:%s (no matching gateway session — cold start)", job.get("id", "?"), platform_name, chat_id, ) except Exception as e: logger.debug( - "Job '%s': delivery mirror failed for %s:%s: %s", - job.get("id", "?"), platform_name, chat_id, e, + "Job '%s': delivery mirror failed for %s:%s: %s", job.get("id", "?"), platform_name, chat_id, e, ) -def _open_continuable_cron_thread( - job: dict, - adapter, - chat_id: str, - loop, -) -> Optional[str]: +def _open_continuable_cron_thread(job: dict, adapter, chat_id: str, loop) -> Optional[str]: """Open a thread for a continuable cron job via ``adapter.create_handoff_thread``. Returns the thread_id, or ``None`` (no thread primitive / failed) = caller falls back to the DM mirror.""" create_thread = getattr(adapter, "create_handoff_thread", None) if not callable(create_thread) or loop is None: return None - task_name = job.get("name") or job.get("id", "cron") - thread_name = f"Hermes — {task_name}" + thread_name = f"Hermes — {job.get('name') or job.get('id', 'cron')}" try: from agent.async_utils import safe_schedule_threadsafe - coro = create_thread(str(chat_id), thread_name) - future = safe_schedule_threadsafe(coro, loop) # type: ignore[arg-type] + future = safe_schedule_threadsafe(create_thread(str(chat_id), thread_name), loop) # type: ignore[arg-type] if future is None: return None new_thread_id = future.result(timeout=30) return str(new_thread_id) if new_thread_id else None except Exception as e: logger.debug( - "Job '%s': create_handoff_thread failed on %s — falling back to " - "DM-session mirror: %s", + "Job '%s': create_handoff_thread failed on %s — falling back to DM-session mirror: %s", job.get("id", "?"), getattr(adapter, "name", "?"), e, ) return None @@ -299,36 +274,22 @@ def _seed_cron_session( # Discord keys in-thread messages with chat_id == thread_id; Slack/Telegram use the # parent channel. seed_chat_id = ( - str(thread_id) - if discord_keys_on_thread and platform_enum == Platform.DISCORD - else str(chat_id) + str(thread_id) if discord_keys_on_thread and platform_enum == Platform.DISCORD else str(chat_id) ) dest_source = SessionSource( - platform=platform_enum, - chat_id=seed_chat_id, - chat_name=chat_name, - chat_type=chat_type, - user_id=user_id, - user_name=user_name, - thread_id=thread_id, + platform=platform_enum, chat_id=seed_chat_id, chat_name=chat_name, chat_type=chat_type, + user_id=user_id, user_name=user_name, thread_id=thread_id, scope_id=str(scope_id) if scope_id else None, ) # Create the row and pass its exact id to the mirror — origin-heuristic rediscovery # bails on populated chats. - _entry = session_store.get_or_create_session(dest_source) - seeded_session_id = getattr(_entry, "session_id", None) + seeded_session_id = getattr(session_store.get_or_create_session(dest_source), "session_id", None) from gateway.mirror import mirror_to_session return mirror_to_session( - platform_name, - str(chat_id), - f"[Cron delivery: {job.get('name') or job.get('id', 'cron')}]\n{text}", - source_label="cron", - thread_id=thread_id, - user_id=user_id, - role="user", - session_id=seeded_session_id, + platform_name, str(chat_id), _cron_mirror_message(job, text), + source_label="cron", thread_id=thread_id, user_id=user_id, role="user", session_id=seeded_session_id, ) @@ -353,12 +314,8 @@ def _seed_cron_thread_session( try: ok = _seed_cron_session( job, adapter, platform_name, chat_id, text, - thread_id=str(thread_id), - chat_type="dm" if is_dm else "thread", - user_id="system:cron", - user_name="Cron", - chat_name=chat_name, - scope_id=scope_id, + thread_id=str(thread_id), chat_type="dm" if is_dm else "thread", + user_id="system:cron", user_name="Cron", chat_name=chat_name, scope_id=scope_id, discord_keys_on_thread=True, ) if ok: @@ -405,10 +362,8 @@ def _seed_cron_channel_session( ok = _seed_cron_session( job, adapter, platform_name, chat_id, text, thread_id=None, # flat — the whole-channel/DM session - chat_type=chat_type, - user_id=str(user_id) if user_id else None, - chat_name=chat_name, - scope_id=scope_id, + chat_type=chat_type, user_id=str(user_id) if user_id else None, + chat_name=chat_name, scope_id=scope_id, ) if ok: logger.info( @@ -431,7 +386,6 @@ def _cron_job_origin_log_suffix(job: dict) -> str: origin = job.get("origin") if not isinstance(origin, dict): return "" - fields = [] for key in ("platform", "chat_id", "thread_id", "source_ip", "remote", "forwarded_for"): value = origin.get(key) @@ -458,69 +412,62 @@ def _plugin_cron_env_var(platform_name: str) -> str: def _is_known_delivery_platform(platform_name: str) -> bool: """Valid cron delivery platform: built-in, or plugin with a ``cron_deliver_env_var``.""" name = platform_name.lower() - if name in _KNOWN_DELIVERY_PLATFORMS: - return True - return bool(_plugin_cron_env_var(name)) + return name in _KNOWN_DELIVERY_PLATFORMS or bool(_plugin_cron_env_var(name)) def _resolve_home_env_var(platform_name: str) -> str: """Env var name for a platform's cron home channel (built-in table, then plugin registry).""" name = platform_name.lower() - env_var = _HOME_TARGET_ENV_VARS.get(name) - if env_var: - return env_var - return _plugin_cron_env_var(name) + return _HOME_TARGET_ENV_VARS.get(name) or _plugin_cron_env_var(name) def _get_config_home_channel(platform_name: str): """Persisted ``HomeChannel`` from gateway config — the canonical store ``/sethome`` writes. - The ``_HOME_CHANNEL`` env var is only a best-effort mirror; relay-fronted platforms - may exist solely in config.yaml, so reading only the env mirror silently drops their delivery. - """ + may exist solely in config.yaml, so reading only the env mirror silently drops their delivery.""" try: from gateway.config import load_gateway_config, Platform - config = load_gateway_config() - platform = Platform(platform_name.lower()) - return config.get_home_channel(platform) + return load_gateway_config().get_home_channel(Platform(platform_name.lower())) except Exception: - logger.debug( - "config home_channel lookup failed for platform %r", - platform_name, exc_info=True, - ) + logger.debug("config home_channel lookup failed for platform %r", platform_name, exc_info=True) return None -def _env_home_target_chat_id(platform_name: str) -> str: - """Home chat id from the env mirror only (no config). +def _home_env_lookup(env_var: str, suffix: str = "", *, strip: bool = False) -> str: + """Value of ````, falling back to the legacy name (same suffix) when unset. Reads via ``get_secret``, not ``os.getenv``: in a multiplex gateway the tick runs with the job-owning profile's secret scope (run_one_job sets it), so this resolves the OWNING profile's - chat id rather than the host process's environ. + value rather than the host process's environ. ``os.getenv`` only if the scope module is missing. """ - env_var = _resolve_home_env_var(platform_name) - if not env_var: - return "" try: from agent.secret_scope import get_secret + + def read(name: str) -> str: + return get_secret(name, "") or "" except Exception: - get_secret = None # type: ignore - if get_secret is not None: - value = get_secret(env_var, "") - if not value: - legacy = _LEGACY_HOME_TARGET_ENV_VARS.get(env_var) - if legacy: - value = get_secret(legacy, "") - return value or "" - value = os.getenv(env_var, "") + def read(name: str) -> str: + return os.getenv(name, "") + + def read_clean(name: str) -> str: + value = read(name) + return value.strip() if strip else value + + value = read_clean(env_var + suffix) if not value: legacy = _LEGACY_HOME_TARGET_ENV_VARS.get(env_var) if legacy: - value = os.getenv(legacy, "") + value = read_clean(legacy + suffix) return value +def _env_home_target_chat_id(platform_name: str) -> str: + """Home chat id from the env mirror only (no config).""" + env_var = _resolve_home_env_var(platform_name) + return _home_env_lookup(env_var) if env_var else "" + + def _get_home_target_chat_id(platform_name: str) -> str: """Home target chat id: env var (first, so operator overrides win) → legacy env var → config.yaml ``home_channel``.""" @@ -528,45 +475,19 @@ def _get_home_target_chat_id(platform_name: str) -> str: if value: return value home = _get_config_home_channel(platform_name) - if home is not None and home.chat_id: - return str(home.chat_id) - return "" + return str(home.chat_id) if home is not None and home.chat_id else "" def _get_home_target_thread_id(platform_name: str) -> Optional[str]: - """Optional thread/topic id for a platform home target. - - Telegram: ``TELEGRAM_CRON_THREAD_ID`` overrides ``TELEGRAM_HOME_CHANNEL_THREAD_ID`` — in topic - mode a root-DM delivery lands in the system-only lobby where the user cannot reply. - """ - env_var = _resolve_home_env_var(platform_name) - try: - from agent.secret_scope import get_secret - except Exception: - get_secret = None # type: ignore - - def _scope_get(name: str) -> str: - if get_secret is None: - return "" - v = get_secret(name, "") - return v if v is not None else "" - + """Optional thread/topic id for a platform home target. Telegram: ``TELEGRAM_CRON_THREAD_ID`` + overrides ``TELEGRAM_HOME_CHANNEL_THREAD_ID`` — in topic mode a root-DM delivery lands in the + system-only lobby where the user cannot reply.""" if platform_name.lower() == "telegram": - cron_thread = _scope_get("TELEGRAM_CRON_THREAD_ID").strip() + cron_thread = _home_env_lookup("TELEGRAM_CRON_THREAD_ID", strip=True) if cron_thread: return cron_thread - if get_secret is not None: - value = _scope_get(f"{env_var}_THREAD_ID").strip() if env_var else "" - if not value and env_var: - legacy = _LEGACY_HOME_TARGET_ENV_VARS.get(env_var) - if legacy: - value = _scope_get(f"{legacy}_THREAD_ID").strip() - else: - value = os.getenv(f"{env_var}_THREAD_ID", "").strip() if env_var else "" - if not value and env_var: - legacy = _LEGACY_HOME_TARGET_ENV_VARS.get(env_var) - if legacy: - value = os.getenv(f"{legacy}_THREAD_ID", "").strip() + env_var = _resolve_home_env_var(platform_name) + value = _home_env_lookup(env_var, "_THREAD_ID", strip=True) if env_var else "" if value: return value # config.yaml fallback only when the chat id also came from config (an env-provided chat id @@ -580,8 +501,7 @@ def _get_home_target_thread_id(platform_name: str) -> Optional[str]: def _iter_home_target_platforms(): """Iterate built-in + plugin platform names that expose a home channel.""" - for name in _HOME_TARGET_ENV_VARS: - yield name + yield from _HOME_TARGET_ENV_VARS with contextlib.suppress(Exception): from hermes_cli.plugins import discover_plugins discover_plugins() # idempotent @@ -617,54 +537,43 @@ def cron_delivery_targets() -> list[dict]: try: from gateway.config import load_gateway_config - gateway_config = load_gateway_config() - connected = {p.value for p in gateway_config.get_connected_platforms()} + connected = {p.value for p in load_gateway_config().get_connected_platforms()} connected |= _relay_fronted_delivery_platforms(connected) except Exception: logger.debug("cron_delivery_targets: gateway config unavailable", exc_info=True) connected = set() for name in _sched._iter_home_target_platforms(): - if name not in connected: + if name not in connected or not _sched._is_known_delivery_platform(name): continue - if not _sched._is_known_delivery_platform(name): - continue - env_var = _resolve_home_env_var(name) - targets.append( - { - "id": name, - "name": name.replace("_", " ").title(), - "home_target_set": bool(_sched._get_home_target_chat_id(name)), - "home_env_var": env_var or None, - } - ) + targets.append({ + "id": name, + "name": name.replace("_", " ").title(), + "home_target_set": bool(_sched._get_home_target_chat_id(name)), + "home_env_var": _resolve_home_env_var(name) or None, + }) # Bot Chat targets: one per local profile (machine-local; no gateway config or home channel). try: from hermes_cli.profiles import list_profile_names for profile_name in list_profile_names(): - targets.append( - { - "id": f"{BOT_CHAT_PLATFORM}:{profile_name}", - "name": f"Bot Chat ({profile_name})", - "home_target_set": True, - "home_env_var": None, - } - ) + targets.append({ + "id": f"{BOT_CHAT_PLATFORM}:{profile_name}", + "name": f"Bot Chat ({profile_name})", + "home_target_set": True, + "home_env_var": None, + }) except Exception: logger.debug("cron_delivery_targets: profile listing unavailable", exc_info=True) return targets def _origin_thread_is_stale(origin: dict) -> bool: - """True when a Slack origin's thread is a stale creation-turn artifact. - - Thread-per-message Slack stamps each top-level message id as the session thread (a KEY, not a - location); old jobs carry it as ``origin.thread_id``. Heuristic: if the origin chat IS the Slack - home chat, the pinned thread is that artifact and delivery goes top-level (or to the home - target's thread). Non-home chats keep their threads. - """ + """True when a Slack origin's thread is a stale creation-turn artifact. Thread-per-message + Slack stamps each top-level message id as the session thread (a KEY, not a location); old jobs + carry it as ``origin.thread_id``. Heuristic: if the origin chat IS the Slack home chat, the + pinned thread is that artifact and delivery goes top-level (or to the home target's thread).""" if str(origin.get("platform") or "").lower() != "slack" or not origin.get("thread_id"): return False home_chat = _sched._get_home_target_chat_id("slack") @@ -692,9 +601,7 @@ def _home_target(platform_name: str, chat_id: str, resolved_from: Optional[str] def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[dict]: """Resolve one concrete auto-delivery target for a cron job.""" - origin = _sched._resolve_origin(job) - if deliver_value == "local": return None @@ -709,8 +616,7 @@ def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[d "platform": origin["platform"], "chat_id": str(origin["chat_id"]), "thread_id": _origin_delivery_thread(origin), - # Provenance for _target_mirror_eligible. - "_resolved_from": "origin", + "_resolved_from": "origin", # provenance for _target_mirror_eligible } # No origin (API/script job): fall back to a home channel instead of silently dropping. for platform_name in _sched._iter_home_target_platforms(): @@ -718,8 +624,7 @@ def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[d if chat_id: logger.info( "Job '%s' has deliver=origin but no origin; falling back to %s home channel", - job.get("name", job.get("id", "?")), - platform_name, + job.get("name", job.get("id", "?")), platform_name, ) # Stands in for the primary conversation (NOT a broadcast): mirror-eligible. return _home_target(platform_name, chat_id, "origin_fallback") @@ -729,10 +634,7 @@ def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[d platform_name, rest = deliver_value.split(":", 1) platform_key = platform_name.lower() - from tools.send_message_tool import ( - prepare_send_message_platforms, - resolve_send_target, - ) + from tools.send_message_tool import prepare_send_message_platforms, resolve_send_target prepare_send_message_platforms() # pass_unresolved_references: no model in the loop to react; an unknown-to-directory target @@ -759,8 +661,7 @@ def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[d "platform": platform_name, "chat_id": chat_id, "thread_id": thread_id, - # Mirror-eligible only under the job's own attach_to_session opt-in. - "_resolved_from": "explicit", + "_resolved_from": "explicit", # mirror-eligible only under attach_to_session opt-in } platform_name = deliver_value @@ -768,11 +669,7 @@ def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[d chat_id = _sched._get_home_target_chat_id(platform_name) if chat_id: return _home_target(platform_name, chat_id) - return { - "platform": platform_name, - "chat_id": str(origin["chat_id"]), - "thread_id": origin.get("thread_id"), - } + return {"platform": platform_name, "chat_id": str(origin["chat_id"]), "thread_id": origin.get("thread_id")} if not _sched._is_known_delivery_platform(platform_name): return None @@ -784,8 +681,7 @@ def _get_bot_chat_delivery_timeout() -> int: """Timeout for one bot-chat delivery turn (a full agent turn — minutes, not seconds). ``cron.bot_chat_delivery_timeout_seconds``; default 600.""" try: - cfg = _sched.load_config() - value = int(cfg.get("cron", {}).get("bot_chat_delivery_timeout_seconds", 600)) + value = int(_sched.load_config().get("cron", {}).get("bot_chat_delivery_timeout_seconds", 600)) return value if value > 0 else 600 except Exception: return 600 @@ -799,25 +695,22 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str] alternation-safe (inbound turn, not a transcript splice). ``profile`` is ``""`` for the job's own profile. Returns None on success or an error string for ``last_delivery_error``. """ - import shutil as _shutil import tempfile job_id = job.get("id", "?") - job_name = job.get("name", job_id) - - hermes_bin = _shutil.which("hermes") + hermes_bin = shutil.which("hermes") if hermes_bin: argv = [hermes_bin] else: try: import importlib.util as _ilu - if _ilu.find_spec("hermes_cli") is not None: - argv = [sys.executable, "-m", "hermes_cli.main"] - else: - return "bot-chat delivery failed: hermes CLI not resolvable" + found = _ilu.find_spec("hermes_cli") is not None except Exception: + found = False + if not found: return "bot-chat delivery failed: hermes CLI not resolvable" + argv = [sys.executable, "-m", "hermes_cli.main"] env = os.environ.copy() if profile: @@ -827,47 +720,38 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str] # Prefix marks this as scheduled output, not the human (Bot Mode sender-attribution). message = ( - f'[Cronjob "{job_name}" output — scheduled job, not the user. ' + f'[Cronjob "{job.get("name", job_id)}" output — scheduled job, not the user. ' f"Review it, act on anything that needs action, and summarize " f"for the chat.]\n\n{content}" ) + profile_label = profile or "(own)" query_file = None try: with tempfile.NamedTemporaryFile( - "w", encoding="utf-8", suffix=".txt", prefix="hermes-cron-botchat-", - delete=False, + "w", encoding="utf-8", suffix=".txt", prefix="hermes-cron-botchat-", delete=False, ) as fh: fh.write(message) query_file = fh.name - argv += [ - "chat", "--in", "~", "-c", "Bot Chat", "--create-if-missing", - "-Q", "--query-file", query_file, - ] - + argv += ["chat", "--in", "~", "-c", "Bot Chat", "--create-if-missing", "-Q", "--query-file", query_file] result = subprocess.run( - argv, - capture_output=True, - text=True, - timeout=_get_bot_chat_delivery_timeout(), - env=env, + argv, capture_output=True, text=True, timeout=_get_bot_chat_delivery_timeout(), env=env, creationflags=_sched.windows_hide_flags(), ) if result.returncode != 0: tail = (result.stderr or result.stdout or "").strip()[-500:] msg = ( - f"bot-chat delivery to profile " - f"'{profile or '(own)'}' failed (exit {result.returncode})" + f"bot-chat delivery to profile '{profile_label}' failed (exit {result.returncode})" + (f": {tail}" if tail else "") ) logger.warning("Job '%s': %s", job_id, msg) return msg - logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile or "(own)") + logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile_label) return None except subprocess.TimeoutExpired: msg = ( - f"bot-chat delivery to profile '{profile or '(own)'}' timed out " + f"bot-chat delivery to profile '{profile_label}' timed out " f"after {_get_bot_chat_delivery_timeout()}s (the bot's turn may " "still complete; raise cron.bot_chat_delivery_timeout_seconds if " "this recurs)" @@ -886,10 +770,8 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str] def _normalize_deliver_value(deliver) -> str: """Normalize ``deliver`` to its canonical comma-separated string; ``"local"`` when falsy. - Lists/tuples (MCP clients, hand-edited jobs.json) are flattened — ``str(["telegram"])`` would - yield ``"['telegram']"`` and fail resolution silently. - """ + yield ``"['telegram']"`` and fail resolution silently.""" if deliver is None or deliver == "": return "local" if isinstance(deliver, (list, tuple)): @@ -902,7 +784,6 @@ def _normalize_deliver_value(deliver) -> str: # configured home chat_id (_expand_routing_tokens); ``bot-chat`` is NOT in ``all`` (costs a turn). _ROUTING_TOKENS = frozenset({"all"}) - # Pseudo-platform: deliver output as a real inbound turn into a profile's "Bot Chat" (not a mirror). # ``bot-chat`` = own profile; ``bot-chat:`` = named profile on THIS machine. BOT_CHAT_PLATFORM = "bot-chat" @@ -933,16 +814,14 @@ def _resolve_bot_chat_target(job: dict, profile_arg: str) -> Optional[dict]: canon = normalize_profile_name(profile_arg) if not profile_exists(canon): logger.warning( - "Job '%s': bot-chat delivery profile '%s' not found on this " - "machine — skipping target", + "Job '%s': bot-chat delivery profile '%s' not found on this machine — skipping target", job.get("id", "?"), profile_arg, ) return None return {"platform": BOT_CHAT_PLATFORM, "chat_id": canon, "thread_id": None} except Exception: logger.warning( - "Job '%s': failed to resolve bot-chat profile '%s'", - job.get("id", "?"), profile_arg, exc_info=True, + "Job '%s': failed to resolve bot-chat profile '%s'", job.get("id", "?"), profile_arg, exc_info=True, ) return None @@ -950,14 +829,9 @@ def _resolve_bot_chat_target(job: dict, profile_arg: str) -> Optional[dict]: def _expand_routing_tokens(part: str) -> List[str]: """Expand ``all`` to every home-target platform with a configured chat_id; non-tokens pass through as a single-element list.""" - token = part.lower() - if token not in _ROUTING_TOKENS: + if part.lower() not in _ROUTING_TOKENS: return [part] - expanded: List[str] = [] - for platform_name in _sched._iter_home_target_platforms(): - if _sched._get_home_target_chat_id(platform_name): - expanded.append(platform_name) - return expanded + return [p for p in _sched._iter_home_target_platforms() if _sched._get_home_target_chat_id(p)] def _delivery_lane_value(job: dict, *, for_failure: bool = False): @@ -981,28 +855,29 @@ def _resolve_delivery_targets(job: dict, *, for_failure: bool = False) -> List[d if deliver == "local": return [] - raw_parts = [p.strip() for p in deliver.split(",") if p.strip()] - parts: List[str] = [] - for raw in raw_parts: - parts.extend(_expand_routing_tokens(raw)) + for raw in deliver.split(","): + if raw.strip(): + parts.extend(_expand_routing_tokens(raw.strip())) seen = {} targets = [] for part in parts: target = _resolve_single_delivery_target(job, part) - if target: - key = (target["platform"].lower(), str(target["chat_id"]), target.get("thread_id")) - if key not in seen: - seen[key] = target - targets.append(target) - else: - # OR-merge provenance on dedup: "origin,all" in either order must keep the - # origin/origin_fallback tag or mirror eligibility would depend on token order. - kept = seen[key] - if _MIRROR_PROVENANCE_RANK.get(str(target.get("_resolved_from") or ""), 0) > \ - _MIRROR_PROVENANCE_RANK.get(str(kept.get("_resolved_from") or ""), 0): - kept["_resolved_from"] = target.get("_resolved_from") + if not target: + continue + key = (target["platform"].lower(), str(target["chat_id"]), target.get("thread_id")) + kept = seen.get(key) + if kept is None: + seen[key] = target + targets.append(target) + elif ( + # OR-merge provenance on dedup: "origin,all" in either order must keep the + # origin/origin_fallback tag or mirror eligibility would depend on token order. + _MIRROR_PROVENANCE_RANK.get(str(target.get("_resolved_from") or ""), 0) + > _MIRROR_PROVENANCE_RANK.get(str(kept.get("_resolved_from") or ""), 0) + ): + kept["_resolved_from"] = target.get("_resolved_from") return targets @@ -1014,8 +889,6 @@ def _resolve_delivery_target(job: dict) -> Optional[dict]: # Audio routing is centralized in gateway.platforms.base.should_send_media_as_audio(). _VIDEO_EXTS = frozenset({'.mp4', '.mov', '.avi', '.mkv', '.webm', '.3gp'}) - - _IMAGE_EXTS = frozenset({'.jpg', '.jpeg', '.png', '.webp', '.gif'}) @@ -1065,9 +938,7 @@ def _send_media_via_adapter( future = safe_schedule_threadsafe(coro, loop) if future is None: - _note_target_error( - job_ref, f"cannot send media {media_path}: gateway loop unavailable", errors, - ) + _note_target_error(job_ref, f"cannot send media {media_path}: gateway loop unavailable", errors) return errors try: # Large attachments can exceed 30s; configurable via _get_media_send_timeout(). @@ -1077,18 +948,21 @@ def _send_media_via_adapter( raise if result and not getattr(result, "success", True): _note_target_error( - job_ref, - f"media send failed for {media_path}: {getattr(result, 'error', 'unknown')}", - errors, + job_ref, f"media send failed for {media_path}: {getattr(result, 'error', 'unknown')}", errors, ) except Exception as e: # TimeoutError etc. have an empty str(); fall back to the class name. - _note_target_error( - job_ref, f"failed to send media {media_path}: {str(e) or type(e).__name__}", errors, - ) + _note_target_error(job_ref, f"failed to send media {media_path}: {str(e) or type(e).__name__}", errors) return errors +def _result_field(send_result, key: str, default=None): + """Read ``key`` from a SendResult-like object or the plain dict the silence filter returns.""" + if isinstance(send_result, dict): + return send_result.get(key, default) + return getattr(send_result, key, default) + + def _confirm_adapter_delivery(send_result, job_id: str = "?", unverified: Optional[list] = None) -> bool: """Return True only if ``send_result`` unambiguously confirms delivery. @@ -1099,23 +973,12 @@ def _confirm_adapter_delivery(send_result, job_id: str = "?", unverified: Option """ if send_result is None: return False - if isinstance(send_result, dict): - if "success" not in send_result: - return False - success = bool(send_result.get("success")) - delivered = send_result.get("delivered") - message_id = send_result.get("message_id") - raw_response = send_result.get("raw_response") - else: - if not hasattr(send_result, "success"): - return False - success = bool(getattr(send_result, "success")) - delivered = getattr(send_result, "delivered", None) - message_id = getattr(send_result, "message_id", None) - raw_response = getattr(send_result, "raw_response", None) - if not success or delivered is False: + has_success = "success" in send_result if isinstance(send_result, dict) else hasattr(send_result, "success") + if not has_success: return False - if message_id is None and not raw_response: + if not bool(_result_field(send_result, "success")) or _result_field(send_result, "delivered") is False: + return False + if _result_field(send_result, "message_id") is None and not _result_field(send_result, "raw_response"): logger.warning( "Job '%s': live adapter reported success with no delivery evidence " "(no message_id, no raw_response) — treating as delivered but " @@ -1127,12 +990,7 @@ def _confirm_adapter_delivery(send_result, job_id: str = "?", unverified: Option return True -def _is_channel_dm_topic( - runtime_adapter: Any, - chat_id: Any, - loop: Any, - job_id: str, -) -> bool: +def _is_channel_dm_topic(runtime_adapter: Any, chat_id: Any, loop: Any, job_id: str) -> bool: """Is an ambiguous ``telegram::`` target a channel Direct-Messages topic (``direct_messages_topic_id``) rather than a private-chat forum topic (``message_thread_id``)? Shape cannot decide; signal is ``get_chat_info`` type == ``channel``. @@ -1145,26 +1003,20 @@ def _is_channel_dm_topic( try: from agent.async_utils import safe_schedule_threadsafe - future = safe_schedule_threadsafe( - get_chat_info(runtime_adapter, str(chat_id)), loop, # type: ignore[arg-type] - ) + future = safe_schedule_threadsafe(get_chat_info(runtime_adapter, str(chat_id)), loop) # type: ignore[arg-type] if future is None: return False # Metadata-only call, so a shorter bound than the send waits is intentional. info = future.result(timeout=10) except Exception: logger.debug( - "Job '%s': get_chat_info probe failed for chat=%s — " - "defaulting to message_thread_id routing", + "Job '%s': get_chat_info probe failed for chat=%s — defaulting to message_thread_id routing", job_id, chat_id, exc_info=True, ) return False is_channel = isinstance(info, dict) and str(info.get("type") or "").lower() == "channel" if is_channel: - logger.info( - "Job '%s': chat=%s is a channel — routing via direct_messages_topic_id", - job_id, chat_id, - ) + logger.info("Job '%s': chat=%s is a channel — routing via direct_messages_topic_id", job_id, chat_id) return is_channel @@ -1173,12 +1025,8 @@ def _cron_delivery_notify_enabled(cfg: Optional[dict]) -> bool: missing/malformed section keeps the default so a typo cannot silently mute briefs.""" try: cron_cfg = (cfg or {}).get("cron") - if not isinstance(cron_cfg, dict): - return True - delivery_cfg = cron_cfg.get("delivery") - if not isinstance(delivery_cfg, dict): - return True - return delivery_cfg.get("notify", True) is not False + delivery_cfg = cron_cfg.get("delivery") if isinstance(cron_cfg, dict) else None + return not isinstance(delivery_cfg, dict) or delivery_cfg.get("notify", True) is not False except Exception: return True @@ -1223,6 +1071,7 @@ class _TargetDelivery: in_channel_surface: bool inchannel_continuable: bool opened_thread_id: Optional[str] + live_adapter_ready: bool = False @property def is_relay(self) -> bool: @@ -1319,15 +1168,11 @@ def _live_route_metadata(t: _TargetDelivery) -> tuple[Optional[str], dict, dict] and looks_like_telegram_private_chat_id(str(t.chat_id)) and _looks_like_int(str(thread_id)) ) - if is_ambiguous_telegram_topic and _is_channel_dm_topic( - t.runtime_adapter, t.chat_id, t.loop, job["id"], - ): + if is_ambiguous_telegram_topic and _is_channel_dm_topic(t.runtime_adapter, t.chat_id, t.loop, job["id"]): # Channel DM topic: direct_messages_topic_id, no bare thread_id; media mirrors text. route_thread_id = None route_metadata = { - "direct_messages_topic_id": str(thread_id), - "job_id": job["id"], - "notify": t.notify_delivery, + "direct_messages_topic_id": str(thread_id), "job_id": job["id"], "notify": t.notify_delivery, } media_metadata = {"direct_messages_topic_id": str(thread_id), "notify": t.notify_delivery} else: @@ -1366,18 +1211,10 @@ def _live_send_text( job = t.job router = DeliveryRouter(t.config, t.target_adapters) - route_target = DeliveryTarget( - platform=t.platform, - chat_id=str(t.chat_id), - thread_id=route_thread_id, - is_explicit=True, - ) + route_target = DeliveryTarget(platform=t.platform, chat_id=str(t.chat_id), thread_id=route_thread_id, is_explicit=True) # Thread routing goes via the target, not a bare metadata "thread_id": the router only applies # its Telegram DM-topic detection when thread_id/message_thread_id are absent from metadata. - future = safe_schedule_threadsafe( - router._deliver_to_platform(route_target, text_to_send, route_metadata), - t.loop, - ) + future = safe_schedule_threadsafe(router._deliver_to_platform(route_target, text_to_send, route_metadata), t.loop) if future is None: target_errors.append("live adapter event loop scheduling failed") return False, False, None @@ -1388,10 +1225,7 @@ def _live_send_text( # cannot be un-sent, standalone resend would DUPLICATE: assume delivered. True -> never # started (loop wedged): MUST fall through to standalone or it is silently dropped. if future.cancel(): - msg = ( - f"live adapter send to {t.where} " - "timed out before the coroutine was dispatched" - ) + msg = f"live adapter send to {t.where} timed out before the coroutine was dispatched" logger.warning("Job '%s': %s, falling back to standalone", job["id"], msg) target_errors.append(msg) return False, False, None @@ -1410,12 +1244,8 @@ def _live_send_text( # _deliver_to_platform returns a SendResult, or a plain dict {"success": True, "delivered": # False, ...} when the silence-narration filter drops the message. - if isinstance(send_result, dict): - send_raw_response = send_result.get("raw_response") - delivered_message_id = send_result.get("message_id") - else: - send_raw_response = getattr(send_result, "raw_response", None) - delivered_message_id = getattr(send_result, "message_id", None) + send_raw_response = _result_field(send_result, "raw_response") + delivered_message_id = _result_field(send_result, "message_id") _evidence_gap: list = [] send_success = _confirm_adapter_delivery(send_result, job["id"], _evidence_gap) if send_success and _evidence_gap: @@ -1440,8 +1270,7 @@ def _live_send_text( requested_thread_id = send_raw_response.get("requested_thread_id") or t.thread_id _note_target_error( job, - f"configured thread_id {requested_thread_id} for " - f"{t.where} was not found; delivered without thread_id", + f"configured thread_id {requested_thread_id} for {t.where} was not found; delivered without thread_id", delivery_errors, ) return True, False, delivered_message_id @@ -1459,13 +1288,7 @@ def _live_send_media(t: _TargetDelivery, media_metadata: dict, media_files: list if logical_home.scope_id: routed_media_metadata["scope_id"] = logical_home.scope_id _media_errors = _sched._send_media_via_adapter( - t.runtime_adapter, - t.chat_id, - media_files, - routed_media_metadata or None, - t.loop, - t.job, - platform=t.platform, + t.runtime_adapter, t.chat_id, media_files, routed_media_metadata or None, t.loop, t.job, platform=t.platform, ) # Surface per-file failures into run status: text delivered but attachment lost is not ok. for _me in _media_errors: @@ -1477,15 +1300,12 @@ def _seed_live_delivery_sessions(t: _TargetDelivery, delivered_message_id) -> No Thread seeding is deferred here so open-succeeds/deliver-fails never seeds an unseen brief.""" job = t.job origin = t.origin + seed_kwargs = dict(chat_name=origin.get("chat_name"), is_dm=t.is_dm_target, scope_id=origin.get("scope_id")) thread_seeded = False inchannel_seeded = False if t.opened_thread_id: _sched._seed_cron_thread_session( - job, t.runtime_adapter, t.platform_name, t.chat_id, - t.opened_thread_id, t.mirror_text, - chat_name=origin.get("chat_name"), - is_dm=t.is_dm_target, - scope_id=origin.get("scope_id"), + job, t.runtime_adapter, t.platform_name, t.chat_id, t.opened_thread_id, t.mirror_text, **seed_kwargs, ) thread_seeded = True # in_channel: CREATE + seed the flat session (the mirror only APPENDS to an existing one). Same @@ -1493,27 +1313,20 @@ def _seed_live_delivery_sessions(t: _TargetDelivery, delivered_message_id) -> No # seed without mirror opt-in; others only via _inchannel_seed_allowed (user-less seed = orphan). if t.in_channel_surface and t.inchannel_continuable and not thread_seeded: inchannel_seeded = _sched._seed_cron_channel_session( - job, t.runtime_adapter, t.platform_name, t.chat_id, - t.mirror_text, is_dm=t.is_dm_target, - user_id=t.origin_user_id, - chat_name=origin.get("chat_name"), - scope_id=origin.get("scope_id"), + job, t.runtime_adapter, t.platform_name, t.chat_id, t.mirror_text, + user_id=t.origin_user_id, **seed_kwargs, ) if not inchannel_seeded: logger.warning( - "Job '%s': in_channel seed did NOT land on %s:%s " - "— a plain reply will not see this brief", + "Job '%s': in_channel seed did NOT land on %s:%s — a plain reply will not see this brief", job["id"], t.platform_name, t.chat_id, ) # Companion THREAD seed: a reply in the brief's own thread keys to (chat, thread=), # which the flat seed never touches. Seed it too so BOTH reply surfaces continue the job. if delivered_message_id: _sched._seed_cron_thread_session( - job, t.runtime_adapter, t.platform_name, t.chat_id, - str(delivered_message_id), t.mirror_text, - chat_name=origin.get("chat_name"), - is_dm=t.is_dm_target, - scope_id=origin.get("scope_id"), + job, t.runtime_adapter, t.platform_name, t.chat_id, str(delivered_message_id), t.mirror_text, + **seed_kwargs, ) elif t.in_channel_surface and not t.inchannel_continuable: logger.warning( @@ -1523,12 +1336,10 @@ def _seed_live_delivery_sessions(t: _TargetDelivery, delivered_message_id) -> No "fallback/opted-in target the seed can key) — seed " "skipped; the plain mirror below may still apply", job["id"], t.platform_name, t.chat_id, - origin.get("platform"), origin.get("chat_id"), - origin.get("thread_id"), + origin.get("platform"), origin.get("chat_id"), origin.get("thread_id"), ) _maybe_mirror_cron_delivery( - job, t.platform_name, t.chat_id, t.mirror_text, - thread_id=t.thread_id, user_id=t.origin_user_id, + job, t.platform_name, t.chat_id, t.mirror_text, thread_id=t.thread_id, user_id=t.origin_user_id, enabled=t.mirror_this_target and not thread_seeded and not inchannel_seeded, ) @@ -1552,21 +1363,15 @@ def _deliver_via_live_adapter( # Send cleaned text (MEDIA tags stripped) through the gateway's DeliveryRouter so it gets # the same platform routing as live messages (Telegram's three-mode topic routing). text_to_send = cleaned_text.strip() - adapter_ok = True - timed_out = False - delivered_message_id = None + adapter_ok, timed_out, delivered_message_id = True, False, None if not text_to_send and not media_files: # Fail closed so the run reports the empty payload. - _note_target_error( - job, f"live adapter send skipped (empty text and no media) for {t.where}", target_errors, - ) + _note_target_error(job, f"live adapter send skipped (empty text and no media) for {t.where}", target_errors) adapter_ok = False elif text_to_send: adapter_ok, timed_out, delivered_message_id = _live_send_text( t, text_to_send, route_thread_id, route_metadata, - target_errors=target_errors, - delivery_errors=delivery_errors, - unverified_targets=unverified_targets, + target_errors=target_errors, delivery_errors=delivery_errors, unverified_targets=unverified_targets, ) # Media rides the same DM-topic-aware routing as text. Skipped after a confirmation @@ -1576,8 +1381,7 @@ def _deliver_via_live_adapter( elif timed_out and media_files: _note_target_error( job, - f"{len(media_files)} media attachment(s) not delivered to " - f"{t.where} (live adapter confirmation timed out)", + f"{len(media_files)} media attachment(s) not delivered to {t.where} (live adapter confirmation timed out)", delivery_errors, ) @@ -1608,9 +1412,11 @@ def _standalone_send(t: _TargetDelivery, content: str, media_files: list) -> tup shutdown_msg = f"delivery to {t.where} skipped — interpreter is shutting down" def _send(): - return _send_to_platform( - t.platform, t.pconfig, t.chat_id, content, thread_id=t.thread_id, media_files=media_files, - ) + return _send_to_platform(t.platform, t.pconfig, t.chat_id, content, thread_id=t.thread_id, media_files=media_files) + + def _warned(msg: str) -> tuple[None, str]: + logger.warning("Job '%s': %s", job["id"], msg) + return None, msg def _failed(e) -> tuple[None, str]: msg = f"delivery to {t.where} failed: {e}" @@ -1620,14 +1426,11 @@ def _standalone_send(t: _TargetDelivery, content: str, media_files: list) -> tup # Interpreter finalizing (SIGTERM/restart/OOM): asyncio.run and a fresh ThreadPoolExecutor both # raise "cannot schedule new futures after interpreter shutdown" — warn, not ERROR traceback. if _sched._interpreter_shutting_down(): - logger.warning("Job '%s': %s", job["id"], shutdown_msg) - return None, shutdown_msg + return _warned(shutdown_msg) # The live lane failed closed on an empty payload; standalone senders don't (Telegram returns # success=True for empty content WITHOUT an API call) — a phantom delivery would result. if not content.strip() and not media_files: - msg = f"standalone send skipped (empty text and no media) for {t.where}" - logger.warning("Job '%s': %s", job["id"], msg) - return None, msg + return _warned(f"standalone send skipped (empty text and no media) for {t.where}") coro = _send() try: return asyncio.run(coro), None @@ -1635,23 +1438,20 @@ def _standalone_send(t: _TargetDelivery, content: str, media_files: list) -> tup # asyncio.run() refuses inside a running loop; close the unstarted coro, retry in a thread. coro.close() if _sched._interpreter_shutting_down(run_err): - logger.warning("Job '%s': %s", job["id"], shutdown_msg) - return None, shutdown_msg + return _warned(shutdown_msg) # The fallback can itself raise (SMTP, result timeout); catch it or remaining targets skip. try: pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) try: # A fresh thread does NOT inherit the profile ContextVars (home override + secret # scope); run in the active context or the sender reads the default bot token. - _fallback_context = contextvars.copy_context() - future = pool.submit(_fallback_context.run, asyncio.run, _send()) + future = pool.submit(contextvars.copy_context().run, asyncio.run, _send()) return future.result(timeout=30), None finally: pool.shutdown(wait=False) except Exception as e: if _sched._interpreter_shutting_down(e): - logger.warning("Job '%s': %s", job["id"], shutdown_msg) - return None, shutdown_msg + return _warned(shutdown_msg) return _failed(e) except Exception as e: return _failed(e) @@ -1680,8 +1480,7 @@ def _deliver_standalone( # Standalone senders report per-file attachment failures in ``warnings`` while returning # success; surface them so a vanished attachment doesn't mark the run ok. - _sender_warnings = (result.get("warnings") if isinstance(result, dict) else None) or [] - for _w in _sender_warnings: + for _w in (result.get("warnings") if isinstance(result, dict) else None) or []: msg = f"delivery warning: {_w} (target {t.where})" logger.error("Job '%s': %s", job["id"], msg) delivery_errors.append(msg) @@ -1689,12 +1488,146 @@ def _deliver_standalone( logger.info("Job '%s': delivered to %s:%s", job["id"], t.platform_name, t.chat_id) # Thread seeding only happens on the live lane, so no thread_seeded gate applies here. _maybe_mirror_cron_delivery( - job, t.platform_name, t.chat_id, t.mirror_text, - thread_id=t.thread_id, user_id=t.origin_user_id, + job, t.platform_name, t.chat_id, t.mirror_text, thread_id=t.thread_id, user_id=t.origin_user_id, enabled=t.mirror_this_target, ) +def _prepare_target_delivery( + job: dict, + target: dict, + *, + adapters, + loop, + config, + notify_delivery: bool, + mirror_enabled: bool, + mirror_text: str, + delivery_errors: list, +) -> Optional[_TargetDelivery]: + """Per-target prologue of ``_deliver_result``: origin/mirror/in_channel gates, transport + resolution and the continuable-thread open. Returns None (error already recorded in + ``delivery_errors``) when the target cannot be served.""" + from gateway.config import Platform + + platform_name = target["platform"] + chat_id = target["chat_id"] + thread_id = target.get("thread_id") + + origin = _sched._resolve_origin(job) or {} + origin_thread = origin.get("thread_id") + if origin_thread and not thread_id: + logger.warning( + "Job '%s': origin has thread_id=%s but delivery target lost it (deliver=%s, target=%s)", + job["id"], origin_thread, job.get("deliver", "local"), target, + ) + elif thread_id: + logger.debug("Job '%s': delivering to %s:%s thread_id=%s", job["id"], platform_name, chat_id, thread_id) + + # Mirror: origin, home FALLBACK for origin-less deliver=origin, or attach_to_session opt-in. + origin_target = _target_matches_origin(origin, platform_name, chat_id, thread_id) + mirror_this_target = mirror_enabled and _target_mirror_eligible( + job, target, global_mirror=mirror_enabled, origin_match=origin_target, + ) + # Resolved for ANY origin match (not just mirror-enabled): the in_channel seed needs it too. + origin_user_id = origin.get("user_id") if origin_target else None + + # DM shape for BOTH the flatten gate and seed chat_type (Slack DM ids start with "D"). + origin_chat_type = str(origin.get("chat_type") or "").lower() + is_dm_target = origin_chat_type == "dm" or (not origin_chat_type and str(chat_id).startswith("D")) + + # in_channel gate shared by thread-flatten and flat seed — they MUST match or brief and + # session land in different places. Origin qualifies unconditionally; others only when the + # seed can create a resolvable session (_inchannel_seed_allowed). + inchannel_continuable = origin_target or ( + mirror_this_target and _inchannel_seed_allowed(is_dm=is_dm_target, user_id=origin_user_id) + ) + + # Plugin platform names create dynamic members via Platform._missing_(). + try: + platform = Platform(platform_name.lower()) + except (ValueError, KeyError): + _note_target_error(job, f"unknown platform '{platform_name}'", delivery_errors) + return None + + resolved, resolve_err = _resolve_target_transport(job, platform, platform_name, target, adapters, config) + if resolved is None: + _note_target_error(job, resolve_err, delivery_errors) + return None + transport, pconfig, runtime_adapter, target_adapters = resolved + + # Live send needs a RUNNING loop, not just an adapter. Computed ONCE so the in_channel + # thread_id clear below stays in lockstep with the seed (standalone cannot seed flat). + live_adapter_ready = ( + runtime_adapter is not None and loop is not None and getattr(loop, "is_running", lambda: False)() + ) + + # Continuable surface (D1/D2/D6) from platform config ``extra``; default "thread". + # ``in_channel`` delivers FLAT so a plain channel reply continues via the shared session + # ``(platform, chat_id, None)``. Unsupported adapters fail SAFE to thread. + in_channel_surface = _resolve_cron_surface_mode(pconfig, platform_name) == "in_channel" + if ( + in_channel_surface + and runtime_adapter is not None + and not _inchannel_surface_supported(runtime_adapter, platform_name) + ): + logger.debug( + "Job '%s': cron_continuable_surface=in_channel not supported on %s, using thread", + job.get("id", "?"), platform_name, + ) + in_channel_surface = False + + if in_channel_surface and inchannel_continuable and live_adapter_ready: + # Force flat (D2): an inherited thread_id would never match the flat seed (None). Gated + # on `inchannel_continuable` (SAME gate as the seed) AND `live_adapter_ready` (fallback + # never seeds). Stay AFTER mirror_this_target/origin_user_id (need ORIGINAL thread_id). + thread_id = None + + # Thread-preferred continuable cron: open a DEDICATED thread; its session is seeded after a + # successful send. DM-only platforms return None → mirror the origin DM. in_channel SKIPS + # this: it posts flat and _seed_cron_channel_session CREATES the session. + opened_thread_id: Optional[str] = None + if ( + mirror_this_target + and not in_channel_surface + and runtime_adapter is not None + and loop is not None + and not thread_id # never override an explicit origin thread/topic + ): + opened_thread_id = _sched._open_continuable_cron_thread(job, runtime_adapter, chat_id, loop) or None + if opened_thread_id: + thread_id = opened_thread_id + + return _TargetDelivery( + job=job, platform=platform, platform_name=platform_name, chat_id=chat_id, thread_id=thread_id, + transport=transport, pconfig=pconfig, runtime_adapter=runtime_adapter, target_adapters=target_adapters, + config=config, loop=loop, notify_delivery=notify_delivery, origin=origin, origin_target=origin_target, + origin_user_id=origin_user_id, is_dm_target=is_dm_target, mirror_text=mirror_text, + mirror_this_target=mirror_this_target, in_channel_surface=in_channel_surface, + inchannel_continuable=inchannel_continuable, opened_thread_id=opened_thread_id, + live_adapter_ready=live_adapter_ready, + ) + + +def _unresolved_delivery_outcome(job: dict, for_failure: bool) -> Optional[str]: + """Result of ``_deliver_result`` when no target resolved: None (not a failure) for + ``local`` and for origin-less ``origin`` (CLI jobs never capture an origin and would emit a + spurious error every run), else an error string.""" + deliver_value = _normalize_deliver_value(_delivery_lane_value(job, for_failure=for_failure)) + if deliver_value == "local": + return None + if deliver_value == "origin": + logger.info( + "Job '%s': deliver=origin but no origin or home channels — " + "skipping delivery (output saved in last_output)", + job.get("name", job.get("id", "?")), + ) + return None + msg = f"no delivery target resolved for deliver={deliver_value}" + logger.warning("Job '%s': %s", job["id"], msg) + return msg + + def _deliver_result( job: dict, content: str, adapters=None, loop=None, *, for_failure: bool = False ) -> Optional[str]: @@ -1704,25 +1637,9 @@ def _deliver_result( ``failure_deliver`` override when present (NS-788). Returns None on success or an error string.""" targets = _sched._resolve_delivery_targets(job, for_failure=for_failure) if not targets: - deliver_value = _normalize_deliver_value( - _delivery_lane_value(job, for_failure=for_failure) - ) - if deliver_value == "local": - return None # local-only jobs don't deliver — not a failure - # deliver=origin with no origin and no home channels: treat as local, not an error — CLI - # jobs never capture an origin and would emit a spurious error every run. - if deliver_value == "origin": - logger.info( - "Job '%s': deliver=origin but no origin or home channels — " - "skipping delivery (output saved in last_output)", - job.get("name", job.get("id", "?")), - ) - return None - msg = f"no delivery target resolved for deliver={deliver_value}" - logger.warning("Job '%s': %s", job["id"], msg) - return msg + return _unresolved_delivery_outcome(job, for_failure) - from gateway.config import load_gateway_config, Platform + from gateway.config import load_gateway_config # Wrap with header/footer unless cron.wrap_response: false. wrap_response = True @@ -1739,10 +1656,9 @@ def _deliver_result( if wrap_response: task_name = job.get("name", job["id"]) - job_id = job.get("id", "") delivery_content = ( f"Cronjob Response: {task_name}\n" - f"(job_id: {job_id})\n" + f"(job_id: {job.get('id', '')})\n" f"-------------\n\n" f"{content}\n\n" f"To stop or manage this job, send me a new message (e.g. \"stop reminder {task_name}\")." @@ -1759,19 +1675,15 @@ def _deliver_result( apply_media_policy_env(user_cfg) media_files, cleaned_delivery_content = BasePlatformAdapter.extract_media(delivery_content) - requested_media = [(str(p), v) for p, v in media_files] + requested_media = len(media_files) media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files) # Policy-dropped attachments will never be sent on ANY lane — record them in run status. - _policy_dropped = len(requested_media) - len(media_files) - policy_drop_errors = ( - [ - f"{_policy_dropped} media attachment(s) dropped by media path " - "policy (missing file, denied prefix, or strict-mode miss); " - "see gateway.strict / media_delivery_allow_dirs in config.yaml" - ] - if _policy_dropped > 0 - else [] - ) + _policy_dropped = requested_media - len(media_files) + policy_drop_errors = [ + f"{_policy_dropped} media attachment(s) dropped by media path " + "policy (missing file, denied prefix, or strict-mode miss); " + "see gateway.strict / media_delivery_allow_dirs in config.yaml" + ] if _policy_dropped > 0 else [] # Resolve the mirror gate ONCE (default off): successful deliveries are appended to the target # chat's session transcript. Mirror the CLEAN, unwrapped output (not the header/footer). @@ -1794,158 +1706,32 @@ def _deliver_result( delivery_errors = [] for target in targets: - platform_name = target["platform"] - chat_id = target["chat_id"] - thread_id = target.get("thread_id") - # bot-chat targets bypass gateway adapters: output becomes an inbound turn in the target # profile's Bot Chat via the chat CLI lane. Must precede the Platform enum, which lacks it. - if platform_name == BOT_CHAT_PLATFORM: - bot_chat_error = _deliver_to_bot_chat(job, content, chat_id) + if target["platform"] == BOT_CHAT_PLATFORM: + bot_chat_error = _deliver_to_bot_chat(job, content, target["chat_id"]) if bot_chat_error: delivery_errors.append(bot_chat_error) continue - origin = _sched._resolve_origin(job) or {} - origin_thread = origin.get("thread_id") - if origin_thread and not thread_id: - logger.warning( - "Job '%s': origin has thread_id=%s but delivery target lost it " - "(deliver=%s, target=%s)", - job["id"], origin_thread, job.get("deliver", "local"), target, - ) - elif thread_id: - logger.debug( - "Job '%s': delivering to %s:%s thread_id=%s", - job["id"], platform_name, chat_id, thread_id, - ) - - # Mirror: origin, home FALLBACK for origin-less deliver=origin, or attach_to_session opt-in. - origin_target = _target_matches_origin(origin, platform_name, chat_id, thread_id) - mirror_this_target = mirror_enabled and _target_mirror_eligible( - job, target, global_mirror=mirror_enabled, origin_match=origin_target, + t = _prepare_target_delivery( + job, target, adapters=adapters, loop=loop, config=config, notify_delivery=notify_delivery, + mirror_enabled=mirror_enabled, mirror_text=mirror_text, delivery_errors=delivery_errors, ) - # Resolved for ANY origin match (not just mirror-enabled): the in_channel seed needs it too. - origin_user_id = origin.get("user_id") if origin_target else None - - # DM shape for BOTH the flatten gate and seed chat_type (Slack DM ids start with "D"). - origin_chat_type = str(origin.get("chat_type") or "").lower() - is_dm_target = origin_chat_type == "dm" or ( - not origin_chat_type and str(chat_id).startswith("D") - ) - - # in_channel gate shared by thread-flatten and flat seed — they MUST match or brief and - # session land in different places. Origin qualifies unconditionally; others only when the - # seed can create a resolvable session (_inchannel_seed_allowed). - inchannel_continuable = origin_target or ( - mirror_this_target - and _inchannel_seed_allowed(is_dm=is_dm_target, user_id=origin_user_id) - ) - - # Plugin platform names create dynamic members via Platform._missing_(). - try: - platform = Platform(platform_name.lower()) - except (ValueError, KeyError): - _note_target_error(job, f"unknown platform '{platform_name}'", delivery_errors) + if t is None: continue - - resolved, resolve_err = _resolve_target_transport( - job, platform, platform_name, target, adapters, config, - ) - if resolved is None: - _note_target_error(job, resolve_err, delivery_errors) - continue - transport, pconfig, runtime_adapter, target_adapters = resolved - - # Live send needs a RUNNING loop, not just an adapter. Computed ONCE so the in_channel - # thread_id clear below stays in lockstep with the seed (standalone cannot seed flat). - live_adapter_ready = ( - runtime_adapter is not None - and loop is not None - and getattr(loop, "is_running", lambda: False)() - ) target_errors: list = [] - - # Continuable surface (D1/D2/D6) from platform config ``extra``; default "thread". - # ``in_channel`` delivers FLAT so a plain channel reply continues via the shared session - # ``(platform, chat_id, None)``. Unsupported adapters fail SAFE to thread. - in_channel_surface = _resolve_cron_surface_mode(pconfig, platform_name) == "in_channel" - if ( - in_channel_surface - and runtime_adapter is not None - and not _inchannel_surface_supported(runtime_adapter, platform_name) - ): - logger.debug( - "Job '%s': cron_continuable_surface=in_channel not supported on " - "%s, using thread", - job.get("id", "?"), platform_name, - ) - in_channel_surface = False - - if in_channel_surface and inchannel_continuable and live_adapter_ready: - # Force flat (D2): an inherited thread_id would never match the flat seed (None). Gated - # on `inchannel_continuable` (SAME gate as the seed) AND `live_adapter_ready` (fallback - # never seeds). Stay AFTER mirror_this_target/origin_user_id (need ORIGINAL thread_id). - thread_id = None - - # Thread-preferred continuable cron: open a DEDICATED thread; its session is seeded after a - # successful send. DM-only platforms return None → mirror the origin DM. in_channel SKIPS - # this: it posts flat and _seed_cron_channel_session CREATES the session. - opened_thread_id: Optional[str] = None - if ( - mirror_this_target - and not in_channel_surface - and runtime_adapter is not None - and loop is not None - and not thread_id # never override an explicit origin thread/topic - ): - opened_thread_id = _sched._open_continuable_cron_thread( - job, runtime_adapter, chat_id, loop, - ) or None - if opened_thread_id: - thread_id = opened_thread_id - - t = _TargetDelivery( - job=job, - platform=platform, - platform_name=platform_name, - chat_id=chat_id, - thread_id=thread_id, - transport=transport, - pconfig=pconfig, - runtime_adapter=runtime_adapter, - target_adapters=target_adapters, - config=config, - loop=loop, - notify_delivery=notify_delivery, - origin=origin, - origin_target=origin_target, - origin_user_id=origin_user_id, - is_dm_target=is_dm_target, - mirror_text=mirror_text, - mirror_this_target=mirror_this_target, - in_channel_surface=in_channel_surface, - inchannel_continuable=inchannel_continuable, - opened_thread_id=opened_thread_id, - ) - delivered = live_adapter_ready and _deliver_via_live_adapter( + delivered = t.live_adapter_ready and _deliver_via_live_adapter( t, cleaned_delivery_content, media_files, - target_errors=target_errors, - delivery_errors=delivery_errors, - unverified_targets=unverified_targets, + target_errors=target_errors, delivery_errors=delivery_errors, unverified_targets=unverified_targets, ) if not delivered: - _deliver_standalone( - t, cleaned_delivery_content, media_files, target_errors, delivery_errors, - ) + _deliver_standalone(t, cleaned_delivery_content, media_files, target_errors, delivery_errors) - if policy_drop_errors: - # Filter-time drops apply to every target; report them once. - delivery_errors.extend(policy_drop_errors) + # Filter-time drops apply to every target; report them once. + delivery_errors.extend(policy_drop_errors) _sched._record_delivery_verification(job, unverified_targets) - if delivery_errors: - return "; ".join(delivery_errors) - return None + return "; ".join(delivery_errors) if delivery_errors else None # Late-bound origin namespace (see module docstring). Imported LAST so this module is fully diff --git a/cron/scheduler_preflight.py b/cron/scheduler_preflight.py index ff7ddf5cb2..873e695ed2 100644 --- a/cron/scheduler_preflight.py +++ b/cron/scheduler_preflight.py @@ -1,8 +1,8 @@ """Cron pre-run preflight: transient provider-resolution error classification, provider-key / delivery-target / skills checks, and the shared-route adapter view used by satellite profiles. -Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident -helpers are reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. +Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident helpers are +reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. """ from __future__ import annotations @@ -16,42 +16,26 @@ from typing import Optional # Log-record parity with the origin module. logger = logging.getLogger("cron.scheduler") - # Error-string prefixes from ``run_job``; ``run_one_job`` keys off them for last_status and the # alert-once dedup. ``:silent`` = already alerted on a previous tick — do not deliver again. BLOCKED_CONFIG_MARKER = "[blocked_config]" - - BLOCKED_CONFIG_SILENT_MARKER = "[blocked_config:silent]" - - # Drift-guard skip: same contract (drift_alerted bit on the job record). DRIFT_SKIP_MARKER = "[drift_skip]" - - DRIFT_SKIP_SILENT_MARKER = "[drift_skip:silent]" - _TRANSIENT_NET_EXC_NAMES = frozenset({ "ConnectError", "ConnectTimeout", "ReadTimeout", "WriteTimeout", "PoolTimeout", "NetworkError", "TimeoutException", "ClientConnectorError", "ClientConnectorDNSError", "ServerTimeoutError", "ClientOSError", }) - - _DNS_FAILURE_NEEDLES = ("nodename nor servname", "name or service not known") - - _TRANSIENT_OSERROR_NEEDLES = _DNS_FAILURE_NEEDLES + ( "temporary failure in name resolution", "network is unreachable", ) - - _TRANSIENT_HTTP_NEEDLES = _TRANSIENT_OSERROR_NEEDLES + ( "failed to resolve", "connection refused", "timed out", "timeout", ) - - _TRANSIENT_ERRNOS = frozenset({ errno.ECONNREFUSED, errno.ECONNRESET, errno.EHOSTUNREACH, errno.ENETUNREACH, errno.ENETDOWN, errno.ETIMEDOUT, errno.EAGAIN, @@ -101,9 +85,7 @@ def _is_transient_provider_resolve_error(exc: BaseException) -> bool: def _cron_preflight_enabled(cfg: dict) -> bool: """Preflight is ON unless ``cron.preflight`` is literally ``false``.""" cron_cfg = (cfg or {}).get("cron") - if not isinstance(cron_cfg, dict): - return True - return cron_cfg.get("preflight", True) is not False + return not isinstance(cron_cfg, dict) or cron_cfg.get("preflight", True) is not False def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]: @@ -118,9 +100,7 @@ def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]: _cron_cfg = cfg.get("cron") if isinstance(cfg.get("cron"), dict) else {} requested = ( - job.get("provider") - or str((_cron_cfg or {}).get("model_provider") or "").strip() - or None + job.get("provider") or str((_cron_cfg or {}).get("model_provider") or "").strip() or None ) model = job.get("model") or os.getenv("HERMES_MODEL") or "" @@ -147,13 +127,11 @@ def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]: def _primary_profile_routes_for_current_home() -> list: """Primary gateway ``profile_routes`` targeting the profile being served; ``[]`` if this IS the - primary home. - - Satellite crons are ticked and delivered by the primary gateway (a satellite holding its own - token is a ``duplicate_credential`` fatal). Reads the primary config.yaml directly (top-level or - nested ``gateway.``) instead of ``load_gateway_config()`` so no primary platform config leaks - into this process. Shared by preflight rescue and delivery-time resolution so they cannot drift. - """ + primary home. Satellite crons are ticked and delivered by the primary gateway (a satellite + holding its own token is a ``duplicate_credential`` fatal). Reads the primary config.yaml + directly (top-level or nested ``gateway.``) instead of ``load_gateway_config()`` so no primary + platform config leaks into this process. Shared by preflight rescue and delivery-time + resolution so they cannot drift.""" try: from hermes_constants import get_default_hermes_root, get_hermes_home @@ -182,8 +160,7 @@ def _primary_profile_routes_for_current_home() -> list: from hermes_cli.profiles import profile_matches_home return [ - route - for route in parse_profile_routes(routes_raw) + route for route in parse_profile_routes(routes_raw) if route.enabled and profile_matches_home(route.profile) ] except Exception: @@ -284,10 +261,11 @@ def _preflight_check_delivery(job: dict) -> Optional[str]: "delivery credential check", exc_info=True, ) return None # fail-open - if platform_name.lower() not in connected: - # Multiplex: a satellite served by the primary's adapters reads unconnected — no block. - if _delivery_platform_routed_from_primary_gateway(platform_name): - continue + # Multiplex: a satellite served by the primary's adapters reads unconnected — no block. + if ( + platform_name.lower() not in connected + and not _delivery_platform_routed_from_primary_gateway(platform_name) + ): return ( f"delivery platform '{platform_name}' has no gateway " "credentials configured (not connected). Configure it via " @@ -296,16 +274,20 @@ def _preflight_check_delivery(job: dict) -> Optional[str]: return None +# ``skill_view`` payload keys naming missing prerequisites -> label for the preflight verdict. +_SKILL_MISSING_FIELDS = ( + ("missing_required_environment_variables", "env ${}"), + ("missing_required_commands", "command '{}'"), + ("missing_credential_files", "credential file {}"), +) + + def _preflight_check_skills(job: dict) -> Optional[str]: """Block only on an affirmative ``setup_needed`` verdict from ``skill_view``; skills that fail to load fall through to ``_build_job_prompt``'s skipped-skill handling (fail-open).""" - skills = job.get("skills") - if skills is None: - legacy = job.get("skill") - skills = [legacy] if legacy else [] - elif isinstance(skills, str): - skills = [skills] - skill_names = [str(name).strip() for name in skills if str(name).strip()] + from cron.scheduler_prompt import _job_skill_names + + skill_names = _job_skill_names(job) if not skill_names: return None @@ -318,23 +300,11 @@ def _preflight_check_skills(job: dict) -> Optional[str]: continue # unreadable/missing skill → existing skip handling if not isinstance(payload, dict) or not payload.get("success"): continue - if ( - payload.get("setup_needed") - or payload.get("readiness_status") == "setup_needed" - ): + if payload.get("setup_needed") or payload.get("readiness_status") == "setup_needed": missing = [ - f"env ${name}" - for name in payload.get( - "missing_required_environment_variables" - ) or [] - ] - missing += [ - f"command '{name}'" - for name in payload.get("missing_required_commands") or [] - ] - missing += [ - f"credential file {name}" - for name in payload.get("missing_credential_files") or [] + fmt.format(name) + for key, fmt in _SKILL_MISSING_FIELDS + for name in payload.get(key) or [] ] detail = ", ".join(missing) or "required setup incomplete" return ( diff --git a/cron/scheduler_prompt.py b/cron/scheduler_prompt.py index ed2eaaee6a..0734efcaaf 100644 --- a/cron/scheduler_prompt.py +++ b/cron/scheduler_prompt.py @@ -1,8 +1,8 @@ """Cron job prompt assembly: context_from injection, skill loading, the assembled-prompt injection scan, and the credential-exfil / config-block guards. -Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident -helpers are reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. +Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident helpers are +reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. """ from __future__ import annotations @@ -19,19 +19,14 @@ logger = logging.getLogger("cron.scheduler") def _parse_wake_gate(script_output: str) -> bool: """Wake gate: False only if the last non-empty stdout line is JSON ``{"wakeAgent": false}`` (agent skipped entirely — no LLM run, no delivery); anything else wakes normally.""" - if not script_output: - return True - stripped_lines = [line for line in script_output.splitlines() if line.strip()] + stripped_lines = [line for line in (script_output or "").splitlines() if line.strip()] if not stripped_lines: return True - last_line = stripped_lines[-1].strip() try: - gate = json.loads(last_line) + gate = json.loads(stripped_lines[-1].strip()) except (json.JSONDecodeError, ValueError): return True - if not isinstance(gate, dict): - return True - return gate.get("wakeAgent", True) is not False + return not isinstance(gate, dict) or gate.get("wakeAgent", True) is not False def _prepend_context_block(prompt: str, heading: str, intro: str, body: str) -> str: @@ -39,8 +34,29 @@ def _prepend_context_block(prompt: str, heading: str, intro: str, body: str) -> return f"## {heading}\n{intro}\n\n```\n{body}\n```\n\n{prompt}" +def _job_skill_names(job: dict) -> list[str]: + """Normalized skill names from ``skills`` (list or str) or the legacy singular ``skill``.""" + skills = job.get("skills") + if skills is None: + legacy = job.get("skill") + skills = [legacy] if legacy else [] + elif isinstance(skills, str): + skills = [skills] + return [str(name).strip() for name in skills if str(name).strip()] + + _MAX_CONTEXT_CHARS = 8000 +_SELF_CONTEXT_INTRO = ( + "The following is this job's most recent output from its previous run. Use it for " + "continuity: avoid repeating what was already reported, and continue where the last run " + "left off." +) +_UPSTREAM_CONTEXT_INTRO = ( + "The following is the most recent output from a preceding cron job. Use it as context for " + "your analysis." +) + def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]: """Prepend the latest output of each ``context_from`` job; returns ``(prompt, injected)``.""" @@ -66,9 +82,7 @@ def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]: continue try: output_files = sorted( - (output_dir / source_job_id).glob("*.md"), - key=lambda f: f.stat().st_mtime, - reverse=True, + (output_dir / source_job_id).glob("*.md"), key=lambda f: f.stat().st_mtime, reverse=True, ) if not output_files: continue # silent skip — no output yet @@ -79,19 +93,11 @@ def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]: continue # silent skip — empty output if is_self: prompt = _prepend_context_block( - prompt, "Your previous run's output", - "The following is this job's most recent output from its " - "previous run. Use it for continuity: avoid repeating what " - "was already reported, and continue where the last run " - "left off.", - latest_output, + prompt, "Your previous run's output", _SELF_CONTEXT_INTRO, latest_output, ) else: prompt = _prepend_context_block( - prompt, f"Output from job '{source_job_id}'", - "The following is the most recent output from a preceding " - "cron job. Use it as context for your analysis.", - latest_output, + prompt, f"Output from job '{source_job_id}'", _UPSTREAM_CONTEXT_INTRO, latest_output, ) injected = True except (OSError, PermissionError) as e: @@ -111,34 +117,31 @@ def _load_cron_skill_parts(job: dict, skill_names: list[str]) -> list[str]: task_id = str(job.get("id") or "") or None parts: list[str] = [] skipped: list[str] = [] + + def _skip(msg: str, *args) -> None: + logger.warning("Cron job '%s': " + msg, job_label, *args) + skipped.append(skill_name) + for skill_name in skill_names: # Bundles shadow same-slug skills, mirroring the CLI/gateway slash-command path. bundle_key = resolve_bundle_command_key(skill_name.lstrip("/")) if bundle_key: - bundle_payload = build_bundle_invocation_message( - bundle_key, user_instruction="", task_id=task_id, - ) + bundle_payload = build_bundle_invocation_message(bundle_key, user_instruction="", task_id=task_id) if bundle_payload: if parts: parts.append("") parts.append(bundle_payload[0]) - continue - logger.warning( - "Cron job '%s': bundle '%s' could not load any skills, skipping", job_label, skill_name, - ) - skipped.append(skill_name) + else: + _skip("bundle '%s' could not load any skills, skipping", skill_name) continue try: loaded = json.loads(skill_view(normalize_skill_lookup_name(skill_name))) except (json.JSONDecodeError, TypeError): - logger.warning("Cron job '%s': skill '%s' returned invalid JSON, skipping", job_label, skill_name) - skipped.append(skill_name) + _skip("skill '%s' returned invalid JSON, skipping", skill_name) continue if not loaded.get("success"): - error = loaded.get("error") or f"Failed to load skill '{skill_name}'" - logger.warning("Cron job '%s': skill not found, skipping — %s", job_label, error) - skipped.append(skill_name) + _skip("skill not found, skipping — %s", loaded.get("error") or f"Failed to load skill '{skill_name}'") continue try: @@ -164,6 +167,19 @@ def _load_cron_skill_parts(job: dict, skill_names: list[str]) -> list[str]: return parts +_CRON_HINT = ( + "[IMPORTANT: You are running as a scheduled cron job. " + "DELIVERY: Your final response will be automatically delivered " + "to the user — do NOT use send_message or try to deliver " + "the output yourself. Just produce your report/output as your " + "final response and the system handles the rest. " + "SILENT: If there is genuinely nothing new to report, respond " + "with exactly \"[SILENT]\" (nothing else) to suppress delivery. " + "Never combine [SILENT] with content — either report your " + "findings normally, or say [SILENT] and nothing more.]\n\n" +) + + def _build_job_prompt( job: dict, prerun_script: Optional[tuple] = None, @@ -179,32 +195,23 @@ def _build_job_prompt( if extra_prompt: user_prompt = f"{user_prompt}\n\n## Run Context\n{extra_prompt}" prompt = user_prompt - skills = job.get("skills") # Runtime DATA (script stdout, upstream output) legitimately quotes command-shape strings, so it # must not be scanned with the strict user-prompt set — see _scan_assembled_cron_prompt. has_injected_data = False script_path = job.get("script") if script_path: - if prerun_script is not None: - success, script_output = prerun_script - else: - success, script_output = _sched._run_job_script(script_path) + success, script_output = ( + prerun_script if prerun_script is not None else _sched._run_job_script(script_path) + ) if success and not script_output: return None # no output → nothing to report, skip the AI call - if success: - prompt = _prepend_context_block( - prompt, "Script Output", - "The following data was collected by a pre-run script. " - "Use it as context for your analysis.", - script_output, - ) - else: - prompt = _prepend_context_block( - prompt, "Script Error", - "The data-collection script failed. Report this to the user.", - script_output, - ) + heading, intro = ( + ("Script Output", "The following data was collected by a pre-run script. Use it as context for your analysis.") + if success + else ("Script Error", "The data-collection script failed. Report this to the user.") + ) + prompt = _prepend_context_block(prompt, heading, intro, script_output) has_injected_data = True prompt, _ctx_injected = _inject_context_from(job, prompt) @@ -218,32 +225,11 @@ def _build_job_prompt( prompt = f"{notepad_section}{prompt}" has_injected_data = True - cron_hint = ( - "[IMPORTANT: You are running as a scheduled cron job. " - "DELIVERY: Your final response will be automatically delivered " - "to the user — do NOT use send_message or try to deliver " - "the output yourself. Just produce your report/output as your " - "final response and the system handles the rest. " - "SILENT: If there is genuinely nothing new to report, respond " - "with exactly \"[SILENT]\" (nothing else) to suppress delivery. " - "Never combine [SILENT] with content — either report your " - "findings normally, or say [SILENT] and nothing more.]\n\n" - ) - prompt = cron_hint + prompt - if skills is None: - legacy = job.get("skill") - skills = [legacy] if legacy else [] - elif isinstance(skills, str): - skills = [skills] - - skill_names = [str(name).strip() for name in skills if str(name).strip()] + prompt = _CRON_HINT + prompt + skill_names = _job_skill_names(job) if not skill_names: return _scan_assembled_cron_prompt( - prompt, - job, - has_skills=False, - has_injected_data=has_injected_data, - user_prompt=user_prompt, + prompt, job, has_skills=False, has_injected_data=has_injected_data, user_prompt=user_prompt, ) parts = _load_cron_skill_parts(job, skill_names) @@ -285,18 +271,15 @@ def _scan_assembled_cron_prompt( if has_skills or has_injected_data: # The cleaned (sanitized) prompt is what actually runs. - cleaned, scan_error = _scan_cron_skill_assembled(assembled) - assembled = cleaned + assembled, scan_error = _scan_cron_skill_assembled(assembled) if not scan_error and not has_skills and user_prompt: scan_error = _scan_cron_prompt(user_prompt) else: scan_error = _scan_cron_prompt(assembled) if scan_error: - job_label = job.get("name") or job.get("id") or "" logger.warning( "Cron job '%s': assembled prompt blocked by injection scanner — %s", - job_label, - scan_error, + job.get("name") or job.get("id") or "", scan_error, ) raise _sched.CronPromptInjectionBlocked(scan_error) return assembled @@ -304,25 +287,20 @@ def _scan_assembled_cron_prompt( def _guard_job_credential_exfil(job: dict) -> None: """Fail closed (RuntimeError) if the stored provider/base_url pair could exfiltrate a key. - Runtime backstop: jobs persisted before the create/update guard, or written directly to the store, reach provider resolution unchecked. Fallback providers come from operator config and - are validated by the caller, not here. - """ + are validated by the caller, not here.""" try: from tools.cronjob_tools import _validate_cron_base_url err = _validate_cron_base_url(job.get("provider"), job.get("base_url")) except Exception as exc: # Fail CLOSED on validator/import errors — but only for jobs WITH a base_url override; a job # without one cannot exfiltrate via this path, so it still runs. - if job.get("base_url"): - err = ( - f"could not validate provider/base_url pair " - f"({exc.__class__.__name__}: {exc}); refusing to run a job with " - "an unverified base_url override" - ) - else: - err = None + err = ( + f"could not validate provider/base_url pair " + f"({exc.__class__.__name__}: {exc}); refusing to run a job with " + "an unverified base_url override" + ) if job.get("base_url") else None if err: job_id = job.get("id") logger.error( diff --git a/cron/scheduler_script.py b/cron/scheduler_script.py index 6ac67845d3..54fa8c2ab7 100644 --- a/cron/scheduler_script.py +++ b/cron/scheduler_script.py @@ -1,8 +1,8 @@ """Cron pre-run script execution: timeouts, Windows venv bootstrap, process-tree termination, and the claim-heartbeat thread that keeps a long script's run claim alive. -Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident -helpers are reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. +Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident helpers are +reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.`` keeps working. """ from __future__ import annotations @@ -20,6 +20,7 @@ import time from cron.jobs import _ensure_cron_dir from pathlib import Path from typing import Any +from typing import Callable from typing import Optional from typing import TYPE_CHECKING @@ -30,37 +31,49 @@ if TYPE_CHECKING: logger = logging.getLogger("cron.scheduler") +def _positive_int(raw) -> Optional[int]: + """``int(float(raw))`` when > 0, else None; raises on unparsable input.""" + timeout = int(float(raw)) + return timeout if timeout > 0 else None + + +def _timeout_from_env_or_config(env_var: str, config_key: str, parse: Callable[[Any], Any], label: str): + """Shared env → ``cron.`` resolution. ``parse`` returns the value or None to keep + looking; a parse error on the env var WARNs, on config DEBUGs. Returns None when neither yields.""" + env_value = os.getenv(env_var, "").strip() + if env_value: + try: + value = parse(env_value) + if value is not None: + return value + except Exception: + logger.warning("Invalid %s=%r; using config/default", env_var, env_value) + try: + cfg = _sched.load_config() or {} + cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {} + configured = cron_cfg.get(config_key) + if configured is not None: + value = parse(configured) + if value is not None: + return value + except Exception as exc: + logger.debug("Failed to load %s from config: %s", label, exc) + return None + + def _get_script_timeout() -> int: """Resolve cron pre-run script timeout from module/env/config with a safe default.""" if _sched._SCRIPT_TIMEOUT != _sched._DEFAULT_SCRIPT_TIMEOUT: try: - timeout = int(float(_sched._SCRIPT_TIMEOUT)) - if timeout > 0: + timeout = _positive_int(_sched._SCRIPT_TIMEOUT) + if timeout is not None: return timeout except Exception: logger.warning("Invalid patched _SCRIPT_TIMEOUT=%r; using env/config/default", _sched._SCRIPT_TIMEOUT) - - env_value = os.getenv("HERMES_CRON_SCRIPT_TIMEOUT", "").strip() - if env_value: - try: - timeout = int(float(env_value)) - if timeout > 0: - return timeout - except Exception: - logger.warning("Invalid HERMES_CRON_SCRIPT_TIMEOUT=%r; using config/default", env_value) - - try: - cfg = _sched.load_config() or {} - cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {} - configured = cron_cfg.get("script_timeout_seconds") - if configured is not None: - timeout = int(float(configured)) - if timeout > 0: - return timeout - except Exception as exc: - logger.debug("Failed to load cron script timeout from config: %s", exc) - - return _sched._DEFAULT_SCRIPT_TIMEOUT + resolved = _timeout_from_env_or_config( + "HERMES_CRON_SCRIPT_TIMEOUT", "script_timeout_seconds", _positive_int, "cron script timeout", + ) + return _sched._DEFAULT_SCRIPT_TIMEOUT if resolved is None else resolved _DEFAULT_MEDIA_SEND_TIMEOUT = 300 @@ -69,72 +82,33 @@ _DEFAULT_MEDIA_SEND_TIMEOUT = 300 def _get_media_send_timeout() -> int: """Per-attachment media-send timeout: HERMES_CRON_MEDIA_SEND_TIMEOUT env, then ``cron.media_send_timeout_seconds``, then 300s (long TTS audio can exceed a 30s window).""" - env_value = os.getenv("HERMES_CRON_MEDIA_SEND_TIMEOUT", "").strip() - if env_value: - try: - timeout = int(float(env_value)) - if timeout > 0: - return timeout - except Exception: - logger.warning( - "Invalid HERMES_CRON_MEDIA_SEND_TIMEOUT=%r; using config/default", - env_value, - ) - - try: - cfg = _sched.load_config() or {} - cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {} - configured = cron_cfg.get("media_send_timeout_seconds") - if configured is not None: - timeout = int(float(configured)) - if timeout > 0: - return timeout - except Exception as exc: - logger.debug("Failed to load cron media-send timeout from config: %s", exc) - - return _DEFAULT_MEDIA_SEND_TIMEOUT + resolved = _timeout_from_env_or_config( + "HERMES_CRON_MEDIA_SEND_TIMEOUT", "media_send_timeout_seconds", _positive_int, + "cron media-send timeout", + ) + return _DEFAULT_MEDIA_SEND_TIMEOUT if resolved is None else resolved def _get_session_db_timeout() -> float: """Bound on run_job's SessionDB init: HERMES_CRON_SESSION_DB_TIMEOUT env, then ``cron.session_db_timeout_seconds`` (in DEFAULT_CONFIG), then 10s. Unlike sibling timeouts, 0 is meaningful (unlimited, debugging opt-in), so values pass through untouched.""" - env_value = os.getenv("HERMES_CRON_SESSION_DB_TIMEOUT", "").strip() - if env_value: - try: - return float(env_value) - except (ValueError, TypeError): - logger.warning( - "Invalid HERMES_CRON_SESSION_DB_TIMEOUT=%r; using config/default", - env_value, - ) - - try: - cfg = _sched.load_config() or {} - cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {} - configured = cron_cfg.get("session_db_timeout_seconds") - if configured is not None: - return float(configured) - except Exception as exc: - logger.debug("Failed to load cron.session_db_timeout_seconds from config: %s", exc) - - return 10.0 + resolved = _timeout_from_env_or_config( + "HERMES_CRON_SESSION_DB_TIMEOUT", "session_db_timeout_seconds", float, + "cron.session_db_timeout_seconds", + ) + return 10.0 if resolved is None else resolved def _read_windows_pyvenv_cfg(venv_dir: Path) -> dict[str, str]: - cfg_path = venv_dir / "pyvenv.cfg" try: - lines = cfg_path.read_text(encoding="utf-8").splitlines() + lines = (venv_dir / "pyvenv.cfg").read_text(encoding="utf-8").splitlines() except OSError: return {} - - parsed: dict[str, str] = {} - for raw in lines: - if "=" not in raw: - continue - key, value = raw.split("=", 1) - parsed[key.strip().lower()] = value.strip() - return parsed + return { + key.strip().lower(): value.strip() + for key, value in (raw.split("=", 1) for raw in lines if "=" in raw) + } def _windows_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, str]]: @@ -178,35 +152,12 @@ def _terminate_cron_script_process(proc: subprocess.Popen) -> None: try: subprocess.run( ["taskkill", "/PID", str(proc.pid), "/T", "/F"], - capture_output=True, - timeout=10, - creationflags=_sched.windows_hide_flags(), - check=False, + capture_output=True, timeout=10, creationflags=_sched.windows_hide_flags(), check=False, ) except (OSError, subprocess.TimeoutExpired): proc.kill() else: - try: - process_group: Optional[int] = os.getpgid(proc.pid) - except (ProcessLookupError, OSError): - process_group = None - if process_group is not None: - try: - os.killpg(process_group, signal.SIGTERM) # windows-footgun: ok — POSIX-only branch (win32 handled above) - except (ProcessLookupError, PermissionError, OSError): - process_group = None - if process_group is not None: - with contextlib.suppress(subprocess.TimeoutExpired): - proc.wait(timeout=1.0) - # Escalate if ANY group member survived TERM: a survivor holds the pipe write ends - # open and the caller's communicate() would block on EOF forever. - try: - os.killpg(process_group, 0) # windows-footgun: ok — POSIX-only branch - except (ProcessLookupError, OSError): - process_group = None - if process_group is not None: - with contextlib.suppress((ProcessLookupError, PermissionError, OSError)): - os.killpg(process_group, getattr(signal, "SIGKILL", signal.SIGTERM)) + _terminate_process_group(proc) try: proc.wait(timeout=1.0) except subprocess.TimeoutExpired: @@ -214,6 +165,24 @@ def _terminate_cron_script_process(proc: subprocess.Popen) -> None: proc.wait(timeout=1.0) +def _terminate_process_group(proc: subprocess.Popen) -> None: + """POSIX: TERM the script's process group, then KILL if ANY member survived (a survivor holds + the pipe write ends open and the caller's communicate() would block on EOF forever).""" + try: + process_group = os.getpgid(proc.pid) + os.killpg(process_group, signal.SIGTERM) # windows-footgun: ok — POSIX-only branch (win32 handled by caller) + except (ProcessLookupError, PermissionError, OSError): + return + with contextlib.suppress(subprocess.TimeoutExpired): + proc.wait(timeout=1.0) + try: + os.killpg(process_group, 0) # windows-footgun: ok — POSIX-only branch + except (ProcessLookupError, OSError): + return + with contextlib.suppress((ProcessLookupError, PermissionError, OSError)): + os.killpg(process_group, getattr(signal, "SIGKILL", signal.SIGTERM)) + + def _terminate_cron_script_tree(proc: subprocess.Popen) -> None: """Terminate a script tree, then fall back to the local process-group path.""" if proc.poll() is not None: @@ -222,8 +191,7 @@ def _terminate_cron_script_tree(proc: subprocess.Popen) -> None: pid = getattr(proc, "pid", None) if not isinstance(pid, int) or pid <= 0: logger.warning( - "Cron script tree-kill received invalid pid %r; " - "falling back to process-group termination", + "Cron script tree-kill received invalid pid %r; falling back to process-group termination", pid, ) _sched._terminate_cron_script_process(proc) @@ -234,8 +202,7 @@ def _terminate_cron_script_tree(proc: subprocess.Popen) -> None: from agent.deadline import kill_process_tree except Exception: logger.warning( - "agent.deadline.kill_process_tree unavailable; " - "falling back to process-group termination", + "agent.deadline.kill_process_tree unavailable; falling back to process-group termination", exc_info=True, ) _sched._terminate_cron_script_process(proc) @@ -244,16 +211,13 @@ def _terminate_cron_script_tree(proc: subprocess.Popen) -> None: if kill_process_tree(pid): return logger.warning( - "Cron script tree-kill reported no signal for pid %s; " - "falling back to process-group termination", + "Cron script tree-kill reported no signal for pid %s; falling back to process-group termination", pid, ) except Exception: logger.warning( - "Cron script tree-kill failed for pid %s; " - "falling back to process-group termination", - pid, - exc_info=True, + "Cron script tree-kill failed for pid %s; falling back to process-group termination", + pid, exc_info=True, ) _sched._terminate_cron_script_process(proc) @@ -274,18 +238,12 @@ def _drain_script_pipes(proc: subprocess.Popen) -> None: proc.wait(timeout=5.0) -def _windows_cron_bootstrap_argv( - python_exe: str, - env_overlay: dict[str, str], - script_path: str, -) -> list[str]: +def _windows_cron_bootstrap_argv(python_exe: str, env_overlay: dict[str, str], script_path: str) -> list[str]: """Bootstrap a cron script under the base interpreter with ``.pth`` support. - Overlay mode runs base ``python.exe`` (avoids the launcher flashing a console window) with the venv on ``PYTHONPATH`` — but ``.pth`` files are only processed by ``site.addsitedir()``, so editable installs would be invisible. Bootstrap via addsitedir + ``runpy.run_path`` (keeps - ``__file__`` and ``sys.path[0]`` semantics); plain invocation if the venv is unresolvable. - """ + ``__file__`` and ``sys.path[0]`` semantics); plain invocation if the venv is unresolvable.""" site_packages = _sched.Path(env_overlay.get("VIRTUAL_ENV", "")) / "Lib" / "site-packages" if not site_packages.is_dir(): # Warn: silent fallback would make "editable installs invisible" undiagnosable. @@ -306,74 +264,76 @@ def _windows_cron_bootstrap_argv( return [python_exe, "-c", bootstrap, script_path] -def _run_job_script( - script_path: str, - workdir: Optional[str] = None, - cancel_event: Optional[_CancelEventLike] = None, -) -> tuple[bool, str]: - """Execute a cron job's script and return ``(success, output)``; on failure *output* is the - error message for the LLM to report. - - Scripts MUST resolve inside HERMES_HOME/scripts/ (relative, absolute and ``~`` paths are all - validated — path traversal / absolute-path injection). Interpreter by extension: - ``.sh``/``.bash`` → bash, else ``sys.executable``. Env goes through ``build_subprocess_env`` - (SECURITY.md §2.3). - ``workdir`` sets the subprocess cwd only; the Python process cwd is NEVER mutated (an - ``os.chdir()`` would leak into concurrent gateway sessions). - """ +def _resolve_script_path(script_path: str) -> tuple[Optional[Path], Optional[str]]: + """Validate a job script path; ``(path, None)`` or ``(None, error)``. Scripts MUST resolve inside + HERMES_HOME/scripts/ (relative, absolute and ``~`` paths are all validated — path traversal / + absolute-path injection). Same contract as cron.lifecycle_guard._expand_candidate_path.""" scripts_dir = _sched._get_hermes_home() / "scripts" _ensure_cron_dir(scripts_dir) scripts_dir_resolved = scripts_dir.resolve() - # Same contract as cron.lifecycle_guard._expand_candidate_path. Reject NUL eagerly: on Windows - # Path ops raise ValueError *after* expanduser so the try below would not catch it. str() first - # so the guard itself cannot raise on a non-str script_path. + # Reject NUL eagerly: on Windows Path ops raise ValueError *after* expanduser so the try below + # would not catch it. str() first so the guard itself cannot raise on a non-str script_path. if "\x00" in str(script_path): - return False, f"Blocked: script path contains a NUL byte: {script_path!r}" - + return None, f"Blocked: script path contains a NUL byte: {script_path!r}" try: raw = _sched.Path(script_path).expanduser() except (ValueError, RuntimeError, OSError): # RuntimeError: unexpandable ``~`` (no resolvable HOME). - return False, f"Blocked: script path is not a valid filesystem path: {script_path!r}" + return None, f"Blocked: script path is not a valid filesystem path: {script_path!r}" path = raw.resolve() if raw.is_absolute() else (scripts_dir / raw).resolve() # Traversal / absolute-path / symlink escape guard — MUST stay inside HERMES_HOME/scripts/. try: path.relative_to(scripts_dir_resolved) except ValueError: - return False, ( + return None, ( f"Blocked: script path resolves outside the scripts directory " f"({scripts_dir_resolved}): {script_path!r}" ) - if not path.exists(): - return False, f"Script not found: {path}" + return None, f"Script not found: {path}" if not path.is_file(): - return False, f"Script path is not a file: {path}" + return None, f"Script path is not a file: {path}" + return path, None - script_timeout = _sched._get_script_timeout() - # Interpreter by extension; the shebang is deliberately NOT honoured (small, auditable surface). - suffix = path.suffix.lower() - if suffix in {".sh", ".bash"}: +def _script_argv(path: Path) -> tuple[Optional[list[str]], dict[str, str], Optional[str]]: + """``(argv, env_overlay, error)`` for a validated script. Interpreter by extension — the shebang + is deliberately NOT honoured (small, auditable surface): ``.sh``/``.bash`` → bash, else + ``sys.executable`` (Windows uv-venv overlay gets the .pth bootstrap).""" + if path.suffix.lower() in {".sh", ".bash"}: # which() finds Git Bash on Windows; None there → clear error instead of a "[WinError 2]". _bash = shutil.which("bash") or ("/bin/bash" if os.path.isfile("/bin/bash") else None) if _bash is None: - return False, ( + return None, {}, ( f"Cannot run .sh/.bash script {path.name!r}: bash not found on PATH. " "On Windows, install Git for Windows (which ships Git Bash) " "or rewrite the script as Python (.py)." - ) - argv = [_bash, str(path)] - env_overlay: dict[str, str] = {} - else: - python_exe, env_overlay = _sched._windows_cron_python_invocation(sys.executable) - if env_overlay: - # Windows uv-venv overlay: needs the .pth bootstrap for editable installs. - argv = _windows_cron_bootstrap_argv(python_exe, env_overlay, str(path)) - else: - argv = [python_exe, str(path)] + ) + return [_bash, str(path)], {}, None + python_exe, env_overlay = _sched._windows_cron_python_invocation(sys.executable) + if env_overlay: + return _windows_cron_bootstrap_argv(python_exe, env_overlay, str(path)), env_overlay, None + return [python_exe, str(path)], env_overlay, None + + +def _run_job_script( + script_path: str, + workdir: Optional[str] = None, + cancel_event: Optional[_CancelEventLike] = None, +) -> tuple[bool, str]: + """Execute a cron job's script and return ``(success, output)``; on failure *output* is the + error message for the LLM to report. Env goes through ``build_subprocess_env`` (SECURITY.md + §2.3). ``workdir`` sets the subprocess cwd only; the Python process cwd is NEVER mutated (an + ``os.chdir()`` would leak into concurrent gateway sessions).""" + path, err = _resolve_script_path(script_path) + if path is None: + return False, err + script_timeout = _sched._get_script_timeout() + argv, env_overlay, err = _script_argv(path) + if argv is None: + return False, err try: from tools.environments.local import build_subprocess_env @@ -381,36 +341,27 @@ def _run_job_script( popen_kwargs: dict[str, Any] = {"start_new_session": True} if sys.platform == "win32": popen_kwargs = { - "creationflags": _sched.windows_hide_flags() - | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0), + "creationflags": _sched.windows_hide_flags() | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0), "encoding": "utf-8", "errors": "replace", } env = build_subprocess_env() env.update(env_overlay) # Subprocess cwd only (default: scripts-dir parent). NEVER os.chdir() the process. - _script_cwd = workdir or str(path.parent) proc = subprocess.Popen( - argv, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - cwd=_script_cwd, - env=env, - **popen_kwargs, + argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + cwd=workdir or str(path.parent), env=env, **popen_kwargs, ) deadline = time.monotonic() + script_timeout while True: + # Tree-kill on cancel AND timeout: killpg misses setsid grandchildren (watchdogs, + # backgrounded shell jobs); kill_process_tree snapshots descendants BEFORE signalling. if cancel_event is not None and cancel_event.is_set(): - # Tree-kill here too: a cancelled fire must not orphan own-session grandchildren. _sched._terminate_cron_script_tree(proc) _drain_script_pipes(proc) return False, "Script cancelled because cron fire ownership was lost" remaining = deadline - time.monotonic() if remaining <= 0: - # Timeout must leave ZERO descendants: killpg misses setsid grandchildren - # (watchdogs, backgrounded shell jobs); kill_process_tree snapshots descendants - # BEFORE signalling. _sched._terminate_cron_script_tree(proc) _drain_script_pipes(proc) return False, f"Script timed out after {script_timeout}s: {path}" @@ -430,8 +381,7 @@ def _run_job_script( stderr = redact_sensitive_text(stderr) except Exception as e: logger.warning("Failed to redact sensitive text from output: %s", e) - stdout = "[REDACTED - redaction failed]" - stderr = "[REDACTED - redaction failed]" + stdout = stderr = "[REDACTED - redaction failed]" if proc.returncode != 0: parts = [f"Script exited with code {proc.returncode}"] @@ -440,9 +390,7 @@ def _run_job_script( if stdout: parts.append(f"stdout:\n{stdout}") return False, "\n".join(parts) - return True, stdout - except Exception as exc: return False, f"Script execution failed: {exc}" @@ -451,9 +399,7 @@ def _start_heartbeat_thread(loop_fn, name: str, fail_log) -> Optional[threading. """Start ``loop_fn`` on a daemon thread inside a copy of the current context (multiplexed profile ContextVars). On failure calls ``fail_log()`` inside the except (traceback intact) and returns None.""" - thread = threading.Thread( - target=contextvars.copy_context().run, args=(loop_fn,), name=name, daemon=True, - ) + thread = threading.Thread(target=contextvars.copy_context().run, args=(loop_fn,), name=name, daemon=True) try: thread.start() except Exception: @@ -478,11 +424,7 @@ def _run_job_script_with_claim_heartbeat( schedule = job.get("schedule") claim = job.get("run_claim") owner = str(claim.get("by") or "") if isinstance(claim, dict) else "" - if not ( - isinstance(schedule, dict) - and schedule.get("kind") == "once" - and owner - ): + if not (isinstance(schedule, dict) and schedule.get("kind") == "once" and owner): return _sched._run_job_script(script_path, workdir=workdir, cancel_event=cancel_event) job_id = str(job.get("id") or "") @@ -497,9 +439,7 @@ def _run_job_script_with_claim_heartbeat( heartbeat_thread = _start_heartbeat_thread( _heartbeat_loop, "cron-script-claim-heartbeat", - lambda: logger.debug( - "Job '%s': could not start script run_claim heartbeat", job_id, exc_info=True, - ), + lambda: logger.debug("Job '%s': could not start script run_claim heartbeat", job_id, exc_info=True), ) if heartbeat_thread is None: return _sched._run_job_script(script_path, workdir=workdir, cancel_event=cancel_event)