Compare commits

...

11 Commits

Author SHA1 Message Date
0f680d70b8 feat: add model fallback verification script (#514)
Some checks failed
Architecture Lint / Linter Tests (pull_request) Successful in 44s
Smoke Test / smoke (pull_request) Failing after 28s
Validate Config / YAML Lint (pull_request) Failing after 20s
Validate Config / JSON Validate (pull_request) Successful in 27s
Validate Config / Python Syntax & Import Check (pull_request) Failing after 1m41s
Validate Config / Shell Script Lint (pull_request) Failing after 44s
Validate Config / Cron Syntax Check (pull_request) Successful in 4s
Validate Config / Deploy Script Dry Run (pull_request) Successful in 6s
Validate Config / Playbook Schema Validation (pull_request) Successful in 13s
PR Checklist / pr-checklist (pull_request) Failing after 12m11s
Architecture Lint / Lint Repository (pull_request) Has been cancelled
Validate Config / Python Test Suite (pull_request) Has been cancelled
- Tests model switches with verification prompts
- Validates context window meets 64K minimum
- Checks primary model and fallback chain
- Supports OpenRouter, Anthropic, Nous, Kimi, Ollama
- Exits with error if no viable model found

Closes #514
2026-04-15 03:20:49 +00:00
d120526244 fix: add python3 shebang to scripts/visual_pr_reviewer.py (#681) 2026-04-15 02:57:53 +00:00
8596ff761b fix: add python3 shebang to scripts/diagram_meaning_extractor.py (#681) 2026-04-15 02:57:40 +00:00
7553fd4f3e fix: add python3 shebang to scripts/captcha_bypass_handler.py (#681) 2026-04-15 02:57:25 +00:00
71082fe06f fix: add python3 shebang to bin/soul_eval_gate.py (#681) 2026-04-15 02:57:14 +00:00
6d678e938e fix: add python3 shebang to bin/nostr-agent-demo.py (#681) 2026-04-15 02:57:00 +00:00
ad751a6de6 docs: add pipeline scheduler README 2026-04-14 22:47:12 +00:00
130fa40f0c feat: add pipeline-scheduler cron job 2026-04-14 22:46:51 +00:00
82f9810081 feat: add nightly-pipeline-scheduler.sh 2026-04-14 22:46:38 +00:00
2548277137 cleanup test
Some checks failed
Architecture Lint / Linter Tests (push) Successful in 22s
Smoke Test / smoke (push) Failing after 21s
Validate Config / YAML Lint (push) Failing after 13s
Validate Config / JSON Validate (push) Successful in 14s
Validate Config / Python Syntax & Import Check (push) Failing after 1m9s
Validate Config / Shell Script Lint (push) Failing after 31s
Validate Config / Cron Syntax Check (push) Successful in 5s
Validate Config / Deploy Script Dry Run (push) Successful in 7s
Validate Config / Playbook Schema Validation (push) Successful in 16s
Architecture Lint / Linter Tests (pull_request) Successful in 14s
Smoke Test / smoke (pull_request) Failing after 13s
Validate Config / YAML Lint (pull_request) Failing after 12s
Validate Config / JSON Validate (pull_request) Successful in 13s
Validate Config / Python Syntax & Import Check (pull_request) Failing after 54s
Validate Config / Shell Script Lint (pull_request) Failing after 21s
Validate Config / Cron Syntax Check (pull_request) Successful in 5s
Validate Config / Deploy Script Dry Run (pull_request) Successful in 7s
Validate Config / Playbook Schema Validation (pull_request) Successful in 18s
PR Checklist / pr-checklist (pull_request) Failing after 3m27s
Architecture Lint / Lint Repository (push) Has been cancelled
Validate Config / Python Test Suite (pull_request) Has been cancelled
Architecture Lint / Lint Repository (pull_request) Has been cancelled
Validate Config / Python Test Suite (push) Has been cancelled
2026-04-14 22:39:03 +00:00
2b234fde79 test: verify API works
Some checks failed
Architecture Lint / Linter Tests (push) Has been cancelled
Architecture Lint / Lint Repository (push) Has been cancelled
Smoke Test / smoke (push) Failing after 12s
Validate Config / YAML Lint (push) Failing after 11s
Validate Config / JSON Validate (push) Successful in 11s
Validate Config / Python Syntax & Import Check (push) Failing after 47s
Validate Config / Shell Script Lint (push) Failing after 33s
Validate Config / Cron Syntax Check (push) Successful in 10s
Validate Config / Deploy Script Dry Run (push) Successful in 10s
Validate Config / Playbook Schema Validation (push) Successful in 14s
Validate Config / Python Test Suite (push) Has been cancelled
2026-04-14 22:39:02 +00:00
9 changed files with 890 additions and 0 deletions

View File

@@ -0,0 +1,443 @@
#!/usr/bin/env python3
"""
Model Fallback Verification Script
Issue #514: [Robustness] Model fallback verification — test before trusting
Tests model switches with verification prompts, validates context windows,
and ensures at least one viable model is available before starting loops.
Usage:
python3 model-fallback-verify.py # Run full verification
python3 model-fallback-verify.py check <model> # Test specific model
python3 model-fallback-verify.py context <model> # Check context window
python3 model-fallback-verify.py list # List available models
"""
import os, sys, json, yaml, urllib.request
from datetime import datetime, timezone
from pathlib import Path
# Configuration
HERMES_HOME = Path(os.environ.get("HERMES_HOME", Path.home() / ".hermes"))
CONFIG_FILE = HERMES_HOME / "config.yaml"
LOG_DIR = HERMES_HOME / "logs"
LOG_FILE = LOG_DIR / "model-verify.log"
MIN_CONTEXT_WINDOW = 64 * 1024 # 64K tokens minimum
# Provider endpoints
PROVIDER_CONFIGS = {
"openrouter": {
"base_url": "https://openrouter.ai/api/v1",
"headers": lambda api_key: {"Authorization": "Bearer " + api_key},
"chat_url": "/chat/completions",
},
"anthropic": {
"base_url": "https://api.anthropic.com/v1",
"headers": lambda api_key: {"x-api-key": api_key, "anthropic-version": "2023-06-01"},
"chat_url": "/messages",
},
"nous": {
"base_url": "https://inference.nousresearch.com/v1",
"headers": lambda api_key: {"Authorization": "Bearer " + api_key},
"chat_url": "/chat/completions",
},
"kimi-coding": {
"base_url": "https://api.kimi.com/coding/v1",
"headers": lambda api_key: {"x-api-key": api_key, "x-api-provider": "kimi-coding"},
"chat_url": "/chat/completions",
},
"custom": {
"base_url": None,
"headers": lambda api_key: {"Authorization": "Bearer " + api_key},
"chat_url": "/chat/completions",
},
}
# Known context windows for common models
KNOWN_CONTEXT_WINDOWS = {
"claude-opus-4-6": 200000,
"claude-sonnet-4": 200000,
"claude-3.5-sonnet": 200000,
"gpt-4o": 128000,
"gpt-4": 128000,
"gpt-3.5-turbo": 16385,
"qwen3:30b": 32768,
"qwen2.5:7b": 32768,
"hermes4:14b": 32768,
"gemma3:1b": 8192,
"gemma4": 32768,
"phi3:3.8b": 128000,
"kimi-k2.5": 128000,
"google/gemini-2.5-pro": 1048576,
"xiaomi/mimo-v2-pro": 131072,
"deepseek/deepseek-r1": 131072,
"deepseek/deepseek-chat-v3-0324": 131072,
}
def log(msg):
"""Log message to file and optionally to console."""
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
log_entry = "[" + timestamp + "] " + msg
LOG_DIR.mkdir(parents=True, exist_ok=True)
with open(LOG_FILE, "a") as f:
f.write(log_entry + "\n")
if "--quiet" not in sys.argv:
print(log_entry)
def load_config():
"""Load Hermes config.yaml."""
if not CONFIG_FILE.exists():
return None
with open(CONFIG_FILE) as f:
return yaml.safe_load(f)
def get_provider_api_key(provider):
"""Get API key for a provider from .env or environment."""
env_file = HERMES_HOME / ".env"
if env_file.exists():
with open(env_file) as f:
for line in f:
line = line.strip()
if line.startswith(provider.upper() + "_API_KEY="):
return line.split("=", 1)[1].strip().strip("'\"")
return os.environ.get(provider.upper() + "_API_KEY")
def get_ollama_models():
"""Get list of available Ollama models."""
ollama_host = os.environ.get("OLLAMA_HOST", "localhost:11434")
try:
resp = urllib.request.urlopen("http://" + ollama_host + "/api/tags", timeout=5)
data = json.loads(resp.read())
return [m["name"] for m in data.get("models", [])]
except:
return []
def test_model(model, provider, api_key=None, base_url=None):
"""
Test a model with a verification prompt.
Returns (success, response, error_message)
"""
if provider == "ollama" or ":" in model:
# Local Ollama model
ollama_host = os.environ.get("OLLAMA_HOST", "localhost:11434")
try:
body = json.dumps({
"model": model,
"prompt": "Say exactly VERIFIED and nothing else.",
"stream": False,
"options": {"num_predict": 10}
}).encode()
req = urllib.request.Request(
"http://" + ollama_host + "/api/generate",
data=body,
headers={"Content-Type": "application/json"}
)
resp = urllib.request.urlopen(req, timeout=30)
result = json.loads(resp.read())
response_text = result.get("response", "").strip()
if "VERIFIED" in response_text.upper():
return True, response_text, None
return False, response_text, "Unexpected response: " + response_text[:100]
except Exception as e:
return False, "", "Ollama error: " + str(e)[:200]
# Cloud provider
config = PROVIDER_CONFIGS.get(provider)
if not config:
return False, "", "Unknown provider: " + provider
url = base_url or config["base_url"]
if not url:
return False, "", "No base URL for provider: " + provider
headers = config["headers"](api_key or "")
headers["Content-Type"] = "application/json"
try:
body = json.dumps({
"model": model,
"max_tokens": 20,
"messages": [{"role": "user", "content": "Say exactly VERIFIED and nothing else."}]
}).encode()
req = urllib.request.Request(
url + config["chat_url"],
data=body,
headers=headers
)
resp = urllib.request.urlopen(req, timeout=30)
result = json.loads(resp.read())
if provider == "anthropic":
content = result.get("content", [{}])[0].get("text", "")
else:
choices = result.get("choices", [{}])
content = choices[0].get("message", {}).get("content", "") if choices else ""
if "VERIFIED" in content.upper():
return True, content, None
return False, content, "Unexpected response: " + content[:100]
except urllib.error.HTTPError as e:
error_body = e.read().decode() if e.fp else str(e)
if e.code == 404:
return False, "", "Model not found (404): " + error_body[:200]
elif e.code == 429:
return True, "", "Rate limited but model exists"
elif e.code >= 500:
return False, "", "Server error (" + str(e.code) + "): " + error_body[:200]
else:
return False, "", "HTTP " + str(e.code) + ": " + error_body[:200]
except Exception as e:
return False, "", "Request error: " + str(e)[:200]
def get_context_window(model, provider):
"""
Get the context window size for a model.
Returns (window_size, source)
"""
if model in KNOWN_CONTEXT_WINDOWS:
return KNOWN_CONTEXT_WINDOWS[model], "known"
model_lower = model.lower()
if "claude" in model_lower:
return 200000, "inferred (claude)"
elif "gpt-4" in model_lower:
return 128000, "inferred (gpt-4)"
elif "gemini" in model_lower:
return 1048576, "inferred (gemini)"
elif "qwen" in model_lower:
return 32768, "inferred (qwen)"
elif "gemma" in model_lower:
return 8192, "inferred (gemma)"
elif "phi" in model_lower:
return 128000, "inferred (phi)"
return 32768, "default"
def verify_model(model, provider, api_key=None, base_url=None):
"""
Full verification of a model: test prompt + context window.
Returns dict with verification results.
"""
result = {
"model": model,
"provider": provider,
"tested": False,
"responded": False,
"response": "",
"error": None,
"context_window": 0,
"context_source": "unknown",
"meets_minimum": False,
"viable": False,
}
success, response, error = test_model(model, provider, api_key, base_url)
result["tested"] = True
result["responded"] = success
result["response"] = response[:200] if response else ""
result["error"] = error
window, source = get_context_window(model, provider)
result["context_window"] = window
result["context_source"] = source
result["meets_minimum"] = window >= MIN_CONTEXT_WINDOW
result["viable"] = success and result["meets_minimum"]
return result
def get_fallback_chain(config):
"""Get the fallback chain from config or defaults."""
chain = []
model_config = config.get("model", {})
if isinstance(model_config, dict):
primary = model_config.get("default", "")
provider = model_config.get("provider", "")
if primary and provider:
chain.append({"model": primary, "provider": provider, "role": "primary"})
elif model_config:
chain.append({"model": str(model_config), "provider": "unknown", "role": "primary"})
auxiliary = config.get("auxiliary", {})
for aux_name, aux_config in auxiliary.items():
if isinstance(aux_config, dict):
aux_model = aux_config.get("model", "")
aux_provider = aux_config.get("provider", "")
if aux_model and aux_provider and aux_provider != "auto":
chain.append({"model": aux_model, "provider": aux_provider, "role": "auxiliary:" + aux_name})
ollama_models = get_ollama_models()
for model in ollama_models[:3]:
if not any(c["model"] == model for c in chain):
chain.append({"model": model, "provider": "ollama", "role": "local-fallback"})
return chain
def run_verification():
"""Run full model fallback verification."""
log("=== Model Fallback Verification ===")
config = load_config()
if not config:
log("ERROR: No config.yaml found")
return {"success": False, "error": "No config file"}
chain = get_fallback_chain(config)
if not chain:
log("ERROR: No models configured")
return {"success": False, "error": "No models in chain"}
results = []
viable_models = []
for entry in chain:
model = entry["model"]
provider = entry["provider"]
role = entry["role"]
api_key = get_provider_api_key(provider) if provider != "ollama" else None
base_url = None
if provider == "custom":
provider_config = config.get("auxiliary", {}).get("vision", {})
base_url = provider_config.get("base_url")
log("Testing [" + role + "] " + model + " (" + provider + ")...")
result = verify_model(model, provider, api_key, base_url)
result["role"] = role
results.append(result)
status = "PASS" if result["viable"] else "FAIL"
details = []
if not result["responded"]:
details.append("no response: " + str(result["error"]))
if not result["meets_minimum"]:
details.append("context " + str(result["context_window"]) + " < " + str(MIN_CONTEXT_WINDOW))
log(" [" + status + "] " + model + " - " + (", ".join(details) if details else "verified"))
if result["viable"]:
viable_models.append(result)
log("=== Results: " + str(len(viable_models)) + "/" + str(len(results)) + " models viable ===")
if not viable_models:
log("CRITICAL: No viable models found!")
for r in results:
log(" - " + r["model"] + " (" + r["provider"] + "): responded=" + str(r["responded"]) + ", context=" + str(r["context_window"]))
return {"success": False, "results": results, "viable": []}
log("Viable models (in priority order):")
for i, r in enumerate(viable_models, 1):
log(" " + str(i) + ". " + r["model"] + " (" + r["provider"] + ") - context: " + str(r["context_window"]) + " tokens [" + r["role"] + "]")
return {
"success": True,
"results": results,
"viable": viable_models,
"primary": viable_models[0] if viable_models else None,
}
def check_single_model(model):
"""Check a specific model."""
if ":" in model:
provider = "ollama"
elif "/" in model:
provider = "openrouter"
else:
provider = "unknown"
config = load_config() or {}
api_key = get_provider_api_key(provider) if provider != "ollama" else None
result = verify_model(model, provider, api_key)
if result["viable"]:
print("PASS: " + model)
print(" Context window: " + str(result["context_window"]) + " tokens")
print(" Response: " + result["response"][:100])
else:
print("FAIL: " + model)
if result["error"]:
print(" Error: " + str(result["error"]))
if not result["meets_minimum"]:
print(" Context window: " + str(result["context_window"]) + " < " + str(MIN_CONTEXT_WINDOW) + " minimum")
return result["viable"]
def check_context_window(model):
"""Check context window for a model."""
if ":" in model:
provider = "ollama"
elif "/" in model:
provider = "openrouter"
else:
provider = "unknown"
window, source = get_context_window(model, provider)
meets = window >= MIN_CONTEXT_WINDOW
print("Model: " + model)
print("Provider: " + provider)
print("Context window: " + str(window) + " tokens (" + source + ")")
print("Minimum (" + str(MIN_CONTEXT_WINDOW) + "): " + ("PASS" if meets else "FAIL"))
return meets
def list_models():
"""List all available models."""
config = load_config() or {}
chain = get_fallback_chain(config)
print("Configured models:")
for entry in chain:
print(" " + entry["model"].ljust(30) + " " + entry["provider"].ljust(15) + " [" + entry["role"] + "]")
ollama = get_ollama_models()
if ollama:
print("")
print("Ollama models:")
for m in ollama:
print(" " + m)
def main():
if len(sys.argv) < 2:
result = run_verification()
sys.exit(0 if result["success"] else 1)
cmd = sys.argv[1]
if cmd == "check" and len(sys.argv) > 2:
model = sys.argv[2]
success = check_single_model(model)
sys.exit(0 if success else 1)
elif cmd == "context" and len(sys.argv) > 2:
model = sys.argv[2]
meets = check_context_window(model)
sys.exit(0 if meets else 1)
elif cmd == "list":
list_models()
elif cmd == "test":
result = run_verification()
sys.exit(0 if result["success"] else 1)
else:
print("Usage:")
print(" model-fallback-verify.py Run full verification")
print(" model-fallback-verify.py check <model> Test specific model")
print(" model-fallback-verify.py context <model> Check context window")
print(" model-fallback-verify.py list List available models")
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -1,3 +1,4 @@
#!/usr/bin/env python3
"""
Full Nostr agent-to-agent communication demo - FINAL WORKING
"""

View File

@@ -1,3 +1,4 @@
#!/usr/bin/env python3
"""
Soul Eval Gate — The Conscience of the Training Pipeline

View File

@@ -0,0 +1,9 @@
- name: Nightly Pipeline Scheduler
schedule: '*/30 18-23,0-8 * * *' # Every 30 min, off-peak hours only
tasks:
- name: Check and start pipelines
shell: "bash scripts/nightly-pipeline-scheduler.sh"
env:
PIPELINE_TOKEN_LIMIT: "500000"
PIPELINE_PEAK_START: "9"
PIPELINE_PEAK_END: "18"

View File

@@ -1,3 +1,4 @@
#!/usr/bin/env python3
import json
from hermes_tools import browser_navigate, browser_vision

View File

@@ -1,3 +1,4 @@
#!/usr/bin/env python3
import json
from hermes_tools import browser_navigate, browser_vision

View File

@@ -0,0 +1,50 @@
# Nightly Pipeline Scheduler
Auto-starts batch pipelines when inference is available.
## What It Does
1. Checks inference provider health (OpenRouter, Ollama, RunPod)
2. Checks if it's off-peak hours (configurable, default: after 6PM)
3. Checks interactive session load (don't fight with live users)
4. Checks daily token budget (configurable limit)
5. Starts the highest-priority incomplete pipeline
## Pipeline Priority Order
| Priority | Pipeline | Deps | Max Tokens |
|----------|----------|------|------------|
| 1 | playground-factory | none | 100,000 |
| 2 | training-factory | none | 150,000 |
| 3 | knowledge-mine | training-factory running | 80,000 |
| 4 | adversary | knowledge-mine running | 50,000 |
| 5 | codebase-genome | none | 120,000 |
## Usage
```bash
# Normal run (used by cron)
./scripts/nightly-pipeline-scheduler.sh
# Dry run (show what would start)
./scripts/nightly-pipeline-scheduler.sh --dry-run
# Status report
./scripts/nightly-pipeline-scheduler.sh --status
# Force start during peak hours
./scripts/nightly-pipeline-scheduler.sh --force
```
## Configuration
Set via environment variables:
- `PIPELINE_TOKEN_LIMIT`: Daily token budget (default: 500,000)
- `PIPELINE_PEAK_START`: Peak hours start (default: 9)
- `PIPELINE_PEAK_END`: Peak hours end (default: 18)
- `HERMES_HOME`: Hermes home directory (default: ~/.hermes)
## Cron
Runs every 30 minutes. Off-peak only (unless --force).
See `cron/pipeline-scheduler.yml`.

View File

@@ -0,0 +1,383 @@
#!/usr/bin/env bash
# nightly-pipeline-scheduler.sh — Auto-start batch pipelines when inference is available.
#
# Checks provider health, pipeline progress, token budget, and interactive load.
# Starts the highest-priority incomplete pipeline that can run.
#
# Usage:
# ./scripts/nightly-pipeline-scheduler.sh # Normal run
# ./scripts/nightly-pipeline-scheduler.sh --dry-run # Show what would start
# ./scripts/nightly-pipeline-scheduler.sh --status # Pipeline status report
set -euo pipefail
# --- Configuration ---
HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
BUDGET_FILE="${HERMES_HOME}/pipeline_budget.json"
STATE_FILE="${HERMES_HOME}/pipeline_state.json"
LOG_FILE="${HERMES_HOME}/logs/pipeline-scheduler.log"
TOKEN_DAILY_LIMIT="${PIPELINE_TOKEN_LIMIT:-500000}"
PEAK_HOURS_START="${PIPELINE_PEAK_START:-9}"
PEAK_HOURS_END="${PIPELINE_PEAK_END:-18}"
# Pipeline definitions (priority order)
# Each pipeline: name, script, max_tokens, dependencies
PIPELINES=(
"playground-factory|scripts/pipeline_playground_factory.sh|100000|none"
"training-factory|scripts/pipeline_training_factory.sh|150000|none"
"knowledge-mine|scripts/pipeline_knowledge_mine.sh|80000|training-factory"
"adversary|scripts/pipeline_adversary.sh|50000|knowledge-mine"
"codebase-genome|scripts/pipeline_codebase_genome.sh|120000|none"
)
# --- Colors ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
NC='\033[0m'
# --- Helpers ---
now_hour() { date +%-H; }
is_peak_hours() {
local h=$(now_hour)
[[ $h -ge $PEAK_HOURS_START && $h -lt $PEAK_HOURS_END ]]
}
ensure_dirs() {
mkdir -p "$(dirname "$LOG_FILE")" "$(dirname "$BUDGET_FILE")" "$(dirname "$STATE_FILE")"
}
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; }
get_budget_used_today() {
if [[ -f "$BUDGET_FILE" ]]; then
local today=$(date +%Y-%m-%d)
python3 -c "
import json, sys
with open('$BUDGET_FILE') as f:
d = json.load(f)
print(d.get('daily', {}).get('$today', {}).get('tokens_used', 0))
" 2>/dev/null || echo 0
else
echo 0
fi
}
get_budget_remaining() {
local used=$(get_budget_used_today)
echo $((TOKEN_DAILY_LIMIT - used))
}
update_budget() {
local pipeline="$1"
local tokens="$2"
local today=$(date +%Y-%m-%d)
python3 -c "
import json, os
path = '$BUDGET_FILE'
d = {}
if os.path.exists(path):
with open(path) as f:
d = json.load(f)
daily = d.setdefault('daily', {})
day = daily.setdefault('$today', {'tokens_used': 0, 'pipelines': {}})
day['tokens_used'] = day.get('tokens_used', 0) + $tokens
day['pipelines']['$pipeline'] = day['pipelines'].get('$pipeline', 0) + $tokens
with open(path, 'w') as f:
json.dump(d, f, indent=2)
"
}
get_pipeline_state() {
if [[ -f "$STATE_FILE" ]]; then
cat "$STATE_FILE"
else
echo "{}"
fi
}
set_pipeline_state() {
local pipeline="$1"
local state="$2" # running, complete, failed, skipped
python3 -c "
import json, os
path = '$STATE_FILE'
d = {}
if os.path.exists(path):
with open(path) as f:
d = json.load(f)
d['$pipeline'] = {'state': '$state', 'updated': '$(date -Iseconds)'}
with open(path, 'w') as f:
json.dump(d, f, indent=2)
"
}
is_pipeline_complete() {
local pipeline="$1"
python3 -c "
import json, os
path = '$STATE_FILE'
if not os.path.exists(path):
print('false')
else:
with open(path) as f:
d = json.load(f)
state = d.get('$pipeline', {}).get('state', 'not_started')
print('true' if state == 'complete' else 'false')
" 2>/dev/null || echo false
}
is_pipeline_running() {
local pipeline="$1"
python3 -c "
import json, os
path = '$STATE_FILE'
if not os.path.exists(path):
print('false')
else:
with open(path) as f:
d = json.load(f)
state = d.get('$pipeline', {}).get('state', 'not_started')
print('true' if state == 'running' else 'false')
" 2>/dev/null || echo false
}
check_dependency() {
local dep="$1"
if [[ "$dep" == "none" ]]; then
return 0
fi
# For knowledge-mine: training-factory must be running or complete
if [[ "$dep" == "training-factory" ]]; then
local state=$(python3 -c "
import json, os
path = '$STATE_FILE'
if not os.path.exists(path):
print('not_started')
else:
with open(path) as f:
d = json.load(f)
print(d.get('training-factory', {}).get('state', 'not_started'))
" 2>/dev/null || echo "not_started")
[[ "$state" == "running" || "$state" == "complete" ]]
return $?
fi
# For adversary: knowledge-mine must be at least 50% done
# Simplified: check if it's running (we'd need progress tracking for 50%)
if [[ "$dep" == "knowledge-mine" ]]; then
local state=$(python3 -c "
import json, os
path = '$STATE_FILE'
if not os.path.exists(path):
print('not_started')
else:
with open(path) as f:
d = json.load(f)
print(d.get('knowledge-mine', {}).get('state', 'not_started'))
" 2>/dev/null || echo "not_started")
[[ "$state" == "running" || "$state" == "complete" ]]
return $?
fi
return 0
}
check_inference_available() {
# Check if any inference provider is responding
# 1. Check OpenRouter
local or_ok=$(curl -s -o /dev/null -w "%{http_code}" \
--connect-timeout 5 "https://openrouter.ai/api/v1/models" 2>/dev/null || echo "000")
# 2. Check local Ollama
local ollama_ok=$(curl -s -o /dev/null -w "%{http_code}" \
--connect-timeout 5 "http://localhost:11434/api/tags" 2>/dev/null || echo "000")
# 3. Check RunPod (if configured)
local runpod_ok="000"
if [[ -n "${RUNPOD_ENDPOINT:-}" ]]; then
runpod_ok=$(curl -s -o /dev/null -w "%{http_code}" \
--connect-timeout 5 "$RUNPOD_ENDPOINT/health" 2>/dev/null || echo "000")
fi
if [[ "$or_ok" == "200" || "$ollama_ok" == "200" || "$runpod_ok" == "200" ]]; then
return 0
fi
return 1
}
check_interactive_load() {
# Check if there are active interactive sessions (don't fight with live users)
# Look for tmux panes with active hermes sessions
local active=$(tmux list-panes -a -F '#{pane_pid} #{pane_current_command}' 2>/dev/null \
| grep -c "hermes\|python3" || echo 0)
# If more than 3 interactive sessions, skip pipeline start
if [[ $active -gt 3 ]]; then
return 1
fi
return 0
}
start_pipeline() {
local name="$1"
local script="$2"
local max_tokens="$3"
local budget_remaining="$4"
local mode="${5:-run}"
if [[ "$budget_remaining" -lt "$max_tokens" ]]; then
log "SKIP $name: insufficient budget ($budget_remaining < $max_tokens tokens)"
return 1
fi
if [[ ! -f "$script" ]]; then
log "SKIP $name: script not found ($script)"
return 1
fi
if [[ "$mode" == "dry-run" ]]; then
log "DRY-RUN: Would start $name (budget: $budget_remaining, needs: $max_tokens)"
return 0
fi
log "START $name (budget: $budget_remaining, max_tokens: $max_tokens)"
set_pipeline_state "$name" "running"
# Run in background, capture output
local log_path="${HERMES_HOME}/logs/pipeline-${name}.log"
bash "$script" --max-tokens "$max_tokens" >> "$log_path" 2>&1 &
local pid=$!
# Wait a moment to check if it started OK
sleep 2
if kill -0 $pid 2>/dev/null; then
log "RUNNING $name (PID: $pid, log: $log_path)"
# Record the PID
python3 -c "
import json, os
path = '$STATE_FILE'
d = {}
if os.path.exists(path):
with open(path) as f:
d = json.load(f)
d['$name']['pid'] = $pid
with open(path, 'w') as f:
json.dump(d, f, indent=2)
"
return 0
else
log "FAIL $name: script exited immediately"
set_pipeline_state "$name" "failed"
return 1
fi
}
# --- Main ---
main() {
local mode="${1:-run}"
ensure_dirs
log "=== Pipeline Scheduler ($mode) ==="
# Check 1: Is inference available?
if ! check_inference_available; then
log "No inference provider available. Skipping all pipelines."
exit 0
fi
log "Inference: AVAILABLE"
# Check 2: Is it peak hours?
if is_peak_hours && [[ "$mode" != "--force" ]]; then
local h=$(now_hour)
log "Peak hours ($h:00). Skipping pipeline start. Use --force to override."
exit 0
fi
log "Off-peak: OK"
# Check 3: Interactive load
if ! check_interactive_load && [[ "$mode" != "--force" ]]; then
log "High interactive load. Skipping pipeline start."
exit 0
fi
log "Interactive load: OK"
# Check 4: Token budget
local budget=$(get_budget_remaining)
log "Token budget remaining: $budget / $TOKEN_DAILY_LIMIT"
if [[ $budget -le 0 ]]; then
log "Daily token budget exhausted. Stopping."
exit 0
fi
# Check 5: Pipeline status
if [[ "$mode" == "--status" ]]; then
echo -e "${CYAN}Pipeline Status:${NC}"
echo "────────────────────────────────────────────────────"
for entry in "${PIPELINES[@]}"; do
IFS='|' read -r name script max_tokens dep <<< "$entry"
local state=$(python3 -c "
import json, os
path = '$STATE_FILE'
if not os.path.exists(path):
print('not_started')
else:
with open(path) as f:
d = json.load(f)
print(d.get('$name', {}).get('state', 'not_started'))
" 2>/dev/null || echo "not_started")
local color=$NC
case "$state" in
running) color=$YELLOW ;;
complete) color=$GREEN ;;
failed) color=$RED ;;
esac
printf " %-25s %b%s%b (max: %s tokens, dep: %s)\n" "$name" "$color" "$state" "$NC" "$max_tokens" "$dep"
done
echo "────────────────────────────────────────────────────"
echo " Budget: $budget / $TOKEN_DAILY_LIMIT tokens remaining"
echo " Peak hours: $PEAK_HOURS_START:00 - $PEAK_HOURS_END:00"
exit 0
fi
# Find and start the highest-priority incomplete pipeline
local started=0
for entry in "${PIPELINES[@]}"; do
IFS='|' read -r name script max_tokens dep <<< "$entry"
# Skip if already running or complete
if [[ "$(is_pipeline_running $name)" == "true" ]]; then
log "SKIP $name: already running"
continue
fi
if [[ "$(is_pipeline_complete $name)" == "true" ]]; then
log "SKIP $name: already complete"
continue
fi
# Check dependency
if ! check_dependency "$dep"; then
log "SKIP $name: dependency $dep not met"
continue
fi
# Try to start
if start_pipeline "$name" "$script" "$max_tokens" "$budget" "$mode"; then
started=1
# Only start one pipeline per run (let it claim tokens before next check)
# Exception: playground-factory and training-factory can run in parallel
if [[ "$name" != "playground-factory" && "$name" != "training-factory" ]]; then
break
fi
fi
done
if [[ $started -eq 0 ]]; then
log "No pipelines to start (all complete, running, or blocked)."
fi
log "=== Pipeline Scheduler done ==="
}
main "$@"

View File

@@ -1,3 +1,4 @@
#!/usr/bin/env python3
import json
from hermes_tools import browser_navigate, browser_vision