Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions cron/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,7 @@ def create_job(
workdir: Optional[str] = None,
no_agent: bool = False,
attach_to_session: Optional[bool] = None,
thread_name_template: Optional[str] = None,
) -> Dict[str, Any]:
"""
Create a new cron job.
Expand Down Expand Up @@ -1092,6 +1093,10 @@ def create_job(
and deliver its stdout directly. Empty stdout = silent (no
delivery). Requires ``script`` to be set. Ideal for classic
watchdogs and periodic alerts that don't need LLM reasoning.
attach_to_session: When True, make the delivery continuable on
thread-capable platforms; omitted preserves the global default.
thread_name_template: Optional template for continuable thread names.
Supported fields are ``{date}``, ``{job_name}``, and ``{job_id}``.

Returns:
The created job dict
Expand Down Expand Up @@ -1124,6 +1129,10 @@ def create_job(
normalized_workdir = _normalize_workdir(workdir)
normalized_no_agent = bool(no_agent)
normalized_attach = attach_to_session if isinstance(attach_to_session, bool) else None
normalized_thread_name_template = (
str(thread_name_template).strip() if isinstance(thread_name_template, str) else None
)
normalized_thread_name_template = normalized_thread_name_template or None

# no_agent jobs are meaningless without a script — the script IS the job.
# Surface this as a clear ValueError at create time so bad configs never
Expand Down Expand Up @@ -1219,6 +1228,8 @@ def create_job(
# global cron.mirror_delivery config, default off).
if normalized_attach is not None:
job["attach_to_session"] = normalized_attach
if normalized_thread_name_template is not None:
job["thread_name_template"] = normalized_thread_name_template

with _jobs_lock():
jobs = load_jobs()
Expand Down
32 changes: 30 additions & 2 deletions cron/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,35 @@ def _maybe_mirror_cron_delivery(
)


def _continuable_cron_thread_name(job: dict) -> str:
"""Resolve the name for a newly-opened continuable cron thread.

Existing jobs keep the historical ``Hermes — <job name>`` default. Jobs
may opt into a small, deterministic template with ``{date}``,
``{job_name}``, and ``{job_id}``; ``{date}`` uses Hermes' configured
timezone rather than the host's implicit timezone.
"""
task_name = str(job.get("name") or job.get("id", "cron")).strip()
default_name = f"Hermes — {task_name}"
template = job.get("thread_name_template")
if not isinstance(template, str) or not template.strip():
return default_name

try:
rendered = template.format(
date=_hermes_now().strftime("%Y-%m-%d"),
job_name=task_name,
job_id=str(job.get("id", "cron")),
).strip()
except (KeyError, IndexError, ValueError) as exc:
logger.warning(
"Job '%s': invalid thread_name_template %r (%s); using default name",
job.get("id", "?"), template, exc,
)
return default_name
return rendered or default_name


def _open_continuable_cron_thread(
job: dict,
adapter,
Expand All @@ -733,8 +762,7 @@ def _open_continuable_cron_thread(
create_thread = getattr(adapter, "create_handoff_thread", None)
if not callable(create_thread) or loop is None:
return None
task_name = job.get("name") or job.get("id", "cron")
thread_name = f"Hermes — {task_name}"
thread_name = _continuable_cron_thread_name(job)
try:
from agent.async_utils import safe_schedule_threadsafe

Expand Down
17 changes: 16 additions & 1 deletion gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -11519,7 +11519,22 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str, run_g
if not history and source.platform and source.platform != Platform.LOCAL and source.platform != Platform.WEBHOOK:
platform_name = source.platform.value
env_key = _home_target_env_var(platform_name)
if not os.getenv(env_key):
home_configured = bool(os.getenv(env_key))
if not home_configured:
# The canonical home-channel setting is config.yaml. Keep the
# environment-variable check for legacy/operator overrides, but
# do not show onboarding when the loaded gateway config already
# contains a valid home channel for this platform.
try:
configured_home = self.config.get_home_channel(source.platform)
home_configured = bool(
configured_home and configured_home.chat_id
)
except Exception:
# Onboarding must remain best-effort if a test/dummy runner
# does not provide the full gateway config interface.
home_configured = False
if not home_configured:
# Slack dispatches all Hermes commands through a single
# parent slash command `/hermes`; bare `/sethome` is not
# registered and would fail with "app did not respond".
Expand Down
5 changes: 5 additions & 0 deletions hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2430,6 +2430,11 @@ def _ensure_hermes_home_managed(home: Path):
"auto_thread": True, # Auto-create threads on @mention in channels (like Slack)
"thread_require_mention": False, # If True, require @mention in threads too (multi-bot threads)
"bots_require_inline_mention": False, # Multi-bot rooms: if True, another bot must type @thisbot in its message to trigger a reply; a Discord reply/quote alone won't. Prevents two bots auto-replying to each other forever. Does not affect humans.
"allow_bots": "none", # none, mentions, or all; bot messages remain blocked by default
"trusted_bot_ids": [], # Optional explicit allowlist for cross-Profile bot IDs
"bot_relay_cooldown_seconds": 10, # Minimum delay between accepted messages from one bot in one channel
"bot_relay_window_seconds": 60, # Sliding window for the relay burst limiter
"bot_relay_max_messages": 3, # Maximum accepted messages per trusted bot/channel/window
"history_backfill": True, # If True, prepend recent channel scrollback when bot is triggered (recovers messages missed while require_mention gated them out)
"history_backfill_limit": 50, # Max number of recent messages to scan when assembling the backfill block
"reactions": True, # Add 👀/✅/❌ reactions to messages during processing
Expand Down
4 changes: 3 additions & 1 deletion hermes_cli/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ class HermesOverlay:
base_url_override="https://chatgpt.com/backend-api/codex",
),
"openai-api": HermesOverlay(
transport="codex_responses",
# GPT-4o and other Chat Completions models do not support the
# Responses-only `reasoning.encrypted_content` include parameter.
transport="openai_chat",
base_url_override="https://api.openai.com/v1",
base_url_env_var="OPENAI_BASE_URL",
),
Expand Down
32 changes: 23 additions & 9 deletions hermes_cli/runtime_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,9 +504,12 @@ def _resolve_runtime_from_pool_entry(
# Auto-detect Anthropic-compatible endpoints (/anthropic suffix,
# Kimi /coding, api.openai.com → codex_responses, api.x.ai →
# codex_responses).
detected = _detect_api_mode_for_url(base_url)
if detected:
api_mode = detected
# Direct ``openai-api`` API-key traffic is intentionally excluded:
# GPT-4o uses Chat Completions and rejects Responses-only fields.
if provider != "openai-api":
detected = _detect_api_mode_for_url(base_url)
if detected:
api_mode = detected

# OpenCode base URLs end with /v1 for OpenAI-compatible models, but the
# Anthropic SDK prepends its own /v1/messages to the base_url. Normalize
Expand Down Expand Up @@ -1496,9 +1499,16 @@ def _resolve_explicit_runtime(
else:
# Auto-detect from URL (Anthropic /anthropic suffix,
# api.openai.com → Responses, Kimi /coding, etc.).
detected = _detect_api_mode_for_url(base_url)
if detected:
api_mode = detected
# Direct ``openai-api`` traffic uses an API key and must not
# inherit the generic api.openai.com Responses default for
# GPT-4o: Responses-only fields such as
# ``include=["reasoning.encrypted_content"]`` are rejected
# with HTTP 400. Use ``openai-codex`` or an explicit
# ``model.api_mode`` when the Responses transport is wanted.
if provider != "openai-api":
detected = _detect_api_mode_for_url(base_url)
if detected:
api_mode = detected

return {
"provider": provider,
Expand Down Expand Up @@ -2057,9 +2067,13 @@ def resolve_runtime_provider(
# Auto-detect Anthropic-compatible endpoints by URL convention
# (e.g. https://api.minimax.io/anthropic, https://dashscope.../anthropic)
# plus api.openai.com → codex_responses and api.x.ai → codex_responses.
detected = _detect_api_mode_for_url(base_url)
if detected:
api_mode = detected
# Direct ``openai-api`` is intentionally excluded: GPT-4o on the
# API-key endpoint uses Chat Completions and rejects Responses-only
# fields such as ``reasoning.encrypted_content``.
if provider != "openai-api":
detected = _detect_api_mode_for_url(base_url)
if detected:
api_mode = detected
# Normalize the /v1 suffix for OpenCode by API mode (see comment above).
if provider in {"opencode-zen", "opencode-go"}:
from hermes_cli.models import normalize_opencode_base_url
Expand Down
73 changes: 71 additions & 2 deletions plugins/platforms/discord/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import tempfile
import threading
import time
from collections import defaultdict
from collections import defaultdict, deque
from contextlib import suppress
from typing import Callable, Dict, List, Optional, Any, Tuple

Expand Down Expand Up @@ -882,6 +882,19 @@ def __init__(self, config: PlatformConfig):
# Dedup cache: prevents duplicate bot responses when Discord
# RESUME replays events after reconnects.
self._dedup = MessageDeduplicator()
# Cross-bot relay circuit breaker. Even trusted bots must use an
# inline mention, and bursts are bounded so two Profiles cannot
# ping-pong forever.
self._bot_relay_events: Dict[tuple[str, str], deque[float]] = {}
self._bot_relay_cooldown = max(
0.0, env_float("HERMES_DISCORD_BOT_RELAY_COOLDOWN_SECONDS", 10.0)
)
self._bot_relay_window = max(
1.0, env_float("HERMES_DISCORD_BOT_RELAY_WINDOW_SECONDS", 60.0)
)
self._bot_relay_max = max(
1, env_int("HERMES_DISCORD_BOT_RELAY_MAX_MESSAGES", 3)
)
# Reply threading mode: "off" (no replies), "first" (reply on first
# chunk only, default), "all" (reply-reference on every chunk).
self._reply_to_mode: str = getattr(config, 'reply_to_mode', 'first') or 'first'
Expand Down Expand Up @@ -1131,14 +1144,21 @@ async def on_message(message: DiscordMessage):
allow_bots = os.getenv("DISCORD_ALLOW_BOTS", "none").lower().strip()
if allow_bots == "none":
return
elif allow_bots == "mentions":
trusted_bot_ids = self._discord_trusted_bot_ids()
if trusted_bot_ids and str(message.author.id) not in trusted_bot_ids:
return
if allow_bots == "mentions":
if not self._self_is_explicitly_mentioned(message):
return
if (
self._discord_bots_require_inline_mention()
and not self._self_is_raw_mentioned(message)
):
return
if not self._accept_bot_relay(
str(message.author.id), str(message.channel.id)
):
return
# "all" falls through; bot is permitted — skip the
# human-user allowlist below (bots aren't in it).
else:
Expand Down Expand Up @@ -4900,6 +4920,41 @@ def _discord_bots_require_inline_mention(self) -> bool:
"on",
}

def _discord_trusted_bot_ids(self) -> set[str]:
"""Return the explicit allowlist for cross-Profile bot messages."""
raw = os.getenv("DISCORD_TRUSTED_BOT_IDS", "").strip()
if not raw:
return set()
try:
parsed = json.loads(raw)
except (TypeError, ValueError):
parsed = raw.split(",")
if isinstance(parsed, str):
parsed = parsed.split(",")
elif not isinstance(parsed, (list, tuple, set)):
parsed = [parsed]
return {
str(item).strip().strip("'\"")
for item in parsed
if item is not None and str(item).strip()
}

def _accept_bot_relay(self, author_id: str, channel_id: str) -> bool:
"""Apply cooldown and burst limits to accepted bot-authored messages."""
now = time.monotonic()
key = (str(author_id), str(channel_id))
events = self._bot_relay_events.setdefault(key, deque())
while events and now - events[0] > self._bot_relay_window:
events.popleft()
if events and now - events[-1] < self._bot_relay_cooldown:
logger.info("[%s] Dropping bot relay during cooldown from %s", self.name, author_id)
return False
if len(events) >= self._bot_relay_max:
logger.info("[%s] Dropping bot relay after burst limit from %s", self.name, author_id)
return False
events.append(now)
return True

def _discord_channel_keys(self, message: Any, parent_channel_id: Optional[str] = None) -> set[str]:
"""Return channel identifiers accepted by Discord channel config gates.

Expand Down Expand Up @@ -8258,6 +8313,20 @@ def _apply_yaml_config(yaml_cfg: dict, discord_cfg: dict) -> dict | None:
os.environ["DISCORD_THREAD_REQUIRE_MENTION"] = str(discord_cfg["thread_require_mention"]).lower()
if "bots_require_inline_mention" in discord_cfg and not os.getenv("DISCORD_BOTS_REQUIRE_INLINE_MENTION"):
os.environ["DISCORD_BOTS_REQUIRE_INLINE_MENTION"] = str(discord_cfg["bots_require_inline_mention"]).lower()
if "allow_bots" in discord_cfg and not os.getenv("DISCORD_ALLOW_BOTS"):
os.environ["DISCORD_ALLOW_BOTS"] = str(discord_cfg["allow_bots"]).lower()
trusted_bot_ids = discord_cfg.get("trusted_bot_ids")
if trusted_bot_ids is not None and not os.getenv("DISCORD_TRUSTED_BOT_IDS"):
if isinstance(trusted_bot_ids, list):
trusted_bot_ids = ",".join(str(v) for v in trusted_bot_ids)
os.environ["DISCORD_TRUSTED_BOT_IDS"] = str(trusted_bot_ids)
for yaml_key, env_key in (
("bot_relay_cooldown_seconds", "HERMES_DISCORD_BOT_RELAY_COOLDOWN_SECONDS"),
("bot_relay_window_seconds", "HERMES_DISCORD_BOT_RELAY_WINDOW_SECONDS"),
("bot_relay_max_messages", "HERMES_DISCORD_BOT_RELAY_MAX_MESSAGES"),
):
if yaml_key in discord_cfg and not os.getenv(env_key):
os.environ[env_key] = str(discord_cfg[yaml_key])
platforms_cfg = yaml_cfg.get("platforms")
platform_extra_cfg = {}
if isinstance(platforms_cfg, dict):
Expand Down
9 changes: 9 additions & 0 deletions tests/cron/test_cronjob_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,12 @@ def test_cronjob_schema_required_array_unchanged():
from tools.cronjob_tools import CRONJOB_SCHEMA

assert CRONJOB_SCHEMA["parameters"]["required"] == ["action"]


def test_cronjob_schema_exposes_thread_name_template():
"""Continuable jobs can configure a date-based thread name."""
from tools.cronjob_tools import CRONJOB_SCHEMA

prop = CRONJOB_SCHEMA["parameters"]["properties"]["thread_name_template"]
assert prop["type"] == "string"
assert "{date}" in prop["description"]
58 changes: 58 additions & 0 deletions tests/cron/test_scheduler.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Tests for cron/scheduler.py — origin resolution, delivery routing, and error logging."""

import contextlib
import asyncio
import itertools
import json
import logging
import os
from datetime import datetime, timezone
from unittest.mock import AsyncMock, patch, MagicMock

import pytest
Expand Down Expand Up @@ -4331,6 +4333,26 @@ def test_target_matches_origin_exact(self):
# Case-insensitive platform match.
assert _target_matches_origin(origin, "Telegram", "123", None) is True

def test_discord_parent_channel_origin_allows_new_thread_lane(self):
"""A parent-channel origin is the correct scope for a new cron thread."""
from cron.scheduler import _target_matches_origin

origin = {"platform": "discord", "chat_id": "1525133234139041842"}
assert _target_matches_origin(origin, "discord", "1525133234139041842", None) is True

def test_old_thread_origin_does_not_match_parent_channel_delivery(self):
"""A stale thread origin must not silently mirror a parent-channel target."""
from cron.scheduler import _target_matches_origin

origin = {
"platform": "discord",
"chat_id": "1526758663577010208",
"thread_id": "1526758663577010208",
}
assert _target_matches_origin(
origin, "discord", "1525133234139041842", None,
) is False

def test_target_matches_origin_rejects_other_chat(self):
from cron.scheduler import _target_matches_origin

Expand Down Expand Up @@ -4472,6 +4494,42 @@ def _run_now(coro, _loop):
)
assert tid == "9001"

def test_open_thread_applies_date_name_template(self):
"""A configured template uses Hermes time and reaches the adapter."""
from cron.scheduler import _open_continuable_cron_thread

adapter = MagicMock()
adapter.create_handoff_thread = AsyncMock(return_value="9002")

def _run_now(coro, _loop):
fut = MagicMock()
fut.result.return_value = asyncio.run(coro)
return fut

job = {
"id": "j2",
"name": "AI digest",
"thread_name_template": "{date}AI摘要",
}
frozen = datetime(2026, 7, 16, 11, 30, tzinfo=timezone.utc)
with patch("cron.scheduler._hermes_now", return_value=frozen), \
patch("agent.async_utils.safe_schedule_threadsafe", side_effect=_run_now):
tid = _open_continuable_cron_thread(
job, adapter, "123", loop=MagicMock(),
)

assert tid == "9002"
adapter.create_handoff_thread.assert_awaited_once_with("123", "2026-07-16AI摘要")

def test_invalid_thread_name_template_falls_back_to_default(self):
from cron.scheduler import _continuable_cron_thread_name

assert _continuable_cron_thread_name({
"id": "j3",
"name": "AI digest",
"thread_name_template": "{missing}",
}) == "Hermes — AI digest"

def test_open_thread_returns_none_on_dm_platform(self):
"""A DM-only adapter (WhatsApp) inherits the base create_handoff_thread
that returns None → _open_continuable_cron_thread returns None so the
Expand Down
Loading