Compare commits
3 Commits
burn/372-1
...
burn/272-1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81fcd51d2f | ||
| 5180c172fa | |||
|
|
b62fa0ec13 |
@@ -544,78 +544,8 @@ def _run_job_script(script_path: str) -> tuple[bool, str]:
|
||||
return False, f"Script execution failed: {exc}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Provider mismatch detection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_PROVIDER_ALIASES: dict[str, set[str]] = {
|
||||
"ollama": {"ollama", "local ollama", "localhost:11434"},
|
||||
"anthropic": {"anthropic", "claude", "sonnet", "opus", "haiku"},
|
||||
"nous": {"nous", "mimo", "nousresearch"},
|
||||
"openrouter": {"openrouter"},
|
||||
"kimi": {"kimi", "moonshot", "kimi-coding"},
|
||||
"zai": {"zai", "glm", "zhipu"},
|
||||
"openai": {"openai", "gpt", "codex"},
|
||||
"gemini": {"gemini", "google"},
|
||||
}
|
||||
|
||||
|
||||
def _classify_runtime(provider: str, model: str) -> str:
|
||||
"""Return 'local' | 'cloud' | 'unknown' for a provider/model pair."""
|
||||
p = (provider or "").strip().lower()
|
||||
m = (model or "").strip().lower()
|
||||
# Explicit cloud providers or prefixed model names → cloud
|
||||
if p and p not in ("ollama", "local"):
|
||||
return "cloud"
|
||||
if "/" in m and m.split("/")[0] in ("nous", "openrouter", "anthropic", "openai", "zai", "kimi", "gemini", "minimax"):
|
||||
return "cloud"
|
||||
# Ollama / local / empty provider with non-prefixed model → local
|
||||
if p in ("ollama", "local") or (not p and m):
|
||||
return "local"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _detect_provider_mismatch(prompt: str, active_provider: str) -> Optional[str]:
|
||||
"""Return the stale provider group referenced in *prompt*, or None."""
|
||||
if not active_provider or not prompt:
|
||||
return None
|
||||
prompt_lower = prompt.lower()
|
||||
active_lower = active_provider.lower().strip()
|
||||
# Find active group
|
||||
active_group: Optional[str] = None
|
||||
for group, aliases in _PROVIDER_ALIASES.items():
|
||||
if active_lower in aliases or active_lower.startswith(group):
|
||||
active_group = group
|
||||
break
|
||||
if not active_group:
|
||||
return None
|
||||
# Check for references to a different group
|
||||
for group, aliases in _PROVIDER_ALIASES.items():
|
||||
if group == active_group:
|
||||
continue
|
||||
for alias in aliases:
|
||||
if alias in prompt_lower:
|
||||
return group
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt builder
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _build_job_prompt(
|
||||
job: dict,
|
||||
*,
|
||||
runtime_model: str = "",
|
||||
runtime_provider: str = "",
|
||||
) -> str:
|
||||
"""Build the effective prompt for a cron job.
|
||||
|
||||
Args:
|
||||
job: The cron job dict.
|
||||
runtime_model: Resolved model name (e.g. "xiaomi/mimo-v2-pro").
|
||||
runtime_provider: Resolved provider name (e.g. "nous", "openrouter").
|
||||
"""
|
||||
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")
|
||||
|
||||
@@ -647,36 +577,6 @@ def _build_job_prompt(
|
||||
|
||||
# Always prepend cron execution guidance so the agent knows how
|
||||
# delivery works and can suppress delivery when appropriate.
|
||||
#
|
||||
# Runtime context injection — tells the agent what it can actually do.
|
||||
# Prevents prompts written for local Ollama from assuming SSH / local
|
||||
# services when the job is now running on a cloud API.
|
||||
_runtime_block = ""
|
||||
if runtime_model or runtime_provider:
|
||||
_kind = _classify_runtime(runtime_provider, runtime_model)
|
||||
_notes: list[str] = []
|
||||
if runtime_model:
|
||||
_notes.append(f"MODEL: {runtime_model}")
|
||||
if runtime_provider:
|
||||
_notes.append(f"PROVIDER: {runtime_provider}")
|
||||
if _kind == "local":
|
||||
_notes.append(
|
||||
"RUNTIME: local — you have access to the local machine, "
|
||||
"local Ollama, SSH keys, and filesystem"
|
||||
)
|
||||
elif _kind == "cloud":
|
||||
_notes.append(
|
||||
"RUNTIME: cloud API — you do NOT have local machine access. "
|
||||
"Do NOT assume you can SSH into servers, check local Ollama, "
|
||||
"or access local filesystem paths. Use terminal tools only "
|
||||
"for commands that work from this environment."
|
||||
)
|
||||
if _notes:
|
||||
_runtime_block = (
|
||||
"[SYSTEM: RUNTIME CONTEXT — "
|
||||
+ "; ".join(_notes)
|
||||
+ ". Adjust your approach based on these capabilities.]\\n\\n"
|
||||
)
|
||||
cron_hint = (
|
||||
"[SYSTEM: You are running as a scheduled cron job. "
|
||||
"DELIVERY: Your final response will be automatically delivered "
|
||||
@@ -696,7 +596,7 @@ def _build_job_prompt(
|
||||
"\"[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 []
|
||||
@@ -766,36 +666,7 @@ def run_job(job: dict) -> tuple[bool, str, str, Optional[str]]:
|
||||
|
||||
job_id = job["id"]
|
||||
job_name = job["name"]
|
||||
|
||||
# ── Early model/provider resolution ───────────────────────────────────
|
||||
# We need the model name before building the prompt so the runtime
|
||||
# context block can be injected. Full provider resolution happens
|
||||
# later (smart routing, etc.) but the basic name is enough here.
|
||||
_early_model = job.get("model") or os.getenv("HERMES_MODEL") or ""
|
||||
_early_provider = os.getenv("HERMES_PROVIDER", "")
|
||||
if not _early_model:
|
||||
try:
|
||||
import yaml
|
||||
_cfg_path = str(_hermes_home / "config.yaml")
|
||||
if os.path.exists(_cfg_path):
|
||||
with open(_cfg_path) as _f:
|
||||
_cfg_early = yaml.safe_load(_f) or {}
|
||||
_mc = _cfg_early.get("model", {})
|
||||
if isinstance(_mc, str):
|
||||
_early_model = _mc
|
||||
elif isinstance(_mc, dict):
|
||||
_early_model = _mc.get("default", "")
|
||||
except Exception:
|
||||
pass
|
||||
# Derive provider from model prefix when not explicitly set
|
||||
if not _early_provider and "/" in _early_model:
|
||||
_early_provider = _early_model.split("/")[0]
|
||||
|
||||
prompt = _build_job_prompt(
|
||||
job,
|
||||
runtime_model=_early_model,
|
||||
runtime_provider=_early_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')}"
|
||||
|
||||
@@ -891,20 +762,6 @@ def run_job(job: dict) -> tuple[bool, str, str, Optional[str]]:
|
||||
message = format_runtime_provider_error(exc)
|
||||
raise RuntimeError(message) from exc
|
||||
|
||||
# ── Provider mismatch warning ─────────────────────────────────
|
||||
# If the job prompt references a provider different from the one
|
||||
# we actually resolved, warn so operators know which prompts are stale.
|
||||
_resolved_provider = runtime.get("provider", "") or ""
|
||||
_raw_prompt = job.get("prompt", "")
|
||||
_mismatch = _detect_provider_mismatch(_raw_prompt, _resolved_provider)
|
||||
if _mismatch:
|
||||
logger.warning(
|
||||
"Job '%s' prompt references '%s' but active provider is '%s' — "
|
||||
"agent will be told to adapt via runtime context. "
|
||||
"Consider updating this job's prompt.",
|
||||
job_name, _mismatch, _resolved_provider,
|
||||
)
|
||||
|
||||
from agent.smart_model_routing import resolve_turn_route
|
||||
turn_route = resolve_turn_route(
|
||||
prompt,
|
||||
|
||||
104
hermes_state.py
104
hermes_state.py
@@ -32,7 +32,7 @@ T = TypeVar("T")
|
||||
|
||||
DEFAULT_DB_PATH = get_hermes_home() / "state.db"
|
||||
|
||||
SCHEMA_VERSION = 6
|
||||
SCHEMA_VERSION = 7
|
||||
|
||||
SCHEMA_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS schema_version (
|
||||
@@ -66,6 +66,7 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
cost_source TEXT,
|
||||
pricing_version TEXT,
|
||||
title TEXT,
|
||||
profile TEXT,
|
||||
FOREIGN KEY (parent_session_id) REFERENCES sessions(id)
|
||||
);
|
||||
|
||||
@@ -86,6 +87,7 @@ CREATE TABLE IF NOT EXISTS messages (
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_source ON sessions(source);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_profile ON sessions(profile);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_parent ON sessions(parent_session_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_started ON sessions(started_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, timestamp);
|
||||
@@ -330,6 +332,19 @@ class SessionDB:
|
||||
except sqlite3.OperationalError:
|
||||
pass # Column already exists
|
||||
cursor.execute("UPDATE schema_version SET version = 6")
|
||||
if current_version < 7:
|
||||
# v7: add profile column to sessions for profile isolation (#323)
|
||||
try:
|
||||
cursor.execute('ALTER TABLE sessions ADD COLUMN "profile" TEXT')
|
||||
except sqlite3.OperationalError:
|
||||
pass # Column already exists
|
||||
try:
|
||||
cursor.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_sessions_profile ON sessions(profile)"
|
||||
)
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
cursor.execute("UPDATE schema_version SET version = 7")
|
||||
|
||||
# Unique title index — always ensure it exists (safe to run after migrations
|
||||
# since the title column is guaranteed to exist at this point)
|
||||
@@ -362,13 +377,19 @@ class SessionDB:
|
||||
system_prompt: str = None,
|
||||
user_id: str = None,
|
||||
parent_session_id: str = None,
|
||||
profile: str = None,
|
||||
) -> str:
|
||||
"""Create a new session record. Returns the session_id."""
|
||||
"""Create a new session record. Returns the session_id.
|
||||
|
||||
Args:
|
||||
profile: Profile name for session isolation. When set, sessions
|
||||
are tagged so queries can filter by profile. (#323)
|
||||
"""
|
||||
def _do(conn):
|
||||
conn.execute(
|
||||
"""INSERT OR IGNORE INTO sessions (id, source, user_id, model, model_config,
|
||||
system_prompt, parent_session_id, started_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
system_prompt, parent_session_id, profile, started_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
session_id,
|
||||
source,
|
||||
@@ -377,6 +398,7 @@ class SessionDB:
|
||||
json.dumps(model_config) if model_config else None,
|
||||
system_prompt,
|
||||
parent_session_id,
|
||||
profile,
|
||||
time.time(),
|
||||
),
|
||||
)
|
||||
@@ -505,19 +527,23 @@ class SessionDB:
|
||||
session_id: str,
|
||||
source: str = "unknown",
|
||||
model: str = None,
|
||||
profile: str = None,
|
||||
) -> None:
|
||||
"""Ensure a session row exists, creating it with minimal metadata if absent.
|
||||
|
||||
Used by _flush_messages_to_session_db to recover from a failed
|
||||
create_session() call (e.g. transient SQLite lock at agent startup).
|
||||
INSERT OR IGNORE is safe to call even when the row already exists.
|
||||
|
||||
Args:
|
||||
profile: Profile name for session isolation. (#323)
|
||||
"""
|
||||
def _do(conn):
|
||||
conn.execute(
|
||||
"""INSERT OR IGNORE INTO sessions
|
||||
(id, source, model, started_at)
|
||||
VALUES (?, ?, ?, ?)""",
|
||||
(session_id, source, model, time.time()),
|
||||
(id, source, model, profile, started_at)
|
||||
VALUES (?, ?, ?, ?, ?)""",
|
||||
(session_id, source, model, profile, time.time()),
|
||||
)
|
||||
self._execute_write(_do)
|
||||
|
||||
@@ -788,6 +814,7 @@ class SessionDB:
|
||||
limit: int = 20,
|
||||
offset: int = 0,
|
||||
include_children: bool = False,
|
||||
profile: str = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""List sessions with preview (first user message) and last active timestamp.
|
||||
|
||||
@@ -799,6 +826,10 @@ class SessionDB:
|
||||
|
||||
By default, child sessions (subagent runs, compression continuations)
|
||||
are excluded. Pass ``include_children=True`` to include them.
|
||||
|
||||
Args:
|
||||
profile: Filter sessions to this profile name. Pass None to see all.
|
||||
(#323)
|
||||
"""
|
||||
where_clauses = []
|
||||
params = []
|
||||
@@ -813,6 +844,9 @@ class SessionDB:
|
||||
placeholders = ",".join("?" for _ in exclude_sources)
|
||||
where_clauses.append(f"s.source NOT IN ({placeholders})")
|
||||
params.extend(exclude_sources)
|
||||
if profile:
|
||||
where_clauses.append("s.profile = ?")
|
||||
params.append(profile)
|
||||
|
||||
where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
|
||||
query = f"""
|
||||
@@ -1158,34 +1192,52 @@ class SessionDB:
|
||||
source: str = None,
|
||||
limit: int = 20,
|
||||
offset: int = 0,
|
||||
profile: str = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""List sessions, optionally filtered by source."""
|
||||
"""List sessions, optionally filtered by source and profile.
|
||||
|
||||
Args:
|
||||
profile: Filter sessions to this profile name. Pass None to see all.
|
||||
(#323)
|
||||
"""
|
||||
where_clauses = []
|
||||
params = []
|
||||
if source:
|
||||
where_clauses.append("source = ?")
|
||||
params.append(source)
|
||||
if profile:
|
||||
where_clauses.append("profile = ?")
|
||||
params.append(profile)
|
||||
|
||||
where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
|
||||
query = f"SELECT * FROM sessions {where_sql} ORDER BY started_at DESC LIMIT ? OFFSET ?"
|
||||
params.extend([limit, offset])
|
||||
with self._lock:
|
||||
if source:
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM sessions WHERE source = ? ORDER BY started_at DESC LIMIT ? OFFSET ?",
|
||||
(source, limit, offset),
|
||||
)
|
||||
else:
|
||||
cursor = self._conn.execute(
|
||||
"SELECT * FROM sessions ORDER BY started_at DESC LIMIT ? OFFSET ?",
|
||||
(limit, offset),
|
||||
)
|
||||
cursor = self._conn.execute(query, params)
|
||||
return [dict(row) for row in cursor.fetchall()]
|
||||
|
||||
# =========================================================================
|
||||
# Utility
|
||||
# =========================================================================
|
||||
|
||||
def session_count(self, source: str = None) -> int:
|
||||
"""Count sessions, optionally filtered by source."""
|
||||
def session_count(self, source: str = None, profile: str = None) -> int:
|
||||
"""Count sessions, optionally filtered by source and profile.
|
||||
|
||||
Args:
|
||||
profile: Filter to this profile name. Pass None to count all. (#323)
|
||||
"""
|
||||
where_clauses = []
|
||||
params = []
|
||||
if source:
|
||||
where_clauses.append("source = ?")
|
||||
params.append(source)
|
||||
if profile:
|
||||
where_clauses.append("profile = ?")
|
||||
params.append(profile)
|
||||
|
||||
where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
|
||||
with self._lock:
|
||||
if source:
|
||||
cursor = self._conn.execute(
|
||||
"SELECT COUNT(*) FROM sessions WHERE source = ?", (source,)
|
||||
)
|
||||
else:
|
||||
cursor = self._conn.execute("SELECT COUNT(*) FROM sessions")
|
||||
cursor = self._conn.execute(f"SELECT COUNT(*) FROM sessions {where_sql}", params)
|
||||
return cursor.fetchone()[0]
|
||||
|
||||
def message_count(self, session_id: str = None) -> int:
|
||||
|
||||
368
scripts/deploy_synapse.py
Executable file
368
scripts/deploy_synapse.py
Executable file
@@ -0,0 +1,368 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy Synapse Matrix homeserver on a remote VPS.
|
||||
|
||||
Phase 1 of Matrix integration (Epic #269). Deploys Synapse via Docker
|
||||
on the target host, creates a bot account, and configures Hermes to
|
||||
connect to it.
|
||||
|
||||
Usage:
|
||||
python scripts/deploy_synapse.py --host <vps-host> --user root --domain matrix.example.com
|
||||
python scripts/deploy_synapse.py --host 143.198.27.163 --user root --domain matrix.timmy.dev --dry-run
|
||||
|
||||
Requires SSH access to the target host.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _ssh_cmd(host: str, user: str, port: int = 22, key_path: str = "") -> list:
|
||||
"""Build base SSH command."""
|
||||
cmd = ["ssh", "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=15"]
|
||||
if port != 22:
|
||||
cmd.extend(["-p", str(port)])
|
||||
if key_path:
|
||||
cmd.extend(["-i", key_path])
|
||||
cmd.append(f"{user}@{host}")
|
||||
return cmd
|
||||
|
||||
|
||||
def _run_remote(cmd_base: list, command: str, timeout: int = 60, dry_run: bool = False) -> tuple:
|
||||
"""Run a command on the remote host. Returns (success, stdout, stderr)."""
|
||||
full_cmd = cmd_base + [command]
|
||||
if dry_run:
|
||||
print(f" [DRY RUN] Would execute: {command[:200]}")
|
||||
return True, "", ""
|
||||
try:
|
||||
result = subprocess.run(full_cmd, capture_output=True, text=True, timeout=timeout)
|
||||
return result.returncode == 0, result.stdout, result.stderr
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "", f"Command timed out after {timeout}s"
|
||||
|
||||
|
||||
def check_prerequisites(cmd_base: list) -> bool:
|
||||
"""Check that Docker and docker-compose are available on the remote host."""
|
||||
print("\n[1/6] Checking prerequisites...")
|
||||
|
||||
checks = [
|
||||
("Docker", "command -v docker && docker --version"),
|
||||
("Docker Compose", "command -v docker-compose || docker compose version 2>/dev/null"),
|
||||
("curl", "command -v curl"),
|
||||
]
|
||||
|
||||
all_ok = True
|
||||
for name, check_cmd in checks:
|
||||
ok, stdout, stderr = _run_remote(cmd_base, check_cmd, timeout=15)
|
||||
if ok:
|
||||
print(f" ✓ {name}: {stdout.strip()[:80]}")
|
||||
else:
|
||||
print(f" ✗ {name}: not found")
|
||||
all_ok = False
|
||||
|
||||
return all_ok
|
||||
|
||||
|
||||
def install_docker(cmd_base: list, dry_run: bool = False) -> bool:
|
||||
"""Install Docker on the remote host if not present."""
|
||||
print("\n[1b] Installing Docker...")
|
||||
install_cmd = (
|
||||
"curl -fsSL https://get.docker.com | sh && "
|
||||
"systemctl enable docker && systemctl start docker"
|
||||
)
|
||||
ok, stdout, stderr = _run_remote(cmd_base, install_cmd, timeout=120, dry_run=dry_run)
|
||||
if ok or dry_run:
|
||||
print(" ✓ Docker installed")
|
||||
return True
|
||||
print(f" ✗ Docker install failed: {stderr[:200]}")
|
||||
return False
|
||||
|
||||
|
||||
def deploy_synapse(cmd_base: list, domain: str, data_dir: str = "/opt/synapse",
|
||||
dry_run: bool = False) -> bool:
|
||||
"""Deploy Synapse via Docker on the remote host."""
|
||||
print(f"\n[2/6] Deploying Synapse for {domain}...")
|
||||
|
||||
# Create data directory
|
||||
ok, _, _ = _run_remote(cmd_base, f"mkdir -p {data_dir}/data", dry_run=dry_run)
|
||||
|
||||
# Generate homeserver.yaml if not exists
|
||||
homeserver_yaml = f"""# Synapse homeserver configuration
|
||||
# Generated by deploy_synapse.py for {domain}
|
||||
|
||||
server_name: "{domain}"
|
||||
pid_file: /data/homeserver.pid
|
||||
listeners:
|
||||
- port: 8008
|
||||
tls: false
|
||||
type: http
|
||||
x_forwarded: true
|
||||
resources:
|
||||
- names: [client, federation]
|
||||
compress: false
|
||||
|
||||
database:
|
||||
name: sqlite3
|
||||
args:
|
||||
database: /data/homeserver.db
|
||||
|
||||
media_store_path: /data/media_store
|
||||
signing_key_path: /data/signing.key
|
||||
log_config: "/data/{domain}.log.config"
|
||||
|
||||
suppress_key_server_warning: true
|
||||
enable_registration: false
|
||||
enable_registration_without_verification: false
|
||||
report_stats: false
|
||||
|
||||
# Allow guest access for initial testing (disable in production)
|
||||
allow_guest_access: false
|
||||
|
||||
# Trusted key servers
|
||||
trusted_key_servers:
|
||||
- server_name: "matrix.org"
|
||||
"""
|
||||
|
||||
# Write homeserver.yaml
|
||||
write_cmd = f"cat > {data_dir}/homeserver.yaml << 'HOMESERVER_EOF'\n{homeserver_yaml}HOMESERVER_EOF"
|
||||
ok, _, _ = _run_remote(cmd_base, write_cmd, dry_run=dry_run)
|
||||
if not ok and not dry_run:
|
||||
print(" ✗ Failed to write homeserver.yaml")
|
||||
return False
|
||||
|
||||
# Generate log config
|
||||
log_config = f"""version: 1
|
||||
|
||||
formatters:
|
||||
precise:
|
||||
format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s'
|
||||
|
||||
handlers:
|
||||
console:
|
||||
class: logging.StreamHandler
|
||||
formatter: precise
|
||||
level: INFO
|
||||
|
||||
loggers:
|
||||
synapse.storage.SQL:
|
||||
level: WARNING
|
||||
|
||||
root:
|
||||
level: INFO
|
||||
handlers: [console]
|
||||
"""
|
||||
|
||||
write_log_cmd = f"cat > {data_dir}/data/{domain}.log.config << 'LOG_EOF'\n{log_config}LOG_EOF"
|
||||
_run_remote(cmd_base, write_log_cmd, dry_run=dry_run)
|
||||
|
||||
# Docker run command
|
||||
docker_cmd = (
|
||||
f"docker run -d --name synapse "
|
||||
f"--restart unless-stopped "
|
||||
f"-v {data_dir}/data:/data "
|
||||
f"-p 127.0.0.1:8008:8008 "
|
||||
f"-e SYNAPSE_CONFIG_PATH=/data/homeserver.yaml "
|
||||
f"matrixdotorg/synapse:latest"
|
||||
)
|
||||
|
||||
# Stop existing if running
|
||||
_run_remote(cmd_base, "docker stop synapse 2>/dev/null; docker rm synapse 2>/dev/null", dry_run=dry_run)
|
||||
|
||||
ok, stdout, stderr = _run_remote(cmd_base, docker_cmd, timeout=120, dry_run=dry_run)
|
||||
if not ok and not dry_run:
|
||||
print(f" ✗ Docker run failed: {stderr[:200]}")
|
||||
return False
|
||||
if not dry_run:
|
||||
print(f" ✓ Synapse container started: {stdout.strip()[:12]}")
|
||||
else:
|
||||
print(" ✓ Synapse container (dry run)")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def wait_for_synapse(cmd_base: list, max_wait: int = 60, dry_run: bool = False) -> bool:
|
||||
"""Wait for Synapse to become healthy."""
|
||||
print("\n[3/6] Waiting for Synapse to start...")
|
||||
if dry_run:
|
||||
print(" ✓ Skipped (dry run)")
|
||||
return True
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < max_wait:
|
||||
ok, stdout, _ = _run_remote(
|
||||
cmd_base,
|
||||
"curl -sf http://127.0.0.1:8008/_matrix/client/versions 2>/dev/null | head -c 100",
|
||||
timeout=10,
|
||||
)
|
||||
if ok and "versions" in stdout:
|
||||
elapsed = int(time.time() - start)
|
||||
print(f" ✓ Synapse is up (took {elapsed}s)")
|
||||
return True
|
||||
time.sleep(3)
|
||||
|
||||
print(f" ✗ Synapse did not start within {max_wait}s")
|
||||
return False
|
||||
|
||||
|
||||
def create_bot_account(cmd_base: list, domain: str, data_dir: str = "/opt/synapse",
|
||||
bot_user: str = "hermes-bot", bot_password: str = "",
|
||||
dry_run: bool = False) -> dict:
|
||||
"""Create the Hermes bot account on the homeserver."""
|
||||
print(f"\n[4/6] Creating bot account @{bot_user}:{domain}...")
|
||||
|
||||
if not bot_password:
|
||||
import secrets
|
||||
bot_password = secrets.token_urlsafe(24)
|
||||
|
||||
# Register user via Synapse admin API
|
||||
register_cmd = (
|
||||
f"docker exec synapse register_new_matrix_user "
|
||||
f"http://localhost:8008 "
|
||||
f"-c /data/homeserver.yaml "
|
||||
f"-u {bot_user} "
|
||||
f"-p '{bot_password}' "
|
||||
f"--no-admin"
|
||||
)
|
||||
|
||||
ok, stdout, stderr = _run_remote(cmd_base, register_cmd, timeout=30, dry_run=dry_run)
|
||||
result = {
|
||||
"user_id": f"@{bot_user}:{domain}",
|
||||
"password": bot_password,
|
||||
"homeserver_url": f"https://{domain}",
|
||||
}
|
||||
|
||||
if ok or dry_run:
|
||||
print(f" ✓ Bot account created: {result['user_id']}")
|
||||
elif "User ID already taken" in stderr:
|
||||
print(f" ⚠ Bot account already exists: @{bot_user}:{domain}")
|
||||
else:
|
||||
print(f" ⚠ Bot registration: {stderr[:100]}")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def login_and_get_token(cmd_base: list, domain: str, bot_user: str, bot_password: str,
|
||||
dry_run: bool = False) -> str:
|
||||
"""Login and get an access token for the bot."""
|
||||
print("\n[5/6] Getting access token...")
|
||||
|
||||
if dry_run:
|
||||
print(" ✓ Skipped (dry run)")
|
||||
return "dry-run-token"
|
||||
|
||||
login_data = json.dumps({
|
||||
"type": "m.login.password",
|
||||
"user": bot_user,
|
||||
"password": bot_password,
|
||||
"device_id": "HERMES_BOT",
|
||||
})
|
||||
|
||||
login_cmd = (
|
||||
f"curl -sf -X POST http://127.0.0.1:8008/_matrix/client/v3/login "
|
||||
f"-H 'Content-Type: application/json' "
|
||||
f"-d '{login_data}'"
|
||||
)
|
||||
|
||||
ok, stdout, _ = _run_remote(cmd_base, login_cmd, timeout=15)
|
||||
if ok:
|
||||
try:
|
||||
resp = json.loads(stdout)
|
||||
token = resp.get("access_token", "")
|
||||
device_id = resp.get("device_id", "")
|
||||
if token:
|
||||
print(f" ✓ Access token obtained (device: {device_id})")
|
||||
return token
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
print(" ✗ Failed to get access token")
|
||||
return ""
|
||||
|
||||
|
||||
def print_config(domain: str, bot_user: str, token: str, bot_password: str):
|
||||
"""Print the configuration needed for Hermes."""
|
||||
print("\n[6/6] Configuration for Hermes")
|
||||
print("=" * 60)
|
||||
print(f"Add these to ~/.hermes/.env:")
|
||||
print()
|
||||
print(f"MATRIX_HOMESERVER=https://{domain}")
|
||||
print(f"MATRIX_ACCESS_TOKEN={token}")
|
||||
print(f"MATRIX_USER_ID=@{bot_user}:{domain}")
|
||||
print(f"MATRIX_DEVICE_ID=HERMES_BOT")
|
||||
print()
|
||||
print(f"Bot password (save securely): {bot_password}")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Deploy Synapse on a VPS for Hermes Matrix integration")
|
||||
parser.add_argument("--host", required=True, help="VPS hostname or IP")
|
||||
parser.add_argument("--user", default="root", help="SSH user (default: root)")
|
||||
parser.add_argument("--port", type=int, default=22, help="SSH port")
|
||||
parser.add_argument("--key", default="", help="SSH key path")
|
||||
parser.add_argument("--domain", required=True, help="Matrix domain (e.g., matrix.timmy.dev)")
|
||||
parser.add_argument("--data-dir", default="/opt/synapse", help="Synapse data directory")
|
||||
parser.add_argument("--bot-user", default="hermes-bot", help="Bot username")
|
||||
parser.add_argument("--bot-password", default="", help="Bot password (auto-generated if empty)")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Print commands without executing")
|
||||
parser.add_argument("--skip-docker-install", action="store_true", help="Skip Docker installation")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
print(f"Synapse Deployment for Hermes")
|
||||
print(f" Host: {args.user}@{args.host}:{args.port}")
|
||||
print(f" Domain: {args.domain}")
|
||||
print(f" Data dir: {args.data_dir}")
|
||||
if args.dry_run:
|
||||
print(f" Mode: DRY RUN")
|
||||
|
||||
cmd_base = _ssh_cmd(args.host, args.user, args.port, args.key)
|
||||
|
||||
# Step 1: Prerequisites
|
||||
if not check_prerequisites(cmd_base):
|
||||
if not args.skip_docker_install:
|
||||
if not install_docker(cmd_base, args.dry_run):
|
||||
print("\n✗ Deployment failed: could not install Docker")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("\n✗ Deployment failed: prerequisites not met")
|
||||
sys.exit(1)
|
||||
|
||||
# Step 2: Deploy Synapse
|
||||
if not deploy_synapse(cmd_base, args.domain, args.data_dir, args.dry_run):
|
||||
print("\n✗ Deployment failed: could not start Synapse")
|
||||
sys.exit(1)
|
||||
|
||||
# Step 3: Wait for healthy
|
||||
if not wait_for_synapse(cmd_base, dry_run=args.dry_run):
|
||||
print("\n✗ Deployment failed: Synapse not healthy")
|
||||
sys.exit(1)
|
||||
|
||||
# Step 4: Create bot account
|
||||
account = create_bot_account(
|
||||
cmd_base, args.domain, args.data_dir,
|
||||
args.bot_user, args.bot_password, args.dry_run,
|
||||
)
|
||||
|
||||
# Step 5: Get access token
|
||||
token = login_and_get_token(
|
||||
cmd_base, args.domain, args.bot_user,
|
||||
account["password"], args.dry_run,
|
||||
)
|
||||
|
||||
# Step 6: Print config
|
||||
print_config(args.domain, args.bot_user, token, account["password"])
|
||||
|
||||
print("\n✓ Synapse deployment complete!")
|
||||
print(f" Next: configure Nginx reverse proxy for https://{domain}")
|
||||
print(f" Then: add the env vars above to ~/.hermes/.env and restart the gateway")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,129 +0,0 @@
|
||||
"""Tests for cron scheduler: provider mismatch detection, runtime classification,
|
||||
and capability-aware prompt building."""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _import_scheduler():
|
||||
"""Import the scheduler module, bypassing __init__.py re-exports that may
|
||||
reference symbols not yet merged upstream."""
|
||||
import importlib.util
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"cron.scheduler", str(Path(__file__).resolve().parent.parent / "cron" / "scheduler.py"),
|
||||
)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
try:
|
||||
spec.loader.exec_module(mod)
|
||||
except Exception:
|
||||
pass # some top-level imports may fail in CI; functions are still defined
|
||||
return mod
|
||||
|
||||
|
||||
_sched = _import_scheduler()
|
||||
_classify_runtime = _sched._classify_runtime
|
||||
_detect_provider_mismatch = _sched._detect_provider_mismatch
|
||||
_build_job_prompt = _sched._build_job_prompt
|
||||
|
||||
|
||||
# ── _classify_runtime ─────────────────────────────────────────────────────
|
||||
|
||||
class TestClassifyRuntime:
|
||||
def test_ollama_is_local(self):
|
||||
assert _classify_runtime("ollama", "qwen2.5:7b") == "local"
|
||||
|
||||
def test_empty_provider_is_local(self):
|
||||
assert _classify_runtime("", "my-local-model") == "local"
|
||||
|
||||
def test_prefixed_model_is_cloud(self):
|
||||
assert _classify_runtime("", "nous/mimo-v2-pro") == "cloud"
|
||||
|
||||
def test_nous_provider_is_cloud(self):
|
||||
assert _classify_runtime("nous", "mimo-v2-pro") == "cloud"
|
||||
|
||||
def test_openrouter_is_cloud(self):
|
||||
assert _classify_runtime("openrouter", "anthropic/claude-sonnet-4") == "cloud"
|
||||
|
||||
def test_empty_both_is_unknown(self):
|
||||
assert _classify_runtime("", "") == "unknown"
|
||||
|
||||
|
||||
# ── _detect_provider_mismatch ─────────────────────────────────────────────
|
||||
|
||||
class TestDetectProviderMismatch:
|
||||
def test_no_mismatch_when_not_mentioned(self):
|
||||
assert _detect_provider_mismatch("Check system health", "nous") is None
|
||||
|
||||
def test_detects_ollama_when_nous_active(self):
|
||||
assert _detect_provider_mismatch("Check Ollama is responding", "nous") == "ollama"
|
||||
|
||||
def test_detects_anthropic_when_nous_active(self):
|
||||
assert _detect_provider_mismatch("Use Claude to analyze", "nous") == "anthropic"
|
||||
|
||||
def test_no_mismatch_same_provider(self):
|
||||
assert _detect_provider_mismatch("Check Ollama models", "ollama") is None
|
||||
|
||||
def test_empty_prompt(self):
|
||||
assert _detect_provider_mismatch("", "nous") is None
|
||||
|
||||
def test_empty_provider(self):
|
||||
assert _detect_provider_mismatch("Check Ollama", "") is None
|
||||
|
||||
def test_detects_kimi_when_openrouter(self):
|
||||
assert _detect_provider_mismatch("Use Kimi for coding", "openrouter") == "kimi"
|
||||
|
||||
def test_detects_glm_when_nous(self):
|
||||
assert _detect_provider_mismatch("Use GLM for analysis", "nous") == "zai"
|
||||
|
||||
|
||||
# ── _build_job_prompt ─────────────────────────────────────────────────────
|
||||
|
||||
class TestBuildJobPrompt:
|
||||
def _job(self, prompt="Do something"):
|
||||
return {"prompt": prompt, "skills": []}
|
||||
|
||||
def test_no_runtime_no_block(self):
|
||||
result = _build_job_prompt(self._job())
|
||||
assert "Do something" in result
|
||||
assert "RUNTIME CONTEXT" not in result
|
||||
|
||||
def test_cloud_runtime_injected(self):
|
||||
result = _build_job_prompt(
|
||||
self._job(),
|
||||
runtime_model="xiaomi/mimo-v2-pro",
|
||||
runtime_provider="nous",
|
||||
)
|
||||
assert "MODEL: xiaomi/mimo-v2-pro" in result
|
||||
assert "PROVIDER: nous" in result
|
||||
assert "cloud API" in result
|
||||
assert "Do NOT assume you can SSH" in result
|
||||
|
||||
def test_local_runtime_injected(self):
|
||||
result = _build_job_prompt(
|
||||
self._job(),
|
||||
runtime_model="qwen2.5:7b",
|
||||
runtime_provider="ollama",
|
||||
)
|
||||
assert "RUNTIME: local" in result
|
||||
assert "SSH keys" in result
|
||||
|
||||
def test_empty_runtime_no_block(self):
|
||||
result = _build_job_prompt(self._job(), runtime_model="", runtime_provider="")
|
||||
assert "RUNTIME CONTEXT" not in result
|
||||
|
||||
def test_cron_hint_always_present(self):
|
||||
result = _build_job_prompt(self._job())
|
||||
assert "scheduled cron job" in result
|
||||
assert "[SYSTEM:" in result
|
||||
|
||||
def test_runtime_block_before_cron_hint(self):
|
||||
result = _build_job_prompt(
|
||||
self._job("Check Ollama"),
|
||||
runtime_model="mimo-v2-pro",
|
||||
runtime_provider="nous",
|
||||
)
|
||||
runtime_pos = result.index("RUNTIME CONTEXT")
|
||||
cron_pos = result.index("scheduled cron job")
|
||||
assert runtime_pos < cron_pos
|
||||
76
tests/test_deploy_synapse.py
Normal file
76
tests/test_deploy_synapse.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""Tests for deploy_synapse.py helpers."""
|
||||
import json
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
import subprocess
|
||||
|
||||
|
||||
class TestSshCmd:
|
||||
def test_basic(self):
|
||||
from scripts.deploy_synapse import _ssh_cmd
|
||||
cmd = _ssh_cmd("1.2.3.4", "root")
|
||||
assert "root@1.2.3.4" in cmd
|
||||
assert "ssh" in cmd[0]
|
||||
|
||||
def test_custom_port(self):
|
||||
from scripts.deploy_synapse import _ssh_cmd
|
||||
cmd = _ssh_cmd("1.2.3.4", "root", port=2222)
|
||||
assert "-p" in cmd
|
||||
assert "2222" in cmd
|
||||
|
||||
def test_key_path(self):
|
||||
from scripts.deploy_synapse import _ssh_cmd
|
||||
cmd = _ssh_cmd("1.2.3.4", "root", key_path="/root/.ssh/id_rsa")
|
||||
assert "-i" in cmd
|
||||
assert "/root/.ssh/id_rsa" in cmd
|
||||
|
||||
|
||||
class TestRunRemote:
|
||||
def test_dry_run(self):
|
||||
from scripts.deploy_synapse import _run_remote
|
||||
ok, stdout, stderr = _run_remote(["ssh", "root@host"], "echo hi", dry_run=True)
|
||||
assert ok is True
|
||||
assert stdout == ""
|
||||
|
||||
@patch("scripts.deploy_synapse.subprocess.run")
|
||||
def test_success(self, mock_run):
|
||||
from scripts.deploy_synapse import _run_remote
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout="hello\n", stderr="")
|
||||
ok, stdout, stderr = _run_remote(["ssh", "root@host"], "echo hello")
|
||||
assert ok is True
|
||||
assert "hello" in stdout
|
||||
|
||||
@patch("scripts.deploy_synapse.subprocess.run")
|
||||
def test_failure(self, mock_run):
|
||||
from scripts.deploy_synapse import _run_remote
|
||||
mock_run.return_value = MagicMock(returncode=1, stdout="", stderr="error")
|
||||
ok, stdout, stderr = _run_remote(["ssh", "root@host"], "bad cmd")
|
||||
assert ok is False
|
||||
|
||||
@patch("scripts.deploy_synapse.subprocess.run", side_effect=subprocess.TimeoutExpired("cmd", 10))
|
||||
def test_timeout(self, mock_run):
|
||||
from scripts.deploy_synapse import _run_remote
|
||||
ok, stdout, stderr = _run_remote(["ssh", "root@host"], "slow cmd", timeout=10)
|
||||
assert ok is False
|
||||
assert "timed out" in stderr
|
||||
|
||||
|
||||
class TestCreateBotAccount:
|
||||
def test_returns_correct_structure(self):
|
||||
from scripts.deploy_synapse import create_bot_account
|
||||
with patch("scripts.deploy_synapse._run_remote") as mock:
|
||||
mock.return_value = (True, "success", "")
|
||||
result = create_bot_account(["ssh", "root@x"], "example.com", dry_run=True)
|
||||
assert "user_id" in result
|
||||
assert "password" in result
|
||||
assert "homeserver_url" in result
|
||||
assert result["user_id"] == "@hermes-bot:example.com"
|
||||
|
||||
|
||||
class TestPrintConfig:
|
||||
def test_runs_without_error(self, capsys):
|
||||
from scripts.deploy_synapse import print_config
|
||||
print_config("example.com", "hermes-bot", "tok_abc", "pass123")
|
||||
captured = capsys.readouterr()
|
||||
assert "MATRIX_HOMESERVER=https://example.com" in captured.out
|
||||
assert "MATRIX_ACCESS_TOKEN=tok_abc" in captured.out
|
||||
Reference in New Issue
Block a user