Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
40a3b9f
C1: add resolve_channel_model per-route model resolver
banditburai May 31, 2026
659b393
C1: bridge channel_models for all platforms; channel_skill_bindings f…
banditburai May 31, 2026
db394fd
C1: apply per-route channel_models override in runtime resolution (se…
banditburai May 31, 2026
77ec864
C1: Telegram group_topics per-topic model + unified skill parity
banditburai May 31, 2026
d8b6efe
C1: per-topic system_prompt overlay applies to dm_topics and group_to…
banditburai May 31, 2026
e641987
C2: add gateway.routing.resolve_profile_route (platform-agnostic, exa…
banditburai May 31, 2026
c321896
C2: load + fail-closed validate gateway.profile_routing
banditburai May 31, 2026
23751fc
C2: parameterize build_session_key profile prefix (default 'main' = i…
banditburai May 31, 2026
6d9a879
C2: worker arg builder (no --replace) + HERMES_GATEWAY_ONLY_PLATFORMS…
banditburai May 31, 2026
23220ea
C2: front-owned worker pool (spawn/probe/idle-evict/respawn + one-loo…
banditburai May 31, 2026
35ab4e9
C2: worker_client — POST /v1/runs, relay SSE deltas + approval round-…
banditburai May 31, 2026
cb0651d
C2: route inbound messages to per-profile workers (host path unchange…
banditburai May 31, 2026
aca5251
C2: per-profile token-bucket rate limit before dispatch (#9514)
banditburai May 31, 2026
b184e70
C2: scope /new and /reset to the routed worker session (#18423)
banditburai May 31, 2026
18a782c
C2: regression guards for per-peer DM keys + thread→parent routing
banditburai May 31, 2026
943c8ee
C3: inbound media_refs claim-check on /v1/runs
banditburai May 31, 2026
4f83947
C3: outbound response.media SSE + front upload via existing send_* (#…
banditburai May 31, 2026
856ec31
C3: media-ref auth + cleanup + safe_root confinement (harvest #18510;…
banditburai May 31, 2026
28cdd64
C4: /profile command — list + persisted per-chat binding
banditburai May 31, 2026
56b7318
C4: @mention per-turn profile override (binding untouched)
banditburai May 31, 2026
8cac327
C5: harden worker pool — crash breaker on lazy-respawn + cooldown sel…
banditburai May 31, 2026
9915da4
C5: harden routed dispatch — lifecycle wiring, session continuity, re…
banditburai May 31, 2026
cf81c88
C5: media_spool — drop dead sub-clause in kind_for
banditburai May 31, 2026
51740cc
test: real-socket front<->worker round-trip (dispatch, continue_sessi…
banditburai Jun 1, 2026
1504f3f
fix: guard self.config in the per-route model overlay
banditburai Jun 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions gateway/chat_bindings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Persisted per-chat profile bindings (Tier-2 manual control, salvaged from #24914).

A `/profile <name>` binding is a deliberate user action, so it overrides the
config routing table for that chat. Bindings live in a small JSON file under
the sessions dir and survive restarts.
"""

from __future__ import annotations

import json
import re
from pathlib import Path

from gateway.session import SessionSource

# A leading @<profile> followed by a message body (profile names are
# [a-z0-9][a-z0-9_-]*). Requires a body so a bare "@name" isn't a route.
_MENTION_RE = re.compile(r"^@([a-z0-9][a-z0-9_-]*)\s+(\S.*)$", re.IGNORECASE | re.DOTALL)


def parse_profile_mention(text: str) -> tuple[str | None, str]:
"""Split a leading ``@profile`` override off *text*.

Returns ``(profile, body)`` for ``@coder do x`` → ``("coder", "do x")``,
else ``(None, text)`` unchanged. The caller still gates on whether the
named profile exists before routing.
"""
m = _MENTION_RE.match(text or "")
return (m.group(1), m.group(2)) if m else (None, text)


def chat_binding_key(source: SessionSource) -> str:
"""Stable per-chat key (platform + chat + thread)."""
return f"{source.platform.value}:{source.chat_id or ''}:{source.thread_id or ''}"


class ChatBindings:
def __init__(self, path: Path | str):
self.path = Path(path)
try:
self._data = json.loads(self.path.read_text())
except (FileNotFoundError, json.JSONDecodeError):
self._data = {}

def get(self, key: str) -> str | None:
return self._data.get(key)

def set(self, key: str, profile: str) -> None:
self._data[key] = profile
self._save()

def clear(self, key: str) -> None:
self._data.pop(key, None)
self._save()

def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(self._data, indent=2))
58 changes: 57 additions & 1 deletion gateway/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,38 @@ def from_dict(cls, data: Dict[str, Any]) -> "StreamingConfig":
}


_ROUTE_MATCH_KEYS = ("platform", "chat_id", "channel_id", "thread_id", "guild_id", "user_id")


def _validate_profile_routing(routing: dict) -> dict:
"""Fail-closed validation of a profile_routing table (see design §8).

Raises ValueError on an unknown/invalid target profile or two routes with
an identical match-key set. An absent table is handled by the caller.
"""
from hermes_cli.profiles import profile_exists, validate_profile_name

routes = routing.get("routes") or []
seen: set[tuple] = set()
for route in routes:
if not isinstance(route, dict):
raise ValueError(f"profile_routing route must be a mapping, got {type(route).__name__}")
profile = route.get("profile")
if not profile:
raise ValueError(f"profile_routing route is missing a 'profile': {route!r}")
validate_profile_name(str(profile))
if not profile_exists(str(profile)):
raise ValueError(f"profile_routing references unknown profile {profile!r}")
signature = tuple((k, str(route[k])) for k in _ROUTE_MATCH_KEYS if k in route)
if signature in seen:
raise ValueError(f"Duplicate profile_routing route for match {dict(signature)!r}")
seen.add(signature)
for name in (routing.get("default"),):
if name and not profile_exists(str(name)):
raise ValueError(f"profile_routing default references unknown profile {name!r}")
return routing


@dataclass
class GatewayConfig:
"""
Expand Down Expand Up @@ -485,6 +517,10 @@ class GatewayConfig:
# STT settings
stt_enabled: bool = True # Whether to auto-transcribe inbound voice messages

# Tier-2 profile routing table (gateway.profile_routing). None => no
# routing; every message stays on the host profile (legacy behavior).
profile_routing: Optional[dict] = None

# Session isolation in shared chats
group_sessions_per_user: bool = True # Isolate group/channel sessions per participant when user IDs are available
thread_sessions_per_user: bool = False # When False (default), threads are shared across all participants
Expand Down Expand Up @@ -636,6 +672,12 @@ def from_dict(cls, data: Dict[str, Any]) -> "GatewayConfig":
if stt_enabled is None:
stt_enabled = data.get("stt", {}).get("enabled") if isinstance(data.get("stt"), dict) else None

profile_routing = data.get("profile_routing")
if isinstance(profile_routing, dict):
profile_routing = _validate_profile_routing(profile_routing)
else:
profile_routing = None

group_sessions_per_user = data.get("group_sessions_per_user")
thread_sessions_per_user = data.get("thread_sessions_per_user")
unauthorized_dm_behavior = _normalize_unauthorized_dm_behavior(
Expand All @@ -662,6 +704,7 @@ def from_dict(cls, data: Dict[str, Any]) -> "GatewayConfig":
data.get("filter_silence_narration"), True
),
stt_enabled=_coerce_bool(stt_enabled, True),
profile_routing=profile_routing,
group_sessions_per_user=_coerce_bool(group_sessions_per_user, True),
thread_sessions_per_user=_coerce_bool(thread_sessions_per_user, False),
unauthorized_dm_behavior=unauthorized_dm_behavior,
Expand Down Expand Up @@ -748,6 +791,13 @@ def load_gateway_config() -> GatewayConfig:
if isinstance(stt_cfg, dict):
gw_data["stt"] = stt_cfg

# profile_routing is gateway-level (cross-platform); accept it under
# gateway: or at the top level.
_routing = yaml_cfg.get("gateway", {}).get("profile_routing") if isinstance(yaml_cfg.get("gateway"), dict) else None
_routing = _routing or yaml_cfg.get("profile_routing")
if _routing is not None:
gw_data["profile_routing"] = _routing

if "group_sessions_per_user" in yaml_cfg:
gw_data["group_sessions_per_user"] = yaml_cfg["group_sessions_per_user"]

Expand Down Expand Up @@ -886,14 +936,20 @@ def _merge_platform_map(source_platforms: Any) -> None:
bridged["group_allow_admin_from"] = platform_cfg["group_allow_admin_from"]
if "group_user_allowed_commands" in platform_cfg:
bridged["group_user_allowed_commands"] = platform_cfg["group_user_allowed_commands"]
if plat in {Platform.DISCORD, Platform.SLACK} and "channel_skill_bindings" in platform_cfg:
if plat in {Platform.DISCORD, Platform.SLACK, Platform.TELEGRAM} and "channel_skill_bindings" in platform_cfg:
bridged["channel_skill_bindings"] = platform_cfg["channel_skill_bindings"]
if "channel_prompts" in platform_cfg:
channel_prompts = platform_cfg["channel_prompts"]
if isinstance(channel_prompts, dict):
bridged["channel_prompts"] = {str(k): v for k, v in channel_prompts.items()}
else:
bridged["channel_prompts"] = channel_prompts
if "channel_models" in platform_cfg:
channel_models = platform_cfg["channel_models"]
if isinstance(channel_models, dict):
bridged["channel_models"] = {str(k): v for k, v in channel_models.items()}
else:
bridged["channel_models"] = channel_models
if "gateway_restart_notification" in platform_cfg:
bridged["gateway_restart_notification"] = platform_cfg["gateway_restart_notification"]
enabled_was_explicit = "enabled" in platform_cfg
Expand Down
178 changes: 178 additions & 0 deletions gateway/media_spool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
"""Media claim-check spool (Tier-2, design §6).

A ``media_ref`` is an opaque token, **never a path on the wire**. The front
mints refs for inbound media; the worker resolves each ref to local bytes and
materializes them into its own cache, feeding the existing media path with zero
downstream change. Outbound, the worker mints refs the front resolves + uploads.

MVP resolver = a shared spool directory both processes can read. The wire
contract (``MediaRef.to_wire``) carries only metadata, so the end-state
HTTP-fetch resolver is an additive swap with no schema change.
"""

from __future__ import annotations

import hashlib
import hmac
import os
import secrets
from dataclasses import dataclass
from pathlib import Path

VALID_KINDS = frozenset({"image", "voice", "video", "document"})


def sign_ref(run_id: str, ref: str, secret: str) -> str:
"""HMAC binding a ref to its run, so a token can't be replayed across runs."""
return hmac.new(secret.encode(), f"{run_id}:{ref}".encode(), hashlib.sha256).hexdigest()


def verify_ref(run_id: str, ref: str, token: str, secret: str) -> bool:
return hmac.compare_digest(sign_ref(run_id, ref, secret), token or "")


def confine_to_safe_root(path: str, safe_root: Path | str) -> Path:
"""Resolve *path* under *safe_root*, rejecting any escape (harvested from #18510)."""
root = Path(safe_root).resolve()
candidate = Path(path)
resolved = (candidate if candidate.is_absolute() else root / candidate).resolve()
if resolved != root and root not in resolved.parents:
raise ValueError(f"path {path!r} escapes safe_root {safe_root!r}")
return resolved


def default_spool_root() -> Path:
"""Shared spool dir both front and worker can read.

Anchored to the default hermes root (not a per-profile home) so the
transport-owner front and a worker that resolved a different HERMES_HOME
still meet on the same filesystem path. Override with HERMES_MEDIA_SPOOL.
"""
override = os.getenv("HERMES_MEDIA_SPOOL")
if override:
return Path(override)
from hermes_constants import get_default_hermes_root

return get_default_hermes_root() / "cache" / "gateway_media_spool"


@dataclass
class MediaRef:
ref: str
filename: str
mime: str
kind: str
size: int
as_document: bool = False
is_voice: bool = False

def to_wire(self) -> dict:
"""Serialize for the request/SSE body — metadata only, never a path."""
return {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sign_ref and verify_ref are never represented in this wire object. The worker materializes MediaRef.ref without verification, so the claimed per-run capability is not enforced. Include a scoped signature in this payload and verify it before materialization.

"ref": self.ref,
"filename": self.filename,
"mime": self.mime,
"kind": self.kind,
"size": self.size,
"as_document": self.as_document,
"is_voice": self.is_voice,
}

@classmethod
def from_wire(cls, data: dict) -> "MediaRef":
return cls(
ref=str(data["ref"]),
filename=str(data.get("filename", "")),
mime=str(data.get("mime", "application/octet-stream")),
kind=str(data.get("kind", "document")),
size=int(data.get("size", 0)),
as_document=bool(data.get("as_document", False)),
is_voice=bool(data.get("is_voice", False)),
)


class MediaSpool:
def __init__(self, root: Path | str):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self._filenames: dict[str, str] = {}

def _path(self, ref: str) -> Path:
# Refs come off the wire — confine to the spool root, never trust them.
return confine_to_safe_root(ref, self.root)

def mint(self, data: bytes, *, filename: str, mime: str, kind: str, **flags) -> MediaRef:
ref = secrets.token_hex(24)
self._path(ref).write_bytes(data)
self._filenames[ref] = filename
return MediaRef(
ref=ref, filename=filename, mime=mime, kind=kind, size=len(data),
as_document=bool(flags.get("as_document", False)),
is_voice=bool(flags.get("is_voice", False)),
)

def resolve(self, ref: str) -> bytes:
path = self._path(ref)
if not path.is_file():
raise KeyError(f"unknown media ref {ref!r}")
return path.read_bytes()

def materialize(self, ref: str, dest_dir: Path, *, filename: str | None = None) -> Path:
"""Write the ref's bytes into *dest_dir*, preserving the original suffix."""
data = self.resolve(ref)
suffix = Path(filename or self._filenames.get(ref, "") or ref).suffix
dest = Path(dest_dir) / f"{ref}{suffix}"
dest.write_bytes(data)
return dest

def unlink(self, ref: str) -> None:
self._filenames.pop(ref, None)
try:
os.unlink(self._path(ref))
except FileNotFoundError:
pass


_VIDEO_EXTS = frozenset({".mp4", ".mov", ".webm", ".mkv", ".avi"})
_AUDIO_EXTS = frozenset({".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac", ".aac"})
_IMAGE_EXTS = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".svg"})


def kind_for(path: str, is_voice: bool) -> str:
ext = Path(path).suffix.lower()
if is_voice:
return "voice"
if ext in _IMAGE_EXTS:
return "image"
if ext in _VIDEO_EXTS:
return "video"
if ext in _AUDIO_EXTS:
return "voice"
return "document"


def mint_outbound(spool: MediaSpool, media_files: list[tuple[str, bool]]) -> list[dict]:
"""Mint refs for worker-produced files (path, is_voice) → wire dicts."""
import mimetypes

refs = []
for path, is_voice in media_files:
p = Path(path)
kind = kind_for(path, is_voice)
mime = mimetypes.guess_type(path)[0] or "application/octet-stream"
ref = spool.mint(p.read_bytes(), filename=p.name, mime=mime, kind=kind, is_voice=is_voice)
refs.append(ref.to_wire())
return refs


def materialize_inbound(spool: MediaSpool, refs: list[dict], dest_dir: Path) -> list[tuple[Path, MediaRef]]:
"""Resolve inbound wire refs to local files in *dest_dir* (worker side).

Uses only the wire metadata, so it works cross-process from a spool that
never minted these refs itself.
"""
out: list[tuple[Path, MediaRef]] = []
for data in refs:
mref = MediaRef.from_wire(data)
out.append((spool.materialize(mref.ref, dest_dir, filename=mref.filename), mref))
return out
Loading
Loading