diff --git a/cron/scheduler.py b/cron/scheduler.py index e94ff86858..f1cd08125c 100644 --- a/cron/scheduler.py +++ b/cron/scheduler.py @@ -2,7 +2,6 @@ A file lock (~/.hermes/cron/.tick.lock) keeps overlapping processes to one tick at a time. """ -import asyncio import atexit import concurrent.futures import contextlib @@ -12,8 +11,7 @@ import json import logging import os import re -import shutil -import signal +import shutil # noqa: F401 (tests reach shutil.which through cron.scheduler) import subprocess import sys import threading @@ -39,7 +37,7 @@ from typing import Any, Callable, List, Optional, Protocol sys.path.insert(0, str(Path(__file__).parent.parent)) from hermes_constants import get_hermes_home -from hermes_cli._subprocess_compat import windows_hide_flags +from hermes_cli._subprocess_compat import windows_hide_flags # noqa: F401 (tests patch cron.scheduler.windows_hide_flags) from hermes_cli.config import ( _expand_env_vars, cron_model_drift_axes, @@ -471,38 +469,6 @@ def _resolve_job_reasoning_config(job: dict, cfg: dict, model: str) -> dict | No return resolve_reasoning_config(cfg if isinstance(cfg, dict) else {}, str(model)) -# Validates user-supplied delivery platform names, preventing env-var enumeration via crafted names. -_KNOWN_DELIVERY_PLATFORMS = frozenset({ - "telegram", "discord", "slack", "whatsapp", "signal", - "matrix", "mattermost", "homeassistant", "dingtalk", "feishu", - "wecom", "wecom_callback", "weixin", "sms", "email", "webhook", "bluebubbles", - "qqbot", "yuanbao", -}) - -# Platforms supporting a cron/notification home target -> env var used by gateway config. -_HOME_TARGET_ENV_VARS = { - "matrix": "MATRIX_HOME_ROOM", - "telegram": "TELEGRAM_HOME_CHANNEL", - "discord": "DISCORD_HOME_CHANNEL", - "slack": "SLACK_HOME_CHANNEL", - "signal": "SIGNAL_HOME_CHANNEL", - "mattermost": "MATTERMOST_HOME_CHANNEL", - "sms": "SMS_HOME_CHANNEL", - "email": "EMAIL_HOME_ADDRESS", - "dingtalk": "DINGTALK_HOME_CHANNEL", - "feishu": "FEISHU_HOME_CHANNEL", - "wecom": "WECOM_HOME_CHANNEL", - "weixin": "WEIXIN_HOME_CHANNEL", - "bluebubbles": "BLUEBUBBLES_HOME_CHANNEL", - "qqbot": "QQBOT_HOME_CHANNEL", - "whatsapp": "WHATSAPP_HOME_CHANNEL", - "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. -_LEGACY_HOME_TARGET_ENV_VARS = {"QQBOT_HOME_CHANNEL": "QQ_HOME_CHANNEL"} - from cron.jobs import ( _ensure_cron_dir, advance_next_runs, @@ -1115,1892 +1081,6 @@ def _reclaim_fds_best_effort() -> None: apply_nofile_soft_limit(None) -def _resolve_cron_surface_mode(pconfig, logical_platform_name: str) -> str: - """Return ``"in_channel"`` or ``"thread"`` (default) for a platform config. - - Native: flat ``platforms.

.extra.cron_continuable_surface``. Relay-fronted: - ``platforms.relay.extra..cron_continuable_surface`` (same sub-block as the relay's - Slack knobs); the sub-block wins over the flat key and is scoped to its logical platform. - Unlike _relay_slack_extra (all-or-nothing), this falls back to the flat key when the sub-block - omits the knob — deliberate, the flat key must keep working — so a flat value applies to EVERY - platform the relay fronts (only the D6 capability gate contains it). Scope it on multi-platform - relays. - """ - with contextlib.suppress(Exception): - extra = getattr(pconfig, "extra", None) or {} - sub = extra.get(str(logical_platform_name or "").lower()) - if isinstance(sub, dict) and sub.get("cron_continuable_surface") is not None: - raw = sub.get("cron_continuable_surface") - else: - raw = extra.get("cron_continuable_surface") - if raw is not None and str(raw).strip().lower() == "in_channel": - return "in_channel" - return "thread" - - -def _resolve_origin(job: dict) -> Optional[dict]: - """Extract origin info from a job. Non-dict origins (provenance strings, hand-edited - jobs.json) are treated as missing — otherwise every fire crashed on ``origin.get``.""" - origin = job.get("origin") - if isinstance(origin, dict) and origin.get("platform") and origin.get("chat_id"): - return origin - return None - - -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/thread-surface mirror. The mirror uses ``mirror_to_session`` at a turn boundary, so it - is alternation- and cache-safe. - """ - per_job = job.get("attach_to_session") - if isinstance(per_job, bool): - return per_job - try: - if cfg is None: - cfg = load_config() or {} - return bool((cfg.get("cron", {}) or {}).get("mirror_delivery", False)) - except Exception: - return False - - -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. - """ - 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 "") - - -# Provenance rank for the dedup OR-merge in _resolve_delivery_targets (higher = stronger mirror -# claim). Broadcasts rank 0 so "origin,all"/"all,origin" keep the origin tag regardless of order. -_MIRROR_PROVENANCE_RANK = {"origin": 3, "origin_fallback": 2, "explicit": 1} - - -def _target_mirror_eligible( - job: dict, - target: dict, - *, - global_mirror: bool, - origin_match: Optional[bool] = None, -) -> bool: - """Whether a resolved delivery target may receive the transcript mirror. - - Origin targets: always. ``origin_fallback`` (deliver=origin with no captured origin → home - channel, standing in for the user's primary conversation): same flags as a true origin. - ``explicit`` ``platform:chat_id``: ONLY with per-job ``attach_to_session: true`` — the global - flag must never write transcripts into arbitrary explicitly-addressed chats (shared channels, - other users' DMs). Untagged broadcasts (``all``, bare-platform home) are never eligible. - ``origin_match`` may be precomputed by the caller; computed here when ``None``. - """ - if origin_match is None: - origin = _resolve_origin(job) or {} - origin_match = _target_matches_origin( - origin, target.get("platform", ""), target.get("chat_id", ""), - target.get("thread_id"), - ) - if origin_match: - return True - resolved_from = target.get("_resolved_from") - if resolved_from == "origin_fallback": - # 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) - 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. - """ - return bool(is_dm or user_id) - - -def _maybe_mirror_cron_delivery( - job: dict, - platform_name: str, - chat_id: str, - mirror_text: str, - thread_id: Optional[str] = None, - user_id: Optional[str] = None, - *, - 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 - ``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. - """ - if not enabled: - return - text = (mirror_text or "").strip() - if not text: - return - try: - from gateway.mirror import mirror_to_session - - # 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", - ) - if ok: - logger.info( - "Job '%s': mirrored delivery into %s:%s session transcript", - job.get("id", "?"), platform_name, chat_id, - ) - else: - logger.debug( - "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, - ) - - -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}" - 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] - 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.get("id", "?"), getattr(adapter, "name", "?"), e, - ) - return None - - -def _seed_cron_session( - job: dict, - adapter, - platform_name: str, - chat_id: str, - text: str, - *, - thread_id: Optional[str], - chat_type: str, - user_id: Optional[str], - user_name: Optional[str] = None, - chat_name: Optional[str], - scope_id: Optional[str], - discord_keys_on_thread: bool = False, -) -> bool: - """Create the session row (so the mirror has a target) and mirror the brief as a USER turn. - The seeded key must equal the reply's ``build_session_key``: chat_type, user_id, thread_id and - scope_id (Slack team id) are all part of it, so callers pass exactly what the reply carries.""" - from gateway.config import Platform - from gateway.session import SessionSource - - seeded_session_id: Optional[str] = None - session_store = getattr(adapter, "_session_store", None) - if session_store is not None: - try: - platform_enum = Platform(platform_name.lower()) - except (ValueError, KeyError): - platform_enum = None - if platform_enum is not None: - # 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) - ) - 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, - 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) - - 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, - ) - - -def _seed_cron_thread_session( - job: dict, - adapter, - platform_name: str, - chat_id: str, - thread_id: str, - mirror_text: str, - chat_name: Optional[str] = None, - is_dm: bool = False, - scope_id: Optional[str] = None, -) -> None: - """Seed the freshly-opened cron thread's session with the brief (never raises), else the - user's in-thread reply resolves to a transcript without it. Threads are participant-shared (no - real user_id); a DM thread must seed ``chat_type="dm"`` — DM-thread replies route through the DM - arm (``…:dm::``), so a "thread"-typed seed is a row no DM reply ever hits.""" - text = (mirror_text or "").strip() - if not text: - return - 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, - discord_keys_on_thread=True, - ) - if ok: - logger.info( - "Job '%s': opened continuable thread %s on %s:%s and seeded the brief", - job.get("id", "?"), thread_id, platform_name, chat_id, - ) - else: - logger.warning( - "Job '%s': thread seed did NOT land on %s:%s thread=%s — an " - "in-thread reply will not see this brief", - job.get("id", "?"), platform_name, chat_id, thread_id, - ) - except Exception as e: - # WARNING, not debug: a silent seed failure IS the continuation-amnesia bug. - logger.warning( - "Job '%s': seeding cron thread session failed for %s:%s:%s: %s", - job.get("id", "?"), platform_name, chat_id, thread_id, e, - ) - - -def _seed_cron_channel_session( - job: dict, - adapter, - platform_name: str, - chat_id: str, - mirror_text: str, - *, - is_dm: bool, - user_id: Optional[str], - chat_name: Optional[str] = None, - scope_id: Optional[str] = None, -) -> bool: - """Seed the FLAT (thread_id=None) session for an ``in_channel`` delivery; True on success. - ``mirror_to_session`` only APPENDS to an existing session and the flat row is only created by an - inbound human message, so the row must be created first or the brief is silently dropped. Group - keys are user-isolated (``…:group::``): the seed MUST carry the origin's real - user_id, not ``system:cron``; DM keys omit user_id. chat_type mirrors the inbound handler.""" - text = (mirror_text or "").strip() - if not text: - return False - try: - chat_type = "dm" if is_dm else "group" - 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, - ) - if ok: - logger.info( - "Job '%s': seeded flat in_channel session on %s:%s (chat_type=%s)", - job.get("id", "?"), platform_name, chat_id, chat_type, - ) - return bool(ok) - except Exception as e: - # WARNING, not debug: a silent seed failure IS the continuation-amnesia bug. - logger.warning( - "Job '%s': seeding in_channel session failed for %s:%s: %s", - job.get("id", "?"), platform_name, chat_id, e, - ) - return False - - -def _cron_job_origin_log_suffix(job: dict) -> str: - """Secret-free provenance suffix (origin platform/chat/source-IP fields) for security warnings - about a bad stored ``context_from`` reference, where no live request object exists.""" - 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) - if value is None: - continue - text = str(value).replace("\r", " ").replace("\n", " ").strip() - if text: - fields.append(f"origin_{key}={text[:200]!r}") - return " " + " ".join(fields) if fields else "" - - -def _plugin_cron_env_var(platform_name: str) -> str: - """Cron home-channel env var registered by a plugin ``PlatformEntry.cron_deliver_env_var``.""" - with contextlib.suppress(Exception): - from hermes_cli.plugins import discover_plugins - discover_plugins() # idempotent - from gateway.platform_registry import platform_registry - entry = platform_registry.get(platform_name.lower()) - if entry and entry.cron_deliver_env_var: - return entry.cron_deliver_env_var - return "" - - -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)) - - -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) - - -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. - """ - try: - from gateway.config import load_gateway_config, Platform - - config = load_gateway_config() - platform = Platform(platform_name.lower()) - return config.get_home_channel(platform) - except Exception: - 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). - - 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. - """ - env_var = _resolve_home_env_var(platform_name) - if not env_var: - return "" - try: - from agent.secret_scope import get_secret - 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, "") - if not value: - legacy = _LEGACY_HOME_TARGET_ENV_VARS.get(env_var) - if legacy: - value = os.getenv(legacy, "") - return value - - -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``.""" - value = _env_home_target_chat_id(platform_name) - 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 "" - - -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 "" - - if platform_name.lower() == "telegram": - cron_thread = _scope_get("TELEGRAM_CRON_THREAD_ID").strip() - 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() - if value: - return value - # config.yaml fallback only when the chat id also came from config (an env-provided chat id - # keeps its env-provided thread semantics). - if not _env_home_target_chat_id(platform_name): - home = _get_config_home_channel(platform_name) - if home is not None and home.thread_id: - return str(home.thread_id) - return None - - -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 - with contextlib.suppress(Exception): - from hermes_cli.plugins import discover_plugins - discover_plugins() # idempotent - from gateway.platform_registry import platform_registry - for entry in platform_registry.plugin_entries(): - if entry.cron_deliver_env_var and entry.name not in _HOME_TARGET_ENV_VARS: - yield entry.name - - -def _relay_fronted_delivery_platforms(connected: set) -> set: - """Logical platforms deliverable through a connected relay. ``get_connected_platforms()`` only - sees native platforms; fronted ones come from the same ``GATEWAY_RELAY_PLATFORMS`` stamp - fire-time routing uses (validation symmetric with routing). No relay -> empty set.""" - if "relay" not in connected: - return set() - try: - from gateway.relay import relay_fronted_platforms - - return relay_fronted_platforms() - except Exception: - logger.debug("relay fronted-platform lookup failed", exc_info=True) - return set() - - -def cron_delivery_targets() -> list[dict]: - """Platforms a cron job can auto-deliver to (single source of truth for UIs). - - Included when a valid delivery platform AND gateway-configured; ``home_target_set`` flags - whether the home channel exists. Returns ``{"id", "name", "home_target_set", "home_env_var"}`` - dicts in canonical order; callers prepend the implicit ``local`` option themselves. - """ - 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 |= _relay_fronted_delivery_platforms(connected) - except Exception: - logger.debug("cron_delivery_targets: gateway config unavailable", exc_info=True) - connected = set() - - for name in _iter_home_target_platforms(): - if name not in connected: - continue - if not _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(_get_home_target_chat_id(name)), - "home_env_var": env_var 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, - } - ) - 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. - """ - if str(origin.get("platform") or "").lower() != "slack" or not origin.get("thread_id"): - return False - home_chat = _get_home_target_chat_id("slack") - return bool(home_chat) and str(origin.get("chat_id")) == str(home_chat) - - -def _origin_delivery_thread(origin: dict): - """The thread a deliver=origin job should use, stale stamps dropped.""" - if _origin_thread_is_stale(origin): - return _get_home_target_thread_id("slack") or None - return origin.get("thread_id") - - -def _home_target(platform_name: str, chat_id: str, resolved_from: Optional[str] = None) -> dict: - """Target dict for a platform's configured home channel (+ optional mirror provenance).""" - target = { - "platform": platform_name, - "chat_id": chat_id, - "thread_id": _get_home_target_thread_id(platform_name), - } - if resolved_from: - target["_resolved_from"] = resolved_from - return target - - -def _resolve_single_delivery_target(job: dict, deliver_value: str) -> Optional[dict]: - """Resolve one concrete auto-delivery target for a cron job.""" - - origin = _resolve_origin(job) - - if deliver_value == "local": - return None - - # Must precede the generic platform:chat_id split so the profile name isn't parsed as chat_id. - bot_chat_profile = parse_bot_chat_deliver_token(deliver_value) - if bot_chat_profile is not None: - return _resolve_bot_chat_target(job, bot_chat_profile) - - if deliver_value == "origin": - if origin: - return { - "platform": origin["platform"], - "chat_id": str(origin["chat_id"]), - "thread_id": _origin_delivery_thread(origin), - # Provenance for _target_mirror_eligible. - "_resolved_from": "origin", - } - # No origin (API/script job): fall back to a home channel instead of silently dropping. - for platform_name in _iter_home_target_platforms(): - chat_id = _get_home_target_chat_id(platform_name) - 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, - ) - # Stands in for the primary conversation (NOT a broadcast): mirror-eligible. - return _home_target(platform_name, chat_id, "origin_fallback") - return None - - if ":" in deliver_value: - 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, - ) - - prepare_send_message_platforms() - # pass_unresolved_references: no model in the loop to react; an unknown-to-directory target - # must reach the adapter as written or the job's output is silently lost. - chat_id, thread_id, resolution_error = resolve_send_target( - platform_key, rest, pass_unresolved_references=True - ) - if resolution_error: - logger.warning("Invalid cron delivery target '%s': %s", deliver_value, resolution_error) - return None - - if ( - thread_id is None - and platform_key == "slack" - and origin - and str(origin.get("platform") or "").lower() == platform_key - and str(origin.get("chat_id")) == str(chat_id) - and origin.get("thread_id") - and not _origin_thread_is_stale(origin) - ): - thread_id = origin.get("thread_id") - - return { - "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", - } - - platform_name = deliver_value - if origin and origin.get("platform") == platform_name: - chat_id = _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"), - } - - if not _is_known_delivery_platform(platform_name): - return None - chat_id = _get_home_target_chat_id(platform_name) - return _home_target(platform_name, chat_id) if chat_id else None - - -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 = load_config() - value = int(cfg.get("cron", {}).get("bot_chat_delivery_timeout_seconds", 600)) - return value if value > 0 else 600 - except Exception: - return 600 - - -def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str]: - """Deliver job output into a profile's canonical Bot Chat as a real inbound user turn. - - Runs ``hermes [-p ] chat --in ~ -c "Bot Chat" --create-if-missing -Q --query-file`` — - the same lane Bot Mode agent-to-agent messages use, so canonical-session rules apply and it is - 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") - 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" - except Exception: - return "bot-chat delivery failed: hermes CLI not resolvable" - - env = os.environ.copy() - if profile: - argv += ["-p", profile] - # -p owns profile resolution; this scheduler's HERMES_HOME must not shadow it. - env.pop("HERMES_HOME", None) - - # 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"Review it, act on anything that needs action, and summarize " - f"for the chat.]\n\n{content}" - ) - - query_file = None - try: - with tempfile.NamedTemporaryFile( - "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, - ] - - result = subprocess.run( - argv, - capture_output=True, - text=True, - timeout=_get_bot_chat_delivery_timeout(), - env=env, - creationflags=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": {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)") - return None - except subprocess.TimeoutExpired: - msg = ( - f"bot-chat delivery to profile '{profile or '(own)'}' 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)" - ) - logger.warning("Job '%s': %s", job_id, msg) - return msg - except Exception as e: - msg = f"bot-chat delivery failed: {str(e) or type(e).__name__}" - logger.warning("Job '%s': %s", job_id, msg, exc_info=True) - return msg - finally: - if query_file: - with contextlib.suppress(OSError): - os.unlink(query_file) - - -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. - """ - if deliver is None or deliver == "": - return "local" - if isinstance(deliver, (list, tuple)): - parts = [str(p).strip() for p in deliver if str(p).strip()] - return ",".join(parts) if parts else "local" - return str(deliver) - - -# Routing tokens resolve at fire time (a job outlives platform wiring). ``all`` = platforms with a -# 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" - - -def parse_bot_chat_deliver_token(part: str) -> Optional[str]: - """``bot-chat[:]`` → ``""`` (own profile), the name, or ``None`` if not a bot-chat token. - Token is case-insensitive; the name is normalized later by the profile layer.""" - raw = (part or "").strip() - lowered = raw.lower() - if lowered == BOT_CHAT_PLATFORM: - return "" - prefix = BOT_CHAT_PLATFORM + ":" - if lowered.startswith(prefix): - return raw[len(prefix):].strip() - return None - - -def _resolve_bot_chat_target(job: dict, profile_arg: str) -> Optional[dict]: - """Resolve a bot-chat token to a delivery target. ``""`` = own profile (no ``-p`` needed); - otherwise the profile must exist locally — cross-machine delivery is intentionally unsupported - so same-named profiles on other gateways can never be targeted by accident.""" - if not profile_arg: - return {"platform": BOT_CHAT_PLATFORM, "chat_id": "", "thread_id": None} - try: - from hermes_cli.profiles import normalize_profile_name, profile_exists - - 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.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, - ) - return None - - -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: - return [part] - expanded: List[str] = [] - for platform_name in _iter_home_target_platforms(): - if _get_home_target_chat_id(platform_name): - expanded.append(platform_name) - return expanded - - -def _delivery_lane_value(job: dict, *, for_failure: bool = False): - """Raw deliver-lane value for a run outcome: the failure lane when ``for_failure`` and the job - overrides it, else ``deliver``. Bookkeeping (outcome classification, unresolved-origin, incident - 'alerted' marking) must read the SAME lane the notice was routed through (NS-788).""" - if for_failure: - failure_deliver = job.get("failure_deliver") - if failure_deliver is not None and str(failure_deliver).strip(): - return failure_deliver - return job.get("deliver", "local") - - -def _resolve_delivery_targets(job: dict, *, for_failure: bool = False) -> List[dict]: - """Resolve auto-delivery targets from comma-separated ``deliver``; ``all`` expands to every - platform with a home channel and combines with explicit targets. Dedup by (platform, chat_id, - thread_id). ``for_failure=True`` (failure summaries, interrupted-run notices, drift/preflight - alerts) resolves from ``failure_deliver`` INSTEAD when the job carries one — ``failure_deliver: - local`` is the structural opt-out for shared channels; absent, failures follow ``deliver``.""" - deliver = _normalize_deliver_value(_delivery_lane_value(job, for_failure=for_failure)) - 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)) - - 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") - return targets - - -def _resolve_delivery_target(job: dict) -> Optional[dict]: - """Resolve the concrete auto-delivery target for a cron job, if any.""" - targets = _resolve_delivery_targets(job) - return targets[0] if targets else None - - -# 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'}) - - -def _send_media_via_adapter( - adapter, - chat_id: str, - media_files: list, - metadata: dict | None, - loop, - job: dict, - platform=None, -) -> list: - """Send MEDIA files as native attachments (routed by extension, as in - _process_message_background). Returns per-file error strings so a dropped attachment surfaces - in run status, not just the gateway log.""" - from gateway.platforms.base import ( - BasePlatformAdapter, should_send_media_as_audio, validate_media_delivery_path, - ) - from agent.async_utils import safe_schedule_threadsafe - - job_ref = {"id": job.get("id", "?")} - errors: list = [] - requested = [(str(p), v) for p, v in (media_files or [])] - media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files) - # Report paths the safety filter dropped (missing file, denied prefix, strict-mode miss). - kept = {p for p, _ in media_files} - for raw_path, _v in requested: - try: - dropped = validate_media_delivery_path(raw_path) not in kept - except Exception: - dropped = True - if dropped: - errors.append(f"attachment dropped by media path policy: {raw_path}") - - route_platform = platform if platform is not None else getattr(adapter, "platform", None) - for media_path, _is_voice in media_files: - try: - ext = Path(media_path).suffix.lower() - if should_send_media_as_audio(route_platform, ext, is_voice=_is_voice): - coro = adapter.send_voice(chat_id=chat_id, audio_path=media_path, metadata=metadata) - elif ext in _VIDEO_EXTS: - coro = adapter.send_video(chat_id=chat_id, video_path=media_path, metadata=metadata) - elif ext in _IMAGE_EXTS: - coro = adapter.send_image_file(chat_id=chat_id, image_path=media_path, metadata=metadata) - else: - coro = adapter.send_document(chat_id=chat_id, file_path=media_path, metadata=metadata) - - 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, - ) - return errors - try: - # Large attachments can exceed 30s; configurable via _get_media_send_timeout(). - result = future.result(timeout=_get_media_send_timeout()) - except TimeoutError: - future.cancel() - 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, - ) - 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, - ) - return errors - - -def _confirm_adapter_delivery(send_result, job_id: str = "?", unverified: Optional[list] = None) -> bool: - """Return True only if ``send_result`` unambiguously confirms delivery. - - ``None`` or no ``success`` attr/key is NOT success (would log "delivered" while nothing was - sent). ``delivered is False`` REJECTS even with truthy ``success``: the silence-narration filter - returns ``{"success": True, "delivered": False}`` (dropped). No ``message_id``/``raw_response`` - is still accepted (some adapters return a bare success) but logged at WARNING as UNVERIFIED. - """ - 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: - return False - if message_id is None and not raw_response: - logger.warning( - "Job '%s': live adapter reported success with no delivery evidence " - "(no message_id, no raw_response) — treating as delivered but " - "UNVERIFIED", - job_id, - ) - if unverified is not None: - unverified.append(True) - return True - - -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``. - Fails SAFE to False (thread routing) without a probe or on any probe error/timeout.""" - # Resolve on the CLASS, not the instance: a MagicMock instance auto-creates a truthy - # ``get_chat_info``, so an instance-level probe would misclassify test doubles. - get_chat_info = getattr(type(runtime_adapter), "get_chat_info", None) - if not callable(get_chat_info): - return False - 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] - ) - 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_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, - ) - return is_channel - - -def _cron_delivery_notify_enabled(cfg: Optional[dict]) -> bool: - """Resolve ``cron.delivery.notify`` (default True). Only an explicit ``False`` disables; a - 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 - except Exception: - return True - - -def _record_delivery_verification(job: dict, unverified_targets: list) -> None: - """Persist ``last_delivery_unverified``: list of ``platform:chat_id`` targets acked with no - evidence, or None. Skips the write when unchanged; never raises (bookkeeping must not fail a - delivery).""" - new_value = list(unverified_targets) or None - if (job.get("last_delivery_unverified") or None) == new_value: - return - try: - from cron.jobs import update_job - - update_job(job["id"], {"last_delivery_unverified": new_value}) - except Exception as exc: # pragma: no cover - defensive - logger.debug("Job '%s': could not record delivery verification: %s", job.get("id"), exc) - - -@dataclass -class _TargetDelivery: - """Per-target delivery state shared by the live-adapter and standalone lanes.""" - - job: dict - platform: Any - platform_name: str - chat_id: str - thread_id: Optional[str] - transport: Any - pconfig: Any - runtime_adapter: Any - target_adapters: Any - config: Any - loop: Any - notify_delivery: bool - origin: dict - origin_target: bool - origin_user_id: Optional[str] - is_dm_target: bool - mirror_text: str - mirror_this_target: bool - in_channel_surface: bool - inchannel_continuable: bool - opened_thread_id: Optional[str] - - @property - def is_relay(self) -> bool: - return self.transport is not None and self.transport.is_relay - - @property - def where(self) -> str: - return f"{self.platform_name}:{self.chat_id}" - - -def _note_target_error(job: dict, msg: str, errors: list) -> None: - """Log a per-target delivery failure as a WARNING and record it in ``errors``.""" - logger.warning("Job '%s': %s", job["id"], msg) - errors.append(msg) - - -def _warn_live_lane_failure(job: dict, msg: str, is_relay: bool) -> None: - """Relay targets have no standalone fallback, so the log line must not promise one.""" - if is_relay: - logger.warning("Job '%s': %s", job["id"], msg) - else: - logger.warning("Job '%s': %s, falling back to standalone", job["id"], msg) - - -def _resolve_target_transport(job: dict, platform, platform_name: str, target: dict, adapters, config): - """Resolve ``(transport, pconfig, runtime_adapter, target_adapters)`` for one target, or - ``(None, error)`` when it cannot be served (relay-fronted with no live transport, or not - configured/enabled).""" - from gateway.delivery import resolve_delivery_transport - - target_adapters = adapters - if isinstance(adapters, SharedRouteAdapters): - # Credentialless satellite: the primary adapter serves THIS target only when an exact - # primary route maps it to this profile; a miss fails closed below. - shared = adapters.get(platform, target) - target_adapters = {platform: shared} if shared is not None else {} - transport = resolve_delivery_transport(platform, config, target_adapters) - if transport is not None: - pconfig = transport.config - runtime_adapter = transport.adapter - else: - # Relay-fronted platforms have NO standalone fallback (the connector owns the credential), - # so surface that instead of the native configured/enabled gate, which misdiagnoses them. - from gateway.relay import relay_fronted_platforms - - if platform_name in relay_fronted_platforms(): - return None, ( - f"platform '{platform_name}' is relay-fronted and has no " - "live gateway transport; start the gateway (its ticker " - "owns relay-fronted delivery and will fire the job on " - "schedule)" - ) - pconfig = config.platforms.get(platform) - runtime_adapter = None - - if transport is not None and transport.is_relay: - # Relay transport carries the RELAY adapter's config (enablement already checked). The - # logical platform is deliberately NOT natively enabled, so the native gate must not apply. - if pconfig is None: - from gateway.config import PlatformConfig - pconfig = PlatformConfig(enabled=True) - elif not pconfig or not pconfig.enabled: - return None, f"platform '{platform_name}' not configured/enabled" - return (transport, pconfig, runtime_adapter, target_adapters), None - - -def _inchannel_surface_supported(runtime_adapter, platform_name: str) -> bool: - """D6 probe: can this adapter deliver a continuable in_channel brief on ``platform_name``? - Per-platform check first (one RelayAdapter fronts N platforms; the scalar attr only carries - the PRIMARY identity's bit); native adapters use the class attribute.""" - per_platform_check = getattr(runtime_adapter, "supports_inchannel_continuable_for_platform", None) - if callable(per_platform_check): - try: - return bool(per_platform_check(platform_name)) - except Exception: - return False - return bool(getattr(runtime_adapter, "supports_inchannel_continuable", False)) - - -def _live_route_metadata(t: _TargetDelivery) -> tuple[Optional[str], dict, dict]: - """Compute ``(route_thread_id, route_metadata, media_metadata)`` for a live send, ONCE so text - and media agree. ``telegram::`` is ambiguous (private - forum topic vs channel DM topic need OPPOSITE routing) — see ``_is_channel_dm_topic``. - ``thread_id`` rides in ``route_metadata`` to bypass the DeliveryRouter's private-chat - reply-anchor requirement for anchorless cron sends.""" - from gateway.config import Platform - from gateway.delivery import _looks_like_int, looks_like_telegram_private_chat_id - - job = t.job - thread_id = t.thread_id - is_ambiguous_telegram_topic = ( - t.platform == Platform.TELEGRAM - and thread_id is not None - 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"], - ): - # 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, - } - media_metadata = {"direct_messages_topic_id": str(thread_id), "notify": t.notify_delivery} - else: - # Forum-style topic or non-topic target: message_thread_id. - route_thread_id = str(thread_id) if thread_id is not None else None - route_metadata = {"job_id": job["id"], "notify": t.notify_delivery} - if route_thread_id: - route_metadata["thread_id"] = route_thread_id - media_metadata = {"notify": t.notify_delivery} - if thread_id: - media_metadata["thread_id"] = thread_id - - # Relay egress needs metadata.scope_id (fail-closed tenant guard; scope cache is COLD after a - # restart; router stamps HOME only). Origin targets only: a wrong fan-out scope is worse than - # none. - if t.origin_target and t.origin.get("scope_id"): - route_metadata.setdefault("scope_id", str(t.origin["scope_id"])) - media_metadata.setdefault("scope_id", str(t.origin["scope_id"])) - return route_thread_id, route_metadata, media_metadata - - -def _live_send_text( - t: _TargetDelivery, - text_to_send: str, - route_thread_id: Optional[str], - route_metadata: dict, - *, - target_errors: list, - delivery_errors: list, - unverified_targets: list, -) -> tuple[bool, bool, Any]: - """Schedule the text send on the gateway loop; returns ``(adapter_ok, timed_out, message_id)``. - Re-raises a real send error so the caller falls through to standalone.""" - from agent.async_utils import safe_schedule_threadsafe - from gateway.delivery import DeliveryRouter, DeliveryTarget - - 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, - ) - # 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, - ) - if future is None: - target_errors.append("live adapter event loop scheduling failed") - return False, False, None - try: - send_result = future.result(timeout=60) - except TimeoutError: - # Slow confirmation != failure; future.cancel() disambiguates. False -> already in flight, - # 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" - ) - logger.warning("Job '%s': %s, falling back to standalone", job["id"], msg) - target_errors.append(msg) - return False, False, None - logger.warning( - "Job '%s': live adapter send to %s:%s timed out " - "after 60s; already dispatched (in flight), " - "assuming delivered (skipping standalone fallback " - "to avoid duplicate)", - job["id"], t.platform_name, t.chat_id, - ) - return True, True, None - except Exception as ex: - # Real send error (not a slow confirmation): fall through to standalone. - target_errors.append(f"live adapter send failed: {ex}") - raise - - # _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) - _evidence_gap: list = [] - send_success = _confirm_adapter_delivery(send_result, job["id"], _evidence_gap) - if send_success and _evidence_gap: - unverified_targets.append(t.where) - - if not send_success: - if isinstance(send_result, dict): - # A filtered drop carries no "error" — name the filter instead of reporting "unknown". - err = send_result.get("error") or send_result.get("filtered") or "unknown" - shape = "dict" - elif send_result is not None: - err = getattr(send_result, "error", None) - shape = type(send_result).__name__ - else: - err = "no response from adapter" - shape = "None" - msg = f"live adapter send to {t.where} returned unconfirmed result ({shape}, error={err})" - _warn_live_lane_failure(job, msg, t.is_relay) - target_errors.append(msg) - return False, False, None - if send_raw_response and t.thread_id and send_raw_response.get("thread_fallback"): - 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", - delivery_errors, - ) - return True, False, delivered_message_id - - -def _live_send_media(t: _TargetDelivery, media_metadata: dict, media_files: list, delivery_errors: list) -> None: - """Send extracted media as native attachments with the same routing as the text send.""" - routed_media_metadata = dict(media_metadata or {}) - if t.is_relay: - routed_media_metadata["_relay_logical_platform"] = t.platform.value - logical_home = t.config.get_home_channel(t.platform) - if logical_home is not None and logical_home.chat_id == t.chat_id: - if logical_home.user_id: - routed_media_metadata["user_id"] = logical_home.user_id - if logical_home.scope_id: - routed_media_metadata["scope_id"] = logical_home.scope_id - _media_errors = _send_media_via_adapter( - 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: - delivery_errors.append(f"{_me} (target {t.where})") - - -def _seed_live_delivery_sessions(t: _TargetDelivery, delivered_message_id) -> None: - """After a confirmed live send, seed continuation session(s) and run the generic mirror. - Thread seeding is deferred here so open-succeeds/deliver-fails never seeds an unseen brief.""" - job = t.job - origin = t.origin - thread_seeded = False - inchannel_seeded = False - if t.opened_thread_id: - _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"), - ) - thread_seeded = True - # in_channel: CREATE + seed the flat session (the mirror only APPENDS to an existing one). Same - # `inchannel_continuable` gate as the flatten in _deliver_result (must not drift). Origin - # 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 = _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"), - ) - 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["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: - _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"), - ) - elif t.in_channel_surface and not t.inchannel_continuable: - logger.warning( - "Job '%s': in_channel delivery to %s:%s is not a " - "continuable target (origin=%s:%s thread=%s; not the " - "origin conversation, and not a mirror-eligible " - "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"), - ) - _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, - enabled=t.mirror_this_target and not thread_seeded and not inchannel_seeded, - ) - - -def _deliver_via_live_adapter( - t: _TargetDelivery, - cleaned_text: str, - media_files: list, - *, - target_errors: list, - delivery_errors: list, - unverified_targets: list, -) -> bool: - """Deliver one target via the live gateway adapter; True once delivered. ``target_errors`` = - this lane's soft failures (surfaced only if standalone also fails); ``delivery_errors`` = - partial failures (media, thread fallback) that surface even on success.""" - job = t.job - route_thread_id, route_metadata, media_metadata = _live_route_metadata(t) - delivered = False - try: - # 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 - 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, - ) - 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, - ) - - # Media rides the same DM-topic-aware routing as text. Skipped after a confirmation - # timeout (loop contended, text already assumed delivered) — record the drop instead. - if adapter_ok and not timed_out and media_files: - _live_send_media(t, media_metadata, media_files, delivery_errors) - 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)", - delivery_errors, - ) - - if adapter_ok: - # Log WHERE it went: a ghost delivery in the wrong lane is otherwise indistinguishable. - logger.info( - "Job '%s': delivered to %s:%s via live adapter thread=%s message_id=%s", - job["id"], t.platform_name, t.chat_id, - route_thread_id if route_thread_id is not None else "-", - delivered_message_id if delivered_message_id is not None else "-", - ) - delivered = True - _seed_live_delivery_sessions(t, delivered_message_id) - except Exception as e: - err_msg = f"live adapter delivery to {t.where} failed: {e}" - if not any(err_msg in err for err in target_errors): - target_errors.append(err_msg) - _warn_live_lane_failure(job, err_msg, t.is_relay) - return delivered - - -def _standalone_send(t: _TargetDelivery, content: str, media_files: list) -> tuple[Any, Optional[str]]: - """Run the standalone sender for one target: ``(result, None)`` or ``(None, error)`` (already - logged — WARNING for a shutdown race, ERROR with traceback otherwise).""" - from tools.send_message_tool import _send_to_platform - - job = t.job - 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, - ) - - def _failed(e) -> tuple[None, str]: - msg = f"delivery to {t.where} failed: {e}" - logger.error("Job '%s': %s", job["id"], msg, exc_info=True) - return None, msg - - # 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 _interpreter_shutting_down(): - logger.warning("Job '%s': %s", job["id"], shutdown_msg) - return None, 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 - coro = _send() - try: - return asyncio.run(coro), None - except RuntimeError as run_err: - # asyncio.run() refuses inside a running loop; close the unstarted coro, retry in a thread. - coro.close() - if _interpreter_shutting_down(run_err): - logger.warning("Job '%s': %s", job["id"], shutdown_msg) - return None, 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()) - return future.result(timeout=30), None - finally: - pool.shutdown(wait=False) - except Exception as e: - if _interpreter_shutting_down(e): - logger.warning("Job '%s': %s", job["id"], shutdown_msg) - return None, shutdown_msg - return _failed(e) - except Exception as e: - return _failed(e) - - -def _deliver_standalone( - t: _TargetDelivery, content: str, media_files: list, target_errors: list, delivery_errors: list, -) -> None: - """Standalone fallback for a target the live lane did not deliver.""" - job = t.job - if t.is_relay: - # Relay owns the destination and credential; a native retry could duplicate — fail closed. - if not target_errors: - target_errors.append(f"relay delivery to {t.where} failed") - delivery_errors.extend(target_errors) - return - result, err = _standalone_send(t, content, media_files) - if err is None and result and result.get("error"): - # Not inside an except block — the error comes from the result dict, no traceback. - err = f"delivery error: {result['error']} (target {t.where})" - logger.error("Job '%s': %s", job["id"], err) - if err is not None: - target_errors.append(err) - delivery_errors.extend(target_errors) - return - - # 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: - msg = f"delivery warning: {_w} (target {t.where})" - logger.error("Job '%s': %s", job["id"], msg) - delivery_errors.append(msg) - - 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, - enabled=t.mirror_this_target, - ) - - -def _deliver_result( - job: dict, content: str, adapters=None, loop=None, *, for_failure: bool = False -) -> Optional[str]: - """Deliver job output to the configured target(s). With ``adapters``/``loop`` (gateway - running) the live adapter is tried first (E2EE rooms can't use the standalone HTTP path), then - standalone fallback. ``for_failure=True`` routes failure-category notices through the job's - ``failure_deliver`` override when present (NS-788). Returns None on success or an error string.""" - targets = _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 - - from gateway.config import load_gateway_config, Platform - - # Wrap with header/footer unless cron.wrap_response: false. - wrap_response = True - user_cfg = None - with contextlib.suppress(Exception): - user_cfg = load_config() - wrap_response = user_cfg.get("cron", {}).get("wrap_response", True) - - # Mark live sends FINAL so the platform pushes them (Telegram "important" mode mutes otherwise). - notify_delivery = _cron_delivery_notify_enabled(user_cfg) - # Targets acked with NO evidence (bare SendResult(success=True) — Slack/Matrix/Mattermost); - # persisted as ``last_delivery_unverified`` so `hermes cron list` shows it. - unverified_targets: list = [] - - 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"-------------\n\n" - f"{content}\n\n" - f"To stop or manage this job, send me a new message (e.g. \"stop reminder {task_name}\")." - ) - else: - delivery_content = content - - from gateway.platforms.base import BasePlatformAdapter - - # Bridge media-policy config into the env vars the path validator reads. The gateway does this - # at boot; standalone runs (`hermes cron run`) did not, silently dropping files. Idempotent. - from gateway.media_policy import apply_media_policy_env - - 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] - 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 [] - ) - - # 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). - try: - mirror_enabled = _cron_mirror_delivery_enabled(job, user_cfg) - except Exception: - mirror_enabled = False - # Independent of the mirror knob: continuable surfaces (in_channel) must seed even when - # attach_to_session=false and cron.mirror_delivery=false, else the seed gets "" and fails. - _, mirror_text = BasePlatformAdapter.extract_media(content) - mirror_text = (mirror_text or "").strip() - - try: - config = load_gateway_config() - except Exception as e: - msg = f"failed to load gateway config: {e}" - logger.error("Job '%s': %s", job["id"], msg) - return msg - - 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 bot_chat_error: - delivery_errors.append(bot_chat_error) - continue - - origin = _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) - 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 = _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( - t, cleaned_delivery_content, media_files, - 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, - ) - - if policy_drop_errors: - # Filter-time drops apply to every target; report them once. - delivery_errors.extend(policy_drop_errors) - _record_delivery_verification(job, unverified_targets) - if delivery_errors: - return "; ".join(delivery_errors) - return None - - _DEFAULT_SCRIPT_TIMEOUT = 3600 # seconds (1 hour) # Backward-compatible module override used by tests and emergency monkeypatches. _SCRIPT_TIMEOUT = _DEFAULT_SCRIPT_TIMEOUT @@ -3008,1164 +1088,6 @@ _RUN_CLAIM_HEARTBEAT_SECONDS = 60.0 _FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS = _RUN_CLAIM_HEARTBEAT_SECONDS * 3 -def _get_script_timeout() -> int: - """Resolve cron pre-run script timeout from module/env/config with a safe default.""" - if _SCRIPT_TIMEOUT != _DEFAULT_SCRIPT_TIMEOUT: - try: - timeout = int(float(_SCRIPT_TIMEOUT)) - if timeout > 0: - return timeout - except Exception: - logger.warning("Invalid patched _SCRIPT_TIMEOUT=%r; using env/config/default", _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 = 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 _DEFAULT_SCRIPT_TIMEOUT - - -_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 = 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 - - -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 = 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 - - -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() - 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 - - -def _windows_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, str]]: - """Hidden, output-capable Python invocation for Windows cron scripts. ``pythonw.exe`` loses - captured output; uv venv launchers can re-exec the base console python and flash a window even - with CREATE_NO_WINDOW, so run the base python directly with venv paths overlaid in env.""" - if sys.platform != "win32": - return python_exe, {} - - interpreter = Path(python_exe) - venv_dir = interpreter.parent.parent - env_overlay: dict[str, str] = {} - - if interpreter.name.lower() == "pythonw.exe": - sibling = interpreter.with_name("python.exe") - if sibling.exists(): - interpreter = sibling - - cfg = _read_windows_pyvenv_cfg(venv_dir) - home = cfg.get("home", "") - site_packages = venv_dir / "Lib" / "site-packages" - if "uv" in cfg and home: - base_python = Path(home) / "python.exe" - if base_python.exists() and site_packages.exists(): - interpreter = base_python - env_overlay["VIRTUAL_ENV"] = str(venv_dir) - pythonpath_entries = [str(Path(__file__).resolve().parents[1]), str(site_packages)] - existing_pythonpath = os.environ.get("PYTHONPATH", "") - if existing_pythonpath: - pythonpath_entries.append(existing_pythonpath) - env_overlay["PYTHONPATH"] = os.pathsep.join(pythonpath_entries) - - return str(interpreter), env_overlay - - -def _terminate_cron_script_process(proc: subprocess.Popen) -> None: - """Best-effort hard stop of a cron script and every child it spawned.""" - if proc.poll() is not None: - return - if sys.platform == "win32": - try: - subprocess.run( - ["taskkill", "/PID", str(proc.pid), "/T", "/F"], - capture_output=True, - timeout=10, - creationflags=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)) - try: - proc.wait(timeout=1.0) - except subprocess.TimeoutExpired: - proc.kill() - proc.wait(timeout=1.0) - - -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: - # Already reaped: kill_process_tree would log a spurious "no signal" warning. - return - 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", - pid, - ) - _terminate_cron_script_process(proc) - return - try: - # Function-local (monkeypatchable); separate try so an import problem is not - # misreported as a kill failure. - from agent.deadline import kill_process_tree - except Exception: - logger.warning( - "agent.deadline.kill_process_tree unavailable; " - "falling back to process-group termination", - exc_info=True, - ) - _terminate_cron_script_process(proc) - return - try: - if kill_process_tree(pid): - return - logger.warning( - "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, - ) - _terminate_cron_script_process(proc) - - -def _drain_script_pipes(proc: subprocess.Popen) -> None: - """Reap a terminated script without blocking forever: a surviving descendant can hold the pipe - write ends open, so bound the drain and abandon the pipes (output is not needed).""" - with contextlib.suppress(subprocess.TimeoutExpired): - proc.communicate(timeout=5.0) - return - with contextlib.suppress(OSError): - proc.kill() - for stream in (proc.stdout, proc.stderr): - with contextlib.suppress(OSError): - if stream is not None: - stream.close() - with contextlib.suppress(subprocess.TimeoutExpired): - proc.wait(timeout=5.0) - - -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. - """ - site_packages = Path(env_overlay.get("VIRTUAL_ENV", "")) / "Lib" / "site-packages" - if not site_packages.is_dir(): - # Warn: silent fallback would make "editable installs invisible" undiagnosable. - logger.warning( - "Windows cron script: venv site-packages %s not found; running " - "without .pth processing (editable installs may be unimportable)", - site_packages, - ) - return [python_exe, script_path] - bootstrap = ( - "import os, runpy, site, sys;" - f"site.addsitedir({str(site_packages)!r});" - "script = sys.argv[1];" - "sys.argv = [script] + sys.argv[2:];" - "sys.path.insert(0, os.path.dirname(os.path.abspath(script)));" - "runpy.run_path(script, run_name='__main__')" - ) - 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). - """ - scripts_dir = _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. - if "\x00" in str(script_path): - return False, f"Blocked: script path contains a NUL byte: {script_path!r}" - - try: - raw = 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}" - 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, ( - 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}" - if not path.is_file(): - return False, f"Script path is not a file: {path}" - - script_timeout = _get_script_timeout() - - # Interpreter by extension; the shebang is deliberately NOT honoured (small, auditable surface). - suffix = path.suffix.lower() - if suffix 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, ( - 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 = _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)] - - try: - from tools.environments.local import build_subprocess_env - - popen_kwargs: dict[str, Any] = {"start_new_session": True} - if sys.platform == "win32": - popen_kwargs = { - "creationflags": 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, - ) - deadline = time.monotonic() + script_timeout - while True: - if cancel_event is not None and cancel_event.is_set(): - # Tree-kill here too: a cancelled fire must not orphan own-session grandchildren. - _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. - _terminate_cron_script_tree(proc) - _drain_script_pipes(proc) - return False, f"Script timed out after {script_timeout}s: {path}" - try: - stdout_raw, stderr_raw = proc.communicate(timeout=min(0.1, remaining)) - break - except subprocess.TimeoutExpired: - continue - - stdout = (stdout_raw or "").strip() - stderr = (stderr_raw or "").strip() - - # Redact secrets before ANY return path. - try: - from agent.redact import redact_sensitive_text - stdout = redact_sensitive_text(stdout) - 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]" - - if proc.returncode != 0: - parts = [f"Script exited with code {proc.returncode}"] - if stderr: - parts.append(f"stderr:\n{stderr}") - 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}" - - -def _start_heartbeat_thread(loop_fn, name: str, fail_log) -> Optional[threading.Thread]: - """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, - ) - try: - thread.start() - except Exception: - fail_log() - return None - return thread - - -def _run_job_script_with_claim_heartbeat( - job: dict, - script_path: str, - workdir: Optional[str] = None, - cancel_event: Optional[_CancelEventLike] = None, -) -> tuple[bool, str]: - """Run a cron script while heartbeating its owned one-shot claim. - - A long script can outlive the stale-claim TTL; without a heartbeat another scheduler would - re-dispatch the one-shot. Recurring/unclaimed runs have no durable claim → no thread. The owner - is captured from the dispatched job, never re-read, so a stale runner cannot extend a - replacement owner's claim. - """ - 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 - ): - return _run_job_script(script_path, workdir=workdir, cancel_event=cancel_event) - - job_id = str(job.get("id") or "") - stop = threading.Event() - - def _heartbeat_loop() -> None: - while not stop.wait(_RUN_CLAIM_HEARTBEAT_SECONDS): - try: - heartbeat_run_claim(job_id, expected_owner=owner) - except Exception: - logger.debug("Job '%s': script run_claim heartbeat failed", job_id, exc_info=True) - - 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, - ), - ) - if heartbeat_thread is None: - return _run_job_script(script_path, workdir=workdir, cancel_event=cancel_event) - - try: - return _run_job_script(script_path, workdir=workdir, cancel_event=cancel_event) - finally: - stop.set() - # Bounded join: the heartbeat may be blocked on another process's jobs-file lock. - heartbeat_thread.join(timeout=1.0) - - -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()] - if not stripped_lines: - return True - last_line = stripped_lines[-1].strip() - try: - gate = json.loads(last_line) - except (json.JSONDecodeError, ValueError): - return True - if not isinstance(gate, dict): - return True - return gate.get("wakeAgent", True) is not False - - -def _prepend_context_block(prompt: str, heading: str, intro: str, body: str) -> str: - """Prefix ``prompt`` with a fenced ``## heading`` data block.""" - return f"## {heading}\n{intro}\n\n```\n{body}\n```\n\n{prompt}" - - -_MAX_CONTEXT_CHARS = 8000 - - -def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]: - """Prepend the latest output of each ``context_from`` job; returns ``(prompt, injected)``.""" - context_from = job.get("context_from") - if not context_from: - return prompt, False - from cron.jobs import get_cron_output_dir - output_dir = get_cron_output_dir() - if isinstance(context_from, str): - context_from = [context_from] - injected = False - for source_job_id in context_from: - # "self" = the job's own id: continuity across runs without touching session history. - if isinstance(source_job_id, str) and source_job_id.strip().lower() == "self": - source_job_id = str(job.get("id") or "") - is_self = source_job_id == job.get("id") - # Traversal guard — valid job IDs are hex strings. - if not source_job_id or not all(c in "0123456789abcdef" for c in source_job_id): - logger.warning( - "context_from: skipping invalid job_id %r for job_id=%r name=%r%s", - source_job_id, job.get("id"), job.get("name"), _cron_job_origin_log_suffix(job), - ) - continue - try: - output_files = sorted( - (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 - latest_output = output_files[0].read_text(encoding="utf-8").strip() - if len(latest_output) > _MAX_CONTEXT_CHARS: - latest_output = latest_output[:_MAX_CONTEXT_CHARS] + "\n\n[... output truncated ...]" - if not latest_output: - 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, - ) - 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, - ) - injected = True - except (OSError, PermissionError) as e: - # silent skip — never put error text into the prompt - logger.warning("context_from: failed to read output for job %r: %s", source_job_id, e) - return prompt, injected - - -def _load_cron_skill_parts(job: dict, skill_names: list[str]) -> list[str]: - """Load each named skill/bundle into prompt parts; unknown ones are skipped with a user notice.""" - from tools.skills_tool import skill_view - from tools.skill_usage import bump_use - from agent.skill_bundles import build_bundle_invocation_message, resolve_bundle_command_key - from agent.skill_utils import normalize_skill_lookup_name - - job_label = job.get("name", job.get("id")) - task_id = str(job.get("id") or "") or None - parts: list[str] = [] - skipped: list[str] = [] - 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, - ) - 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) - 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) - 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) - continue - - try: - bump_use(skill_name, task_id=task_id) - except Exception: - logger.debug("Cron job: failed to bump skill usage for '%s'", skill_name, exc_info=True) - - if parts: - parts.append("") - parts.extend([ - f'[IMPORTANT: The user has invoked the "{skill_name}" skill, indicating they want you to follow its instructions. The full skill content is loaded below.]', - "", - str(loaded.get("content") or "").strip(), - ]) - - if skipped: - parts.insert(0, ( - f"[IMPORTANT: The following skill(s) were listed for this job but could not be found " - f"and were skipped: {', '.join(skipped)}. " - f"Start your response with a brief notice so the user is aware, e.g.: " - f"'⚠️ Skill(s) not found and skipped: {', '.join(skipped)}']" - )) - return parts - - -def _build_job_prompt( - job: dict, - prerun_script: Optional[tuple] = None, - extra_prompt: Optional[str] = None, -) -> str: - """Build the effective prompt for a cron job, optionally loading skills first. - - ``prerun_script``: cached ``(success, stdout)`` from a script the caller already ran (wake-gate - check) — skips re-execution. ``extra_prompt``: per-run ``## Run Context`` for this fire only, - never persisted to the job. - """ - user_prompt = str(job.get("prompt") or "") - 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 = _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, - ) - has_injected_data = True - - prompt, _ctx_injected = _inject_context_from(job, prompt) - has_injected_data = has_injected_data or _ctx_injected - - # Durable per-job notepad; empty renders as "" so unused → byte-identical prompt. - from cron import notepad as cron_notepad - - notepad_section = cron_notepad.render_notepad_section(str(job.get("id") or "")) - if notepad_section: - 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()] - if not skill_names: - return _scan_assembled_cron_prompt( - prompt, - job, - has_skills=False, - has_injected_data=has_injected_data, - user_prompt=user_prompt, - ) - - parts = _load_cron_skill_parts(job, skill_names) - stable_prefix = None - if prompt: - from agent.skill_commands import append_user_instruction - - parts.append("") - # Skill blocks are stable per job config; the appended instruction is volatile per-run. - # Declare that boundary for the Anthropic cache planner. - stable_prefix = append_user_instruction(parts, prompt) - assembled = _scan_assembled_cron_prompt("\n".join(parts), job, has_skills=True) - if stable_prefix and len(assembled) > len(stable_prefix) and assembled.startswith(stable_prefix): - # Guarded: the scanner may mutate the bytes; mismatch → whole-message caching. - from agent.prompt_cache_boundary import register_stable_prefix - - register_stable_prefix(stable_prefix) - return assembled - - -def _scan_assembled_cron_prompt( - assembled: str, - job: dict, - *, - has_skills: bool = False, - has_injected_data: bool = False, - user_prompt: Optional[str] = None, -) -> str: - """Scan the assembled cron prompt for injection; raise ``CronPromptInjectionBlocked`` on a hit. - - Needed because skill content is loaded from disk at runtime (never scanned at create/update) - and cron auto-approves tool calls. Tier is chosen by what the prompt CONTAINS: user prompt + - hint only → STRICT ``_scan_cron_prompt``; skills or injected data → LOOSER - ``_scan_cron_skill_assembled`` (command-shape patterns dropped, invisible unicode sanitized not - blocked, so a false positive cannot permanently kill a job). With injected data but no skills, - ``user_prompt`` is additionally scanned STRICT (defense-in-depth for legacy jobs). - """ - from tools.cronjob_tools import _scan_cron_prompt, _scan_cron_skill_assembled - - 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 - 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, - ) - raise CronPromptInjectionBlocked(scan_error) - return assembled - - -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. - """ - 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 - if err: - job_id = job.get("id") - logger.error( - "Job '%s': refusing to run — unsafe provider/base_url pair could " - "exfiltrate a stored credential: %s", - job_id, err, - ) - raise RuntimeError(f"Cron job '{job_id}' blocked for safety: {err}") - - -def _block_and_pause_job( - job_id: str, job_name: str, reason: str -) -> tuple[bool, str, str, Optional[str]]: - """Fail a run closed and pause the job: an unrunnable job left enabled re-fires every tick - forever; ``paused_at``/``paused_reason`` give an auditable record.""" - from cron.jobs import pause_job - - logger.error("Job '%s': %s", job_id, reason) - try: - pause_job(job_id, f"Auto-paused by scheduler: {reason}") - except Exception: - logger.exception("Job '%s': failed to auto-pause unrunnable job", job_id) - - now_iso = _hermes_now().strftime("%Y-%m-%d %H:%M:%S") - doc = ( - f"# Cron Job: {job_name}\n\n" - f"**Job ID:** {job_id}\n" - f"**Run Time:** {now_iso}\n" - f"**Status:** blocked (unrunnable job) — auto-paused\n\n" - f"{reason}\n" - ) - alert = f"⚠ Cron job '{job_name}' was auto-paused\n\n{reason}" - return False, doc, alert, reason - - -# 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, -}) - - -def _is_transient_provider_resolve_error(exc: BaseException) -> bool: - """True when primary provider resolution failed for a transient network reason (DNS blip, - ConnectError...). Must be eligible for ``fallback_providers`` like AuthError, else a healthy - fallback rung is never tried and the job dies before the first model call.""" - import socket - - # gaierror carries EAI_* codes, plain OSError carries errno — never mix the namespaces (raw - # literals like {8, 7, 11} are macOS-only and wrong on Linux). - eai_transient = { - getattr(socket, n) for n in ("EAI_NONAME", "EAI_AGAIN", "EAI_FAIL", "EAI_NODATA") - if hasattr(socket, n) - } - # Walk the cause chain; the scheduler wraps raw transport errors. - seen: set[int] = set() - cur: Optional[BaseException] = exc - while cur is not None and id(cur) not in seen: - seen.add(id(cur)) - module = type(cur).__module__ or "" - msg = str(cur).lower() - if type(cur).__name__ in _TRANSIENT_NET_EXC_NAMES: - return True - if any(m in module for m in ("httpx", "httpcore", "aiohttp")) and any( - needle in msg for needle in _TRANSIENT_HTTP_NEEDLES - ): - return True - if isinstance(cur, OSError): - if isinstance(cur, socket.gaierror): - if cur.errno in eai_transient: - return True - elif getattr(cur, "errno", None) in _TRANSIENT_ERRNOS: - return True - if any(needle in msg for needle in _TRANSIENT_OSERROR_NEEDLES): - return True - # Bare exceptions that carry the raw DNS text (format_runtime_provider_error). - if any(needle in msg for needle in _DNS_FAILURE_NEEDLES): - return True - cur = cur.__cause__ or cur.__context__ - return False - - -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 - - -def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]: - """READ-ONLY probe: would provider resolution fail for lack of a key? Mirrors run_job's - requested-provider computation. Skipped when a fallback chain exists — auth-fallback may - legitimately rescue a missing primary key, so blocking here would break that contract.""" - try: - if get_fallback_chain(cfg): - return None - except Exception: - return None # fail-open: never block on a preflight-internal error - - _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 - ) - model = job.get("model") or os.getenv("HERMES_MODEL") or "" - - from hermes_cli.auth import AuthError - - try: - from hermes_cli.runtime_provider import resolve_runtime_provider - - kwargs = {"requested": requested, "target_model": model} - if job.get("base_url"): - kwargs["explicit_base_url"] = job.get("base_url") - resolve_runtime_provider(**kwargs) - except AuthError as exc: - return ( - f"provider credential missing: {exc}. " - "Set the provider API key in .env (or `hermes setup`), or pin a " - "working provider via `hermes cron edit " - f"{job.get('id')} --provider

`." - ) - except Exception: - return None # non-auth errors are not a missing-credential verdict; real path reports them - return None - - -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. - """ - try: - from hermes_constants import get_default_hermes_root, get_hermes_home - - primary_home = get_default_hermes_root() - current_home = Path(get_hermes_home()) - if ( - primary_home.expanduser().resolve(strict=False) - == current_home.expanduser().resolve(strict=False) - ): - return [] # this IS the primary home — nothing to consult - config_path = primary_home.expanduser() / "config.yaml" - if not config_path.exists(): - return [] - - import yaml - - with open(config_path, encoding="utf-8") as f: - raw = yaml.safe_load(f) or {} - routes_raw = raw.get("profile_routes") - if routes_raw is None and isinstance(raw.get("gateway"), dict): - routes_raw = raw["gateway"].get("profile_routes") - if not isinstance(routes_raw, list): - return [] - - from gateway.profile_routing import parse_profile_routes - from hermes_cli.profiles import profile_matches_home - - return [ - route - for route in parse_profile_routes(routes_raw) - if route.enabled and profile_matches_home(route.profile) - ] - except Exception: - logger.debug("primary-gateway profile-route lookup unavailable", exc_info=True) - return [] - - -def _delivery_platform_routed_from_primary_gateway(platform_name: str) -> bool: - """True when the primary gateway routes this platform to the profile being served.""" - platform_key = platform_name.lower() - return any( - str(route.platform).lower() == platform_key - for route in _primary_profile_routes_for_current_home() - ) - - -class SharedRouteAdapters: - """Read-only adapter map for a credentialless satellite profile. - - ``get(platform, target)`` resolves the PRIMARY adapter iff the inbound route matcher - (``ProfileRoute.matches``) accepts the target; anything else (unmatched target, disabled route, - other profile, or target-less ``get(platform)``) is a miss — fail closed, never the default bot. - """ - - def __init__(self, primary_adapters, routes) -> None: - self._primary = dict(primary_adapters or {}) - self._routes = list(routes or []) - - def __bool__(self) -> bool: - return bool(self._primary) and bool(self._routes) - - def get(self, platform, target=None, default=None): - if not target: - return default - adapter = self._primary.get(platform) - if adapter is None: - return default - platform_key = str(getattr(platform, "value", platform)).lower() - chat_id = str(target.get("chat_id") or "") or None - thread_id = target.get("thread_id") - thread_id = str(thread_id) if thread_id else None - for route in self._routes: - if str(route.platform).lower() != platform_key: - continue - if not (route.chat_id or route.thread_id): - continue # guild-only routes are not target-exact - if route.matches(str(route.platform), chat_id=chat_id, thread_id=thread_id): - return adapter - return default - - -def _preflight_check_delivery(job: dict) -> Optional[str]: - """Check delivery targets resolve to configured platforms. - - ``local``/``origin``/``all`` are never checked (no gateway-config load). Unknown platform always - blocks; known platform blocks only if the gateway config loads AND reports it unconnected. - Config load failures fail OPEN. ``failure_deliver`` is checked with the same rules: a typo'd - failure platform would otherwise only surface when a failure occurs (NS-788). - """ - deliver_value = _normalize_deliver_value(job.get("deliver", "local")) - failure_deliver_value = _normalize_deliver_value( - _delivery_lane_value(job, for_failure=True) - ) - lane_values = [deliver_value] - if failure_deliver_value != deliver_value: - lane_values.append(failure_deliver_value) - platform_parts: list[str] = [] - for lane_value in lane_values: - for part in lane_value.split(","): - part = part.strip() - if not part or part.lower() in {"local", "origin", "all"}: - continue - # bot-chat targets deliver via a local subprocess; failures surface in last_delivery_error. - if parse_bot_chat_deliver_token(part) is not None: - continue - platform_parts.append(part.split(":", 1)[0].strip()) - if not platform_parts: - return None - - connected: Optional[set] = None - for platform_name in platform_parts: - if not _is_known_delivery_platform(platform_name): - return ( - f"delivery platform '{platform_name}' is not a known cron " - "delivery target. Fix the job's `deliver` value or configure " - "the platform's gateway credentials." - ) - if connected is None: - 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 |= _relay_fronted_delivery_platforms(connected) - except Exception: - logger.debug( - "preflight: gateway config unavailable — skipping " - "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 - return ( - f"delivery platform '{platform_name}' has no gateway " - "credentials configured (not connected). Configure it via " - "`hermes setup` or change the job's `deliver` target." - ) - return None - - -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()] - if not skill_names: - return None - - from tools.skills_tool import skill_view - - for skill_name in skill_names: - try: - payload = json.loads(skill_view(skill_name)) - except Exception: - 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" - ): - 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 [] - ] - detail = ", ".join(missing) or "required setup incomplete" - return ( - f"attached skill '{skill_name}' is not ready: missing " - f"{detail}. Provide the missing prerequisites or detach the " - "skill from this job." - ) - return None - - -def _preflight_job_config(job: dict, cfg: dict) -> Optional[str]: - """Pre-dispatch validation: return a reason (missing key, unconfigured delivery, unready skill) - so the caller refuses BEFORE building agent machinery or burning an LLM call. Every check fails - open — preflight blocks only on an affirmative misconfiguration verdict.""" - for name, check in ( - ("provider_key", lambda: _preflight_check_provider_key(job, cfg)), - ("skills", lambda: _preflight_check_skills(job)), - ("delivery", lambda: _preflight_check_delivery(job)), - ): - try: - reason = check() - except Exception: - logger.debug("preflight check %s raised — failing open", name, exc_info=True) - continue - if reason: - return reason - return None - - def _cron_cleanup_timeout_seconds() -> float: """Return the wall-clock bound for cron post-run cleanup.""" default = 10.0 @@ -6384,3 +3306,118 @@ def tick( if __name__ == "__main__": tick(verbose=True) + + +# --------------------------------------------------------------------------- +# Split modules — re-exported so ``scheduler.`` keeps resolving (and stays the single +# monkeypatch target). +# --------------------------------------------------------------------------- +from cron.scheduler_delivery import ( # noqa: E402,F401 + BOT_CHAT_PLATFORM, + _HOME_TARGET_ENV_VARS, + _IMAGE_EXTS, + _KNOWN_DELIVERY_PLATFORMS, + _LEGACY_HOME_TARGET_ENV_VARS, + _MIRROR_PROVENANCE_RANK, + _ROUTING_TOKENS, + _TargetDelivery, + _VIDEO_EXTS, + _confirm_adapter_delivery, + _cron_delivery_notify_enabled, + _cron_job_origin_log_suffix, + _cron_mirror_delivery_enabled, + _deliver_result, + _deliver_standalone, + _deliver_to_bot_chat, + _deliver_via_live_adapter, + _delivery_lane_value, + _env_home_target_chat_id, + _expand_routing_tokens, + _get_bot_chat_delivery_timeout, + _get_config_home_channel, + _get_home_target_chat_id, + _get_home_target_thread_id, + _home_target, + _inchannel_seed_allowed, + _inchannel_surface_supported, + _is_channel_dm_topic, + _is_known_delivery_platform, + _iter_home_target_platforms, + _live_route_metadata, + _live_send_media, + _live_send_text, + _maybe_mirror_cron_delivery, + _normalize_deliver_value, + _note_target_error, + _open_continuable_cron_thread, + _origin_delivery_thread, + _origin_thread_is_stale, + _plugin_cron_env_var, + _record_delivery_verification, + _relay_fronted_delivery_platforms, + _resolve_bot_chat_target, + _resolve_cron_surface_mode, + _resolve_delivery_target, + _resolve_delivery_targets, + _resolve_home_env_var, + _resolve_origin, + _resolve_single_delivery_target, + _resolve_target_transport, + _seed_cron_channel_session, + _seed_cron_session, + _seed_cron_thread_session, + _seed_live_delivery_sessions, + _send_media_via_adapter, + _standalone_send, + _target_matches_origin, + _target_mirror_eligible, + _warn_live_lane_failure, + cron_delivery_targets, + parse_bot_chat_deliver_token, +) +from cron.scheduler_script import ( # noqa: E402,F401 + _DEFAULT_MEDIA_SEND_TIMEOUT, + _drain_script_pipes, + _get_media_send_timeout, + _get_script_timeout, + _get_session_db_timeout, + _read_windows_pyvenv_cfg, + _run_job_script, + _run_job_script_with_claim_heartbeat, + _start_heartbeat_thread, + _terminate_cron_script_process, + _terminate_cron_script_tree, + _windows_cron_bootstrap_argv, + _windows_cron_python_invocation, +) +from cron.scheduler_prompt import ( # noqa: E402,F401 + _MAX_CONTEXT_CHARS, + _block_and_pause_job, + _build_job_prompt, + _guard_job_credential_exfil, + _inject_context_from, + _load_cron_skill_parts, + _parse_wake_gate, + _prepend_context_block, + _scan_assembled_cron_prompt, +) +from cron.scheduler_preflight import ( # noqa: E402,F401 + BLOCKED_CONFIG_MARKER, + BLOCKED_CONFIG_SILENT_MARKER, + DRIFT_SKIP_MARKER, + DRIFT_SKIP_SILENT_MARKER, + SharedRouteAdapters, + _DNS_FAILURE_NEEDLES, + _TRANSIENT_ERRNOS, + _TRANSIENT_HTTP_NEEDLES, + _TRANSIENT_NET_EXC_NAMES, + _TRANSIENT_OSERROR_NEEDLES, + _cron_preflight_enabled, + _delivery_platform_routed_from_primary_gateway, + _is_transient_provider_resolve_error, + _preflight_check_delivery, + _preflight_check_provider_key, + _preflight_check_skills, + _preflight_job_config, + _primary_profile_routes_for_current_home, +) diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py new file mode 100644 index 0000000000..ef89a328ba --- /dev/null +++ b/cron/scheduler_delivery.py @@ -0,0 +1,1953 @@ +"""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. +""" + +from __future__ import annotations + +import asyncio +import concurrent.futures +import contextlib +import contextvars +import logging +import os +import subprocess +import sys +from dataclasses import dataclass +from typing import Any +from typing import List +from typing import Optional + +# Log-record parity with the origin module. +logger = logging.getLogger("cron.scheduler") + + +# Validates user-supplied delivery platform names, preventing env-var enumeration via crafted names. +_KNOWN_DELIVERY_PLATFORMS = frozenset({ + "telegram", "discord", "slack", "whatsapp", "signal", + "matrix", "mattermost", "homeassistant", "dingtalk", "feishu", + "wecom", "wecom_callback", "weixin", "sms", "email", "webhook", "bluebubbles", + "qqbot", "yuanbao", +}) + + +# Platforms supporting a cron/notification home target -> env var used by gateway config. +_HOME_TARGET_ENV_VARS = { + "matrix": "MATRIX_HOME_ROOM", + "telegram": "TELEGRAM_HOME_CHANNEL", + "discord": "DISCORD_HOME_CHANNEL", + "slack": "SLACK_HOME_CHANNEL", + "signal": "SIGNAL_HOME_CHANNEL", + "mattermost": "MATTERMOST_HOME_CHANNEL", + "sms": "SMS_HOME_CHANNEL", + "email": "EMAIL_HOME_ADDRESS", + "dingtalk": "DINGTALK_HOME_CHANNEL", + "feishu": "FEISHU_HOME_CHANNEL", + "wecom": "WECOM_HOME_CHANNEL", + "weixin": "WEIXIN_HOME_CHANNEL", + "bluebubbles": "BLUEBUBBLES_HOME_CHANNEL", + "qqbot": "QQBOT_HOME_CHANNEL", + "whatsapp": "WHATSAPP_HOME_CHANNEL", + "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. +_LEGACY_HOME_TARGET_ENV_VARS = {"QQBOT_HOME_CHANNEL": "QQ_HOME_CHANNEL"} + + +def _resolve_cron_surface_mode(pconfig, logical_platform_name: str) -> str: + """Return ``"in_channel"`` or ``"thread"`` (default) for a platform config. + + Native: flat ``platforms.

.extra.cron_continuable_surface``. Relay-fronted: + ``platforms.relay.extra..cron_continuable_surface`` (same sub-block as the relay's + Slack knobs); the sub-block wins over the flat key and is scoped to its logical platform. + Unlike _relay_slack_extra (all-or-nothing), this falls back to the flat key when the sub-block + omits the knob — deliberate, the flat key must keep working — so a flat value applies to EVERY + platform the relay fronts (only the D6 capability gate contains it). Scope it on multi-platform + relays. + """ + with contextlib.suppress(Exception): + extra = getattr(pconfig, "extra", None) or {} + sub = extra.get(str(logical_platform_name or "").lower()) + if isinstance(sub, dict) and sub.get("cron_continuable_surface") is not None: + raw = sub.get("cron_continuable_surface") + else: + raw = extra.get("cron_continuable_surface") + if raw is not None and str(raw).strip().lower() == "in_channel": + return "in_channel" + return "thread" + + +def _resolve_origin(job: dict) -> Optional[dict]: + """Extract origin info from a job. Non-dict origins (provenance strings, hand-edited + jobs.json) are treated as missing — otherwise every fire crashed on ``origin.get``.""" + origin = job.get("origin") + if isinstance(origin, dict) and origin.get("platform") and origin.get("chat_id"): + return origin + return None + + +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/thread-surface mirror. The mirror uses ``mirror_to_session`` at a turn boundary, so it + is alternation- and cache-safe. + """ + per_job = job.get("attach_to_session") + if isinstance(per_job, bool): + return per_job + try: + if cfg is None: + cfg = _sched.load_config() or {} + return bool((cfg.get("cron", {}) or {}).get("mirror_delivery", False)) + except Exception: + return False + + +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. + """ + 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 "") + + +# Provenance rank for the dedup OR-merge in _resolve_delivery_targets (higher = stronger mirror +# claim). Broadcasts rank 0 so "origin,all"/"all,origin" keep the origin tag regardless of order. +_MIRROR_PROVENANCE_RANK = {"origin": 3, "origin_fallback": 2, "explicit": 1} + + +def _target_mirror_eligible( + job: dict, + target: dict, + *, + global_mirror: bool, + origin_match: Optional[bool] = None, +) -> bool: + """Whether a resolved delivery target may receive the transcript mirror. + + Origin targets: always. ``origin_fallback`` (deliver=origin with no captured origin → home + channel, standing in for the user's primary conversation): same flags as a true origin. + ``explicit`` ``platform:chat_id``: ONLY with per-job ``attach_to_session: true`` — the global + flag must never write transcripts into arbitrary explicitly-addressed chats (shared channels, + other users' DMs). Untagged broadcasts (``all``, bare-platform home) are never eligible. + ``origin_match`` may be precomputed by the caller; computed here when ``None``. + """ + 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"), + ) + if origin_match: + return True + resolved_from = target.get("_resolved_from") + if resolved_from == "origin_fallback": + # 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) + 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. + """ + return bool(is_dm or user_id) + + +def _maybe_mirror_cron_delivery( + job: dict, + platform_name: str, + chat_id: str, + mirror_text: str, + thread_id: Optional[str] = None, + user_id: Optional[str] = None, + *, + 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 + ``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. + """ + if not enabled: + return + text = (mirror_text or "").strip() + if not text: + return + try: + from gateway.mirror import mirror_to_session + + # 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", + ) + if ok: + logger.info( + "Job '%s': mirrored delivery into %s:%s session transcript", + job.get("id", "?"), platform_name, chat_id, + ) + else: + logger.debug( + "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, + ) + + +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}" + 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] + 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.get("id", "?"), getattr(adapter, "name", "?"), e, + ) + return None + + +def _seed_cron_session( + job: dict, + adapter, + platform_name: str, + chat_id: str, + text: str, + *, + thread_id: Optional[str], + chat_type: str, + user_id: Optional[str], + user_name: Optional[str] = None, + chat_name: Optional[str], + scope_id: Optional[str], + discord_keys_on_thread: bool = False, +) -> bool: + """Create the session row (so the mirror has a target) and mirror the brief as a USER turn. + The seeded key must equal the reply's ``build_session_key``: chat_type, user_id, thread_id and + scope_id (Slack team id) are all part of it, so callers pass exactly what the reply carries.""" + from gateway.config import Platform + from gateway.session import SessionSource + + seeded_session_id: Optional[str] = None + session_store = getattr(adapter, "_session_store", None) + if session_store is not None: + try: + platform_enum = Platform(platform_name.lower()) + except (ValueError, KeyError): + platform_enum = None + if platform_enum is not None: + # 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) + ) + 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, + 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) + + 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, + ) + + +def _seed_cron_thread_session( + job: dict, + adapter, + platform_name: str, + chat_id: str, + thread_id: str, + mirror_text: str, + chat_name: Optional[str] = None, + is_dm: bool = False, + scope_id: Optional[str] = None, +) -> None: + """Seed the freshly-opened cron thread's session with the brief (never raises), else the + user's in-thread reply resolves to a transcript without it. Threads are participant-shared (no + real user_id); a DM thread must seed ``chat_type="dm"`` — DM-thread replies route through the DM + arm (``…:dm::``), so a "thread"-typed seed is a row no DM reply ever hits.""" + text = (mirror_text or "").strip() + if not text: + return + 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, + discord_keys_on_thread=True, + ) + if ok: + logger.info( + "Job '%s': opened continuable thread %s on %s:%s and seeded the brief", + job.get("id", "?"), thread_id, platform_name, chat_id, + ) + else: + logger.warning( + "Job '%s': thread seed did NOT land on %s:%s thread=%s — an " + "in-thread reply will not see this brief", + job.get("id", "?"), platform_name, chat_id, thread_id, + ) + except Exception as e: + # WARNING, not debug: a silent seed failure IS the continuation-amnesia bug. + logger.warning( + "Job '%s': seeding cron thread session failed for %s:%s:%s: %s", + job.get("id", "?"), platform_name, chat_id, thread_id, e, + ) + + +def _seed_cron_channel_session( + job: dict, + adapter, + platform_name: str, + chat_id: str, + mirror_text: str, + *, + is_dm: bool, + user_id: Optional[str], + chat_name: Optional[str] = None, + scope_id: Optional[str] = None, +) -> bool: + """Seed the FLAT (thread_id=None) session for an ``in_channel`` delivery; True on success. + ``mirror_to_session`` only APPENDS to an existing session and the flat row is only created by an + inbound human message, so the row must be created first or the brief is silently dropped. Group + keys are user-isolated (``…:group::``): the seed MUST carry the origin's real + user_id, not ``system:cron``; DM keys omit user_id. chat_type mirrors the inbound handler.""" + text = (mirror_text or "").strip() + if not text: + return False + try: + chat_type = "dm" if is_dm else "group" + 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, + ) + if ok: + logger.info( + "Job '%s': seeded flat in_channel session on %s:%s (chat_type=%s)", + job.get("id", "?"), platform_name, chat_id, chat_type, + ) + return bool(ok) + except Exception as e: + # WARNING, not debug: a silent seed failure IS the continuation-amnesia bug. + logger.warning( + "Job '%s': seeding in_channel session failed for %s:%s: %s", + job.get("id", "?"), platform_name, chat_id, e, + ) + return False + + +def _cron_job_origin_log_suffix(job: dict) -> str: + """Secret-free provenance suffix (origin platform/chat/source-IP fields) for security warnings + about a bad stored ``context_from`` reference, where no live request object exists.""" + 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) + if value is None: + continue + text = str(value).replace("\r", " ").replace("\n", " ").strip() + if text: + fields.append(f"origin_{key}={text[:200]!r}") + return " " + " ".join(fields) if fields else "" + + +def _plugin_cron_env_var(platform_name: str) -> str: + """Cron home-channel env var registered by a plugin ``PlatformEntry.cron_deliver_env_var``.""" + with contextlib.suppress(Exception): + from hermes_cli.plugins import discover_plugins + discover_plugins() # idempotent + from gateway.platform_registry import platform_registry + entry = platform_registry.get(platform_name.lower()) + if entry and entry.cron_deliver_env_var: + return entry.cron_deliver_env_var + return "" + + +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)) + + +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) + + +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. + """ + try: + from gateway.config import load_gateway_config, Platform + + config = load_gateway_config() + platform = Platform(platform_name.lower()) + return config.get_home_channel(platform) + except Exception: + 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). + + 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. + """ + env_var = _resolve_home_env_var(platform_name) + if not env_var: + return "" + try: + from agent.secret_scope import get_secret + 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, "") + if not value: + legacy = _LEGACY_HOME_TARGET_ENV_VARS.get(env_var) + if legacy: + value = os.getenv(legacy, "") + return value + + +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``.""" + value = _env_home_target_chat_id(platform_name) + 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 "" + + +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 "" + + if platform_name.lower() == "telegram": + cron_thread = _scope_get("TELEGRAM_CRON_THREAD_ID").strip() + 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() + if value: + return value + # config.yaml fallback only when the chat id also came from config (an env-provided chat id + # keeps its env-provided thread semantics). + if not _env_home_target_chat_id(platform_name): + home = _get_config_home_channel(platform_name) + if home is not None and home.thread_id: + return str(home.thread_id) + return None + + +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 + with contextlib.suppress(Exception): + from hermes_cli.plugins import discover_plugins + discover_plugins() # idempotent + from gateway.platform_registry import platform_registry + for entry in platform_registry.plugin_entries(): + if entry.cron_deliver_env_var and entry.name not in _HOME_TARGET_ENV_VARS: + yield entry.name + + +def _relay_fronted_delivery_platforms(connected: set) -> set: + """Logical platforms deliverable through a connected relay. ``get_connected_platforms()`` only + sees native platforms; fronted ones come from the same ``GATEWAY_RELAY_PLATFORMS`` stamp + fire-time routing uses (validation symmetric with routing). No relay -> empty set.""" + if "relay" not in connected: + return set() + try: + from gateway.relay import relay_fronted_platforms + + return relay_fronted_platforms() + except Exception: + logger.debug("relay fronted-platform lookup failed", exc_info=True) + return set() + + +def cron_delivery_targets() -> list[dict]: + """Platforms a cron job can auto-deliver to (single source of truth for UIs). + + Included when a valid delivery platform AND gateway-configured; ``home_target_set`` flags + whether the home channel exists. Returns ``{"id", "name", "home_target_set", "home_env_var"}`` + dicts in canonical order; callers prepend the implicit ``local`` option themselves. + """ + 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 |= _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: + 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, + } + ) + + # 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, + } + ) + 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. + """ + 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") + return bool(home_chat) and str(origin.get("chat_id")) == str(home_chat) + + +def _origin_delivery_thread(origin: dict): + """The thread a deliver=origin job should use, stale stamps dropped.""" + if _origin_thread_is_stale(origin): + return _sched._get_home_target_thread_id("slack") or None + return origin.get("thread_id") + + +def _home_target(platform_name: str, chat_id: str, resolved_from: Optional[str] = None) -> dict: + """Target dict for a platform's configured home channel (+ optional mirror provenance).""" + target = { + "platform": platform_name, + "chat_id": chat_id, + "thread_id": _sched._get_home_target_thread_id(platform_name), + } + if resolved_from: + target["_resolved_from"] = resolved_from + return target + + +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 + + # Must precede the generic platform:chat_id split so the profile name isn't parsed as chat_id. + bot_chat_profile = parse_bot_chat_deliver_token(deliver_value) + if bot_chat_profile is not None: + return _resolve_bot_chat_target(job, bot_chat_profile) + + if deliver_value == "origin": + if origin: + return { + "platform": origin["platform"], + "chat_id": str(origin["chat_id"]), + "thread_id": _origin_delivery_thread(origin), + # Provenance for _target_mirror_eligible. + "_resolved_from": "origin", + } + # No origin (API/script job): fall back to a home channel instead of silently dropping. + for platform_name in _sched._iter_home_target_platforms(): + chat_id = _sched._get_home_target_chat_id(platform_name) + 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, + ) + # Stands in for the primary conversation (NOT a broadcast): mirror-eligible. + return _home_target(platform_name, chat_id, "origin_fallback") + return None + + if ":" in deliver_value: + 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, + ) + + prepare_send_message_platforms() + # pass_unresolved_references: no model in the loop to react; an unknown-to-directory target + # must reach the adapter as written or the job's output is silently lost. + chat_id, thread_id, resolution_error = resolve_send_target( + platform_key, rest, pass_unresolved_references=True + ) + if resolution_error: + logger.warning("Invalid cron delivery target '%s': %s", deliver_value, resolution_error) + return None + + if ( + thread_id is None + and platform_key == "slack" + and origin + and str(origin.get("platform") or "").lower() == platform_key + and str(origin.get("chat_id")) == str(chat_id) + and origin.get("thread_id") + and not _origin_thread_is_stale(origin) + ): + thread_id = origin.get("thread_id") + + return { + "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", + } + + platform_name = deliver_value + if origin and origin.get("platform") == platform_name: + 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"), + } + + if not _sched._is_known_delivery_platform(platform_name): + return None + chat_id = _sched._get_home_target_chat_id(platform_name) + return _home_target(platform_name, chat_id) if chat_id else None + + +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)) + return value if value > 0 else 600 + except Exception: + return 600 + + +def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str]: + """Deliver job output into a profile's canonical Bot Chat as a real inbound user turn. + + Runs ``hermes [-p ] chat --in ~ -c "Bot Chat" --create-if-missing -Q --query-file`` — + the same lane Bot Mode agent-to-agent messages use, so canonical-session rules apply and it is + 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") + 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" + except Exception: + return "bot-chat delivery failed: hermes CLI not resolvable" + + env = os.environ.copy() + if profile: + argv += ["-p", profile] + # -p owns profile resolution; this scheduler's HERMES_HOME must not shadow it. + env.pop("HERMES_HOME", None) + + # 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"Review it, act on anything that needs action, and summarize " + f"for the chat.]\n\n{content}" + ) + + query_file = None + try: + with tempfile.NamedTemporaryFile( + "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, + ] + + result = subprocess.run( + 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": {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)") + return None + except subprocess.TimeoutExpired: + msg = ( + f"bot-chat delivery to profile '{profile or '(own)'}' 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)" + ) + logger.warning("Job '%s': %s", job_id, msg) + return msg + except Exception as e: + msg = f"bot-chat delivery failed: {str(e) or type(e).__name__}" + logger.warning("Job '%s': %s", job_id, msg, exc_info=True) + return msg + finally: + if query_file: + with contextlib.suppress(OSError): + os.unlink(query_file) + + +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. + """ + if deliver is None or deliver == "": + return "local" + if isinstance(deliver, (list, tuple)): + parts = [str(p).strip() for p in deliver if str(p).strip()] + return ",".join(parts) if parts else "local" + return str(deliver) + + +# Routing tokens resolve at fire time (a job outlives platform wiring). ``all`` = platforms with a +# 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" + + +def parse_bot_chat_deliver_token(part: str) -> Optional[str]: + """``bot-chat[:]`` → ``""`` (own profile), the name, or ``None`` if not a bot-chat token. + Token is case-insensitive; the name is normalized later by the profile layer.""" + raw = (part or "").strip() + lowered = raw.lower() + if lowered == BOT_CHAT_PLATFORM: + return "" + prefix = BOT_CHAT_PLATFORM + ":" + if lowered.startswith(prefix): + return raw[len(prefix):].strip() + return None + + +def _resolve_bot_chat_target(job: dict, profile_arg: str) -> Optional[dict]: + """Resolve a bot-chat token to a delivery target. ``""`` = own profile (no ``-p`` needed); + otherwise the profile must exist locally — cross-machine delivery is intentionally unsupported + so same-named profiles on other gateways can never be targeted by accident.""" + if not profile_arg: + return {"platform": BOT_CHAT_PLATFORM, "chat_id": "", "thread_id": None} + try: + from hermes_cli.profiles import normalize_profile_name, profile_exists + + 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.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, + ) + return None + + +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: + 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 + + +def _delivery_lane_value(job: dict, *, for_failure: bool = False): + """Raw deliver-lane value for a run outcome: the failure lane when ``for_failure`` and the job + overrides it, else ``deliver``. Bookkeeping (outcome classification, unresolved-origin, incident + 'alerted' marking) must read the SAME lane the notice was routed through (NS-788).""" + if for_failure: + failure_deliver = job.get("failure_deliver") + if failure_deliver is not None and str(failure_deliver).strip(): + return failure_deliver + return job.get("deliver", "local") + + +def _resolve_delivery_targets(job: dict, *, for_failure: bool = False) -> List[dict]: + """Resolve auto-delivery targets from comma-separated ``deliver``; ``all`` expands to every + platform with a home channel and combines with explicit targets. Dedup by (platform, chat_id, + thread_id). ``for_failure=True`` (failure summaries, interrupted-run notices, drift/preflight + alerts) resolves from ``failure_deliver`` INSTEAD when the job carries one — ``failure_deliver: + local`` is the structural opt-out for shared channels; absent, failures follow ``deliver``.""" + deliver = _normalize_deliver_value(_delivery_lane_value(job, for_failure=for_failure)) + 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)) + + 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") + return targets + + +def _resolve_delivery_target(job: dict) -> Optional[dict]: + """Resolve the concrete auto-delivery target for a cron job, if any.""" + targets = _sched._resolve_delivery_targets(job) + return targets[0] if targets else None + + +# 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'}) + + +def _send_media_via_adapter( + adapter, + chat_id: str, + media_files: list, + metadata: dict | None, + loop, + job: dict, + platform=None, +) -> list: + """Send MEDIA files as native attachments (routed by extension, as in + _process_message_background). Returns per-file error strings so a dropped attachment surfaces + in run status, not just the gateway log.""" + from gateway.platforms.base import ( + BasePlatformAdapter, should_send_media_as_audio, validate_media_delivery_path, + ) + from agent.async_utils import safe_schedule_threadsafe + + job_ref = {"id": job.get("id", "?")} + errors: list = [] + requested = [(str(p), v) for p, v in (media_files or [])] + media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files) + # Report paths the safety filter dropped (missing file, denied prefix, strict-mode miss). + kept = {p for p, _ in media_files} + for raw_path, _v in requested: + try: + dropped = validate_media_delivery_path(raw_path) not in kept + except Exception: + dropped = True + if dropped: + errors.append(f"attachment dropped by media path policy: {raw_path}") + + route_platform = platform if platform is not None else getattr(adapter, "platform", None) + for media_path, _is_voice in media_files: + try: + ext = _sched.Path(media_path).suffix.lower() + if should_send_media_as_audio(route_platform, ext, is_voice=_is_voice): + coro = adapter.send_voice(chat_id=chat_id, audio_path=media_path, metadata=metadata) + elif ext in _VIDEO_EXTS: + coro = adapter.send_video(chat_id=chat_id, video_path=media_path, metadata=metadata) + elif ext in _IMAGE_EXTS: + coro = adapter.send_image_file(chat_id=chat_id, image_path=media_path, metadata=metadata) + else: + coro = adapter.send_document(chat_id=chat_id, file_path=media_path, metadata=metadata) + + 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, + ) + return errors + try: + # Large attachments can exceed 30s; configurable via _get_media_send_timeout(). + result = future.result(timeout=_sched._get_media_send_timeout()) + except TimeoutError: + future.cancel() + 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, + ) + 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, + ) + return errors + + +def _confirm_adapter_delivery(send_result, job_id: str = "?", unverified: Optional[list] = None) -> bool: + """Return True only if ``send_result`` unambiguously confirms delivery. + + ``None`` or no ``success`` attr/key is NOT success (would log "delivered" while nothing was + sent). ``delivered is False`` REJECTS even with truthy ``success``: the silence-narration filter + returns ``{"success": True, "delivered": False}`` (dropped). No ``message_id``/``raw_response`` + is still accepted (some adapters return a bare success) but logged at WARNING as UNVERIFIED. + """ + 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: + return False + if message_id is None and not raw_response: + logger.warning( + "Job '%s': live adapter reported success with no delivery evidence " + "(no message_id, no raw_response) — treating as delivered but " + "UNVERIFIED", + job_id, + ) + if unverified is not None: + unverified.append(True) + return True + + +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``. + Fails SAFE to False (thread routing) without a probe or on any probe error/timeout.""" + # Resolve on the CLASS, not the instance: a MagicMock instance auto-creates a truthy + # ``get_chat_info``, so an instance-level probe would misclassify test doubles. + get_chat_info = getattr(type(runtime_adapter), "get_chat_info", None) + if not callable(get_chat_info): + return False + 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] + ) + 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_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, + ) + return is_channel + + +def _cron_delivery_notify_enabled(cfg: Optional[dict]) -> bool: + """Resolve ``cron.delivery.notify`` (default True). Only an explicit ``False`` disables; a + 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 + except Exception: + return True + + +def _record_delivery_verification(job: dict, unverified_targets: list) -> None: + """Persist ``last_delivery_unverified``: list of ``platform:chat_id`` targets acked with no + evidence, or None. Skips the write when unchanged; never raises (bookkeeping must not fail a + delivery).""" + new_value = list(unverified_targets) or None + if (job.get("last_delivery_unverified") or None) == new_value: + return + try: + from cron.jobs import update_job + + update_job(job["id"], {"last_delivery_unverified": new_value}) + except Exception as exc: # pragma: no cover - defensive + logger.debug("Job '%s': could not record delivery verification: %s", job.get("id"), exc) + + +@dataclass +class _TargetDelivery: + """Per-target delivery state shared by the live-adapter and standalone lanes.""" + + job: dict + platform: Any + platform_name: str + chat_id: str + thread_id: Optional[str] + transport: Any + pconfig: Any + runtime_adapter: Any + target_adapters: Any + config: Any + loop: Any + notify_delivery: bool + origin: dict + origin_target: bool + origin_user_id: Optional[str] + is_dm_target: bool + mirror_text: str + mirror_this_target: bool + in_channel_surface: bool + inchannel_continuable: bool + opened_thread_id: Optional[str] + + @property + def is_relay(self) -> bool: + return self.transport is not None and self.transport.is_relay + + @property + def where(self) -> str: + return f"{self.platform_name}:{self.chat_id}" + + +def _note_target_error(job: dict, msg: str, errors: list) -> None: + """Log a per-target delivery failure as a WARNING and record it in ``errors``.""" + logger.warning("Job '%s': %s", job["id"], msg) + errors.append(msg) + + +def _warn_live_lane_failure(job: dict, msg: str, is_relay: bool) -> None: + """Relay targets have no standalone fallback, so the log line must not promise one.""" + if is_relay: + logger.warning("Job '%s': %s", job["id"], msg) + else: + logger.warning("Job '%s': %s, falling back to standalone", job["id"], msg) + + +def _resolve_target_transport(job: dict, platform, platform_name: str, target: dict, adapters, config): + """Resolve ``(transport, pconfig, runtime_adapter, target_adapters)`` for one target, or + ``(None, error)`` when it cannot be served (relay-fronted with no live transport, or not + configured/enabled).""" + from gateway.delivery import resolve_delivery_transport + + target_adapters = adapters + if isinstance(adapters, _sched.SharedRouteAdapters): + # Credentialless satellite: the primary adapter serves THIS target only when an exact + # primary route maps it to this profile; a miss fails closed below. + shared = adapters.get(platform, target) + target_adapters = {platform: shared} if shared is not None else {} + transport = resolve_delivery_transport(platform, config, target_adapters) + if transport is not None: + pconfig = transport.config + runtime_adapter = transport.adapter + else: + # Relay-fronted platforms have NO standalone fallback (the connector owns the credential), + # so surface that instead of the native configured/enabled gate, which misdiagnoses them. + from gateway.relay import relay_fronted_platforms + + if platform_name in relay_fronted_platforms(): + return None, ( + f"platform '{platform_name}' is relay-fronted and has no " + "live gateway transport; start the gateway (its ticker " + "owns relay-fronted delivery and will fire the job on " + "schedule)" + ) + pconfig = config.platforms.get(platform) + runtime_adapter = None + + if transport is not None and transport.is_relay: + # Relay transport carries the RELAY adapter's config (enablement already checked). The + # logical platform is deliberately NOT natively enabled, so the native gate must not apply. + if pconfig is None: + from gateway.config import PlatformConfig + pconfig = PlatformConfig(enabled=True) + elif not pconfig or not pconfig.enabled: + return None, f"platform '{platform_name}' not configured/enabled" + return (transport, pconfig, runtime_adapter, target_adapters), None + + +def _inchannel_surface_supported(runtime_adapter, platform_name: str) -> bool: + """D6 probe: can this adapter deliver a continuable in_channel brief on ``platform_name``? + Per-platform check first (one RelayAdapter fronts N platforms; the scalar attr only carries + the PRIMARY identity's bit); native adapters use the class attribute.""" + per_platform_check = getattr(runtime_adapter, "supports_inchannel_continuable_for_platform", None) + if callable(per_platform_check): + try: + return bool(per_platform_check(platform_name)) + except Exception: + return False + return bool(getattr(runtime_adapter, "supports_inchannel_continuable", False)) + + +def _live_route_metadata(t: _TargetDelivery) -> tuple[Optional[str], dict, dict]: + """Compute ``(route_thread_id, route_metadata, media_metadata)`` for a live send, ONCE so text + and media agree. ``telegram::`` is ambiguous (private + forum topic vs channel DM topic need OPPOSITE routing) — see ``_is_channel_dm_topic``. + ``thread_id`` rides in ``route_metadata`` to bypass the DeliveryRouter's private-chat + reply-anchor requirement for anchorless cron sends.""" + from gateway.config import Platform + from gateway.delivery import _looks_like_int, looks_like_telegram_private_chat_id + + job = t.job + thread_id = t.thread_id + is_ambiguous_telegram_topic = ( + t.platform == Platform.TELEGRAM + and thread_id is not None + 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"], + ): + # 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, + } + media_metadata = {"direct_messages_topic_id": str(thread_id), "notify": t.notify_delivery} + else: + # Forum-style topic or non-topic target: message_thread_id. + route_thread_id = str(thread_id) if thread_id is not None else None + route_metadata = {"job_id": job["id"], "notify": t.notify_delivery} + if route_thread_id: + route_metadata["thread_id"] = route_thread_id + media_metadata = {"notify": t.notify_delivery} + if thread_id: + media_metadata["thread_id"] = thread_id + + # Relay egress needs metadata.scope_id (fail-closed tenant guard; scope cache is COLD after a + # restart; router stamps HOME only). Origin targets only: a wrong fan-out scope is worse than + # none. + if t.origin_target and t.origin.get("scope_id"): + route_metadata.setdefault("scope_id", str(t.origin["scope_id"])) + media_metadata.setdefault("scope_id", str(t.origin["scope_id"])) + return route_thread_id, route_metadata, media_metadata + + +def _live_send_text( + t: _TargetDelivery, + text_to_send: str, + route_thread_id: Optional[str], + route_metadata: dict, + *, + target_errors: list, + delivery_errors: list, + unverified_targets: list, +) -> tuple[bool, bool, Any]: + """Schedule the text send on the gateway loop; returns ``(adapter_ok, timed_out, message_id)``. + Re-raises a real send error so the caller falls through to standalone.""" + from agent.async_utils import safe_schedule_threadsafe + from gateway.delivery import DeliveryRouter, DeliveryTarget + + 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, + ) + # 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, + ) + if future is None: + target_errors.append("live adapter event loop scheduling failed") + return False, False, None + try: + send_result = future.result(timeout=60) + except TimeoutError: + # Slow confirmation != failure; future.cancel() disambiguates. False -> already in flight, + # 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" + ) + logger.warning("Job '%s': %s, falling back to standalone", job["id"], msg) + target_errors.append(msg) + return False, False, None + logger.warning( + "Job '%s': live adapter send to %s:%s timed out " + "after 60s; already dispatched (in flight), " + "assuming delivered (skipping standalone fallback " + "to avoid duplicate)", + job["id"], t.platform_name, t.chat_id, + ) + return True, True, None + except Exception as ex: + # Real send error (not a slow confirmation): fall through to standalone. + target_errors.append(f"live adapter send failed: {ex}") + raise + + # _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) + _evidence_gap: list = [] + send_success = _confirm_adapter_delivery(send_result, job["id"], _evidence_gap) + if send_success and _evidence_gap: + unverified_targets.append(t.where) + + if not send_success: + if isinstance(send_result, dict): + # A filtered drop carries no "error" — name the filter instead of reporting "unknown". + err = send_result.get("error") or send_result.get("filtered") or "unknown" + shape = "dict" + elif send_result is not None: + err = getattr(send_result, "error", None) + shape = type(send_result).__name__ + else: + err = "no response from adapter" + shape = "None" + msg = f"live adapter send to {t.where} returned unconfirmed result ({shape}, error={err})" + _warn_live_lane_failure(job, msg, t.is_relay) + target_errors.append(msg) + return False, False, None + if send_raw_response and t.thread_id and send_raw_response.get("thread_fallback"): + 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", + delivery_errors, + ) + return True, False, delivered_message_id + + +def _live_send_media(t: _TargetDelivery, media_metadata: dict, media_files: list, delivery_errors: list) -> None: + """Send extracted media as native attachments with the same routing as the text send.""" + routed_media_metadata = dict(media_metadata or {}) + if t.is_relay: + routed_media_metadata["_relay_logical_platform"] = t.platform.value + logical_home = t.config.get_home_channel(t.platform) + if logical_home is not None and logical_home.chat_id == t.chat_id: + if logical_home.user_id: + routed_media_metadata["user_id"] = logical_home.user_id + 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, + ) + # Surface per-file failures into run status: text delivered but attachment lost is not ok. + for _me in _media_errors: + delivery_errors.append(f"{_me} (target {t.where})") + + +def _seed_live_delivery_sessions(t: _TargetDelivery, delivered_message_id) -> None: + """After a confirmed live send, seed continuation session(s) and run the generic mirror. + Thread seeding is deferred here so open-succeeds/deliver-fails never seeds an unseen brief.""" + job = t.job + origin = t.origin + 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"), + ) + thread_seeded = True + # in_channel: CREATE + seed the flat session (the mirror only APPENDS to an existing one). Same + # `inchannel_continuable` gate as the flatten in _deliver_result (must not drift). Origin + # 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"), + ) + 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["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"), + ) + elif t.in_channel_surface and not t.inchannel_continuable: + logger.warning( + "Job '%s': in_channel delivery to %s:%s is not a " + "continuable target (origin=%s:%s thread=%s; not the " + "origin conversation, and not a mirror-eligible " + "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"), + ) + _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, + enabled=t.mirror_this_target and not thread_seeded and not inchannel_seeded, + ) + + +def _deliver_via_live_adapter( + t: _TargetDelivery, + cleaned_text: str, + media_files: list, + *, + target_errors: list, + delivery_errors: list, + unverified_targets: list, +) -> bool: + """Deliver one target via the live gateway adapter; True once delivered. ``target_errors`` = + this lane's soft failures (surfaced only if standalone also fails); ``delivery_errors`` = + partial failures (media, thread fallback) that surface even on success.""" + job = t.job + route_thread_id, route_metadata, media_metadata = _live_route_metadata(t) + delivered = False + try: + # 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 + 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, + ) + 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, + ) + + # Media rides the same DM-topic-aware routing as text. Skipped after a confirmation + # timeout (loop contended, text already assumed delivered) — record the drop instead. + if adapter_ok and not timed_out and media_files: + _live_send_media(t, media_metadata, media_files, delivery_errors) + 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)", + delivery_errors, + ) + + if adapter_ok: + # Log WHERE it went: a ghost delivery in the wrong lane is otherwise indistinguishable. + logger.info( + "Job '%s': delivered to %s:%s via live adapter thread=%s message_id=%s", + job["id"], t.platform_name, t.chat_id, + route_thread_id if route_thread_id is not None else "-", + delivered_message_id if delivered_message_id is not None else "-", + ) + delivered = True + _seed_live_delivery_sessions(t, delivered_message_id) + except Exception as e: + err_msg = f"live adapter delivery to {t.where} failed: {e}" + if not any(err_msg in err for err in target_errors): + target_errors.append(err_msg) + _warn_live_lane_failure(job, err_msg, t.is_relay) + return delivered + + +def _standalone_send(t: _TargetDelivery, content: str, media_files: list) -> tuple[Any, Optional[str]]: + """Run the standalone sender for one target: ``(result, None)`` or ``(None, error)`` (already + logged — WARNING for a shutdown race, ERROR with traceback otherwise).""" + from tools.send_message_tool import _send_to_platform + + job = t.job + 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, + ) + + def _failed(e) -> tuple[None, str]: + msg = f"delivery to {t.where} failed: {e}" + logger.error("Job '%s': %s", job["id"], msg, exc_info=True) + return None, msg + + # 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 + # 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 + coro = _send() + try: + return asyncio.run(coro), None + except RuntimeError as run_err: + # 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 + # 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()) + 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 _failed(e) + except Exception as e: + return _failed(e) + + +def _deliver_standalone( + t: _TargetDelivery, content: str, media_files: list, target_errors: list, delivery_errors: list, +) -> None: + """Standalone fallback for a target the live lane did not deliver.""" + job = t.job + if t.is_relay: + # Relay owns the destination and credential; a native retry could duplicate — fail closed. + if not target_errors: + target_errors.append(f"relay delivery to {t.where} failed") + delivery_errors.extend(target_errors) + return + result, err = _standalone_send(t, content, media_files) + if err is None and result and result.get("error"): + # Not inside an except block — the error comes from the result dict, no traceback. + err = f"delivery error: {result['error']} (target {t.where})" + logger.error("Job '%s': %s", job["id"], err) + if err is not None: + target_errors.append(err) + delivery_errors.extend(target_errors) + return + + # 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: + msg = f"delivery warning: {_w} (target {t.where})" + logger.error("Job '%s': %s", job["id"], msg) + delivery_errors.append(msg) + + 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, + enabled=t.mirror_this_target, + ) + + +def _deliver_result( + job: dict, content: str, adapters=None, loop=None, *, for_failure: bool = False +) -> Optional[str]: + """Deliver job output to the configured target(s). With ``adapters``/``loop`` (gateway + running) the live adapter is tried first (E2EE rooms can't use the standalone HTTP path), then + standalone fallback. ``for_failure=True`` routes failure-category notices through the job's + ``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 + + from gateway.config import load_gateway_config, Platform + + # Wrap with header/footer unless cron.wrap_response: false. + wrap_response = True + user_cfg = None + with contextlib.suppress(Exception): + user_cfg = _sched.load_config() + wrap_response = user_cfg.get("cron", {}).get("wrap_response", True) + + # Mark live sends FINAL so the platform pushes them (Telegram "important" mode mutes otherwise). + notify_delivery = _cron_delivery_notify_enabled(user_cfg) + # Targets acked with NO evidence (bare SendResult(success=True) — Slack/Matrix/Mattermost); + # persisted as ``last_delivery_unverified`` so `hermes cron list` shows it. + unverified_targets: list = [] + + 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"-------------\n\n" + f"{content}\n\n" + f"To stop or manage this job, send me a new message (e.g. \"stop reminder {task_name}\")." + ) + else: + delivery_content = content + + from gateway.platforms.base import BasePlatformAdapter + + # Bridge media-policy config into the env vars the path validator reads. The gateway does this + # at boot; standalone runs (`hermes cron run`) did not, silently dropping files. Idempotent. + from gateway.media_policy import apply_media_policy_env + + 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] + 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 [] + ) + + # 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). + try: + mirror_enabled = _cron_mirror_delivery_enabled(job, user_cfg) + except Exception: + mirror_enabled = False + # Independent of the mirror knob: continuable surfaces (in_channel) must seed even when + # attach_to_session=false and cron.mirror_delivery=false, else the seed gets "" and fails. + _, mirror_text = BasePlatformAdapter.extract_media(content) + mirror_text = (mirror_text or "").strip() + + try: + config = load_gateway_config() + except Exception as e: + msg = f"failed to load gateway config: {e}" + logger.error("Job '%s': %s", job["id"], msg) + return msg + + 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 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, + ) + # 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) + 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( + t, cleaned_delivery_content, media_files, + 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, + ) + + if 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 + + +# Late-bound origin namespace (see module docstring). Imported LAST so this module is fully +# populated before ``scheduler`` re-exports from it. +from cron import scheduler as _sched # noqa: E402 diff --git a/cron/scheduler_preflight.py b/cron/scheduler_preflight.py new file mode 100644 index 0000000000..ff7ddf5cb2 --- /dev/null +++ b/cron/scheduler_preflight.py @@ -0,0 +1,369 @@ +"""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. +""" + +from __future__ import annotations + +import errno +import json +import logging +import os +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, +}) + + +def _is_transient_provider_resolve_error(exc: BaseException) -> bool: + """True when primary provider resolution failed for a transient network reason (DNS blip, + ConnectError...). Must be eligible for ``fallback_providers`` like AuthError, else a healthy + fallback rung is never tried and the job dies before the first model call.""" + import socket + + # gaierror carries EAI_* codes, plain OSError carries errno — never mix the namespaces (raw + # literals like {8, 7, 11} are macOS-only and wrong on Linux). + eai_transient = { + getattr(socket, n) for n in ("EAI_NONAME", "EAI_AGAIN", "EAI_FAIL", "EAI_NODATA") + if hasattr(socket, n) + } + # Walk the cause chain; the scheduler wraps raw transport errors. + seen: set[int] = set() + cur: Optional[BaseException] = exc + while cur is not None and id(cur) not in seen: + seen.add(id(cur)) + module = type(cur).__module__ or "" + msg = str(cur).lower() + if type(cur).__name__ in _TRANSIENT_NET_EXC_NAMES: + return True + if any(m in module for m in ("httpx", "httpcore", "aiohttp")) and any( + needle in msg for needle in _TRANSIENT_HTTP_NEEDLES + ): + return True + if isinstance(cur, OSError): + if isinstance(cur, socket.gaierror): + if cur.errno in eai_transient: + return True + elif getattr(cur, "errno", None) in _TRANSIENT_ERRNOS: + return True + if any(needle in msg for needle in _TRANSIENT_OSERROR_NEEDLES): + return True + # Bare exceptions that carry the raw DNS text (format_runtime_provider_error). + if any(needle in msg for needle in _DNS_FAILURE_NEEDLES): + return True + cur = cur.__cause__ or cur.__context__ + return False + + +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 + + +def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]: + """READ-ONLY probe: would provider resolution fail for lack of a key? Mirrors run_job's + requested-provider computation. Skipped when a fallback chain exists — auth-fallback may + legitimately rescue a missing primary key, so blocking here would break that contract.""" + try: + if _sched.get_fallback_chain(cfg): + return None + except Exception: + return None # fail-open: never block on a preflight-internal error + + _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 + ) + model = job.get("model") or os.getenv("HERMES_MODEL") or "" + + from hermes_cli.auth import AuthError + + try: + from hermes_cli.runtime_provider import resolve_runtime_provider + + kwargs = {"requested": requested, "target_model": model} + if job.get("base_url"): + kwargs["explicit_base_url"] = job.get("base_url") + resolve_runtime_provider(**kwargs) + except AuthError as exc: + return ( + f"provider credential missing: {exc}. " + "Set the provider API key in .env (or `hermes setup`), or pin a " + "working provider via `hermes cron edit " + f"{job.get('id')} --provider

`." + ) + except Exception: + return None # non-auth errors are not a missing-credential verdict; real path reports them + return None + + +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. + """ + try: + from hermes_constants import get_default_hermes_root, get_hermes_home + + primary_home = get_default_hermes_root() + current_home = _sched.Path(get_hermes_home()) + if ( + primary_home.expanduser().resolve(strict=False) + == current_home.expanduser().resolve(strict=False) + ): + return [] # this IS the primary home — nothing to consult + config_path = primary_home.expanduser() / "config.yaml" + if not config_path.exists(): + return [] + + import yaml + + with open(config_path, encoding="utf-8") as f: + raw = yaml.safe_load(f) or {} + routes_raw = raw.get("profile_routes") + if routes_raw is None and isinstance(raw.get("gateway"), dict): + routes_raw = raw["gateway"].get("profile_routes") + if not isinstance(routes_raw, list): + return [] + + from gateway.profile_routing import parse_profile_routes + from hermes_cli.profiles import profile_matches_home + + return [ + route + for route in parse_profile_routes(routes_raw) + if route.enabled and profile_matches_home(route.profile) + ] + except Exception: + logger.debug("primary-gateway profile-route lookup unavailable", exc_info=True) + return [] + + +def _delivery_platform_routed_from_primary_gateway(platform_name: str) -> bool: + """True when the primary gateway routes this platform to the profile being served.""" + platform_key = platform_name.lower() + return any( + str(route.platform).lower() == platform_key + for route in _primary_profile_routes_for_current_home() + ) + + +class SharedRouteAdapters: + """Read-only adapter map for a credentialless satellite profile. + + ``get(platform, target)`` resolves the PRIMARY adapter iff the inbound route matcher + (``ProfileRoute.matches``) accepts the target; anything else (unmatched target, disabled route, + other profile, or target-less ``get(platform)``) is a miss — fail closed, never the default bot. + """ + + def __init__(self, primary_adapters, routes) -> None: + self._primary = dict(primary_adapters or {}) + self._routes = list(routes or []) + + def __bool__(self) -> bool: + return bool(self._primary) and bool(self._routes) + + def get(self, platform, target=None, default=None): + if not target: + return default + adapter = self._primary.get(platform) + if adapter is None: + return default + platform_key = str(getattr(platform, "value", platform)).lower() + chat_id = str(target.get("chat_id") or "") or None + thread_id = target.get("thread_id") + thread_id = str(thread_id) if thread_id else None + for route in self._routes: + if str(route.platform).lower() != platform_key: + continue + if not (route.chat_id or route.thread_id): + continue # guild-only routes are not target-exact + if route.matches(str(route.platform), chat_id=chat_id, thread_id=thread_id): + return adapter + return default + + +def _preflight_check_delivery(job: dict) -> Optional[str]: + """Check delivery targets resolve to configured platforms. + + ``local``/``origin``/``all`` are never checked (no gateway-config load). Unknown platform always + blocks; known platform blocks only if the gateway config loads AND reports it unconnected. + Config load failures fail OPEN. ``failure_deliver`` is checked with the same rules: a typo'd + failure platform would otherwise only surface when a failure occurs (NS-788). + """ + deliver_value = _sched._normalize_deliver_value(job.get("deliver", "local")) + failure_deliver_value = _sched._normalize_deliver_value( + _sched._delivery_lane_value(job, for_failure=True) + ) + lane_values = [deliver_value] + if failure_deliver_value != deliver_value: + lane_values.append(failure_deliver_value) + platform_parts: list[str] = [] + for lane_value in lane_values: + for part in lane_value.split(","): + part = part.strip() + if not part or part.lower() in {"local", "origin", "all"}: + continue + # bot-chat targets deliver via a local subprocess; failures surface in last_delivery_error. + if _sched.parse_bot_chat_deliver_token(part) is not None: + continue + platform_parts.append(part.split(":", 1)[0].strip()) + if not platform_parts: + return None + + connected: Optional[set] = None + for platform_name in platform_parts: + if not _sched._is_known_delivery_platform(platform_name): + return ( + f"delivery platform '{platform_name}' is not a known cron " + "delivery target. Fix the job's `deliver` value or configure " + "the platform's gateway credentials." + ) + if connected is None: + 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 |= _sched._relay_fronted_delivery_platforms(connected) + except Exception: + logger.debug( + "preflight: gateway config unavailable — skipping " + "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 + return ( + f"delivery platform '{platform_name}' has no gateway " + "credentials configured (not connected). Configure it via " + "`hermes setup` or change the job's `deliver` target." + ) + return None + + +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()] + if not skill_names: + return None + + from tools.skills_tool import skill_view + + for skill_name in skill_names: + try: + payload = json.loads(skill_view(skill_name)) + except Exception: + 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" + ): + 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 [] + ] + detail = ", ".join(missing) or "required setup incomplete" + return ( + f"attached skill '{skill_name}' is not ready: missing " + f"{detail}. Provide the missing prerequisites or detach the " + "skill from this job." + ) + return None + + +def _preflight_job_config(job: dict, cfg: dict) -> Optional[str]: + """Pre-dispatch validation: return a reason (missing key, unconfigured delivery, unready skill) + so the caller refuses BEFORE building agent machinery or burning an LLM call. Every check fails + open — preflight blocks only on an affirmative misconfiguration verdict.""" + for name, check in ( + ("provider_key", lambda: _preflight_check_provider_key(job, cfg)), + ("skills", lambda: _preflight_check_skills(job)), + ("delivery", lambda: _preflight_check_delivery(job)), + ): + try: + reason = check() + except Exception: + logger.debug("preflight check %s raised — failing open", name, exc_info=True) + continue + if reason: + return reason + return None + + +# Late-bound origin namespace (see module docstring). Imported LAST so this module is fully +# populated before ``scheduler`` re-exports from it. +from cron import scheduler as _sched # noqa: E402 diff --git a/cron/scheduler_prompt.py b/cron/scheduler_prompt.py new file mode 100644 index 0000000000..ed2eaaee6a --- /dev/null +++ b/cron/scheduler_prompt.py @@ -0,0 +1,363 @@ +"""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. +""" + +from __future__ import annotations + +import json +import logging +from hermes_time import now as _hermes_now +from typing import Optional + +# Log-record parity with the origin module. +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()] + if not stripped_lines: + return True + last_line = stripped_lines[-1].strip() + try: + gate = json.loads(last_line) + except (json.JSONDecodeError, ValueError): + return True + if not isinstance(gate, dict): + return True + return gate.get("wakeAgent", True) is not False + + +def _prepend_context_block(prompt: str, heading: str, intro: str, body: str) -> str: + """Prefix ``prompt`` with a fenced ``## heading`` data block.""" + return f"## {heading}\n{intro}\n\n```\n{body}\n```\n\n{prompt}" + + +_MAX_CONTEXT_CHARS = 8000 + + +def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]: + """Prepend the latest output of each ``context_from`` job; returns ``(prompt, injected)``.""" + context_from = job.get("context_from") + if not context_from: + return prompt, False + from cron.jobs import get_cron_output_dir + output_dir = get_cron_output_dir() + if isinstance(context_from, str): + context_from = [context_from] + injected = False + for source_job_id in context_from: + # "self" = the job's own id: continuity across runs without touching session history. + if isinstance(source_job_id, str) and source_job_id.strip().lower() == "self": + source_job_id = str(job.get("id") or "") + is_self = source_job_id == job.get("id") + # Traversal guard — valid job IDs are hex strings. + if not source_job_id or not all(c in "0123456789abcdef" for c in source_job_id): + logger.warning( + "context_from: skipping invalid job_id %r for job_id=%r name=%r%s", + source_job_id, job.get("id"), job.get("name"), _sched._cron_job_origin_log_suffix(job), + ) + continue + try: + output_files = sorted( + (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 + latest_output = output_files[0].read_text(encoding="utf-8").strip() + if len(latest_output) > _MAX_CONTEXT_CHARS: + latest_output = latest_output[:_MAX_CONTEXT_CHARS] + "\n\n[... output truncated ...]" + if not latest_output: + 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, + ) + 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, + ) + injected = True + except (OSError, PermissionError) as e: + # silent skip — never put error text into the prompt + logger.warning("context_from: failed to read output for job %r: %s", source_job_id, e) + return prompt, injected + + +def _load_cron_skill_parts(job: dict, skill_names: list[str]) -> list[str]: + """Load each named skill/bundle into prompt parts; unknown ones are skipped with a user notice.""" + from tools.skills_tool import skill_view + from tools.skill_usage import bump_use + from agent.skill_bundles import build_bundle_invocation_message, resolve_bundle_command_key + from agent.skill_utils import normalize_skill_lookup_name + + job_label = job.get("name", job.get("id")) + task_id = str(job.get("id") or "") or None + parts: list[str] = [] + skipped: list[str] = [] + 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, + ) + 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) + 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) + 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) + continue + + try: + bump_use(skill_name, task_id=task_id) + except Exception: + logger.debug("Cron job: failed to bump skill usage for '%s'", skill_name, exc_info=True) + + if parts: + parts.append("") + parts.extend([ + f'[IMPORTANT: The user has invoked the "{skill_name}" skill, indicating they want you to follow its instructions. The full skill content is loaded below.]', + "", + str(loaded.get("content") or "").strip(), + ]) + + if skipped: + parts.insert(0, ( + f"[IMPORTANT: The following skill(s) were listed for this job but could not be found " + f"and were skipped: {', '.join(skipped)}. " + f"Start your response with a brief notice so the user is aware, e.g.: " + f"'⚠️ Skill(s) not found and skipped: {', '.join(skipped)}']" + )) + return parts + + +def _build_job_prompt( + job: dict, + prerun_script: Optional[tuple] = None, + extra_prompt: Optional[str] = None, +) -> str: + """Build the effective prompt for a cron job, optionally loading skills first. + + ``prerun_script``: cached ``(success, stdout)`` from a script the caller already ran (wake-gate + check) — skips re-execution. ``extra_prompt``: per-run ``## Run Context`` for this fire only, + never persisted to the job. + """ + user_prompt = str(job.get("prompt") or "") + 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) + 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, + ) + has_injected_data = True + + prompt, _ctx_injected = _inject_context_from(job, prompt) + has_injected_data = has_injected_data or _ctx_injected + + # Durable per-job notepad; empty renders as "" so unused → byte-identical prompt. + from cron import notepad as cron_notepad + + notepad_section = cron_notepad.render_notepad_section(str(job.get("id") or "")) + if notepad_section: + 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()] + if not skill_names: + return _scan_assembled_cron_prompt( + prompt, + job, + has_skills=False, + has_injected_data=has_injected_data, + user_prompt=user_prompt, + ) + + parts = _load_cron_skill_parts(job, skill_names) + stable_prefix = None + if prompt: + from agent.skill_commands import append_user_instruction + + parts.append("") + # Skill blocks are stable per job config; the appended instruction is volatile per-run. + # Declare that boundary for the Anthropic cache planner. + stable_prefix = append_user_instruction(parts, prompt) + assembled = _scan_assembled_cron_prompt("\n".join(parts), job, has_skills=True) + if stable_prefix and len(assembled) > len(stable_prefix) and assembled.startswith(stable_prefix): + # Guarded: the scanner may mutate the bytes; mismatch → whole-message caching. + from agent.prompt_cache_boundary import register_stable_prefix + + register_stable_prefix(stable_prefix) + return assembled + + +def _scan_assembled_cron_prompt( + assembled: str, + job: dict, + *, + has_skills: bool = False, + has_injected_data: bool = False, + user_prompt: Optional[str] = None, +) -> str: + """Scan the assembled cron prompt for injection; raise ``CronPromptInjectionBlocked`` on a hit. + + Needed because skill content is loaded from disk at runtime (never scanned at create/update) + and cron auto-approves tool calls. Tier is chosen by what the prompt CONTAINS: user prompt + + hint only → STRICT ``_scan_cron_prompt``; skills or injected data → LOOSER + ``_scan_cron_skill_assembled`` (command-shape patterns dropped, invisible unicode sanitized not + blocked, so a false positive cannot permanently kill a job). With injected data but no skills, + ``user_prompt`` is additionally scanned STRICT (defense-in-depth for legacy jobs). + """ + from tools.cronjob_tools import _scan_cron_prompt, _scan_cron_skill_assembled + + 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 + 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, + ) + raise _sched.CronPromptInjectionBlocked(scan_error) + return assembled + + +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. + """ + 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 + if err: + job_id = job.get("id") + logger.error( + "Job '%s': refusing to run — unsafe provider/base_url pair could " + "exfiltrate a stored credential: %s", + job_id, err, + ) + raise RuntimeError(f"Cron job '{job_id}' blocked for safety: {err}") + + +def _block_and_pause_job( + job_id: str, job_name: str, reason: str +) -> tuple[bool, str, str, Optional[str]]: + """Fail a run closed and pause the job: an unrunnable job left enabled re-fires every tick + forever; ``paused_at``/``paused_reason`` give an auditable record.""" + from cron.jobs import pause_job + + logger.error("Job '%s': %s", job_id, reason) + try: + pause_job(job_id, f"Auto-paused by scheduler: {reason}") + except Exception: + logger.exception("Job '%s': failed to auto-pause unrunnable job", job_id) + + now_iso = _hermes_now().strftime("%Y-%m-%d %H:%M:%S") + doc = ( + f"# Cron Job: {job_name}\n\n" + f"**Job ID:** {job_id}\n" + f"**Run Time:** {now_iso}\n" + f"**Status:** blocked (unrunnable job) — auto-paused\n\n" + f"{reason}\n" + ) + alert = f"⚠ Cron job '{job_name}' was auto-paused\n\n{reason}" + return False, doc, alert, reason + + +# Late-bound origin namespace (see module docstring). Imported LAST so this module is fully +# populated before ``scheduler`` re-exports from it. +from cron import scheduler as _sched # noqa: E402 diff --git a/cron/scheduler_script.py b/cron/scheduler_script.py new file mode 100644 index 0000000000..6ac67845d3 --- /dev/null +++ b/cron/scheduler_script.py @@ -0,0 +1,517 @@ +"""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. +""" + +from __future__ import annotations + +import contextlib +import contextvars +import logging +import os +import shutil +import signal +import subprocess +import sys +import threading +import time +from cron.jobs import _ensure_cron_dir +from pathlib import Path +from typing import Any +from typing import Optional +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from cron.scheduler import _CancelEventLike + +# Log-record parity with the origin module. +logger = logging.getLogger("cron.scheduler") + + +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: + 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 + + +_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 + + +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 + + +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() + 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 + + +def _windows_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, str]]: + """Hidden, output-capable Python invocation for Windows cron scripts. ``pythonw.exe`` loses + captured output; uv venv launchers can re-exec the base console python and flash a window even + with CREATE_NO_WINDOW, so run the base python directly with venv paths overlaid in env.""" + if sys.platform != "win32": + return python_exe, {} + + interpreter = _sched.Path(python_exe) + venv_dir = interpreter.parent.parent + env_overlay: dict[str, str] = {} + + if interpreter.name.lower() == "pythonw.exe": + sibling = interpreter.with_name("python.exe") + if sibling.exists(): + interpreter = sibling + + cfg = _read_windows_pyvenv_cfg(venv_dir) + home = cfg.get("home", "") + site_packages = venv_dir / "Lib" / "site-packages" + if "uv" in cfg and home: + base_python = _sched.Path(home) / "python.exe" + if base_python.exists() and site_packages.exists(): + interpreter = base_python + env_overlay["VIRTUAL_ENV"] = str(venv_dir) + pythonpath_entries = [str(_sched.Path(__file__).resolve().parents[1]), str(site_packages)] + existing_pythonpath = os.environ.get("PYTHONPATH", "") + if existing_pythonpath: + pythonpath_entries.append(existing_pythonpath) + env_overlay["PYTHONPATH"] = os.pathsep.join(pythonpath_entries) + + return str(interpreter), env_overlay + + +def _terminate_cron_script_process(proc: subprocess.Popen) -> None: + """Best-effort hard stop of a cron script and every child it spawned.""" + if proc.poll() is not None: + return + if sys.platform == "win32": + try: + subprocess.run( + ["taskkill", "/PID", str(proc.pid), "/T", "/F"], + 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)) + try: + proc.wait(timeout=1.0) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=1.0) + + +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: + # Already reaped: kill_process_tree would log a spurious "no signal" warning. + return + 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", + pid, + ) + _sched._terminate_cron_script_process(proc) + return + try: + # Function-local (monkeypatchable); separate try so an import problem is not + # misreported as a kill failure. + from agent.deadline import kill_process_tree + except Exception: + logger.warning( + "agent.deadline.kill_process_tree unavailable; " + "falling back to process-group termination", + exc_info=True, + ) + _sched._terminate_cron_script_process(proc) + return + try: + if kill_process_tree(pid): + return + logger.warning( + "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, + ) + _sched._terminate_cron_script_process(proc) + + +def _drain_script_pipes(proc: subprocess.Popen) -> None: + """Reap a terminated script without blocking forever: a surviving descendant can hold the pipe + write ends open, so bound the drain and abandon the pipes (output is not needed).""" + with contextlib.suppress(subprocess.TimeoutExpired): + proc.communicate(timeout=5.0) + return + with contextlib.suppress(OSError): + proc.kill() + for stream in (proc.stdout, proc.stderr): + with contextlib.suppress(OSError): + if stream is not None: + stream.close() + with contextlib.suppress(subprocess.TimeoutExpired): + proc.wait(timeout=5.0) + + +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. + """ + 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. + logger.warning( + "Windows cron script: venv site-packages %s not found; running " + "without .pth processing (editable installs may be unimportable)", + site_packages, + ) + return [python_exe, script_path] + bootstrap = ( + "import os, runpy, site, sys;" + f"site.addsitedir({str(site_packages)!r});" + "script = sys.argv[1];" + "sys.argv = [script] + sys.argv[2:];" + "sys.path.insert(0, os.path.dirname(os.path.abspath(script)));" + "runpy.run_path(script, run_name='__main__')" + ) + 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). + """ + 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. + if "\x00" in str(script_path): + return False, 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}" + 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, ( + 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}" + if not path.is_file(): + return False, f"Script path is not a file: {path}" + + 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"}: + # 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, ( + 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)] + + try: + from tools.environments.local import build_subprocess_env + + 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), + "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, + ) + deadline = time.monotonic() + script_timeout + while True: + 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}" + try: + stdout_raw, stderr_raw = proc.communicate(timeout=min(0.1, remaining)) + break + except subprocess.TimeoutExpired: + continue + + stdout = (stdout_raw or "").strip() + stderr = (stderr_raw or "").strip() + + # Redact secrets before ANY return path. + try: + from agent.redact import redact_sensitive_text + stdout = redact_sensitive_text(stdout) + 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]" + + if proc.returncode != 0: + parts = [f"Script exited with code {proc.returncode}"] + if stderr: + parts.append(f"stderr:\n{stderr}") + 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}" + + +def _start_heartbeat_thread(loop_fn, name: str, fail_log) -> Optional[threading.Thread]: + """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, + ) + try: + thread.start() + except Exception: + fail_log() + return None + return thread + + +def _run_job_script_with_claim_heartbeat( + job: dict, + script_path: str, + workdir: Optional[str] = None, + cancel_event: Optional[_CancelEventLike] = None, +) -> tuple[bool, str]: + """Run a cron script while heartbeating its owned one-shot claim. + + A long script can outlive the stale-claim TTL; without a heartbeat another scheduler would + re-dispatch the one-shot. Recurring/unclaimed runs have no durable claim → no thread. The owner + is captured from the dispatched job, never re-read, so a stale runner cannot extend a + replacement owner's claim. + """ + 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 + ): + return _sched._run_job_script(script_path, workdir=workdir, cancel_event=cancel_event) + + job_id = str(job.get("id") or "") + stop = threading.Event() + + def _heartbeat_loop() -> None: + while not stop.wait(_sched._RUN_CLAIM_HEARTBEAT_SECONDS): + try: + _sched.heartbeat_run_claim(job_id, expected_owner=owner) + except Exception: + logger.debug("Job '%s': script run_claim heartbeat failed", job_id, exc_info=True) + + 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, + ), + ) + if heartbeat_thread is None: + return _sched._run_job_script(script_path, workdir=workdir, cancel_event=cancel_event) + + try: + return _sched._run_job_script(script_path, workdir=workdir, cancel_event=cancel_event) + finally: + stop.set() + # Bounded join: the heartbeat may be blocked on another process's jobs-file lock. + heartbeat_thread.join(timeout=1.0) + + +# Late-bound origin namespace (see module docstring). Imported LAST so this module is fully +# populated before ``scheduler`` re-exports from it. +from cron import scheduler as _sched # noqa: E402 diff --git a/tests/tools/test_windows_native_support.py b/tests/tools/test_windows_native_support.py index b1adc95bf6..716709baa2 100644 --- a/tests/tools/test_windows_native_support.py +++ b/tests/tools/test_windows_native_support.py @@ -611,12 +611,12 @@ class TestCodeExecutionTransportTcpFallback: class TestCronSchedulerBashResolution: - """cron.scheduler must NOT hardcode /bin/bash — .sh scripts need a + """cron.scheduler_script (the pre-run script runner) must NOT hardcode /bin/bash — .sh scripts need a dynamically-resolved bash so Windows (Git Bash) works.""" def test_source_uses_shutil_which_for_bash(self): root = Path(__file__).resolve().parents[2] - source = (root / "cron" / "scheduler.py").read_text(encoding="utf-8") + source = (root / "cron" / "scheduler_script.py").read_text(encoding="utf-8") # The old hardcoded path should be gone as the sole bash source. # It may still appear as a POSIX fallback after shutil.which(), so # we check for the shutil.which call near the .sh/.bash branch. @@ -626,7 +626,7 @@ class TestCronSchedulerBashResolution: def test_error_message_when_bash_missing(self): root = Path(__file__).resolve().parents[2] - source = (root / "cron" / "scheduler.py").read_text(encoding="utf-8") + source = (root / "cron" / "scheduler_script.py").read_text(encoding="utf-8") # The graceful-failure message must mention "bash not found" so # Windows users without Git Bash see an actionable error instead # of a WinError 2 traceback.