Repository navigation
Route messages to per-profile workers behind one bot token #36872
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+2,846
−15
Closed
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 659b393
C1: bridge channel_models for all platforms; channel_skill_bindings f…
banditburai db394fd
C1: apply per-route channel_models override in runtime resolution (se…
banditburai 77ec864
C1: Telegram group_topics per-topic model + unified skill parity
banditburai d8b6efe
C1: per-topic system_prompt overlay applies to dm_topics and group_to…
banditburai e641987
C2: add gateway.routing.resolve_profile_route (platform-agnostic, exa…
banditburai c321896
C2: load + fail-closed validate gateway.profile_routing
banditburai 23751fc
C2: parameterize build_session_key profile prefix (default 'main' = i…
banditburai 6d9a879
C2: worker arg builder (no --replace) + HERMES_GATEWAY_ONLY_PLATFORMS…
banditburai 23220ea
C2: front-owned worker pool (spawn/probe/idle-evict/respawn + one-loo…
banditburai 35ab4e9
C2: worker_client — POST /v1/runs, relay SSE deltas + approval round-…
banditburai cb0651d
C2: route inbound messages to per-profile workers (host path unchange…
banditburai aca5251
C2: per-profile token-bucket rate limit before dispatch (#9514)
banditburai b184e70
C2: scope /new and /reset to the routed worker session (#18423)
banditburai 18a782c
C2: regression guards for per-peer DM keys + thread→parent routing
banditburai 943c8ee
C3: inbound media_refs claim-check on /v1/runs
banditburai 4f83947
C3: outbound response.media SSE + front upload via existing send_* (#…
banditburai 856ec31
C3: media-ref auth + cleanup + safe_root confinement (harvest #18510;…
banditburai 28cdd64
C4: /profile command — list + persisted per-chat binding
banditburai 56b7318
C4: @mention per-turn profile override (binding untouched)
banditburai 8cac327
C5: harden worker pool — crash breaker on lazy-respawn + cooldown sel…
banditburai 9915da4
C5: harden routed dispatch — lifecycle wiring, session continuity, re…
banditburai cf81c88
C5: media_spool — drop dead sub-clause in kind_for
banditburai 51740cc
test: real-socket front<->worker round-trip (dispatch, continue_sessi…
banditburai 1504f3f
fix: guard self.config in the per-route model overlay
banditburai File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
| "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 | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sign_refandverify_refare never represented in this wire object. The worker materializesMediaRef.refwithout verification, so the claimed per-run capability is not enforced. Include a scoped signature in this payload and verify it before materialization.