The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: profiles.list/profiles.create ws RPC + plugin session-navigation doors (#85093)
Teknium89a84e1ae6cc
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex ae7d02a4200..ba6e636dbb0 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -20,12 +20,13 @@import { atom, type ReadableAtom } from 'nanostores'+import { openSession, type OpenSessionIntent } from '@/app/open-session'import { $narrowViewport } from '@/components/pane-shell/tree/store'import { onGatewayEvent } from '@/contrib/events'import { getLogs, getStatus } from '@/hermes'import { $gateway } from '@/store/gateway'import { notify, notifyError } from '@/store/notifications'-import { $activeGatewayProfile } from '@/store/profile'+import { $activeGatewayProfile, ensureGatewayProfile, newSessionInProfile } from '@/store/profile'import { $activeSessionId, $currentCwd, $currentModel, $gatewayState } from '@/store/session'import { runGatewayRestart } from '@/store/system-actions'@@ -87,6 +88,43 @@ export const host = {window.location.hash = path.startsWith('#') ? path : `#${path}`},+ /** Open a stored session the way core surfaces do (focus an existing+ * tile/main, else load into main). When `profile` names a non-active+ * profile, its backend is activated first so the resume routes to the+ * right state.db — the same soft profile swap the unified sidebar does. */+ openSession: async (+ storedSessionId: string,+ options: { intent?: OpenSessionIntent; profile?: null | string } = {}+ ): Promise<void> => {+ const profile = (options.profile ?? '').trim()++ if (profile && profile !== $activeGatewayProfile.get()) {+ await ensureGatewayProfile(profile)+ }++ openSession(+ storedSessionId,+ (to: string, opts?: { replace?: boolean }) => {+ const target = to.startsWith('#') ? to : `#${to}`++ if (opts?.replace) {+ window.location.replace(target)+ } else {+ window.location.hash = target+ }+ },+ options.intent ?? 'in-place'+ )+ },++ /** Start a fresh chat draft, optionally pointed at another profile (its+ * backend spins up in the background — same door the sidebar's per-profile+ * "+" uses). */+ newChat: (profile?: null | string): void => {+ newSessionInProfile((profile ?? '').trim() || $activeGatewayProfile.get())+ window.location.hash = '#/'+ },+/** HEAR the gateway stream (message deltas, session lifecycle, tool* activity, …) by event type — `'*'` for everything. Returns a disposer.* Listeners are isolated; a throw can't affect app dispatch. */diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.pynew file mode 100644index 00000000000..d93510f32b2--- /dev/null+++ b/tui_gateway/methods_profiles.py@@ -0,0 +1,175 @@+"""Profile JSON-RPC handlers — the ws twin of the dashboard's /api/profiles.++Motivation: desktop plugins reach the backend exclusively through the+generic ws JSON-RPC door (`host.request`). Profile enumeration/creation+previously lived only on the dashboard REST router, which plugins cannot+reach, so anything "one chat per agent profile"-shaped (bot rosters,+profile pickers, team panes) was impossible to build as a plugin. These+handlers delegate to the same `hermes_cli.profiles` primitives the REST+endpoints use.++Handlers are rebound onto server.py's globals at install time — see+method_ctx.py. They may reference server.py module globals (`_ok`,+`_err`, `is_truthy_value`, ...) that are not imported here.+"""++from .method_ctx import HandlerRegistry++_registry = HandlerRegistry()+method = _registry.method+++@method("profiles.list")+def _(rid, params: dict) -> dict:+ """List Hermes profiles (name, path, model, description, skill count).++ ``include_sessions`` (default true) additionally reports each profile's+ most recent conversation as ``last_session`` so a roster UI can paint+ per-agent previews without N follow-up calls.++ NOTE: helpers must be nested — install() rebinds this handler's+ __globals__ onto server.py, so module-level names here are invisible.+ """++ def _latest_profile_session_row(profile_path):+ """Most recent human-facing session in a profile's state.db, or None.++ Mirrors session.list's deny-list (drops ``tool`` sub-agent rows and+ ``kanban`` dispatcher workers). Best-effort: any failure (missing+ state.db, locked db, older schema) degrades to None rather than+ failing the whole profiles.list call.+ """+ try:+ from pathlib import Path++ db_path = Path(profile_path) / "state.db"+ if not db_path.exists():+ return None+ from hermes_state import SessionDB++ deny = frozenset({"kanban", "tool"})+ db = SessionDB(db_path=db_path)+ try:+ for s in db.list_sessions_rich(+ source=None, limit=20, order_by_last_active=True, compact_rows=True+ ):+ if (s.get("source") or "").strip().lower() in deny:+ continue+ return {+ "id": s["id"],+ "title": s.get("title") or "",+ "preview": s.get("preview") or "",+ "started_at": s.get("started_at") or 0,+ "last_active": s.get("last_active") or s.get("started_at") or 0,+ "message_count": s.get("message_count") or 0,+ }+ finally:+ try:+ db.close()+ except Exception:+ pass+ except Exception:+ return None+ return None++ try:+ 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 "",+ "skill_count": getattr(p, "skill_count", 0) or 0,+ }+ if include_sessions:+ row["last_session"] = _latest_profile_session_row(p.path)+ out.append(row)+ return _ok(rid, {"profiles": out})+ except Exception as e:+ return _err(rid, 5061, str(e))+++@method("profiles.create")+def _(rid, params: dict) -> dict:+ """Create a profile — the ws twin of POST /api/profiles.++ Params: ``name`` (required, lowercase slug), ``description``,+ ``clone_from`` (source profile; omitted = fresh profile with bundled+ skills), ``clone_all``, ``no_skills``, ``soul`` (SOUL.md content),+ ``model`` + ``provider`` (optional model pin, best-effort).+ """+ name = str(params.get("name") or "").strip()+ if not name:+ return _err(rid, 4061, "name required")+ try:+ from hermes_cli import profiles as profiles_mod++ clone_from = str(params.get("clone_from") or "").strip() or None+ clone_all = is_truthy_value(params.get("clone_all", False))+ path = profiles_mod.create_profile(+ 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,+ )+ except (ValueError, FileExistsError, FileNotFoundError) as e:+ return _err(rid, 4062, str(e))+ except Exception as e:+ return _err(rid, 5062, str(e))++ # Mirror the CLI/REST create flow: fresh profiles get the bundled+ # skills; safe alias wrapper. Both best-effort.+ try:+ if not clone_from:+ profiles_mod.seed_profile_skills(path, quiet=True)+ except Exception:+ pass+ try:+ if not profiles_mod.check_alias_collision(name):+ profiles_mod.create_wrapper_script(name)+ except Exception:+ pass++ soul = params.get("soul")+ soul_written = False+ if isinstance(soul, str) and soul.strip():+ try:+ (path / "SOUL.md").write_text(soul, encoding="utf-8")+ soul_written = True+ except Exception:+ pass++ model = str(params.get("model") or "").strip()+ provider = str(params.get("provider") or "").strip()+ model_set = False+ if model and provider:+ try:+ from hermes_cli.web_routers.profiles import _write_profile_model++ _write_profile_model(path, provider, model)+ model_set = True+ except Exception:+ pass++ return _ok(+ rid,+ {+ "ok": True,+ "name": name,+ "path": str(path),+ "soul_written": soul_written,+ "model_set": model_set,+ },+ )+++def register(server) -> None:+ _registry.install(server)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 4e15cce335e..2239e4163bb 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -249,6 +249,12 @@ _LONG_HANDLERS = frozenset(# reloads via _mcp_reload_lock."reload.mcp","process.list",+ # profiles.list runs list_profiles() (recursive skill-tree walk per+ # profile) and opens each profile's state.db for the last-session+ # preview; profiles.create copies skill bundles. Both are seconds-+ # scale on cold disks — keep them off the WS reader thread.+ "profiles.create",+ "profiles.list","projects.discover_repos","projects.record_repos","projects.for_cwd",@@ -14428,6 +14434,7 @@ def _browser_disconnect(rid) -> dict:from . import ( # noqa: E402methods_complete as _methods_complete,methods_config as _methods_config,+ methods_profiles as _methods_profiles,methods_prompt as _methods_prompt,methods_session as _methods_session,methods_tools as _methods_tools,@@ -14439,6 +14446,7 @@ for _m in (_methods_config,_methods_complete,_methods_tools,+ _methods_profiles,):_m.register(sys.modules[__name__])del _mdiff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex 2e5abb8bec3..f85454e47d5 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -377,6 +377,10 @@ ctx.os.openExternal(url) // OS default handler (browser, mail,ctx.os.revealPath(path) // reveal in Finder / Explorer → Promise<boolean>ctx.os.writeClipboard(text) // system clipboard → Promise<boolean>host.navigate('/route') // hash-route navigation+host.openSession(id, { profile?, intent? }) // open a stored session core-style;+ // profile: soft-swap to that profile's backend first+ // intent: 'in-place' (default) | 'stack' | 'tab' | 'window'+host.newChat(profile?) // fresh chat draft, optionally in another profilehost.onEvent(type, fn) // gateway event stream ('*' = all); returns disposerhost.logs(...) // tail an app log filehost.status() // one-shot system status snapshot@@ -385,7 +389,13 @@ host.request<T>(method, params?) // gateway JSON-RPC — the real powe````host.request` is the same JSON-RPC the app itself uses (sessions, config, skills,-cron, kanban, …). `host.onEvent` streams live gateway events (message deltas,+cron, kanban, …). Profile-shaped plugins get first-class methods too:+`profiles.list` (each profile + its most recent conversation as+`last_session`; pass `include_sessions: false` to skip the per-profile DB+probe) and `profiles.create` (`name`, `description`, `clone_from`,+`clone_all`, `no_skills`, `soul`, optional `model` + `provider` pin) — the+ws twins of the dashboard's `/api/profiles` REST routes.+`host.onEvent` streams live gateway events (message deltas,session lifecycle, tool activity). Listeners are isolated — a throw in yourlistener can't affect app dispatch. Every `host` door is async-safe: a sync throwfrom an internal helper (e.g. no desktop bridge in a plain browser) becomes a