The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main into feat/unified-gateway-runtime
Tekniumb17aa114d2d0
diff --cc apps/desktop/electron/main.tsindex 935d8bb0c1e,24ca25e8176..4ab82ea6ab0--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -64,15 -57,9 +68,10 @@@ import} from './backend-claim'import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'import { createBackendConnectionState } from './backend-connection-state'+import { assertDescriptorStillOwned, forgetFailedDescriptor } from './backend-descriptor-cache'import { BackendDialClaims } from './backend-dial-claim'import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'- import {- isReauthRequiredError,- makeNousCloudBackendDownError,- makeUnsignedOauthError,- waitForHermesReady- } from './backend-health'+ import { isReauthRequiredError, waitForHermesReady } from './backend-health'import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'import {canImportHermesCli,@@@ -296,7 -277,9 +289,10 @@@ import { loadNativeTokenSet, type Nativimport { registerNativeNotifications } from './notification-ipc'import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request'import { LEGACY_OAUTH_PARTITION, resolveOauthPartition } from './oauth-partition'+ import { mintGatewayWsTicket as mintOauthGatewayWsTicket, requestWithOauthFallback } from './oauth-rest-request'+ import { wireOauthSessionResponse } from './oauth-session-response'+ import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'+import { createParentStartMarkerResolver } from './parent-process-identity'import { registerPetOverlayIpc } from './pet-overlay-ipc'import {pendingNotice as pendingPluginCompatNotice,@@@ -10928,22 -11004,8 +10793,20 @@@ async function fetchJsonForProfile(prof// Issue an arbitrary method against a profile's resolved backend, parsed JSON.async function requestJsonForProfile(profile: string, path: string, method: string, body?: string) {const conn = await ensureBackend(profile)- const url = `${conn.baseUrl}${path}`- const opts = { method, body, timeoutMs: DEFAULT_FETCH_TIMEOUT_MS }- return fetchJsonForBackend(conn, path, { method, body, timeoutMs: DEFAULT_FETCH_TIMEOUT_MS })+ if (conn.authMode === 'oauth') {+ // Native RFC 8252 flow: authenticate with the bearer token (cookieless)+ // when we hold one for this gateway; otherwise use the cookie partition.+ const nativeAt = await ensureNativeAccessToken(conn.baseUrl).catch(() => null)++ if (nativeAt) {+ return fetchJson(url, null, { ...opts, bearer: nativeAt, headers: conn.headers })+ }++ return fetchJsonViaOauthSession(url, { ...opts, headers: conn.headers })+ }++ return fetchJson(url, conn.token, { ...opts, headers: conn.headers, gatewayDescriptor: conn.gatewayEndpoint ? conn : undefined })}async function probeRemoteAuthMode(rawUrl) {@@@ -12305,9 -12750,28 +12127,21 @@@ const backendShutdown = createBackendShconst primary = backendConnectionState.invalidate()stopBackendChild(primary)- const pooledStops = stopAllPoolBackends()-- if (poolIdleReaper) {- clearInterval(poolIdleReaper)- poolIdleReaper = null- }-- await waitForTeardown([localShutdown, waitForBackendExit(primary), pooledStops], 7_000)+ await Promise.all([waitForBackendExit(primary), stopAllPoolBackends()])})+ const quitTeardown = createQuitTeardownCoordinator(() => app.quit())++ async function teardownSshForQuit() {+ const scopes = [...sshConnections.keys()]++ for (const scope of scopes) {+ void teardownSshConnection(scope || null).catch(error => rememberLog(`SSH teardown failed: ${error.message}`))+ }++ await sshTeardowns.finish(sshBootstrapCoordinator.promises(), () => sshBootstrapCoordinator.forceCleanupAll())+ }+async function exitAfterBackendShutdown(code) {await backendShutdown.run()app.exit(code)diff --cc apps/desktop/src/plugins/hermes-bots/group-rounds.tsindex 9b95748bfec,d49d44426df..f9a4b70882d--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts@@@ -663,8 -660,12 +662,13 @@@ export function sendToGroupChatthread?: null | string,images?: Attachment[]): null | string {+ if (group.startsWith('canonical:')) {throw new Error('Canonical rooms are driven by the gateway')}const trimmed = String(text || '').trim()++ if (rejectGroupSlashCommand(trimmed)) {+ return null+ }+const attached = Array.isArray(images) ? images.filter((img: Attachment) => img && img.data) : []if ((!trimmed && !attached.length) || !members.length) {diff --cc gateway/platforms/api_server.pyindex 62c64bc50ab,11e49a35e37..8e5c41a01c5--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@@ -3663,8 -3659,8 +3677,9 @@@ class APIServerAdapter(OpenAICompatRoutroute: Optional[Dict[str, Any]] = None, session_model: Optional[str] = None,requested_runtime: Optional[Dict[str, Any]] = None, route_source: str = "global",confirmed_runtime_lock: bool = False, bind_declared_conversation: bool = False,+ request_id: Optional[str] = None, history_from_session: bool = False,- session_history_delivery: str = "", turn_author: Optional[Dict[str, Any]] = None) -> tuple:+ session_history_delivery: str = "", turn_author: Optional[Dict[str, Any]] = None,+ relay_metadata: Optional[Dict[str, Any]] = None) -> tuple:"""Create an agent and run one turn in a thread executor -> ``(result, usage)``.``agent_ref[0]`` receives the agent so SSE writers can interrupt it; ``active_run_id``registers it in ``_active_run_agents``. Under a confirmed model lock the actualdiff --cc gateway/platforms/api_server_openai_routes.pyindex 1192d9ab242,3d4c92dce9d..b2f50c7f4d1--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@@ -867,16 -851,7 +872,16 @@@ class OpenAICompatRoutesMixinuser_message=user_message, conversation_history=conversation_history,ephemeral_system_prompt=instructions, session_id=session_id,gateway_session_key=gateway_session_key, bind_declared_conversation=_declared_selected,- **agent_overrides, route=route)+ **agent_overrides, route=route, relay_metadata=relay_metadata)+ if getattr(self.gateway_runner, 'session_authority', None) is not None:+ key = request.headers.get('Idempotency-Key')+ if key:+ import hashlib+ # A fresh responses request must recover its target before admission.+ if not stored_session_id and not gateway_session_key:+ session_id = 'response-' + hashlib.sha256(key.encode()).hexdigest()+ run_kwargs['session_id'] = session_id+ run_kwargs['request_id'] = 'responses:' + keyif stream:_stream_q = ThreadSafeAsyncQueue()diff --cc gateway/run.pyindex e8d2cb8e8bc,7c0bc37efbf..ba0470abe45--- a/gateway/run.py+++ b/gateway/run.py@@@ -3292,7 -3328,7 +3339,7 @@@ class GatewayRunnerGatewayVoiceMixin, GatewayAdapterLifecycleMixin, GatewayTopicThreadsMixin, GatewayTurnMixin,GatewayShutdownMixin, GatewayBusySessionMixin, GatewayConfigLoadersMixin, GatewayStartupMixin,GatewaySessionWatchersMixin, GatewayNotificationsMixin, GatewayInboundMixin, GatewayGoalsMixin,- GatewayAgentCacheMixin, GatewayRuntimeInitMixin, GatewayWisdomMixin):- GatewayAgentCacheMixin):++ GatewayAgentCacheMixin, GatewayRuntimeInitMixin):"""Main gateway controller: manages adapter lifecycles, routes messages to/from the agent."""# Class-level defaults so partial construction in tests doesn't blow up on attribute access.diff --cc gateway/run_adapters.pyindex e97b9a12b0d,2897c97e1af..c9bf6880872--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@@ -1298,24 -1296,24 +1299,29 @@@ class GatewayAdapterLifecycleMixin(auth runs BEFORE the agent-turn scope, so the profile's ``.env`` must be visible here)."""from gateway.run import _async_profile_runtime_scopeprofile_home = self._profile_home_or_none(profile_name)+ from gateway.session_ingress_context import native_callback, register_transport_home+ register_transport_home(self, profile_name, profile_home)- async def _handler(event):+ async def _handler(_runner, event):self._stamp_event_profile(event, profile_name)- async with self._scope_or_null(_async_profile_runtime_scope, profile_home):- return await self._handle_message(event)+ if profile_home is not None:+ event.source._authorization_profile_home = profile_home+ with native_callback(self, event, profile_home, profile_name):+ async with self._scope_or_null(_async_profile_runtime_scope, profile_home):+ return await self._handle_message(event)- return _handler+ return _handler.__get__(self)def _make_profile_busy_session_handler(self, profile_name: str):- """Stamp an owning adapter's profile before resolving busy policy."""+ """Stamp an owning adapter's profile, then resolve busy policy under the profile scope+ (auth runs against the profile's own allowlist, same as the cold-path message handler)."""+ from gateway.run import _async_profile_runtime_scope+ profile_home = self._profile_home_or_none(profile_name)+async def _handler(event, _session_key):self._stamp_event_profile(event, profile_name)- return await self._handle_active_session_busy_message(event, self._session_key_for_source(event.source))+ async with self._scope_or_null(_async_profile_runtime_scope, profile_home):+ return await self._handle_active_session_busy_message(event, self._session_key_for_source(event.source))return _handler@@@ -1324,31 -1322,53 +1330,57 @@@with the transport profile (a routed profile may have no credential/allowlist)."""from gateway.run import _async_profile_runtime_scope, get_hermes_homedefault_home = Path(get_hermes_home())+ from gateway.session_ingress_context import register_transport_home+ register_transport_home(self, None, default_home)- async def _handler(event):+ async def _handler(_runner, event):- source = event.source- # In-process only (serialization ignores dynamic attrs); route ≠ admitting bot.- source._authorization_profile_home = default_home- if (- not getattr(source, "profile", None)- and getattr(source, "profile_route_rejected", False) is not True- and not self._stamp_routed_profile(source)- ):- # Read by the ``_handle_message`` ingress gate, which drops fail-closed.- source.profile_route_rejected = True- profile_home = (- self._resolve_profile_home_for_source(source)- if getattr(source, "profile", None) else default_home- )+ # A rejected route still enters ``_handle_message``, whose ingress gate drops it fail-closed.+ profile_home = self._admit_primary_source(event.source, default_home) or default_home- async with _async_profile_runtime_scope(profile_home):- return await self._handle_message(event)+ from gateway.session_ingress_context import native_callback+ with native_callback(self, event, default_home):+ async with _async_profile_runtime_scope(profile_home):+ return await self._handle_message(event)- return _handler+ return _handler.__get__(self)+ def _make_default_profile_busy_session_handler(self):+ """Busy-path twin of ``_make_default_profile_message_handler``: busy callbacks bypass the message+ handler, so the routed scope and transport-home authorization must be re-established here or the+ follow-up is authorized in whatever scope is ambient (#103717)."""+ from gateway.run import _async_profile_runtime_scope, get_hermes_home+ default_home = Path(get_hermes_home())++ async def _handler(event, _session_key):+ source = event.source+ profile_home = self._admit_primary_source(source, default_home)+ if profile_home is None:+ return True # rejected route: swallow, same disposition as the ingress gate+ async with _async_profile_runtime_scope(profile_home):+ return await self._handle_active_session_busy_message(+ event, self._session_key_for_source(source)+ )++ return _handler++ def _admit_primary_source(self, source, default_home: Path) -> Optional[Path]:+ """Stamp the transport home (authorization) and routed profile on a primary-adapter source and+ return the runtime home to scope the turn under; ``None`` when the route targets an unserved+ profile. ``_authorization_profile_home`` is in-process only (serialization ignores dynamic attrs);+ route ≠ admitting bot."""+ source._authorization_profile_home = default_home+ if (+ not getattr(source, "profile", None)+ and getattr(source, "profile_route_rejected", False) is not True+ and not self._stamp_routed_profile(source)+ ):+ source.profile_route_rejected = True+ if getattr(source, "profile_route_rejected", False) is True:+ return None+ return (+ self._resolve_profile_home_for_source(source)+ if getattr(source, "profile", None) else default_home+ )+def _stamp_routed_profile(self, source) -> bool:"""Stamp ``source.profile`` from ``profile_routes``; False when the route is rejected."""from gateway.profile_routing import ProfileRouteRejected@@@ -1360,9 -1380,15 +1392,16 @@@def _primary_message_handler(self):"""Return the correctly scoped handler for a primary adapter."""- return self._make_default_profile_message_handler() if self._multiplex_on() else self._handle_message+ shared = getattr(self, 'session_authority', None) is not None+ return self._make_default_profile_message_handler() if self._multiplex_on() or shared else self._handle_message+ def _primary_busy_session_handler(self):+ """Return the correctly scoped busy-session handler for a primary adapter."""+ return (+ self._make_default_profile_busy_session_handler()+ if self._multiplex_on() else self._handle_active_session_busy_message+ )+def _multiplex_on(self) -> bool:return bool(getattr(self.config, "multiplex_profiles", False))diff --cc hermes_cli/subcommands/gateway.pyindex 657a99a57be,c135f803016..33758ddb0c6--- a/hermes_cli/subcommands/gateway.py+++ b/hermes_cli/subcommands/gateway.py@@@ -8,26 -8,13 +8,33 @@@ from typing import Callablfrom hermes_cli.subcommands._shared import add_accept_hooks_flag+ # `start`/`restart` on a named profile refuse while the default multiplexer serves it (a second gateway+ # would double-bind its platforms); `gateway run` carries its own broader --force text.+ _FORCE_SERVED_PROFILE_HELP = (+ "Start a separate gateway for this profile even when the default multiplexer already serves it "+ "(not recommended: two pollers on one bot token, port conflicts)")+++class _GatewayCommandParser(argparse.ArgumentParser):+ """Ensure's parser errors share its machine-readable command boundary."""++ def __init__(self, *args, ensure_json=False, **kwargs):+ self.ensure_json = ensure_json+ super().__init__(*args, **kwargs)++ def parse_known_args(self, args=None, namespace=None):+ parsed, unknown = super().parse_known_args(args, namespace)+ if self.ensure_json and unknown:+ self.error("unknown arguments")+ return parsed, unknown++ def error(self, message):+ if not self.ensure_json:+ return super().error(message)+ print('{"endpoint":null,"reason_code":"invalid_invocation","state":"inaccessible"}')+ self.exit(2, "gateway ensure: invalid invocation\n")++def _flag(parser, *names, help, **kw):parser.add_argument(*names, action="store_true", help=help, **kw)diff --cc hermes_cli/web_server_sessions.pyindex a708ff636fd,70bfbc914b0..86759f06380--- a/hermes_cli/web_server_sessions.py+++ b/hermes_cli/web_server_sessions.py@@@ -170,42 -115,73 +170,39 @@@ def _open_session_db_at_path(db_path: Pif not read_only:return acquire(db_path)- def _needs_bootstrap() -> bool:- try:- return db_path.stat().st_size == 0- except FileNotFoundError:- return True- except OSError:- return False-- if _needs_bootstrap():- with _session_db_bootstrap_lock:- if _needs_bootstrap():- db = acquire(db_path)- release_or_close(db)-- def _open_probed():+ try:+ initialized = db_path.stat().st_size > 0+ except FileNotFoundError:+ initialized = False+ if not initialized:+ raise HTTPException(+ status_code=503,+ detail="Session store is not initialized. Start this profile's gateway to initialize it.")++ try:db = SessionDB(db_path=db_path, read_only=True)- # Unit-test fakes may replace SessionDB without exposing a raw- # connection. Probe only real connections.- conn = getattr(db, "_conn", None)- if conn is not None and str(db_path) not in _session_db_heal_exhausted:- try:+ try:+ conn = getattr(db, "_conn", None)+ if conn is not None:for statement in _session_db_read_probe_statements():conn.execute(statement).fetchone()- except BaseException:- db.close()- raise- return db-- try:- return _open_probed()- except (sqlite3.DatabaseError, UnicodeDecodeError) as exc:- # UnicodeDecodeError = pysqlite could not decode SQLite's own error- # message because corrupt file bytes were embedded in it; the- # one-writable-open heal is the only repair path, so treat it as- # malformed schema.- if not (- _is_stale_schema_error(exc)- or is_malformed_schema_error(exc)- or isinstance(exc, UnicodeDecodeError)):+ return db+ except BaseException:+ db.close()raise- db = acquire(db_path)- release_or_close(db)- try:- return _open_probed()- except (sqlite3.DatabaseError, UnicodeDecodeError) as still_stale:- if not _is_stale_schema_error(still_stale):- raise- # Writable open succeeded but the store is STILL behind the probe:- # serve reads without the probe (only queries touching the broken- # part fail) and stop paying the writable init per poll.- _session_db_heal_exhausted.add(str(db_path))- if str(db_path) not in _session_db_heal_warned:- _session_db_heal_warned.add(str(db_path))- _log.warning(- "state.db at %s is missing schema that a writable "- "reconcile could not add (%s); read paths may partially "- "fail until the store is repaired",- db_path,- still_stale)- return _open_probed()+ except (sqlite3.DatabaseError, UnicodeDecodeError) as exc:+ if isinstance(exc, sqlite3.OperationalError) and is_transient_sqlite_error(exc):+ detail = "Session store is busy (disk I/O or lock). Retry; the list was not cleared."+ else:+ detail = (+ "Session store schema is unavailable or corrupt. Start or restart this profile's "+ "gateway to reconcile it; if it persists, run `hermes doctor` for diagnosis. "+ "Browsing does not repair the store.")+ raise HTTPException(status_code=503, detail=detail) from exc- def _open_session_db_for_profile(profile: Optional[str], *, read_only: bool):- """Open a SessionDB for ``profile`` (None/empty = this process's own state.db).-- Access-mode semantics: see :func:`_open_session_db_at_path`.- """+ def _session_db_path_for_profile(profile: Optional[str]) -> Path:+ """state.db path for ``profile`` (None/empty = this process's own)."""from hermes_cli.web_server_cron import _cron_profile_homefrom hermes_state import _default_db_pathdiff --cc tools/mcp_tool_registration.pyindex afed0f16bd5,df3a4aad332..40fccd1e143--- a/tools/mcp_tool_registration.py+++ b/tools/mcp_tool_registration.py@@@ -365,18 -387,10 +387,18 @@@ def _register_server_tools(name: str, s_record_tool_trust_metadata(name, config, server._tools)candidates = _tool_candidates(name, server._tools, should_register, server.tool_timeout)candidates += _utility_candidates(name, _select_utility_schemas(name, server, config), server.tool_timeout)+ if (_core._server_registry_scope(name) or '').startswith('editor-session:'):+ import json+ from hermes_state_runtime import RuntimeStoreError+ manifest = json.dumps({c.registry_name: c.schema for c in candidates}, sort_keys=True)+ frozen = getattr(server, '_editor_frozen_manifest', manifest)+ if manifest != frozen:+ raise RuntimeStoreError('acp_mcp_schema_changed')+ server._editor_frozen_manifest = frozenregistered = _register_candidates(name, _resolve_name_collisions(name, candidates),- check_fn=_make_check_fn(name), scope=lambda: _core._server_registry_scope(name), lazy=False)- if registered and not (_core._server_registry_scope(name) or '').startswith('editor-session:'):+ check_fn=_make_check_fn(name), scope=lambda: _core._server_registry_scope(key), lazy=False, key=key)- if registered:++ if registered and not (_core._server_registry_scope(key) or '').startswith('editor-session:'):_write_schema_cache(name, server, config, should_register)return registereddiff --cc tui_gateway/methods_complete.pyindex 126114a221f,a7e5decc116..9b1b2c5cca9--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@@ -215,11 -221,53 +215,10 @@@ def _(rid, params: dict) -> dict@method("complete.slash")- @_profile_scoped@_catch(5020)def _(rid, params: dict) -> dict:- text = params.get("text", "")- if not text.startswith("/"):- return _ok(rid, {"items": []})- from hermes_cli.commands_completion import SlashCommandCompleter- from prompt_toolkit.document import Document- from prompt_toolkit.formatted_text import to_plain_text- from agent.skill_commands import get_skill_commands- from agent.skill_bundles import get_skill_bundles- completer = SlashCommandCompleter(- skill_commands_provider=lambda: get_skill_commands(), skill_bundles_provider=lambda: get_skill_bundles())- # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):- # skills/bundles are the only completions for an inline `/skill` typed mid-message.- skill_names = {key.lstrip("/").lower() for key in (*get_skill_commands(), *get_skill_bundles())}-- def to_items(doc: Document) -> list[dict]:- # display/display_meta are FormattedText; the TUI contract is a plain string- # (the raw list trips Ink's row layout into 1-char truncation).- return [- {- "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,- "meta": to_plain_text(c.display_meta) if c.display_meta else "",- "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}- for c in completer.get_completions(doc, None)]- items = to_items(Document(text, len(text)))- # Rank + bound while a `/token` is under the cursor (the one stage skills are- # offered at); an argument stage (`/personality `) keeps its command's order.- if text.rsplit(" ", 1)[-1].startswith("/"):- score_of = None- # Command-token stage: the completer only emits name-prefix matches, so merge in- # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).- if " " not in text and len(text) > 1:- from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query- items, score_of = fuzzy_rank_slash_items(- items, to_items(Document("/", 1)), normalize_slash_search_query(text))- usage, origin_of = _skill_usage_lookup()- items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)- else:- items = items[:_SLASH_COMPLETION_LIMIT]- text_lower = text.lower()- for extra_text, extra_meta in _SLASH_EXTRAS:- if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):- items.append({**_item(extra_text, extra_meta), "kind": "command"})- if (details_items := _details_completions(text)) is not None:- return _ok(rid, {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)})- return _ok(rid, {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1})+ from tui_gateway.command_discovery import slash_completions+ return _ok(rid, slash_completions(params.get("text", "")))def _session_agent(params: dict):diff --cc tui_gateway/server.pyindex 476e81a815c,cbfe41572db..b9da78b0ff3--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@@ -1959,9 -3233,8 +1956,9 @@@ from . import ( # noqa: E40methods_connectors as _methods_connectors)for _m in (+ _session_registry, _agent_factory,_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,- _session_compression, _change_watcher, _tool_progress, _session_wisdom, _session_notifications,+ _session_compression, _change_watcher, _tool_progress, _session_notifications,_prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue,_methods_complete_helpers, _methods_slash, _methods_voice, _methods_browser,_methods_browser_control, _methods_session, _methods_prompt, _methods_config,diff --cc web/src/lib/api.tsindex d67575a0070,bf38969ceb0..12c7ec7c658--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@@ -371,32 -389,57 +393,45 @@@ export const api =},getSessionMessages: (id: string, profile = getManagementProfile()) =>fetchJSON<SessionMessagesResponse>(- appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/messages?limit=500&order=latest`, profile)+ appendProfileParam(+ `/api/sessions/${encodeURIComponent(id)}/messages?limit=500&order=latest`,+ profile,+ ),),getSessionDetail: (id: string, profile = getManagementProfile()) =>- fetchJSON<SessionInfo>(appendProfileParam(`/api/sessions/${encodeURIComponent(id)}`, profile)),+ fetchJSON<SessionInfo>(+ appendProfileParam(`/api/sessions/${encodeURIComponent(id)}`, profile),+ ),getSessionLatestDescendant: (id: string, profile = getManagementProfile()) =>fetchJSON<SessionLatestDescendantResponse>(- appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/latest-descendant`, profile)+ appendProfileParam(+ `/api/sessions/${encodeURIComponent(id)}/latest-descendant`,+ profile,+ ),),deleteSession: (id: string, profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean }>(- appendProfileParam(`/api/sessions/${encodeURIComponent(id)}`, profile),- {- method: "DELETE",- },- ),+ mutateSessionHttp<{ ok: boolean }>(id, "DELETE", {}, profile),getEmptySessionsCount: (profile = getManagementProfile()) =>- fetchJSON<{ count: number }>(appendProfileParam('/api/sessions/empty/count', profile)),+ fetchJSON<{ count: number }>(+ appendProfileParam("/api/sessions/empty/count", profile),+ ),deleteEmptySessions: (profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean; deleted: number }>(appendProfileParam('/api/sessions/empty', profile), {- method: 'DELETE'- }),+ fetchJSON<{ ok: boolean; deleted: number }>(+ appendProfileParam("/api/sessions/empty", profile),+ {+ method: "DELETE",+ },+ ),bulkDeleteSessions: (ids: string[], profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean; deleted: number }>('/api/sessions/bulk-delete', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ ids, profile: profile || undefined })+ fetchJSON<{ ok: boolean; deleted: number }>("/api/sessions/bulk-delete", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ids, profile: profile || undefined }),}),renameSession: (id: string, title: string, profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean; title: string }>(- `/api/sessions/${encodeURIComponent(id)}`,- {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ title, profile: profile || undefined }),- },- ),+ mutateSessionHttp<{ ok: boolean; title: string }>(id, "PATCH", { title }, profile),getSessionStats: (profile = getManagementProfile()) =>- fetchJSON<SessionStoreStats>(appendProfileParam('/api/sessions/stats', profile)),+ fetchJSON<SessionStoreStats>(appendProfileParam("/api/sessions/stats", profile)),exportSessionUrl: (id: string, profile = getManagementProfile()) =>appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/export`, profile),importSessions: (