Cleanup time!

This commit is contained in:
teknium1 2026-02-20 23:23:32 -08:00
parent 9a19fe1f50
commit 70dd3a16dc
38 changed files with 150 additions and 351 deletions

View file

@ -57,6 +57,7 @@ import time
import requests
from typing import Dict, Any, Optional, List
from pathlib import Path
from hermes_constants import OPENROUTER_CHAT_URL
# Try to import httpx for async LLM calls
try:
@ -821,7 +822,7 @@ Provide a concise summary focused on interactive elements and key content."""
try:
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
"https://openrouter.ai/api/v1/chat/completions",
OPENROUTER_CHAT_URL,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
@ -1324,7 +1325,7 @@ Focus on answering the user's specific question."""
async def analyze_screenshot():
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(
"https://openrouter.ai/api/v1/chat/completions",
OPENROUTER_CHAT_URL,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
@ -1374,7 +1375,7 @@ Focus on answering the user's specific question."""
else:
# Fallback: use synchronous requests
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
OPENROUTER_CHAT_URL,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"

View file

@ -345,7 +345,7 @@ def execute_code(
# --- Set up temp directory with hermes_tools.py and script.py ---
tmpdir = tempfile.mkdtemp(prefix="hermes_sandbox_")
sock_path = f"/tmp/hermes_rpc_{uuid.uuid4().hex}.sock"
sock_path = os.path.join(tempfile.gettempdir(), f"hermes_rpc_{uuid.uuid4().hex}.sock")
tool_call_log: list = []
tool_call_counter = [0] # mutable so the RPC thread can increment

View file

@ -446,33 +446,3 @@ def _map_normalized_positions(original: str, normalized: str,
original_matches.append((orig_start, min(orig_end, len(original))))
return original_matches
# =============================================================================
# Utility Functions
# =============================================================================
def find_best_match(content: str, pattern: str) -> Optional[Tuple[int, int, str]]:
"""
Find the best match for a pattern and return the strategy name.
Returns:
Tuple of (start, end, strategy_name) or None if no match
"""
strategies = [
("exact", _strategy_exact),
("line_trimmed", _strategy_line_trimmed),
("whitespace_normalized", _strategy_whitespace_normalized),
("indentation_flexible", _strategy_indentation_flexible),
("escape_normalized", _strategy_escape_normalized),
("trimmed_boundary", _strategy_trimmed_boundary),
("block_anchor", _strategy_block_anchor),
("context_aware", _strategy_context_aware),
]
for strategy_name, strategy_fn in strategies:
matches = strategy_fn(content, pattern)
if matches:
return (matches[0][0], matches[0][1], strategy_name)
return None

View file

@ -53,8 +53,8 @@ import datetime
from pathlib import Path
from typing import Dict, Any, List, Optional
from openai import AsyncOpenAI
from hermes_constants import OPENROUTER_BASE_URL
# Initialize OpenRouter API client lazily (only when needed)
_openrouter_client = None
def _get_openrouter_client():
@ -66,7 +66,7 @@ def _get_openrouter_client():
raise ValueError("OPENROUTER_API_KEY environment variable not set")
_openrouter_client = AsyncOpenAI(
api_key=api_key,
base_url="https://openrouter.ai/api/v1"
base_url=OPENROUTER_BASE_URL
)
return _openrouter_client

View file

@ -23,6 +23,7 @@ import logging
from typing import Dict, Any, List, Optional
from openai import AsyncOpenAI
from hermes_constants import OPENROUTER_BASE_URL
SUMMARIZER_MODEL = "google/gemini-3-flash-preview"
MAX_SESSION_CHARS = 100_000
@ -40,7 +41,7 @@ def _get_client() -> AsyncOpenAI:
raise ValueError("OPENROUTER_API_KEY not set")
_summarizer_client = AsyncOpenAI(
api_key=api_key,
base_url="https://openrouter.ai/api/v1",
base_url=OPENROUTER_BASE_URL,
)
return _summarizer_client

View file

@ -29,6 +29,8 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import List, Tuple
from hermes_constants import OPENROUTER_BASE_URL
# ---------------------------------------------------------------------------
# Hardcoded trust configuration
@ -941,7 +943,7 @@ def llm_audit_skill(skill_path: Path, static_result: ScanResult,
return static_result
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
base_url=OPENROUTER_BASE_URL,
api_key=api_key,
)
response = client.chat.completions.create(
@ -1037,11 +1039,6 @@ def _get_configured_model() -> str:
return ""
def check_guard_requirements() -> Tuple[bool, str]:
"""Check if the guard module can operate. Always returns True (no external deps)."""
return True, "Skills Guard ready"
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------

View file

@ -212,7 +212,7 @@ def _check_disk_usage_warning():
if f.is_file():
try:
total_bytes += f.stat().st_size
except:
except OSError:
pass
total_gb = total_bytes / (1024 ** 3)
@ -341,7 +341,7 @@ def _prompt_dangerous_approval(command: str, description: str, timeout_seconds:
def get_input():
try:
result["choice"] = input(" Choice [o/s/a/D]: ").strip().lower()
except:
except (EOFError, OSError):
result["choice"] = ""
thread = threading.Thread(target=get_input, daemon=True)
@ -894,7 +894,7 @@ class _SingularityEnvironment:
"""Cleanup on destruction."""
try:
self.cleanup()
except:
except Exception:
pass
@ -1022,13 +1022,13 @@ class _SSHEnvironment:
cmd = ["ssh", "-o", f"ControlPath={self.control_socket}", "-O", "exit",
f"{self.user}@{self.host}"]
subprocess.run(cmd, capture_output=True, timeout=5)
except:
except (OSError, subprocess.SubprocessError):
pass
# Remove socket file
try:
self.control_socket.unlink()
except:
except OSError:
pass
def stop(self):
@ -1039,7 +1039,7 @@ class _SSHEnvironment:
"""Cleanup on destruction."""
try:
self.cleanup()
except:
except Exception:
pass
@ -1112,7 +1112,7 @@ class _DockerEnvironment:
"""Cleanup on destruction."""
try:
self.cleanup()
except:
except Exception:
pass
@ -1189,7 +1189,7 @@ class _ModalEnvironment:
"""Cleanup on destruction."""
try:
self.cleanup()
except:
except Exception:
pass
@ -1504,7 +1504,7 @@ def get_active_environments_info() -> Dict[str, Any]:
try:
size = sum(f.stat().st_size for f in Path(path).rglob('*') if f.is_file())
total_size += size
except:
except OSError:
pass
info["total_disk_usage_mb"] = round(total_size / (1024 * 1024), 2)
@ -1532,7 +1532,7 @@ def cleanup_all_environments():
try:
shutil.rmtree(path, ignore_errors=True)
print(f"[Terminal Cleanup] Removed orphaned: {path}")
except:
except OSError:
pass
if not os.getenv("HERMES_QUIET") and cleaned > 0:
@ -1669,7 +1669,6 @@ def terminal_tool(
# This prevents parallel tasks from overwriting each other's files
# In CLI mode (HERMES_QUIET), use the cwd directly without subdirectories
if env_type == "local" and not os.getenv("HERMES_QUIET"):
import uuid
with _env_lock:
if effective_task_id not in _task_workdirs:
task_workdir = Path(cwd) / f"hermes-{effective_task_id}-{uuid.uuid4().hex[:8]}"
@ -1944,7 +1943,7 @@ def check_terminal_requirements() -> bool:
if __name__ == "__main__":
"""Simple test when run directly."""
# Simple test when run directly
print("Terminal Tool Module (mini-swe-agent backend)")
print("=" * 50)

View file

@ -99,8 +99,3 @@ def transcribe_audio(file_path: str, model: Optional[str] = None) -> dict:
"transcript": "",
"error": str(e),
}
def check_stt_requirements() -> bool:
"""Check if OpenAI API key is available for speech-to-text."""
return bool(os.getenv("HERMES_OPENAI_API_KEY") or os.getenv("OPENAI_API_KEY"))

View file

@ -36,9 +36,9 @@ import base64
from pathlib import Path
from typing import Dict, Any, Optional
from openai import AsyncOpenAI
import httpx # Use httpx for async HTTP requests
import httpx
from hermes_constants import OPENROUTER_BASE_URL
# Initialize OpenRouter API client lazily (only when needed)
_openrouter_client = None
def _get_openrouter_client():
@ -50,7 +50,7 @@ def _get_openrouter_client():
raise ValueError("OPENROUTER_API_KEY environment variable not set")
_openrouter_client = AsyncOpenAI(
api_key=api_key,
base_url="https://openrouter.ai/api/v1"
base_url=OPENROUTER_BASE_URL
)
return _openrouter_client

View file

@ -50,6 +50,7 @@ from pathlib import Path
from typing import List, Dict, Any, Optional
from firecrawl import Firecrawl
from openai import AsyncOpenAI
from hermes_constants import OPENROUTER_BASE_URL
# Initialize Firecrawl client lazily (only when needed)
# This prevents import errors when FIRECRAWL_API_KEY is not set
@ -77,7 +78,7 @@ def _get_summarizer_client():
raise ValueError("OPENROUTER_API_KEY environment variable not set")
_summarizer_client = AsyncOpenAI(
api_key=api_key,
base_url="https://openrouter.ai/api/v1"
base_url=OPENROUTER_BASE_URL
)
return _summarizer_client