refactor(cron): split scheduler.py into delivery/script/prompt/preflight modules

cron/scheduler.py 6386 -> 3423. Four sibling modules hold the free-function clusters,
re-exported from cron.scheduler so every existing import/monkeypatch target keeps resolving;
origin-resident helpers are reached late-bound via `_sched` (same-object visibility, no
import cycle). Every moved node is AST-identical to the base. Source-inspection test for the
bash resolver repointed to cron/scheduler_script.py.
This commit is contained in:
Teknium
2026-09-02 18:34:26 -07:00
parent 113f04616b
commit 5a8fbbf16c
6 changed files with 3322 additions and 3083 deletions
+117 -3080
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+369
View File
@@ -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.<name>`` 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 <p>`."
)
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
+363
View File
@@ -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.<name>`` 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 "<unknown>"
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
+517
View File
@@ -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.<name>`` 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
+3 -3
View File
@@ -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.