Skip to content

The agent that grows with you

refactor(hermes_cli/web_routers): simplify ops, chat_ws, files, mcp, cron routers (dead code, shared helpers, gate/sender unification)

Tekniuma6b634ca4f78
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py
index 8d38a1a5914..81825bcced7 100644
--- a/hermes_cli/web_routers/chat_ws.py
+++ b/hermes_cli/web_routers/chat_ws.py
@@ -1,21 +1,22 @@
-"""Chat-tab WebSocket routes: /api/console, /api/pty, the /api/ws gateway sidecar and /api/pub + /api/events broadcast.
+"""Chat-tab WebSocket routes: /api/console, /api/pty, the /api/ws gateway
+sidecar and /api/pub + /api/events broadcast.
-Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on
-``web_server`` stay there and are imported lazily at call time (cycle-safe).
+Helpers/state that tests monkeypatch on ``web_server`` stay there and are
+reached through the late-binding seam (cycle-safe).
"""
import asyncio
import functools
-import logging
import json
-from fastapi import APIRouter
-from hermes_cli.web_deps import late
-from fastapi import HTTPException, WebSocket, WebSocketDisconnect
-from hermes_cli.pty_session import RegistryFull
+import logging
+import re
from pathlib import Path
from typing import Any, Dict, Optional
-import re
-from fastapi import FastAPI
+
+from fastapi import APIRouter, FastAPI, HTTPException, WebSocket, WebSocketDisconnect
+
+from hermes_cli.pty_session import RegistryFull
+from hermes_cli.web_deps import LateState, late
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
@@ -33,17 +34,13 @@ _ws_auth_reason = late("_ws_auth_reason")
_ws_client_reason = late("_ws_client_reason")
_ws_host_origin_reason = late("_ws_host_origin_reason")
_ws_request_is_allowed = late("_ws_request_is_allowed")
+_DASHBOARD_EMBEDDED_CHAT_ENABLED = LateState("_DASHBOARD_EMBEDDED_CHAT_ENABLED")
def _get_event_state(app: "FastAPI"):
- """Return (event_channels, event_lock) from app.state.
-
- Lazily initialises the state if the lifespan hasn't run (e.g. when
- TestClient is constructed without a ``with`` block). The lifespan
- path is preferred because it guarantees the Lock is created on the
- correct event loop, but the lazy path lets existing non-``with``
- TestClient usages keep working.
- """
+ """(event_channels, event_lock) from app.state, lazily initialised when the
+ lifespan hasn't run (TestClient without a ``with`` block). The lifespan path
+ is preferred because it creates the Lock on the correct event loop."""
try:
return app.state.event_channels, app.state.event_lock
except AttributeError:
@@ -71,20 +68,17 @@ async def _broadcast_event(app: Any, channel: str, payload: str) -> None:
event_channels, event_lock = _get_event_state(app)
async with event_lock:
subs = list(event_channels.get(channel, ()))
-
for sub in subs:
try:
await sub.send_text(payload)
except Exception:
- # Subscriber went away mid-send; the /api/events finally clause
- # will remove it from the registry on its next iteration.
+ # Subscriber went away mid-send; /api/events' finally removes it.
_log.warning("broadcast send failed for subscriber on %s", channel, exc_info=True)
def _channel_or_close_code(ws: WebSocket) -> Optional[str]:
- """Return the channel id from the query string or None if invalid."""
+ """Channel id from the query string, or None if invalid."""
channel = ws.query_params.get("channel", "")
-
return channel if _VALID_CHANNEL_RE.match(channel) else None
@@ -93,198 +87,142 @@ def _read_active_session_file(path: Path) -> Optional[str]:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return None
-
- session_id = str(data.get("session_id") or "").strip()
- return session_id or None
-
-
-def _forget_active_session_file(path: Path) -> None:
- try:
- path.unlink(missing_ok=True)
- except OSError:
- pass
+ return str(data.get("session_id") or "").strip() or None
def _ws_close_reason(text: str) -> str:
- """Clamp a WS close reason to the protocol's 123-byte UTF-8 limit.
-
- RFC 6455 caps the close-frame reason at 123 bytes; uvicorn raises if a
- longer string is passed. Our reasons embed an attacker-controlled origin,
- so truncate defensively rather than crash the close handler.
- """
+ """Clamp to RFC 6455's 123-byte close-reason limit (uvicorn raises past it);
+ reasons embed an attacker-controlled origin, so truncate rather than crash."""
encoded = text.encode("utf-8", "replace")
if len(encoded) <= 123:
return text
return encoded[:120].decode("utf-8", "ignore") + "..."
-# ---------------------------------------------------------------------------
-# /api/console — safe Hermes Console command WebSocket.
-#
-# Unlike /api/pty, this endpoint never spawns a PTY, shell, or full Hermes CLI
-# subprocess. It runs the curated console engine in-process and exchanges
-# structured JSON frames with the dashboard xterm overlay.
-# ---------------------------------------------------------------------------
+async def _ws_gate(ws: WebSocket, kind: str) -> Optional[tuple[str, str, str]]:
+ """Run the pre-accept gates for /api/console and /api/pty.
-_CONSOLE_PROMPT = "hermes> "
+ Each gate maps to a distinct close code so the log and the browser banner
+ agree on the cause: 4404 chat disabled, 4401 bad credential, 4403
+ host/origin mismatch, 4408 peer not allowed. Returns ``(peer, mode, cred)``
+ once every gate passes, or None after closing the socket.
+ """
+ peer = ws.client.host if ws.client else "?"
+ if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:
+ _log.info("%s refused: embedded chat disabled peer=%s", kind, peer)
+ await ws.close(code=4404, reason="embedded chat disabled")
+ return None
+
+ auth_reason, cred = _ws_auth_reason(ws)
+ mode = _ws_auth_mode()
+ if auth_reason is not None:
+ _log.warning("%s auth rejected reason=%s mode=%s cred=%s peer=%s", kind, auth_reason, mode, cred, peer)
+ await ws.close(code=4401, reason=_ws_close_reason(f"auth: {auth_reason}"))
+ return None
+ host_origin_reason = _ws_host_origin_reason(ws)
+ if host_origin_reason is not None:
+ _log.warning("%s refused: %s peer=%s", kind, host_origin_reason, peer)
+ await ws.close(code=4403, reason=_ws_close_reason(host_origin_reason))
+ return None
-_CONSOLE_COMMAND_TIMEOUT_SECONDS = 60.0
+ client_reason = _ws_client_reason(ws)
+ if client_reason is not None:
+ _log.warning("%s refused: %s", kind, client_reason)
+ await ws.close(code=4408, reason=_ws_close_reason(client_reason))
+ return None
+ return peer, mode, cred
-_CONSOLE_OUTPUT_LIMIT = 50000
+async def _close_unless_sidecar_allowed(ws: WebSocket) -> bool:
+ """Pre-accept gates for the /api/ws, /api/pub and /api/events sidecars:
+ 4403 when chat is disabled or the request isn't allowed, 4401 on bad auth."""
+ if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:
+ await ws.close(code=4403)
+ return False
+ if not _ws_auth_ok(ws):
+ await ws.close(code=4401)
+ return False
+ if not _ws_request_is_allowed(ws):
+ await ws.close(code=4403)
+ return False
+ return True
+
+# --- /api/console: the curated console engine, in-process, exchanging JSON
+# frames with the dashboard xterm overlay. Never spawns a PTY, shell or CLI.
-def _console_profile_from_ws(ws: WebSocket) -> Optional[str]:
- profile = (ws.query_params.get("profile") or "").strip()
- return profile or None
+_CONSOLE_PROMPT = "hermes> "
+_CONSOLE_COMMAND_TIMEOUT_SECONDS = 60.0
+_CONSOLE_OUTPUT_LIMIT = 50000
-def _execute_console_line(
- engine: Any,
- line: str,
- *,
- confirmed: bool,
- profile: Optional[str],
-) -> Any:
+def _execute_console_line(engine: Any, line: str, *, confirmed: bool, profile: Optional[str]) -> Any:
# _profile_scope swaps process-global skill module paths; keep it inside
# the worker thread and never hold it across awaits.
with _profile_scope(profile):
return engine.execute(line, confirmed=confirmed)
-async def _console_send(
- ws: WebSocket,
- send_lock: asyncio.Lock,
- payload: Dict[str, Any],
-) -> None:
- async with send_lock:
- await ws.send_json(payload)
-
-
-async def _console_send_result(
- ws: WebSocket,
- send_lock: asyncio.Lock,
- result: Any,
- *,
- command_id: int,
-) -> None:
- command = result.command or ""
- status = result.status
- if status == "ok":
- if result.output:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "output",
- "id": command_id,
- "stream": "stdout",
- "data": result.output,
- "command": command,
- },
+class _ConsoleSender:
+ """Serialises frames onto one console socket and owns the prompt suffix."""
+
+ def __init__(self, ws: WebSocket) -> None:
+ self.ws = ws
+ self.lock = asyncio.Lock()
+
+ async def send(self, payload: Dict[str, Any]) -> None:
+ async with self.lock:
+ await self.ws.send_json(payload)
+
+ async def prompt(self, **payload: Any) -> None:
+ await self.send({**payload, "prompt": _CONSOLE_PROMPT})
+
+ async def error(self, message: str, *, id: Optional[int] = None, command: Optional[str] = None,
+ prompt: Optional[str] = None) -> None:
+ # Key order matches the historical frames: type, id, message, command, prompt.
+ frame: Dict[str, Any] = {"type": "error"}
+ if id is not None:
+ frame["id"] = id
+ frame["message"] = message
+ if command is not None:
+ frame["command"] = command
+ if prompt is not None:
+ frame["prompt"] = prompt
+ await self.send(frame)
+
+ async def complete(self, status: str, command: str, command_id: int, *, prompt: str = _CONSOLE_PROMPT) -> None:
+ await self.send({"type": "complete", "id": command_id, "status": status, "command": command, "prompt": prompt})
+
+ async def error_then_complete(self, message: str, command: str, command_id: int, status: str) -> None:
+ await self.error(message, id=command_id, command=command)
+ await self.complete(status, command, command_id)
+
+ async def send_result(self, result: Any, *, command_id: int) -> None:
+ command = result.command or ""
+ status = result.status
+ if status == "ok":
+ if result.output:
+ await self.send({
+ "type": "output", "id": command_id, "stream": "stdout",
+ "data": result.output, "command": command,
+ })
+ await self.complete("ok", command, command_id)
+ elif status == "error":
+ await self.error_then_complete(result.output or "Command failed.", command, command_id, "error")
+ elif status == "confirm_required":
+ await self.prompt(
+ type="confirm_required", id=command_id, command=command,
+ message=result.confirmation_message or f"Run `{command}`?",
)
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "id": command_id,
- "status": "ok",
- "command": command,
- "prompt": _CONSOLE_PROMPT,
- },
- )
- return
-
- if status == "error":
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "id": command_id,
- "message": result.output or "Command failed.",
- "command": command,
- },
- )
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "id": command_id,
- "status": "error",
- "command": command,
- "prompt": _CONSOLE_PROMPT,
- },
- )
- return
-
- if status == "confirm_required":
- await _console_send(
- ws,
- send_lock,
- {
- "type": "confirm_required",
- "id": command_id,
- "command": command,
- "message": result.confirmation_message or f"Run `{command}`?",
- "prompt": _CONSOLE_PROMPT,
- },
- )
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "id": command_id,
- "status": "confirm_required",
- "command": command,
- "prompt": _CONSOLE_PROMPT,
- },
- )
- return
-
- if status == "clear":
- await _console_send(ws, send_lock, {"type": "clear", "id": command_id})
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "id": command_id,
- "status": "clear",
- "command": command,
- "prompt": _CONSOLE_PROMPT,
- },
- )
- return
-
- if status == "exit":
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "id": command_id,
- "status": "exit",
- "command": command,
- "prompt": "",
- },
- )
- return
-
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "id": command_id,
- "message": f"Unknown console result status: {status}",
- "command": command,
- },
- )
+ await self.complete("confirm_required", command, command_id)
+ elif status == "clear":
+ await self.send({"type": "clear", "id": command_id})
+ await self.complete("clear", command, command_id)
+ elif status == "exit":
+ await self.complete("exit", command, command_id, prompt="")
+ else:
+ await self.error(f"Unknown console result status: {status}", id=command_id, command=command)
def _console_json_payload(msg: Any) -> tuple[Optional[dict[str, Any]], Optional[str]]:
@@ -309,40 +247,14 @@ def _console_json_payload(msg: Any) -> tuple[Optional[dict[str, Any]], Optional[
@router.websocket("/api/console")
async def console_ws(ws: WebSocket) -> None:
- from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED
- peer = ws.client.host if ws.client else "?"
-
- if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:
- _log.info("console refused: embedded chat disabled peer=%s", peer)
- await ws.close(code=4404, reason="embedded chat disabled")
+ gate = await _ws_gate(ws, "console")
+ if gate is None:
return
-
- auth_reason, cred = _ws_auth_reason(ws)
- mode = _ws_auth_mode()
- if auth_reason is not None:
- _log.warning(
- "console auth rejected reason=%s mode=%s cred=%s peer=%s",
- auth_reason, mode, cred, peer,
- )
- await ws.close(code=4401, reason=_ws_close_reason(f"auth: {auth_reason}"))
- return
-
- host_origin_reason = _ws_host_origin_reason(ws)
- if host_origin_reason is not None:
- _log.warning("console refused: %s peer=%s", host_origin_reason, peer)
- await ws.close(code=4403, reason=_ws_close_reason(host_origin_reason))
- return
-
- client_reason = _ws_client_reason(ws)
- if client_reason is not None:
- _log.warning("console refused: %s", client_reason)
- await ws.close(code=4408, reason=_ws_close_reason(client_reason))
- return
-
+ peer, mode, cred = gate
await ws.accept()
- profile = _console_profile_from_ws(ws)
- send_lock = asyncio.Lock()
+ profile = (ws.query_params.get("profile") or "").strip() or None
+ out = _ConsoleSender(ws)
try:
from hermes_cli.console_engine import HermesConsoleEngine
@@ -351,47 +263,17 @@ async def console_ws(ws: WebSocket) -> None:
if profile and profile.lower() != "current":
_resolve_profile_dir(profile)
except HTTPException as exc:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": str(exc.detail),
- "prompt": "",
- },
- )
+ await out.error(str(exc.detail), prompt="")
await ws.close(code=4400, reason=_ws_close_reason(str(exc.detail)))
return
except Exception as exc:
_log.exception("console failed to initialize")
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": f"Console unavailable: {exc}",
- "prompt": "",
- },
- )
+ await out.error(f"Console unavailable: {exc}", prompt="")
await ws.close(code=1011)
return
- _log.info(
- "console accepted peer=%s mode=%s cred=%s profile=%s",
- peer,
- mode,
- cred,
- profile or "current",
- )
- await _console_send(
- ws,
- send_lock,
- {
- "type": "ready",
- "profile": profile or "current",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ _log.info("console accepted peer=%s mode=%s cred=%s profile=%s", peer, mode, cred, profile or "current")
+ await out.prompt(type="ready", profile=profile or "current")
active_task: asyncio.Task | None = None
pending_confirmation: Optional[str] = None
@@ -404,13 +286,7 @@ async def console_ws(ws: WebSocket) -> None:
result = await asyncio.wait_for(
loop.run_in_executor(
_get_console_executor(),
- functools.partial(
- _execute_console_line,
- engine,
- line,
- confirmed=confirmed,
- profile=profile,
- ),
+ functools.partial(_execute_console_line, engine, line, confirmed=confirmed, profile=profile),
),
timeout=_CONSOLE_COMMAND_TIMEOUT_SECONDS,
)
@@ -419,79 +295,29 @@ async def console_ws(ws: WebSocket) -> None:
except asyncio.TimeoutError:
if command_id == command_generation:
pending_confirmation = None
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "id": command_id,
- "message": (
- "Command timed out. Hermes Console returned to the prompt."
- ),
- "command": line,
- },
- )
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "id": command_id,
- "status": "timeout",
- "command": line,
- "prompt": _CONSOLE_PROMPT,
- },
+ await out.error_then_complete(
+ "Command timed out. Hermes Console returned to the prompt.", line, command_id, "timeout",
)
except Exception as exc:
if command_id == command_generation:
pending_confirmation = None
_log.exception("console command failed")
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "id": command_id,
- "message": str(exc) or exc.__class__.__name__,
- "command": line,
- },
- )
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "id": command_id,
- "status": "error",
- "command": line,
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.error_then_complete(str(exc) or exc.__class__.__name__, line, command_id, "error")
else:
if command_id != command_generation:
return
- pending_confirmation = (
- result.command if result.status == "confirm_required" else None
- )
- await _console_send_result(
- ws,
- send_lock,
- result,
- command_id=command_id,
- )
+ pending_confirmation = result.command if result.status == "confirm_required" else None
+ await out.send_result(result, command_id=command_id)
if result.status == "exit":
await ws.close(code=1000)
finally:
if command_id == command_generation:
active_task = None
- async def start_command(line: str, *, confirmed: bool = False) -> None:
+ def start_command(line: str, *, confirmed: bool = False) -> None:
nonlocal active_task, command_generation
command_generation += 1
- command_id = command_generation
- active_task = asyncio.create_task(
- run_command(line, confirmed=confirmed, command_id=command_id)
- )
+ active_task = asyncio.create_task(run_command(line, confirmed=confirmed, command_id=command_generation))
try:
while True:
@@ -499,35 +325,19 @@ async def console_ws(ws: WebSocket) -> None:
msg = await ws.receive()
except RuntimeError:
break
- msg_type = msg.get("type")
- if msg_type == "websocket.disconnect":
+ if msg.get("type") == "websocket.disconnect":
break
payload, error = _console_json_payload(msg)
if error:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": error,
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="error", message=error)
continue
if payload is None:
continue
frame_type = str(payload.get("type") or "").strip().lower()
if frame_type == "ping":
- await _console_send(
- ws,
- send_lock,
- {
- "type": "pong",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="pong")
continue
if frame_type == "cancel":
@@ -536,117 +346,45 @@ async def console_ws(ws: WebSocket) -> None:
active_task.cancel()
active_task = None
pending_confirmation = None
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "status": "cancelled",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="complete", status="cancelled")
elif pending_confirmation:
pending_confirmation = None
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "status": "cancelled",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="complete", status="cancelled")
else:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "status": "idle",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="complete", status="idle")
continue
if active_task and not active_task.done():
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": "A console command is already running.",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="error", message="A console command is already running.")
continue
if frame_type == "confirm":
command = str(payload.get("command") or pending_confirmation or "").strip()
if not pending_confirmation:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": "No command is waiting for confirmation.",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="error", message="No command is waiting for confirmation.")
continue
if command != pending_confirmation:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": "Confirmation does not match the pending command.",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="error", message="Confirmation does not match the pending command.")
continue
pending_confirmation = None
- await start_command(command, confirmed=True)
+ start_command(command, confirmed=True)
continue
if frame_type in {"input", "command"}:
line = str(payload.get("line") or payload.get("command") or "").strip()
if not line:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "complete",
- "status": "ok",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="complete", status="ok")
continue
if pending_confirmation:
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": (
- "Confirm or cancel the pending command before "
- "running another one."
- ),
- "prompt": _CONSOLE_PROMPT,
- },
+ await out.prompt(
+ type="error",
+ message="Confirm or cancel the pending command before running another one.",
)
continue
- await start_command(line)
+ start_command(line)
continue
- await _console_send(
- ws,
- send_lock,
- {
- "type": "error",
- "message": f"Unsupported console frame: {frame_type or '?'}",
- "prompt": _CONSOLE_PROMPT,
- },
- )
+ await out.prompt(type="error", message=f"Unsupported console frame: {frame_type or '?'}")
except WebSocketDisconnect:
pass
finally:
@@ -658,56 +396,28 @@ async def console_ws(ws: WebSocket) -> None:
pass
+async def _pty_fail(ws: WebSocket, text: str) -> None:
+ await ws.send_text(f"\r\n\x1b[31m{text}\x1b[0m\r\n")
+ await ws.close(code=1011)
+
+
@router.websocket("/api/pty")
async def pty_ws(ws: WebSocket) -> None:
from hermes_cli.web_server import (
PTY_REGISTRY,
PtyBridge,
PtyUnavailableError,
- _DASHBOARD_EMBEDDED_CHAT_ENABLED,
_PTY_BRIDGE_AVAILABLE,
_RESIZE_RE,
)
- peer = ws.client.host if ws.client else "?"
-
- if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:
- _log.info("pty refused: embedded chat disabled peer=%s", peer)
- await ws.close(code=4404, reason="embedded chat disabled")
- return
-
- # --- auth + host/origin/peer check (before accept so we can close
- # cleanly AND tell the client WHY via the close code + reason).
- # Each gate maps to a distinct close code so the log and the
- # browser banner agree on the cause:
- # 4401 bad credential 4403 host/origin mismatch
- # 4408 peer not allowed 4404 chat disabled
- auth_reason, cred = _ws_auth_reason(ws)
- mode = _ws_auth_mode()
- if auth_reason is not None:
- _log.warning(
- "pty auth rejected reason=%s mode=%s cred=%s peer=%s",
- auth_reason, mode, cred, peer,
- )
- await ws.close(code=4401, reason=_ws_close_reason(f"auth: {auth_reason}"))
- return
-
- host_origin_reason = _ws_host_origin_reason(ws)
- if host_origin_reason is not None:
- _log.warning("pty refused: %s peer=%s", host_origin_reason, peer)
- await ws.close(code=4403, reason=_ws_close_reason(host_origin_reason))
+ gate = await _ws_gate(ws, "pty")
+ if gate is None:
return
-
- client_reason = _ws_client_reason(ws)
- if client_reason is not None:
- _log.warning("pty refused: %s", client_reason)
- await ws.close(code=4408, reason=_ws_close_reason(client_reason))
- return
-
+ peer, mode, cred = gate
await ws.accept()
_log.info("pty accepted peer=%s mode=%s cred=%s", peer, mode, cred)
- # On native Windows, the POSIX PTY bridge can't be imported. Tell the
- # client and close cleanly rather than pretending the feature works.
+ # Native Windows can't import the POSIX PTY bridge: say so and close cleanly.
if not _PTY_BRIDGE_AVAILABLE:
await ws.send_text(
"\r\n\x1b[31mChat unavailable: the embedded terminal requires a "
@@ -718,56 +428,43 @@ async def pty_ws(ws: WebSocket) -> None:
await ws.close(code=1011)
return
- # --- spawn PTY ------------------------------------------------------
raw_resume = ws.query_params.get("resume") or None
resume = raw_resume
profile = ws.query_params.get("profile") or None
channel = _channel_or_close_code(ws)
sidecar_url = _build_sidecar_url(channel) if channel else None
- force_fresh = (ws.query_params.get("fresh") or "").strip().lower() in {
- "1",
- "true",
- "yes",
- "on",
- }
+ force_fresh = (ws.query_params.get("fresh") or "").strip().lower() in {"1", "true", "yes", "on"}
active_session_file: Optional[Path] = None
if channel:
active_session_file = _active_session_file_for_channel(ws.app, channel)
if force_fresh:
resume = None
- _forget_active_session_file(active_session_file)
+ try:
+ active_session_file.unlink(missing_ok=True)
+ except OSError:
+ pass
elif not resume:
resume = _read_active_session_file(active_session_file)
if resume:
- # The client only knows to pin the viewport to the bottom
- # when it requested `?resume=`. Tell it a replay is coming
- # anyway so the implicit active-session fallback gets the
- # same follow-scroll treatment as an explicit resume (#93518).
+ # The client only pins the viewport to the bottom when it asked
+ # for `?resume=`; announce the implicit active-session replay so
+ # it gets the same follow-scroll treatment.
await ws.send_json({"type": "resume", "id": resume})
- resolve_kwargs = {
- "resume": resume,
- "sidecar_url": sidecar_url,
- "profile": profile,
- }
+ resolve_kwargs = {"resume": resume, "sidecar_url": sidecar_url, "profile": profile}
if active_session_file is not None:
resolve_kwargs["active_session_file"] = str(active_session_file)
try:
argv, cwd, env = await _resolve_chat_argv_async(**resolve_kwargs)
- except HTTPException as exc:
- # Unknown/invalid profile from _resolve_profile_dir.
- await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc.detail}\x1b[0m\r\n")
- await ws.close(code=1011)
+ except HTTPException as exc: # unknown/invalid profile
+ await _pty_fail(ws, f"Chat unavailable: {exc.detail}")
return
- except SystemExit as exc:
- # _make_tui_argv calls sys.exit(1) when node/npm is missing.
- await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc}\x1b[0m\r\n")
- await ws.close(code=1011)
+ except SystemExit as exc: # _make_tui_argv sys.exit(1)s when node/npm is missing
+ await _pty_fail(ws, f"Chat unavailable: {exc}")
return
-
attach_token = ws.query_params.get("attach") or None
registry_resume = raw_resume
if raw_resume and env:
@@ -780,52 +477,38 @@ async def pty_ws(ws: WebSocket) -> None:
return PtyBridge.spawn(argv, cwd=cwd, env=env)
if attach_token is None:
- # Legacy path: 1:1 socket<->PTY, killed on disconnect (unchanged).
+ # Legacy path: 1:1 socket<->PTY, killed on disconnect.
try:
bridge = _spawn()
except PtyUnavailableError as exc:
- await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc}\x1b[0m\r\n")
- await ws.close(code=1011)
+ await _pty_fail(ws, f"Chat unavailable: {exc}")
return
except (FileNotFoundError, OSError) as exc:
- await ws.send_text(f"\r\n\x1b[31mChat failed to start: {exc}\x1b[0m\r\n")
- await ws.close(code=1011)
+ await _pty_fail(ws, f"Chat failed to start: {exc}")
return
await _legacy_pump(ws, bridge)
return
# Keep-alive path: the PTY outlives this socket; reattach by token.
try:
- session, _created = await PTY_REGISTRY.attach_or_spawn(
- attach_token, spawn=_spawn
- )
- except PtyUnavailableError as exc:
- await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc}\x1b[0m\r\n")
- await ws.close(code=1011)
- return
- except (FileNotFoundError, OSError, RegistryFull) as exc:
- await ws.send_text(f"\r\n\x1b[31mChat unavailable: {exc}\x1b[0m\r\n")
- await ws.close(code=1011)
+ session, _created = await PTY_REGISTRY.attach_or_spawn(attach_token, spawn=_spawn)
+ except (PtyUnavailableError, FileNotFoundError, OSError, RegistryFull) as exc:
+ await _pty_fail(ws, f"Chat unavailable: {exc}")
return
- # A fresh xterm cannot reliably reconstruct the TUI from an arbitrary
- # bounded tail of alternate-screen, differential ANSI output. Reused PTYs
- # emit a complete frame after replay so reconnects never reopen blank.
+ # A fresh xterm can't rebuild the TUI from an arbitrary tail of alternate-
+ # screen differential output; reused PTYs emit a full frame after replay.
await session.attach(ws, force_redraw=not _created)
- # --- writer loop: WebSocket → PTY master ----------------------------
- # No reader task here: the session's drain task (spawned once per PTY,
- # inside the registry) forwards PTY output to whichever socket is
- # attached and rings-buffers it while detached. On child EOF the drain
- # closes the attached socket with 4410, which unparks ``ws.receive()``
- # below — same half-open-socket protection the legacy pump has (#54028).
+ # Writer loop only: the session's drain task (one per PTY, inside the
+ # registry) forwards output to whichever socket is attached and ring-buffers
+ # it while detached. On child EOF it closes the attached socket with 4410,
+ # which unparks ws.receive() — same half-open protection as the legacy pump.
try:
while True:
try:
msg = await ws.receive()
- except RuntimeError:
- # ws.receive() after the socket is already disconnected
- # (e.g. closed by the drain task on process exit).
+ except RuntimeError: # receive() after the drain task already closed us
break
if msg.get("type") == "websocket.disconnect":
break
@@ -835,13 +518,11 @@ async def pty_ws(ws: WebSocket) -> None:
raw = text.encode("utf-8") if isinstance(text, str) else b""
if not raw:
continue
-
# Resize escape is consumed locally, never written to the PTY.
match = _RESIZE_RE.match(raw)
if match and match.end() == len(raw):
session.bridge.resize(cols=int(match.group(1)), rows=int(match.group(2)))
continue
-
session.bridge.write(raw)
except WebSocketDisconnect:
pass
@@ -851,37 +532,20 @@ async def pty_ws(ws: WebSocket) -> None:
PTY_REGISTRY.detach(attach_token, ws)
-# ---------------------------------------------------------------------------
-# /api/ws — JSON-RPC WebSocket sidecar for the dashboard "Chat" tab.
-#
-# Drives the same `tui_gateway.dispatch` surface Ink uses over stdio, so the
-# dashboard can render structured metadata (model badge, tool-call sidebar,
-# slash launcher, session info) alongside the xterm.js terminal that PTY
-# already paints. Both transports bind to the same session id when one is
-# active, so a tool.start emitted by the agent fans out to both sinks.
-# ---------------------------------------------------------------------------
+# --- /api/ws: JSON-RPC sidecar for the Chat tab. Drives the same
+# tui_gateway.dispatch surface Ink uses over stdio so the dashboard can render
+# structured metadata next to the xterm; both transports bind to the same
+# session id, so agent emits fan out to both sinks.
@router.websocket("/api/ws")
async def gateway_ws(ws: WebSocket) -> None:
- from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED
- if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:
- await ws.close(code=4403)
+ if not await _close_unless_sidecar_allowed(ws):
return
-
- if not _ws_auth_ok(ws):
- await ws.close(code=4401)
- return
-
- if not _ws_request_is_allowed(ws):
- await ws.close(code=4403)
- return
-
from tui_gateway.ws import handle_ws
- # The authenticated identity (ticket / internal credential) was stamped
- # onto the WS object by _ws_auth_reason; carry it into the gateway
- # transport where it becomes the identity authority for privileged RPCs
+ # The authenticated identity (ticket / internal credential) stamped by
+ # _ws_auth_reason becomes the identity authority for privileged RPCs
# (browser.controller.register). None on the legacy token path.
await handle_ws(
ws,
@@ -890,40 +554,29 @@ async def gateway_ws(ws: WebSocket) -> None:
)
-# ---------------------------------------------------------------------------
-# /api/pub + /api/events — chat-tab event broadcast.
-#
-# The PTY-side ``tui_gateway.entry`` opens /api/pub at startup (driven by
-# HERMES_TUI_SIDECAR_URL set in /api/pty's PTY env) and writes every
-# dispatcher emit through it. The dashboard fans those frames out to any
-# subscriber that opened /api/events on the same channel id. This is what
-# gives the React sidebar its tool-call feed without breaking the PTY
+# --- /api/pub + /api/events: the PTY-side tui_gateway.entry opens /api/pub
+# (HERMES_TUI_SIDECAR_URL from /api/pty's env) and writes every dispatcher emit
+# through it; the dashboard fans frames out to /api/events subscribers on the
+# same channel — the React sidebar's tool-call feed without touching the PTY
# child's stdio handshake with Ink.
-# ---------------------------------------------------------------------------
-
-
[email protected]("/api/pub")
-async def pub_ws(ws: WebSocket) -> None:
- from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED
- if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:
- await ws.close(code=4403)
- return
- if not _ws_auth_ok(ws):
- await ws.close(code=4401)
- return
-
- if not _ws_request_is_allowed(ws):
- await ws.close(code=4403)
- return
+async def _accept_channel_ws(ws: WebSocket) -> Optional[str]:
+ if not await _close_unless_sidecar_allowed(ws):
+ return None
channel = _channel_or_close_code(ws)
if not channel:
await ws.close(code=4400)
- return
-
+ return None
await ws.accept()
+ return channel
+
[email protected]("/api/pub")
+async def pub_ws(ws: WebSocket) -> None:
+ channel = await _accept_channel_ws(ws)
+ if channel is None:
+ return
try:
while True:
await _broadcast_event(ws.app, channel, await ws.receive_text())
@@ -933,44 +586,22 @@ async def pub_ws(ws: WebSocket) -> None:
@router.websocket("/api/events")
async def events_ws(ws: WebSocket) -> None:
- from hermes_cli.web_server import _DASHBOARD_EMBEDDED_CHAT_ENABLED
- if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:
- await ws.close(code=4403)
+ channel = await _accept_channel_ws(ws)
+ if channel is None:
return
-
- if not _ws_auth_ok(ws):
- await ws.close(code=4401)
- return
-
- if not _ws_request_is_allowed(ws):
- await ws.close(code=4403)
- return
-
- channel = _channel_or_close_code(ws)
- if not channel:
- await ws.close(code=4400)
- return
-
- await ws.accept()
-
event_channels, event_lock = _get_event_state(ws.app)
async with event_lock:
event_channels.setdefault(channel, set()).add(ws)
-
try:
while True:
- # Subscribers don't speak — the receive() just blocks until
- # disconnect so the connection stays open as long as the
- # browser holds it.
+ # Subscribers don't speak — receive() just blocks until disconnect.
await ws.receive_text()
except WebSocketDisconnect:
pass
finally:
async with event_lock:
subs = event_channels.get(channel)
-
if subs is not None:
subs.discard(ws)
-
if not subs:
event_channels.pop(channel, None)
diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.py
index 2cc466462dc..da7b15d0535 100644
--- a/hermes_cli/web_routers/cron.py
+++ b/hermes_cli/web_routers/cron.py
@@ -8,20 +8,19 @@ late-binding seam so ``monkeypatch.setattr(web_server, ...)`` keeps working.
import asyncio
import functools
import time
-from typing import Optional
+from pathlib import Path
+from typing import Any, Dict, List, Optional
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from hermes_cli.web_deps import late
from hermes_cli.web_models import (
+ AutomationBlueprintInstantiate,
CronJobCreate,
CronJobUpdate,
- AutomationBlueprintInstantiate,
)
from hermes_cli.web_routers._common import log as _log
-from typing import Any, Dict, List
-from pathlib import Path
router = APIRouter()
@@ -46,47 +45,51 @@ _cron_optional_text = late("_cron_optional_text")
_cron_string_list = late("_cron_string_list")
_normalize_dashboard_cron_script = late("_normalize_dashboard_cron_script")
+def _job_not_found() -> HTTPException:
+ return HTTPException(status_code=404, detail="Job not found")
+
-def _normalize_dashboard_cron_updates(
- updates: Dict[str, Any],
- profile_home: Path,
-) -> Dict[str, Any]:
+def _normalize_dashboard_cron_updates(updates: Dict[str, Any], profile_home: Path) -> Dict[str, Any]:
"""Normalize dashboard JSON into cron.jobs.update_job's storage shape.
- This intentionally stays in the dashboard adapter layer: cron/jobs.py is the
- source of truth for scheduling behaviour; the dashboard only translates form
- payloads into the shapes that existing core functions already accept.
+ Stays in the dashboard adapter layer on purpose: cron/jobs.py is the source
+ of truth for scheduling; this only translates form payloads into shapes the
+ core functions already accept.
"""
normalized = dict(updates or {})
-
for key in ("model", "provider", "workdir"):
if key in normalized:
normalized[key] = _cron_optional_text(normalized[key])
if "script" in normalized:
- normalized["script"] = _normalize_dashboard_cron_script(
- normalized["script"],
- profile_home,
- )
+ normalized["script"] = _normalize_dashboard_cron_script(normalized["script"], profile_home)
if "base_url" in normalized:
- normalized["base_url"] = _cron_optional_text(
- normalized["base_url"], strip_trailing_slash=True
- )
+ normalized["base_url"] = _cron_optional_text(normalized["base_url"], strip_trailing_slash=True)
if "deliver" in normalized:
normalized["deliver"] = _cron_optional_text(normalized["deliver"]) or "local"
if "failure_deliver" in normalized:
- # Same text normalization as deliver, but empty CLEARS the override
- # (failures fall back to deliver) rather than coalescing to a target
- # — the field is optional by design (NS-788).
- normalized["failure_deliver"] = _cron_optional_text(
- normalized["failure_deliver"]
- )
- if "context_from" in normalized:
- normalized["context_from"] = _cron_string_list(normalized["context_from"])
- if "enabled_toolsets" in normalized:
- normalized["enabled_toolsets"] = _cron_string_list(normalized["enabled_toolsets"])
+ # Same normalization as deliver, but empty CLEARS the override (failures
+ # fall back to deliver) rather than coalescing — the field is optional.
+ normalized["failure_deliver"] = _cron_optional_text(normalized["failure_deliver"])
+ for key in ("context_from", "enabled_toolsets"):
+ if key in normalized:
+ normalized[key] = _cron_string_list(normalized[key])
return normalized
+def _job_profile(job_id: str, profile: Optional[str]) -> str:
+ """Profile owning ``job_id`` (explicit or discovered); 404 when none."""
+ selected = profile or _find_cron_job_profile(job_id)
+ if not selected:
+ raise _job_not_found()
+ return selected
+
+
+def _found(job):
+ if not job:
+ raise _job_not_found()
+ return job
+
+
def _list_cron_jobs_sync(profile: str = "all"):
requested = (profile or "all").strip()
if requested.lower() != "all":
@@ -105,29 +108,17 @@ def _list_cron_jobs_sync(profile: str = "all"):
def _get_cron_job_sync(job_id: str, profile: Optional[str] = None):
- selected = profile or _find_cron_job_profile(job_id)
- if not selected:
- raise HTTPException(status_code=404, detail="Job not found")
- job = _call_cron_for_profile(selected, "get_job", job_id)
- if not job:
- raise HTTPException(status_code=404, detail="Job not found")
- return job
+ return _found(_call_cron_for_profile(_job_profile(job_id, profile), "get_job", job_id))
def _list_cron_job_runs_sync(job_id: str, profile: Optional[str] = None, limit: int = 20):
"""Run sessions produced by a cron job, newest first.
- Cron runs are stored as ordinary sessions whose id is
- ``cron_{job_id}_{timestamp}`` (see cron/scheduler.run_job). A job's history
- is therefore every session whose id carries that prefix; ``source='cron'``
- narrows it and the id prefix binds it to this job. Powers the run-history
- list under each job in the desktop cron detail. Same row shape as
- ``/api/sessions`` so the frontend can reuse SessionInfo.
-
- Backed by ``SessionDB.list_cron_job_runs`` — a bounded ``[prefix, hi)``
- id-range scan, not the compression-chain CTE used for the recents list,
- so the cost scales with the requested window and not the (unbounded) total
- cron history.
+ Runs are ordinary sessions with id ``cron_{job_id}_{timestamp}`` (see
+ cron/scheduler.run_job); ``source='cron'`` plus the id prefix binds them to
+ this job. Same row shape as ``/api/sessions`` so the frontend reuses
+ SessionInfo. Backed by ``SessionDB.list_cron_job_runs`` — a bounded id-range
+ scan, so cost scales with the requested window, not total cron history.
"""
selected = profile or _find_cron_job_profile(job_id)
# job_id may be a human name; resolve to the canonical id used in run-session ids.
@@ -159,26 +150,18 @@ def _list_cron_job_runs_sync(job_id: str, profile: Optional[str] = None, limit:
db.close()
+_EXECUTION_FIELDS = {"prompt", "skill", "skills", "script", "no_agent"}
+
+
def _update_cron_job_sync(job_id: str, body: CronJobUpdate, profile: Optional[str] = None):
- selected = profile or _find_cron_job_profile(job_id)
- if not selected:
- raise HTTPException(status_code=404, detail="Job not found")
+ selected = _job_profile(job_id, profile)
try:
profile_name, profile_home = _cron_profile_home(selected)
- existing = _call_cron_for_profile(profile_name, "get_job", job_id)
- if not existing:
- raise HTTPException(status_code=404, detail="Job not found")
- updates = _normalize_dashboard_cron_updates(
- body.updates,
- profile_home,
- )
+ existing = _found(_call_cron_for_profile(profile_name, "get_job", job_id))
+ updates = _normalize_dashboard_cron_updates(body.updates, profile_home)
if "context_from" in updates:
- _validate_dashboard_cron_context_from(
- updates.get("context_from"),
- profile_name,
- )
- execution_fields = {"prompt", "skill", "skills", "script", "no_agent"}
- if execution_fields.intersection(updates):
+ _validate_dashboard_cron_context_from(updates.get("context_from"), profile_name)
+ if _EXECUTION_FIELDS.intersection(updates):
effective = {**existing, **updates}
if "skills" in updates and "skill" not in updates:
effective["skill"] = None
@@ -188,43 +171,24 @@ def _update_cron_job_sync(job_id: str, body: CronJobUpdate, profile: Optional[st
raise
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
- if not job:
- raise HTTPException(status_code=404, detail="Job not found")
- return job
+ return _found(job)
def _pause_cron_job_sync(job_id: str, profile: Optional[str] = None):
- selected = profile or _find_cron_job_profile(job_id)
- if not selected:
- raise HTTPException(status_code=404, detail="Job not found")
- job = _mutate_cron_for_profile(selected, "pause_job", job_id)
- if not job:
- raise HTTPException(status_code=404, detail="Job not found")
- return job
+ return _found(_mutate_cron_for_profile(_job_profile(job_id, profile), "pause_job", job_id))
def _resume_cron_job_sync(job_id: str, profile: Optional[str] = None):
- selected = profile or _find_cron_job_profile(job_id)
- if not selected:
- raise HTTPException(status_code=404, detail="Job not found")
- job = _mutate_cron_for_profile(selected, "resume_job", job_id)
- if not job:
- raise HTTPException(status_code=404, detail="Job not found")
- return job
+ return _found(_mutate_cron_for_profile(_job_profile(job_id, profile), "resume_job", job_id))
def _trigger_cron_job_sync(job_id: str, profile: Optional[str] = None):
- selected = profile or _find_cron_job_profile(job_id)
- if not selected:
- raise HTTPException(status_code=404, detail="Job not found")
- job = _call_cron_for_profile(selected, "resolve_job_ref", job_id)
- if not job:
- raise HTTPException(status_code=404, detail="Job not found")
- # Do not expose the job as due before claiming it: the built-in ticker and
- # external/manual fire paths share the same durable claim, so only one can
- # execute this selected run even if they race across processes. Active jobs
- # keep the legacy provider call shape; paused jobs need the explicit force
- # flag to resume and claim atomically.
+ selected = _job_profile(job_id, profile)
+ job = _found(_call_cron_for_profile(selected, "resolve_job_ref", job_id))
+ # Never expose the job as due before claiming it: the built-in ticker and
+ # external/manual fire paths share one durable claim, so only one executes
+ # this run even racing across processes. Active jobs keep the legacy call
+ # shape; paused jobs need the explicit force flag to resume + claim atomically.
force = not job.get("enabled", True) or job.get("state") == "paused"
ran = _fire_cron_job_for_profile(selected, job["id"], force=force)
refreshed = _call_cron_for_profile(selected, "get_job", job["id"])
@@ -237,31 +201,26 @@ def _trigger_cron_job_sync(job_id: str, profile: Optional[str] = None):
)
if refreshed:
return refreshed
- # A one-shot may remove itself after exhausting repeat=1. Keep the response
- # shape compatible without inventing an outcome that is no longer present
- # in the job store; authoritative list refresh removes the completed row.
- return {
- **job,
- "enabled": False,
- "state": "completed",
- }
+ # A one-shot may remove itself after exhausting repeat=1: keep the response
+ # shape without inventing an outcome the store no longer holds; the list
+ # refresh removes the completed row.
+ return {**job, "enabled": False, "state": "completed"}
def _delete_cron_job_sync(job_id: str, profile: Optional[str] = None):
- selected = profile or _find_cron_job_profile(job_id)
- if not selected:
- raise HTTPException(status_code=404, detail="Job not found")
+ selected = _job_profile(job_id, profile)
try:
removed = _mutate_cron_for_profile(selected, "remove_job", job_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not removed:
- raise HTTPException(status_code=404, detail="Job not found")
+ raise _job_not_found()
return {"ok": True}
-# Retry-After hint (seconds) on retryable cron-fire 503s: sized to clear a
-# scale-to-zero wake or gateway restart so a scheduler that honors it spaces
-# its next attempt past the outage instead of burning its retry budget in it.
+
+# Retry-After (seconds) on retryable cron-fire 503s: sized to clear a
+# scale-to-zero wake or gateway restart so a scheduler that honors it spaces its
+# next attempt past the outage instead of burning its retry budget in it.
_CRON_FIRE_RETRY_AFTER_SECONDS = 60
@@ -290,14 +249,7 @@ async def get_cron_delivery_targets():
"""Delivery targets for the cron dropdown: implicit ``local`` plus the
configured gateway platforms (a platform without a cron home channel is
still listed with ``home_target_set: false`` so the UI can say so)."""
- targets = [
- {
- "id": "local",
- "name": "Local (save only)",
- "home_target_set": True,
- "home_env_var": None,
- }
- ]
+ targets = [{"id": "local", "name": "Local (save only)", "home_target_set": True, "home_env_var": None}]
try:
from cron.scheduler import cron_delivery_targets
@@ -336,13 +288,12 @@ async def delete_cron_job(job_id: str, profile: Optional[str] = None):
async def cron_fire_webhook(request: Request):
"""Chronos managed-cron fire webhook (NAS -> agent) — gateway forwarder.
- Gated by the NAS-minted JWT (this path is in ``PUBLIC_API_PATHS``), not the
- dashboard cookie. The dashboard is only the public door: execution belongs
- to the GATEWAY process (it owns the live platform adapters relay-fronted
- and E2EE targets need), so the fire is forwarded to the gateway
- api_server's own ``/api/cron/fire`` on loopback and its response passed
- through (the gateway re-verifies the JWT). Gateway unreachable -> 503 so
- NAS retries; deliberately NO local-execution fallback.
+ Gated by the NAS-minted JWT (path is in ``PUBLIC_API_PATHS``), not the
+ dashboard cookie. Execution belongs to the GATEWAY process (it owns the live
+ platform adapters relay-fronted and E2EE targets need), so the fire is
+ forwarded to the gateway api_server's own ``/api/cron/fire`` on loopback
+ and its response passed through (the gateway re-verifies the JWT). Gateway
+ unreachable -> 503 so NAS retries; deliberately NO local-execution fallback.
"""
from plugins.cron_providers.chronos.verify import get_fire_verifier
@@ -369,15 +320,14 @@ async def cron_fire_webhook(request: Request):
# Walks every profile's job list (file I/O) — off the event loop.
profile = await _run_cron_dashboard_io(_find_cron_job_profile, job_id)
- if not profile:
- # Job is gone (cancelled / completed): 200 so NAS does not retry.
+ if not profile: # job is gone (cancelled / completed): 200 so NAS does not retry
return JSONResponse({"status": "gone", "job_id": job_id}, status_code=200)
forwarded = await _forward_cron_fire_to_gateway(profile, job_id, auth)
if forwarded is None:
# Stamp the miss on the job record (last_fire_error) so the dead hop is
- # visible in `cronjob list` / the dashboard, not just gui.log.
- # Best-effort: visibility must never break the retry contract below.
+ # visible in `cronjob list` / the dashboard. Best-effort: visibility
+ # must never break the retry contract below.
try:
await _run_cron_dashboard_io(
_call_cron_for_profile,
@@ -394,7 +344,7 @@ async def cron_fire_webhook(request: Request):
# Split by operator intent: a deliberately stopped gateway (durable
# desired_state == "stopped") can never be reached by retrying, so drop
# with 200 + a structured log line — the Chronos provider re-arms every
- # job on the next gateway start. A transient window (wake, restart,
+ # job on the next gateway start. A transient window (wake, restart,
# crash loop) keeps the retryable 503 with a Retry-After hint.
if await _run_cron_dashboard_io(_gateway_intentionally_stopped, profile):
_log.info(
@@ -414,19 +364,14 @@ async def cron_fire_webhook(request: Request):
status_code=200,
)
return JSONResponse(
- {
- "error": "gateway unreachable; retry",
- "job_id": job_id,
- "profile": profile,
- },
+ {"error": "gateway unreachable; retry", "job_id": job_id, "profile": profile},
status_code=503,
headers={"Retry-After": str(_CRON_FIRE_RETRY_AFTER_SECONDS)},
)
status_code, gateway_body = forwarded
if isinstance(gateway_body, dict):
gateway_body.setdefault("job_id", job_id)
- # The gateway's own 503s (draining, admission failure) are equally
- # transient — same spacing hint.
+ # The gateway's own 503s (draining, admission failure) are equally transient.
headers = {"Retry-After": str(_CRON_FIRE_RETRY_AFTER_SECONDS)} if status_code == 503 else None
return JSONResponse(gateway_body, status_code=status_code, headers=headers)
@@ -465,21 +410,20 @@ async def list_cron_blueprints():
async def instantiate_blueprint(body: AutomationBlueprintInstantiate, profile: str = "default"):
"""Fill a blueprint's slots and create the cron job (form-submit path)."""
try:
- from cron.blueprint_catalog import fill_blueprint, get_blueprint, BlueprintFillError
+ from cron.blueprint_catalog import BlueprintFillError, fill_blueprint, get_blueprint
blueprint = get_blueprint(body.blueprint)
if blueprint is None:
raise HTTPException(status_code=404, detail=f"Unknown blueprint: {body.blueprint}")
try:
spec = fill_blueprint(blueprint, body.values)
- except BlueprintFillError as exc:
- # Field-level validation error — 422 so the form can show it inline.
+ except BlueprintFillError as exc: # field-level error — 422 so the form shows it inline
raise HTTPException(status_code=422, detail=str(exc)) from exc
- # Blueprint jobs deliver to the dashboard's configured target by
- # default; the form's deliver slot overrides via spec["deliver"].
+ # Blueprint jobs deliver to the dashboard's configured target by default;
+ # the form's deliver slot overrides via spec["deliver"].
spec.pop("origin", None)
- # Off the event loop like the sibling endpoints; partial keeps **spec
- # keys from colliding with the wrapper's own parameters.
+ # Off-loop like the siblings; partial keeps **spec keys from colliding
+ # with the wrapper's own parameters.
_create = functools.partial(_call_cron_for_profile, profile, "create_job", **spec)
created = await _run_cron_dashboard_io(_create)
# Reconcile the profile-scoped provider (file I/O + NAS calls) off-loop.
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 3600e922b71..681c8d3c2bd 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -1,31 +1,38 @@
"""Managed-files, chat image upload, /api/media and /api/fs dashboard routes.
-Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on
-``web_server`` stay there and are imported lazily at call time (cycle-safe).
+Helpers/state that tests monkeypatch on ``web_server`` stay there and are
+reached through the late-binding seam (cycle-safe).
"""
+import asyncio
import base64
import binascii
import mimetypes
import os
import re
-import stat
-import tempfile
-import asyncio
import secrets
import shutil
+import stat
import subprocess
import sys
+import tempfile
from datetime import datetime
-from fastapi import APIRouter
-from hermes_cli.web_deps import late
-from fastapi import File, Form, HTTPException, Request, UploadFile
-from fastapi.responses import FileResponse
-from hermes_cli._subprocess_compat import windows_hide_flags
-from hermes_cli.web_models import ManagedFileUpload, ChatImageUpload, ManagedDirectoryCreate, ManagedFileDelete, FsWriteText
from pathlib import Path
from typing import Any, Dict, Optional
+from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
+from fastapi.responses import FileResponse
+
+from hermes_cli._subprocess_compat import windows_hide_flags
+from hermes_cli.web_deps import late
+from hermes_cli.web_models import (
+ ChatImageUpload,
+ FsWriteText,
+ ManagedDirectoryCreate,
+ ManagedFileDelete,
+ ManagedFileUpload,
+)
+
router = APIRouter()
# web_server helpers, late-bound so monkeypatch.setattr(web_server, ...) stays authoritative.
@@ -38,8 +45,8 @@ get_hermes_home = late("get_hermes_home")
load_config = late("load_config")
-# Image MIME types this endpoint will serve. Extension-allowlisted so an
-# authenticated caller can't pull non-image files through it.
+# Image types GET /api/media serves — extension-allowlisted so an authenticated
+# caller can't pull non-image files through it.
_MEDIA_CONTENT_TYPES = {
".png": "image/png",
".jpg": "image/jpeg",
@@ -50,55 +57,22 @@ _MEDIA_CONTENT_TYPES = {
".bmp": "image/bmp",
".ico": "image/x-icon",
}
-
-
_MEDIA_MAX_BYTES = 25 * 1024 * 1024
-
-_STREAMABLE_MEDIA_EXTENSIONS = frozenset(
- {
- ".avi",
- ".flac",
- ".m4a",
- ".mkv",
- ".mov",
- ".mp3",
- ".mp4",
- ".ogg",
- ".opus",
- ".wav",
- ".webm",
- }
-)
-
+_STREAMABLE_MEDIA_EXTENSIONS = frozenset({
+ ".avi", ".flac", ".m4a", ".mkv", ".mov", ".mp3", ".mp4", ".ogg", ".opus", ".wav", ".webm",
+})
_FS_READDIR_HIDDEN = {
- ".git",
- ".hg",
- ".svn",
- ".cache",
- ".next",
- ".turbo",
- ".venv",
- "__pycache__",
- "build",
- "dist",
- "node_modules",
- "target",
- "venv",
+ ".git", ".hg", ".svn", ".cache", ".next", ".turbo", ".venv", "__pycache__",
+ "build", "dist", "node_modules", "target", "venv",
}
-
-# Filenames that must never be listed, read, or downloaded through the
-# managed-files API. These typically contain credentials (API keys, tokens)
-# and exposing them through the dashboard file browser is a security leak —
-# see issue #57505. The set mirrors the credential-file basenames of the two
-# canonical credential guards elsewhere in the codebase
-# (agent.file_safety.get_read_block_error and
-# gateway.platforms.base._ROOT_CREDENTIAL_FILES) so the dashboard Files tab
-# doesn't lag behind them — an operator can point the managed root at
-# HERMES_HOME itself, at which point every one of these basenames is a live
-# secret store sitting in the browsable tree.
+# Basenames the managed-files API must never list, read or download: credential
+# stores that become live secrets in the browsable tree the moment an operator
+# points the managed root at HERMES_HOME. Mirrors the two canonical guards
+# (agent.file_safety.get_read_block_error, gateway.platforms.base
+# ._ROOT_CREDENTIAL_FILES) so the Files tab never lags behind them.
_SENSITIVE_MANAGED_FILE_BASENAMES = frozenset({
"auth.json",
"auth.lock",
@@ -111,41 +85,22 @@ _SENSITIVE_MANAGED_FILE_BASENAMES = frozenset({
"webhook_subscriptions.json",
"bws_cache.json",
"bws_cache.enc.json",
- # git's credential-store helper cache (agent.file_safety blocks this too).
- ".git-credentials",
+ ".git-credentials", # git's credential-store cache (file_safety blocks it too)
})
-
-# Directory names whose entire subtree is credential material. Both canonical
-# guards deny these as directory trees, not basenames:
-# * gateway.platforms.base._ROOT_CREDENTIAL_DIRS = {"pairing", "mcp-tokens"}
-# * agent.file_safety.get_read_block_error (mcp-tokens/ prefix match)
-# The managed-files API lets the browser descend into subdirs, so a
-# basename-only guard would still expose e.g. ``mcp-tokens/<server>.json``
-# (live MCP OAuth tokens) and ``pairing/<x>``. We match on ANY path component
-# so these trees are blocked wherever they appear under the browsable root,
-# without needing to resolve them relative to HERMES_HOME.
-_SENSITIVE_MANAGED_DIR_NAMES = frozenset({
- "mcp-tokens",
- "pairing",
-})
+# Directory names whose whole subtree is credential material (the canonical
+# guards deny these as trees: _ROOT_CREDENTIAL_DIRS and the mcp-tokens/ prefix
+# match). The browser can descend into subdirs, so a basename-only guard would
+# still expose ``mcp-tokens/<server>.json``; match on ANY path component so the
+# trees are blocked wherever they sit under the root, no HERMES_HOME resolution.
+_SENSITIVE_MANAGED_DIR_NAMES = frozenset({"mcp-tokens", "pairing"})
def _is_sensitive_filename(name: str) -> bool:
- """Return True for a basename the managed-files API must never expose.
-
- Covers ``.env`` / ``.env.<suffix>`` / ``.envrc`` variants plus the
- canonical Hermes credential-store basenames (see
- ``_SENSITIVE_MANAGED_FILE_BASENAMES`` above).
-
- Case-insensitive so ``.ENV`` / ``.Env.local`` / ``Auth.JSON`` on
- case-insensitive filesystems (macOS/Windows mounts) can't slip past
- the guard.
-
- Basename-only: for the directory-tree credential stores
- (``mcp-tokens/``, ``pairing/``) that the canonical guards also deny,
- use :func:`_is_sensitive_path`, which the API call sites route through.
- """
+ """Basename denylist: ``.env`` / ``.env.<suffix>`` / ``.envrc`` plus the
+ credential-store basenames. Case-insensitive so ``.ENV`` / ``Auth.JSON``
+ on case-insensitive mounts can't slip past. Basename-only — call sites use
+ :func:`_is_sensitive_path`, which adds the credential-directory check."""
lowered = name.lower()
if lowered == ".env" or lowered.startswith(".env.") or lowered == ".envrc":
return True
@@ -153,75 +108,29 @@ def _is_sensitive_filename(name: str) -> bool:
def _is_sensitive_path(path: Path) -> bool:
- """Return True for any path the managed-files API must never expose.
-
- Combines the basename denylist (:func:`_is_sensitive_filename`) with a
- credential-directory-tree check: a path is sensitive if its own basename
- is sensitive OR any of its path components is a credential directory
- (``mcp-tokens`` / ``pairing``). The component match is case-insensitive
- and needs no HERMES_HOME resolution, so it blocks these trees wherever
- they sit under the operator-configured managed root — closing the gap
- the canonical guards cover as directory trees but a basename-only check
- would miss.
-
- Read-side only: this guards list/read/download (the #57505 exfil surface).
- The write endpoints (upload/mkdir/delete) are a separate threat class
- handled by the write-path checks; extending this guard to them is out of
- scope for this fix.
- """
+ """True when the basename is sensitive OR any path component (case-
+ insensitive) is a credential directory. Read-side guard (list/read/
+ download); the write endpoints are a separate threat class."""
if _is_sensitive_filename(path.name):
return True
return any(part.lower() in _SENSITIVE_MANAGED_DIR_NAMES for part in path.parts)
_FS_TEXT_SOURCE_MAX_BYTES = 64 * 1024 * 1024
-
-
_FS_TEXT_PREVIEW_MAX_BYTES = 512 * 1024
-
-
-# Upper bound for the in-app spot editor's save. The editor only opens
-# non-truncated text (<= the preview cap), so this is a safety ceiling against
-# a pasted-in megablob, not the expected payload size.
+# Spot-editor save ceiling: the editor only opens non-truncated text (<= the
+# preview cap), so this guards against a pasted megablob, not expected payloads.
_FS_TEXT_WRITE_MAX_BYTES = 8 * 1024 * 1024
-
_FS_PREVIEW_LANGUAGE_BY_EXT = {
- ".c": "c",
- ".conf": "ini",
- ".cpp": "cpp",
- ".css": "css",
- ".csv": "csv",
- ".go": "go",
- ".graphql": "graphql",
- ".h": "c",
- ".hpp": "cpp",
- ".html": "html",
- ".java": "java",
- ".js": "javascript",
- ".json": "json",
- ".jsx": "jsx",
- ".kt": "kotlin",
- ".lua": "lua",
- ".md": "markdown",
- ".mjs": "javascript",
- ".py": "python",
- ".rb": "ruby",
- ".rs": "rust",
- ".sh": "shell",
- ".sql": "sql",
- ".svg": "xml",
- ".toml": "toml",
- ".ts": "typescript",
- ".tsx": "tsx",
- ".txt": "text",
- ".xml": "xml",
- ".yaml": "yaml",
- ".yml": "yaml",
- ".zsh": "shell",
+ ".c": "c", ".conf": "ini", ".cpp": "cpp", ".css": "css", ".csv": "csv", ".go": "go",
+ ".graphql": "graphql", ".h": "c", ".hpp": "cpp", ".html": "html", ".java": "java",
+ ".js": "javascript", ".json": "json", ".jsx": "jsx", ".kt": "kotlin", ".lua": "lua",
+ ".md": "markdown", ".mjs": "javascript", ".py": "python", ".rb": "ruby", ".rs": "rust",
+ ".sh": "shell", ".sql": "sql", ".svg": "xml", ".toml": "toml", ".ts": "typescript",
+ ".tsx": "tsx", ".txt": "text", ".xml": "xml", ".yaml": "yaml", ".yml": "yaml", ".zsh": "shell",
}
-
_FS_MIME_TYPES = {
".avi": "video/x-msvideo",
".bmp": "image/bmp",
@@ -265,9 +174,7 @@ def _fs_regular_file(path: Path) -> tuple[Path, os.stat_result]:
target = _fs_path(str(path))
try:
st = target.stat()
- except FileNotFoundError:
- raise HTTPException(status_code=404, detail="File not found")
- except NotADirectoryError:
+ except (FileNotFoundError, NotADirectoryError):
raise HTTPException(status_code=404, detail="File not found")
except PermissionError:
raise HTTPException(status_code=403, detail="File is not readable")
@@ -280,6 +187,19 @@ def _fs_regular_file(path: Path) -> tuple[Path, os.stat_result]:
return target, st
+def _fs_read_bytes(target: Path, limit: Optional[int] = None) -> bytes:
+ """Read (a prefix of) ``target``; 403/400 on failure."""
+ try:
+ if limit is None:
+ return target.read_bytes()
+ with target.open("rb") as handle:
+ return handle.read(limit)
+ except PermissionError:
+ raise HTTPException(status_code=403, detail="File is not readable")
+ except OSError as exc:
+ raise HTTPException(status_code=400, detail=str(exc) or "File read failed")
+
+
def _fs_find_git_root(start: Path) -> str | None:
directory = start
for _ in range(50):
@@ -310,36 +230,22 @@ def _fs_default_cwd() -> str:
def _fs_git_branch(cwd: str) -> str:
try:
- run_kwargs: Dict[str, Any] = {
- "capture_output": True,
- "text": True,
- "timeout": 2,
- "check": False,
- }
+ run_kwargs: Dict[str, Any] = {"capture_output": True, "text": True, "timeout": 2, "check": False}
if sys.platform == "win32":
run_kwargs["creationflags"] = windows_hide_flags()
- result = subprocess.run(
- ["git", "-C", cwd, "branch", "--show-current"],
- **run_kwargs,
- )
+ result = subprocess.run(["git", "-C", cwd, "branch", "--show-current"], **run_kwargs)
return result.stdout.strip() if result.returncode == 0 else ""
except Exception:
return ""
def _media_serve_roots() -> list[Path]:
- """Directories ``GET /api/media`` is allowed to read from.
-
- Confined to where the agent and attach pipeline actually write media on the
- gateway host — its images dir and cache subtree. This stops an authenticated
- client from reading image-extension files anywhere on disk (e.g. a renamed
- key or a screenshot outside the cache) merely because the suffix passes the
- allowlist.
- """
+ """Directories GET /api/media may read: where the agent and attach pipeline
+ actually write media (images, screenshots, cache). Stops an authenticated
+ client reading image-suffixed files anywhere else on disk."""
home = get_hermes_home()
- roots = [home / "images", home / "screenshots", home / "cache"]
out: list[Path] = []
- for root in roots:
+ for root in (home / "images", home / "screenshots", home / "cache"):
try:
out.append(root.resolve())
except (OSError, RuntimeError):
@@ -349,16 +255,9 @@ def _media_serve_roots() -> list[Path]:
@router.get("/api/media")
async def get_media(path: str):
- """Return a gateway-local image file as a base64 data URL.
-
- Lets remote clients (the desktop app over the network, or the web dashboard
- in a browser) display images the agent wrote to *this* machine's filesystem
- — they can't read the gateway's local disk directly.
-
- Auth-gated by the session token like every other /api route. Restricted to
- an image-extension allowlist, a size cap, AND the gateway's own media roots
- (resolved, symlink-safe) so it can't be used to read arbitrary files.
- """
+ """Return a gateway-local image as a base64 data URL for remote clients
+ that can't read this machine's disk. Auth-gated; restricted to the image
+ allowlist, a size cap AND the resolved (symlink-safe) media roots."""
try:
target = Path(path).expanduser().resolve()
except (OSError, RuntimeError):
@@ -366,11 +265,9 @@ async def get_media(path: str):
if target.suffix.lower() not in _MEDIA_CONTENT_TYPES:
raise HTTPException(status_code=415, detail="Unsupported media type")
-
roots = _media_serve_roots()
if not any(target == root or root in target.parents for root in roots):
raise HTTPException(status_code=403, detail="Path outside media roots")
-
if not target.is_file():
raise HTTPException(status_code=404, detail="File not found")
if target.stat().st_size > _MEDIA_MAX_BYTES:
@@ -380,15 +277,6 @@ async def get_media(path: str):
return {"data_url": f"data:{_MEDIA_CONTENT_TYPES[target.suffix.lower()]};base64,{encoded}"}
-def _local_dashboard_request(request: Request) -> bool:
- if getattr(request.app.state, "auth_required", False):
- return False
- host = (request.url.hostname or "").lower()
- client_host = (request.client.host if request.client else "").lower()
- local_hosts = {"", "localhost", "127.0.0.1", "::1", "testserver", "testclient"}
- return host in local_hosts or client_host in local_hosts
-
-
def _decode_data_url(data_url: str) -> tuple[bytes, str]:
from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES
text = (data_url or "").strip()
@@ -408,11 +296,7 @@ def _decode_data_url(data_url: str) -> tuple[bytes, str]:
_CHAT_IMAGE_UPLOAD_MAX_BYTES = 25 * 1024 * 1024
-
-
_CHAT_IMAGE_ALLOWED_EXTENSIONS = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"})
-
-
_CHAT_IMAGE_MAGIC: tuple[tuple[bytes, str], ...] = (
(b"\x89PNG\r\n\x1a\n", ".png"),
(b"\xff\xd8\xff", ".jpg"),
@@ -425,8 +309,7 @@ _CHAT_IMAGE_MAGIC: tuple[tuple[bytes, str], ...] = (
def _sanitize_chat_image_filename(filename: str | None) -> str:
candidate = Path(str(filename or "").strip()).name
candidate = re.sub(r"[\x00-\x1f]+", "_", candidate)
- candidate = candidate.strip().strip(".")
- return candidate or "pasted-image"
+ return candidate.strip().strip(".") or "pasted-image"
def _chat_image_extension(data: bytes) -> str | None:
@@ -446,7 +329,6 @@ def _decode_chat_image_upload(payload: ChatImageUpload) -> tuple[bytes, str, str
if len(data) > _CHAT_IMAGE_UPLOAD_MAX_BYTES:
mb = _CHAT_IMAGE_UPLOAD_MAX_BYTES // (1024 * 1024)
raise HTTPException(status_code=413, detail=f"Image is too large; cap is {mb} MB")
-
ext = _chat_image_extension(data)
if ext not in _CHAT_IMAGE_ALLOWED_EXTENSIONS:
raise HTTPException(status_code=400, detail="Unsupported image type")
@@ -455,20 +337,17 @@ def _decode_chat_image_upload(payload: ChatImageUpload) -> tuple[bytes, str, str
@router.post("/api/chat/image-upload")
async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = None):
- """Persist a browser-provided chat image where the embedded TUI can read it.
-
- The dashboard /chat page runs Hermes inside an xterm.js PTY. Browser
- clipboard image bytes are not visible to the server-side clipboard, so the
- page uploads them here, then drives the TUI's ``/image <path>`` command
- with the returned gateway-visible path. Files land under
- ``HERMES_HOME/images/`` — the same directory ``clipboard.paste`` /
- ``image.attach`` already use.
+ """Persist a browser clipboard image where the embedded TUI can read it.
+
+ Browser clipboard bytes aren't visible to the server-side clipboard, so the
+ /chat page uploads them here and drives the TUI's ``/image <path>`` with
+ the returned gateway-visible path under ``HERMES_HOME/images/`` (the same
+ dir ``clipboard.paste`` / ``image.attach`` use).
"""
def _run():
data, mime_type, ext = _decode_chat_image_upload(payload)
with _profile_scope(profile) as scoped_home:
- home = scoped_home or get_hermes_home()
- img_dir = Path(home) / "images"
+ img_dir = Path(scoped_home or get_hermes_home()) / "images"
try:
img_dir.mkdir(parents=True, exist_ok=True)
except PermissionError:
@@ -480,7 +359,6 @@ async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = N
stem = re.sub(r"[^A-Za-z0-9_.-]+", "_", stem).strip("._-") or "pasted-image"
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
target = img_dir / f"dashboard_{ts}_{secrets.token_hex(4)}_{stem}{ext}"
-
try:
target.write_bytes(data)
except PermissionError:
@@ -496,9 +374,9 @@ async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = N
"mime_type": mime_type,
}
- # _profile_scope acquires _SKILLS_PROFILE_LOCK and the body does file I/O —
- # keep both off the event loop (asyncio.to_thread copies the contextvar
- # context, so the profile override stays scoped to the worker thread).
+ # _profile_scope takes _SKILLS_PROFILE_LOCK and the body does file I/O — both
+ # off the loop; to_thread copies the contextvar context so the override
+ # stays scoped to the worker thread.
return await asyncio.to_thread(_run)
@@ -527,16 +405,13 @@ async def list_managed_files(request: Request, path: Optional[str] = None):
parent = None
if target.parent != target and (locked_root is None or target != locked_root):
parent = str(target.parent)
- return {
- "path": display_path,
- "parent": parent,
- "entries": entries,
- **_managed_response_meta(policy),
- }
+ return {"path": display_path, "parent": parent, "entries": entries, **_managed_response_meta(policy)}
[email protected]("/api/files/read")
-async def read_managed_file(request: Request, path: str):
+def _managed_readable_file(request: Request, path: str) -> tuple[Any, Path, str, int, str]:
+ """Resolve + guard a managed file for reading: existence, regular file,
+ sensitive-path denylist, size cap. Returns (policy, target, display_path,
+ size, mime_type)."""
from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES
policy, target, display_path = _resolve_managed_path(path, request)
if not target.exists():
@@ -545,22 +420,29 @@ async def read_managed_file(request: Request, path: str):
raise HTTPException(status_code=400, detail="Path is not a file")
if _is_sensitive_path(target):
raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed")
+ return policy, target, display_path, _MANAGED_FILE_MAX_BYTES, mimetypes.guess_type(target.name)[0] or "application/octet-stream"
+
+def _managed_file_size(target: Path, max_bytes: int) -> int:
try:
size = target.stat().st_size
except OSError as exc:
raise HTTPException(status_code=500, detail=f"Could not stat file: {exc}")
- if size > _MANAGED_FILE_MAX_BYTES:
+ if size > max_bytes:
raise HTTPException(status_code=413, detail="File is too large")
+ return size
+
- mime_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
[email protected]("/api/files/read")
+async def read_managed_file(request: Request, path: str):
+ policy, target, display_path, max_bytes, mime_type = _managed_readable_file(request, path)
+ size = _managed_file_size(target, max_bytes)
try:
encoded = base64.b64encode(target.read_bytes()).decode("ascii")
except PermissionError:
raise HTTPException(status_code=403, detail="File is not readable")
except OSError as exc:
raise HTTPException(status_code=500, detail=f"Could not read file: {exc}")
-
return {
"name": target.name,
"path": display_path,
@@ -578,27 +460,11 @@ def _managed_file_response(
content_disposition_type: str,
media_only: bool = False,
) -> FileResponse:
- """Build a range-aware response after applying managed-file policy."""
- from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES
- policy, target, _display_path = _resolve_managed_path(path, request)
- if not target.exists():
- raise HTTPException(status_code=404, detail="File not found")
- if not target.is_file():
- raise HTTPException(status_code=400, detail="Path is not a file")
- if _is_sensitive_path(target):
- raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed")
+ """Range-aware response after applying managed-file policy."""
+ _policy, target, _display_path, max_bytes, mime_type = _managed_readable_file(request, path)
if media_only and target.suffix.lower() not in _STREAMABLE_MEDIA_EXTENSIONS:
raise HTTPException(status_code=415, detail="Unsupported media type")
-
- try:
- size = target.stat().st_size
- except OSError as exc:
- raise HTTPException(status_code=500, detail=f"Could not stat file: {exc}")
- if size > _MANAGED_FILE_MAX_BYTES:
- raise HTTPException(status_code=413, detail="File is too large")
-
- mime_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"
-
+ _managed_file_size(target, max_bytes)
return FileResponse(
path=str(target),
media_type=mime_type,
@@ -612,16 +478,11 @@ def _managed_file_response(
async def download_managed_file(request: Request, path: str):
"""Stream a managed file as an attachment download.
- Remote clients (desktop app, browser dashboard) open agent-written files
- that live on *this* gateway's disk, not theirs. Auth-gated like every other
- managed-files route — ``auth_middleware`` additionally accepts the session
- token as a ``?token=`` query param here so a shell/browser-opened download
- (which can't set the session header) still authenticates. See ``/api/pty``
- for the same query-token precedent. Chromium identifies ``<audio>`` and
- ``<video>`` subresource requests through ``Sec-Fetch-Dest``; serve those
- inline for compatibility with Desktop builds that still use this route as
- their player source, while preserving attachment semantics for ordinary
- link/document requests.
+ ``auth_middleware`` also accepts the session token as ``?token=`` here so a
+ shell/browser-opened download (no session header) still authenticates.
+ Chromium marks ``<audio>``/``<video>`` subresource requests via
+ ``Sec-Fetch-Dest``; those are served inline for Desktop builds that still
+ use this route as their player source, attachment semantics otherwise.
"""
fetch_destination = request.headers.get("sec-fetch-dest", "").lower()
is_media_subresource = fetch_destination in {"audio", "video"}
@@ -636,39 +497,23 @@ async def download_managed_file(request: Request, path: str):
@router.get("/api/files/stream")
@router.head("/api/files/stream")
async def stream_managed_file(request: Request, path: str):
- """Stream managed audio/video inline with HTTP Range support.
-
- Electron's Chromium media pipeline may reject an attachment response used
- as an ``<audio>`` or ``<video>`` source. This route shares the download
- endpoint's authentication, size cap, sensitive-file guard, MIME detection,
- and Starlette ``FileResponse`` range handling, but explicitly marks the
- response inline so metadata loading, playback, and seeking work remotely.
- """
- return _managed_file_response(
- request,
- path,
- content_disposition_type="inline",
- media_only=True,
- )
+ """Stream managed audio/video inline with HTTP Range support — Electron's
+ media pipeline may reject an attachment response as an ``<audio>``/
+ ``<video>`` source. Same auth, size cap, sensitive guard and MIME detection
+ as download."""
+ return _managed_file_response(request, path, content_disposition_type="inline", media_only=True)
[email protected]("/api/files/upload")
-async def upload_managed_file(payload: ManagedFileUpload, request: Request):
- policy, target, display_path = _resolve_managed_path(payload.path, request, for_write=True)
+def _managed_write_target(path: str, request: Request, overwrite: bool):
+ policy, target, display_path = _resolve_managed_path(path, request, for_write=True)
if target.exists() and target.is_dir():
raise HTTPException(status_code=409, detail="A directory already exists at that path")
- if target.exists() and not payload.overwrite:
+ if target.exists() and not overwrite:
raise HTTPException(status_code=409, detail="File already exists")
+ return policy, target, display_path
- data, _mime_type = _decode_data_url(payload.data_url)
- try:
- target.parent.mkdir(parents=True, exist_ok=True)
- target.write_bytes(data)
- except PermissionError:
- raise HTTPException(status_code=403, detail="File is not writable")
- except OSError as exc:
- raise HTTPException(status_code=500, detail=f"Could not write file: {exc}")
+def _managed_write_result(policy, target: Path, display_path: str) -> dict:
return {
"ok": True,
"entry": _managed_file_entry(policy, target),
@@ -677,32 +522,38 @@ async def upload_managed_file(payload: ManagedFileUpload, request: Request):
}
[email protected]("/api/files/upload-stream")
-async def upload_managed_file_stream(
- request: Request,
- file: UploadFile = File(...),
- path: str = Form(...),
- overwrite: bool = Form(True),
-):
- from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES, _UPLOAD_CHUNK_BYTES
- policy, target, display_path = _resolve_managed_path(path, request, for_write=True)
- if target.exists() and target.is_dir():
- raise HTTPException(status_code=409, detail="A directory already exists at that path")
- if target.exists() and not overwrite:
- raise HTTPException(status_code=409, detail="File already exists")
-
[email protected]("/api/files/upload")
+async def upload_managed_file(payload: ManagedFileUpload, request: Request):
+ policy, target, display_path = _managed_write_target(payload.path, request, payload.overwrite)
+ data, _mime_type = _decode_data_url(payload.data_url)
try:
target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(data)
except PermissionError:
raise HTTPException(status_code=403, detail="File is not writable")
except OSError as exc:
- raise HTTPException(status_code=500, detail=f"Could not create parent directory: {exc}")
+ raise HTTPException(status_code=500, detail=f"Could not write file: {exc}")
+ return _managed_write_result(policy, target, display_path)
- # Write to a sibling temp file first so a partial/aborted upload never
- # clobbers an existing file, then atomically rename into place.
- tmp_fd, tmp_name = tempfile.mkstemp(
- prefix=f".{target.name}.", suffix=".upload", dir=str(target.parent)
- )
+
+async def stream_upload_to_path(
+ file: UploadFile,
+ target: Path,
+ *,
+ too_large: str,
+ not_writable: str,
+ write_failed: str,
+) -> int:
+ """Stream a multipart upload to ``target`` in chunks; returns bytes written.
+
+ Writes a sibling temp file first so a partial/aborted upload never clobbers
+ an existing file, enforces ``_MANAGED_FILE_MAX_BYTES`` as it goes (413
+ ``too_large``), then atomically renames into place. The temp file is
+ removed on EVERY non-success exit — including asyncio.CancelledError when a
+ browser aborts a large upload mid-stream.
+ """
+ from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES, _UPLOAD_CHUNK_BYTES
+ tmp_fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".upload", dir=str(target.parent))
tmp_path = Path(tmp_name)
total = 0
renamed = False
@@ -714,32 +565,46 @@ async def upload_managed_file_stream(
break
total += len(chunk)
if total > _MANAGED_FILE_MAX_BYTES:
- raise HTTPException(status_code=413, detail="File is too large")
+ raise HTTPException(status_code=413, detail=too_large)
out.write(chunk)
os.replace(tmp_path, target)
renamed = True
except HTTPException:
raise
except PermissionError:
- raise HTTPException(status_code=403, detail="File is not writable")
+ raise HTTPException(status_code=403, detail=not_writable)
except OSError as exc:
- raise HTTPException(status_code=500, detail=f"Could not write file: {exc}")
+ raise HTTPException(status_code=500, detail=f"{write_failed}: {exc}")
finally:
- # Clean up the temp file on every non-success exit, including
- # BaseException paths the `except` clauses above don't catch — most
- # importantly asyncio.CancelledError when a browser aborts a large
- # upload mid-stream (the exact NS-501 scenario). os.replace clears
- # tmp_path on success, so only unlink when the rename didn't happen.
if not renamed:
tmp_path.unlink(missing_ok=True)
await file.close()
+ return total
- return {
- "ok": True,
- "entry": _managed_file_entry(policy, target),
- "path": display_path,
- **_managed_response_meta(policy),
- }
+
[email protected]("/api/files/upload-stream")
+async def upload_managed_file_stream(
+ request: Request,
+ file: UploadFile = File(...),
+ path: str = Form(...),
+ overwrite: bool = Form(True),
+):
+ """Chunked multipart upload: constant memory and no base64 inflation, unlike
+ the JSON data-URL endpoint that trips proxy body-size limits on large archives."""
+ policy, target, display_path = _managed_write_target(path, request, overwrite)
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ except PermissionError:
+ raise HTTPException(status_code=403, detail="File is not writable")
+ except OSError as exc:
+ raise HTTPException(status_code=500, detail=f"Could not create parent directory: {exc}")
+ await stream_upload_to_path(
+ file, target,
+ too_large="File is too large",
+ not_writable="File is not writable",
+ write_failed="Could not write file",
+ )
+ return _managed_write_result(policy, target, display_path)
@router.post("/api/files/mkdir")
@@ -747,20 +612,13 @@ async def create_managed_directory(payload: ManagedDirectoryCreate, request: Req
policy, target, display_path = _resolve_managed_path(payload.path, request, for_write=True)
if target.exists() and not target.is_dir():
raise HTTPException(status_code=409, detail="A file already exists at that path")
-
try:
target.mkdir(parents=True, exist_ok=True)
except PermissionError:
raise HTTPException(status_code=403, detail="Directory is not writable")
except OSError as exc:
raise HTTPException(status_code=500, detail=f"Could not create directory: {exc}")
-
- return {
- "ok": True,
- "entry": _managed_file_entry(policy, target),
- "path": display_path,
- **_managed_response_meta(policy),
- }
+ return _managed_write_result(policy, target, display_path)
@router.delete("/api/files")
@@ -784,10 +642,16 @@ async def delete_managed_file(payload: ManagedFileDelete, request: Request):
except OSError as exc:
status_code = 409 if target.is_dir() and not payload.recursive else 500
raise HTTPException(status_code=status_code, detail=f"Could not delete path: {exc}")
-
return {"ok": True, "path": display_path, **_managed_response_meta(policy)}
+_FS_LIST_ERRNO = (
+ (FileNotFoundError, "ENOENT"),
+ (NotADirectoryError, "ENOTDIR"),
+ (PermissionError, "EACCES"),
+)
+
+
@router.get("/api/fs/list")
async def fs_list(path: str):
target = _fs_path(path)
@@ -804,13 +668,10 @@ async def fs_list(path: str):
})
entries.sort(key=lambda item: (not item["isDirectory"], item["name"].lower(), item["name"]))
return {"entries": entries}
- except FileNotFoundError:
- return {"entries": [], "error": "ENOENT"}
- except NotADirectoryError:
- return {"entries": [], "error": "ENOTDIR"}
- except PermissionError:
- return {"entries": [], "error": "EACCES"}
except OSError as exc:
+ for exc_type, code in _FS_LIST_ERRNO:
+ if isinstance(exc, exc_type):
+ return {"entries": [], "error": code}
return {"entries": [], "error": getattr(exc, "strerror", None) or "read-error"}
@@ -819,14 +680,7 @@ async def fs_read_text(path: str):
target, st = _fs_regular_file(_fs_path(path))
if st.st_size > _FS_TEXT_SOURCE_MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
- bytes_to_read = min(st.st_size, _FS_TEXT_PREVIEW_MAX_BYTES)
- try:
- with target.open("rb") as handle:
- data = handle.read(bytes_to_read)
- except PermissionError:
- raise HTTPException(status_code=403, detail="File is not readable")
- except OSError as exc:
- raise HTTPException(status_code=400, detail=str(exc) or "File read failed")
+ data = _fs_read_bytes(target, min(st.st_size, _FS_TEXT_PREVIEW_MAX_BYTES))
return {
"binary": _fs_looks_binary(data[:4096]),
"byteSize": st.st_size,
@@ -842,13 +696,11 @@ async def fs_read_text(path: str):
async def fs_write_text(payload: FsWriteText):
"""Overwrite (or create) a UTF-8 text file for the in-app spot editor.
- Mirrors the local Electron ``hermes:fs:writeText`` hardening: the path is
- resolved + validated by ``_fs_path``, the parent directory must already
- exist (we never build directory trees), only regular files may be replaced,
- and the payload is size-capped. The write is staged to a sibling temp file
- and ``os.replace``-d into place so a crash mid-write can't truncate the
- original. Stale-on-disk detection is the client's job (re-read before save),
- so both transports behave identically.
+ Mirrors the Electron ``hermes:fs:writeText`` hardening: path validated by
+ ``_fs_path``, the parent must already exist (never build trees), only
+ regular files may be replaced, payload size-capped, staged to a sibling
+ temp file and ``os.replace``-d so a crash can't truncate the original.
+ Stale-on-disk detection is the client's job (re-read before save).
"""
target = _fs_path(payload.path)
text = payload.content or ""
@@ -881,7 +733,6 @@ async def fs_write_text(payload: FsWriteText):
except OSError as exc:
tmp.unlink(missing_ok=True)
raise HTTPException(status_code=500, detail=f"Could not write file: {exc}")
-
return {"ok": True, "path": str(target), "byteSize": len(text.encode("utf-8"))}
@@ -891,12 +742,7 @@ async def fs_read_data_url(path: str):
target, st = _fs_regular_file(_fs_path(path))
if st.st_size > _FS_DATA_URL_MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
- try:
- encoded = base64.b64encode(target.read_bytes()).decode("ascii")
- except PermissionError:
- raise HTTPException(status_code=403, detail="File is not readable")
- except OSError as exc:
- raise HTTPException(status_code=400, detail=str(exc) or "File read failed")
+ encoded = base64.b64encode(_fs_read_bytes(target)).decode("ascii")
return {"dataUrl": f"data:{_fs_mime_type(target)};base64,{encoded}"}
diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.py
index 8e846215d50..cda360ad37e 100644
--- a/hermes_cli/web_routers/mcp.py
+++ b/hermes_cli/web_routers/mcp.py
@@ -1,20 +1,22 @@
"""MCP dashboard routes.
-The OAuth flow registry (``_mcp_oauth_flows`` + lock + pending cap) and the
-worker/helpers stay in web_server — reached via the late-binding seam so tests
-that mutate ``web_server._mcp_oauth_flows`` or monkeypatch its helpers keep
-working unchanged.
+The OAuth flow registry (``_mcp_oauth_flows``) and the worker/helpers stay in
+web_server — reached via the late-binding seam so tests that mutate
+``web_server._mcp_oauth_flows`` or monkeypatch its helpers keep working.
"""
import asyncio
+import hashlib
+import re
import secrets
import threading
+import time
from typing import Any, Dict, Optional
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse
-from hermes_cli.web_deps import late, LateState
+from hermes_cli.web_deps import LateState, late
from hermes_cli.web_models import (
MCPCatalogInstall,
MCPEnabledToggle,
@@ -26,12 +28,10 @@ from hermes_cli.web_routers._common import (
_profile_scope,
_spawn_hermes_action,
config_write_scope,
+ http_failure,
log as _log,
scoped_to_thread,
)
-import hashlib
-import re
-import time
router = APIRouter()
@@ -45,37 +45,25 @@ save_config = late("save_config")
save_env_value = late("save_env_value")
_mcp_oauth_flows = LateState("_mcp_oauth_flows")
-
-
-_MCP_DASHBOARD_OAUTH_TTL = 15 * 60
-
-
_mcp_oauth_flows_lock = threading.Lock()
-
-
+_MCP_DASHBOARD_OAUTH_TTL = 15 * 60
_MAX_PENDING_MCP_OAUTH_FLOWS = 8
def _gc_mcp_oauth_flows() -> None:
cutoff = time.time() - _MCP_DASHBOARD_OAUTH_TTL
with _mcp_oauth_flows_lock:
- stale = [
- flow_id
- for flow_id, flow in _mcp_oauth_flows.items()
- if getattr(flow, "created_at", 0) < cutoff
- ]
+ stale = [fid for fid, flow in _mcp_oauth_flows.items() if getattr(flow, "created_at", 0) < cutoff]
for flow_id in stale:
_mcp_oauth_flows.pop(flow_id, None)
def _mcp_oauth_callback_url(request: Request, server_name: str) -> str:
- """Build the externally reachable callback URL for a dashboard flow."""
- from urllib.parse import urlparse, urlunparse
+ """Externally reachable callback URL for a dashboard flow."""
+ from urllib.parse import quote, urlparse, urlunparse
from hermes_cli.dashboard_auth.prefix import prefix_from_request, resolve_public_url
- from urllib.parse import quote
-
suffix = f"/api/mcp/oauth/callback/{quote(server_name, safe='')}"
public_url = resolve_public_url()
if public_url:
@@ -102,20 +90,12 @@ async def list_mcp_servers(profile: Optional[str] = None):
from hermes_cli.mcp_config import _get_mcp_servers
servers = await scoped_to_thread(profile, _get_mcp_servers)
- return {
- "servers": [
- _mcp_server_summary(name, cfg) for name, cfg in sorted(servers.items())
- ]
- }
+ return {"servers": [_mcp_server_summary(name, cfg) for name, cfg in sorted(servers.items())]}
@router.post("/api/mcp/servers")
async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):
- from hermes_cli.mcp_config import (
- _get_mcp_servers,
- _save_bearer_auth_token,
- _save_mcp_server,
- )
+ from hermes_cli.mcp_config import _get_mcp_servers, _save_bearer_auth_token, _save_mcp_server
try:
name, server_config, bearer_token = _normalize_mcp_server_create(body)
@@ -124,13 +104,11 @@ async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):
def _run():
# _save_mcp_server does its own load→mutate→save; the duplicate-name
- # check sits under the same lock span so a concurrent add of the same
- # name can't slip between check and save.
+ # check sits under the same lock span so a concurrent add can't slip
+ # between check and save.
with config_write_scope(body.profile or profile):
if name in _get_mcp_servers():
- raise HTTPException(
- status_code=409, detail=f"Server '{name}' already exists"
- )
+ raise HTTPException(status_code=409, detail=f"Server '{name}' already exists")
if bearer_token is not None:
server_config["headers"] = _save_bearer_auth_token(name, bearer_token)
if not _save_mcp_server(name, server_config):
@@ -146,18 +124,14 @@ async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):
except Exception as exc:
_log.exception("POST /api/mcp/servers failed")
raise HTTPException(status_code=400, detail=str(exc)) from exc
-
return _mcp_server_summary(name, server_config)
@router.put("/api/mcp/servers")
async def replace_mcp_servers(body: MCPServersReplace, profile: Optional[str] = None):
- """Replace the entire ``mcp_servers`` map (the GUI mcp.json editor's save).
-
- The generic ``/api/config`` endpoint deep-merges maps and so can never
- delete a key or drop an ``enabled: false``; this sets the whole map so
- removals actually persist.
- """
+ """Replace the entire ``mcp_servers`` map (the mcp.json editor's save) —
+ the deep-merging ``/api/config`` can never delete a key or drop an
+ ``enabled: false``, so removals wouldn't persist through it."""
from hermes_cli.mcp_config import _replace_mcp_servers
def _run():
@@ -178,20 +152,15 @@ async def remove_mcp_server(name: str, profile: Optional[str] = None):
with config_write_scope(profile):
return _remove_mcp_server(name)
- removed = await asyncio.to_thread(_run)
- if not removed:
+ if not await asyncio.to_thread(_run):
raise HTTPException(status_code=404, detail=f"Server '{name}' not found")
return {"ok": True}
@router.post("/api/mcp/servers/{name}/test")
async def test_mcp_server(name: str, profile: Optional[str] = None):
- """Connect to the server, list its tools, disconnect. Returns tool list."""
- from hermes_cli.mcp_config import (
- _get_mcp_servers,
- _oauth_tokens_present,
- _probe_single_server,
- )
+ """Connect to the server, list its tools, disconnect."""
+ from hermes_cli.mcp_config import _get_mcp_servers, _oauth_tokens_present, _probe_single_server
servers = await scoped_to_thread(profile, _get_mcp_servers)
if name not in servers:
@@ -204,32 +173,21 @@ async def test_mcp_server(name: str, profile: Optional[str] = None):
def _probe_scoped():
# Home-only scope (contextvar), NOT _profile_scope: a probe can block for
- # many seconds (stdio `npx` cold start) and _profile_scope holds the
- # process-global skills lock for its whole body, which serialized every
- # other endpoint behind a slow server. The probe only needs the
- # HERMES_HOME override for .env interpolation + OAuth token resolution.
+ # seconds (stdio `npx` cold start) and _profile_scope holds the
+ # process-global skills lock for its whole body, serializing every other
+ # endpoint. The probe only needs HERMES_HOME for .env + token resolution.
with _config_profile_scope(profile):
tools = _probe_single_server(name, servers[name], details=details)
- token_present = _oauth_tokens_present(name) if needs_oauth_token else True
- return tools, token_present
+ return tools, (_oauth_tokens_present(name) if needs_oauth_token else True)
- try:
- # Probe blocks on a dedicated MCP event loop — keep it off the FastAPI loop.
+ try: # probe blocks on a dedicated MCP event loop — keep it off the FastAPI loop
tools, token_present = await asyncio.to_thread(_probe_scoped)
except Exception as exc:
- return {
- "ok": False,
- "error": str(exc),
- "tools": [],
- }
+ return {"ok": False, "error": str(exc), "tools": []}
if not token_present:
- return {
- "ok": False,
- "error": "OAuth authentication required — no token found.",
- "tools": [],
- }
- # Optional per-tool schema size (chars) — the desktop's cost overlay
- # estimates tokens from it; failed probes simply omit it.
+ return {"ok": False, "error": "OAuth authentication required — no token found.", "tools": []}
+ # Optional per-tool schema size (chars) for the desktop's cost overlay;
+ # failed probes simply omit it.
schema_chars = details.get("schema_chars") or {}
return {
"ok": True,
@@ -237,11 +195,7 @@ async def test_mcp_server(name: str, profile: Optional[str] = None):
{
"name": t,
"description": d,
- **(
- {"schema_chars": schema_chars[t]}
- if isinstance(schema_chars.get(t), int)
- else {}
- ),
+ **({"schema_chars": schema_chars[t]} if isinstance(schema_chars.get(t), int) else {}),
}
for t, d in tools
],
@@ -254,17 +208,20 @@ async def test_mcp_server(name: str, profile: Optional[str] = None):
async def auth_mcp_server(name: str, request: Request, profile: Optional[str] = None):
"""Start MCP OAuth and hand the authorization URL to the dashboard browser."""
from hermes_cli.mcp_config import _get_mcp_servers
+ from hermes_constants import get_hermes_home
from tools.mcp_dashboard_oauth import DashboardOAuthFlow
_require_token(request)
_gc_mcp_oauth_flows()
- from hermes_constants import get_hermes_home
- process_home = str(get_hermes_home().expanduser().resolve(strict=False))
+ def _home() -> str:
+ return str(get_hermes_home().expanduser().resolve(strict=False))
+
+ process_home = _home()
def _read():
with _profile_scope(profile):
- return _get_mcp_servers(), str(get_hermes_home().expanduser().resolve(strict=False))
+ return _get_mcp_servers(), _home()
servers, flow_home = await asyncio.to_thread(_read)
if name not in servers:
@@ -282,36 +239,18 @@ async def auth_mcp_server(name: str, request: Request, profile: Optional[str] =
server_name=name,
profile=profile,
hermes_home=flow_home,
- redirect_uri=(cfg.get("oauth") or {}).get("redirect_uri")
- or _mcp_oauth_callback_url(request, name),
+ redirect_uri=(cfg.get("oauth") or {}).get("redirect_uri") or _mcp_oauth_callback_url(request, name),
reconnect_live=flow_home == process_home,
)
with _mcp_oauth_flows_lock:
- pending = sum(
- not flow.worker_done
- for flow in _mcp_oauth_flows.values()
- )
- if pending >= _MAX_PENDING_MCP_OAUTH_FLOWS:
- raise HTTPException(
- status_code=429,
- detail="Too many MCP OAuth flows are already in progress",
- )
- if any(
- flow.server_name == name
- and flow.hermes_home == flow_home
- and not flow.worker_done
- for flow in _mcp_oauth_flows.values()
- ):
- raise HTTPException(
- status_code=409,
- detail=f"MCP OAuth for '{name}' is already in progress",
- )
+ live = [f for f in _mcp_oauth_flows.values() if not f.worker_done]
+ if len(live) >= _MAX_PENDING_MCP_OAUTH_FLOWS:
+ raise HTTPException(status_code=429, detail="Too many MCP OAuth flows are already in progress")
+ if any(f.server_name == name and f.hermes_home == flow_home for f in live):
+ raise HTTPException(status_code=409, detail=f"MCP OAuth for '{name}' is already in progress")
_mcp_oauth_flows[flow_id] = flow
threading.Thread(
- target=_run_dashboard_mcp_oauth,
- args=(flow, cfg),
- daemon=True,
- name=f"mcp-oauth-{name}",
+ target=_run_dashboard_mcp_oauth, args=(flow, cfg), daemon=True, name=f"mcp-oauth-{name}",
).start()
try:
await flow.wait_for_authorization_url(timeout=30)
@@ -334,14 +273,13 @@ async def mcp_oauth_flow_status(flow_id: str, request: Request):
@router.delete("/api/mcp/oauth/flows/{flow_id}")
async def cancel_mcp_oauth_flow(flow_id: str, request: Request):
- """Cancel an in-flight MCP OAuth flow. mark_error unblocks the worker so
- it frees the per-server "already in progress" slot — otherwise a renderer
- that stops polling leaves the flow squatting until the 300s callback
- timeout and every retry 409s. Idempotent: a settled flow is left as-is."""
+ """Cancel an in-flight flow. mark_error unblocks the worker so it frees the
+ per-server "already in progress" slot — otherwise a renderer that stops
+ polling leaves the flow squatting until the 300s callback timeout and every
+ retry 409s. Idempotent: a settled flow is left as-is."""
_require_token(request)
flow = _mcp_oauth_flows.get(flow_id)
- if flow is None:
- # Expired/GC'd is the goal state of a cancel — not an error.
+ if flow is None: # expired/GC'd is the goal state of a cancel — not an error
return {"ok": True, "status": "expired"}
flow.mark_error("Cancelled by user")
return {"ok": True, "status": flow.snapshot()["status"]}
@@ -357,18 +295,13 @@ async def mcp_oauth_callback(
_gc_mcp_oauth_flows()
with _mcp_oauth_flows_lock:
candidates = [
- flow
- for flow in _mcp_oauth_flows.values()
- if flow.server_name == server_name
- and flow.status == "authorization_required"
+ flow for flow in _mcp_oauth_flows.values()
+ if flow.server_name == server_name and flow.status == "authorization_required"
]
flow = next(
(
- candidate
- for candidate in candidates
- if candidate.expected_state is not None
- and state is not None
- and secrets.compare_digest(candidate.expected_state, state)
+ c for c in candidates
+ if c.expected_state is not None and state is not None and secrets.compare_digest(c.expected_state, state)
),
None,
)
@@ -377,12 +310,9 @@ async def mcp_oauth_callback(
try:
flow.deliver_callback(code=code, state=state, error=error)
except ValueError as exc:
- reason = str(exc)
- status_code = 409 if "already received" in reason else 400
return HTMLResponse(
- "<h1>OAuth callback rejected</h1>"
- "<p>The callback was invalid or already used.</p>",
- status_code=status_code,
+ "<h1>OAuth callback rejected</h1><p>The callback was invalid or already used.</p>",
+ status_code=409 if "already received" in str(exc) else 400,
)
if error:
return HTMLResponse("<h1>Authorization failed</h1><p>Return to Hermes for details.</p>", status_code=400)
@@ -390,11 +320,9 @@ async def mcp_oauth_callback(
@router.put("/api/mcp/servers/{name}/enabled")
-async def set_mcp_server_enabled(
- name: str, body: MCPEnabledToggle, profile: Optional[str] = None
-):
- """Toggle the server's ``enabled`` flag (takes effect on next session/gateway);
- disabled servers stay in config so they can be re-enabled without re-entry."""
+async def set_mcp_server_enabled(name: str, body: MCPEnabledToggle, profile: Optional[str] = None):
+ """Toggle ``enabled`` (takes effect on next session/gateway); disabled
+ servers stay in config so they can be re-enabled without re-entry."""
def _run():
with config_write_scope(body.profile or profile):
cfg = load_config()
@@ -410,82 +338,70 @@ async def set_mcp_server_enabled(
return await asyncio.to_thread(_run)
+def _catalog_entry_json(entry: Any, installed: bool, enabled: bool) -> Dict[str, Any]:
+ auth = entry.auth
+ transport = entry.transport
+ install = entry.install
+ return {
+ "name": entry.name,
+ "description": entry.description,
+ "source": entry.source,
+ "transport": transport.type,
+ "auth_type": getattr(auth, "type", "none"),
+ # Env vars the user must supply (names + prompts only, never values).
+ "required_env": [
+ {"name": e.name, "prompt": e.prompt, "required": e.required}
+ for e in getattr(auth, "env", []) or []
+ ],
+ # Transport details surfaced on purpose: the trust model asks users to
+ # inspect command/args/url + bootstrap before installing.
+ "command": transport.command,
+ "args": list(transport.args or []),
+ "url": transport.url,
+ # Git bootstrap (present only for entries that clone + build).
+ "install_url": install.url if install else None,
+ "install_ref": install.ref if install else None,
+ "bootstrap": list(install.bootstrap) if install else [],
+ "default_enabled": list(entry.tools.default_enabled) if entry.tools.default_enabled is not None else None,
+ "post_install": entry.post_install or "",
+ # Composer-suggestion triggers (desktop brand pills), only when the
+ # manifest declares a `suggest` block.
+ "suggest": {"keywords": list(entry.suggest.keywords), "hosts": list(entry.suggest.hosts)} if entry.suggest else None,
+ "needs_install": install is not None,
+ "installed": installed,
+ "enabled": enabled,
+ }
+
+
@router.get("/api/mcp/catalog")
async def list_mcp_catalog(profile: Optional[str] = None):
"""Browse the Nous-approved MCP catalog (optional-mcps/ manifests), each
entry annotated with installed/enabled state for ``profile``."""
- try:
+ with http_failure("mcp_catalog import failed", 500, "Catalog unavailable"):
from hermes_cli import mcp_catalog
- except Exception as exc:
- _log.exception("mcp_catalog import failed")
- raise HTTPException(status_code=500, detail=f"Catalog unavailable: {exc}")
entries = []
try:
def _read():
with _profile_scope(profile):
catalog = list(mcp_catalog.list_catalog())
- state = {
- e.name: (mcp_catalog.is_installed(e.name), mcp_catalog.is_enabled(e.name))
- for e in catalog
- }
+ state = {e.name: (mcp_catalog.is_installed(e.name), mcp_catalog.is_enabled(e.name)) for e in catalog}
return catalog, state
catalog_entries, installed_state = await asyncio.to_thread(_read)
for entry in catalog_entries:
- auth = entry.auth
- transport = entry.transport
- install = entry.install
- entries.append({
- "name": entry.name,
- "description": entry.description,
- "source": entry.source,
- "transport": transport.type,
- "auth_type": getattr(auth, "type", "none"),
- # Env vars the user must supply (names + prompts only, never values).
- "required_env": [
- {"name": e.name, "prompt": e.prompt, "required": e.required}
- for e in getattr(auth, "env", []) or []
- ],
- # Transport details surfaced on purpose: the trust model asks
- # users to inspect command/args/url + bootstrap before installing.
- "command": transport.command,
- "args": list(transport.args or []),
- "url": transport.url,
- # Git bootstrap (present only for entries that clone + build).
- "install_url": install.url if install else None,
- "install_ref": install.ref if install else None,
- "bootstrap": list(install.bootstrap) if install else [],
- # Default tool pre-selection hint and post-install guidance.
- "default_enabled": list(entry.tools.default_enabled)
- if entry.tools.default_enabled is not None
- else None,
- "post_install": entry.post_install or "",
- # Composer-suggestion triggers (desktop brand pills). Present
- # only for entries whose manifest declares a `suggest` block.
- "suggest": {
- "keywords": list(entry.suggest.keywords),
- "hosts": list(entry.suggest.hosts),
- } if entry.suggest else None,
- "needs_install": entry.install is not None,
- "installed": installed_state.get(entry.name, (False, False))[0],
- "enabled": installed_state.get(entry.name, (False, False))[1],
- })
- except HTTPException:
- # Unknown/invalid profile → 404, not a silently-empty catalog.
+ installed, enabled = installed_state.get(entry.name, (False, False))
+ entries.append(_catalog_entry_json(entry, installed, enabled))
+ except HTTPException: # unknown/invalid profile → 404, not a silently-empty catalog
raise
except Exception:
_log.exception("list_mcp_catalog failed")
diagnostics = []
try:
- diagnostics = [
- {"name": n, "kind": k, "message": m}
- for (n, k, m) in mcp_catalog.catalog_diagnostics()
- ]
+ diagnostics = [{"name": n, "kind": k, "message": m} for (n, k, m) in mcp_catalog.catalog_diagnostics()]
except Exception:
pass
-
return {"entries": entries, "diagnostics": diagnostics}
@@ -494,6 +410,7 @@ async def install_mcp_catalog_entry(body: MCPCatalogInstall, profile: Optional[s
"""Install a catalog MCP into config.yaml (declared env vars go to .env
first; git-bootstrap entries run via the background CLI action path)."""
from hermes_cli import mcp_catalog
+ from hermes_cli.config import validate_env_var_name_for_write
name = (body.name or "").strip()
entry = mcp_catalog.get_entry(name)
@@ -507,23 +424,16 @@ async def install_mcp_catalog_entry(body: MCPCatalogInstall, profile: Optional[s
if undeclared_env:
raise HTTPException(
status_code=400,
- detail=(
- f"Catalog entry '{name}' does not declare environment "
- f"variable(s): {', '.join(undeclared_env)}"
- ),
+ detail=f"Catalog entry '{name}' does not declare environment variable(s): {', '.join(undeclared_env)}",
)
-
# Validate the complete map before the first write so a mixed
# valid+invalid request cannot partially persist credentials.
- from hermes_cli.config import validate_env_var_name_for_write
-
try:
for key in body.env:
validate_env_var_name_for_write(key)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
- # Persist any supplied, declared env vars first.
effective_profile = body.profile or profile
if body.env:
def _write_env():
@@ -534,16 +444,12 @@ async def install_mcp_catalog_entry(body: MCPCatalogInstall, profile: Optional[s
await asyncio.to_thread(_write_env)
- # Git-bootstrap entries can take a while to clone — background action path
- # so the request returns immediately. Per-entry action name: a shared
- # "mcp-install" would let a re-click overwrite the tracked process/log.
+ # Git-bootstrap entries can take a while to clone — background action so
+ # the request returns immediately (per-entry action name, see helper).
if entry.install is not None:
action = _mcp_install_action_name(name)
try:
- _spawn_hermes_action(
- _profile_cli_args(effective_profile) + ["mcp", "install", name],
- action,
- )
+ _spawn_hermes_action(_profile_cli_args(effective_profile) + ["mcp", "install", name], action)
except HTTPException:
raise
except Exception as exc:
@@ -553,9 +459,7 @@ async def install_mcp_catalog_entry(body: MCPCatalogInstall, profile: Optional[s
# No git step — install synchronously; install_entry goes through the
# call-time config/env resolvers so the profile scope covers it.
try:
- await scoped_to_thread(
- effective_profile, lambda: mcp_catalog.install_entry(entry, enable=body.enable)
- )
+ await scoped_to_thread(effective_profile, lambda: mcp_catalog.install_entry(entry, enable=body.enable))
except HTTPException:
raise
except Exception as exc:
diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py
index 5943828ed1a..125e7934744 100644
--- a/hermes_cli/web_routers/ops.py
+++ b/hermes_cli/web_routers/ops.py
@@ -1,27 +1,43 @@
-"""Pairing, webhooks, gateway lifecycle, credential pool, memory provider and operations (doctor/backup/import/hooks/checkpoints) dashboard routes.
+"""Pairing, webhooks, gateway lifecycle, credential pool, memory provider and
+operations (doctor/backup/import/hooks/checkpoints) dashboard routes.
-Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on
-``web_server`` stay there and are imported lazily at call time (cycle-safe).
+Helpers/state that tests monkeypatch on ``web_server`` stay there and are
+reached through the late-binding seam (cycle-safe).
"""
-import logging
-import re
-import tempfile
-import zipfile
import asyncio
+import contextlib
+import logging
import os
+import re
import secrets
+import time
+import zipfile
from datetime import datetime, timezone
-from fastapi import APIRouter
-from hermes_cli.web_routers._common import http_failure
-from hermes_cli.web_deps import late
-from fastapi import File, Form, HTTPException, UploadFile
-from fastapi.responses import FileResponse
-from hermes_cli.config import redact_key
-from hermes_cli.web_models import PairingApprove, PairingRevoke, WebhookCreate, WebhookEnabledToggle, CredentialPoolAdd, MemoryProviderSelect, MemoryReset, BackupRequest, ImportRequest, HookCreate, HookDelete
from pathlib import Path
from typing import Any, Dict, List, Optional
+from fastapi import APIRouter, File, Form, HTTPException, UploadFile
+from fastapi.responses import FileResponse
+
+from hermes_cli.config import redact_key
+from hermes_cli.web_deps import late
+from hermes_cli.web_models import (
+ BackupRequest,
+ CredentialPoolAdd,
+ HookCreate,
+ HookDelete,
+ ImportRequest,
+ MemoryProviderSelect,
+ MemoryReset,
+ PairingApprove,
+ PairingRevoke,
+ WebhookCreate,
+ WebhookEnabledToggle,
+)
+from hermes_cli.web_routers._common import _CONFIG_MUTATION_LOCK, http_failure, spawn_profile_action
+from hermes_cli.web_routers.files import stream_upload_to_path
+
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
@@ -40,76 +56,55 @@ save_config = late("save_config")
_restart_gateway_after = late("_restart_gateway_after")
-def _restart_gateway_after_webhook_enable(profile: Optional[str] = None) -> dict[str, Any]:
- return _restart_gateway_after(profile, what="enabling webhooks", label="Webhook enable")
+def _spawn_action(argv: List[str], name: str, *, log_msg: str, prefix: str) -> dict:
+ """Spawn a dashboard-profile ``hermes <argv>`` action; spawn failure -> 500."""
+ return spawn_profile_action(None, argv, name, log_msg=log_msg, prefix=prefix)
-# ---------------------------------------------------------------------------
-# Pairing endpoints — approve / revoke / list messaging pairing codes.
-#
-# These are how a remote admin onboards messaging users (Telegram, Discord, …)
-# without shell access. Wraps gateway.pairing.PairingStore directly.
-# ---------------------------------------------------------------------------
+# --- Pairing: how a remote admin onboards messaging users without shell access.
def _pairing_store(profile: Optional[str] = None):
"""Pairing store for ``profile`` — the dashboard's own when unspecified.
- Every other admin endpoint scopes by profile, and the gateway already
- keeps one store per served profile (``gateway/run.py``). Without this the
- dashboard and desktop always read the global store, so an operator on a
- named profile approves into a whitelist their gateway never consults.
-
- ``PairingStore`` resolves the profile's home itself (``default`` maps back
- to the global store), so this only needs to validate the name — no
- ``_profile_scope`` needed, and nothing process-global is swapped across
- the ``await`` boundary.
+ The gateway keeps one store per served profile, so without scoping an
+ operator on a named profile would approve into a whitelist their gateway
+ never consults. ``PairingStore`` resolves the profile home itself
+ (``default`` maps to the global store); only the name is validated here,
+ so nothing process-global is swapped across the ``await`` boundary.
"""
from gateway.pairing import PairingStore
requested = (profile or "").strip()
if not requested or requested.lower() == "current":
return PairingStore()
-
_resolve_profile_dir(requested) # 400/404 on an unknown profile
-
return PairingStore(profile=requested)
@router.get("/api/pairing")
async def list_pairing(profile: Optional[str] = None):
store = _pairing_store(profile)
- return {
- "pending": store.list_pending(),
- "approved": store.list_approved(),
- }
+ return {"pending": store.list_pending(), "approved": store.list_approved()}
@router.post("/api/pairing/approve")
async def approve_pairing(body: PairingApprove):
store = _pairing_store(body.profile)
platform = (body.platform or "").lower().strip()
- # `request_id` is what an admin surface sends after listing pending
- # requests; `code` is the one-time code the user relays from their DM.
- # A GUI that only knows the older field name still works — a value with
- # request-id shape routes to the request path either way.
+ # `request_id` is what an admin surface sends after listing pending requests;
+ # `code` is the one-time code the user relays. A request-id-shaped value in
+ # the older `code` field still routes to the request path.
target = (body.request_id or body.code or "").strip()
if not platform or not target:
- raise HTTPException(
- status_code=400, detail="platform and request_id or code are required"
- )
+ raise HTTPException(status_code=400, detail="platform and request_id or code are required")
by_request_id = bool(body.request_id) or store.looks_like_request_id(target)
- if by_request_id:
- result = store.approve_request(platform, target)
- else:
- result = store.approve_code(platform, target.upper())
-
+ result = store.approve_request(platform, target) if by_request_id else store.approve_code(platform, target.upper())
if result:
return {"ok": True, "user": result}
- # Lockout only gates the code path, so only report it there — otherwise a
- # stale request id would surface as a bogus 429 while the platform sat
- # locked out for an unrelated reason.
+ # Lockout only gates the code path — a stale request id must not surface
+ # as a bogus 429 while the platform is locked out for an unrelated reason.
if not by_request_id and store._is_locked_out(platform):
raise HTTPException(
status_code=429,
@@ -137,18 +132,11 @@ async def revoke_pairing(body: PairingRevoke):
@router.post("/api/pairing/clear-pending")
async def clear_pending_pairing(profile: Optional[str] = None):
- store = _pairing_store(profile)
- count = store.clear_pending()
- return {"ok": True, "cleared": count}
+ return {"ok": True, "cleared": _pairing_store(profile).clear_pending()}
-# ---------------------------------------------------------------------------
-# Webhook subscription endpoints — list / subscribe / remove.
-#
-# Wraps the same JSON store the CLI uses (hermes_cli.webhook); the webhook
-# adapter hot-reloads it without a gateway restart. Per-route HMAC secrets
-# are redacted on read and surfaced once on create.
-# ---------------------------------------------------------------------------
+# --- Webhooks: same JSON store as the CLI (hermes_cli.webhook); the adapter
+# hot-reloads it. Per-route HMAC secrets are redacted on read, surfaced once on create.
def _webhook_route_summary(name: str, route: Dict[str, Any], base_url: str) -> Dict[str, Any]:
@@ -163,7 +151,6 @@ def _webhook_route_summary(name: str, route: Dict[str, Any], base_url: str) -> D
"skills": list(route.get("skills") or []),
"created_at": route.get("created_at"),
"url": f"{base_url}/webhooks/{name}",
- # Secret is masked on read; full value only returned on create.
"secret_set": bool(route.get("secret")),
# Default-enabled; only an explicit enabled:false turns a route off.
"enabled": route.get("enabled", True) is not False,
@@ -175,29 +162,24 @@ async def list_webhooks():
import hermes_cli.webhook as wh
base_url = wh._get_webhook_base_url()
- subs = wh._load_subscriptions()
return {
"enabled": wh._is_webhook_enabled(),
"base_url": base_url,
"subscriptions": [
_webhook_route_summary(name, route, base_url)
- for name, route in subs.items()
+ for name, route in wh._load_subscriptions().items()
],
}
@router.post("/api/webhooks/enable")
async def enable_webhooks():
- try:
+ with http_failure(
+ "Failed to enable webhook platform from dashboard", 500,
+ detail="Failed to enable webhook platform.",
+ ):
_write_platform_enabled("webhook", True)
- except Exception as exc:
- _log.exception("Failed to enable webhook platform from dashboard")
- raise HTTPException(
- status_code=500,
- detail="Failed to enable webhook platform.",
- ) from exc
-
- restart_result = _restart_gateway_after_webhook_enable()
+ restart_result = _restart_gateway_after(None, what="enabling webhooks", label="Webhook enable")
return {
"ok": True,
"platform": "webhook",
@@ -209,9 +191,6 @@ async def enable_webhooks():
@router.post("/api/webhooks")
async def create_webhook(body: WebhookCreate):
- import re as _re
- import secrets as _secrets
- import time as _time
import hermes_cli.webhook as wh
if not wh._is_webhook_enabled():
@@ -219,21 +198,19 @@ async def create_webhook(body: WebhookCreate):
status_code=400,
detail="Webhook platform is not enabled. Enable it from the Webhooks page first.",
)
-
name = (body.name or "").strip().lower().replace(" ", "-")
- if not _re.match(r"^[a-z0-9][a-z0-9_-]*$", name):
+ if not re.match(r"^[a-z0-9][a-z0-9_-]*$", name):
raise HTTPException(
status_code=400,
detail="Invalid name. Use lowercase alphanumeric with hyphens/underscores.",
)
-
if body.deliver_only and body.deliver == "log":
raise HTTPException(
status_code=400,
detail="Direct delivery requires a real target (telegram, discord, …), not 'log'.",
)
- secret = body.secret or _secrets.token_urlsafe(32)
+ secret = body.secret or secrets.token_urlsafe(32)
route: Dict[str, Any] = {
"description": body.description or f"Dashboard-created subscription: {name}",
"events": [e.strip() for e in body.events if e.strip()],
@@ -241,7 +218,7 @@ async def create_webhook(body: WebhookCreate):
"prompt": body.prompt or "",
"skills": [s.strip() for s in body.skills if s.strip()],
"deliver": body.deliver or "log",
- "created_at": _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime()),
+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
if body.script and body.script.strip():
route["script"] = body.script.strip()
@@ -254,21 +231,25 @@ async def create_webhook(body: WebhookCreate):
subs[name] = route
wh._save_subscriptions(subs)
- base_url = wh._get_webhook_base_url()
- summary = _webhook_route_summary(name, route, base_url)
- # Surface the secret exactly once, on create.
- summary["secret"] = secret
+ summary = _webhook_route_summary(name, route, wh._get_webhook_base_url())
+ summary["secret"] = secret # surfaced exactly once, on create
return summary
[email protected]("/api/webhooks/{name}")
-async def delete_webhook(name: str):
+def _webhook_subs_with(name: str):
+ """(module, subscriptions, key) for an existing route; 404 otherwise."""
import hermes_cli.webhook as wh
key = (name or "").strip().lower()
subs = wh._load_subscriptions()
if key not in subs:
raise HTTPException(status_code=404, detail=f"No subscription named '{key}'")
+ return wh, subs, key
+
+
[email protected]("/api/webhooks/{name}")
+async def delete_webhook(name: str):
+ wh, subs, key = _webhook_subs_with(name)
del subs[key]
wh._save_subscriptions(subs)
return {"ok": True}
@@ -276,32 +257,16 @@ async def delete_webhook(name: str):
@router.put("/api/webhooks/{name}/enabled")
async def set_webhook_enabled(name: str, body: WebhookEnabledToggle):
- """Enable or disable a webhook route.
-
- Disabled routes stay in the subscriptions file (so they can be
- re-enabled) but the gateway rejects incoming events with 403. The
- gateway hot-reloads the subscriptions file, so this takes effect on the
- next event without a restart.
- """
- import hermes_cli.webhook as wh
-
- key = (name or "").strip().lower()
- subs = wh._load_subscriptions()
- if key not in subs:
- raise HTTPException(status_code=404, detail=f"No subscription named '{key}'")
+ """Disabled routes stay on disk (re-enable later) but the gateway rejects
+ their events with 403; it hot-reloads the file, so no restart is needed."""
+ wh, subs, key = _webhook_subs_with(name)
subs[key]["enabled"] = bool(body.enabled)
wh._save_subscriptions(subs)
return {"ok": True, "name": key, "enabled": bool(body.enabled)}
-# ---------------------------------------------------------------------------
-# Gateway lifecycle endpoints — start / stop.
-#
-# restart + update already exist above; these complete the lifecycle so a
-# remote admin can bring the gateway up or down without shell access. Both
-# spawn the real `hermes gateway <verb>` so behaviour matches the CLI exactly.
-# Status is already surfaced by /api/status (gateway_running/state/platforms).
-# ---------------------------------------------------------------------------
+# --- Gateway lifecycle: spawn the real `hermes gateway <verb>` so behaviour
+# matches the CLI exactly (status is surfaced by /api/status).
@router.post("/api/gateway/start")
@@ -318,32 +283,29 @@ async def stop_gateway(profile: Optional[str] = None):
return {"ok": True, "pid": proc.pid, "name": "gateway-stop"}
-# ---------------------------------------------------------------------------
-# Credential pool endpoints — list / add / remove rotation keys.
+# --- Credential pool (auth.json -> credential_pool.<provider>[]): secrets are
+# redacted on read; only the agent sees raw values at session start.
#
-# The credential pool (auth.json -> credential_pool.<provider>[]) holds the
-# rotating API keys the agent round-robins through. Secrets are redacted on
-# read; only the agent ever sees the raw values at session start.
-# ---------------------------------------------------------------------------
+# load_pool() may hit the network synchronously (Copilot token exchange over raw
+# urllib, whose timeout does NOT bound DNS resolution) — on a networkless host it
+# once froze the uvicorn loop for 17 minutes. Every pool load below runs off-loop.
def _pool_entry_summary(entry: Any, index: int) -> Dict[str, Any]:
- """Redacted, display-safe view of one PooledCredential.
-
- ``index`` is 1-based to match CredentialPool.remove_index().
- """
- token = getattr(entry, "access_token", "") or ""
+ """Redacted view of one PooledCredential; ``index`` is 1-based to match
+ CredentialPool.remove_index()."""
+ token = entry.access_token or ""
return {
"index": index,
- "id": getattr(entry, "id", None),
- "label": getattr(entry, "label", None),
- "auth_type": getattr(entry, "auth_type", None),
- "source": getattr(entry, "source", None),
- "priority": getattr(entry, "priority", 0),
- "last_status": getattr(entry, "last_status", None),
- "request_count": getattr(entry, "request_count", 0),
+ "id": entry.id,
+ "label": entry.label,
+ "auth_type": entry.auth_type,
+ "source": entry.source,
+ "priority": entry.priority,
+ "last_status": entry.last_status,
+ "request_count": entry.request_count,
"token_preview": redact_key(token) if token else "",
- "has_refresh": bool(getattr(entry, "refresh_token", None)),
+ "has_refresh": bool(entry.refresh_token),
}
@@ -352,32 +314,22 @@ async def list_credential_pool():
from agent.credential_pool import load_pool
from hermes_cli.auth import read_credential_pool
- # load_pool() may hit the network synchronously (Copilot token exchange
- # over raw urllib). urllib's timeout does NOT bound DNS resolution
- # (getaddrinfo blocks in C), so on a networkless Windows host this froze
- # the uvicorn event loop for 17 minutes (2026-08-22 00:03-00:20 stall).
- # Keep every provider load off the loop - same pattern as
- # get_memory_status below.
def _run():
providers = []
- # read_credential_pool(None) lists every provider that has pooled entries;
- # load_pool() then gives us the rich PooledCredential objects per provider.
- raw_pool = read_credential_pool()
- for provider_id in sorted(raw_pool.keys()):
+ # read_credential_pool(None) lists every provider with pooled entries;
+ # load_pool() gives the rich PooledCredential objects per provider.
+ for provider_id in sorted(read_credential_pool().keys()):
try:
pool = load_pool(provider_id)
except Exception:
_log.exception("load_pool(%s) failed", provider_id)
continue
entries = pool.entries()
- if not entries:
- continue
- providers.append({
- "provider": provider_id,
- "entries": [
- _pool_entry_summary(e, i) for i, e in enumerate(entries, start=1)
- ],
- })
+ if entries:
+ providers.append({
+ "provider": provider_id,
+ "entries": [_pool_entry_summary(e, i) for i, e in enumerate(entries, start=1)],
+ })
return {"providers": providers}
return await asyncio.to_thread(_run)
@@ -385,13 +337,13 @@ async def list_credential_pool():
@router.post("/api/credentials/pool")
async def add_credential_pool_entry(body: CredentialPoolAdd):
- import uuid as _uuid
+ import uuid
from agent.credential_pool import (
- load_pool,
- PooledCredential,
AUTH_TYPE_API_KEY,
CUSTOM_POOL_PREFIX,
SOURCE_MANUAL,
+ PooledCredential,
+ load_pool,
)
provider = (body.provider or "").strip().lower()
@@ -399,33 +351,26 @@ async def add_credential_pool_entry(body: CredentialPoolAdd):
if not provider or not api_key:
raise HTTPException(status_code=400, detail="provider and api_key are required")
- # load_pool() may run synchronous OAuth token exchanges (network I/O);
- # keep it off the event loop - see list_credential_pool (2026-08-22
- # 17-minute stall fix).
def _run():
try:
pool = load_pool(provider)
label = (body.label or "").strip() or f"key #{len(pool.entries()) + 1}"
- entry = PooledCredential(
+ pool.add_entry(PooledCredential(
provider=provider,
- id=_uuid.uuid4().hex[:6],
+ id=uuid.uuid4().hex[:6],
label=label,
auth_type=AUTH_TYPE_API_KEY,
priority=0,
source=SOURCE_MANUAL,
access_token=api_key,
- )
- pool.add_entry(entry)
- # Re-adding a credential is an explicit re-engagement signal: lift
- # every suppression for this provider so a source deleted earlier
- # (via DELETE below or `hermes auth add`) can seed again.
- # Mirrors the `hermes auth add` behaviour in auth_commands.py.
+ ))
+ # Re-adding is an explicit re-engagement signal: lift every suppression
+ # for this provider so a source deleted earlier can seed again
+ # (mirrors `hermes auth add`).
if not provider.startswith(CUSTOM_POOL_PREFIX):
try:
- from hermes_cli.auth import (
- _load_auth_store,
- unsuppress_credential_source,
- )
+ from hermes_cli.auth import _load_auth_store, unsuppress_credential_source
+
suppressed = _load_auth_store().get("suppressed_sources", {})
for src in list(suppressed.get(provider, []) or []):
unsuppress_credential_source(provider, src)
@@ -443,25 +388,21 @@ async def add_credential_pool_entry(body: CredentialPoolAdd):
@router.delete("/api/credentials/pool/{provider}/{index}")
async def remove_credential_pool_entry(provider: str, index: int):
- """Remove a pool entry. ``index`` is 1-based (matches the list response).
-
- Removal must be sticky (#55217): ``load_pool()`` re-seeds entries from
- their backing source (.env var, OAuth singleton file, custom-provider
- config) on every call, so deleting only the pool row silently reverts on
- the next dashboard refresh. We dispatch through the same RemovalStep
- registry the CLI ``hermes auth remove`` uses: each source cleans up its
- external state and suppresses ``(provider, source)`` so the seeders skip
- it. Manual entries have no registered step — nothing external to clean,
- no suppression needed (they aren't re-seeded).
+ """Remove a pool entry (``index`` is 1-based, as listed).
+
+ Removal must be sticky: ``load_pool()`` re-seeds entries from their backing
+ source (.env var, OAuth file, custom-provider config) on every call, so
+ deleting only the row silently reverts on the next refresh. Dispatch through
+ the same RemovalStep registry as ``hermes auth remove``: each source cleans
+ its external state and suppresses ``(provider, source)`` so seeders skip it.
+ Manual entries have no step — nothing external, and they aren't re-seeded.
"""
from agent.credential_pool import load_pool
from agent.credential_sources import find_removal_step
from hermes_cli.auth import suppress_credential_source
provider = (provider or "").strip().lower()
- # load_pool() may run synchronous token exchanges and the removal steps do
- # blocking disk writes - keep them off the event loop (see
- # list_credential_pool; 2026-08-22 17-minute stall fix).
+
def _run():
try:
pool = load_pool(provider)
@@ -483,9 +424,8 @@ async def remove_credential_pool_entry(provider: str, index: int):
if result.suppress:
suppress_credential_source(provider, removed.source)
except Exception:
- # Cleanup is best-effort, but suppression is the actual bug fix -
- # without it the entry resurrects on the next load_pool(). Apply
- # it even when source-specific cleanup blew up.
+ # Cleanup is best-effort, but suppression is the actual fix —
+ # without it the entry resurrects on the next load_pool().
_log.exception(
"credential source cleanup failed for %s/%s; suppressing anyway",
provider, removed.source,
@@ -505,33 +445,24 @@ async def remove_credential_pool_entry(provider: str, index: int):
return await asyncio.to_thread(_run)
-# ---------------------------------------------------------------------------
-# Memory provider endpoints — status / list providers / select / disable / reset.
-#
-# Provider setup is dashboard-native when a provider exposes get_config_schema().
-# The dashboard never runs interactive provider setup hooks; activation is only
-# allowed once the provider is discoverable, available, and has required config.
-# ---------------------------------------------------------------------------
+# --- Memory provider: setup is dashboard-native only via get_config_schema();
+# interactive setup hooks never run here, and activation requires the provider
+# to be discoverable, available and fully configured.
+
+_MEMORY_FILES = (("MEMORY.md", "memory"), ("USER.md", "user"))
@router.get("/api/memory")
async def get_memory_status():
- # load_config(), file stats and provider discovery are disk reads — keep
- # them off the event loop.
- def _run():
+ def _run(): # load_config(), stats and discovery are disk reads — off-loop
cfg = load_config()
- active = ""
mem = cfg.get("memory")
- if isinstance(mem, dict):
- active = _normalize_memory_provider_name(mem.get("provider"))
-
- # Built-in memory file sizes (so the UI can show what a reset would erase).
+ active = _normalize_memory_provider_name(mem.get("provider")) if isinstance(mem, dict) else ""
mem_dir = get_hermes_home() / "memories"
- files = {}
- for fname, key in (("MEMORY.md", "memory"), ("USER.md", "user")):
+ files = {} # sizes so the UI can show what a reset would erase
+ for fname, key in _MEMORY_FILES:
path = mem_dir / fname
files[key] = path.stat().st_size if path.exists() else 0
-
return {
"active": active,
"providers": _discover_memory_provider_statuses(),
@@ -543,12 +474,10 @@ async def get_memory_status():
@router.put("/api/memory/provider")
async def set_memory_provider(body: MemoryProviderSelect):
- from hermes_cli.web_server import _CONFIG_MUTATION_LOCK
provider = _normalize_memory_provider_name(body.provider)
def _run():
_require_memory_provider_ready(provider)
-
with _CONFIG_MUTATION_LOCK:
cfg = load_config()
if not isinstance(cfg.get("memory"), dict):
@@ -568,14 +497,9 @@ async def reset_memory(body: MemoryReset):
mem_dir = get_hermes_home() / "memories"
deleted = []
- targets = []
- if target in {"all", "memory"}:
- targets.append("MEMORY.md")
- if target in {"all", "user"}:
- targets.append("USER.md")
- for fname in targets:
+ for fname, key in _MEMORY_FILES:
path = mem_dir / fname
- if path.exists():
+ if target in {"all", key} and path.exists():
try:
path.unlink()
deleted.append(fname)
@@ -584,71 +508,43 @@ async def reset_memory(body: MemoryReset):
return {"ok": True, "deleted": deleted}
-# ---------------------------------------------------------------------------
-# Operations endpoints — doctor / security audit / backup / import /
-# checkpoints / hooks.
-#
-# Diagnostic and maintenance commands. The long-running / text-output ones
-# (doctor, security audit, backup, import, skills install) are spawned as
-# background actions whose logs the dashboard tails via
-# /api/actions/{name}/status — same pattern as gateway restart and update.
-# The cheap, structured reads (hooks list, checkpoints list) return JSON
-# directly.
-# ---------------------------------------------------------------------------
+# --- Operations: long-running text-output commands (doctor, audit, backup,
+# import) are spawned as background actions whose logs the dashboard tails via
+# /api/actions/{name}/status; cheap structured reads return JSON directly.
@router.post("/api/ops/doctor")
async def run_doctor():
- try:
- proc = _spawn_hermes_action(["doctor"], "doctor")
- except Exception as exc:
- _log.exception("Failed to spawn doctor")
- raise HTTPException(status_code=500, detail=f"Failed to run doctor: {exc}")
- return {"ok": True, "pid": proc.pid, "name": "doctor"}
+ return _spawn_action(["doctor"], "doctor", log_msg="Failed to spawn doctor", prefix="Failed to run doctor")
@router.post("/api/ops/security-audit")
async def run_security_audit():
- try:
- proc = _spawn_hermes_action(["security", "audit"], "security-audit")
- except Exception as exc:
- _log.exception("Failed to spawn security audit")
- raise HTTPException(status_code=500, detail=f"Failed to run security audit: {exc}")
- return {"ok": True, "pid": proc.pid, "name": "security-audit"}
+ return _spawn_action(
+ ["security", "audit"], "security-audit",
+ log_msg="Failed to spawn security audit", prefix="Failed to run security audit",
+ )
def _dashboard_backup_dir() -> Path:
return get_hermes_home() / "backups"
-def _new_dashboard_backup_path() -> Path:
- stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
- return _dashboard_backup_dir() / f"hermes-backup-{stamp}-{secrets.token_hex(4)}.zip"
-
-
@router.post("/api/ops/backup")
async def run_backup(body: BackupRequest):
- args = ["backup"]
archive: Optional[Path] = None
output = (body.output or "").strip()
- if output:
- args.extend(["-o", output])
- else:
- archive = _new_dashboard_backup_path()
+ if not output:
+ stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
+ archive = _dashboard_backup_dir() / f"hermes-backup-{stamp}-{secrets.token_hex(4)}.zip"
try:
archive.parent.mkdir(parents=True, exist_ok=True)
except OSError as exc:
- raise HTTPException(
- status_code=500,
- detail=f"Could not create backup directory: {exc}",
- )
- args.extend(["-o", str(archive)])
- try:
- proc = _spawn_hermes_action(args, "backup")
- except Exception as exc:
- _log.exception("Failed to spawn backup")
- raise HTTPException(status_code=500, detail=f"Failed to run backup: {exc}")
- response = {"ok": True, "pid": proc.pid, "name": "backup"}
+ raise HTTPException(status_code=500, detail=f"Could not create backup directory: {exc}")
+ output = str(archive)
+ response = _spawn_action(
+ ["backup", "-o", output], "backup", log_msg="Failed to spawn backup", prefix="Failed to run backup",
+ )
if archive is not None:
response["archive"] = str(archive)
return response
@@ -668,7 +564,6 @@ async def download_dashboard_backup(archive: str):
raise HTTPException(status_code=403, detail="Backup is outside the dashboard backup directory")
if not target.is_file():
raise HTTPException(status_code=404, detail="Backup not found")
-
return FileResponse(
path=str(target),
media_type="application/zip",
@@ -677,6 +572,13 @@ async def download_dashboard_backup(archive: str):
)
+def _spawn_import(archive: str, force: bool) -> dict:
+ args = ["import", archive]
+ if force:
+ args.append("--force")
+ return _spawn_action(args, "import", log_msg="Failed to spawn import", prefix="Failed to run import")
+
+
@router.post("/api/ops/import")
async def run_import(body: ImportRequest):
archive = (body.archive or "").strip()
@@ -684,22 +586,12 @@ async def run_import(body: ImportRequest):
raise HTTPException(status_code=400, detail="archive path is required")
if not os.path.isfile(archive):
raise HTTPException(status_code=404, detail=f"Archive not found: {archive}")
- args = ["import", archive]
- if body.force:
- args.append("--force")
- try:
- proc = _spawn_hermes_action(args, "import")
- except Exception as exc:
- _log.exception("Failed to spawn import")
- raise HTTPException(status_code=500, detail=f"Failed to run import: {exc}")
- return {"ok": True, "pid": proc.pid, "name": "import"}
+ return _spawn_import(archive, body.force)
def _safe_backup_upload_name(filename: str | None) -> str:
name = Path(filename or "backup.zip").name.strip()
- name = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip(".-")
- if not name:
- name = "backup.zip"
+ name = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip(".-") or "backup.zip"
if not name.lower().endswith(".zip"):
name = f"{name}.zip"
return name
@@ -710,97 +602,38 @@ async def run_import_upload(
file: UploadFile = File(...),
force: bool = Form(False),
):
- from hermes_cli.web_server import _MANAGED_FILE_MAX_BYTES, _UPLOAD_CHUNK_BYTES
staging_dir = _dashboard_backup_dir()
try:
staging_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
- raise HTTPException(
- status_code=500,
- detail=f"Could not create import staging directory: {exc}",
- )
+ raise HTTPException(status_code=500, detail=f"Could not create import staging directory: {exc}")
- safe_name = _safe_backup_upload_name(file.filename)
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
- target = staging_dir / f"dashboard-import-{stamp}-{secrets.token_hex(4)}-{safe_name}"
- tmp_fd, tmp_name = tempfile.mkstemp(
- prefix=f".{target.name}.",
- suffix=".upload",
- dir=str(staging_dir),
+ target = staging_dir / f"dashboard-import-{stamp}-{secrets.token_hex(4)}-{_safe_backup_upload_name(file.filename)}"
+ total = await stream_upload_to_path(
+ file, target,
+ too_large="Archive is too large",
+ not_writable="Import staging directory is not writable",
+ write_failed="Could not write uploaded archive",
)
- tmp_path = Path(tmp_name)
- total = 0
- renamed = False
- try:
- with os.fdopen(tmp_fd, "wb") as out:
- while True:
- chunk = await file.read(_UPLOAD_CHUNK_BYTES)
- if not chunk:
- break
- total += len(chunk)
- if total > _MANAGED_FILE_MAX_BYTES:
- raise HTTPException(status_code=413, detail="Archive is too large")
- out.write(chunk)
- os.replace(tmp_path, target)
- renamed = True
- except HTTPException:
- raise
- except PermissionError:
- raise HTTPException(
- status_code=403,
- detail="Import staging directory is not writable",
- )
- except OSError as exc:
- raise HTTPException(
- status_code=500,
- detail=f"Could not write uploaded archive: {exc}",
- )
- finally:
- if not renamed:
- tmp_path.unlink(missing_ok=True)
- await file.close()
-
if not zipfile.is_zipfile(target):
target.unlink(missing_ok=True)
- raise HTTPException(
- status_code=400,
- detail="Uploaded archive is not a valid zip file",
- )
-
- args = ["import", str(target)]
- if force:
- args.append("--force")
- try:
- proc = _spawn_hermes_action(args, "import")
- except Exception as exc:
- _log.exception("Failed to spawn import")
- raise HTTPException(status_code=500, detail=f"Failed to run import: {exc}")
- return {
- "ok": True,
- "pid": proc.pid,
- "name": "import",
- "archive": str(target),
- "uploaded_bytes": total,
- }
+ raise HTTPException(status_code=400, detail="Uploaded archive is not a valid zip file")
+ return {**_spawn_import(str(target), force), "archive": str(target), "uploaded_bytes": total}
@router.get("/api/ops/hooks")
async def list_hooks():
- """List configured shell hooks from config.yaml with consent + health.
-
- Reports each hook's allowlist (consent) status and whether the script is
- currently executable, plus the set of valid hook events so the create
- form can offer them.
- """
+ """Configured shell hooks with consent (allowlist) status, whether the
+ script is currently executable, and the valid hook events for the form."""
def _run():
from hermes_cli.config import load_config as _load_config
from agent import shell_hooks
- try:
+ valid_events = []
+ with contextlib.suppress(Exception):
from hermes_cli.plugins import VALID_HOOKS
valid_events = sorted(VALID_HOOKS)
- except Exception:
- valid_events = []
specs = []
try:
@@ -811,15 +644,11 @@ async def list_hooks():
out = []
for spec in specs:
entry = None
- try:
- entry = shell_hooks.allowlist_entry_for(spec.event, spec.command)
- except Exception:
- pass
executable = False
- try:
+ with contextlib.suppress(Exception):
+ entry = shell_hooks.allowlist_entry_for(spec.event, spec.command)
+ with contextlib.suppress(Exception):
executable = shell_hooks.script_is_executable(spec.command)
- except Exception:
- pass
out.append({
"event": spec.event,
"matcher": spec.matcher,
@@ -829,53 +658,48 @@ async def list_hooks():
"approved_at": (entry or {}).get("approved_at"),
"executable": executable,
})
-
return {"hooks": out, "valid_events": valid_events}
return await asyncio.to_thread(_run)
+def _hook_body_fields(body) -> tuple[str, str]:
+ event = (body.event or "").strip()
+ command = (body.command or "").strip()
+ if not event or not command:
+ raise HTTPException(status_code=400, detail="event and command are required")
+ return event, command
+
+
@router.post("/api/ops/hooks")
async def create_hook(body: HookCreate):
- """Add a shell hook to config.yaml (and optionally approve it).
+ """Add a shell hook to config.yaml and optionally record consent.
- Shell hooks run arbitrary commands, so this is a privileged action: it
- writes to the ``hooks:`` config block and, when ``approve`` is set, records
- consent in the allowlist so the hook actually fires. Takes effect on the
- next session / gateway restart.
+ Shell hooks run arbitrary commands, so this is privileged: it writes the
+ ``hooks:`` block and, with ``approve``, records the allowlist entry so the
+ hook actually fires. Takes effect on the next session / gateway restart.
"""
- from hermes_cli.web_server import _CONFIG_MUTATION_LOCK
from agent import shell_hooks
- event = (body.event or "").strip()
- command = (body.command or "").strip()
- if not event or not command:
- raise HTTPException(status_code=400, detail="event and command are required")
-
- try:
- from hermes_cli.plugins import VALID_HOOKS
- if event not in VALID_HOOKS:
- raise HTTPException(
- status_code=400,
- detail=f"Unknown event '{event}'. Valid: {', '.join(sorted(VALID_HOOKS))}",
- )
- except HTTPException:
- raise
- except Exception:
- pass
+ event, command = _hook_body_fields(body)
+ valid_hooks = None
+ with contextlib.suppress(Exception):
+ from hermes_cli.plugins import VALID_HOOKS as valid_hooks
+ if valid_hooks is not None and event not in valid_hooks:
+ raise HTTPException(
+ status_code=400,
+ detail=f"Unknown event '{event}'. Valid: {', '.join(sorted(valid_hooks))}",
+ )
def _run():
with _CONFIG_MUTATION_LOCK:
cfg = load_config()
hooks_cfg = cfg.get("hooks")
if not isinstance(hooks_cfg, dict):
- hooks_cfg = {}
- cfg["hooks"] = hooks_cfg
+ hooks_cfg = cfg["hooks"] = {}
entries = hooks_cfg.get(event)
if not isinstance(entries, list):
- entries = []
- hooks_cfg[event] = entries
-
+ entries = hooks_cfg[event] = []
new_entry: Dict[str, Any] = {"command": command}
if body.matcher:
new_entry["matcher"] = body.matcher
@@ -891,7 +715,6 @@ async def create_hook(body: HookCreate):
approved = True
except Exception:
_log.exception("hook consent record failed")
-
return {"ok": True, "event": event, "command": command, "approved": approved}
return await asyncio.to_thread(_run)
@@ -900,13 +723,9 @@ async def create_hook(body: HookCreate):
@router.delete("/api/ops/hooks")
async def delete_hook(body: HookDelete):
"""Remove a hook from config.yaml and revoke its consent allowlist entry."""
- from hermes_cli.web_server import _CONFIG_MUTATION_LOCK
from agent import shell_hooks
- event = (body.event or "").strip()
- command = (body.command or "").strip()
- if not event or not command:
- raise HTTPException(status_code=400, detail="event and command are required")
+ event, command = _hook_body_fields(body)
def _run():
removed = False
@@ -925,28 +744,21 @@ async def delete_hook(body: HookDelete):
if not hooks_cfg:
cfg.pop("hooks", None)
save_config(cfg)
-
# Revoke consent regardless so a re-add re-prompts.
- try:
+ with contextlib.suppress(Exception):
shell_hooks.revoke(command)
- except Exception:
- pass
return removed
- removed = await asyncio.to_thread(_run)
-
- if not removed:
+ if not await asyncio.to_thread(_run):
raise HTTPException(status_code=404, detail="No matching hook found")
return {"ok": True}
@router.get("/api/ops/checkpoints")
async def list_checkpoints():
- """List the /rollback shadow store checkpoints (read-only)."""
- # Checkpoints live under <hermes_home>/checkpoints/. Surface a count +
- # total size so the dashboard can show what a prune would reclaim; the
- # actual prune is a spawned action so confirmation/pruning logic stays
- # in one place (the CLI).
+ """/rollback shadow-store checkpoints (read-only): count + size per session
+ so the UI can show what a prune reclaims; pruning itself is a spawned CLI
+ action so the confirmation logic stays in one place."""
cp_dir = get_hermes_home() / "checkpoints"
sessions = []
total_bytes = 0
@@ -956,8 +768,7 @@ async def list_checkpoints():
for child in children:
if not child.is_dir():
continue
- size = 0
- count = 0
+ size = count = 0
for f in child.rglob("*"):
if f.is_file():
try:
@@ -966,19 +777,13 @@ async def list_checkpoints():
except OSError:
pass
total_bytes += size
- sessions.append({
- "session": child.name,
- "files": count,
- "bytes": size,
- })
+ sessions.append({"session": child.name, "files": count, "bytes": size})
return {"sessions": sessions, "total_bytes": total_bytes}
@router.post("/api/ops/checkpoints/prune")
async def prune_checkpoints():
- try:
- proc = _spawn_hermes_action(["checkpoints", "prune"], "checkpoints-prune")
- except Exception as exc:
- _log.exception("Failed to spawn checkpoints prune")
- raise HTTPException(status_code=500, detail=f"Failed to prune checkpoints: {exc}")
- return {"ok": True, "pid": proc.pid, "name": "checkpoints-prune"}
+ return _spawn_action(
+ ["checkpoints", "prune"], "checkpoints-prune",
+ log_msg="Failed to spawn checkpoints prune", prefix="Failed to prune checkpoints",
+ )