Compare commits

...

1 Commits

Author SHA1 Message Date
Alexander Whitestone
49c8635261 fix(cron): derive provider from model prefix in _build_job_prompt
Some checks failed
Forge CI / smoke-and-build (pull_request) Failing after 1m3s
When runtime_provider is empty but runtime_model has a cloud prefix
(e.g. "nous/mimo-v2-pro"), the PROVIDER field in the runtime context
block was missing. Now _build_job_prompt derives the provider from
the model prefix before building the context block.

Also adds the runtime context infrastructure that was missing from main:
- _classify_runtime: classify cloud/local/unknown from provider+model
- _detect_provider_mismatch: warn when prompt refs different provider
- _build_job_prompt now accepts runtime_model/runtime_provider kwargs
- run_job passes resolved model/provider into _build_job_prompt
- ModelContextError, CRON_MIN_CONTEXT_TOKENS, _check_model_context_compat
  added to unblock pre-existing test imports

Fixes #565

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:39:04 -04:00
2 changed files with 218 additions and 4 deletions

View File

@@ -41,6 +41,42 @@ from agent.model_metadata import is_local_endpoint
logger = logging.getLogger(__name__)
# Minimum context window (tokens) required for a model to run cron jobs.
# Models below this threshold are rejected at job startup.
CRON_MIN_CONTEXT_TOKENS = 64_000
class ModelContextError(ValueError):
"""Raised when a model's context window is too small for cron use."""
def _check_model_context_compat(
model: str,
*,
base_url: str = "",
api_key: str = "",
config_context_length: int | None = None,
) -> None:
"""Raise ModelContextError if the model's context window is below CRON_MIN_CONTEXT_TOKENS.
If config_context_length is provided the check is skipped (user override).
Detection failures are non-fatal (fail-open) — the job proceeds.
"""
if config_context_length is not None:
return
try:
from agent.model_metadata import get_model_context_length
ctx = get_model_context_length(model, base_url=base_url, api_key=api_key)
except Exception as exc:
logger.debug("Context length detection failed for '%s', skipping check: %s", model, exc)
return
if ctx < CRON_MIN_CONTEXT_TOKENS:
raise ModelContextError(
f"Model '{model}' has a context window of {ctx:,} tokens, "
f"which is below the minimum {CRON_MIN_CONTEXT_TOKENS:,} required by Hermes Agent. "
f"To override, set model.context_length in config.yaml."
)
# =====================================================================
# Deploy Sync Guard
@@ -545,7 +581,49 @@ def _run_job_script(script_path: str) -> tuple[bool, str]:
return False, f"Script execution failed: {exc}"
def _build_job_prompt(job: dict) -> str:
_PROVIDER_ALIASES = {
"ollama": {"ollama", "localhost:11434"},
"anthropic": {"anthropic", "claude"},
"nous": {"nous", "mimo"},
"openrouter": {"openrouter"},
"openai": {"openai", "gpt"},
"gemini": {"gemini", "google"},
}
_CLOUD_PREFIXES = frozenset({"nous", "openrouter", "anthropic", "openai", "zai", "kimi", "gemini", "minimax"})
def _classify_runtime(provider: str, model: str) -> str:
"""Return 'cloud', 'local', or 'unknown' based on provider/model hints."""
p = (provider or "").strip().lower()
m = (model or "").strip().lower()
if p and p not in ("ollama", "local"):
return "cloud"
if "/" in m and m.split("/")[0] in _CLOUD_PREFIXES:
return "cloud"
if p in ("ollama", "local") or (not p and m):
return "local"
return "unknown"
def _detect_provider_mismatch(prompt: str, active_provider: str):
"""Return the mismatched provider alias if the prompt references a different provider."""
if not active_provider or not prompt:
return None
pl = prompt.lower()
al = active_provider.lower().strip()
active_group = next(
(g for g, aliases in _PROVIDER_ALIASES.items() if al in aliases or al.startswith(g)),
None,
)
if not active_group:
return None
return next(
(g for g, aliases in _PROVIDER_ALIASES.items() if g != active_group and any(x in pl for x in aliases)),
None,
)
def _build_job_prompt(job: dict, *, runtime_model: str = "", runtime_provider: str = "") -> str:
"""Build the effective prompt for a cron job, optionally loading one or more skills first."""
prompt = job.get("prompt", "")
skills = job.get("skills")
@@ -576,6 +654,26 @@ def _build_job_prompt(job: dict) -> str:
f"{prompt}"
)
# Build runtime context block — inject model/provider/runtime classification
# so the agent knows what infrastructure it has access to.
# Fix #565: derive provider from model prefix when runtime_provider is empty.
_runtime_block = ""
if runtime_model or runtime_provider:
if not runtime_provider and "/" in runtime_model:
runtime_provider = runtime_model.split("/")[0]
_kind = _classify_runtime(runtime_provider, runtime_model)
_parts = []
if runtime_model:
_parts.append(f"MODEL: {runtime_model}")
if runtime_provider:
_parts.append(f"PROVIDER: {runtime_provider}")
if _kind == "local":
_parts.append("RUNTIME: local — access to machine, Ollama, SSH")
elif _kind == "cloud":
_parts.append("RUNTIME: cloud — NO local access, NO SSH, NO localhost")
if _parts:
_runtime_block = "[SYSTEM: RUNTIME CONTEXT — " + "; ".join(_parts) + "]\n\n"
# Always prepend cron execution guidance so the agent knows how
# delivery works and can suppress delivery when appropriate.
cron_hint = (
@@ -597,7 +695,7 @@ def _build_job_prompt(job: dict) -> str:
"\"[SCRIPT_FAILED]: forge.alexanderwhitestone.com timed out\" "
"\"[SCRIPT_FAILED]: script exited with code 1\".]\\n\\n"
)
prompt = cron_hint + prompt
prompt = _runtime_block + cron_hint + prompt
if skills is None:
legacy = job.get("skill")
skills = [legacy] if legacy else []
@@ -667,7 +765,23 @@ def run_job(job: dict) -> tuple[bool, str, str, Optional[str]]:
job_id = job["id"]
job_name = job["name"]
prompt = _build_job_prompt(job)
# Resolve runtime model/provider early so the prompt gets accurate context.
_runtime_model = job.get("model") or os.getenv("HERMES_MODEL") or ""
_runtime_provider = os.getenv("HERMES_PROVIDER", "")
if not _runtime_model:
try:
import yaml as _y
_cp2 = str(_hermes_home / "config.yaml")
if os.path.exists(_cp2):
with open(_cp2) as _f:
_ce = _y.safe_load(_f) or {}
_mc = _ce.get("model", {})
_runtime_model = _mc if isinstance(_mc, str) else (_mc.get("default", "") if isinstance(_mc, dict) else "")
except Exception:
pass
prompt = _build_job_prompt(job, runtime_model=_runtime_model, runtime_provider=_runtime_provider)
origin = _resolve_origin(job)
_cron_session_id = f"cron_{job_id}_{_hermes_now().strftime('%Y%m%d_%H%M%S')}"
@@ -779,6 +893,14 @@ def run_job(job: dict) -> tuple[bool, str, str, Optional[str]]:
message = format_runtime_provider_error(exc)
raise RuntimeError(message) from exc
_active_provider = runtime.get("provider", "") or ""
_mismatch = _detect_provider_mismatch(job.get("prompt", ""), _active_provider)
if _mismatch:
logger.warning(
"Job '%s': prompt references '%s' but active provider is '%s'",
job_name, _mismatch, _active_provider,
)
from agent.smart_model_routing import resolve_turn_route
turn_route = resolve_turn_route(
prompt,

View File

@@ -7,7 +7,7 @@ from unittest.mock import AsyncMock, patch, MagicMock
import pytest
from cron.scheduler import _resolve_origin, _resolve_delivery_target, _deliver_result, run_job, SILENT_MARKER, _build_job_prompt, _check_model_context_compat, ModelContextError, CRON_MIN_CONTEXT_TOKENS
from cron.scheduler import _resolve_origin, _resolve_delivery_target, _deliver_result, run_job, SILENT_MARKER, _build_job_prompt, _check_model_context_compat, ModelContextError, CRON_MIN_CONTEXT_TOKENS, _classify_runtime, _detect_provider_mismatch
class TestResolveOrigin:
@@ -827,6 +827,98 @@ class TestBuildJobPromptMissingSkill:
assert "go" in result
class TestClassifyRuntime:
"""Unit tests for _classify_runtime."""
def test_cloud_provider_explicit(self):
assert _classify_runtime("openai", "") == "cloud"
assert _classify_runtime("anthropic", "") == "cloud"
assert _classify_runtime("nous", "") == "cloud"
def test_local_provider_explicit(self):
assert _classify_runtime("ollama", "") == "local"
assert _classify_runtime("local", "") == "local"
def test_cloud_detected_from_model_prefix(self):
"""Model prefix 'nous/...' should be classified as cloud even with no provider."""
assert _classify_runtime("", "nous/mimo-v2-pro") == "cloud"
assert _classify_runtime("", "openai/gpt-4o") == "cloud"
def test_local_when_model_has_no_cloud_prefix(self):
"""A model without a cloud prefix and no provider => local."""
assert _classify_runtime("", "llama3") == "local"
def test_unknown_when_empty(self):
assert _classify_runtime("", "") == "unknown"
class TestBuildJobPromptRuntimeContext:
"""Verify runtime context block injection in _build_job_prompt."""
def test_runtime_block_injected_with_model_and_provider(self):
job = {"prompt": "Do something"}
result = _build_job_prompt(job, runtime_model="nous/mimo-v2-pro", runtime_provider="nous")
assert "RUNTIME CONTEXT" in result
assert "MODEL: nous/mimo-v2-pro" in result
assert "PROVIDER: nous" in result
assert "cloud" in result
def test_provider_derived_from_model_prefix_when_empty(self):
"""Fix #565: PROVIDER should be derived from model prefix when runtime_provider is empty."""
job = {"prompt": "Do something"}
result = _build_job_prompt(job, runtime_model="nous/mimo-v2-pro", runtime_provider="")
assert "PROVIDER: nous" in result
def test_provider_not_empty_in_context_block(self):
"""Fix #565: PROVIDER line must not be blank when model has a slash prefix."""
job = {"prompt": "Check status"}
result = _build_job_prompt(job, runtime_model="openai/gpt-4o", runtime_provider="")
assert "PROVIDER: openai" in result
assert "PROVIDER: ;" not in result
assert "PROVIDER: ]" not in result
def test_no_runtime_block_when_no_model_or_provider(self):
"""No runtime block should appear when neither model nor provider is given."""
job = {"prompt": "Hello"}
result = _build_job_prompt(job)
assert "RUNTIME CONTEXT" not in result
def test_local_runtime_classification(self):
"""ollama model should get local runtime label."""
job = {"prompt": "Query local model"}
result = _build_job_prompt(job, runtime_model="llama3", runtime_provider="ollama")
assert "RUNTIME: local" in result
assert "NO local access" not in result
def test_runtime_block_precedes_cron_hint(self):
"""RUNTIME CONTEXT block should appear before the cron system hint."""
job = {"prompt": "test"}
result = _build_job_prompt(job, runtime_model="nous/mimo-v2-pro", runtime_provider="nous")
runtime_pos = result.index("RUNTIME CONTEXT")
cron_pos = result.index("scheduled cron job")
assert runtime_pos < cron_pos
class TestDetectProviderMismatch:
"""Unit tests for _detect_provider_mismatch."""
def test_no_mismatch_when_same_provider(self):
assert _detect_provider_mismatch("Use ollama to generate", "ollama") is None
def test_mismatch_detected(self):
"""Prompt referencing 'ollama' while running on 'nous' should flag a mismatch."""
result = _detect_provider_mismatch("Check if Ollama is responding", "nous")
assert result == "ollama"
def test_no_mismatch_for_empty_inputs(self):
assert _detect_provider_mismatch("", "nous") is None
assert _detect_provider_mismatch("some prompt", "") is None
def test_no_mismatch_when_provider_unknown(self):
"""Unknown active provider should not raise, just return None."""
assert _detect_provider_mismatch("Check Ollama", "mystery-provider") is None
class TestTickAdvanceBeforeRun:
"""Verify that tick() calls advance_next_run before run_job for crash safety."""