Merge branch 'simp/r3-36-F' into simp/r3-36
This commit is contained in:
+147
-294
@@ -1,12 +1,7 @@
|
||||
"""Config / projects / setup JSON-RPC handlers.
|
||||
|
||||
Handlers and module-level helpers are rebound onto server.py's globals at
|
||||
install time (see method_ctx.bind_module), so bodies reference server.py
|
||||
globals bare (``_ok``, ``_err``, ``_load_cfg``, ``_sessions``, ...).
|
||||
``config.set`` still lives in server.py.
|
||||
"""Config / projects / setup JSON-RPC handlers. Bodies are rebound onto server.py's globals
|
||||
(method_ctx.bind_module) and reference them bare. ``config.set`` lives in methods_config_set.
|
||||
"""
|
||||
|
||||
|
||||
from .method_ctx import HandlerRegistry, bind_module
|
||||
|
||||
from hermes_constants import DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES
|
||||
@@ -16,168 +11,116 @@ method = _registry.method
|
||||
_profile_scoped = _registry.profile_scoped
|
||||
|
||||
|
||||
def _projects_handler(name: str):
|
||||
"""``@method(name)`` (profile-scoped) whose body's uncaught exception becomes ``_err(rid, 5061)``."""
|
||||
def deco(fn):
|
||||
def handler(rid, params: dict) -> dict:
|
||||
try:
|
||||
return fn(rid, params)
|
||||
except Exception as e:
|
||||
return _err(rid, 5061, str(e))
|
||||
return method(name)(_profile_scoped(handler))
|
||||
return deco
|
||||
|
||||
|
||||
def _reconcile_repo_discovery(pdb, conn, policy, policy_key):
|
||||
pdb.reconcile_discovered_repos_policy(
|
||||
conn, policy_key, preserve_unversioned=_repo_discovery_policy_is_default(policy)
|
||||
)
|
||||
conn, policy_key, preserve_unversioned=_repo_discovery_policy_is_default(policy))
|
||||
|
||||
|
||||
@method("projects.discover_repos")
|
||||
@_profile_scoped
|
||||
@_projects_handler("projects.discover_repos")
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Repos for the desktop overview: scanned-from-disk (cached) ∪ session-derived."""
|
||||
try:
|
||||
with _profile_db(params) as db:
|
||||
if db is None:
|
||||
return _ok(rid, {"repos": []})
|
||||
from hermes_cli import projects_db as pdb
|
||||
|
||||
policy = _repo_discovery_policy()
|
||||
with pdb.connect_closing() as conn:
|
||||
_reconcile_repo_discovery(pdb, conn, policy, _repo_discovery_policy_key(policy))
|
||||
# `scan=true` (desktop in remote-gateway mode): the desktop's
|
||||
# native scan only sees its local filesystem, so ask the host
|
||||
# to scan the policy roots itself so zero-session repos surface.
|
||||
if params.get("scan") and policy["enabled"]:
|
||||
_scan_discovered_repos_remote(conn, policy)
|
||||
repos = _discover_repos_payload(db, conn=conn, include_cached=policy["enabled"])
|
||||
return _ok(rid, {"repos": repos, "discovery_policy": policy})
|
||||
except Exception as e:
|
||||
return _err(rid, 5061, str(e))
|
||||
|
||||
|
||||
@method("projects.record_repos")
|
||||
@_profile_scoped
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Persist git repo roots found by the client's filesystem scan (the native
|
||||
crawl runs on the desktop), then return the merged repo list."""
|
||||
try:
|
||||
with _profile_db(params) as db:
|
||||
if db is None:
|
||||
return _ok(rid, {"repos": []})
|
||||
from hermes_cli import projects_db as pdb
|
||||
|
||||
policy = _repo_discovery_policy()
|
||||
policy_key = _repo_discovery_policy_key(policy)
|
||||
incoming_raw = params.get("discovery_policy")
|
||||
incoming_policy = (
|
||||
_repo_discovery_policy(incoming_raw) if isinstance(incoming_raw, dict) else None
|
||||
)
|
||||
incoming_matches = (
|
||||
incoming_policy is not None
|
||||
and _repo_discovery_policy_key(incoming_policy) == policy_key
|
||||
)
|
||||
accept_legacy_default = (
|
||||
incoming_policy is None and _repo_discovery_policy_is_default(policy)
|
||||
)
|
||||
|
||||
pairs: list[tuple[str, str | None]] = []
|
||||
for item in params.get("repos") or []:
|
||||
if isinstance(item, str):
|
||||
pairs.append((item, None))
|
||||
elif isinstance(item, dict) and item.get("root"):
|
||||
pairs.append((str(item["root"]), item.get("label")))
|
||||
|
||||
with pdb.connect_closing() as conn:
|
||||
_reconcile_repo_discovery(pdb, conn, policy, policy_key)
|
||||
accepted = bool(policy["enabled"] and (incoming_matches or accept_legacy_default))
|
||||
if accepted:
|
||||
pdb.record_discovered_repos(conn, pairs, replace=True, policy_key=policy_key)
|
||||
elif not policy["enabled"]:
|
||||
pdb.clear_discovered_repos(conn, policy_key=policy_key)
|
||||
_reconcile_repo_discovery(pdb, conn, policy, _repo_discovery_policy_key(policy))
|
||||
# `scan=true` (remote-gateway desktop): its native scan only sees its own
|
||||
# filesystem, so the host scans the policy roots so zero-session repos surface.
|
||||
if params.get("scan") and policy["enabled"]:
|
||||
_scan_discovered_repos_remote(conn, policy)
|
||||
repos = _discover_repos_payload(db, conn=conn, include_cached=policy["enabled"])
|
||||
return _ok(rid, {"repos": repos, "discovery_policy": policy})
|
||||
|
||||
with _profile_db(params) as db:
|
||||
return _ok(
|
||||
rid,
|
||||
{
|
||||
"repos": _discover_repos_payload(db, include_cached=policy["enabled"])
|
||||
if db is not None
|
||||
else [],
|
||||
"accepted": accepted,
|
||||
"discovery_policy": policy,
|
||||
},
|
||||
)
|
||||
except Exception as e:
|
||||
return _err(rid, 5061, str(e))
|
||||
|
||||
@_projects_handler("projects.record_repos")
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Persist repo roots found by the client's (desktop-side) scan; return the merged list."""
|
||||
from hermes_cli import projects_db as pdb
|
||||
policy = _repo_discovery_policy()
|
||||
policy_key = _repo_discovery_policy_key(policy)
|
||||
incoming_raw = params.get("discovery_policy")
|
||||
incoming_policy = (
|
||||
_repo_discovery_policy(incoming_raw) if isinstance(incoming_raw, dict) else None)
|
||||
incoming_matches = (incoming_policy is not None
|
||||
and _repo_discovery_policy_key(incoming_policy) == policy_key)
|
||||
accept_legacy_default = (incoming_policy is None
|
||||
and _repo_discovery_policy_is_default(policy))
|
||||
pairs: list[tuple[str, str | None]] = []
|
||||
for item in params.get("repos") or []:
|
||||
if isinstance(item, str):
|
||||
pairs.append((item, None))
|
||||
elif isinstance(item, dict) and item.get("root"):
|
||||
pairs.append((str(item["root"]), item.get("label")))
|
||||
with pdb.connect_closing() as conn:
|
||||
_reconcile_repo_discovery(pdb, conn, policy, policy_key)
|
||||
accepted = bool(policy["enabled"] and (incoming_matches or accept_legacy_default))
|
||||
if accepted:
|
||||
pdb.record_discovered_repos(conn, pairs, replace=True, policy_key=policy_key)
|
||||
elif not policy["enabled"]:
|
||||
pdb.clear_discovered_repos(conn, policy_key=policy_key)
|
||||
with _profile_db(params) as db:
|
||||
repos = ([] if db is None
|
||||
else _discover_repos_payload(db, include_cached=policy["enabled"]))
|
||||
return _ok(rid, {"repos": repos, "accepted": accepted, "discovery_policy": policy})
|
||||
|
||||
|
||||
def _stamped_project_tree(db, params, **kwargs):
|
||||
"""``_build_project_tree`` + profile stamping shared by the two tree RPCs."""
|
||||
from tui_gateway.project_tree import stamp_profile
|
||||
|
||||
tree, active_id = _build_project_tree(db, **kwargs)
|
||||
stamp_profile(tree["projects"], _response_profile_name(params.get("profile")))
|
||||
return tree, active_id
|
||||
|
||||
|
||||
@method("projects.tree")
|
||||
@_profile_scoped
|
||||
@_projects_handler("projects.tree")
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Authoritative project overview: project -> repo -> lane structure with
|
||||
counts + a few preview sessions per project, plus the flat set of session
|
||||
ids claimed by any project (so the desktop excludes them from flat Recents).
|
||||
Lanes carry no session rows here; drill-in uses ``projects.project_sessions``.
|
||||
"""
|
||||
try:
|
||||
with _profile_db(params) as db:
|
||||
if db is None:
|
||||
return _ok(rid, {"projects": [], "active_id": None, "scoped_session_ids": []})
|
||||
tree, active_id = _stamped_project_tree(
|
||||
db,
|
||||
params,
|
||||
preview_limit=int(params.get("preview_limit") or 3),
|
||||
hydrate=False,
|
||||
session_limit=int(params.get("session_limit") or 2000),
|
||||
include_discovered=True,
|
||||
)
|
||||
return _ok(
|
||||
rid,
|
||||
{
|
||||
"projects": tree["projects"],
|
||||
"active_id": active_id,
|
||||
"scoped_session_ids": tree["scoped_session_ids"],
|
||||
},
|
||||
)
|
||||
except Exception as e:
|
||||
return _err(rid, 5061, str(e))
|
||||
"""Project -> repo -> lane overview with counts + a few preview sessions per project, plus
|
||||
the flat set of session ids claimed by any project (excluded from flat Recents). Lanes carry
|
||||
no session rows here; drill-in uses ``projects.project_sessions``."""
|
||||
with _profile_db(params) as db:
|
||||
if db is None:
|
||||
return _ok(rid, {"projects": [], "active_id": None, "scoped_session_ids": []})
|
||||
tree, active_id = _stamped_project_tree(
|
||||
db, params, preview_limit=int(params.get("preview_limit") or 3), hydrate=False,
|
||||
session_limit=int(params.get("session_limit") or 2000), include_discovered=True)
|
||||
return _ok(rid, {
|
||||
"projects": tree["projects"], "active_id": active_id,
|
||||
"scoped_session_ids": tree["scoped_session_ids"]})
|
||||
|
||||
|
||||
@method("projects.project_sessions")
|
||||
@_profile_scoped
|
||||
@_projects_handler("projects.project_sessions")
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Fully hydrated lanes (repo -> lane -> session rows) for one project,
|
||||
built from the same authoritative grouping as ``projects.tree`` so ids and
|
||||
membership match exactly."""
|
||||
try:
|
||||
project_id = str(params.get("project_id") or "")
|
||||
if not project_id:
|
||||
return _err(rid, 5063, "project_id required")
|
||||
|
||||
with _profile_db(params) as db:
|
||||
if db is None:
|
||||
return _ok(rid, {"project": None})
|
||||
# Drill-in only needs the entered project (which has sessions):
|
||||
# skip the zero-session discovery tier.
|
||||
tree, _active = _stamped_project_tree(
|
||||
db,
|
||||
params,
|
||||
preview_limit=0,
|
||||
hydrate=True,
|
||||
session_limit=int(params.get("session_limit") or 5000),
|
||||
include_discovered=False,
|
||||
)
|
||||
proj = next((p for p in tree["projects"] if p["id"] == project_id), None)
|
||||
return _ok(rid, {"project": proj})
|
||||
except Exception as e:
|
||||
return _err(rid, 5061, str(e))
|
||||
"""Fully hydrated lanes for one project, from the same grouping as ``projects.tree``."""
|
||||
project_id = str(params.get("project_id") or "")
|
||||
if not project_id:
|
||||
return _err(rid, 5063, "project_id required")
|
||||
with _profile_db(params) as db:
|
||||
if db is None:
|
||||
return _ok(rid, {"project": None})
|
||||
# Drill-in only needs the entered project: skip the zero-session discovery tier.
|
||||
tree, _active = _stamped_project_tree(
|
||||
db, params, preview_limit=0, hydrate=True,
|
||||
session_limit=int(params.get("session_limit") or 5000), include_discovered=False)
|
||||
proj = next((p for p in tree["projects"] if p["id"] == project_id), None)
|
||||
return _ok(rid, {"project": proj})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# config.get — one getter per key. Each returns the result payload (a dict) or
|
||||
# a full ``_err`` response (dicts containing "error" pass through untouched).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _display_cfg() -> dict:
|
||||
display = _load_cfg().get("display")
|
||||
return display if isinstance(display, dict) else {}
|
||||
# ── config.get — one getter per key; returns the result payload or a full ``_err`` response
|
||||
# (dicts containing "error" pass through untouched).
|
||||
|
||||
|
||||
def _display_mode(cfg: dict, key: str, allowed: frozenset, default: str) -> str:
|
||||
@@ -185,28 +128,24 @@ def _display_mode(cfg: dict, key: str, allowed: frozenset, default: str) -> str:
|
||||
return raw if raw in allowed else default
|
||||
|
||||
|
||||
_DETAILS_MODES = frozenset({"hidden", "collapsed", "expanded"})
|
||||
_THINKING_MODES = frozenset({"collapsed", "truncated", "full"})
|
||||
|
||||
|
||||
def _cfg_get_provider(rid, params):
|
||||
try:
|
||||
from hermes_cli.models import list_available_providers, normalize_provider
|
||||
|
||||
model = _resolve_model()
|
||||
parts = model.split("/", 1)
|
||||
return {
|
||||
"model": model,
|
||||
"provider": normalize_provider(parts[0]) if len(parts) > 1 else "unknown",
|
||||
"providers": list_available_providers(),
|
||||
}
|
||||
"providers": list_available_providers()}
|
||||
except Exception as e:
|
||||
return _err(rid, 5013, str(e))
|
||||
|
||||
|
||||
def _cfg_get_profile(rid, params):
|
||||
from hermes_constants import display_hermes_home
|
||||
|
||||
return {"home": str(_hermes_home), "display": display_hermes_home()}
|
||||
|
||||
|
||||
@@ -218,18 +157,15 @@ def _cfg_get_project(rid, params):
|
||||
|
||||
|
||||
def _cfg_get_indicator(rid, params):
|
||||
# Normalize so a hand-edited config.yaml (stray casing / unknown value)
|
||||
# reads back the SAME value the TUI rendered (frontend falls back to
|
||||
# DEFAULT_INDICATOR_STYLE for the same inputs).
|
||||
# Normalize so a hand-edited config.yaml (stray casing / unknown value) reads back the SAME
|
||||
# value the TUI rendered (frontend falls back to DEFAULT_INDICATOR_STYLE for the same inputs).
|
||||
norm = str((_load_cfg().get("display") or {}).get("tui_status_indicator", "")).strip().lower()
|
||||
return {"value": norm if norm in INDICATOR_STYLES else DEFAULT_INDICATOR_STYLE}
|
||||
|
||||
|
||||
def _cfg_get_personality(rid, params):
|
||||
# EFFECTIVE personality via the single owner — a stale/unknown name in
|
||||
# config must not display as active.
|
||||
# EFFECTIVE personality via the single owner — a stale/unknown name must not show as active.
|
||||
from hermes_cli.personality import active_personality_name
|
||||
|
||||
return {"value": active_personality_name(_load_cfg()) or "none"}
|
||||
|
||||
|
||||
@@ -238,18 +174,12 @@ def _cfg_get_reasoning(rid, params):
|
||||
session = _sessions.get(params.get("session_id", ""))
|
||||
reasoning_config = None
|
||||
if session is not None:
|
||||
if isinstance(session.get("create_reasoning_override"), dict):
|
||||
reasoning_config = session.get("create_reasoning_override")
|
||||
else:
|
||||
agent_reasoning = getattr(session.get("agent"), "reasoning_config", None)
|
||||
if isinstance(agent_reasoning, dict):
|
||||
reasoning_config = agent_reasoning
|
||||
|
||||
reasoning_config = session.get("create_reasoning_override")
|
||||
if not isinstance(reasoning_config, dict):
|
||||
reasoning_config = getattr(session.get("agent"), "reasoning_config", None)
|
||||
if isinstance(reasoning_config, dict):
|
||||
if reasoning_config.get("enabled") is False:
|
||||
effort = "none"
|
||||
else:
|
||||
effort = str(reasoning_config.get("effort") or "medium")
|
||||
enabled = reasoning_config.get("enabled") is not False
|
||||
effort = str(reasoning_config.get("effort") or "medium") if enabled else "none"
|
||||
else:
|
||||
raw_effort = (cfg.get("agent") or {}).get("reasoning_effort", "")
|
||||
# YAML `reasoning_effort: false` means thinking disabled, not "unset".
|
||||
@@ -259,9 +189,8 @@ def _cfg_get_reasoning(rid, params):
|
||||
|
||||
|
||||
def _cfg_get_fast(rid, params):
|
||||
# `config.set fast` is session-scoped, so prefer the session's live/pinned
|
||||
# value over the global key; a pre-build session keeps its pin in
|
||||
# create_service_tier_override.
|
||||
# `config.set fast` is session-scoped: prefer the session's live/pinned value over the
|
||||
# global key (a pre-build session keeps its pin in create_service_tier_override).
|
||||
session = _sessions.get(params.get("session_id", ""))
|
||||
tier = None
|
||||
if session is not None:
|
||||
@@ -287,7 +216,7 @@ def _cfg_get_thinking_mode(rid, params):
|
||||
raw = str((cfg.get("display") or {}).get("thinking_mode", "") or "").strip().lower()
|
||||
if raw in _THINKING_MODES:
|
||||
return {"value": raw}
|
||||
dm = _display_mode(cfg, "details_mode", _DETAILS_MODES, "collapsed")
|
||||
dm = _display_mode(cfg, "details_mode", _DETAIL_MODES, "collapsed")
|
||||
return {"value": "full" if dm == "expanded" else "collapsed"}
|
||||
|
||||
|
||||
@@ -296,27 +225,20 @@ def _cfg_get_theme(rid, params):
|
||||
return {"value": raw if raw in {"auto", "light", "dark"} else "auto"}
|
||||
|
||||
|
||||
def _cfg_get_focus(rid, params):
|
||||
on = bool(_display_cfg().get("focus_view", False))
|
||||
return {"value": "on" if on else "off", "tool_progress": _load_tool_progress_mode()}
|
||||
|
||||
|
||||
def _cfg_get_mtime(rid, params):
|
||||
cfg_path = _hermes_home / "config.yaml"
|
||||
try:
|
||||
mtime = cfg_path.stat().st_mtime if cfg_path.exists() else 0
|
||||
except Exception:
|
||||
return {"mtime": 0}
|
||||
# mcp_rev: hash of the MCP-relevant config sections so the TUI's poller
|
||||
# reloads MCP servers only when their config changed — a /skin write bumps
|
||||
# mtime but must not cost a multi-second MCP reconnect.
|
||||
# mcp_rev: hash of the MCP-relevant sections so the poller reloads MCP servers only when
|
||||
# their config changed — a /skin write bumps mtime but must not cost an MCP reconnect.
|
||||
return {"mtime": mtime, "mcp_rev": _compute_mcp_rev()}
|
||||
|
||||
|
||||
def _config_getters() -> dict:
|
||||
"""key -> getter(rid, params). Built inside a function (not a module-level
|
||||
dict) so, once rebound onto server.py, every entry resolves to the rebound
|
||||
helper copies rather than this module's un-rebound originals."""
|
||||
"""key -> getter(rid, params). Built per call so, once rebound onto server.py, every entry
|
||||
resolves to the rebound helper copies rather than this module's originals."""
|
||||
return {
|
||||
"provider": _cfg_get_provider,
|
||||
"profile": _cfg_get_profile,
|
||||
@@ -332,20 +254,19 @@ def _config_getters() -> dict:
|
||||
"approval_mode": _cfg_get_approval_mode,
|
||||
"approvals.mode": _cfg_get_approval_mode,
|
||||
"details_mode": lambda rid, params: {
|
||||
"value": _display_mode(_load_cfg(), "details_mode", _DETAILS_MODES, "collapsed")
|
||||
},
|
||||
"value": _display_mode(_load_cfg(), "details_mode", _DETAIL_MODES, "collapsed")},
|
||||
"thinking_mode": _cfg_get_thinking_mode,
|
||||
"density": lambda rid, params: {
|
||||
"value": "on" if bool((_load_cfg().get("display") or {}).get("tui_compact", False)) else "off"
|
||||
},
|
||||
"theme": _cfg_get_theme,
|
||||
"statusbar": lambda rid, params: {
|
||||
"value": _coerce_statusbar(_display_cfg().get("tui_statusbar", "top"))
|
||||
},
|
||||
"focus": _cfg_get_focus,
|
||||
"value": _coerce_statusbar(_display_cfg().get("tui_statusbar", "top"))},
|
||||
"focus": lambda rid, params: {
|
||||
"value": "on" if bool(_display_cfg().get("focus_view", False)) else "off",
|
||||
"tool_progress": _load_tool_progress_mode()},
|
||||
"mouse": lambda rid, params: {"value": _display_mouse_tracking(_load_cfg().get("display"))},
|
||||
"mtime": _cfg_get_mtime,
|
||||
}
|
||||
"mtime": _cfg_get_mtime}
|
||||
|
||||
|
||||
@method("config.get")
|
||||
@@ -361,27 +282,19 @@ def _(rid, params: dict) -> dict:
|
||||
return _ok(rid, payload)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# setup readiness
|
||||
# ---------------------------------------------------------------------------
|
||||
# ── setup readiness
|
||||
|
||||
|
||||
def _readiness_profile_scope(params: dict):
|
||||
"""Resolve the optional ``profile`` param of the setup readiness RPCs.
|
||||
|
||||
Returns ``(profile, scope)``: ``scope`` binds that profile's HERMES_HOME and
|
||||
``.env`` secret scope (ContextVars, so concurrent checks stay isolated); the
|
||||
launch profile / no param yields ``("", nullcontext())``. A profile unknown
|
||||
to this host raises ``FileNotFoundError`` — a readiness check must never
|
||||
quietly answer for the launch profile instead.
|
||||
"""
|
||||
"""``(profile, scope)`` for the readiness RPCs' optional ``profile`` param: ``scope`` binds
|
||||
that profile's HERMES_HOME + ``.env`` secret scope (ContextVars, so concurrent checks stay
|
||||
isolated); no param yields ``("", nullcontext())``. An unknown profile raises
|
||||
``FileNotFoundError`` — never quietly answer for the launch profile instead."""
|
||||
import contextlib
|
||||
|
||||
profile = str(params.get("profile") or "").strip() if isinstance(params, dict) else ""
|
||||
if not profile:
|
||||
return "", contextlib.nullcontext()
|
||||
from hermes_cli import profiles as profiles_mod
|
||||
|
||||
if not profiles_mod.profile_exists(profile):
|
||||
raise FileNotFoundError(f"Profile '{profile}' does not exist on this backend.")
|
||||
home = _profile_home(profile)
|
||||
@@ -391,11 +304,8 @@ def _readiness_profile_scope(params: dict):
|
||||
|
||||
|
||||
def _readiness_check(rid, params, probe):
|
||||
"""Shared shell of setup.status / setup.runtime_check.
|
||||
|
||||
``probe(profile)`` runs inside the profile scope and returns the payload;
|
||||
an unknown profile answers ``ok=False`` (never a JSON-RPC error).
|
||||
"""
|
||||
"""Shared shell of setup.status / setup.runtime_check: ``probe(profile)`` runs inside the
|
||||
profile scope; an unknown profile answers ``ok=False`` (never a JSON-RPC error)."""
|
||||
try:
|
||||
profile, scope = _readiness_profile_scope(params)
|
||||
except FileNotFoundError as e:
|
||||
@@ -413,11 +323,7 @@ def _(rid, params: dict) -> dict:
|
||||
|
||||
def probe(profile):
|
||||
configured = bool(_has_any_provider_configured(strict_profile_scope=bool(profile)))
|
||||
payload = {"provider_configured": configured}
|
||||
if profile:
|
||||
payload["profile"] = profile
|
||||
return payload
|
||||
|
||||
return {"provider_configured": configured, **({"profile": profile} if profile else {})}
|
||||
return _readiness_check(rid, params, probe)
|
||||
except Exception as e:
|
||||
return _err(rid, 5016, str(e))
|
||||
@@ -426,69 +332,39 @@ def _(rid, params: dict) -> dict:
|
||||
@method("setup.runtime_check")
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Strict provider check: does the configured/default model resolve to a usable runtime?
|
||||
|
||||
Unlike setup.status (True if ANY provider auth state is discoverable, incl.
|
||||
indirect fallbacks like ``gh auth token``), this runs the same
|
||||
resolve_runtime_provider() the agent uses on session creation and returns
|
||||
ok=False with the auth error when the model cannot actually be served, so
|
||||
UIs can surface onboarding before a doomed prompt. ``profile`` (optional)
|
||||
answers for THAT profile's config.yaml pin and ``.env``; an unknown profile
|
||||
answers ``ok=False`` rather than the launch profile's readiness.
|
||||
"""
|
||||
Unlike setup.status (True if ANY provider auth state is discoverable), this runs the same
|
||||
resolve_runtime_provider() the agent uses on session creation and returns ok=False with the
|
||||
auth error when the model can't be served, so UIs surface onboarding before a doomed prompt.
|
||||
``profile`` answers for THAT profile's pin and ``.env``; unknown -> ``ok=False``."""
|
||||
try:
|
||||
from hermes_cli.runtime_provider import resolve_runtime_provider
|
||||
from hermes_cli.auth import has_usable_secret
|
||||
from hermes_cli.main import _has_any_provider_configured
|
||||
|
||||
requested = str(params.get("provider") or "").strip() or None
|
||||
|
||||
def probe(profile):
|
||||
runtime = resolve_runtime_provider(requested=requested)
|
||||
provider_configured = bool(
|
||||
_has_any_provider_configured(strict_profile_scope=bool(profile))
|
||||
)
|
||||
_has_any_provider_configured(strict_profile_scope=bool(profile)))
|
||||
scoped = {"profile": profile} if profile else {}
|
||||
provider = runtime.get("provider") or "provider"
|
||||
source = str(runtime.get("source") or "")
|
||||
if (
|
||||
not provider_configured
|
||||
and provider == "bedrock"
|
||||
and source in {"iam-role", "aws-sdk-default-chain"}
|
||||
):
|
||||
return {
|
||||
"ok": False,
|
||||
"provider": provider,
|
||||
"model": runtime.get("model"),
|
||||
"source": source,
|
||||
"error": "No Hermes provider is configured.",
|
||||
**scoped,
|
||||
}
|
||||
|
||||
def fail(error, src):
|
||||
return {"ok": False, "provider": provider, "model": runtime.get("model"),
|
||||
"source": src, "error": error, **scoped}
|
||||
if (not provider_configured and provider == "bedrock"
|
||||
and source in {"iam-role", "aws-sdk-default-chain"}):
|
||||
return fail("No Hermes provider is configured.", source)
|
||||
api_key = runtime.get("api_key")
|
||||
api_key_text = "" if callable(api_key) else str(api_key or "").strip()
|
||||
credential_ok = (
|
||||
callable(api_key)
|
||||
or api_key_text in {"aws-sdk", "no-key-required"}
|
||||
or has_usable_secret(api_key_text)
|
||||
or bool(runtime.get("command"))
|
||||
)
|
||||
callable(api_key) or api_key_text in {"aws-sdk", "no-key-required"}
|
||||
or has_usable_secret(api_key_text) or bool(runtime.get("command")))
|
||||
if not credential_ok:
|
||||
return {
|
||||
"ok": False,
|
||||
"provider": provider,
|
||||
"model": runtime.get("model"),
|
||||
"source": runtime.get("source"),
|
||||
"error": f"No usable credentials found for {provider}.",
|
||||
**scoped,
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"provider": runtime.get("provider"),
|
||||
"model": runtime.get("model"),
|
||||
"source": runtime.get("source"),
|
||||
**scoped,
|
||||
}
|
||||
|
||||
return fail(f"No usable credentials found for {provider}.", runtime.get("source"))
|
||||
return {"ok": True, "provider": runtime.get("provider"), "model": runtime.get("model"),
|
||||
"source": runtime.get("source"), **scoped}
|
||||
return _readiness_check(rid, params, probe)
|
||||
except Exception as e:
|
||||
return _ok(rid, {"ok": False, "error": str(e)})
|
||||
@@ -496,74 +372,51 @@ def _(rid, params: dict) -> dict:
|
||||
|
||||
@method("diagnostics.share_nous")
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Upload a redacted debug bundle to Nous-internal diagnostics storage.
|
||||
|
||||
Same collection + force-redaction pipeline as ``hermes debug share --nous``;
|
||||
redaction is NOT client-controllable. Consent lives with the CALLER (the
|
||||
desktop shows the privacy notice + Upload button first). Structured
|
||||
``ok``/``error`` envelope rather than JSON-RPC errors so the client can
|
||||
render upload failures inline.
|
||||
|
||||
Params (optional): ``error_context`` (client text about the failure,
|
||||
redacted, attached as ``error-context.txt``), ``extra_files`` ({label →
|
||||
text} client-side artifacts such as a remote desktop.log; force-redacted,
|
||||
labels sanitized and size-capped), ``log_lines`` (default 200).
|
||||
"""
|
||||
"""Upload a redacted debug bundle to Nous-internal diagnostics storage — same collection +
|
||||
force-redaction pipeline as ``hermes debug share --nous``; redaction is NOT
|
||||
client-controllable and consent lives with the CALLER (privacy notice first). Structured
|
||||
``ok``/``error`` envelope so the client renders upload failures inline. Optional params:
|
||||
``error_context`` (redacted, attached as ``error-context.txt``), ``extra_files`` ({label ->
|
||||
text}, force-redacted, labels sanitized and size-capped), ``log_lines`` (default 200)."""
|
||||
try:
|
||||
from hermes_cli.debug import _redact_log_text, build_nous_bundle, collect_share_bundle
|
||||
from hermes_cli.diagnostics_upload import share_to_nous
|
||||
|
||||
log_lines = params.get("log_lines")
|
||||
if not isinstance(log_lines, int) or not (10 <= log_lines <= 2000):
|
||||
log_lines = 200
|
||||
|
||||
bundle = collect_share_bundle(log_lines=log_lines, redact=True)
|
||||
|
||||
# Client text goes through the SAME upload-safe redactor as backend
|
||||
# logs (force secret redaction + email masking), never the weaker bare
|
||||
# secret pass.
|
||||
# Client text goes through the SAME upload-safe redactor as backend logs (force secret
|
||||
# redaction + email masking), never the weaker bare secret pass.
|
||||
error_context = params.get("error_context")
|
||||
if isinstance(error_context, str) and error_context.strip():
|
||||
bundle["error-context.txt"] = _redact_log_text(error_context.strip()[:8_000])
|
||||
|
||||
# Bounded: at most 4 files, 512KB each, sanitized labels — a
|
||||
# diagnostics channel, not an arbitrary upload surface.
|
||||
# Bounded: at most 4 files, 512KB each, sanitized labels — not an arbitrary upload surface.
|
||||
extra_files = params.get("extra_files")
|
||||
if isinstance(extra_files, dict):
|
||||
for label, text in list(extra_files.items())[:4]:
|
||||
if not isinstance(label, str) or not isinstance(text, str):
|
||||
continue
|
||||
safe_label = "".join(ch for ch in label if ch.isalnum() or ch in "._- ()").strip()[:64]
|
||||
# Collapse dot-runs / leading dots so traversal-shaped labels
|
||||
# can't survive even cosmetically.
|
||||
# Collapse dot-runs / leading dots so traversal-shaped labels can't survive.
|
||||
while ".." in safe_label:
|
||||
safe_label = safe_label.replace("..", ".")
|
||||
safe_label = safe_label.lstrip(".").strip()
|
||||
if not safe_label or not text.strip():
|
||||
continue
|
||||
bundle[f"client/{safe_label}"] = _redact_log_text(text[:524_288])
|
||||
|
||||
res = share_to_nous(build_nous_bundle(bundle, redact=True))
|
||||
view_url = res.get("viewUrl") or res.get("view_url")
|
||||
upload_id = res.get("id")
|
||||
if not view_url and not upload_id:
|
||||
# An upload the user can't reference is useless to support.
|
||||
return _ok(
|
||||
rid, {"ok": False, "error": "upload succeeded but returned no view URL or id"}
|
||||
)
|
||||
return _ok(
|
||||
rid,
|
||||
{
|
||||
"ok": True,
|
||||
"view_url": view_url,
|
||||
"upload_id": upload_id,
|
||||
"expires_at": res.get("expiresAt") or res.get("expires_at"),
|
||||
},
|
||||
)
|
||||
return _ok(rid, {"ok": False,
|
||||
"error": "upload succeeded but returned no view URL or id"})
|
||||
return _ok(rid, {
|
||||
"ok": True, "view_url": view_url, "upload_id": upload_id,
|
||||
"expires_at": res.get("expiresAt") or res.get("expires_at")})
|
||||
except Exception as e:
|
||||
return _ok(rid, {"ok": False, "error": str(e)})
|
||||
|
||||
|
||||
def register(server) -> None:
|
||||
"""Publish helpers + handlers onto ``server``, rebound to its globals."""
|
||||
bind_module(globals(), server, skip=("_",))
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
"""``config.set`` — one JSON-RPC method, dispatched on ``key`` through a table.
|
||||
|
||||
Bodies are rebound onto server.py's globals (method_ctx.bind_module) and reference them bare.
|
||||
Each ``_set_*`` handler takes ``(rid, params, key, value, session)`` and returns the JSON-RPC
|
||||
envelope. Keys match exactly except ``details_mode.<section>`` (prefix) and ``_DISPLAY_TOGGLE_KEYS``.
|
||||
"""``config.set`` — one JSON-RPC method, dispatched on ``key`` through a table. Bodies are
|
||||
rebound onto server.py's globals (method_ctx.bind_module) and reference them bare. Each
|
||||
``_set_*`` takes ``(rid, params, key, value, session)`` and returns the JSON-RPC envelope.
|
||||
Keys match exactly except ``details_mode.<section>`` (prefix) and ``_DISPLAY_TOGGLE_KEYS``.
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -16,18 +15,13 @@ method = _registry.method
|
||||
_profile_scoped = _registry.profile_scoped
|
||||
|
||||
|
||||
# ── shared helpers ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _display_section(cfg: dict) -> dict:
|
||||
display = cfg.get("display")
|
||||
return display if isinstance(display, dict) else {}
|
||||
|
||||
# ── shared helpers
|
||||
|
||||
def _write_display_sections(*, sections=None, drop_sections=(), **display_fields) -> None:
|
||||
"""Persist ``display.<field>`` + ``display.sections`` edits via the raw (uncached) config write-back."""
|
||||
"""Persist ``display.<field>`` + ``display.sections`` edits via the raw (uncached) write-back."""
|
||||
cfg = _load_cfg_raw()
|
||||
display = _display_section(cfg)
|
||||
display = cfg.get("display")
|
||||
display = display if isinstance(display, dict) else {}
|
||||
cur = display.get("sections")
|
||||
cur = cur if isinstance(cur, dict) else {}
|
||||
display.update(display_fields)
|
||||
@@ -52,28 +46,28 @@ def _emit_all_session_info() -> None:
|
||||
|
||||
def _toggle_display_bool(rid, key, value, *, cfg_key, on_words, off_words):
|
||||
"""Shared body of the on/off/toggle display booleans (``density``, ``battery``)."""
|
||||
raw = str(value or "").strip().lower()
|
||||
cur_b = bool(_display_section(_load_cfg()).get(cfg_key, False))
|
||||
raw = _word(value)
|
||||
cur_b = bool(_display_cfg().get(cfg_key, False))
|
||||
if raw in {"", "toggle"}:
|
||||
nv_b = not cur_b
|
||||
elif raw in on_words:
|
||||
nv_b = True
|
||||
elif raw in off_words:
|
||||
nv_b = False
|
||||
elif raw in on_words or raw in off_words:
|
||||
nv_b = raw in on_words
|
||||
else:
|
||||
return _err(rid, 4002, f"unknown {key} value: {value}")
|
||||
_write_config_key(f"display.{cfg_key}", nv_b)
|
||||
return _ok(rid, {"key": key, "value": "on" if nv_b else "off"})
|
||||
|
||||
|
||||
def _word(value) -> str:
|
||||
return str(value or "").strip().lower()
|
||||
|
||||
|
||||
def _cfgset_await_agent(session, rid):
|
||||
"""Wait for an in-progress agent build; the error envelope if it failed, else None."""
|
||||
init_err = _wait_agent(session, rid)
|
||||
if init_err:
|
||||
return init_err
|
||||
if session.get("agent") is None:
|
||||
return _err(rid, 5032, "agent initialization failed")
|
||||
return None
|
||||
return _err(rid, 5032, "agent initialization failed") if session.get("agent") is None else None
|
||||
|
||||
|
||||
def _cfgset_model_ok(rid, key, value, warning, confirm_required, confirm_message, scope, **extra):
|
||||
@@ -81,8 +75,7 @@ def _cfgset_model_ok(rid, key, value, warning, confirm_required, confirm_message
|
||||
"confirm_message": confirm_message, "scope": scope, **extra})
|
||||
|
||||
|
||||
# ── per-key handlers ──────────────────────────────────────────────────
|
||||
|
||||
# ── per-key handlers
|
||||
|
||||
def _set_model(rid, params, key, value, session):
|
||||
"""Live/deferred model switch; see _apply_model_switch and _apply_pending_model_switch."""
|
||||
@@ -92,11 +85,9 @@ def _set_model(rid, params, key, value, session):
|
||||
confirmed = bool(params.get("confirm_expensive_model", False))
|
||||
if session:
|
||||
from hermes_cli.model_switch import parse_model_switch_args
|
||||
|
||||
sid = params.get("session_id", "")
|
||||
# No live swap while a turn streams: agent.switch_model() mutates model/provider/
|
||||
# base_url/client that the worker thread reads every iteration. Stash the pick and
|
||||
# apply it at the NEXT turn start (_apply_pending_model_switch).
|
||||
# No live swap while a turn streams (agent.switch_model() mutates fields the worker
|
||||
# thread reads every iteration): stash the pick for the NEXT turn start.
|
||||
if session.get("running"):
|
||||
parsed = parse_model_switch_args(value)
|
||||
try:
|
||||
@@ -105,12 +96,12 @@ def _set_model(rid, params, key, value, session):
|
||||
pending_model = str(value)
|
||||
pending_provider = (getattr(parsed, "explicit_provider", "") or "").strip()
|
||||
# Selection guards run HERE (the only moment a confirm round-trip is possible);
|
||||
# otherwise an unconfirmed stashed pick is dropped at turn start, never confirmed.
|
||||
# otherwise an unconfirmed stashed pick is dropped at turn start.
|
||||
if not confirmed:
|
||||
pending_warning = _pending_switch_selection_warning(pending_model, pending_provider)
|
||||
if pending_warning is not None:
|
||||
# Nothing stashed; the client re-sends with confirm_expensive_model.
|
||||
# `confirm_message` is canonical, `warning` its legacy alias — identical.
|
||||
# `confirm_message` is canonical, `warning` its legacy alias.
|
||||
return _cfgset_model_ok(
|
||||
rid, key, pending_model, pending_warning, True, pending_warning, "session", deferred=False
|
||||
)
|
||||
@@ -118,10 +109,9 @@ def _set_model(rid, params, key, value, session):
|
||||
"raw": value,
|
||||
"confirm_expensive_model": confirmed,
|
||||
# _session_info reports these while pending so the end-of-turn settle keeps
|
||||
# showing the user's pick instead of the still-live old model.
|
||||
# showing the user's pick, not the still-live old model.
|
||||
"display_model": pending_model,
|
||||
"display_provider": pending_provider,
|
||||
}
|
||||
"display_provider": pending_provider}
|
||||
return _cfgset_model_ok(rid, key, pending_model, "", False, "", "session", deferred=True)
|
||||
parsed_flags = parse_model_switch_args(value)
|
||||
explicit_provider = parsed_flags.explicit_provider
|
||||
@@ -134,12 +124,10 @@ def _set_model(rid, params, key, value, session):
|
||||
return _err(rid, 5032, "agent initialization timed out")
|
||||
failed_agent_init = (
|
||||
failed_agent_init and session.get("agent") is None and session.get("agent_error") is not None
|
||||
and session.get("agent_ready") is failed_ready and failed_ready.is_set()
|
||||
)
|
||||
and session.get("agent_ready") is failed_ready and failed_ready.is_set())
|
||||
if session.get("agent") is None and not explicit_provider.strip() and not failed_agent_init:
|
||||
_start_agent_build(sid, session)
|
||||
init_err = _cfgset_await_agent(session, rid)
|
||||
if init_err:
|
||||
if init_err := _cfgset_await_agent(session, rid):
|
||||
return init_err
|
||||
with _session_profile_runtime_scope(session):
|
||||
result = _apply_model_switch(
|
||||
@@ -147,8 +135,7 @@ def _set_model(rid, params, key, value, session):
|
||||
)
|
||||
if failed_agent_init and not result.get("confirm_required"):
|
||||
_restart_completed_failed_agent_build(sid, session, failed_ready)
|
||||
init_err = _cfgset_await_agent(session, rid)
|
||||
if init_err:
|
||||
if init_err := _cfgset_await_agent(session, rid):
|
||||
return init_err
|
||||
with _session_profile_runtime_scope(session):
|
||||
_persist_live_session_runtime(session)
|
||||
@@ -156,14 +143,17 @@ def _set_model(rid, params, key, value, session):
|
||||
result = _apply_model_switch("", {"agent": None}, value, confirm_expensive_model=confirmed)
|
||||
return _cfgset_model_ok(
|
||||
rid, key, result["value"], result["warning"], result.get("confirm_required", False),
|
||||
result.get("confirm_message", ""), result.get("scope", "session"),
|
||||
)
|
||||
result.get("confirm_message", ""), result.get("scope", "session"))
|
||||
except Exception as e:
|
||||
return _err(rid, 5001, str(e))
|
||||
|
||||
|
||||
_FAST_WORDS = {"fast": "fast", "on": "fast", "normal": "normal", "off": "normal",
|
||||
"auto": "auto", "cold": "cold"}
|
||||
|
||||
|
||||
def _set_fast(rid, params, key, value, session):
|
||||
raw = str(value or "").strip().lower()
|
||||
raw = _word(value)
|
||||
agent = session.get("agent") if session else None
|
||||
if agent is not None:
|
||||
current_tier = getattr(agent, "service_tier", None)
|
||||
@@ -173,24 +163,15 @@ def _set_fast(rid, params, key, value, session):
|
||||
else:
|
||||
current_tier = _load_service_tier()
|
||||
current_fast = current_tier == "priority"
|
||||
|
||||
if raw in {"status"}:
|
||||
if raw == "status":
|
||||
return _ok(rid, {"key": key, "value": {"priority": "fast", None: "normal"}.get(current_tier, current_tier)})
|
||||
if raw in {"", "toggle"}:
|
||||
nv = "normal" if current_fast else "fast"
|
||||
elif raw in {"fast", "on"}:
|
||||
nv = "fast"
|
||||
elif raw in {"normal", "off"}:
|
||||
nv = "normal"
|
||||
elif raw in {"auto", "cold"}:
|
||||
nv = raw
|
||||
else:
|
||||
toggled = ("normal" if current_fast else "fast") if raw in {"", "toggle"} else None
|
||||
nv = _FAST_WORDS.get(raw, toggled)
|
||||
if nv is None:
|
||||
return _err(rid, 4002, f"unknown fast mode: {value}")
|
||||
|
||||
overrides = None
|
||||
if nv == "fast":
|
||||
from hermes_cli.models import resolve_fast_mode_overrides
|
||||
|
||||
if agent is not None:
|
||||
target_model = getattr(agent, "model", None)
|
||||
else:
|
||||
@@ -199,16 +180,14 @@ def _set_fast(rid, params, key, value, session):
|
||||
target_model = (isinstance(session_override, dict) and session_override.get("model")) or _resolve_model()
|
||||
if not target_model:
|
||||
return _err(rid, 4002, "fast mode is not available without a selected model")
|
||||
overrides = resolve_fast_mode_overrides(
|
||||
target_model, provider=getattr(agent, "provider", None), base_url=getattr(agent, "base_url", None)
|
||||
)
|
||||
overrides = resolve_fast_mode_overrides(target_model, provider=getattr(agent, "provider", None),
|
||||
base_url=getattr(agent, "base_url", None))
|
||||
if overrides is None:
|
||||
return _err(rid, 4002, "fast mode is not available for this model")
|
||||
|
||||
if session is not None:
|
||||
# Session-scoped like `reasoning` (global persistence is `--global` / Settings → Model):
|
||||
# writing config.yaml here flipped fast mode for every other session/profile/CLI/gateway.
|
||||
# The create override keeps the choice across lazy builds and rebuilds; "" pins normal.
|
||||
# writing config.yaml here flipped fast mode for every other surface. The create
|
||||
# override keeps the choice across lazy builds and rebuilds; "" pins normal.
|
||||
session["create_service_tier_override"] = {"fast": "priority", "normal": ""}.get(nv, nv)
|
||||
else:
|
||||
_write_config_key("agent.service_tier", nv)
|
||||
@@ -226,7 +205,7 @@ def _set_fast(rid, params, key, value, session):
|
||||
|
||||
|
||||
def _set_busy(rid, params, key, value, session):
|
||||
raw = str(value or "").strip().lower()
|
||||
raw = _word(value)
|
||||
if raw in {"", "status"}:
|
||||
return _ok(rid, {"key": key, "value": _load_busy_input_mode()})
|
||||
if raw not in {"queue", "steer", "interrupt"}:
|
||||
@@ -248,25 +227,22 @@ def _set_verbose(rid, params, key, value, session):
|
||||
_write_config_key("display.tool_progress", nv)
|
||||
if session:
|
||||
session["tool_progress_mode"] = nv
|
||||
agent = session.get("agent")
|
||||
if agent is not None:
|
||||
agent.verbose_logging = nv == "verbose"
|
||||
if session.get("agent") is not None:
|
||||
session["agent"].verbose_logging = nv == "verbose"
|
||||
return _ok(rid, {"key": key, "value": nv})
|
||||
|
||||
|
||||
def _set_focus(rid, params, key, value, session):
|
||||
# Focus view (/focus): display-only reduced output composed with tool_progress — enabling
|
||||
# stashes the configured mode and pins tool_progress "off"; disabling restores the stash.
|
||||
# Focus view (/focus): enabling stashes the configured tool_progress mode and pins it
|
||||
# "off"; disabling restores the stash.
|
||||
from hermes_cli.focus_view import FOCUS_TOOL_PROGRESS_MODE, normalize_tool_progress_mode, resolve_focus_arg
|
||||
|
||||
d_f = _display_section(_load_cfg())
|
||||
d_f = _display_cfg()
|
||||
cur_focus = bool(d_f.get("focus_view", False))
|
||||
action, target = resolve_focus_arg(str(value or ""), cur_focus)
|
||||
if action == "usage":
|
||||
return _err(rid, 4002, f"unknown focus value: {value} (use on|off|status)")
|
||||
if action == "status" or target is None:
|
||||
return _ok(rid, {"key": key, "value": "on" if cur_focus else "off", "tool_progress": _load_tool_progress_mode()})
|
||||
|
||||
if target:
|
||||
saved = (cur_focus and d_f.get("focus_saved_tool_progress")) or _load_tool_progress_mode()
|
||||
_write_config_key("display.focus_saved_tool_progress", normalize_tool_progress_mode(saved))
|
||||
@@ -276,19 +252,17 @@ def _set_focus(rid, params, key, value, session):
|
||||
effective = normalize_tool_progress_mode(d_f.get("focus_saved_tool_progress") or "all")
|
||||
_write_config_key("display.tool_progress", effective)
|
||||
_write_config_key("display.focus_view", bool(target))
|
||||
|
||||
if session:
|
||||
session["focus_view"] = bool(target)
|
||||
session["tool_progress_mode"] = effective
|
||||
agent_f = session.get("agent")
|
||||
if agent_f is not None:
|
||||
if session.get("agent") is not None:
|
||||
with contextlib.suppress(Exception):
|
||||
agent_f.tool_progress_mode = effective
|
||||
session["agent"].tool_progress_mode = effective
|
||||
return _ok(rid, {"key": key, "value": "on" if target else "off", "tool_progress": effective})
|
||||
|
||||
|
||||
def _set_approval_mode(rid, params, key, value, session):
|
||||
raw = str(value or "").strip().lower()
|
||||
raw = _word(value)
|
||||
if raw not in _APPROVAL_MODES:
|
||||
return _err(rid, 4002, f"unknown approval mode: {value}; pick one of manual|smart|off")
|
||||
_write_config_key("approvals.mode", raw)
|
||||
@@ -297,30 +271,24 @@ def _set_approval_mode(rid, params, key, value, session):
|
||||
|
||||
|
||||
def _set_yolo(rid, params, key, value, session):
|
||||
# Approval bypass. scope="session" (default; TUI Shift+Tab) toggles ONLY this session's flag.
|
||||
# scope="global" (Shift+click the zap) flips persistent approvals.mode between "off" (bypass
|
||||
# on) and "manual" (bypass off) for every surface, surviving restarts.
|
||||
scope = str(params.get("scope") or "session").strip().lower()
|
||||
# scope="session" (default; Shift+Tab) toggles ONLY this session's flag. scope="global"
|
||||
# (Shift+click the zap) flips persistent approvals.mode between "off" and "manual".
|
||||
scope = _word(params.get("scope") or "session")
|
||||
try:
|
||||
from tools.approval import disable_session_yolo, enable_session_yolo, is_session_yolo_enabled
|
||||
|
||||
raw = str(value or "").strip().lower()
|
||||
raw = _word(value)
|
||||
|
||||
def _resolve_toggle(current: bool) -> bool:
|
||||
return _BOOL_WORDS.get(raw, not current)
|
||||
|
||||
if scope == "global":
|
||||
from tools.approval import _normalize_approval_mode
|
||||
|
||||
cfg = _load_cfg()
|
||||
appr = cfg.get("approvals") if isinstance(cfg, dict) else None
|
||||
appr = _load_cfg().get("approvals")
|
||||
appr = appr if isinstance(appr, dict) else {}
|
||||
enable = _resolve_toggle(_normalize_approval_mode(appr.get("mode", "manual")) == "off")
|
||||
# Binary affordance: no restore of a prior "smart"/custom mode (those live in config.yaml).
|
||||
_write_config_key("approvals.mode", "off" if enable else "manual")
|
||||
_emit_all_session_info() # reflect the flip in every live indicator
|
||||
return _ok(rid, {"key": key, "value": "1" if enable else "0", "scope": "global"})
|
||||
|
||||
if session:
|
||||
skey = session["session_key"]
|
||||
enable = _resolve_toggle(is_session_yolo_enabled(skey))
|
||||
@@ -338,29 +306,25 @@ def _set_yolo(rid, params, key, value, session):
|
||||
|
||||
|
||||
# /reasoning display words: (accepted inputs, reported value, display field, sections.thinking,
|
||||
# session show_reasoning or None). full/clamp mirror the CLI's reasoning_full toggle; the TUI
|
||||
# renders thinking as an expand/collapse section and display.reasoning_full is persisted too.
|
||||
# session show_reasoning or None). full/clamp mirror the CLI's reasoning_full toggle.
|
||||
_REASONING_DISPLAY_WORDS = (
|
||||
({"show", "on"}, "show", {"show_reasoning": True}, "expanded", True),
|
||||
({"hide", "off"}, "hide", {"show_reasoning": False}, "hidden", False),
|
||||
({"full", "all"}, "full", {"reasoning_full": True}, "expanded", None),
|
||||
({"clamp", "collapse", "short"}, "clamp", {"reasoning_full": False}, "collapsed", None),
|
||||
)
|
||||
({"clamp", "collapse", "short"}, "clamp", {"reasoning_full": False}, "collapsed", None))
|
||||
|
||||
|
||||
def _set_reasoning(rid, params, key, value, session):
|
||||
try:
|
||||
from hermes_constants import parse_reasoning_effort
|
||||
|
||||
arg = str(value or "").strip().lower()
|
||||
scope = str(params.get("scope") or "").strip().lower()
|
||||
arg = _word(value)
|
||||
scope = _word(params.get("scope"))
|
||||
for words, reported, fields, thinking, show in _REASONING_DISPLAY_WORDS:
|
||||
if arg in words:
|
||||
_write_display_sections(sections={"thinking": thinking}, **fields)
|
||||
if show is not None and session:
|
||||
session["show_reasoning"] = show
|
||||
return _ok(rid, {"key": key, "value": reported})
|
||||
|
||||
parsed = parse_reasoning_effort(arg)
|
||||
if parsed is None:
|
||||
return _err(rid, 4002, f"unknown reasoning value: {value}")
|
||||
@@ -369,8 +333,8 @@ def _set_reasoning(rid, params, key, value, session):
|
||||
if session is not None:
|
||||
session.pop("create_reasoning_override", None)
|
||||
else:
|
||||
# Session-scoped like the messaging gateway's `/reasoning <level>`; otherwise every
|
||||
# desktop model-menu pick rewrote the global default.
|
||||
# Session-scoped like the gateway's `/reasoning <level>`; otherwise every desktop
|
||||
# model-menu pick rewrote the global default.
|
||||
session["create_reasoning_override"] = parsed
|
||||
if session and session.get("agent") is not None:
|
||||
session["agent"].reasoning_config = parsed
|
||||
@@ -382,7 +346,7 @@ def _set_reasoning(rid, params, key, value, session):
|
||||
|
||||
|
||||
def _set_details_mode(rid, params, key, value, session):
|
||||
nv = str(value or "").strip().lower()
|
||||
nv = _word(value)
|
||||
if nv not in _DETAIL_MODES:
|
||||
return _err(rid, 4002, f"unknown details_mode: {value}")
|
||||
_write_display_sections(sections={section: nv for section in _DETAIL_SECTION_NAMES}, details_mode=nv)
|
||||
@@ -390,12 +354,12 @@ def _set_details_mode(rid, params, key, value, session):
|
||||
|
||||
|
||||
def _set_details_section(rid, params, key, value, session):
|
||||
# `details_mode.<section>` -> `display.sections.<section>`. Empty value clears the explicit
|
||||
# override so the frontend applies built-in section defaults before the global details_mode.
|
||||
# `details_mode.<section>` -> `display.sections.<section>`; empty clears the override so the
|
||||
# frontend applies built-in section defaults before the global details_mode.
|
||||
section = key.split(".", 1)[1]
|
||||
if section not in _DETAIL_SECTION_NAMES:
|
||||
return _err(rid, 4002, f"unknown section: {section}")
|
||||
nv = str(value or "").strip().lower()
|
||||
nv = _word(value)
|
||||
if not nv:
|
||||
_write_display_sections(drop_sections=(section,))
|
||||
elif nv not in _DETAIL_MODES:
|
||||
@@ -406,7 +370,7 @@ def _set_details_section(rid, params, key, value, session):
|
||||
|
||||
|
||||
def _set_thinking_mode(rid, params, key, value, session):
|
||||
nv = str(value or "").strip().lower()
|
||||
nv = _word(value)
|
||||
if nv not in {"collapsed", "truncated", "full"}:
|
||||
return _err(rid, 4002, f"unknown thinking_mode: {value}")
|
||||
_write_config_key("display.thinking_mode", nv)
|
||||
@@ -427,7 +391,7 @@ def _set_battery(rid, params, key, value, session):
|
||||
|
||||
def _set_theme(rid, params, key, value, session):
|
||||
# 'light'/'dark' pin beats background auto-detection (xterm.js hosts misreport OSC 11).
|
||||
raw = str(value or "").strip().lower()
|
||||
raw = _word(value)
|
||||
if raw not in {"auto", "light", "dark"}:
|
||||
return _err(rid, 4002, f"unknown theme value: {value} (use auto|light|dark)")
|
||||
_write_config_key("display.tui_theme", raw)
|
||||
@@ -435,14 +399,12 @@ def _set_theme(rid, params, key, value, session):
|
||||
|
||||
|
||||
def _set_statusbar(rid, params, key, value, session):
|
||||
raw = str(value or "").strip().lower()
|
||||
current = _coerce_statusbar(_display_section(_load_cfg()).get("tui_statusbar", "top"))
|
||||
raw = _word(value)
|
||||
current = _coerce_statusbar(_display_cfg().get("tui_statusbar", "top"))
|
||||
if raw in {"", "toggle"}:
|
||||
nv = "top" if current == "off" else "off"
|
||||
elif raw == "on":
|
||||
nv = "top"
|
||||
elif raw in _STATUSBAR_MODES:
|
||||
nv = raw
|
||||
elif raw == "on" or raw in _STATUSBAR_MODES:
|
||||
nv = "top" if raw == "on" else raw
|
||||
else:
|
||||
return _err(rid, 4002, f"unknown statusbar value: {value}")
|
||||
_write_config_key("display.tui_statusbar", nv)
|
||||
@@ -450,10 +412,10 @@ def _set_statusbar(rid, params, key, value, session):
|
||||
|
||||
|
||||
def _set_mouse(rid, params, key, value, session):
|
||||
# Explicit None check (not `value or ""`) so falsy non-string inputs (0, False from
|
||||
# programmatic callers) reach the alias map as themselves (-> 'off') instead of toggling.
|
||||
# Explicit None check so falsy non-string inputs (0, False) reach the alias map as
|
||||
# themselves (-> 'off') instead of toggling.
|
||||
raw = ("" if value is None else str(value)).strip().lower()
|
||||
current = _display_mouse_tracking(_display_section(_load_cfg()))
|
||||
current = _display_mouse_tracking(_display_cfg())
|
||||
if raw in {"", "toggle"}:
|
||||
nv = "all" if current == "off" else "off"
|
||||
elif raw in _MOUSE_TRACKING_ALIASES:
|
||||
@@ -498,10 +460,9 @@ def _set_prompt_like(rid, params, key, value, session):
|
||||
_save_cfg(cfg)
|
||||
elif key == "personality":
|
||||
pname, new_prompt = _validate_personality(str(value or ""), cfg)
|
||||
# Personality text is an in-session overlay; persistence goes through
|
||||
# hermes_cli.personality (single owner), never the user-owned global system prompt.
|
||||
# Personality persists through hermes_cli.personality (single owner), never the
|
||||
# user-owned global system prompt.
|
||||
from hermes_cli.personality import persist_personality
|
||||
|
||||
persist_personality(pname)
|
||||
resp["value"] = str(value or "none")
|
||||
history_reset, info = _apply_personality_to_session(params.get("session_id", ""), session, new_prompt, pname)
|
||||
@@ -511,8 +472,8 @@ def _set_prompt_like(rid, params, key, value, session):
|
||||
else:
|
||||
_write_config_key(f"display.{key}", value)
|
||||
if key == "skin":
|
||||
# Every connected surface repaints; then sync the watcher baseline so the poll
|
||||
# loop doesn't re-broadcast the skin this RPC just applied.
|
||||
# Every surface repaints; sync the watcher baseline so the poll loop doesn't
|
||||
# re-broadcast the skin this RPC just applied.
|
||||
_broadcast_global_event("skin.changed", resolve_skin())
|
||||
_note_skin_broadcast()
|
||||
return _ok(rid, resp)
|
||||
@@ -528,7 +489,7 @@ def _set_display_toggle(rid, params, key, value, session):
|
||||
return _ok(rid, {"key": key, "value": on})
|
||||
|
||||
|
||||
# ── dispatch ──────────────────────────────────────────────────────────
|
||||
# ── dispatch
|
||||
|
||||
_CONFIG_SETTERS = {
|
||||
"model": _set_model, "fast": _set_fast, "busy": _set_busy, "verbose": _set_verbose, "focus": _set_focus,
|
||||
@@ -537,19 +498,7 @@ _CONFIG_SETTERS = {
|
||||
"density": _set_density, "battery": _set_battery, "theme": _set_theme, "statusbar": _set_statusbar,
|
||||
"mouse": _set_mouse, "indicator": _set_indicator,
|
||||
"cwd": _set_cwd, "terminal.cwd": _set_cwd, "workdir": _set_cwd,
|
||||
"prompt": _set_prompt_like, "personality": _set_prompt_like, "skin": _set_prompt_like,
|
||||
}
|
||||
|
||||
|
||||
def _config_setter(key: str):
|
||||
handler = _CONFIG_SETTERS.get(key)
|
||||
if handler is not None:
|
||||
return handler
|
||||
if key.startswith("details_mode."):
|
||||
return _set_details_section
|
||||
if key in _DISPLAY_TOGGLE_KEYS:
|
||||
return _set_display_toggle
|
||||
return None
|
||||
"prompt": _set_prompt_like, "personality": _set_prompt_like, "skin": _set_prompt_like}
|
||||
|
||||
|
||||
@method("config.set")
|
||||
@@ -557,12 +506,15 @@ def _config_setter(key: str):
|
||||
def _(rid, params: dict) -> dict:
|
||||
key, value = params.get("key", ""), params.get("value", "")
|
||||
session = _sessions.get(params.get("session_id", ""))
|
||||
handler = _config_setter(key)
|
||||
handler = _CONFIG_SETTERS.get(key)
|
||||
if handler is None and key.startswith("details_mode."):
|
||||
handler = _set_details_section
|
||||
elif handler is None and key in _DISPLAY_TOGGLE_KEYS:
|
||||
handler = _set_display_toggle
|
||||
if handler is None:
|
||||
return _err(rid, 4002, f"unknown config key: {key}")
|
||||
return handler(rid, params, key, value, session)
|
||||
|
||||
|
||||
def register(server) -> None:
|
||||
"""Publish helpers + the config.set handler onto ``server``, rebound to its globals."""
|
||||
bind_module(globals(), server, skip=("_",))
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
"""Image-generation JSON-RPC handler (ws twin of the image_generate tool), so UI
|
||||
surfaces (avatar pickers, artifact panes) can generate directly. The result is
|
||||
returned as a data URL: a remote desktop can't read a gateway file path and hosted
|
||||
URLs are often CORS-opaque to a renderer canvas.
|
||||
"""Image-generation JSON-RPC handler (ws twin of the image_generate tool) for UI surfaces
|
||||
(avatar pickers, artifact panes). The result is a data URL: a remote desktop can't read a
|
||||
gateway file path and hosted URLs are often CORS-opaque to a renderer canvas.
|
||||
|
||||
Bodies are rebound onto server.py's globals at install time (see
|
||||
method_ctx.bind_module), so they reference server.py globals bare.
|
||||
Bodies are rebound onto server.py's globals (method_ctx.bind_module) and reference them bare.
|
||||
"""
|
||||
|
||||
from .method_ctx import HandlerRegistry, bind_module
|
||||
@@ -16,7 +14,6 @@ method = _registry.method
|
||||
def _image_gen_available() -> bool:
|
||||
try:
|
||||
from tools.image_generation_tool import check_image_generation_requirements
|
||||
|
||||
return bool(check_image_generation_requirements())
|
||||
except Exception:
|
||||
return False
|
||||
@@ -27,11 +24,9 @@ def _image_to_data_url(ref: str, cap: int):
|
||||
import base64
|
||||
import mimetypes
|
||||
import os
|
||||
|
||||
try:
|
||||
if ref.startswith(("http://", "https://")):
|
||||
import urllib.request
|
||||
|
||||
req = urllib.request.Request(ref, headers={"User-Agent": "hermes-agent"})
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
if resp.length is not None and resp.length > cap:
|
||||
@@ -66,46 +61,28 @@ def _(rid, params: dict) -> dict:
|
||||
if is_truthy_value(params.get("probe", False)):
|
||||
return _ok(rid, {"available": available})
|
||||
if not available:
|
||||
return _ok(
|
||||
rid,
|
||||
{
|
||||
"available": False,
|
||||
"success": False,
|
||||
"error": "No image generation backend configured (run `hermes tools` to enable one).",
|
||||
},
|
||||
)
|
||||
|
||||
return _ok(rid, {
|
||||
"available": False, "success": False,
|
||||
"error": "No image generation backend configured (run `hermes tools` to enable one).",
|
||||
})
|
||||
prompt = str(params.get("prompt") or "").strip()
|
||||
if not prompt:
|
||||
return _err(rid, 4071, "prompt required")
|
||||
|
||||
aspect = str(params.get("aspect_ratio") or "square").strip().lower()
|
||||
try:
|
||||
cap = min(int(params.get("max_bytes", 8_000_000) or 8_000_000), 16_000_000)
|
||||
except (TypeError, ValueError):
|
||||
cap = 8_000_000
|
||||
|
||||
try:
|
||||
from tools.image_generation_tool import _handle_image_generate
|
||||
|
||||
# Full provider dispatcher — same path as the model tool (source-image
|
||||
# confinement, plugin providers, managed routing, FAL fallback); calling
|
||||
# the FAL leaf directly bypassed configured providers.
|
||||
raw = _handle_image_generate({"prompt": prompt, "aspect_ratio": aspect})
|
||||
result = json.loads(raw)
|
||||
# Full provider dispatcher — same path as the model tool (source-image confinement,
|
||||
# plugin providers, managed routing, FAL fallback); the FAL leaf bypassed providers.
|
||||
result = json.loads(_handle_image_generate({"prompt": prompt, "aspect_ratio": aspect}))
|
||||
except Exception as e:
|
||||
return _err(rid, 5071, str(e))
|
||||
|
||||
if not result.get("success"):
|
||||
return _ok(
|
||||
rid,
|
||||
{
|
||||
"available": True,
|
||||
"success": False,
|
||||
"error": str(result.get("error") or "generation failed"),
|
||||
},
|
||||
)
|
||||
|
||||
return _ok(rid, {"available": True, "success": False,
|
||||
"error": str(result.get("error") or "generation failed")})
|
||||
image_ref = str(result.get("image") or "")
|
||||
payload = {"available": True, "success": True, "image": image_ref}
|
||||
data_url = _image_to_data_url(image_ref, cap) if image_ref else None
|
||||
@@ -115,5 +92,4 @@ def _(rid, params: dict) -> dict:
|
||||
|
||||
|
||||
def register(server) -> None:
|
||||
"""Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
|
||||
bind_module(globals(), server, skip=("_",))
|
||||
|
||||
+82
-140
@@ -1,9 +1,8 @@
|
||||
"""Profile JSON-RPC handlers — the ws twin of the dashboard's /api/profiles (desktop plugins
|
||||
only have the ws door), on the same `hermes_cli.profiles` primitives.
|
||||
|
||||
Bodies are rebound onto server.py's globals (method_ctx.bind_module) and use them bare
|
||||
(`_ok`, `_err`, `os`, `json`, `Path`, `is_truthy_value`, `get_hermes_home`, ...); module-level
|
||||
names are published onto server.py, so they must not collide with its globals.
|
||||
Bodies are rebound onto server.py's globals (method_ctx.bind_module) and use them bare;
|
||||
module-level names are published onto server.py, so they must not collide with its globals.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
@@ -31,8 +30,8 @@ def _profile_handler(name: str, code: int):
|
||||
|
||||
|
||||
def _lazy(module, name):
|
||||
"""Late-bound attribute lookup (heavy / cyclic modules). ``__import__`` builtin on purpose:
|
||||
rebound bodies see only server.py globals, not this module's imports."""
|
||||
"""Late-bound attribute lookup; ``__import__`` builtin on purpose (rebound bodies see only
|
||||
server.py globals, not this module's imports)."""
|
||||
return getattr(__import__(module, fromlist=[name]), name)
|
||||
|
||||
|
||||
@@ -58,10 +57,6 @@ def _best_effort(fn) -> bool:
|
||||
return _try(lambda: (fn(), True)[1], False)
|
||||
|
||||
|
||||
def _read_text_if_file(path) -> str:
|
||||
return _try(lambda: path.read_text(encoding="utf-8", errors="replace") if path.is_file() else "", "")
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _hermes_home_scope(path):
|
||||
"""Scope config/auth resolution to ``path`` for the block."""
|
||||
@@ -98,9 +93,8 @@ def _clean_revisions(raw: dict) -> dict:
|
||||
|
||||
|
||||
def _latest_message_preview(db, session_id):
|
||||
"""≤80-char excerpt of the NEWEST active user/assistant message, or "" (roster semantics:
|
||||
latest exchange, not the first-message preview). Same query shape as
|
||||
``SessionDB.latest_message_row_id`` — keep them in step."""
|
||||
"""≤80-char excerpt of the NEWEST active user/assistant message, or "" (roster semantics).
|
||||
Same query shape as ``SessionDB.latest_message_row_id`` — keep them in step."""
|
||||
try:
|
||||
with db._lock:
|
||||
row = db._conn.execute(
|
||||
@@ -108,8 +102,7 @@ def _latest_message_preview(db, session_id):
|
||||
" WHERE session_id = ? AND role IN ('user', 'assistant')"
|
||||
" AND active = 1 AND content IS NOT NULL AND TRIM(content) != ''"
|
||||
" ORDER BY id DESC LIMIT 1",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
(session_id,)).fetchone()
|
||||
except Exception:
|
||||
return ""
|
||||
if not row:
|
||||
@@ -119,8 +112,8 @@ def _latest_message_preview(db, session_id):
|
||||
|
||||
|
||||
def _open_profile_session_db_readonly(profile_path):
|
||||
"""Read-only attach for roster previews, or None. A writable ``SessionDB()`` waits up to
|
||||
20s for the write lock + runs DDL; the 5s roster poll stalled past the desktop timeout."""
|
||||
"""Read-only attach for roster previews, or None (a writable ``SessionDB()`` waits up to 20s
|
||||
for the write lock + runs DDL and stalled the 5s roster poll)."""
|
||||
db_path = Path(profile_path) / "state.db"
|
||||
if not _try(db_path.exists, False):
|
||||
return None
|
||||
@@ -128,8 +121,8 @@ def _open_profile_session_db_readonly(profile_path):
|
||||
|
||||
|
||||
def _resurrect_recoverable_canonical(db, profile_path, session_id):
|
||||
"""Un-archive an accidentally archived canonical row, or False. Recoverability is judged on
|
||||
the read-only handle; the write uses a short-lived writable handle."""
|
||||
"""Un-archive an accidentally archived canonical row (judged read-only, written via a
|
||||
short-lived writable handle), or False."""
|
||||
try:
|
||||
row = db.get_session(session_id)
|
||||
if not row or not row.get("archived"):
|
||||
@@ -149,10 +142,9 @@ def _resurrect_recoverable_canonical(db, profile_path, session_id):
|
||||
|
||||
|
||||
def _canonical_session_row(db, profile_path):
|
||||
"""Summary of the profile's canonical "Bot Chat" row, or None. Identity is the NAME, so
|
||||
preview and click target agree without a client pointer. Hidden rows resolve; lineages
|
||||
via ``get_compression_tip`` (NOT the resume walker's unmarked-child fallback); worker
|
||||
sources count as absent. ``id`` is the registry row, ``resolved_id`` the live tip."""
|
||||
"""Summary of the profile's canonical "Bot Chat" row (identity is the NAME), or None.
|
||||
Lineages via ``get_compression_tip`` (NOT the resume walker's unmarked-child fallback);
|
||||
worker sources count as absent. ``id`` is the registry row, ``resolved_id`` the live tip."""
|
||||
if db is None:
|
||||
return None
|
||||
try:
|
||||
@@ -169,15 +161,11 @@ def _canonical_session_row(db, profile_path):
|
||||
tip_row = db.get_session(tip) or row
|
||||
started = row.get("started_at") or 0
|
||||
return {
|
||||
"id": session_id,
|
||||
"resolved_id": tip,
|
||||
"root_title": row.get("title") or "",
|
||||
"title": tip_row.get("title") or "",
|
||||
"preview": _latest_message_preview(db, tip),
|
||||
"id": session_id, "resolved_id": tip, "root_title": row.get("title") or "",
|
||||
"title": tip_row.get("title") or "", "preview": _latest_message_preview(db, tip),
|
||||
"started_at": tip_row.get("started_at") or started,
|
||||
"last_active": tip_row.get("last_activity_at") or tip_row.get("started_at") or started,
|
||||
"message_count": tip_row.get("message_count") or 0,
|
||||
}
|
||||
"message_count": tip_row.get("message_count") or 0}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@@ -199,16 +187,12 @@ def _latest_profile_session_rows(db):
|
||||
continue
|
||||
if human is not None:
|
||||
continue
|
||||
human = {
|
||||
"id": s["id"],
|
||||
"title": title,
|
||||
"preview": s.get("preview") or "",
|
||||
"started_at": s.get("started_at") or 0,
|
||||
"last_active": last_active,
|
||||
"message_count": s.get("message_count") or 0,
|
||||
}
|
||||
# Rosters want "where the conversation IS": prefer the newest text.
|
||||
human["preview"] = _latest_message_preview(db, s["id"]) or human["preview"]
|
||||
human = {
|
||||
"id": s["id"], "title": title,
|
||||
"preview": _latest_message_preview(db, s["id"]) or s.get("preview") or "",
|
||||
"started_at": s.get("started_at") or 0, "last_active": last_active,
|
||||
"message_count": s.get("message_count") or 0}
|
||||
if worker is not None:
|
||||
break
|
||||
return human, worker
|
||||
@@ -230,11 +214,8 @@ def _profile_session_fields(row, profile_path):
|
||||
|
||||
def _profile_ui_meta_fields(row: dict, profile_dir) -> None:
|
||||
"""Attach ``ui_meta`` / ``ui_meta_revisions`` / ``has_avatar`` from profile.yaml + assets.
|
||||
|
||||
Client-agnostic UI metadata lives in profile.yaml so every client paints the
|
||||
same roster. ``ui_meta_revisions`` is always present: it feature-detects
|
||||
gateway-owned CAS even for a brand-new profile.
|
||||
"""
|
||||
``ui_meta_revisions`` is always present: it feature-detects gateway-owned CAS even for a
|
||||
brand-new profile."""
|
||||
row["ui_meta_revisions"] = {}
|
||||
raw_meta = _try(lambda: _read_profile_yaml(profile_dir), {})
|
||||
ui_meta = raw_meta.get("ui_meta")
|
||||
@@ -249,25 +230,17 @@ def _profile_ui_meta_fields(row: dict, profile_dir) -> None:
|
||||
|
||||
@_profile_handler("profiles.list", 5061)
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""List Hermes profiles (name, path, model, description, skill count).
|
||||
|
||||
``include_sessions`` (default true) adds ``last_session`` / ``worker_session``
|
||||
/ ``canonical_session`` so a roster paints per-agent previews without N calls.
|
||||
"""
|
||||
"""List Hermes profiles. ``include_sessions`` (default true) adds ``last_session`` /
|
||||
``worker_session`` / ``canonical_session`` so a roster paints previews without N calls."""
|
||||
from hermes_cli.profiles import list_profiles
|
||||
include_sessions = is_truthy_value(params.get("include_sessions", True))
|
||||
out = []
|
||||
for p in list_profiles():
|
||||
row = {
|
||||
"name": p.name,
|
||||
"path": str(p.path),
|
||||
"is_default": bool(p.is_default),
|
||||
"model": p.model,
|
||||
"provider": p.provider,
|
||||
"description": getattr(p, "description", "") or "",
|
||||
"display_name": getattr(p, "display_name", "") or "",
|
||||
"skill_count": getattr(p, "skill_count", 0) or 0,
|
||||
}
|
||||
"name": p.name, "path": str(p.path), "is_default": bool(p.is_default),
|
||||
"model": p.model, "provider": p.provider,
|
||||
"description": p.description or "", "display_name": p.display_name or "",
|
||||
"skill_count": p.skill_count or 0}
|
||||
if include_sessions:
|
||||
_profile_session_fields(row, p.path)
|
||||
_profile_ui_meta_fields(row, Path(str(p.path)))
|
||||
@@ -280,32 +253,33 @@ def _(rid, params: dict) -> dict:
|
||||
def _has_real_env_content(env_path) -> bool:
|
||||
"""True when .env has any non-comment, non-blank line."""
|
||||
lines = env_path.read_text(encoding="utf-8", errors="replace").splitlines()
|
||||
return any(s and not s.startswith("#") for s in (line.strip() for line in lines))
|
||||
return any(s and not s.startswith("#") for s in map(str.strip, lines))
|
||||
|
||||
|
||||
def _copy_secret_file(src, dst) -> None:
|
||||
def _copy_secret_file(src, dst, wanted: bool) -> bool:
|
||||
"""Copy ``src`` -> ``dst`` (0600) when ``src`` exists and ``wanted``; True if copied."""
|
||||
if not (src.is_file() and wanted):
|
||||
return False
|
||||
import shutil
|
||||
shutil.copy2(src, dst)
|
||||
with contextlib.suppress(OSError):
|
||||
os.chmod(str(dst), 0o600)
|
||||
return True
|
||||
|
||||
|
||||
def _mirror_env(path, launch_home) -> bool:
|
||||
"""Copy the launch .env only over the seeded comment-only stub (never a clone's secrets)."""
|
||||
src, dst = launch_home / ".env", path / ".env"
|
||||
if not (src.is_file() and _has_real_env_content(src) and not _try(lambda: _has_real_env_content(dst), False)):
|
||||
return False
|
||||
_copy_secret_file(src, dst)
|
||||
return True
|
||||
return _copy_secret_file(
|
||||
src, dst, _has_real_env_content(src) and not _try(lambda: _has_real_env_content(dst), False))
|
||||
|
||||
|
||||
def _mirror_auth(path, launch_home) -> bool:
|
||||
"""Copy the launch auth.json when absent (skipped under ``share_auth``: a copy forks token
|
||||
state and the first refresh in either store strands the other)."""
|
||||
src, dst = launch_home / "auth.json", path / "auth.json"
|
||||
if not (src.is_file() and not dst.exists()):
|
||||
if not _copy_secret_file(src, dst, not dst.exists()):
|
||||
return False
|
||||
_copy_secret_file(src, dst)
|
||||
# Drop single-use OAuth grants (first refresh strands every sibling); they read from
|
||||
# the root grant via the pool fallback. API keys stay.
|
||||
_best_effort(lambda: _lazy("hermes_cli.auth", "strip_cloned_single_use_oauth_grants")(path))
|
||||
@@ -322,8 +296,7 @@ def _mirror_voice_sections(path) -> bool:
|
||||
if not sections:
|
||||
return False
|
||||
with _hermes_home_scope(path):
|
||||
# RAW file: load_config() merges DEFAULT_CONFIG (every section looks present
|
||||
# and save_config would persist the whole default tree).
|
||||
# RAW file: load_config() merges DEFAULT_CONFIG (every section would look present).
|
||||
dst_cfg = read_user_config_raw() or {}
|
||||
missing = {k: v for k, v in sections.items() if k not in dst_cfg}
|
||||
if missing:
|
||||
@@ -352,10 +325,8 @@ def _inherit_launch_model(path) -> bool:
|
||||
|
||||
def _mirror_launch_credentials(path, params: dict) -> dict:
|
||||
"""Copy launch .env / auth.json / voice sections into a new profile (best-effort per item).
|
||||
|
||||
``share_auth`` reports ``auth: "shared"`` and skips the auth copy; ``mirror_credentials``
|
||||
false skips everything. ``model_inherited`` is filled in by the caller.
|
||||
"""
|
||||
false skips everything. ``model_inherited`` is filled in by the caller."""
|
||||
mirrored = {"env": False, "auth": False, "model_inherited": False, "voice": False}
|
||||
share_auth = is_truthy_value(params.get("share_auth", False))
|
||||
if share_auth:
|
||||
@@ -372,13 +343,11 @@ def _mirror_launch_credentials(path, params: dict) -> dict:
|
||||
|
||||
@method("profiles.create")
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Create a profile (ws twin of POST /api/profiles).
|
||||
|
||||
Params: ``name``, ``description``, ``clone_from`` (omitted = fresh + bundled skills),
|
||||
``clone_all``, ``no_skills``, ``soul``, ``model`` + ``provider``, ``share_auth``,
|
||||
``mirror_credentials`` (default true). Mirroring exists because ``create_profile()``
|
||||
seeds a comment-only .env and no auth.json — a headless profile had NO provider.
|
||||
"""
|
||||
"""Create a profile (ws twin of POST /api/profiles). Params: ``name``, ``description``,
|
||||
``clone_from`` (omitted = fresh + bundled skills), ``clone_all``, ``no_skills``, ``soul``,
|
||||
``model`` + ``provider``, ``share_auth``, ``mirror_credentials`` (default true — a
|
||||
``create_profile()`` seeds a comment-only .env and no auth.json, so a headless profile had
|
||||
NO provider)."""
|
||||
name = str(params.get("name") or "").strip()
|
||||
if not name:
|
||||
return _err(rid, 4061, "name required")
|
||||
@@ -390,13 +359,11 @@ def _(rid, params: dict) -> dict:
|
||||
name=name, clone_from=clone_from, clone_all=clone_all,
|
||||
clone_config=bool(clone_from) and not clone_all,
|
||||
no_skills=is_truthy_value(params.get("no_skills", False)),
|
||||
description=str(params.get("description") or "").strip() or None,
|
||||
)
|
||||
description=str(params.get("description") or "").strip() or None)
|
||||
except (ValueError, FileExistsError, FileNotFoundError) as e:
|
||||
return _err(rid, 4062, str(e))
|
||||
except Exception as e:
|
||||
return _err(rid, 5062, str(e))
|
||||
|
||||
# CLI/REST create flow: bundled skills for fresh profiles, then the alias wrapper.
|
||||
if not clone_from:
|
||||
_best_effort(lambda: profiles_mod.seed_profile_skills(path, quiet=True))
|
||||
@@ -413,16 +380,15 @@ def _(rid, params: dict) -> dict:
|
||||
model_set = _best_effort(lambda: _pin_profile_model(path, provider, model))
|
||||
elif is_truthy_value(params.get("mirror_credentials", True)):
|
||||
mirrored["model_inherited"] = _try(lambda: _inherit_launch_model(path), False)
|
||||
return _ok(
|
||||
rid,
|
||||
{"ok": True, "name": name, "path": str(path), "soul_written": soul_written, "model_set": model_set, "mirrored": mirrored},
|
||||
)
|
||||
return _ok(rid, {"ok": True, "name": name, "path": str(path), "soul_written": soul_written,
|
||||
"model_set": model_set, "mirrored": mirrored})
|
||||
|
||||
|
||||
def _describe_toolsets(cfg):
|
||||
"""``(toolsets, pinned_set)`` as the `hermes tools` checklist presents them (the raw registry
|
||||
leaks platform composites and reports everything "enabled" without a pin)."""
|
||||
from hermes_cli.tools_config import _get_effective_configurable_toolsets, _get_platform_tools, _toolset_allowed_for_platform
|
||||
from hermes_cli.tools_config import (
|
||||
_get_effective_configurable_toolsets, _get_platform_tools, _toolset_allowed_for_platform)
|
||||
from toolsets import resolve_toolset
|
||||
pinned = (cfg.get("tools") if isinstance(cfg.get("tools"), dict) else {}).get("enabled_toolsets")
|
||||
pinned_set = _clean_names(pinned) if isinstance(pinned, list) else None
|
||||
@@ -437,9 +403,8 @@ def _describe_toolsets(cfg):
|
||||
if (ts_name in default_off or ts_name == "yuanbao") and not enabled:
|
||||
continue
|
||||
tool_count = _try(lambda: len(set(resolve_toolset(ts_name))), 0)
|
||||
toolsets_out.append(
|
||||
{"name": ts_name, "label": ts_label, "description": ts_desc or "", "tool_count": tool_count, "enabled": enabled}
|
||||
)
|
||||
toolsets_out.append({"name": ts_name, "label": ts_label, "description": ts_desc or "",
|
||||
"tool_count": tool_count, "enabled": enabled})
|
||||
return toolsets_out, pinned_set
|
||||
|
||||
|
||||
@@ -448,25 +413,17 @@ def _describe_mcp_servers(cfg):
|
||||
mcp_cfg = cfg.get("mcp_servers")
|
||||
if not isinstance(mcp_cfg, dict):
|
||||
return []
|
||||
return _try(
|
||||
lambda: [
|
||||
{
|
||||
"name": str(srv_name),
|
||||
"enabled": not is_truthy_value(entry.get("disabled", False)),
|
||||
"transport": str(entry.get("transport") or "http") if entry.get("url") else "stdio",
|
||||
}
|
||||
for srv_name in sorted(mcp_cfg.keys())
|
||||
for entry in (mcp_cfg[srv_name],)
|
||||
if isinstance(entry, dict)
|
||||
],
|
||||
[],
|
||||
)
|
||||
return _try(lambda: [
|
||||
{"name": str(srv_name), "enabled": not is_truthy_value(entry.get("disabled", False)),
|
||||
"transport": str(entry.get("transport") or "http") if entry.get("url") else "stdio"}
|
||||
for srv_name in sorted(mcp_cfg.keys()) for entry in (mcp_cfg[srv_name],)
|
||||
if isinstance(entry, dict)
|
||||
], [])
|
||||
|
||||
|
||||
@_profile_handler("profiles.describe", 5063)
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Editor snapshot: ``{name, description, soul, model, skills: [{name, enabled}], toolsets,
|
||||
toolsets_pinned, mcp_servers}``; installed skills are enabled unless in ``skills.disabled``."""
|
||||
"""Editor snapshot; installed skills are enabled unless in ``skills.disabled``."""
|
||||
name, profile_dir, err = _resolve_profile(rid, params)
|
||||
if err is not None:
|
||||
return err
|
||||
@@ -478,24 +435,19 @@ def _(rid, params: dict) -> dict:
|
||||
skills_root = profile_dir / "skills"
|
||||
installed = [
|
||||
{"name": md.parent.name, "enabled": md.parent.name.lower() not in disabled}
|
||||
for md in (sorted(skills_root.rglob("SKILL.md")) if skills_root.is_dir() else ())
|
||||
]
|
||||
for md in (sorted(skills_root.rglob("SKILL.md")) if skills_root.is_dir() else ())]
|
||||
toolsets_out, pinned_set = _describe_toolsets(cfg)
|
||||
soul = _read_text_if_file(profile_dir / "SOUL.md")
|
||||
soul_path = profile_dir / "SOUL.md"
|
||||
soul = _try(lambda: soul_path.read_text(encoding="utf-8", errors="replace") if soul_path.is_file() else "", "")
|
||||
mcp_out = _describe_mcp_servers(cfg)
|
||||
model_cfg = cfg.get("model") if isinstance(cfg.get("model"), dict) else {}
|
||||
meta = _try(lambda: _lazy("hermes_cli.profiles", "read_profile_meta")(profile_dir), {})
|
||||
result = {
|
||||
"name": name,
|
||||
"description": str(meta.get("description") or ""),
|
||||
"soul": soul,
|
||||
"model": {"provider": str(model_cfg.get("provider") or ""), "default": str(model_cfg.get("default") or "")},
|
||||
"skills": installed,
|
||||
"toolsets": toolsets_out,
|
||||
"toolsets_pinned": pinned_set is not None,
|
||||
"mcp_servers": mcp_out,
|
||||
}
|
||||
return _ok(rid, result)
|
||||
return _ok(rid, {
|
||||
"name": name, "description": str(meta.get("description") or ""), "soul": soul,
|
||||
"model": {"provider": str(model_cfg.get("provider") or ""),
|
||||
"default": str(model_cfg.get("default") or "")},
|
||||
"skills": installed, "toolsets": toolsets_out,
|
||||
"toolsets_pinned": pinned_set is not None, "mcp_servers": mcp_out})
|
||||
|
||||
|
||||
def _configure_ui_meta(profile_dir, params, applied) -> None:
|
||||
@@ -546,23 +498,16 @@ def _configure_ui_meta(profile_dir, params, applied) -> None:
|
||||
|
||||
|
||||
def _configure_model(profile_dir, params, applied):
|
||||
"""Apply a ``model`` + ``provider`` pin, or return a confirm message and write NOTHING (the
|
||||
``config.set model`` handshake: client resends with ``confirm_expensive_model``). A failing
|
||||
guard counts as "no warning", matching ``_apply_model_switch``."""
|
||||
"""Apply a ``model`` + ``provider`` pin, or return a confirm message and write NOTHING (client
|
||||
resends with ``confirm_expensive_model``). A failing guard = "no warning" (as _apply_model_switch)."""
|
||||
model = str(params.get("model") or "").strip()
|
||||
provider = str(params.get("provider") or "").strip()
|
||||
confirm_message = None
|
||||
if not (model and provider):
|
||||
return None
|
||||
if not is_truthy_value(params.get("confirm_expensive_model", False)):
|
||||
confirm_message = _try(
|
||||
lambda: getattr(
|
||||
_lazy("hermes_cli.model_selection_guards", "combined_selection_warning")(model, provider=provider or None),
|
||||
"message",
|
||||
None,
|
||||
),
|
||||
None,
|
||||
)
|
||||
warn = _lazy("hermes_cli.model_selection_guards", "combined_selection_warning")
|
||||
confirm_message = _try(lambda: getattr(warn(model, provider=provider or None), "message", None), None)
|
||||
if confirm_message is None:
|
||||
applied["model"] = _best_effort(lambda: _pin_profile_model(profile_dir, provider, model))
|
||||
return confirm_message
|
||||
@@ -570,8 +515,8 @@ def _configure_model(profile_dir, params, applied):
|
||||
|
||||
def _configure_cfg_sections(profile_dir, params, applied) -> None:
|
||||
"""Apply ``disabled_skills`` / ``enabled_toolsets`` / ``enabled_mcp_servers`` (replace
|
||||
semantics; empty toolsets clears the pin). Enabling an undefined MCP server copies its
|
||||
definition from the LAUNCH catalog (unknown names skipped); credentials stay in .env/auth."""
|
||||
semantics; empty toolsets clears the pin). An undefined MCP server is copied from the LAUNCH
|
||||
catalog (unknown names skipped); credentials stay in .env/auth."""
|
||||
want_mcp = isinstance(params.get("enabled_mcp_servers"), list)
|
||||
# Launch catalog read BEFORE the home override flips config resolution.
|
||||
launch_mcp = _try(_launch_mcp_catalog, {}) if want_mcp else {}
|
||||
@@ -589,9 +534,8 @@ def _configure_cfg_sections(profile_dir, params, applied) -> None:
|
||||
if isinstance(params.get("enabled_toolsets"), list):
|
||||
applied["toolsets"] = _best_effort(lambda: _save_toolset_pin(cfg, params["enabled_toolsets"], save_config))
|
||||
if want_mcp:
|
||||
applied["mcp_servers"] = _best_effort(
|
||||
lambda: _save_mcp_toggles(load_config() or {}, params["enabled_mcp_servers"], launch_mcp, save_config)
|
||||
)
|
||||
applied["mcp_servers"] = _best_effort(lambda: _save_mcp_toggles(
|
||||
load_config() or {}, params["enabled_mcp_servers"], launch_mcp, save_config))
|
||||
|
||||
|
||||
def _clean_names(values) -> set:
|
||||
@@ -640,11 +584,9 @@ def _(rid, params: dict) -> dict:
|
||||
if isinstance(params.get("soul"), str):
|
||||
applied["soul"] = _best_effort(lambda: (profile_dir / "SOUL.md").write_text(params["soul"], encoding="utf-8"))
|
||||
if isinstance(params.get("description"), str):
|
||||
applied["description"] = _best_effort(
|
||||
lambda: _lazy("hermes_cli.profiles", "write_profile_meta")(
|
||||
profile_dir, description=params["description"].strip(), description_auto=False
|
||||
)
|
||||
)
|
||||
write_meta = _lazy("hermes_cli.profiles", "write_profile_meta")
|
||||
applied["description"] = _best_effort(lambda: write_meta(
|
||||
profile_dir, description=params["description"].strip(), description_auto=False))
|
||||
confirm_message = _configure_model(profile_dir, params, applied)
|
||||
if any(isinstance(params.get(k), list) for k in ("disabled_skills", "enabled_toolsets", "enabled_mcp_servers")):
|
||||
_configure_cfg_sections(profile_dir, params, applied)
|
||||
@@ -676,7 +618,7 @@ def _unlink_asset_files(assets_dir, asset) -> int:
|
||||
@_profile_handler("profiles.set_asset", 5065)
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Store ``assets/<asset>.<ext>`` atomically. Params: ``name``, ``asset`` (``"avatar"`` only),
|
||||
``data`` (data URL or base64; PNG/JPEG/WebP ≤2MB) or ``clear: true``. Result ``{ok, asset, size}``."""
|
||||
``data`` (data URL or base64; PNG/JPEG/WebP ≤2MB) or ``clear: true``."""
|
||||
asset = str(params.get("asset") or "avatar").strip().lower()
|
||||
if not str(params.get("name") or "").strip():
|
||||
return _err(rid, 4063, "name required")
|
||||
@@ -715,7 +657,7 @@ def _(rid, params: dict) -> dict:
|
||||
|
||||
@_profile_handler("profiles.get_asset", 5066)
|
||||
def _(rid, params: dict) -> dict:
|
||||
"""Profile asset as a data URL: ``{found, data?, mime?, size?}``; absent is ``found: false``, not an error."""
|
||||
"""Profile asset as a data URL; absent is ``found: false``, not an error."""
|
||||
asset = str(params.get("asset") or "avatar").strip().lower()
|
||||
import base64
|
||||
_name, profile_dir, err = _resolve_profile(rid, params)
|
||||
|
||||
+259
-423
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user