Compare commits

..

1 Commits

Author SHA1 Message Date
Alexander Whitestone
e6c346c6bb feat: time-aware model routing for cron jobs (#317)
Some checks failed
Forge CI / smoke-and-build (pull_request) Failing after 1m5s
Route cron jobs to different models based on time of day.

- Peak hours (user active): cheaper model, user catches errors
- Off-peak hours (user absent): stronger model, errors go uncorrected

Config under smart_model_routing.cron_time_routing:
  enabled, timezone, peak_hours (start/end), peak_model, offpeak_model

Integrates into cron/scheduler.py via resolve_cron_turn_route(), which
checks time-aware routing first, then falls back to normal smart routing.

12 tests added (test_cron_time_routing.py). All 18 routing tests pass.

Closes #317
2026-04-13 17:30:07 -04:00
9 changed files with 357 additions and 474 deletions

View File

@@ -4,6 +4,7 @@ from __future__ import annotations
import os
import re
from datetime import datetime
from typing import Any, Dict, Optional
from utils import is_truthy_value
@@ -182,7 +183,7 @@ def resolve_turn_route(user_message: str, routing_config: Optional[Dict[str, Any
"command": runtime.get("command"),
"args": list(runtime.get("args") or []),
},
"label": f"smart route {route.get('model')} ({runtime.get('provider')})",
"label": f"smart route \u2192 {route.get('model')} ({runtime.get('provider')})",
"signature": (
route.get("model"),
runtime.get("provider"),
@@ -192,3 +193,151 @@ def resolve_turn_route(user_message: str, routing_config: Optional[Dict[str, Any
tuple(runtime.get("args") or ()),
),
}
# ---------------------------------------------------------------------------
# Time-aware cron model routing
# ---------------------------------------------------------------------------
# During peak hours (user active), cron jobs use a cheaper model because the
# user is present to catch and correct errors. During off-peak hours (user
# absent), cron jobs use a stronger model because errors go uncorrected.
#
# Config (under smart_model_routing.cron_time_routing):
# enabled: true
# timezone: "America/New_York" # IANA timezone name (default: UTC)
# peak_hours:
# start: 9 # inclusive, 0-23
# end: 18 # exclusive, 0-23
# peak_model: # model to use during peak hours
# provider: openrouter
# model: xiaomi/mimo-v2-pro
# offpeak_model: # model to use during off-peak hours
# provider: openrouter
# model: anthropic/claude-sonnet-4
def _get_current_hour_in_tz(tz_name: str) -> int:
"""Return the current hour (0-23) in the given IANA timezone."""
try:
from zoneinfo import ZoneInfo
tz = ZoneInfo(tz_name)
except Exception:
try:
import pytz
tz = pytz.timezone(tz_name)
except Exception:
return datetime.utcnow().hour
return datetime.now(tz).hour
def _is_peak_hour(hour: int, peak_start: int, peak_end: int) -> bool:
"""Return True if *hour* falls within [peak_start, peak_end).
Handles wrap-around (e.g. start=22, end=6 means 22:00-05:59 is peak).
"""
if peak_start <= peak_end:
return peak_start <= hour < peak_end
else:
# Wraps midnight: e.g. 22-6 means 22,23,0,1,2,3,4,5
return hour >= peak_start or hour < peak_end
def resolve_cron_time_route(
routing_config: Optional[Dict[str, Any]],
) -> Optional[Dict[str, Any]]:
"""Return a time-aware model override for cron jobs.
Considers the current hour in the configured timezone and picks
between a peak-hours model (cheaper, user present) and an off-peak
model (stronger, user absent, errors go uncorrected).
Returns None when time-aware routing is disabled or misconfigured,
so the caller falls through to normal routing.
"""
cfg = routing_config or {}
cron_cfg = cfg.get("cron_time_routing") or {}
if not _coerce_bool(cron_cfg.get("enabled"), False):
return None
tz_name = str(cron_cfg.get("timezone", "UTC")).strip()
peak = cron_cfg.get("peak_hours") or {}
peak_start = _coerce_int(peak.get("start"), 9)
peak_end = _coerce_int(peak.get("end"), 18)
current_hour = _get_current_hour_in_tz(tz_name)
is_peak = _is_peak_hour(current_hour, peak_start, peak_end)
if is_peak:
model_cfg = cron_cfg.get("peak_model") or {}
reason = "cron_peak_hours"
else:
model_cfg = cron_cfg.get("offpeak_model") or {}
reason = "cron_offpeak_hours"
provider = str(model_cfg.get("provider") or "").strip().lower()
model = str(model_cfg.get("model") or "").strip()
if not provider or not model:
return None
return {
"provider": provider,
"model": model,
"base_url": model_cfg.get("base_url", ""),
"api_key_env": model_cfg.get("api_key_env", ""),
"routing_reason": reason,
"is_peak_hour": is_peak,
"hour": current_hour,
}
def resolve_cron_turn_route(
user_message: str,
routing_config: Optional[Dict[str, Any]],
primary: Dict[str, Any],
) -> Dict[str, Any]:
"""Resolve model route for a cron job turn with time-awareness.
Checks time-aware routing first (cron_time_routing), then falls
back to normal smart routing, then falls back to primary.
"""
# 1. Time-aware cron routing (peak vs off-peak)
time_route = resolve_cron_time_route(routing_config)
if time_route:
from hermes_cli.runtime_provider import resolve_runtime_provider
explicit_api_key = None
api_key_env = str(time_route.get("api_key_env") or "").strip()
if api_key_env:
explicit_api_key = os.getenv(api_key_env) or None
try:
runtime = resolve_runtime_provider(
requested=time_route.get("provider"),
explicit_api_key=explicit_api_key,
explicit_base_url=time_route.get("base_url"),
)
peak_label = "peak" if time_route.get("is_peak_hour") else "off-peak"
return {
"model": time_route.get("model"),
"runtime": {
"api_key": runtime.get("api_key"),
"base_url": runtime.get("base_url"),
"provider": runtime.get("provider"),
"api_mode": runtime.get("api_mode"),
"command": runtime.get("command"),
"args": list(runtime.get("args") or []),
},
"label": f"cron {peak_label} -> {time_route.get('model')} ({runtime.get('provider')})",
"signature": (
time_route.get("model"),
runtime.get("provider"),
runtime.get("base_url"),
runtime.get("api_mode"),
runtime.get("command"),
tuple(runtime.get("args") or ()),
),
}
except Exception:
pass # Fall through to normal routing
# 2. Normal smart routing (simple-turn cheap model)
return resolve_turn_route(user_message, routing_config, primary)

View File

@@ -87,6 +87,21 @@ model:
# cheap_model:
# provider: openrouter
# model: google/gemini-2.5-flash
# # Time-aware cron routing: pick model based on hour of day.
# # Peak hours = user present, cheaper model OK (they catch errors).
# # Off-peak = user absent, stronger model (errors go uncorrected).
# cron_time_routing:
# enabled: true
# timezone: "America/New_York" # IANA timezone (default: UTC)
# peak_hours:
# start: 9 # inclusive, 0-23
# end: 18 # exclusive, 0-23
# peak_model: # model during peak hours (user active)
# provider: openrouter
# model: xiaomi/mimo-v2-pro
# offpeak_model: # model during off-peak (user absent)
# provider: openrouter
# model: anthropic/claude-sonnet-4
# =============================================================================
# Git Worktree Isolation

View File

@@ -762,8 +762,8 @@ def run_job(job: dict) -> tuple[bool, str, str, Optional[str]]:
message = format_runtime_provider_error(exc)
raise RuntimeError(message) from exc
from agent.smart_model_routing import resolve_turn_route
turn_route = resolve_turn_route(
from agent.smart_model_routing import resolve_cron_turn_route
turn_route = resolve_cron_turn_route(
prompt,
smart_routing,
{
@@ -776,6 +776,8 @@ def run_job(job: dict) -> tuple[bool, str, str, Optional[str]]:
"args": list(runtime.get("args") or []),
},
)
if turn_route.get("label"):
logger.info("Job '%s': %s", job_name, turn_route["label"])
_agent_kwargs = _safe_agent_kwargs({
"model": turn_route["model"],

View File

@@ -107,7 +107,6 @@ class SessionResetPolicy:
mode: str = "both" # "daily", "idle", "both", or "none"
at_hour: int = 4 # Hour for daily reset (0-23, local time)
idle_minutes: int = 1440 # Minutes of inactivity before reset (24 hours)
max_messages: int = 200 # Max messages per session before forced checkpoint+restart (0 = unlimited)
notify: bool = True # Send a notification to the user when auto-reset occurs
notify_exclude_platforms: tuple = ("api_server", "webhook") # Platforms that don't get reset notifications
@@ -116,7 +115,6 @@ class SessionResetPolicy:
"mode": self.mode,
"at_hour": self.at_hour,
"idle_minutes": self.idle_minutes,
"max_messages": self.max_messages,
"notify": self.notify,
"notify_exclude_platforms": list(self.notify_exclude_platforms),
}
@@ -127,14 +125,12 @@ class SessionResetPolicy:
mode = data.get("mode")
at_hour = data.get("at_hour")
idle_minutes = data.get("idle_minutes")
max_messages = data.get("max_messages")
notify = data.get("notify")
exclude = data.get("notify_exclude_platforms")
return cls(
mode=mode if mode is not None else "both",
at_hour=at_hour if at_hour is not None else 4,
idle_minutes=idle_minutes if idle_minutes is not None else 1440,
max_messages=max_messages if max_messages is not None else 200,
notify=notify if notify is not None else True,
notify_exclude_platforms=tuple(exclude) if exclude is not None else ("api_server", "webhook"),
)

View File

@@ -2343,13 +2343,6 @@ class GatewayRunner:
reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'idle'
if reset_reason == "daily":
context_note = "[System note: The user's session was automatically reset by the daily schedule. This is a fresh conversation with no prior context.]"
elif reset_reason == "message_limit":
context_note = (
"[System note: The user's previous session reached the message limit "
"and was automatically checkpointed and rotated. This is a fresh session. "
"The prior conversation context was preserved via checkpoint. "
"If the user references something from before, you can search session history.]"
)
else:
context_note = "[System note: The user's previous session expired due to inactivity. This is a fresh conversation with no prior context.]"
context_prompt = context_note + "\n\n" + context_prompt
@@ -2375,18 +2368,16 @@ class GatewayRunner:
if adapter:
if reset_reason == "daily":
reason_text = f"daily schedule at {policy.at_hour}:00"
elif reset_reason == "message_limit":
reason_text = f"reached {policy.max_messages} message limit"
else:
hours = policy.idle_minutes // 60
mins = policy.idle_minutes % 60
duration = f"{hours}h" if not mins else f"{hours}h {mins}m" if hours else f"{mins}m"
reason_text = f"inactive for {duration}"
notice = (
f"◐ Session automatically rotated ({reason_text}). "
f"Conversation was checkpointed before rotation.\n"
f"◐ Session automatically reset ({reason_text}). "
f"Conversation history cleared.\n"
f"Use /resume to browse and restore a previous session.\n"
f"Adjust limits in config.yaml under session_reset."
f"Adjust reset timing in config.yaml under session_reset."
)
try:
session_info = self._format_session_info()
@@ -3082,51 +3073,6 @@ class GatewayRunner:
last_prompt_tokens=agent_result.get("last_prompt_tokens", 0),
)
# Marathon session limit (#326): check if we hit the message cap
# after this turn. If so, auto-checkpoint and rotate the session.
try:
_post_limit = self.session_store.get_message_limit_info(session_key)
if _post_limit["at_limit"] and _post_limit["max_messages"] > 0:
logger.info(
"[Marathon] Session %s hit message limit (%d/%d). "
"Auto-checkpointing and rotating.",
session_key, _post_limit["message_count"], _post_limit["max_messages"],
)
# Attempt filesystem checkpoint before rotation
try:
from tools.checkpoint_manager import CheckpointManager
_cp_cfg_path = _hermes_home / "config.yaml"
if _cp_cfg_path.exists():
import yaml as _cp_yaml
with open(_cp_cfg_path, encoding="utf-8") as _cpf:
_cp_data = _cp_yaml.safe_load(_cpf) or {}
_cp_settings = _cp_data.get("checkpoints", {})
if _cp_settings.get("enabled"):
_cwd = _cp_settings.get("working_dir") or os.getcwd()
mgr = CheckpointManager(
max_checkpoints=_cp_settings.get("max_checkpoints", 20),
)
cp = mgr.create_checkpoint(
str(_cwd),
label=f"marathon-limit-{session_entry.session_id[:8]}",
)
if cp:
logger.info("[Marathon] Checkpoint created: %s", cp.label)
except Exception as cp_err:
logger.debug("[Marathon] Checkpoint creation failed (non-fatal): %s", cp_err)
# Rotate session: reset creates a new session ID
new_entry = self.session_store.reset_session(session_key)
if new_entry:
logger.info(
"[Marathon] Session rotated: %s -> %s",
session_entry.session_id, new_entry.session_id,
)
# Reset message count for the new session
self.session_store.reset_message_count(session_key)
except Exception as rot_err:
logger.debug("[Marathon] Post-turn rotation check failed (non-fatal): %s", rot_err)
# Auto voice reply: send TTS audio before the text response
_already_sent = bool(agent_result.get("already_sent"))
if self._should_send_voice_reply(event, response, agent_messages, already_sent=_already_sent):
@@ -6592,29 +6538,6 @@ class GatewayRunner:
if self._ephemeral_system_prompt:
combined_ephemeral = (combined_ephemeral + "\n\n" + self._ephemeral_system_prompt).strip()
# Marathon session limit warning (#326): inject near-limit warning
# into ephemeral prompt so the agent knows to wrap up.
try:
_limit_info = self.session_store.get_message_limit_info(session_key)
if _limit_info["near_limit"] and not _limit_info["at_limit"]:
_remaining = _limit_info["remaining"]
_limit_warn = (
f"[SESSION LIMIT: This session has {_limit_info['message_count']} messages. "
f"Only {_remaining} message(s) remain before automatic session rotation at "
f"{_limit_info['max_messages']} messages. Start wrapping up your work and "
f"provide a summary. Save any important state before the session rotates.]"
)
combined_ephemeral = (combined_ephemeral + "\n\n" + _limit_warn).strip()
elif _limit_info["at_limit"]:
_limit_warn = (
f"[SESSION LIMIT REACHED: This session has hit the {_limit_info['max_messages']} "
f"message limit. This is your FINAL response. Summarize what was accomplished "
f"and provide any critical next steps. The session will rotate after this turn.]"
)
combined_ephemeral = (combined_ephemeral + "\n\n" + _limit_warn).strip()
except Exception:
pass # Non-fatal: limit warning is advisory only
# Re-read .env and config for fresh credentials (gateway is long-lived,
# keys may change without restart).
try:

View File

@@ -383,11 +383,6 @@ class SessionEntry:
# survives gateway restarts (the old in-memory _pre_flushed_sessions
# set was lost on restart, causing redundant re-flushes).
memory_flushed: bool = False
# Marathon session limit tracking (#326).
# Counts total messages (user + assistant + tool) in this session.
# Used to trigger checkpoint+restart at max_messages threshold.
message_count: int = 0
def to_dict(self) -> Dict[str, Any]:
result = {
@@ -407,7 +402,6 @@ class SessionEntry:
"estimated_cost_usd": self.estimated_cost_usd,
"cost_status": self.cost_status,
"memory_flushed": self.memory_flushed,
"message_count": self.message_count,
}
if self.origin:
result["origin"] = self.origin.to_dict()
@@ -444,7 +438,6 @@ class SessionEntry:
estimated_cost_usd=data.get("estimated_cost_usd", 0.0),
cost_status=data.get("cost_status", "unknown"),
memory_flushed=data.get("memory_flushed", False),
message_count=data.get("message_count", 0),
)
@@ -633,10 +626,10 @@ class SessionStore:
def _should_reset(self, entry: SessionEntry, source: SessionSource) -> Optional[str]:
"""
Check if a session should be reset based on policy.
Returns the reset reason ("idle", "daily", or "message_limit") if a reset
is needed, or None if the session is still valid.
Returns the reset reason ("idle" or "daily") if a reset is needed,
or None if the session is still valid.
Sessions with active background processes are never reset.
"""
if self._has_active_processes_fn:
@@ -648,37 +641,30 @@ class SessionStore:
platform=source.platform,
session_type=source.chat_type
)
if policy.mode == "none":
# Even with mode=none, enforce message_limit if set
if policy.max_messages > 0 and entry.message_count >= policy.max_messages:
return "message_limit"
return None
now = _now()
if policy.mode in ("idle", "both"):
idle_deadline = entry.updated_at + timedelta(minutes=policy.idle_minutes)
if now > idle_deadline:
return "idle"
if policy.mode in ("daily", "both"):
today_reset = now.replace(
hour=policy.at_hour,
minute=0,
second=0,
hour=policy.at_hour,
minute=0,
second=0,
microsecond=0
)
if now.hour < policy.at_hour:
today_reset -= timedelta(days=1)
if entry.updated_at < today_reset:
return "daily"
# Marathon session limit (#326): force checkpoint+restart at max_messages
if policy.max_messages > 0 and entry.message_count >= policy.max_messages:
return "message_limit"
return None
def has_any_sessions(self) -> bool:
@@ -836,70 +822,6 @@ class SessionStore:
entry.last_prompt_tokens = last_prompt_tokens
self._save()
def get_message_count(self, session_key: str) -> int:
"""Get the current message count for a session.
Returns the locally-tracked count from SessionEntry. Falls back to
DB query if the entry is not in memory.
"""
with self._lock:
self._ensure_loaded_locked()
entry = self._entries.get(session_key)
if entry:
return entry.message_count
# Fallback: query DB directly
if self._db:
try:
return self._db.message_count(entry.session_id) if entry else 0
except Exception:
pass
return 0
def get_message_limit_info(self, session_key: str) -> Dict[str, Any]:
"""Get message count and limit info for a session.
Returns dict with: message_count, max_messages, remaining, near_limit,
at_limit, and threshold (fraction of limit used).
"""
with self._lock:
self._ensure_loaded_locked()
entry = self._entries.get(session_key)
if not entry:
return {"message_count": 0, "max_messages": 0, "remaining": 0,
"near_limit": False, "at_limit": False, "threshold": 0.0}
policy = self.config.get_reset_policy(
platform=entry.platform,
session_type=entry.chat_type,
)
max_msgs = policy.max_messages
count = entry.message_count
remaining = max(0, max_msgs - count) if max_msgs > 0 else float("inf")
threshold = count / max_msgs if max_msgs > 0 else 0.0
return {
"message_count": count,
"max_messages": max_msgs,
"remaining": remaining,
"near_limit": max_msgs > 0 and count >= int(max_msgs * 0.85),
"at_limit": max_msgs > 0 and count >= max_msgs,
"threshold": threshold,
}
def reset_message_count(self, session_key: str) -> None:
"""Reset the message count to zero for a session.
Called after a session rotation to start fresh counting.
"""
with self._lock:
self._ensure_loaded_locked()
entry = self._entries.get(session_key)
if entry:
entry.message_count = 0
self._save()
def reset_session(self, session_key: str) -> Optional[SessionEntry]:
"""Force reset a session, creating a new session ID."""
db_end_session_id = None
@@ -927,7 +849,6 @@ class SessionStore:
display_name=old_entry.display_name,
platform=old_entry.platform,
chat_type=old_entry.chat_type,
message_count=0, # Fresh count after rotation (#326)
)
self._entries[session_key] = new_entry
@@ -1021,18 +942,12 @@ class SessionStore:
def append_to_transcript(self, session_id: str, message: Dict[str, Any], skip_db: bool = False) -> None:
"""Append a message to a session's transcript (SQLite + legacy JSONL).
Also increments the session's message_count for marathon session
limit tracking (#326).
Args:
skip_db: When True, only write to JSONL and skip the SQLite write.
Used when the agent already persisted messages to SQLite
via its own _flush_messages_to_session_db(), preventing
the duplicate-write bug (#860).
"""
# Skip counting session_meta entries (tool defs, metadata)
is_meta = message.get("role") == "session_meta"
# Write to SQLite (unless the agent already handled it)
if self._db and not skip_db:
try:
@@ -1046,20 +961,11 @@ class SessionStore:
)
except Exception as e:
logger.debug("Session DB operation failed: %s", e)
# Also write legacy JSONL (keeps existing tooling working during transition)
transcript_path = self.get_transcript_path(session_id)
with open(transcript_path, "a", encoding="utf-8") as f:
f.write(json.dumps(message, ensure_ascii=False) + "\n")
# Increment message count for marathon session tracking (#326)
if not is_meta:
with self._lock:
for entry in self._entries.values():
if entry.session_id == session_id:
entry.message_count += 1
self._save()
break
def rewrite_transcript(self, session_id: str, messages: List[Dict[str, Any]]) -> None:
"""Replace the entire transcript for a session with new messages.

View File

@@ -299,6 +299,13 @@ DEFAULT_CONFIG = {
"max_simple_chars": 160,
"max_simple_words": 28,
"cheap_model": {},
"cron_time_routing": {
"enabled": False,
"timezone": "UTC",
"peak_hours": {"start": 9, "end": 18},
"peak_model": {},
"offpeak_model": {},
},
},
# Auxiliary model config — provider:model for each side task.

View File

@@ -0,0 +1,164 @@
"""Tests for time-aware cron model routing."""
from agent.smart_model_routing import (
_is_peak_hour,
resolve_cron_time_route,
resolve_cron_turn_route,
)
# ---------------------------------------------------------------------------
# _is_peak_hour
# ---------------------------------------------------------------------------
def test_peak_hour_within_normal_range():
assert _is_peak_hour(10, 9, 18) is True
assert _is_peak_hour(12, 9, 18) is True
assert _is_peak_hour(17, 9, 18) is True
def test_peak_hour_outside_normal_range():
assert _is_peak_hour(8, 9, 18) is False
assert _is_peak_hour(18, 9, 18) is False
assert _is_peak_hour(22, 9, 18) is False
assert _is_peak_hour(0, 9, 18) is False
def test_peak_hour_at_boundaries():
assert _is_peak_hour(9, 9, 18) is True # start inclusive
assert _is_peak_hour(18, 9, 18) is False # end exclusive
def test_peak_hour_wraps_midnight():
# 22-6 means peak from 22:00 to 05:59
assert _is_peak_hour(22, 22, 6) is True
assert _is_peak_hour(23, 22, 6) is True
assert _is_peak_hour(0, 22, 6) is True
assert _is_peak_hour(5, 22, 6) is True
assert _is_peak_hour(6, 22, 6) is False
assert _is_peak_hour(12, 22, 6) is False
assert _is_peak_hour(21, 22, 6) is False
# ---------------------------------------------------------------------------
# resolve_cron_time_route
# ---------------------------------------------------------------------------
_CRON_ROUTING_CFG = {
"cron_time_routing": {
"enabled": True,
"timezone": "UTC",
"peak_hours": {"start": 9, "end": 18},
"peak_model": {
"provider": "openrouter",
"model": "xiaomi/mimo-v2-pro",
},
"offpeak_model": {
"provider": "openrouter",
"model": "anthropic/claude-sonnet-4",
},
},
}
def test_returns_none_when_disabled():
cfg = {"cron_time_routing": {"enabled": False}}
assert resolve_cron_time_route(cfg) is None
def test_returns_none_when_no_config():
assert resolve_cron_time_route(None) is None
assert resolve_cron_time_route({}) is None
def test_returns_none_when_models_missing():
cfg = {
"cron_time_routing": {
"enabled": True,
"peak_model": {"provider": "", "model": ""},
"offpeak_model": {"provider": "", "model": ""},
}
}
assert resolve_cron_time_route(cfg) is None
def test_returns_route_with_hour_injection(monkeypatch):
"""Force hour=14 (peak) via _get_current_hour_in_tz patch."""
monkeypatch.setattr(
"agent.smart_model_routing._get_current_hour_in_tz",
lambda tz: 14,
)
result = resolve_cron_time_route(_CRON_ROUTING_CFG)
assert result is not None
assert result["model"] == "xiaomi/mimo-v2-pro"
assert result["is_peak_hour"] is True
assert result["hour"] == 14
assert result["routing_reason"] == "cron_peak_hours"
def test_returns_offpeak_route(monkeypatch):
monkeypatch.setattr(
"agent.smart_model_routing._get_current_hour_in_tz",
lambda tz: 3,
)
result = resolve_cron_time_route(_CRON_ROUTING_CFG)
assert result is not None
assert result["model"] == "anthropic/claude-sonnet-4"
assert result["is_peak_hour"] is False
assert result["hour"] == 3
assert result["routing_reason"] == "cron_offpeak_hours"
# ---------------------------------------------------------------------------
# resolve_cron_turn_route
# ---------------------------------------------------------------------------
_PRIMARY = {
"model": "anthropic/claude-opus-4",
"provider": "openrouter",
"base_url": "https://openrouter.ai/api/v1",
"api_mode": "chat_completions",
"api_key": "***",
}
def test_cron_turn_route_uses_time_awareness(monkeypatch):
monkeypatch.setattr(
"agent.smart_model_routing._get_current_hour_in_tz",
lambda tz: 2, # off-peak
)
monkeypatch.setattr(
"hermes_cli.runtime_provider.resolve_runtime_provider",
lambda **kw: {
"api_key": "test-key",
"base_url": "https://openrouter.ai/api/v1",
"provider": "openrouter",
"api_mode": "chat_completions",
"command": None,
"args": [],
},
)
result = resolve_cron_turn_route("check status", _CRON_ROUTING_CFG, _PRIMARY)
assert result["model"] == "anthropic/claude-sonnet-4"
assert "cron off-peak" in (result.get("label") or "")
def test_cron_turn_route_falls_back_to_primary_when_no_config():
result = resolve_cron_turn_route("check status", None, _PRIMARY)
assert result["model"] == "anthropic/claude-opus-4"
assert result["label"] is None # no smart routing match
def test_cron_turn_route_falls_back_on_runtime_error(monkeypatch):
"""If time-route runtime resolution fails, fall back to normal routing."""
monkeypatch.setattr(
"agent.smart_model_routing._get_current_hour_in_tz",
lambda tz: 2,
)
monkeypatch.setattr(
"hermes_cli.runtime_provider.resolve_runtime_provider",
lambda **kw: (_ for _ in ()).throw(RuntimeError("bad")),
)
result = resolve_cron_turn_route("check status", _CRON_ROUTING_CFG, _PRIMARY)
# Falls back to primary since the time-route runtime failed
assert result["model"] == "anthropic/claude-opus-4"

View File

@@ -1,279 +0,0 @@
"""Tests for marathon session limits (#326)."""
import json
import os
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from gateway.config import (
GatewayConfig,
Platform,
PlatformConfig,
SessionResetPolicy,
)
from gateway.session import (
SessionEntry,
SessionSource,
SessionStore,
)
@pytest.fixture
def tmp_sessions_dir(tmp_path):
d = tmp_path / "sessions"
d.mkdir()
return d
@pytest.fixture
def default_config():
return GatewayConfig()
@pytest.fixture
def store(tmp_sessions_dir, default_config):
return SessionStore(tmp_sessions_dir, default_config)
def _make_source(platform=Platform.LOCAL, chat_id="test-chat"):
return SessionSource(
platform=platform,
chat_id=chat_id,
chat_type="dm",
user_id="test-user",
user_name="Test User",
)
class TestSessionResetPolicyMaxMessages:
"""Test max_messages field on SessionResetPolicy."""
def test_default_max_messages(self):
policy = SessionResetPolicy()
assert policy.max_messages == 200
def test_custom_max_messages(self):
policy = SessionResetPolicy(max_messages=500)
assert policy.max_messages == 500
def test_unlimited_when_zero(self):
policy = SessionResetPolicy(max_messages=0)
assert policy.max_messages == 0
def test_to_dict_includes_max_messages(self):
policy = SessionResetPolicy(max_messages=300)
d = policy.to_dict()
assert d["max_messages"] == 300
def test_from_dict_restores_max_messages(self):
data = {"mode": "idle", "max_messages": 150}
policy = SessionResetPolicy.from_dict(data)
assert policy.max_messages == 150
def test_from_dict_defaults_max_messages(self):
data = {"mode": "idle"}
policy = SessionResetPolicy.from_dict(data)
assert policy.max_messages == 200
class TestSessionEntryMessageCount:
"""Test message_count field on SessionEntry."""
def test_default_message_count(self):
entry = SessionEntry(
session_key="test",
session_id="20260101_000000_abc12345",
created_at=datetime.now(),
updated_at=datetime.now(),
)
assert entry.message_count == 0
def test_to_dict_includes_message_count(self):
entry = SessionEntry(
session_key="test",
session_id="20260101_000000_abc12345",
created_at=datetime.now(),
updated_at=datetime.now(),
message_count=42,
)
d = entry.to_dict()
assert d["message_count"] == 42
def test_from_dict_restores_message_count(self):
data = {
"session_key": "test",
"session_id": "20260101_000000_abc12345",
"created_at": "2026-01-01T00:00:00",
"updated_at": "2026-01-01T00:00:00",
"message_count": 99,
}
entry = SessionEntry.from_dict(data)
assert entry.message_count == 99
class TestShouldResetMessageLimit:
"""Test _should_reset returns 'message_limit' when message count exceeds cap."""
def test_reset_at_limit(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 200 # At default limit
result = store._should_reset(entry, source)
assert result == "message_limit"
def test_reset_over_limit(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 250
result = store._should_reset(entry, source)
assert result == "message_limit"
def test_no_reset_below_limit(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 100
result = store._should_reset(entry, source)
assert result is None
def test_no_reset_when_unlimited(self):
config = GatewayConfig()
config.default_reset_policy = SessionResetPolicy(
mode="none", max_messages=0
)
store = SessionStore(Path(tempfile.mkdtemp()), config)
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 9999
result = store._should_reset(entry, source)
assert result is None
def test_custom_limit(self):
config = GatewayConfig()
config.default_reset_policy = SessionResetPolicy(max_messages=50)
store = SessionStore(Path(tempfile.mkdtemp()), config)
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 50
result = store._should_reset(entry, source)
assert result == "message_limit"
def test_no_reset_just_under(self):
config = GatewayConfig()
config.default_reset_policy = SessionResetPolicy(max_messages=50)
store = SessionStore(Path(tempfile.mkdtemp()), config)
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 49
result = store._should_reset(entry, source)
assert result is None
class TestAppendToTranscriptIncrementsCount:
"""Test that append_to_transcript increments message_count."""
def test_increment_on_user_message(self, store, tmp_sessions_dir):
source = _make_source()
entry = store.get_or_create_session(source)
assert entry.message_count == 0
store.append_to_transcript(
entry.session_id,
{"role": "user", "content": "hello"},
)
# Re-read entry
entry = store.get_or_create_session(source)
assert entry.message_count == 1
def test_increment_on_assistant_message(self, store, tmp_sessions_dir):
source = _make_source()
entry = store.get_or_create_session(source)
store.append_to_transcript(
entry.session_id,
{"role": "user", "content": "hello"},
)
store.append_to_transcript(
entry.session_id,
{"role": "assistant", "content": "hi there"},
)
entry = store.get_or_create_session(source)
assert entry.message_count == 2
def test_no_increment_on_session_meta(self, store, tmp_sessions_dir):
source = _make_source()
entry = store.get_or_create_session(source)
store.append_to_transcript(
entry.session_id,
{"role": "session_meta", "tools": []},
)
entry = store.get_or_create_session(source)
assert entry.message_count == 0
class TestGetMessageLimitInfo:
"""Test get_message_limit_info returns correct data."""
def test_at_limit(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 200
info = store.get_message_limit_info(entry.session_key)
assert info["message_count"] == 200
assert info["max_messages"] == 200
assert info["remaining"] == 0
assert info["near_limit"] is True
assert info["at_limit"] is True
def test_near_limit(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 180 # 90% of 200
info = store.get_message_limit_info(entry.session_key)
assert info["near_limit"] is True
assert info["at_limit"] is False
assert info["remaining"] == 20
def test_well_below_limit(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 50
info = store.get_message_limit_info(entry.session_key)
assert info["near_limit"] is False
assert info["at_limit"] is False
assert info["remaining"] == 150
def test_unknown_session(self, store):
info = store.get_message_limit_info("nonexistent")
assert info["message_count"] == 0
assert info["at_limit"] is False
class TestResetMessageCount:
"""Test reset_message_count resets to zero."""
def test_reset_count(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 150
store.reset_message_count(entry.session_key)
info = store.get_message_limit_info(entry.session_key)
assert info["message_count"] == 0
class TestSessionRotationPreservesOrigin:
"""Test that session rotation creates fresh entry with message_count=0."""
def test_reset_creates_fresh_count(self, store):
source = _make_source()
entry = store.get_or_create_session(source)
entry.message_count = 200
new_entry = store.reset_session(entry.session_key)
assert new_entry is not None
assert new_entry.message_count == 0
assert new_entry.session_id != entry.session_id