refactor(cron): extract per-target delivery prologue, unify timeout/env/skill-name helpers in scheduler_* modules

This commit is contained in:
Teknium
2026-09-02 19:31:14 -07:00
parent 5a8fbbf16c
commit 76a1ebdb4c
4 changed files with 580 additions and 906 deletions
+346 -560
View File
File diff suppressed because it is too large Load Diff
+30 -60
View File
@@ -1,8 +1,8 @@
"""Cron pre-run preflight: transient provider-resolution error classification, provider-key /
delivery-target / skills checks, and the shared-route adapter view used by satellite profiles.
Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident
helpers are reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.<name>`` keeps working.
Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident helpers are
reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.<name>`` keeps working.
"""
from __future__ import annotations
@@ -16,42 +16,26 @@ from typing import Optional
# Log-record parity with the origin module.
logger = logging.getLogger("cron.scheduler")
# Error-string prefixes from ``run_job``; ``run_one_job`` keys off them for last_status and the
# alert-once dedup. ``:silent`` = already alerted on a previous tick — do not deliver again.
BLOCKED_CONFIG_MARKER = "[blocked_config]"
BLOCKED_CONFIG_SILENT_MARKER = "[blocked_config:silent]"
# Drift-guard skip: same contract (drift_alerted bit on the job record).
DRIFT_SKIP_MARKER = "[drift_skip]"
DRIFT_SKIP_SILENT_MARKER = "[drift_skip:silent]"
_TRANSIENT_NET_EXC_NAMES = frozenset({
"ConnectError", "ConnectTimeout", "ReadTimeout", "WriteTimeout", "PoolTimeout", "NetworkError",
"TimeoutException", "ClientConnectorError", "ClientConnectorDNSError", "ServerTimeoutError",
"ClientOSError",
})
_DNS_FAILURE_NEEDLES = ("nodename nor servname", "name or service not known")
_TRANSIENT_OSERROR_NEEDLES = _DNS_FAILURE_NEEDLES + (
"temporary failure in name resolution", "network is unreachable",
)
_TRANSIENT_HTTP_NEEDLES = _TRANSIENT_OSERROR_NEEDLES + (
"failed to resolve", "connection refused", "timed out", "timeout",
)
_TRANSIENT_ERRNOS = frozenset({
errno.ECONNREFUSED, errno.ECONNRESET, errno.EHOSTUNREACH, errno.ENETUNREACH, errno.ENETDOWN,
errno.ETIMEDOUT, errno.EAGAIN,
@@ -101,9 +85,7 @@ def _is_transient_provider_resolve_error(exc: BaseException) -> bool:
def _cron_preflight_enabled(cfg: dict) -> bool:
"""Preflight is ON unless ``cron.preflight`` is literally ``false``."""
cron_cfg = (cfg or {}).get("cron")
if not isinstance(cron_cfg, dict):
return True
return cron_cfg.get("preflight", True) is not False
return not isinstance(cron_cfg, dict) or cron_cfg.get("preflight", True) is not False
def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]:
@@ -118,9 +100,7 @@ def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]:
_cron_cfg = cfg.get("cron") if isinstance(cfg.get("cron"), dict) else {}
requested = (
job.get("provider")
or str((_cron_cfg or {}).get("model_provider") or "").strip()
or None
job.get("provider") or str((_cron_cfg or {}).get("model_provider") or "").strip() or None
)
model = job.get("model") or os.getenv("HERMES_MODEL") or ""
@@ -147,13 +127,11 @@ def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]:
def _primary_profile_routes_for_current_home() -> list:
"""Primary gateway ``profile_routes`` targeting the profile being served; ``[]`` if this IS the
primary home.
Satellite crons are ticked and delivered by the primary gateway (a satellite holding its own
token is a ``duplicate_credential`` fatal). Reads the primary config.yaml directly (top-level or
nested ``gateway.``) instead of ``load_gateway_config()`` so no primary platform config leaks
into this process. Shared by preflight rescue and delivery-time resolution so they cannot drift.
"""
primary home. Satellite crons are ticked and delivered by the primary gateway (a satellite
holding its own token is a ``duplicate_credential`` fatal). Reads the primary config.yaml
directly (top-level or nested ``gateway.``) instead of ``load_gateway_config()`` so no primary
platform config leaks into this process. Shared by preflight rescue and delivery-time
resolution so they cannot drift."""
try:
from hermes_constants import get_default_hermes_root, get_hermes_home
@@ -182,8 +160,7 @@ def _primary_profile_routes_for_current_home() -> list:
from hermes_cli.profiles import profile_matches_home
return [
route
for route in parse_profile_routes(routes_raw)
route for route in parse_profile_routes(routes_raw)
if route.enabled and profile_matches_home(route.profile)
]
except Exception:
@@ -284,10 +261,11 @@ def _preflight_check_delivery(job: dict) -> Optional[str]:
"delivery credential check", exc_info=True,
)
return None # fail-open
if platform_name.lower() not in connected:
# Multiplex: a satellite served by the primary's adapters reads unconnected — no block.
if _delivery_platform_routed_from_primary_gateway(platform_name):
continue
# Multiplex: a satellite served by the primary's adapters reads unconnected — no block.
if (
platform_name.lower() not in connected
and not _delivery_platform_routed_from_primary_gateway(platform_name)
):
return (
f"delivery platform '{platform_name}' has no gateway "
"credentials configured (not connected). Configure it via "
@@ -296,16 +274,20 @@ def _preflight_check_delivery(job: dict) -> Optional[str]:
return None
# ``skill_view`` payload keys naming missing prerequisites -> label for the preflight verdict.
_SKILL_MISSING_FIELDS = (
("missing_required_environment_variables", "env ${}"),
("missing_required_commands", "command '{}'"),
("missing_credential_files", "credential file {}"),
)
def _preflight_check_skills(job: dict) -> Optional[str]:
"""Block only on an affirmative ``setup_needed`` verdict from ``skill_view``; skills that fail
to load fall through to ``_build_job_prompt``'s skipped-skill handling (fail-open)."""
skills = job.get("skills")
if skills is None:
legacy = job.get("skill")
skills = [legacy] if legacy else []
elif isinstance(skills, str):
skills = [skills]
skill_names = [str(name).strip() for name in skills if str(name).strip()]
from cron.scheduler_prompt import _job_skill_names
skill_names = _job_skill_names(job)
if not skill_names:
return None
@@ -318,23 +300,11 @@ def _preflight_check_skills(job: dict) -> Optional[str]:
continue # unreadable/missing skill → existing skip handling
if not isinstance(payload, dict) or not payload.get("success"):
continue
if (
payload.get("setup_needed")
or payload.get("readiness_status") == "setup_needed"
):
if payload.get("setup_needed") or payload.get("readiness_status") == "setup_needed":
missing = [
f"env ${name}"
for name in payload.get(
"missing_required_environment_variables"
) or []
]
missing += [
f"command '{name}'"
for name in payload.get("missing_required_commands") or []
]
missing += [
f"credential file {name}"
for name in payload.get("missing_credential_files") or []
fmt.format(name)
for key, fmt in _SKILL_MISSING_FIELDS
for name in payload.get(key) or []
]
detail = ", ".join(missing) or "required setup incomplete"
return (
+72 -94
View File
@@ -1,8 +1,8 @@
"""Cron job prompt assembly: context_from injection, skill loading, the assembled-prompt
injection scan, and the credential-exfil / config-block guards.
Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident
helpers are reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.<name>`` keeps working.
Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident helpers are
reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.<name>`` keeps working.
"""
from __future__ import annotations
@@ -19,19 +19,14 @@ logger = logging.getLogger("cron.scheduler")
def _parse_wake_gate(script_output: str) -> bool:
"""Wake gate: False only if the last non-empty stdout line is JSON ``{"wakeAgent": false}``
(agent skipped entirely — no LLM run, no delivery); anything else wakes normally."""
if not script_output:
return True
stripped_lines = [line for line in script_output.splitlines() if line.strip()]
stripped_lines = [line for line in (script_output or "").splitlines() if line.strip()]
if not stripped_lines:
return True
last_line = stripped_lines[-1].strip()
try:
gate = json.loads(last_line)
gate = json.loads(stripped_lines[-1].strip())
except (json.JSONDecodeError, ValueError):
return True
if not isinstance(gate, dict):
return True
return gate.get("wakeAgent", True) is not False
return not isinstance(gate, dict) or gate.get("wakeAgent", True) is not False
def _prepend_context_block(prompt: str, heading: str, intro: str, body: str) -> str:
@@ -39,8 +34,29 @@ def _prepend_context_block(prompt: str, heading: str, intro: str, body: str) ->
return f"## {heading}\n{intro}\n\n```\n{body}\n```\n\n{prompt}"
def _job_skill_names(job: dict) -> list[str]:
"""Normalized skill names from ``skills`` (list or str) or the legacy singular ``skill``."""
skills = job.get("skills")
if skills is None:
legacy = job.get("skill")
skills = [legacy] if legacy else []
elif isinstance(skills, str):
skills = [skills]
return [str(name).strip() for name in skills if str(name).strip()]
_MAX_CONTEXT_CHARS = 8000
_SELF_CONTEXT_INTRO = (
"The following is this job's most recent output from its previous run. Use it for "
"continuity: avoid repeating what was already reported, and continue where the last run "
"left off."
)
_UPSTREAM_CONTEXT_INTRO = (
"The following is the most recent output from a preceding cron job. Use it as context for "
"your analysis."
)
def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]:
"""Prepend the latest output of each ``context_from`` job; returns ``(prompt, injected)``."""
@@ -66,9 +82,7 @@ def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]:
continue
try:
output_files = sorted(
(output_dir / source_job_id).glob("*.md"),
key=lambda f: f.stat().st_mtime,
reverse=True,
(output_dir / source_job_id).glob("*.md"), key=lambda f: f.stat().st_mtime, reverse=True,
)
if not output_files:
continue # silent skip — no output yet
@@ -79,19 +93,11 @@ def _inject_context_from(job: dict, prompt: str) -> tuple[str, bool]:
continue # silent skip — empty output
if is_self:
prompt = _prepend_context_block(
prompt, "Your previous run's output",
"The following is this job's most recent output from its "
"previous run. Use it for continuity: avoid repeating what "
"was already reported, and continue where the last run "
"left off.",
latest_output,
prompt, "Your previous run's output", _SELF_CONTEXT_INTRO, latest_output,
)
else:
prompt = _prepend_context_block(
prompt, f"Output from job '{source_job_id}'",
"The following is the most recent output from a preceding "
"cron job. Use it as context for your analysis.",
latest_output,
prompt, f"Output from job '{source_job_id}'", _UPSTREAM_CONTEXT_INTRO, latest_output,
)
injected = True
except (OSError, PermissionError) as e:
@@ -111,34 +117,31 @@ def _load_cron_skill_parts(job: dict, skill_names: list[str]) -> list[str]:
task_id = str(job.get("id") or "") or None
parts: list[str] = []
skipped: list[str] = []
def _skip(msg: str, *args) -> None:
logger.warning("Cron job '%s': " + msg, job_label, *args)
skipped.append(skill_name)
for skill_name in skill_names:
# Bundles shadow same-slug skills, mirroring the CLI/gateway slash-command path.
bundle_key = resolve_bundle_command_key(skill_name.lstrip("/"))
if bundle_key:
bundle_payload = build_bundle_invocation_message(
bundle_key, user_instruction="", task_id=task_id,
)
bundle_payload = build_bundle_invocation_message(bundle_key, user_instruction="", task_id=task_id)
if bundle_payload:
if parts:
parts.append("")
parts.append(bundle_payload[0])
continue
logger.warning(
"Cron job '%s': bundle '%s' could not load any skills, skipping", job_label, skill_name,
)
skipped.append(skill_name)
else:
_skip("bundle '%s' could not load any skills, skipping", skill_name)
continue
try:
loaded = json.loads(skill_view(normalize_skill_lookup_name(skill_name)))
except (json.JSONDecodeError, TypeError):
logger.warning("Cron job '%s': skill '%s' returned invalid JSON, skipping", job_label, skill_name)
skipped.append(skill_name)
_skip("skill '%s' returned invalid JSON, skipping", skill_name)
continue
if not loaded.get("success"):
error = loaded.get("error") or f"Failed to load skill '{skill_name}'"
logger.warning("Cron job '%s': skill not found, skipping — %s", job_label, error)
skipped.append(skill_name)
_skip("skill not found, skipping — %s", loaded.get("error") or f"Failed to load skill '{skill_name}'")
continue
try:
@@ -164,6 +167,19 @@ def _load_cron_skill_parts(job: dict, skill_names: list[str]) -> list[str]:
return parts
_CRON_HINT = (
"[IMPORTANT: You are running as a scheduled cron job. "
"DELIVERY: Your final response will be automatically delivered "
"to the user — do NOT use send_message or try to deliver "
"the output yourself. Just produce your report/output as your "
"final response and the system handles the rest. "
"SILENT: If there is genuinely nothing new to report, respond "
"with exactly \"[SILENT]\" (nothing else) to suppress delivery. "
"Never combine [SILENT] with content — either report your "
"findings normally, or say [SILENT] and nothing more.]\n\n"
)
def _build_job_prompt(
job: dict,
prerun_script: Optional[tuple] = None,
@@ -179,32 +195,23 @@ def _build_job_prompt(
if extra_prompt:
user_prompt = f"{user_prompt}\n\n## Run Context\n{extra_prompt}"
prompt = user_prompt
skills = job.get("skills")
# Runtime DATA (script stdout, upstream output) legitimately quotes command-shape strings, so it
# must not be scanned with the strict user-prompt set — see _scan_assembled_cron_prompt.
has_injected_data = False
script_path = job.get("script")
if script_path:
if prerun_script is not None:
success, script_output = prerun_script
else:
success, script_output = _sched._run_job_script(script_path)
success, script_output = (
prerun_script if prerun_script is not None else _sched._run_job_script(script_path)
)
if success and not script_output:
return None # no output → nothing to report, skip the AI call
if success:
prompt = _prepend_context_block(
prompt, "Script Output",
"The following data was collected by a pre-run script. "
"Use it as context for your analysis.",
script_output,
)
else:
prompt = _prepend_context_block(
prompt, "Script Error",
"The data-collection script failed. Report this to the user.",
script_output,
)
heading, intro = (
("Script Output", "The following data was collected by a pre-run script. Use it as context for your analysis.")
if success
else ("Script Error", "The data-collection script failed. Report this to the user.")
)
prompt = _prepend_context_block(prompt, heading, intro, script_output)
has_injected_data = True
prompt, _ctx_injected = _inject_context_from(job, prompt)
@@ -218,32 +225,11 @@ def _build_job_prompt(
prompt = f"{notepad_section}{prompt}"
has_injected_data = True
cron_hint = (
"[IMPORTANT: You are running as a scheduled cron job. "
"DELIVERY: Your final response will be automatically delivered "
"to the user — do NOT use send_message or try to deliver "
"the output yourself. Just produce your report/output as your "
"final response and the system handles the rest. "
"SILENT: If there is genuinely nothing new to report, respond "
"with exactly \"[SILENT]\" (nothing else) to suppress delivery. "
"Never combine [SILENT] with content — either report your "
"findings normally, or say [SILENT] and nothing more.]\n\n"
)
prompt = cron_hint + prompt
if skills is None:
legacy = job.get("skill")
skills = [legacy] if legacy else []
elif isinstance(skills, str):
skills = [skills]
skill_names = [str(name).strip() for name in skills if str(name).strip()]
prompt = _CRON_HINT + prompt
skill_names = _job_skill_names(job)
if not skill_names:
return _scan_assembled_cron_prompt(
prompt,
job,
has_skills=False,
has_injected_data=has_injected_data,
user_prompt=user_prompt,
prompt, job, has_skills=False, has_injected_data=has_injected_data, user_prompt=user_prompt,
)
parts = _load_cron_skill_parts(job, skill_names)
@@ -285,18 +271,15 @@ def _scan_assembled_cron_prompt(
if has_skills or has_injected_data:
# The cleaned (sanitized) prompt is what actually runs.
cleaned, scan_error = _scan_cron_skill_assembled(assembled)
assembled = cleaned
assembled, scan_error = _scan_cron_skill_assembled(assembled)
if not scan_error and not has_skills and user_prompt:
scan_error = _scan_cron_prompt(user_prompt)
else:
scan_error = _scan_cron_prompt(assembled)
if scan_error:
job_label = job.get("name") or job.get("id") or "<unknown>"
logger.warning(
"Cron job '%s': assembled prompt blocked by injection scanner — %s",
job_label,
scan_error,
job.get("name") or job.get("id") or "<unknown>", scan_error,
)
raise _sched.CronPromptInjectionBlocked(scan_error)
return assembled
@@ -304,25 +287,20 @@ def _scan_assembled_cron_prompt(
def _guard_job_credential_exfil(job: dict) -> None:
"""Fail closed (RuntimeError) if the stored provider/base_url pair could exfiltrate a key.
Runtime backstop: jobs persisted before the create/update guard, or written directly to the
store, reach provider resolution unchecked. Fallback providers come from operator config and
are validated by the caller, not here.
"""
are validated by the caller, not here."""
try:
from tools.cronjob_tools import _validate_cron_base_url
err = _validate_cron_base_url(job.get("provider"), job.get("base_url"))
except Exception as exc:
# Fail CLOSED on validator/import errors — but only for jobs WITH a base_url override; a job
# without one cannot exfiltrate via this path, so it still runs.
if job.get("base_url"):
err = (
f"could not validate provider/base_url pair "
f"({exc.__class__.__name__}: {exc}); refusing to run a job with "
"an unverified base_url override"
)
else:
err = None
err = (
f"could not validate provider/base_url pair "
f"({exc.__class__.__name__}: {exc}); refusing to run a job with "
"an unverified base_url override"
) if job.get("base_url") else None
if err:
job_id = job.get("id")
logger.error(
+132 -192
View File
@@ -1,8 +1,8 @@
"""Cron pre-run script execution: timeouts, Windows venv bootstrap, process-tree termination,
and the claim-heartbeat thread that keeps a long script's run claim alive.
Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident
helpers are reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.<name>`` keeps working.
Split out of ``cron.scheduler``; every name is re-exported there, and origin-resident helpers are
reached late-bound via ``_sched`` so monkeypatching ``cron.scheduler.<name>`` keeps working.
"""
from __future__ import annotations
@@ -20,6 +20,7 @@ import time
from cron.jobs import _ensure_cron_dir
from pathlib import Path
from typing import Any
from typing import Callable
from typing import Optional
from typing import TYPE_CHECKING
@@ -30,37 +31,49 @@ if TYPE_CHECKING:
logger = logging.getLogger("cron.scheduler")
def _positive_int(raw) -> Optional[int]:
"""``int(float(raw))`` when > 0, else None; raises on unparsable input."""
timeout = int(float(raw))
return timeout if timeout > 0 else None
def _timeout_from_env_or_config(env_var: str, config_key: str, parse: Callable[[Any], Any], label: str):
"""Shared env → ``cron.<config_key>`` resolution. ``parse`` returns the value or None to keep
looking; a parse error on the env var WARNs, on config DEBUGs. Returns None when neither yields."""
env_value = os.getenv(env_var, "").strip()
if env_value:
try:
value = parse(env_value)
if value is not None:
return value
except Exception:
logger.warning("Invalid %s=%r; using config/default", env_var, env_value)
try:
cfg = _sched.load_config() or {}
cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {}
configured = cron_cfg.get(config_key)
if configured is not None:
value = parse(configured)
if value is not None:
return value
except Exception as exc:
logger.debug("Failed to load %s from config: %s", label, exc)
return None
def _get_script_timeout() -> int:
"""Resolve cron pre-run script timeout from module/env/config with a safe default."""
if _sched._SCRIPT_TIMEOUT != _sched._DEFAULT_SCRIPT_TIMEOUT:
try:
timeout = int(float(_sched._SCRIPT_TIMEOUT))
if timeout > 0:
timeout = _positive_int(_sched._SCRIPT_TIMEOUT)
if timeout is not None:
return timeout
except Exception:
logger.warning("Invalid patched _SCRIPT_TIMEOUT=%r; using env/config/default", _sched._SCRIPT_TIMEOUT)
env_value = os.getenv("HERMES_CRON_SCRIPT_TIMEOUT", "").strip()
if env_value:
try:
timeout = int(float(env_value))
if timeout > 0:
return timeout
except Exception:
logger.warning("Invalid HERMES_CRON_SCRIPT_TIMEOUT=%r; using config/default", env_value)
try:
cfg = _sched.load_config() or {}
cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {}
configured = cron_cfg.get("script_timeout_seconds")
if configured is not None:
timeout = int(float(configured))
if timeout > 0:
return timeout
except Exception as exc:
logger.debug("Failed to load cron script timeout from config: %s", exc)
return _sched._DEFAULT_SCRIPT_TIMEOUT
resolved = _timeout_from_env_or_config(
"HERMES_CRON_SCRIPT_TIMEOUT", "script_timeout_seconds", _positive_int, "cron script timeout",
)
return _sched._DEFAULT_SCRIPT_TIMEOUT if resolved is None else resolved
_DEFAULT_MEDIA_SEND_TIMEOUT = 300
@@ -69,72 +82,33 @@ _DEFAULT_MEDIA_SEND_TIMEOUT = 300
def _get_media_send_timeout() -> int:
"""Per-attachment media-send timeout: HERMES_CRON_MEDIA_SEND_TIMEOUT env, then
``cron.media_send_timeout_seconds``, then 300s (long TTS audio can exceed a 30s window)."""
env_value = os.getenv("HERMES_CRON_MEDIA_SEND_TIMEOUT", "").strip()
if env_value:
try:
timeout = int(float(env_value))
if timeout > 0:
return timeout
except Exception:
logger.warning(
"Invalid HERMES_CRON_MEDIA_SEND_TIMEOUT=%r; using config/default",
env_value,
)
try:
cfg = _sched.load_config() or {}
cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {}
configured = cron_cfg.get("media_send_timeout_seconds")
if configured is not None:
timeout = int(float(configured))
if timeout > 0:
return timeout
except Exception as exc:
logger.debug("Failed to load cron media-send timeout from config: %s", exc)
return _DEFAULT_MEDIA_SEND_TIMEOUT
resolved = _timeout_from_env_or_config(
"HERMES_CRON_MEDIA_SEND_TIMEOUT", "media_send_timeout_seconds", _positive_int,
"cron media-send timeout",
)
return _DEFAULT_MEDIA_SEND_TIMEOUT if resolved is None else resolved
def _get_session_db_timeout() -> float:
"""Bound on run_job's SessionDB init: HERMES_CRON_SESSION_DB_TIMEOUT env, then
``cron.session_db_timeout_seconds`` (in DEFAULT_CONFIG), then 10s. Unlike sibling timeouts,
0 is meaningful (unlimited, debugging opt-in), so values pass through untouched."""
env_value = os.getenv("HERMES_CRON_SESSION_DB_TIMEOUT", "").strip()
if env_value:
try:
return float(env_value)
except (ValueError, TypeError):
logger.warning(
"Invalid HERMES_CRON_SESSION_DB_TIMEOUT=%r; using config/default",
env_value,
)
try:
cfg = _sched.load_config() or {}
cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {}
configured = cron_cfg.get("session_db_timeout_seconds")
if configured is not None:
return float(configured)
except Exception as exc:
logger.debug("Failed to load cron.session_db_timeout_seconds from config: %s", exc)
return 10.0
resolved = _timeout_from_env_or_config(
"HERMES_CRON_SESSION_DB_TIMEOUT", "session_db_timeout_seconds", float,
"cron.session_db_timeout_seconds",
)
return 10.0 if resolved is None else resolved
def _read_windows_pyvenv_cfg(venv_dir: Path) -> dict[str, str]:
cfg_path = venv_dir / "pyvenv.cfg"
try:
lines = cfg_path.read_text(encoding="utf-8").splitlines()
lines = (venv_dir / "pyvenv.cfg").read_text(encoding="utf-8").splitlines()
except OSError:
return {}
parsed: dict[str, str] = {}
for raw in lines:
if "=" not in raw:
continue
key, value = raw.split("=", 1)
parsed[key.strip().lower()] = value.strip()
return parsed
return {
key.strip().lower(): value.strip()
for key, value in (raw.split("=", 1) for raw in lines if "=" in raw)
}
def _windows_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, str]]:
@@ -178,35 +152,12 @@ def _terminate_cron_script_process(proc: subprocess.Popen) -> None:
try:
subprocess.run(
["taskkill", "/PID", str(proc.pid), "/T", "/F"],
capture_output=True,
timeout=10,
creationflags=_sched.windows_hide_flags(),
check=False,
capture_output=True, timeout=10, creationflags=_sched.windows_hide_flags(), check=False,
)
except (OSError, subprocess.TimeoutExpired):
proc.kill()
else:
try:
process_group: Optional[int] = os.getpgid(proc.pid)
except (ProcessLookupError, OSError):
process_group = None
if process_group is not None:
try:
os.killpg(process_group, signal.SIGTERM) # windows-footgun: ok — POSIX-only branch (win32 handled above)
except (ProcessLookupError, PermissionError, OSError):
process_group = None
if process_group is not None:
with contextlib.suppress(subprocess.TimeoutExpired):
proc.wait(timeout=1.0)
# Escalate if ANY group member survived TERM: a survivor holds the pipe write ends
# open and the caller's communicate() would block on EOF forever.
try:
os.killpg(process_group, 0) # windows-footgun: ok — POSIX-only branch
except (ProcessLookupError, OSError):
process_group = None
if process_group is not None:
with contextlib.suppress((ProcessLookupError, PermissionError, OSError)):
os.killpg(process_group, getattr(signal, "SIGKILL", signal.SIGTERM))
_terminate_process_group(proc)
try:
proc.wait(timeout=1.0)
except subprocess.TimeoutExpired:
@@ -214,6 +165,24 @@ def _terminate_cron_script_process(proc: subprocess.Popen) -> None:
proc.wait(timeout=1.0)
def _terminate_process_group(proc: subprocess.Popen) -> None:
"""POSIX: TERM the script's process group, then KILL if ANY member survived (a survivor holds
the pipe write ends open and the caller's communicate() would block on EOF forever)."""
try:
process_group = os.getpgid(proc.pid)
os.killpg(process_group, signal.SIGTERM) # windows-footgun: ok — POSIX-only branch (win32 handled by caller)
except (ProcessLookupError, PermissionError, OSError):
return
with contextlib.suppress(subprocess.TimeoutExpired):
proc.wait(timeout=1.0)
try:
os.killpg(process_group, 0) # windows-footgun: ok — POSIX-only branch
except (ProcessLookupError, OSError):
return
with contextlib.suppress((ProcessLookupError, PermissionError, OSError)):
os.killpg(process_group, getattr(signal, "SIGKILL", signal.SIGTERM))
def _terminate_cron_script_tree(proc: subprocess.Popen) -> None:
"""Terminate a script tree, then fall back to the local process-group path."""
if proc.poll() is not None:
@@ -222,8 +191,7 @@ def _terminate_cron_script_tree(proc: subprocess.Popen) -> None:
pid = getattr(proc, "pid", None)
if not isinstance(pid, int) or pid <= 0:
logger.warning(
"Cron script tree-kill received invalid pid %r; "
"falling back to process-group termination",
"Cron script tree-kill received invalid pid %r; falling back to process-group termination",
pid,
)
_sched._terminate_cron_script_process(proc)
@@ -234,8 +202,7 @@ def _terminate_cron_script_tree(proc: subprocess.Popen) -> None:
from agent.deadline import kill_process_tree
except Exception:
logger.warning(
"agent.deadline.kill_process_tree unavailable; "
"falling back to process-group termination",
"agent.deadline.kill_process_tree unavailable; falling back to process-group termination",
exc_info=True,
)
_sched._terminate_cron_script_process(proc)
@@ -244,16 +211,13 @@ def _terminate_cron_script_tree(proc: subprocess.Popen) -> None:
if kill_process_tree(pid):
return
logger.warning(
"Cron script tree-kill reported no signal for pid %s; "
"falling back to process-group termination",
"Cron script tree-kill reported no signal for pid %s; falling back to process-group termination",
pid,
)
except Exception:
logger.warning(
"Cron script tree-kill failed for pid %s; "
"falling back to process-group termination",
pid,
exc_info=True,
"Cron script tree-kill failed for pid %s; falling back to process-group termination",
pid, exc_info=True,
)
_sched._terminate_cron_script_process(proc)
@@ -274,18 +238,12 @@ def _drain_script_pipes(proc: subprocess.Popen) -> None:
proc.wait(timeout=5.0)
def _windows_cron_bootstrap_argv(
python_exe: str,
env_overlay: dict[str, str],
script_path: str,
) -> list[str]:
def _windows_cron_bootstrap_argv(python_exe: str, env_overlay: dict[str, str], script_path: str) -> list[str]:
"""Bootstrap a cron script under the base interpreter with ``.pth`` support.
Overlay mode runs base ``python.exe`` (avoids the launcher flashing a console window) with the
venv on ``PYTHONPATH`` — but ``.pth`` files are only processed by ``site.addsitedir()``, so
editable installs would be invisible. Bootstrap via addsitedir + ``runpy.run_path`` (keeps
``__file__`` and ``sys.path[0]`` semantics); plain invocation if the venv is unresolvable.
"""
``__file__`` and ``sys.path[0]`` semantics); plain invocation if the venv is unresolvable."""
site_packages = _sched.Path(env_overlay.get("VIRTUAL_ENV", "")) / "Lib" / "site-packages"
if not site_packages.is_dir():
# Warn: silent fallback would make "editable installs invisible" undiagnosable.
@@ -306,74 +264,76 @@ def _windows_cron_bootstrap_argv(
return [python_exe, "-c", bootstrap, script_path]
def _run_job_script(
script_path: str,
workdir: Optional[str] = None,
cancel_event: Optional[_CancelEventLike] = None,
) -> tuple[bool, str]:
"""Execute a cron job's script and return ``(success, output)``; on failure *output* is the
error message for the LLM to report.
Scripts MUST resolve inside HERMES_HOME/scripts/ (relative, absolute and ``~`` paths are all
validated — path traversal / absolute-path injection). Interpreter by extension:
``.sh``/``.bash`` → bash, else ``sys.executable``. Env goes through ``build_subprocess_env``
(SECURITY.md §2.3).
``workdir`` sets the subprocess cwd only; the Python process cwd is NEVER mutated (an
``os.chdir()`` would leak into concurrent gateway sessions).
"""
def _resolve_script_path(script_path: str) -> tuple[Optional[Path], Optional[str]]:
"""Validate a job script path; ``(path, None)`` or ``(None, error)``. Scripts MUST resolve inside
HERMES_HOME/scripts/ (relative, absolute and ``~`` paths are all validated — path traversal /
absolute-path injection). Same contract as cron.lifecycle_guard._expand_candidate_path."""
scripts_dir = _sched._get_hermes_home() / "scripts"
_ensure_cron_dir(scripts_dir)
scripts_dir_resolved = scripts_dir.resolve()
# Same contract as cron.lifecycle_guard._expand_candidate_path. Reject NUL eagerly: on Windows
# Path ops raise ValueError *after* expanduser so the try below would not catch it. str() first
# so the guard itself cannot raise on a non-str script_path.
# Reject NUL eagerly: on Windows Path ops raise ValueError *after* expanduser so the try below
# would not catch it. str() first so the guard itself cannot raise on a non-str script_path.
if "\x00" in str(script_path):
return False, f"Blocked: script path contains a NUL byte: {script_path!r}"
return None, f"Blocked: script path contains a NUL byte: {script_path!r}"
try:
raw = _sched.Path(script_path).expanduser()
except (ValueError, RuntimeError, OSError):
# RuntimeError: unexpandable ``~`` (no resolvable HOME).
return False, f"Blocked: script path is not a valid filesystem path: {script_path!r}"
return None, f"Blocked: script path is not a valid filesystem path: {script_path!r}"
path = raw.resolve() if raw.is_absolute() else (scripts_dir / raw).resolve()
# Traversal / absolute-path / symlink escape guard — MUST stay inside HERMES_HOME/scripts/.
try:
path.relative_to(scripts_dir_resolved)
except ValueError:
return False, (
return None, (
f"Blocked: script path resolves outside the scripts directory "
f"({scripts_dir_resolved}): {script_path!r}"
)
if not path.exists():
return False, f"Script not found: {path}"
return None, f"Script not found: {path}"
if not path.is_file():
return False, f"Script path is not a file: {path}"
return None, f"Script path is not a file: {path}"
return path, None
script_timeout = _sched._get_script_timeout()
# Interpreter by extension; the shebang is deliberately NOT honoured (small, auditable surface).
suffix = path.suffix.lower()
if suffix in {".sh", ".bash"}:
def _script_argv(path: Path) -> tuple[Optional[list[str]], dict[str, str], Optional[str]]:
"""``(argv, env_overlay, error)`` for a validated script. Interpreter by extension — the shebang
is deliberately NOT honoured (small, auditable surface): ``.sh``/``.bash`` → bash, else
``sys.executable`` (Windows uv-venv overlay gets the .pth bootstrap)."""
if path.suffix.lower() in {".sh", ".bash"}:
# which() finds Git Bash on Windows; None there → clear error instead of a "[WinError 2]".
_bash = shutil.which("bash") or ("/bin/bash" if os.path.isfile("/bin/bash") else None)
if _bash is None:
return False, (
return None, {}, (
f"Cannot run .sh/.bash script {path.name!r}: bash not found on PATH. "
"On Windows, install Git for Windows (which ships Git Bash) "
"or rewrite the script as Python (.py)."
)
argv = [_bash, str(path)]
env_overlay: dict[str, str] = {}
else:
python_exe, env_overlay = _sched._windows_cron_python_invocation(sys.executable)
if env_overlay:
# Windows uv-venv overlay: needs the .pth bootstrap for editable installs.
argv = _windows_cron_bootstrap_argv(python_exe, env_overlay, str(path))
else:
argv = [python_exe, str(path)]
)
return [_bash, str(path)], {}, None
python_exe, env_overlay = _sched._windows_cron_python_invocation(sys.executable)
if env_overlay:
return _windows_cron_bootstrap_argv(python_exe, env_overlay, str(path)), env_overlay, None
return [python_exe, str(path)], env_overlay, None
def _run_job_script(
script_path: str,
workdir: Optional[str] = None,
cancel_event: Optional[_CancelEventLike] = None,
) -> tuple[bool, str]:
"""Execute a cron job's script and return ``(success, output)``; on failure *output* is the
error message for the LLM to report. Env goes through ``build_subprocess_env`` (SECURITY.md
§2.3). ``workdir`` sets the subprocess cwd only; the Python process cwd is NEVER mutated (an
``os.chdir()`` would leak into concurrent gateway sessions)."""
path, err = _resolve_script_path(script_path)
if path is None:
return False, err
script_timeout = _sched._get_script_timeout()
argv, env_overlay, err = _script_argv(path)
if argv is None:
return False, err
try:
from tools.environments.local import build_subprocess_env
@@ -381,36 +341,27 @@ def _run_job_script(
popen_kwargs: dict[str, Any] = {"start_new_session": True}
if sys.platform == "win32":
popen_kwargs = {
"creationflags": _sched.windows_hide_flags()
| getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
"creationflags": _sched.windows_hide_flags() | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
"encoding": "utf-8",
"errors": "replace",
}
env = build_subprocess_env()
env.update(env_overlay)
# Subprocess cwd only (default: scripts-dir parent). NEVER os.chdir() the process.
_script_cwd = workdir or str(path.parent)
proc = subprocess.Popen(
argv,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=_script_cwd,
env=env,
**popen_kwargs,
argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
cwd=workdir or str(path.parent), env=env, **popen_kwargs,
)
deadline = time.monotonic() + script_timeout
while True:
# Tree-kill on cancel AND timeout: killpg misses setsid grandchildren (watchdogs,
# backgrounded shell jobs); kill_process_tree snapshots descendants BEFORE signalling.
if cancel_event is not None and cancel_event.is_set():
# Tree-kill here too: a cancelled fire must not orphan own-session grandchildren.
_sched._terminate_cron_script_tree(proc)
_drain_script_pipes(proc)
return False, "Script cancelled because cron fire ownership was lost"
remaining = deadline - time.monotonic()
if remaining <= 0:
# Timeout must leave ZERO descendants: killpg misses setsid grandchildren
# (watchdogs, backgrounded shell jobs); kill_process_tree snapshots descendants
# BEFORE signalling.
_sched._terminate_cron_script_tree(proc)
_drain_script_pipes(proc)
return False, f"Script timed out after {script_timeout}s: {path}"
@@ -430,8 +381,7 @@ def _run_job_script(
stderr = redact_sensitive_text(stderr)
except Exception as e:
logger.warning("Failed to redact sensitive text from output: %s", e)
stdout = "[REDACTED - redaction failed]"
stderr = "[REDACTED - redaction failed]"
stdout = stderr = "[REDACTED - redaction failed]"
if proc.returncode != 0:
parts = [f"Script exited with code {proc.returncode}"]
@@ -440,9 +390,7 @@ def _run_job_script(
if stdout:
parts.append(f"stdout:\n{stdout}")
return False, "\n".join(parts)
return True, stdout
except Exception as exc:
return False, f"Script execution failed: {exc}"
@@ -451,9 +399,7 @@ def _start_heartbeat_thread(loop_fn, name: str, fail_log) -> Optional[threading.
"""Start ``loop_fn`` on a daemon thread inside a copy of the current context (multiplexed
profile ContextVars). On failure calls ``fail_log()`` inside the except (traceback intact) and
returns None."""
thread = threading.Thread(
target=contextvars.copy_context().run, args=(loop_fn,), name=name, daemon=True,
)
thread = threading.Thread(target=contextvars.copy_context().run, args=(loop_fn,), name=name, daemon=True)
try:
thread.start()
except Exception:
@@ -478,11 +424,7 @@ def _run_job_script_with_claim_heartbeat(
schedule = job.get("schedule")
claim = job.get("run_claim")
owner = str(claim.get("by") or "") if isinstance(claim, dict) else ""
if not (
isinstance(schedule, dict)
and schedule.get("kind") == "once"
and owner
):
if not (isinstance(schedule, dict) and schedule.get("kind") == "once" and owner):
return _sched._run_job_script(script_path, workdir=workdir, cancel_event=cancel_event)
job_id = str(job.get("id") or "")
@@ -497,9 +439,7 @@ def _run_job_script_with_claim_heartbeat(
heartbeat_thread = _start_heartbeat_thread(
_heartbeat_loop, "cron-script-claim-heartbeat",
lambda: logger.debug(
"Job '%s': could not start script run_claim heartbeat", job_id, exc_info=True,
),
lambda: logger.debug("Job '%s': could not start script run_claim heartbeat", job_id, exc_info=True),
)
if heartbeat_thread is None:
return _sched._run_job_script(script_path, workdir=workdir, cancel_event=cancel_event)