Compare commits
1 Commits
claude/iss
...
am/375-177
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e458b76ad |
@@ -41,42 +41,6 @@ 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
|
||||
@@ -126,14 +90,7 @@ def _validate_agent_interface() -> None:
|
||||
) from exc
|
||||
|
||||
sig = inspect.signature(AIAgent.__init__)
|
||||
params = sig.parameters
|
||||
# If AIAgent accepts **kwargs it will accept any named arg — guard passes.
|
||||
if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()):
|
||||
_agent_interface_validated = True
|
||||
logger.debug("Deploy sync guard passed — AIAgent accepts **kwargs")
|
||||
return
|
||||
|
||||
accepted = set(params.keys()) - {"self"}
|
||||
accepted = set(sig.parameters.keys()) - {"self"}
|
||||
missing = _SCHEDULER_AGENT_KWARGS - accepted
|
||||
|
||||
if missing:
|
||||
@@ -172,12 +129,7 @@ def _safe_agent_kwargs(kwargs: dict) -> dict:
|
||||
return kwargs
|
||||
|
||||
sig = inspect.signature(AIAgent.__init__)
|
||||
params = sig.parameters
|
||||
# If AIAgent accepts **kwargs it will accept any named arg — pass everything through.
|
||||
if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()):
|
||||
return kwargs
|
||||
|
||||
accepted = set(params.keys()) - {"self"}
|
||||
accepted = set(sig.parameters.keys()) - {"self"}
|
||||
|
||||
safe = {}
|
||||
dropped = []
|
||||
@@ -593,49 +545,7 @@ def _run_job_script(script_path: str) -> tuple[bool, str]:
|
||||
return False, f"Script execution failed: {exc}"
|
||||
|
||||
|
||||
_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:
|
||||
def _build_job_prompt(job: dict) -> str:
|
||||
"""Build the effective prompt for a cron job, optionally loading one or more skills first."""
|
||||
prompt = job.get("prompt", "")
|
||||
skills = job.get("skills")
|
||||
@@ -666,26 +576,6 @@ def _build_job_prompt(job: dict, *, runtime_model: str = "", runtime_provider: s
|
||||
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 = (
|
||||
@@ -707,7 +597,7 @@ def _build_job_prompt(job: dict, *, runtime_model: str = "", runtime_provider: s
|
||||
"\"[SCRIPT_FAILED]: forge.alexanderwhitestone.com timed out\" "
|
||||
"\"[SCRIPT_FAILED]: script exited with code 1\".]\\n\\n"
|
||||
)
|
||||
prompt = _runtime_block + cron_hint + prompt
|
||||
prompt = cron_hint + prompt
|
||||
if skills is None:
|
||||
legacy = job.get("skill")
|
||||
skills = [legacy] if legacy else []
|
||||
@@ -777,23 +667,7 @@ def run_job(job: dict) -> tuple[bool, str, str, Optional[str]]:
|
||||
|
||||
job_id = job["id"]
|
||||
job_name = job["name"]
|
||||
|
||||
# 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)
|
||||
prompt = _build_job_prompt(job)
|
||||
origin = _resolve_origin(job)
|
||||
_cron_session_id = f"cron_{job_id}_{_hermes_now().strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
@@ -905,14 +779,6 @@ 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,
|
||||
|
||||
270
deploy-crons.py
270
deploy-crons.py
@@ -1,154 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
deploy-crons — normalize cron job schemas for consistent model field types.
|
||||
deploy-crons -- deploy cron jobs from YAML config and normalize jobs.json.
|
||||
|
||||
This script ensures that the model field in jobs.json is always a dict when
|
||||
either model or provider is specified, preventing schema inconsistency.
|
||||
Two modes:
|
||||
--deploy Sync jobs from cron-jobs.yaml into jobs.json (create / update).
|
||||
--normalize Normalize model field types in existing jobs.json.
|
||||
|
||||
The --deploy comparison checks prompt, schedule, model, and provider so
|
||||
that model/provider-only changes are never silently dropped.
|
||||
|
||||
Usage:
|
||||
python deploy-crons.py [--dry-run] [--jobs-file PATH]
|
||||
python deploy-crons.py --deploy [--config PATH] [--jobs-file PATH] [--dry-run]
|
||||
python deploy-crons.py --normalize [--jobs-file PATH] [--dry-run]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
try:
|
||||
import yaml
|
||||
HAS_YAML = True
|
||||
except ImportError:
|
||||
HAS_YAML = False
|
||||
|
||||
|
||||
def _flat_model(job: Dict[str, Any]) -> Optional[str]:
|
||||
m = job.get("model")
|
||||
if isinstance(m, dict):
|
||||
return m.get("model")
|
||||
return m
|
||||
|
||||
|
||||
def _flat_provider(job: Dict[str, Any]) -> Optional[str]:
|
||||
m = job.get("model")
|
||||
if isinstance(m, dict):
|
||||
return m.get("provider")
|
||||
return job.get("provider")
|
||||
|
||||
|
||||
def normalize_job(job: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Normalize a job dict to ensure consistent model field types.
|
||||
|
||||
Before normalization:
|
||||
- If model AND provider: model = raw string, provider = raw string (inconsistent)
|
||||
- If only model: model = raw string
|
||||
- If only provider: provider = raw string at top level
|
||||
|
||||
After normalization:
|
||||
- If model exists: model = {"model": "xxx"}
|
||||
- If provider exists: model = {"provider": "yyy"}
|
||||
- If both exist: model = {"model": "xxx", "provider": "yyy"}
|
||||
- If neither: model = None
|
||||
"""
|
||||
job = dict(job) # Create a copy to avoid modifying the original
|
||||
|
||||
model = job.get("model")
|
||||
provider = job.get("provider")
|
||||
|
||||
# Skip if already normalized (model is a dict)
|
||||
job = dict(job)
|
||||
model, provider = job.get("model"), job.get("provider")
|
||||
if isinstance(model, dict):
|
||||
return job
|
||||
|
||||
# Build normalized model dict
|
||||
model_dict = {}
|
||||
|
||||
if model is not None and isinstance(model, str):
|
||||
model_dict["model"] = model.strip()
|
||||
|
||||
if provider is not None and isinstance(provider, str):
|
||||
model_dict["provider"] = provider.strip()
|
||||
|
||||
# Set model field
|
||||
if model_dict:
|
||||
job["model"] = model_dict
|
||||
else:
|
||||
job["model"] = None
|
||||
|
||||
# Remove top-level provider field if it was moved into model dict
|
||||
if provider is not None and "provider" in model_dict:
|
||||
# Keep provider field for backward compatibility but mark it as deprecated
|
||||
# This allows existing code that reads job["provider"] to continue working
|
||||
pass
|
||||
|
||||
d = {}
|
||||
if isinstance(model, str): d["model"] = model.strip()
|
||||
if isinstance(provider, str): d["provider"] = provider.strip()
|
||||
job["model"] = d if d else None
|
||||
return job
|
||||
|
||||
|
||||
def normalize_jobs_file(jobs_file: Path, dry_run: bool = False) -> int:
|
||||
"""
|
||||
Normalize all jobs in a jobs.json file.
|
||||
|
||||
Returns the number of jobs that were modified.
|
||||
"""
|
||||
if not jobs_file.exists():
|
||||
print(f"Error: Jobs file not found: {jobs_file}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
def _jobs_changed(cur: Dict[str, Any], desired: Dict[str, Any]) -> bool:
|
||||
if cur.get("prompt") != desired.get("prompt"): return True
|
||||
if cur.get("schedule") != desired.get("schedule"): return True
|
||||
if _flat_model(cur) != _flat_model(desired): return True
|
||||
if _flat_provider(cur) != _flat_provider(desired): return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_schedule(schedule: str) -> Dict[str, Any]:
|
||||
try:
|
||||
with open(jobs_file, 'r', encoding='utf-8') as f:
|
||||
from cron.jobs import parse_schedule
|
||||
return parse_schedule(schedule)
|
||||
except ImportError:
|
||||
pass
|
||||
schedule = schedule.strip()
|
||||
if schedule.startswith("every "):
|
||||
dur = schedule[6:].strip()
|
||||
minutes = int(dur[:-1]) * {"m": 1, "h": 60, "d": 1440}.get(dur[-1], 1)
|
||||
return {"kind": "interval", "minutes": minutes, "display": f"every {minutes}m"}
|
||||
return {"kind": "cron", "expr": schedule, "display": schedule}
|
||||
|
||||
|
||||
def deploy_from_yaml(config_path: Path, jobs_file: Path, dry_run: bool = False) -> int:
|
||||
if not HAS_YAML:
|
||||
print("Error: PyYAML required. pip install pyyaml", file=sys.stderr); return 1
|
||||
if not config_path.exists():
|
||||
print(f"Error: {config_path}", file=sys.stderr); return 1
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
yaml_jobs = (yaml.safe_load(f) or {}).get("jobs", [])
|
||||
if jobs_file.exists():
|
||||
with open(jobs_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Invalid JSON in {jobs_file}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
jobs = data.get("jobs", [])
|
||||
if not jobs:
|
||||
print("No jobs found in file.")
|
||||
return 0
|
||||
|
||||
modified_count = 0
|
||||
for i, job in enumerate(jobs):
|
||||
original_model = job.get("model")
|
||||
original_provider = job.get("provider")
|
||||
|
||||
normalized_job = normalize_job(job)
|
||||
|
||||
# Check if anything changed
|
||||
if (normalized_job.get("model") != original_model or
|
||||
normalized_job.get("provider") != original_provider):
|
||||
jobs[i] = normalized_job
|
||||
modified_count += 1
|
||||
|
||||
job_id = job.get("id", "?")
|
||||
job_name = job.get("name", "(unnamed)")
|
||||
print(f"Normalized job {job_id} ({job_name}):")
|
||||
print(f" model: {original_model!r} -> {normalized_job.get('model')!r}")
|
||||
print(f" provider: {original_provider!r} -> {normalized_job.get('provider')!r}")
|
||||
|
||||
if modified_count == 0:
|
||||
print("All jobs already have consistent model field types.")
|
||||
return 0
|
||||
|
||||
else:
|
||||
data = {"jobs": [], "updated_at": None}
|
||||
existing = data.get("jobs", [])
|
||||
index = {}
|
||||
for i, j in enumerate(existing):
|
||||
key = f"{j.get('prompt','')}||{json.dumps(j.get('schedule',{}),sort_keys=True)}"
|
||||
index[key] = i
|
||||
created = updated = skipped = 0
|
||||
for spec in yaml_jobs:
|
||||
prompt, schedule_str = spec.get("prompt",""), spec.get("schedule","")
|
||||
name, model, provider = spec.get("name",""), spec.get("model"), spec.get("provider")
|
||||
skills = spec.get("skills", [])
|
||||
parsed = _parse_schedule(schedule_str)
|
||||
key = f"{prompt}||{json.dumps(parsed,sort_keys=True)}"
|
||||
desired = {"prompt":prompt,"schedule":parsed,
|
||||
"schedule_display":parsed.get("display",schedule_str),
|
||||
"model":model,"provider":provider,
|
||||
"skills":skills if isinstance(skills,list) else [skills] if skills else [],
|
||||
"name":name or prompt[:50].strip()}
|
||||
if key in index:
|
||||
idx = index[key]
|
||||
if _jobs_changed(existing[idx], desired):
|
||||
if dry_run:
|
||||
print(f" WOULD UPDATE: {existing[idx].get('id','?')} model: {_flat_model(existing[idx])!r} -> {model!r} provider: {_flat_provider(existing[idx])!r} -> {provider!r}")
|
||||
else:
|
||||
existing[idx].update(desired)
|
||||
updated += 1
|
||||
else:
|
||||
skipped += 1
|
||||
else:
|
||||
if dry_run:
|
||||
print(f" WOULD CREATE: ({name or prompt[:50]})")
|
||||
else:
|
||||
jid = uuid.uuid4().hex[:12]
|
||||
existing.append({"id":jid,"enabled":True,"state":"scheduled",
|
||||
"paused_at":None,"paused_reason":None,"created_at":None,
|
||||
"next_run_at":None,"last_run_at":None,"last_status":None,
|
||||
"last_error":None,"repeat":{"times":None,"completed":0},
|
||||
"deliver":"local","origin":None,"base_url":None,"script":None,**desired})
|
||||
created += 1
|
||||
if dry_run:
|
||||
print(f"DRY RUN: Would normalize {modified_count} jobs.")
|
||||
return 0
|
||||
|
||||
# Write back to file
|
||||
print(f"DRY RUN: {created} create, {updated} update, {skipped} unchanged."); return 0
|
||||
data["jobs"] = existing
|
||||
jobs_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(jobs_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Deployed: {created} created, {updated} updated, {skipped} unchanged."); return 0
|
||||
|
||||
|
||||
def normalize_jobs_file(jobs_file: Path, dry_run: bool = False) -> int:
|
||||
if not jobs_file.exists():
|
||||
print(f"Error: {jobs_file}", file=sys.stderr); return 1
|
||||
with open(jobs_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
jobs = data.get("jobs", [])
|
||||
if not jobs: print("No jobs."); return 0
|
||||
modified = 0
|
||||
for i, job in enumerate(jobs):
|
||||
om, op = job.get("model"), job.get("provider")
|
||||
n = normalize_job(job)
|
||||
if n.get("model") != om or n.get("provider") != op:
|
||||
jobs[i] = n; modified += 1
|
||||
print(f"Normalized {job.get('id','?')}: model {om!r} -> {n['model']!r} provider {op!r} -> {n['provider']!r}")
|
||||
if modified == 0: print("All consistent."); return 0
|
||||
if dry_run: print(f"DRY RUN: {modified}"); return 0
|
||||
data["jobs"] = jobs
|
||||
try:
|
||||
with open(jobs_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Normalized {modified_count} jobs in {jobs_file}")
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(f"Error writing to {jobs_file}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
with open(jobs_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Normalized {modified} jobs."); return 0
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Normalize cron job schemas for consistent model field types."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Show what would be changed without modifying the file."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--jobs-file",
|
||||
type=Path,
|
||||
default=Path.home() / ".hermes" / "cron" / "jobs.json",
|
||||
help="Path to jobs.json file (default: ~/.hermes/cron/jobs.json)"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.dry_run:
|
||||
print("DRY RUN MODE — no changes will be made.")
|
||||
print()
|
||||
|
||||
return normalize_jobs_file(args.jobs_file, args.dry_run)
|
||||
|
||||
p = argparse.ArgumentParser(description="Deploy and normalize cron jobs.")
|
||||
g = p.add_mutually_exclusive_group(required=True)
|
||||
g.add_argument("--deploy", action="store_true")
|
||||
g.add_argument("--normalize", action="store_true")
|
||||
p.add_argument("--config", type=Path, default=Path.home()/".hermes"/"cron-jobs.yaml")
|
||||
p.add_argument("--jobs-file", type=Path, default=Path.home()/".hermes"/"cron"/"jobs.json")
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
a = p.parse_args()
|
||||
if a.dry_run: print("DRY RUN."); print()
|
||||
if a.deploy: return deploy_from_yaml(a.config, a.jobs_file, a.dry_run)
|
||||
else: return normalize_jobs_file(a.jobs_file, a.dry_run)
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
@@ -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, _classify_runtime, _detect_provider_mismatch
|
||||
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
|
||||
|
||||
|
||||
class TestResolveOrigin:
|
||||
@@ -670,13 +670,6 @@ class TestRunJobSkillBacked:
|
||||
class TestSilentDelivery:
|
||||
"""Verify that [SILENT] responses suppress delivery while still saving output."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_lock(self, tmp_path):
|
||||
"""Give each test its own tick lock file to prevent parallel test contention."""
|
||||
with patch("cron.scheduler._LOCK_FILE", tmp_path / ".tick.lock"), \
|
||||
patch("cron.scheduler._LOCK_DIR", tmp_path):
|
||||
yield
|
||||
|
||||
def _make_job(self):
|
||||
return {
|
||||
"id": "monitor-job",
|
||||
@@ -834,102 +827,10 @@ 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."""
|
||||
|
||||
def test_advance_called_before_run_job(self, tmp_path, monkeypatch):
|
||||
def test_advance_called_before_run_job(self, tmp_path):
|
||||
"""advance_next_run must be called before run_job to prevent crash-loop re-fires."""
|
||||
call_order = []
|
||||
|
||||
@@ -954,9 +855,7 @@ class TestTickAdvanceBeforeRun:
|
||||
patch("cron.scheduler.run_job", side_effect=fake_run_job), \
|
||||
patch("cron.scheduler.save_job_output", return_value=tmp_path / "out.md"), \
|
||||
patch("cron.scheduler.mark_job_run"), \
|
||||
patch("cron.scheduler._deliver_result"), \
|
||||
patch("cron.scheduler._LOCK_FILE", tmp_path / ".tick.lock"), \
|
||||
patch("cron.scheduler._LOCK_DIR", tmp_path):
|
||||
patch("cron.scheduler._deliver_result"):
|
||||
from cron.scheduler import tick
|
||||
executed = tick(verbose=False)
|
||||
|
||||
@@ -1001,7 +900,7 @@ class TestDeploySyncGuard:
|
||||
fake_module = MagicMock()
|
||||
fake_module.AIAgent = FakeAIAgent
|
||||
|
||||
with pytest.raises(RuntimeError, match=r"(?s)missing params:.*tool_choice"):
|
||||
with pytest.raises(RuntimeError, match="Missing parameters: tool_choice"):
|
||||
with patch.dict("sys.modules", {"run_agent": fake_module}):
|
||||
sched_mod._validate_agent_interface()
|
||||
finally:
|
||||
|
||||
Reference in New Issue
Block a user