Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions README-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ Entries are split on Hermes' built-in delimiter §.

The response includes entry count, char count, configured/default char limits, usage percentage, file path, and modified timestamp.

Optional `memory_profile` selects a profile for these two files independently of the host's `profile` parameter. Omitted, empty, or `current` uses the request's active profile. Explicit names require the original request's host authorization and the target profile's plugin consent before reading files or limits in that profile's context-local scope. Native profile grants cannot read another profile (403); disabled or unavailable target plugins return 404. For unrestricted host sessions, invalid names return 400 and missing profiles return 404. Hosts unable to verify cross-profile authority return 501 for explicit names, including isolated plugin hosts whose IPC admission does not carry the principal's profile authority.

### GET `/builtin/profiles`

Returns `{ "profiles": [{ "name": "current", "label": "Active profile", "hermes_home": "..." }], "switching_supported": false }` when host authorization is unavailable. Hosts with native discovery and the complete authorization boundary also return live profiles the request may access and that permit this plugin, with their labels and home paths, and set `switching_supported` to true. Inaccessible, disabled, missing, and reserved names are omitted before reading their display metadata. The `current` entry always represents the request's active home, including a custom `HERMES_HOME`. This endpoint does not read memory files or contact memory providers.

### GET `/session-search`

Runs an explicit read-only search over previous Hermes sessions through Hermes' built-in `session_search` tool. This endpoint is not called from `/snapshot` or page load; the UI calls it only after the user submits a query.
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,15 @@ Top summary:

Built-in memory section:

- Profile / bot selector for the active profile and other profiles authorized by the host in both Dashboard and Desktop
- Agent memory card (`MEMORY.md`)
- User profile card (`USER.md`)
- path, file existence, modification time
- entry count and char usage bar
- parsed entries

The built-in memory selector changes only the two file cards. Provider and session views continue to follow the host's active profile. Each card shows the selected profile's file path and character limit. Switching profiles or Desktop connections hides the previous files while the new files load. Use the built-in refresh button to reload files and discover newly created profiles. Cross-profile choices require both host access authorization and the target profile's plugin consent. Hosts that cannot verify that authority, including isolated plugin hosts that receive only an admission boolean, offer the active profile only.

Session search section:

- explicit query box for previous Hermes sessions
Expand Down
78 changes: 76 additions & 2 deletions dashboard/dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
e("div", { className: "memory-ui-section-header" },
e("div", null,
e("h2", null, "Built-in memory"),
e("p", null, "Read-only view of MEMORY.md and USER.md from the active Hermes profile.")
e("p", null, "Read-only view of MEMORY.md and USER.md from the selected Hermes profile.")
),
e(Badge, { tone: "outline" }, builtin.total_entries + " total entries")
),
Expand All @@ -172,6 +172,80 @@
);
}

function BuiltinProfileBrowser(props) {
const [profile, setProfile] = useState("current");
const [profiles, setProfiles] = useState([{ name: "current", label: "Active profile" }]);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
const [profilesError, setProfilesError] = useState(null);
const [revision, setRevision] = useState(0);

useEffect(function () {
let active = true;
fetchPluginJSON("/api/plugins/hermes-memory-ui/builtin/profiles")
.then(function (payload) {
if (active) {
if (payload === STALE_PROFILE_RESPONSE) {
setProfilesError("The host profile changed. Refresh built-in memory to reload profiles.");
} else {
setProfiles(payload.profiles || [{ name: "current", label: "Active profile" }]);
setProfilesError(null);
}
}
})
.catch(function (err) { if (active) setProfilesError(err.message || String(err)); });
return function () { active = false; };
}, [revision]);

useEffect(function () {
if (profile === "current" && revision === 0) return;
let active = true;
setError(null);
const path = "/api/plugins/hermes-memory-ui/builtin?memory_profile=" + encodeURIComponent(profile);
fetchPluginJSON(path)
.then(function (payload) {
if (active) {
if (payload === STALE_PROFILE_RESPONSE) {
setError({ profile: profile, source: props.builtin, message: "The host profile changed. Refresh built-in memory to reload." });
} else {
setResult({ profile: profile, source: props.builtin, builtin: payload });
}
}
})
.catch(function (err) { if (active) setError({ profile: profile, source: props.builtin, message: err.message || String(err) }); });
return function () { active = false; };
}, [profile, revision]);

const currentError = error && error.profile === profile && (profile !== "current" || error.source === props.builtin)
? error.message : null;
const builtin = currentError ? null : profile === "current"
? result && result.profile === "current" && result.source === props.builtin ? result.builtin : props.builtin
: result && result.profile === profile ? result.builtin : null;
const options = profiles.some(function (item) { return item.name === profile; })
? profiles : profiles.concat([{ name: profile, label: profile + " (unavailable)" }]);
return e("div", { className: "memory-ui-section" },
e("div", { className: "memory-ui-controls" },
e("label", { className: "memory-ui-control" },
e("span", null, "Built-in memory profile / bot"),
e("select", {
className: "memory-ui-select",
value: profile,
onChange: function (event) { setProfile(event.target.value); setRevision(0); },
"aria-label": "Built-in memory profile / bot"
}, options.map(function (item) {
return e("option", { key: item.name, value: item.name }, item.label || item.name);
}))
),
e(Button, { variant: "outline", onClick: function () { setRevision(function (value) { return value + 1; }); } }, "Refresh built-in memory")
),
e("p", { className: "memory-ui-muted" }, "Select a profile to read its MEMORY.md and USER.md. Provider and session views follow the host's active profile."),
e(ErrorBox, { error: profilesError }),
e(ErrorBox, { error: currentError }),
builtin ? e(BuiltinSection, { builtin: builtin })
: currentError ? null : e(EmptyState, null, "Loading built-in memory...")
);
}

function SessionSearchResultRow(props) {
const result = props.result || {};
const messages = (result.messages || []).slice(0, 4);
Expand Down Expand Up @@ -1096,7 +1170,7 @@
)
),
snapshot ? e(React.Fragment, null,
e(BuiltinSection, { builtin: builtin }),
e(BuiltinProfileBrowser, { builtin: builtin }),
e(Separator, null),
e(SessionSearchSection, null),
showHolographic ? e(React.Fragment, null,
Expand Down
113 changes: 110 additions & 3 deletions dashboard/plugin_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import importlib
import importlib.util
import json
import logging
import os
import re
import shutil
Expand All @@ -23,12 +24,13 @@
import threading
import time
import urllib.parse
from contextlib import asynccontextmanager
from contextvars import copy_context
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple

try:
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi import APIRouter, Depends, HTTPException, Query, Request
except Exception: # Allows local syntax/import tests outside the dashboard.
class APIRouter: # type: ignore
def __init__(self, *_args, **_kwargs):
Expand All @@ -49,6 +51,9 @@ def __init__(self, status_code: int, detail: str):
def Query(default=None, **_kwargs): # type: ignore
return default

class Request: # type: ignore
pass


async def _profile_request_scope(profile: Optional[str] = Query(None)):
"""Bind one plugin request to its explicitly selected Hermes profile.
Expand Down Expand Up @@ -371,6 +376,97 @@ def _builtin_payload(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
}


def _builtin_profile_access(request: Optional[Request]):
"""Host policy hooks only when the original request authority is available.

The isolated plugin host forwards admission, but strips credentials and the
native ticket's profile authority. That boolean cannot authorize another
profile. Older hosts without the complete policy boundary also stay local.
"""
if request is None or "hosted_http_authenticated" in request.scope.get("state", {}):
return None
try:
from hermes_cli.web_server import _require_token
from hermes_cli.dashboard_auth.native_http import _own_profile
from hermes_cli.web_server_dashboard import _plugin_api_request_refused
from hermes_cli.web_server_profiles import _config_profile_scope
except (ImportError, AttributeError):
return None
_require_token(request)
return _own_profile, _plugin_api_request_refused, _config_profile_scope


@asynccontextmanager
async def _builtin_selected_scope(request: Optional[Request], name: str, access):
if access is None:
raise HTTPException(status_code=501, detail="This Hermes host cannot authorize cross-profile memory access.")
own_profile, consent_refused, profile_scope = access
principal = getattr(request.state, "native_http_principal", None)
if principal is not None:
try:
own_profile(name, principal["profile_id"])
except PermissionError as exc:
raise HTTPException(status_code=403, detail="profile_scope_mismatch") from exc
with profile_scope(name):
if await consent_refused("hermes-memory-ui"):
raise HTTPException(status_code=404, detail="Plugin not found")
yield


async def _builtin_profiles_payload(request: Optional[Request] = None) -> Dict[str, Any]:
"""Discover request-addressable homes from Hermes' live-profile registry.

The current choice also covers custom HERMES_HOME deployments. Never guess
profile paths on older hosts: discovery is useful only when the same host
can safely scope the subsequent memory read.
"""
entries = [{
"name": "current",
"label": "Active profile",
"hermes_home": str(_hermes_home()),
}]
access = _builtin_profile_access(request)
if access is None:
return {"profiles": entries, "switching_supported": False}
try:
from hermes_cli.profiles import get_profile_dir, list_profile_names, profile_exists, validate_profile_name
except (ImportError, AttributeError):
return {"profiles": entries, "switching_supported": False}

try:
from hermes_cli.profiles import read_profile_meta
except (ImportError, AttributeError):
read_profile_meta = None

for name in list_profile_names():
# Legacy directories can remain in the registry under names the host's
# request resolver now rejects. Offer only profiles it can address.
try:
validate_profile_name(name)
except ValueError:
continue
# A profile may be removed between discovery and this response.
if name == "current" or not profile_exists(name):
continue
try:
async with _builtin_selected_scope(request, name, access):
home = get_profile_dir(name)
meta = read_profile_meta(home) if read_profile_meta else {}
except Exception as exc:
# Discovery must survive one broken profile's secret sources or
# metadata. Explicit reads still surface that target's failure.
if not isinstance(exc, HTTPException) or exc.status_code not in (400, 403, 404):
logging.getLogger(__name__).warning("Skipping memory profile %s: %s", name, _safe_error(exc))
continue
title = str(meta.get("bot_title") or meta.get("display_name") or "").strip()
entries.append({
"name": name,
"label": f"{title} ({name})" if title and title != name else name,
"hermes_home": str(home),
})
return {"profiles": entries, "switching_supported": True}


def _canonical_session_source(source: str) -> str:
"""Return the canonical Hermes session source for dashboard filter values."""
if not isinstance(source, str):
Expand Down Expand Up @@ -2600,8 +2696,19 @@ async def status() -> Dict[str, Any]:


@router.get("/builtin")
async def builtin() -> Dict[str, Any]:
return _builtin_payload()
async def builtin(memory_profile: Optional[str] = None, request: Request = None) -> Dict[str, Any]:
# This selector is independent of the host's ?profile= scope. In particular,
# Desktop's ctx.rest continues to scope all other providers to its active bot.
requested = (memory_profile or "").strip()
if not requested or requested.lower() == "current":
return _builtin_payload()
async with _builtin_selected_scope(request, requested, _builtin_profile_access(request)):
return _builtin_payload()


@router.get("/builtin/profiles")
async def builtin_profiles(request: Request = None) -> Dict[str, Any]:
return await _builtin_profiles_payload(request)


@router.get("/session-search")
Expand Down
Loading
Loading