Skip to content

The agent that grows with you

90.7 KB
Raw Blame
/**
 * @hermes/plugin-sdk — THE plugin language. The vscode-module model: plugin
 * authors import exactly one module and get everything — they never touch
 * `@/…` internals (lint-fenced) and never need codebase access.
 *
 * Two delivery modes, one surface:
 *  - bundled (`src/plugins/<name>/`): the import resolves here via alias;
 *  - runtime-fetched (plugin host, next phase): the loader injects this same
 *    object as `window.__HERMES_PLUGIN_SDK__` and maps the import to it, so a
 *    published plugin builds against the types with the SDK marked external.
 *
 * Capability tiers (WoW-style):
 *  - `host.state.*` — READONLY app state (nanostore atoms; `.get()` or
 *    subscribe; `useValue` in React).
 *  - `host.*` actions — curated, safe verbs (toast, haptic).
 *  - `host.request` — the gateway JSON-RPC door; the plugin's real power,
 *    and the future seam for per-plugin capability grants.
 *  - `ui.*` — the design language, so plugin UI looks native by default.
 */

import { computed, type ReadableAtom } from 'nanostores'
import type { ReactNode } from 'react'

import { capabilityScoped, getApiRequestConnection } from '@/api/client'
import { mutateSessionFenced } from '@/api/sessions'
import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'
import { openSession, type OpenSessionIntent } from '@/app/open-session'
import { syncWorkspaceRoute } from '@/app/routes'
import type { ClientSessionState } from '@/app/types'
import {
  $newSessionTabAction,
  $paneVisible,
  adoptContributedPanes,
  registerPaneCloser,
  removeTreePane,
  revealTreePane,
  undismissTreePanes
} from '@/components/pane-shell/tree/store'
import {
  $workspaceMode,
  $workspaceOwnerKey,
  setWorkspaceScope as publishWorkspaceScope,
  setWorkspaceOwnerLabel,
  type WorkspaceNewSessionTarget
} from '@/components/pane-shell/workspace-scope'
import { onGatewayEvent } from '@/contrib/events'
import { registry } from '@/contrib/registry'
import type { WorkspaceMode } from '@/contrib/types'
import { deleteProfile, getLogs, getStatus, hermesApi, type HermesGateway } from '@/hermes'
import { traceIdentityChange } from '@/lib/identity-trace'
import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'
import {
  $gateway,
  activeGatewayConnectionId,
  openGatewayForAgent,
  openGatewayForProfile,
  requestGatewayForAgent,
  retainGatewayForAgent,
  retainGatewayForRelay,
  retireLocalProfileGateways
} from '@/store/gateway'
import { notify, notifyError } from '@/store/notifications'
import {
  $activeGatewayProfile,
  $gatewaySwapTarget,
  $hydrationSyncProfile,
  $profiles,
  ensureGatewayAgent,
  ensureGatewayProfile,
  newSessionInAgent,
  newSessionInProfile,
  normalizeProfileKey,
  prewarmProfileBackend,
  refreshProfiles,
  selectProfile,
  setActiveProfile,
  setShowAllProfiles
} from '@/store/profile'
import {
  $activeSessionId,
  $connection,
  $currentCwd,
  $currentModel,
  $gatewayState,
  $messages,
  $selectedStoredSessionId,
  $sessions,
  getSessionOwnerHints,
  rememberedSessionProfile,
  requestSessionResume,
  sessionMatchesStoredId,
  setResumeExhaustedSessionId,
  setSessionOwnerHint
} from '@/store/session'
import { $focusedStoredSessionId } from '@/store/session-focus'
import {
  $focusedRuntimeId,
  $focusedSessionState,
  $sessionStates,
  $sessionTiles,
  dropTilesForProfile,
  focusWorkspaceOwnerSessionTile,
  sessionTileDelegate
} from '@/store/session-states'
import { runGatewayRestart } from '@/store/system-actions'
import type { PaginatedSessions, UsageStats } from '@/types/hermes'

import type { SessionMutationSnapshot } from '../../../shared/src/session-http-mutations'

import { pluginDecisions, profiles, skills, toolsets } from './bridge'
import { composerHost } from './composer'
import { i18nHost } from './i18n'
import { planPluginOpenSession } from './plugin-open-session-plan'
import { dropLeftoverProfilePrefs, warmProfile } from './profile-local'
import {
  type PluginProfileRequestOptions,
  type PluginProfileRoute,
  pluginRouteStillRegistered,
  requestPluginProfile
} from './profile-request'
import { sessionsHost } from './sessions'
import { desktopSettings } from './settings'
import { spellcheckHost } from './spellcheck'
import { $viewport, type ViewportRect } from './viewport'

/** Pane, status bar and titlebar slots; see `./areas` for the mount rules. */
export * from './areas'
/** The plugin authoring contract (`HermesPlugin`, `PluginContext`, `ctx.*` door types). */
export type * from './plugin-contract'
export type { PluginProfileRequestOptions, PluginProfileRoute } from './profile-request'

// -- state: readonly views over the app's live atoms -------------------------

const readonlyAtom = <T>(atomLike: ReadableAtom<T>): ReadableAtom<T> => atomLike

/**
 * Turn flag for the FOCUSED chat — same semantics as the statusbar's busy
 * pulse. While the focused surface is the primary workspace (or a draft with
 * no runtime slice yet) this reads the primary view, which itself falls back
 * to the global draft atoms. Once a session TILE holds focus, the tile's own
 * state slice is authoritative — a background session can never leak in.
 */
const focusedTurnFlag = (
  select: (state: ClientSessionState) => boolean,
  $primary: ReadableAtom<boolean>
): ReadableAtom<boolean> =>
  computed(
    [$focusedStoredSessionId, $selectedStoredSessionId, $focusedSessionState, $primary],
    (focused, selected, state, primary) =>
      !focused || focused === selected ? primary : Boolean(state && select(state))
  )

const $focusedBusy = focusedTurnFlag(state => state.busy, PRIMARY_SESSION_VIEW.$busy)

const $focusedAwaitingResponse = focusedTurnFlag(
  state => state.awaitingResponse,
  PRIMARY_SESSION_VIEW.$awaitingResponse
)

export interface PluginFocusedSessionOwner {
  connectionId: string
  profile: string
}

/**
 * Connection-qualified owner of the FOCUSED chat. The gateway-routing atom
 * (`$activeGatewayProfile`) answers "which backend is the live socket homed
 * on" — but tab/tile focus moves without swapping the socket, and a cold
 * start can restore a route into a session the booting gateway doesn't own.
 * Any per-bot readout must follow the chat the user is LOOKING AT, so this
 * resolves the focused stored session to a unique immutable owner hint or a
 * unique connection-qualified aggregated row. Ambiguous or unresolved focused
 * ids fail closed with null; only a draft/no focused id uses the active gateway
 * owner. `focusedSessionProfile` remains the profile-only compatibility ladder.
 */
const $focusedSessionOwner = computed(
  [$focusedStoredSessionId, $sessions, $activeGatewayProfile, $connection],
  (focused, sessions, activeProfile, connection): PluginFocusedSessionOwner | null => {
    const activeConnectionId = String(connection?.connectionId || (connection?.mode === 'local' ? 'local' : '')).trim()

    const fallback = {
      connectionId: activeConnectionId,
      profile: normalizeProfileKey(activeProfile)
    }

    if (!focused) {
      return fallback
    }

    const hints = getSessionOwnerHints(focused)

    if (hints.length === 1) {
      return {
        connectionId: hints[0].connectionId,
        profile: normalizeProfileKey(hints[0].profile)
      }
    }

    if (hints.length > 1) {
      return null
    }

    const owners = new Map<string, PluginFocusedSessionOwner>()

    for (const row of sessions.filter(session => sessionMatchesStoredId(session, focused))) {
      const connectionId = String(row.connection_id || '').trim()
      const profile = normalizeProfileKey(row.profile)

      if (connectionId) {
        owners.set(`${connectionId}::${profile}`, { connectionId, profile })
      }
    }

    return owners.size === 1 ? [...owners.values()][0] : null
  }
)

const $focusedSessionProfile = computed(
  [$focusedSessionOwner, $focusedStoredSessionId, $sessions, $activeGatewayProfile],
  (owner, focused, sessions, activeProfile) =>
    owner?.profile || rememberedSessionProfile(sessions, focused, activeProfile)
)

/** Runtime session id → mid-turn. Not gateway socket state. */
const $busyBySession = computed($sessionStates, states => {
  const map: Record<string, boolean> = {}

  for (const [id, state] of Object.entries(states)) {
    map[id] = Boolean(state.busy)
  }

  return map
})

/** Live usage of the FOCUSED session, projected out of the streamed session
 *  state — the same readout the core statusbar's context chip paints. */
const $focusedUsage = computed($focusedSessionState, state => state?.usage ?? null)

const $activeConnectionId = computed($connection, connection => {
  if (!connection) {
    return null
  }

  if (connection.connectionId) {
    return connection.connectionId
  }

  // mode:'local' used to report null, which made Bot Mode fall back to the
  // registry primary (often an SSH box) and treat Spark as the active source
  // while this window was actually local.
  return connection.mode === 'local' ? 'local' : null
})

/** Ordinary session opens fail fast when their gateway or socket is dead. */
export const DEFAULT_SESSION_HYDRATION_TIMEOUT_MS = 20_000
/** Cold Bot profiles get a larger per-attempt budget to start their backend
 *  and paint durable history. Bot Mode opts into one retry, so its effective
 *  ceiling is two bounded attempts rather than an unbounded wait. */
export const BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS = 60_000
/** Ceiling on the paint-first "Syncing…" badge. The profile gate it waits on is
 *  not guaranteed to ever fire (see beginHydrationBackgroundSync), so the badge
 *  needs a bound of its own or it outlives the wake it describes. */
export const HYDRATION_SYNC_BADGE_TIMEOUT_MS = 30_000
let openSessionGeneration = 0
/** Which generation's wake most recently set $gatewaySwapTarget. Clearing it
 *  keys off this, not off `generation === openSessionGeneration`, so a
 *  superseded wake still clears the overlay IT put up — the generation
 *  counter has already moved on by the time its `finally` runs, and a later
 *  wake that never sets the target (e.g. a paint-first open without
 *  awaitHydration) would otherwise leave it stuck forever (#115844). */
let gatewaySwapTargetOwnerGeneration: number | null = null

export interface PluginOpenSessionOptions {
  awaitHydration?: boolean
  expectHistory?: boolean
  /** Always request a sequenced session.resume after the open, even when the
   *  surface already looks healthy. The healthy check trusts any non-empty
   *  cached transcript, so an explicit bot-switch re-open can paint a STALE
   *  snapshot kept by the session-states cache and skip the refresh entirely
   *  (#93604 — Bot Chat shows old messages until app restart). Resume is
   *  cheap and idempotent (the route-resume effect consumes redundant
   *  requests as no-ops), so callers who know the user explicitly navigated
   *  here set this to guarantee freshness. Only honored with awaitHydration. */
  forceResume?: boolean
  hydrationTimeoutMs?: number
  intent?: OpenSessionIntent
  keepAllProfilesScope?: boolean
  /** Refresh an already-on-screen surface IN PLACE — no navigation, no
   *  tile-minting, no focus steal. The canonical-chats re-resume
   *  (session.reclaimed, roster activity) is a BACKGROUND refresh: the user
   *  may be reading the Kanban board, a settings page, or another chat, and
   *  a background event must never take the route or the foreground away
   *  (issue 121874). The session is re-resolved (registry consultation,
   *  backend dial, transcript pull) and the transcript of whichever surface
   *  already holds it — its tile, or main when the route points at it — is
   *  refreshed exactly like the SDK's own hydration probe
   *  (`resumeTile(refreshTranscript)` / armed `requestSessionResume`). A
   *  session that is NOT on screen resolves silently with nothing re-opened;
   *  the next explicit open handles it. */
  refreshInPlace?: boolean
  profile?: null | string
  route?: PluginProfileRoute
  workspaceMode?: WorkspaceMode
  workspaceOwnerKey?: string
  /** A cold profile backend can lose the hydration-timeout race once and still
   *  be fine on a second try. When set, a hydration timeout is retried
   *  internally before it reaches the caller or arms the core stranded-session
   *  overlay ($resumeExhaustedSessionId) — a caller-side retry can't do this
   *  itself because only this SDK layer sees $resumeExhaustedSessionId. */
  retryHydrationTimeoutOnce?: boolean
  tabTitle?: string
}

export interface PluginNewChatOptions {
  workspaceMode?: WorkspaceMode
  workspaceOwnerKey?: string
}

// Raise the "Syncing…" affordance for a paint-first wake (#89843) and tear it
// down as soon as the active-profile gate catches up. The listener clears ONLY
// its own profile's badge: a newer wake may have replaced the badge with a
// different profile, and the stale listener must not wipe the winner's.
//
// The gate is not guaranteed to fire. `.listen()` is change-only, and a wake
// is routed here precisely because $activeGatewayProfile did not match at
// resolve time. ensureGatewayProfile does publish the target on a
// shared-primary connection, but when the activation did NOT land it publishes
// the route the registry actually settled on instead — so on that path the
// atom may never become this profile and the listener never fires. Without a
// cap the badge would outlive the wake it describes and strand a permanent
// "Syncing <profile>…" spinner with no user-reachable dismissal; only a full
// app restart would clear it. Cap the wait so the badge can never outlive the
// work.
function beginHydrationBackgroundSync(profile: string): void {
  $hydrationSyncProfile.set(profile)

  let timer: number | undefined

  const clearOwnBadge = (): void => {
    if ($hydrationSyncProfile.get() === profile) {
      $hydrationSyncProfile.set(null)
    }
  }

  const unlisten = $activeGatewayProfile.listen(next => {
    if (normalizeProfileKey(next) === profile) {
      clearOwnBadge()

      if (timer !== undefined) {
        window.clearTimeout(timer)
      }

      unlisten()
    }
  })

  timer = window.setTimeout(() => {
    clearOwnBadge()
    unlisten()
  }, HYDRATION_SYNC_BADGE_TIMEOUT_MS)
}

function waitForFocusedSessionHydration({
  expectHistory,
  generation,
  isCurrent,
  profile,
  requireActiveProfile,
  storedSessionId,
  timeoutMs
}: {
  expectHistory: boolean
  generation: number
  isCurrent?: () => boolean
  profile: string
  requireActiveProfile: boolean
  storedSessionId: string
  timeoutMs: number
}): Promise<void> {
  return new Promise((resolve, reject) => {
    let settled = false
    const unbinds: Array<() => void> = []
    let timer: number | undefined

    const finish = (error?: Error) => {
      if (settled) {
        return
      }

      settled = true

      if (timer !== undefined) {
        window.clearTimeout(timer)
      }

      for (const unbind of unbinds) {
        unbind()
      }

      if (error) {
        reject(error)
      } else {
        resolve()
      }
    }

    const check = () => {
      if (generation !== openSessionGeneration || (isCurrent && !isCurrent())) {
        finish(new Error('Session open was superseded by a newer selection.'))

        return
      }

      const profileMatches = !requireActiveProfile || normalizeProfileKey($activeGatewayProfile.get()) === profile
      const mainMatches = $selectedStoredSessionId.get() === storedSessionId
      const storedTile = $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)
      const tileMatches = $focusedStoredSessionId.get() === storedSessionId || Boolean(storedTile)
      const focusedTileMatches = $focusedStoredSessionId.get() === storedSessionId
      const tileRuntimeId = focusedTileMatches ? $focusedRuntimeId.get() : (storedTile?.runtimeId ?? null)

      const tileState = focusedTileMatches
        ? $focusedSessionState.get()
        : tileRuntimeId
          ? $sessionStates.get()[tileRuntimeId]
          : undefined

      const runtimeReady = mainMatches ? Boolean($activeSessionId.get()) : tileMatches ? Boolean(tileRuntimeId) : false

      const historyPainted = mainMatches
        ? Boolean($messages.get().length)
        : tileMatches
          ? Boolean(tileState?.messages.length)
          : false

      // Paint-first hydration: for a history-bearing chat, the wake is DONE
      // the moment the persisted transcript is painted on the right session —
      // the REST prefetch delivers it seconds after the profile backend's
      // HTTP comes up, while the full runtime resume (agent build, MCP
      // discovery, skill load) keeps warming in the background and binds the
      // composer when it lands. Gating on runtimeReady serialized the wake
      // behind that whole boot: on a cold multi-profile start the 20s budget
      // regularly lost the race on slower machines and surfaced as "errors
      // waking up bots" even though the transcript had been available almost
      // immediately. Only an expected-EMPTY chat still waits for the runtime
      // — with no transcript to paint, a bound runtime is the only proof the
      // surface is real rather than a stuck loader.
      const hydrated = expectHistory ? historyPainted : runtimeReady

      if ((mainMatches || tileMatches) && hydrated) {
        if (profileMatches) {
          finish()

          return
        }

        // Paint-first completion on an unsatisfiable profile gate (#89843).
        // On a shared-remote connection every profile is legitimately served
        // through the primary socket, so $activeGatewayProfile can NEVER
        // equal the bot's profile — the old gate held a fully painted
        // transcript hostage for the whole 20s budget and then stranded the
        // pane. When the stored history is already painted on exactly this
        // session, that content IS the proof the surface is real: resolve
        // now, raise the subtle "Syncing…" affordance, and let the profile
        // gate catch up in the background.
        //
        // Fail closed everywhere the content is NOT its own proof: a
        // superseded generation already rejected above (conflicting
        // concurrent hydration never resolves paint-first), and an
        // expected-EMPTY chat keeps waiting for the full gate — with no
        // transcript to paint, a bound runtime on an unmatched profile is
        // not evidence of a real surface.
        if (expectHistory && historyPainted) {
          beginHydrationBackgroundSync(profile)
          finish()
        }
      }
    }

    unbinds.push($activeGatewayProfile.listen(check))
    unbinds.push($activeConnectionId.listen(check))
    unbinds.push($selectedStoredSessionId.listen(check))
    unbinds.push($activeSessionId.listen(check))
    unbinds.push($messages.listen(check))
    unbinds.push($focusedStoredSessionId.listen(check))
    unbinds.push($focusedRuntimeId.listen(check))
    unbinds.push($focusedSessionState.listen(check))
    unbinds.push($sessionTiles.listen(check))
    unbinds.push($sessionStates.listen(check))
    unbinds.push($workspaceMode.listen(check))
    unbinds.push($workspaceOwnerKey.listen(check))

    timer = window.setTimeout(() => {
      finish(new Error(`Timed out loading ${profile}'s session history.`))
    }, timeoutMs)

    check()
  })
}

// Wait for a profile switch, but never longer than the wake budget.
//
// ensureGatewayProfile awaits the store's dial, and HermesGateway.connect() has
// no dial timeout of its own: a backend that accepts the socket and then never
// completes the handshake leaves this promise pending for the life of the
// window. That is not merely a slow open. waitForFocusedSessionHydration arms
// the only timer on this path, and it is armed AFTER this await returns - so an
// unbounded activation means the wake never settles at all, and the pane wedges
// with no error, no Retry and no timeout (#89556: `ws accepted` in the gateway
// log with no matching `ws closed`).
//
// The activation gets its OWN budget rather than sharing the hydration one. A
// cold profile backend can legitimately spend most of the hydration budget
// painting a large transcript - that race is already tight enough to lose
// (#89617) - so charging activation to the same clock would turn a wedge into a
// regression. The trade is that a wake that is slow in BOTH phases can now take
// up to twice the budget before it surfaces; that is a maintainer call and is
// called out in the PR rather than buried here.
// The caller supplies the dial itself, because WHICH backend to open is a
// routing decision (a workspace switch moves chrome; a plain bot navigation
// only opens the gateway) while the deadline enforced here is the same either
// way.
async function awaitProfileActivation(
  dial: () => Promise<void>,
  targetProfile: string,
  timeoutMs: number
): Promise<void> {
  const activation = dial()
  let timer: number | undefined

  try {
    await Promise.race([
      activation,
      new Promise<never>((_resolve, reject) => {
        // Same message shape as the hydration timeout on purpose: openSession's
        // catch keys the core stranded-session surface off this prefix, and a
        // wedged dial wants exactly that surface. The phase is distinguished in
        // the [bot-wake] support log, not in the user-facing string.
        timer = window.setTimeout(
          () => reject(new Error(`Timed out loading ${targetProfile}'s session history.`)),
          timeoutMs
        )
      })
    ])
  } finally {
    if (timer !== undefined) {
      window.clearTimeout(timer)
    }
  }

  // No extra catch on the abandoned dial: an in-flight activation has no
  // cancellation handle and keeps running after the budget expires, but
  // Promise.race subscribes to every input, so a rejection that lands after the
  // race has settled is already handled and cannot escape as an unhandled
  // rejection. An explicit `activation.catch()` here was dead code - verified
  // by mutation: removing it changed no test outcome.
}

export const host = {
  state: {
    /** Runtime id of the active chat session (null on a fresh draft). */
    activeSessionId: readonlyAtom<null | string>($activeSessionId),
    /** True from send until the first assistant payload on the focused chat. */
    awaitingResponse: readonlyAtom<boolean>($focusedAwaitingResponse),
    /**
     * True while the focused chat is working after a send. Covers the wait
     * for the first token and the stream that follows. Follows tile focus —
     * same signal the statusbar's busy pulse reads. A draft with no runtime
     * id uses the global flag.
     */
    busy: readonlyAtom<boolean>($focusedBusy),
    /** Runtime session id → mid-turn. Not socket state; see `gateway`. */
    busyBySession: readonlyAtom<Record<string, boolean>>($busyBySession),
    /** Registry source that owns the active gateway, when source-scoped. */
    connectionId: readonlyAtom<null | string>($activeConnectionId),
    /** Active workspace cwd ('' when detached). */
    cwd: readonlyAtom<string>($currentCwd),
    /** Runtime id of the FOCUSED chat session — the interacted tile, else the
     *  primary. Prefer this over `activeSessionId` for any readout that
     *  should follow the user between tiles (context, tokens, cost). */
    focusedSessionId: readonlyAtom<null | string>($focusedRuntimeId),
    /** Connection-qualified owner of the focused chat. Prefer this for any
     *  readout or mutation where separate sources can share a profile name. */
    focusedSessionOwner: readonlyAtom<PluginFocusedSessionOwner | null>($focusedSessionOwner),
    /** Owner profile of the focused chat (session-row stamp, falling back to
     *  the gateway profile for drafts/uncached ids). Compatibility projection
     *  of `focusedSessionOwner`; use the complete owner for source routing. */
    focusedSessionProfile: readonlyAtom<string>($focusedSessionProfile),
    /** Stored (durable) id of the focused session — for navigation and
     *  session-list matching, where runtime ids don't survive reloads. */
    focusedStoredSessionId: readonlyAtom<null | string>($focusedStoredSessionId),
    /** Live usage snapshot of the focused session (`context_used` /
     *  `context_max` / `context_percent`, token counts, `cost_usd`) —
     *  streamed by the backend, no RPC needed. Null while unresolved.
     *  The UsageStats-optional fields (context_*, cost_usd) arrive as the
     *  backend reports them, so read them with a fallback. */
    focusedUsage: readonlyAtom<null | UsageStats>($focusedUsage),
    /** Gateway socket state: 'idle' | 'connecting' | 'open' | …. Not turn-busy. */
    gateway: readonlyAtom<string>($gatewayState),
    /** Current main model slug. */
    model: readonlyAtom<string>($currentModel),
    /** Profile the live gateway is routed to. */
    profile: readonlyAtom<string>($activeGatewayProfile),
    /** Window geometry ({ width, height, narrow }). */
    viewport: readonlyAtom<ViewportRect>($viewport)
  },

  /** Read, update, and observe the allowlisted Desktop appearance preferences. */
  settings: desktopSettings,

  /** Toast into the app's notification stack. */
  notify,
  notifyError,

  // NOTE: every host door is async-safe — wrapped so a sync throw from an
  // internal helper (e.g. no desktop bridge in a plain browser) becomes a
  // rejection a plugin's .catch() sees, never an error-boundary crash.

  /** Tail an app log file (`agent` / `errors` / `gateway` / `gui` / …). */
  logs: async (...args: Parameters<typeof getLogs>) => getLogs(...args),

  /** Complete client-local MCP sign-in for a pinned bot profile, optionally
   *  installing its catalog entry first. Uses the same OAuth flow as Settings. */
  completeMcpOAuth: async (options: Parameters<typeof completeMcpDesktopOAuth>[0] & { catalogPreset?: string }) => {
    const profile = capabilityScoped(options.profile)

    if (options.catalogPreset) {
      const added = await requestGatewayForAgent<{ ok?: boolean; error?: string }>(
        profile.connectionId ?? null,
        profile.profile || 'default',
        'mcp.servers.add',
        { name: options.serverName, preset: options.catalogPreset }
      )

      if (!added.ok) {
        throw new Error(added.error || 'Could not add server')
      }
    }

    return completeMcpDesktopOAuth({ ...options, profile })
  },

  /** Navigate the app router (hash routes, e.g. '/command-center?section=system'). */
  navigate: (path: string) => {
    const to = path.startsWith('#') ? path.slice(1) : path

    window.location.hash = `#${to}`
    // The router follows the hash and fronts the workspace pane on a route
    // CHANGE (wiring's `syncWorkspaceRoute` effect). Re-issuing the current
    // route — palette/statusbar/hotkey while already on the page with a tile
    // focused — changes nothing, so no event fires and the page stays behind
    // the tile. Reveal imperatively, the same way `navigateToWorkspacePage`
    // does for the sidebar and keybinds.
    syncWorkspaceRoute(to)
  },

  warmProfile,
  dropLeftoverProfilePrefs,

  /** Delete a profile THROUGH the desktop's teardown-routed REST path — the
   *  same door core surfaces use (DeleteProfileDialog). Electron intercepts
   *  the DELETE, tears down that profile's pool/primary backend first, and
   *  routes the follow-up request away from it, so a live (or hover-warmed)
   *  backend can't hold the profile dir open or respawn mid-delete and
   *  resurrect the directory (issue #52279). Plugins must prefer this over
   *  `cli.exec ['profile','delete',…]`, which bypasses that interception
   *  entirely. When the deleted profile was the live gateway's, the app is
   *  re-homed to the default profile — same semantics as the core dialog.
   *  Rejects with the backend's error when the delete fails. */
  deleteProfile: async (profile: string | PluginProfileRoute): Promise<void> => {
    const route =
      typeof profile === 'string'
        ? null
        : {
            ...profile,
            connectionId: String(profile.connectionId || '').trim(),
            profile: String(profile.profile || '').trim(),
            targetProfile: String(profile.targetProfile || '').trim()
          }

    const name = typeof profile === 'string' ? profile.trim() : route?.profile || ''

    if (route && (!route.connectionId || !route.profile || !route.targetProfile)) {
      throw new Error('deleteProfile: route requires connectionId, profile, and targetProfile')
    }

    const targetProfile = route?.targetProfile || name
    // A name-only call is ambient, not local: Bot Mode's active SSH roster
    // rows deliberately use the ambient gateway door and therefore carry no
    // explicit owner route. Preserve the active registry connection so the
    // profile teardown and DELETE both land on the VPS instead of retiring the
    // unrelated local pool and leaving the warmed remote backend to recreate
    // the deleted profile.
    const ambientConnectionId = route ? null : String(activeGatewayConnectionId() || '').trim()

    const ambientRemoteConnectionId =
      ambientConnectionId && ambientConnectionId !== 'local' ? ambientConnectionId : null

    if (!name) {
      throw new Error('deleteProfile: profile name required')
    }

    if (normalizeProfileKey(targetProfile) === 'default') {
      throw new Error('The default profile cannot be deleted.')
    }

    // Capture before the delete; re-home after so our write is the last one
    // (mirrors DeleteProfileDialog — a refreshActiveProfile racing the dying
    // backend can't clobber the pill back to the deleted profile).
    const wasActive = route
      ? route.connectionId === ($activeConnectionId.get() || '') &&
        normalizeProfileKey(route.profile) === normalizeProfileKey($activeGatewayProfile.get())
      : normalizeProfileKey(name) === normalizeProfileKey($activeGatewayProfile.get())

    // A hover-warmed Bot Mode row owns a retained renderer socket. Retire it
    // before Electron stops the profile backend so the socket closure cannot
    // schedule a reconnect that resurrects the deleted profile.
    if (route?.mode === 'local' || (!route && !ambientRemoteConnectionId)) {
      retireLocalProfileGateways(targetProfile)
    }

    await deleteProfile(
      targetProfile,
      route
        ? { connectionId: route.connectionId, profile: route.profile }
        : ambientRemoteConnectionId
          ? { connectionId: ambientRemoteConnectionId, profile: name }
          : undefined
    )

    // The profile is gone. Drop its persisted tiles now — a leftover tile
    // restores on relaunch and re-creates the deleted profile (hermes-agent#94235).
    dropTilesForProfile(
      route ? route.profile : name,
      route
        ? { connectionId: route.connectionId, profile: route.profile, targetProfile: route.targetProfile }
        : undefined
    )

    // The profile rail paints from the shared $profiles cache; without a
    // refresh the deleted profile's badge survives and clicking it starts a
    // doomed spawn-retry loop against Electron's deletion guard (#88769).
    // Best-effort: the delete itself already succeeded.
    await refreshProfiles().catch(() => undefined)

    if (wasActive) {
      selectProfile('default')
      setActiveProfile('default')
    }
  },

  // ── Multi-source agents (the Bot Mode door) ───────────────────────────────

  /** Registry connection id serving the gateway `host.request` currently hits
   *  — null for the local/legacy primary path. Roster UIs need this to tell
   *  "a row from the backend I'm already showing" apart from "a row from
   *  another source": two connections can both expose a 'default' profile,
   *  and matching by profile name alone duplicates every agent when the
   *  active gateway is a registered remote. Re-read per use — it changes on
   *  profile/agent swaps. */
  activeConnectionId: (): null | string => activeGatewayConnectionId(),

  /** The registered connection list (labels, kinds, primary) — token bytes
   *  never included. Rejects on Desktop builds without the registry. */
  connections: async () => {
    const bridge = window.hermesDesktop?.connections

    if (!bridge) {
      throw new Error('This Desktop build has no connection registry. Update Hermes Desktop.')
    }

    const registryPayload = await bridge.list()
    const rows = Array.isArray(registryPayload?.connections) ? registryPayload.connections : []

    return rows.map(connection => ({ ...connection, primary: connection.id === registryPayload.primary }))
  },

  /** The union agent roster across every registered connection: one row per
   *  (source, profile) with the pre-computed @name-device handle for
   *  duplicates. Sources that are unreachable (or ssh connect-on-demand)
   *  appear in `sources` with an error instead of failing the call. */
  agents: async () => {
    const roster = window.hermesDesktop?.getAgentRoster

    if (!roster) {
      throw new Error('This Desktop build cannot enumerate multi-source agents. Update Hermes Desktop.')
    }

    return roster()
  },

  /** Pre-dial an agent's socket on ITS source — the (connection, profile)
   *  analogue of warmProfile. Fire-and-forget, same semantics, same guarded
   *  resolver (prewarmProfileBackend): a pointer sweep across a
   *  multi-source roster must not spawn past the pool cap either.
   *  `undefined` is accepted alongside `null` because a roster row's
   *  `connectionId` is optional; both mean "no explicit source". */
  warmAgent: (connectionId: null | string | undefined, profile: string): void => {
    prewarmProfileBackend((profile ?? '').trim() || 'default', connectionId ?? null)
  },

  /** Activate an agent's gateway (dialing it if needed) so subsequent
   *  host.request calls hit that agent's backend. Goes through the store's
   *  serialized activation path so $connection / $activeGatewayProfile follow
   *  and rapid switches can't land out of order. The local source falls
   *  through to the profile path — single-source plugins keep working
   *  against older behavior unchanged. */
  ensureAgent: async (connectionId: null | string | undefined, profile: string): Promise<void> =>
    ensureGatewayAgent(connectionId ?? null, (profile ?? '').trim() || 'default'),

  /** Session-list mutations (pin, reorder, colour) — see `./sessions`. */
  sessions: sessionsHost,

  /** Typed capabilities bridge — see `./bridge.ts`. `pluginDecisions` is
   *  read-only: plugin toggling stays in the app's Plugins tab. */
  skills,
  toolsets,
  profiles,
  pluginDecisions,

  /** Open a stored session the way core surfaces do. A plugin/Bot Mode open
   *  is navigation, not a workspace or chrome API-home switch —
   *  keepAllProfilesScope defaults true so `$activeGatewayProfile` /
   *  Sessions REST stay on the previous (usually launch) backend while the
   *  bot backend is dialed in the background. The bot forever-chat is hidden
   *  and would otherwise look like every session disappeared. Pass false to
   *  also scope chrome onto that profile and collapse the sidebar. */
  openSession: async (storedSessionId: string, options: PluginOpenSessionOptions = {}): Promise<void> => {
    const generation = ++openSessionGeneration

    // A new wake owns the syncing affordance — a lingering badge from an
    // earlier paint-first wake must not survive into this one.
    $hydrationSyncProfile.set(null)
    const explicitRoute = options.route ? { ...options.route } : null
    const profile = (explicitRoute?.profile ?? options.profile ?? '').trim()
    const targetProfile = normalizeProfileKey(profile || $activeGatewayProfile.get())

    // A local bot open passes only `profile` (no cross-connection route), but
    // its RPCs STILL have to reach that profile's own local gateway while chrome
    // stays on the launch profile. Synthesize a local owner route from the
    // profile so the persisted tile carries it — the session-request router
    // reads the tile route to dispatch on the owning backend, and the canonical
    // Bot Chat is hidden (never in $sessions), so this is the only owner record
    // it can consult. Without it, submit falls back to the active profile and
    // 4001s / hangs against a backend that never owned the session.
    //
    // This is ROUTING metadata only (tile ownerRoute + owner hint); the dial
    // path below still keys off the explicit cross-connection route, so a plain
    // local open dials exactly as before (openGatewayForProfile), never the
    // registry-secondary path.
    const liveConnection = $connection.get()
    const liveRemote = liveConnection?.mode === 'remote'
    const liveConnectionId = String(liveConnection?.connectionId ?? '').trim()
    const ambientConnectionId = (liveRemote && liveConnectionId) || activeGatewayConnectionId()
    const ambientMode = liveRemote ? ('remote' as const) : ('local' as const)

    const ownerRoute =
      explicitRoute ??
      (options.workspaceMode === 'bots' && profile && ambientConnectionId
        ? { connectionId: ambientConnectionId, mode: ambientMode, profile: targetProfile }
        : null)

    const expectHistory = options.expectHistory ?? false

    // A refreshInPlace wake is not an entry into the workspace — it refreshes
    // a chat the user already opened. Never re-publish the bots scope (that
    // re-homes the pane-strip memory) and never flip the all-profiles view;
    // both belong to the explicit open that already happened.
    if (options.workspaceMode === 'bots' && !options.refreshInPlace) {
      publishWorkspaceScope(
        'bots',
        options.workspaceOwnerKey ?? null,
        ownerRoute ? { kind: 'route', route: ownerRoute } : null
      )
    }

    const openingStillCurrent = () =>
      generation === openSessionGeneration &&
      (options.workspaceMode !== 'bots' ||
        options.refreshInPlace ||
        ($workspaceMode.get() === 'bots' && $workspaceOwnerKey.get() === (options.workspaceOwnerKey ?? null)))

    const plan = planPluginOpenSession({
      activeProfile: $activeGatewayProfile.get(),
      keepAllProfilesScope: options.keepAllProfilesScope,
      profile
    })

    // Wake-path phase timings. Logged ONLY on a hydration timeout (bridged
    // into desktop.log via the renderer-console tap), so a support bundle
    // pinpoints WHERE the budget went — profile activation vs hydration —
    // instead of leaving us to infer it from process spawn timestamps.
    const wakeStartedAt = Date.now()
    let profileActiveAt = wakeStartedAt
    const hydrationTimeoutMs = Math.max(1, options.hydrationTimeoutMs ?? DEFAULT_SESSION_HYDRATION_TIMEOUT_MS)
    // Which half of the wake a timeout landed in. Only meaningful on the
    // failure path, where the two phases have different remedies: a stuck dial
    // is a gateway problem, a slow transcript is a backend-warmup one.
    let wakePhase: 'activation' | 'hydration' = 'activation'

    if (ownerRoute) {
      setSessionOwnerHint(storedSessionId, ownerRoute)
    } else if (profile) {
      // Plugin-owned opens without a cross-connection route still carry an
      // explicit owning profile. Record it: hidden sessions have no sidebar
      // row, so this hint is the only durable owner record the session-RPC
      // router can consult. Do not stamp mode local when the live connection
      // is remote — that hint persists and the next open resolves the profile
      // against this machine (#90477).
      if (ambientConnectionId) {
        setSessionOwnerHint(storedSessionId, {
          connectionId: ambientConnectionId,
          mode: ambientMode,
          profile: targetProfile
        })
      }
    }

    // Bounded to 2 attempts (never more): a cold profile backend can lose the
    // hydration-timeout race once and still be fine moments later, but this is
    // a caller-opt-in retry of the SAME wait, not a backoff loop.
    const maxAttempts = options.awaitHydration && options.retryHydrationTimeoutOnce ? 2 : 1

    try {
      // WHICH backend to dial is the plan's call; HOW LONG to wait is the wake
      // budget's. A workspace switch moves $activeGatewayProfile / chrome REST;
      // a plain navigation only opens the bot's gateway so session.resume can
      // hydrate, leaving chrome on the launch backend.
      // Dial keys off the EXPLICIT cross-connection route only: a synthesized
      // local ownerRoute is routing metadata for the tile/hint, and a local
      // profile must dial through openGatewayForProfile (its established path),
      // not the registry-secondary path openGatewayForAgent takes for a 'local'
      // connection id. Behavior for a plain local open is unchanged.
      const dial = explicitRoute
        ? () =>
            openGatewayForAgent(explicitRoute.connectionId, explicitRoute.profile, {
              spawnPriority: 'foreground'
            })
        : plan.switchWorkspace
          ? () => ensureGatewayProfile(plan.switchWorkspace as string)
          : plan.dialWithoutSwitching
            ? () => openGatewayForProfile(plan.dialWithoutSwitching as string, { spawnPriority: 'foreground' })
            : null

      if (dial) {
        // Bounded only on the hydration contract, which is where a budget and a
        // Retry surface both already exist. A plain open never asked for a
        // deadline and has nowhere to render one, so it keeps today's
        // behaviour rather than gaining a rejection its callers cannot handle.
        await (options.awaitHydration ? awaitProfileActivation(dial, targetProfile, hydrationTimeoutMs) : dial())
        profileActiveAt = Date.now()
      }

      if (!openingStillCurrent()) {
        throw new Error('Session open was superseded by a newer selection.')
      }

      // Only a cross-connection (explicit route) open forces the all-profiles
      // view; a local bot open keeps the planner's decision, unchanged from
      // before the synthesized-route addition. A refreshInPlace wake never
      // touches the view at all.
      if (options.refreshInPlace) {
        // no view change — the refresh inherits whatever is showing
      } else if (explicitRoute) {
        setShowAllProfiles(true)
      } else if (plan.showAllProfiles !== null) {
        setShowAllProfiles(plan.showAllProfiles)
      }

      wakePhase = 'hydration'

      if (!openingStillCurrent()) {
        throw new Error('Session open was superseded by a newer selection.')
      }

      if (options.awaitHydration) {
        // Keep the target-specific overlay visible through transcript hydration,
        // not merely through the gateway/profile activation that precedes it.
        $gatewaySwapTarget.set(targetProfile)
        gatewaySwapTargetOwnerGeneration = generation
      }

      // Only the HYDRATION half retries. Activation already failed its own
      // bounded wait above, and a wedged dial does not get better by dialling
      // again inside the same wake — that is the Retry surface's job.
      for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        try {
          const navigate = (to: string, opts?: { replace?: boolean }) => {
            const target = to.startsWith('#') ? to : `#${to}`

            if (opts?.replace) {
              window.location.replace(target)
            } else {
              window.location.hash = target
            }
          }

          const intent = options.intent ?? 'in-place'

          // Background refresh (refreshInPlace): this wake was triggered by
          // something that HAPPENED in the background (a reclaim, roster
          // activity), not by the user navigating. Never touch the route or
          // the tab strip — the user may be reading the Kanban board, a
          // settings page, or another chat (issue 121874: /kanban was
          // replaced by the Bot Chat route). Refresh only whichever surface
          // already holds the session: its tile via resumeTile
          // (refreshTranscript), or main via the armed explicit-resume
          // request — the same lever markRuntimeGone pulls for background
          // reclaims, consumed only while the route already points at the
          // session, so it can never navigate. A session that is not on
          // screen resolves without re-opening anything; the next explicit
          // open owns that.
          if (options.refreshInPlace) {
            const existingTile = $sessionTiles.get().some(tile => tile.storedSessionId === storedSessionId)
            const tileDelegate = existingTile ? sessionTileDelegate() : null
            // Main is refreshed only when it is actually showing this
            // session — the same surface discriminator the hydration probe
            // uses. An off-screen chat re-opens nothing: the request would
            // sit unconsumed and the wake would silently no-op.
            const mainShowing = $selectedStoredSessionId.get() === storedSessionId

            if (tileDelegate) {
              await tileDelegate.resumeTile(storedSessionId, { refreshTranscript: true })
            } else if (mainShowing) {
              requestSessionResume(storedSessionId, ownerRoute || undefined)
            }

            break
          }

          if (options.workspaceMode === 'bots') {
            openSession(storedSessionId, navigate, intent, {
              ownerRoute: ownerRoute ?? undefined,
              workspaceMode: 'bots',
              workspaceOwnerKey: options.workspaceOwnerKey,
              ...(options.tabTitle ? { workspaceTabTitle: options.tabTitle } : {})
            })
          } else {
            openSession(storedSessionId, navigate, intent)
          }

          // Judge the main surface AFTER the open: on a cold start the persisted
          // route can already point at this session while selection has not
          // settled, so a pre-open "already selected" precondition skips the
          // resume exactly when it is needed (#89206 — blank Bot Chat with the
          // roster preview intact). The surface is healthy only when this stored
          // session is selected, a runtime is bound, and the expected transcript
          // is present; anything less gets an explicit sequenced resume request.
          // The route-resume effect only honors the request while the route
          // points at this session, and consumes it alongside any resume the
          // navigation itself triggers, so a redundant request is a no-op.
          const surfaceHealthy =
            $selectedStoredSessionId.get() === storedSessionId &&
            Boolean($activeSessionId.get()) &&
            (!expectHistory || $messages.get().length > 0)

          // surfaceHealthy trusts ANY non-empty cached transcript, so it
          // cannot distinguish a fresh transcript from a stale snapshot the
          // session-states cache kept across a bot switch (#93604). Callers
          // that represent an explicit user navigation pass forceResume to
          // skip the heuristic entirely; the resume is idempotent either way.
          //
          // Bot Chat opens as a tab/tile. requestSessionResume is consumed
          // only when the MAIN route is that session, so a roster reopen of
          // an already-mounted tile would paint the idle snapshot and never
          // pull messages that arrived while the panel WS was down (#96183).
          // Refresh the tile transcript in place instead.
          if (options.awaitHydration && (options.forceResume || !surfaceHealthy)) {
            const existingTile = $sessionTiles.get().some(tile => tile.storedSessionId === storedSessionId)
            const tileDelegate = existingTile ? sessionTileDelegate() : null

            if (tileDelegate) {
              try {
                await tileDelegate.resumeTile(storedSessionId, { refreshTranscript: true })
              } catch {
                requestSessionResume(storedSessionId, ownerRoute || undefined)
              }
            } else {
              requestSessionResume(storedSessionId, ownerRoute || undefined)
            }
          }

          if (options.awaitHydration) {
            await waitForFocusedSessionHydration({
              expectHistory,
              generation,
              isCurrent: openingStillCurrent,
              profile: targetProfile,
              // A background dial never moves $activeGatewayProfile, so gating
              // hydration on it would wait for something that is not coming.
              requireActiveProfile: ownerRoute ? false : plan.requireActiveProfileForHydration,
              storedSessionId,
              timeoutMs: hydrationTimeoutMs
            })
          }

          break
        } catch (error) {
          const retryable =
            options.awaitHydration &&
            generation === openSessionGeneration &&
            attempt < maxAttempts &&
            error instanceof Error &&
            error.message.startsWith('Timed out loading ')

          if (!retryable) {
            throw error
          }

          // The registry check applies only to a real cross-connection route
          // (explicit): a synthesized local route is never in getProfileRoutes,
          // so checking it would spuriously abort a local bot's hydration retry.
          if (explicitRoute && !(await pluginRouteStillRegistered(explicitRoute))) {
            throw new Error(`The ${targetProfile} gateway is no longer available.`)
          }

          // Logged per attempt so a support bundle shows the retry happened at
          // all; the terminal failure is reported once by the catch below.
          console.warn('[bot-wake] hydration timed out, retrying', {
            attempt,
            hydrationWaitMs: Date.now() - profileActiveAt,
            profile: targetProfile,
            storedSessionId
          })
        }
      }
    } catch (error) {
      if (
        options.awaitHydration &&
        openingStillCurrent() &&
        error instanceof Error &&
        error.message.startsWith('Timed out loading ')
      ) {
        const timedOutAt = Date.now()

        console.warn('[bot-wake] hydration timed out', {
          attempts: wakePhase === 'hydration' ? maxAttempts : 1,
          hydrationWaitMs: wakePhase === 'hydration' ? timedOutAt - profileActiveAt : 0,
          phase: wakePhase,
          profile: targetProfile,
          profileActivationMs: (wakePhase === 'activation' ? timedOutAt : profileActiveAt) - wakeStartedAt,
          runtimeBound: Boolean($activeSessionId.get()),
          selectionSettled: $selectedStoredSessionId.get() === storedSessionId,
          storedSessionId,
          transcriptPainted: $messages.get().length > 0
        })
        // Reuse the core stranded-session surface: it renders the explicit
        // error and Retry button, and the normal resume path clears the latch.
        setResumeExhaustedSessionId(storedSessionId)
      }

      throw error
    } finally {
      // Clear the overlay THIS wake set, even when a later open superseded
      // it: `generation === openSessionGeneration` is false by then, but
      // nothing else is coming to clear it. Skip only when a newer wake has
      // since taken ownership of the target.
      if (gatewaySwapTargetOwnerGeneration === generation) {
        $gatewaySwapTarget.set(null)
        gatewaySwapTargetOwnerGeneration = null
      }
    }
  },

  /** Open (or re-front) a plugin-rendered MAIN-AREA workspace tile — the same
   *  surface a session tile or a preview occupies: a closeable tab docked
   *  beside the main workspace, taking over the chat area when active. This is
   *  the generic main-view door for plugins whose surface is not a stored
   *  session (`openSession` stays the door for those). Re-opening the same
   *  `id` refreshes `render`/`title` in place and fronts the existing tab
   *  instead of stacking a duplicate. Returns a disposer that closes the tab;
   *  the tab's own Close (⌘W / strip ✕) routes through the same teardown and
   *  fires `onClose`. Feature-detect on older desktops
   *  (`typeof host.openWorkspace === 'function'`) and keep an in-panel
   *  fallback. */
  openWorkspace: (
    id: string,
    options: {
      dock?: { before?: null | string; pane: string; pos: 'bottom' | 'center' | 'left' | 'right' | 'top' }
      headerVeto?: boolean
      minWidth?: string
      onClose?: () => void
      render: () => ReactNode
      title?: string
      uncloseable?: boolean
    }
  ): (() => void) => {
    const key = (id ?? '').trim()

    if (!key || typeof options?.render !== 'function') {
      throw new Error('openWorkspace: an id and a render function are required')
    }

    const paneId = `plugin-workspace:${key}`

    const dispose = registry.register({
      area: 'panes',
      data: {
        // The session-tile shape: a full workspace surface docked beside main,
        // closeable so it keeps its tab when it lands in a zone of its own.
        dock: options.dock ?? { pane: 'workspace', pos: 'center' },
        headerVeto: options.headerVeto,
        minWidth: options.minWidth ?? '22rem',
        placement: 'main',
        uncloseable: options.uncloseable
      },
      id: paneId,
      render: options.render,
      title: options.title ?? key
    })

    const close = () => {
      registerPaneCloser(paneId)
      dispose()
      removeTreePane(paneId)
      options.onClose?.()
    }

    // Route the tab's Close through OUR teardown: without a closer, closing a
    // core-sourced contributed pane only dismisses it and the registration
    // would leak past the plugin surface that owns it.
    registerPaneCloser(paneId, close)
    revealTreePane(paneId)

    return close
  },

  /** Name a workspace owner on its tabs (a bot's display name). A canonical
   *  chat's STORED title is an identity the backend resolves by name; this is
   *  the caption shown for it. Feature-detect on older desktops. */
  setWorkspaceOwnerLabel,

  /** Switch the visible main-pane workspace without unregistering retained panes. */
  setWorkspaceScope: (
    mode: WorkspaceMode,
    ownerKey: null | string = null,
    newSessionTarget: WorkspaceNewSessionTarget | null = null
  ): boolean => publishWorkspaceScope(mode, ownerKey, newSessionTarget),

  /** 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 | PluginProfileRoute, options: PluginNewChatOptions = {}): void => {
    if (options.workspaceMode === 'bots') {
      if (!profile || typeof profile === 'string' || !options.workspaceOwnerKey) {
        notify({ kind: 'error', message: 'Select a Bot before starting another chat.' })

        return
      }

      publishWorkspaceScope('bots', options.workspaceOwnerKey, { kind: 'route', route: { ...profile } })

      const openTab = $newSessionTabAction.get()

      if (!openTab) {
        notify({ kind: 'error', message: 'Update Hermes Desktop to open another Bot chat.' })

        return
      }

      openTab()

      return
    }

    if (profile && typeof profile !== 'string') {
      newSessionInAgent({ ...profile })
    } else {
      newSessionInProfile((profile ?? '').trim() || $activeGatewayProfile.get())
    }

    window.location.hash = '#/'
  },

  /** Front the tab a Bot Mode owner already has open — the tile that owner's
   *  zone last had active, else its most recent — and return that stored id;
   *  `null` when the owner has nothing open. A roster click asks this before
   *  resolving the canonical chat, so the tabs the user left (and the ones
   *  they closed) are respected. Presentation only: no gateway activation,
   *  no session create. Feature-detect on older desktops.
   *
   *  `isStaleTile` (hermes-agent#90102): the caller's reconciliation probe
   *  against backend truth. The tile bucket is a Local Storage cache — a
   *  persisted bot tile can name a session the backend has since superseded,
   *  and fronting it pinned the roster click to a stale finished session
   *  forever. Tiles the probe rejects are discarded (never fronted), so the
   *  caller falls through to its authoritative open path. */
  focusOpenWorkspaceSession: (
    workspaceOwnerKey: string,
    isStaleTile?: (tile: { storedSessionId: string; workspaceTabTitle?: string }) => boolean,
    onlyStoredIds?: readonly string[]
  ): null | string => focusWorkspaceOwnerSessionTile(workspaceOwnerKey, isStaleTile, onlyStoredIds),

  /** Reactive on-screen visibility of a contributed pane: true while it is in
   *  the layout tree, not dismissed/hidden, its zone un-minimized, AND holding
   *  its zone's active tab slot (a lone pane in its own zone counts). The
   *  contribution-scoped pane id is `<pluginId>:<paneId>`. Memoized per id —
   *  safe to call in render. Feature-detect on older desktops
   *  (`typeof host.paneVisibility === 'function'`). */
  paneVisibility: (paneId: string): ReadableAtom<boolean> => $paneVisible(paneId),

  /** Forget a persisted Close for a contributed pane so adoption puts it back
   *  where its dock hint says — WITHOUT fronting it or un-collapsing its zone
   *  (that is `revealPane`, for an explicit user action). For a pane a plugin
   *  registers conditionally (Bot Mode's Scheduled jobs pane exists only while
   *  Bot Mode is on screen), its re-registration is the only "show" the user
   *  ever performs, so a remembered Close would otherwise strand the pane until
   *  a full layout reset (#102224). Feature-detect on older desktops. */
  undismissPane: (paneId: string): void => {
    const id = (paneId ?? '').trim()

    if (!id) {
      return
    }

    undismissTreePanes([id])
    adoptContributedPanes()
  },

  /** Reveal a contributed pane and its zone from an explicit user action. */
  revealPane: (paneId: string): void => {
    const id = (paneId ?? '').trim()

    if (!id) {
      return
    }

    revealTreePane(id)
  },

  /** 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. A subscription
   *  made while your plugin's `register()` runs is retired with the plugin on
   *  unload/reload/disable; one made later (a timer, a socket callback) is
   *  yours to wire to `ctx.onDispose` — or use `ctx.onEvent`, which is
   *  tracked wherever it is called. */
  onEvent: onGatewayEvent,

  /** Restart the backend gateway (progress surfaces in the core statusbar). */
  restartGateway: async () => runGatewayRestart(),

  /** One-shot system status snapshot (platforms, versions, …). */
  status: async () => getStatus(),

  /** Credential-free routes across every current registry source. Identity is
   *  the (connectionId, profile) pair; endpoint/auth details stay in Electron. */
  profileRoutes: async () => {
    const desktop = window.hermesDesktop
    const getProfileRoutes = desktop?.getProfileRoutes

    if (!getProfileRoutes) {
      throw new Error('Hermes Desktop connection routing unavailable')
    }

    let profiles = $profiles.get()

    try {
      profiles = await refreshProfiles()
    } catch {
      // Route inventory is a read: a transient backend failure falls back to
      // the last cache. Electron always adds the primary Desktop profile.
    }

    return getProfileRoutes(profiles.map(profile => profile.name))
  },

  /** Gateway JSON-RPC through a credential-free route descriptor without
   *  foregrounding it. Passing a bare profile is the v1/local compatibility
   *  overload; registry callers must pass the descriptor so duplicate names
   *  remain unambiguous.
   *
   *  `timeoutMs` opts one call out of the pool's generic deadline (#93911: a
   *  method whose backend contract is minutes long, such as `bot_relay.deliver`,
   *  otherwise dies at 30s and reports an unclassified failure). Leave it unset
   *  to keep the default.
   *
   *  `options.spawnPriority: 'foreground'` marks the call as an explicit user
   *  action (a roster click opening a Bot Chat) so the dial that may cold-spawn
   *  the route's backend takes the pool's reserved interactive slot instead of
   *  queuing behind background roster hydration (#105104). `timeoutMs` stays
   *  the fourth positional argument so existing callers keep their shape; pass
   *  `undefined` there to set options alone. Default is 'background'. */
  requestProfile: async <T>(
    route: PluginProfileRoute | string,
    method: string,
    params: Record<string, unknown> = {},
    timeoutMs?: number,
    options?: PluginProfileRequestOptions
  ): Promise<T> => requestPluginProfile<T>(route, method, params, timeoutMs, options),

  /** Pin a route's gateway socket open across repeated `requestProfile`
   *  calls (#93594: the bot-relay drain loop was dialing and tearing down a
   *  fresh WebSocket per registered connection per tick). Returns a once-only
   *  release. Local routes are exempt (no-op release): the host gateway's
   *  lifetime does not depend on renderer pins. Feature-detect on older desktops
   *  (`typeof host.retainProfileSocket === 'function'`). */
  retainProfileSocket: (route: PluginProfileRoute | string): (() => void) => {
    if (typeof route === 'string' || !route) {
      // Bare-profile compatibility overload: local/legacy routing — exempt.
      return () => undefined
    }

    return retainGatewayForRelay(route.connectionId, route.profile)
  },

  /** Hold a route's pooled socket open across a multi-RPC, session-scoped
   *  sequence (#93602). Each requestProfile call is its own request lease, so
   *  a non-retained secondary socket closes at refcount 0 between calls — and
   *  the gateway reaps any runtime session that socket minted, failing the
   *  next RPC with 4001. Acquire before the first session-scoped RPC, release
   *  (idempotent) in a `finally`. An explicit user action can mark the retain
   *  foreground so a retired route takes the pool's reserved interactive
   *  slot. Feature-detect: older hosts lack this. */
  retainProfile: async (
    route: PluginProfileRoute | string,
    options?: PluginProfileRequestOptions
  ): Promise<() => void> => {
    if (typeof route !== 'string') {
      if (!route.connectionId.trim() || !route.profile.trim()) {
        throw new Error('Profile route must include connectionId and profile')
      }

      return retainGatewayForAgent(route.connectionId, route.profile, options)
    }

    return retainGatewayForAgent(null, route.trim() || 'default', options)
  },

  /** Read persisted sessions from a profile's owning source without dialing
   *  that profile's gateway. The source primary opens state.db directly. */
  listPersistedSessions: async (
    route: PluginProfileRoute | null,
    options: { profile: string; limit?: number }
  ): Promise<PaginatedSessions> => {
    if (route && (!route.connectionId.trim() || !route.profile.trim() || !route.targetProfile.trim())) {
      throw new Error('Profile route must include connectionId, profile, and targetProfile')
    }

    const profile = options.profile.trim()

    if (!profile) {
      throw new Error('Persisted session reads require a profile')
    }

    const limit = Math.min(500, Math.max(0, options.limit ?? 200))

    const query = new URLSearchParams({
      limit: String(limit),
      offset: '0',
      min_messages: '0',
      archived: 'exclude',
      order: 'created',
      profile
    })

    return hermesApi<PaginatedSessions>({
      ...(route ? { connectionId: route.connectionId } : {}),
      path: `/api/profiles/sessions?${query.toString()}`,
      timeoutMs: 60_000
    })
  },

  /** Mutate the durable hidden flag through the source primary. Keeping the
   *  owner profile in the body (not request.profile) prevents Electron from
   *  starting a profile backend merely to reconcile persisted visibility. */
  setPersistedSessionHidden: async (
    route: PluginProfileRoute | null,
    options: { sessionId: string; profile: string; hidden: boolean }
  ): Promise<{ ok: boolean; hidden: boolean }> => {
    if (route && (!route.connectionId.trim() || !route.profile.trim() || !route.targetProfile.trim())) {
      throw new Error('Profile route must include connectionId, profile, and targetProfile')
    }

    const profile = options.profile.trim()

    if (!profile || !options.sessionId.trim()) {
      throw new Error('Persisted session updates require a profile and session id')
    }

    // Null keeps the window's v1 route (a remote primary stays remote).
    const scope = { connectionId: route?.connectionId || getApiRequestConnection() }
    const path = `/api/sessions/${encodeURIComponent(options.sessionId)}`
    const payload = { hidden: options.hidden, profile }

    return mutateSessionFenced(
      JSON.stringify([scope, options.sessionId, payload]),
      () =>
        hermesApi<SessionMutationSnapshot>({
          ...scope,
          path: `${path}/mutation-snapshot?profile=${encodeURIComponent(profile)}`
        }),
      identity =>
        hermesApi<{ ok: boolean; hidden: boolean }>({
          ...scope,
          path,
          method: 'PATCH',
          body: { ...payload, ...identity }
        })
    )
  },

  /** Gateway JSON-RPC — sessions, config, skills, cron, kanban, everything
   *  the app itself uses. Lazy: resolves the LIVE socket per call. `timeoutMs`
   *  overrides the socket's 30 s default for RPCs that legitimately run longer
   *  (session.compress); unset keeps the default. */
  request: async <T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number): Promise<T> => {
    const gateway = $gateway.get()

    if (!gateway) {
      throw new Error('Hermes gateway unavailable')
    }

    return timeoutMs === undefined ? gateway.request<T>(method, params) : gateway.request<T>(method, params, timeoutMs)
  },

  /** The LIVE gateway instance for the active profile (null before the first
   *  socket opens). Most plugins want `host.request`; this exists for SDK
   *  components that take a `HermesGateway` prop directly (e.g. `ConnectorsTab`),
   *  which need the instance, not just a JSON-RPC door. Re-read per use — the
   *  active instance changes on a profile swap. */
  getGateway: (): HermesGateway | null => $gateway.get(),

  /** Change-only desktop.log line for multi-connection identity diagnostics
   *  (`[category win=…] tag detail`). Call as `host.traceIdentityChange?.(…)`. */
  traceIdentityChange,

  composer: composerHost,

  /** Chromium's custom spell-check dictionary, one validated word per call. */
  spellcheck: spellcheckHost,

  /** Language packs: `host.i18n.registerAppLocale(id, { endonym, rtl?,
   *  translations })` adds a whole UI language at runtime (see `sdk/i18n.ts`);
   *  `host.i18n.languageOptions()` lists what the switcher shows. */
  i18n: i18nHost
}

// -- react bridge -------------------------------------------------------------

export type { DesktopSettingKey, DesktopSettingValues } from './settings'

// -- ui: the design language --------------------------------------------------

export type { ViewportRect } from './viewport'
/** THE whole Capabilities surface (Skills / Tools / MCP tabs, installed
 *  lists, full-skill detail pane, embedded hub picker with one-click
 *  installs). For plugin dialogs pass `embedded` (tab state stays local —
 *  never touches the page router) and `fixedProfile` to pin every tab to one
 *  bot's backend; the internal profile selector hides itself. Add
 *  `fixedConnection` (registry connection id) to pin a bot living on another
 *  registered gateway — probe `CapabilitiesView.supportsFixedConnection` first;
 *  builds without it would route the pin to the ACTIVE gateway. Bot Mode's
 *  Advanced section is the reference consumer. */
export { CapabilitiesView } from '@/app/capabilities'
/** THE Connectors tab core Capabilities renders — managed apps, the user's
 *  own MCP servers, plugin servers and the catalog, with per-server enable,
 *  sign-in and live probes. Renders anywhere under the app router (a plugin
 *  dialog); pass a live `gateway` (see `host.getGateway()`) and the `profile`
 *  to scope it to one bot. */
export { ConnectorsTab } from '@/app/capabilities/connectors/connectors-tab'
// Every contribution surface, plugin-reachable: register keybinds, palette
// commands, routes, themes, panes, composer extensions, and bar items with
// the same area ids + payload types core uses.
export {
  COMPOSER_AREAS,
  type ComposerAtCompletionItem,
  type ComposerAtCompletionSource,
  type ComposerAttachmentProvider,
  type ComposerContextMenuAction,
  type ComposerContextMenuContext,
  type ComposerContextMenuItem,
  type ComposerContextMenuProvider,
  type ComposerMiddleware,
  type ComposerModelPillContext,
  type ComposerModelPillProvider
} from '@/app/chat/composer/contrib'
/** THE session status dot — the one primitive the sidebar row, the pane tabs
 *  and the session switcher render, so a session's status can never disagree
 *  between surfaces. Pass the STORED session id and it resolves the rest
 *  itself: the live state (needs-input / working / stalled / background /
 *  unread / draft / idle) and the project color. Never hand-roll a status
 *  circle beside it — a plugin's own dot inverts core's color vocabulary the
 *  moment either side moves. */
export { SessionStatusDot, type SessionStatusDotProps } from '@/app/chat/session-status-dot'
/** The sidebar row's leading cell — the fixed box a dot, icon or handle sits in.
 *  Reserve it and your label starts on the same left edge as every session row
 *  above you; spell the classes yourself and the row drifts. The session row is
 *  canonical; `row-geometry.ts` explains what each measurement belongs to. */
export { SidebarRowLead } from '@/app/chat/sidebar/chrome'
/** One glyph per gateway kind — device, cloud, terminal, network. The statusbar
 *  switcher, the fleet profile rail and any plugin rail listing gateways share
 *  it, so a connection looks the same wherever it is named. */
export { ConnectionGlyph } from '@/app/chat/sidebar/connection-glyph'
export { SIDEBAR_ROW_LEAD, SIDEBAR_TRUNCATED_LEADING } from '@/app/chat/sidebar/row-geometry'
export { PALETTE_AREA, type PaletteContribution } from '@/app/command-palette/contrib'
/** Page-owned header control (the kanban board switcher): projected into the
 *  workspace page header when the page renders in the workspace pane, and
 *  rendered inline, in place, anywhere else (a split route tile). Prefer it
 *  over a raw `<Contribute area={WORKSPACE_PAGE_HEADER_AREA}>`, which nothing
 *  paints outside the workspace pane. */
export { WorkspacePageHeaderControl } from '@/app/contrib/workspace-page-header'
/** THE overdue test for a cron job's `next_run_at`: non-null once the stored slot
 *  sits past the scheduler grace and the job is expected to fire. Every surface
 *  that prints a next run switches its label on this (`t.cron.next` →
 *  `t.cron.overdueSince`) so a dead scheduler never reads as "Next: 7 hr ago". */
export { nextRunOverdueMs } from '@/app/cron/job-state'
/** Master-detail components for pane content; the overlay-bound Panel root is deliberately private. */
export {
  PanelAction,
  PanelAddButton,
  PanelBlock,
  PanelBody,
  PanelDetail,
  PanelEmpty,
  PanelHeader,
  PanelList,
  PanelListRow,
  type PanelMenuItem,
  PanelMeta,
  type PanelMetaRow,
  PanelPill,
  type PanelPillTone,
  PanelRowMenu,
  PanelSectionLabel
} from '@/app/overlays/panel'

export {
  type ProfileGroupHeaderContribution,
  type ProfileGroupRoute,
  type RouteContribution,
  ROUTES_AREA,
  SIDEBAR_NAV_AREA,
  SIDEBAR_PROFILE_GROUP_HEADER_AREA,
  type SidebarNavContribution,
  WORKSPACE_PAGE_HEADER_AREA
} from '@/app/routes'
/** Appearance settings' plugin seam: register a render contribution at
 *  `APPEARANCE_AREAS.extra` to add controls at the end of the Appearance page.
 *  `ColorSwatches` is the app's own swatch grid (profile rail / project dialog
 *  look) — use it for colour picking instead of driving app widgets through
 *  React internals; pair it with `host.sessions.setColor` for session colours. */
export { APPEARANCE_AREAS } from '@/app/settings/appearance-contrib'
/** THE settings rows: `ListRow` is label + description with the control beside
 *  it (wide) or under it (narrow); `ToggleRow` is the one on/off row — a Switch,
 *  never an Off/On pill pair. Use them for preference rows in plugin panes and
 *  dialogs so they line up with core Settings. */
export { ListRow, ToggleRow } from '@/app/settings/primitives'
/** THE full per-toolset config panel core Settings renders — provider picker,
 *  env vars / API keys, model catalog picker, and post-setup runners. Route-
 *  decoupled (the "manage keys" deep link is a no-op outside the router); pass
 *  `toolset`, optional `onConfiguredChange`, and an optional `profile`. */
export { ToolsetConfigPanel } from '@/app/settings/toolset-config-panel'
/** THE model catalog menu — the same searchable, provider-grouped, family-
 *  collapsing picker the chat composer uses, including the per-row
 *  thinking/effort/fast submenu. Drive it with a `ModelMenuController`: the
 *  menu renders and navigates, your controller decides what a selection MEANS
 *  (write to a session, hold a per-task override, …). Never fork it — a copy
 *  drifts from the composer the first time either side changes. */
export {
  ModelCatalogMenu,
  type ModelChoice,
  ModelMenuCloseContext,
  type ModelMenuController
} from '@/app/shell/model-catalog-menu'
/** Per-model marks inside that same menu: register a `MODEL_MENU_ROW_AREA`
 *  data contribution whose `decorate({ provider, model, label })` returns
 *  `{ icon?, badge? }` (or `null`). Core paints the leading icon slot and a
 *  trailing badge chip; per slot the first usable answer wins, and a throwing
 *  decorator is skipped. Never patch the menu's rows yourself. */
export {
  MODEL_MENU_ROW_AREA,
  type ModelMenuRowContext,
  type ModelMenuRowContribution,
  type ModelMenuRowDecoration
} from '@/app/shell/model-menu-row-decorations'
export type { StatusbarItem } from '@/app/shell/statusbar-controls'
export type { TitlebarTool } from '@/app/shell/titlebar-controls'
/** Canonical raw message renderer: applies Desktop message transforms (including
 * `MEDIA:` delivery directives) and the same rich Markdown/media components as
 * core chat. Prefer this over raw Streamdown for transcript-style messages. */
export { MessageTextContent } from '@/components/assistant-ui/markdown-text'
/** The oversized Collapse lettering an empty chat is titled with — core writes
 *  "HERMES AGENT" with it, a `chat.empty` contribution writes its own name. */
export { Wordmark } from '@/components/chat/wordmark'
/** Pane placement roles. `'floating'` is the one NON-tiling value: the pane is
 *  excluded from the layout tree and rendered as a fixed, draggable card above
 *  it — it takes no width from any zone, has no tab, and can't be docked.
 *  Pair it with `anchor` (spawn corner, default `'top-right'`) plus
 *  `width`/`height`. */
export type { FloatingAnchor } from '@/components/pane-shell/tree/renderer/floating-rect'
export { StatusDot, type StatusTone } from '@/components/status-dot'
export { Badge } from '@/components/ui/badge'
export { Button } from '@/components/ui/button'
export { Checkbox } from '@/components/ui/checkbox'
export { Codicon } from '@/components/ui/codicon'
/** THE color picker — swatch grid plus a clear row that means "back to the
 *  deterministic color". Feed it `PROFILE_SWATCHES` so a hand-picked color
 *  shares the generated palette's saturation and lightness; a bespoke grid of
 *  literal hex drifts off-theme the moment the palette moves. */
export { ColorSwatches } from '@/components/ui/color-swatches'
export { ConfirmDialog } from '@/components/ui/confirm-dialog'
export {
  ContextMenu,
  ContextMenuCheckboxItem,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  // Submenus: Bot Mode files a bot into a user section from its row menu, and
  // a flat list of every folder would swamp the items already there.
  ContextMenuSub,
  ContextMenuSubContent,
  ContextMenuSubTrigger,
  ContextMenuTrigger
} from '@/components/ui/context-menu'
export { CopyButton } from '@/components/ui/copy-button'
export { DecodeText } from '@/components/ui/decode-text'
export {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
/** The caret every collapsible section in core uses — points right when closed
 *  and rotates down when open, so the motion matches the rest of the app. Swap
 *  a hand-written `chevron-down`/`chevron-right` ternary for this. */
export { DisclosureCaret } from '@/components/ui/disclosure-caret'
export {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
export { EmptyState } from '@/components/ui/empty-state'
export { ErrorState } from '@/components/ui/error-state'
export { FadeScroll } from '@/components/ui/fade-scroll'
export { GlyphSpinner } from '@/components/ui/glyph-spinner'
export { Input } from '@/components/ui/input'
export { Kbd, KbdGroup } from '@/components/ui/kbd'
/** The app's canonical loader (animated curves; `lemniscate-bloom` for long
 *  page loads) — the same one every core page uses. */
export { Loader, type LoaderType } from '@/components/ui/loader'
export { LogView } from '@/components/ui/log-view'
export { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
/** Full-row / region click target. Imposes NO styling — the caller keeps its own
 *  layout classes — it just bakes in `type="button"` and a stable `data-slot`.
 *  Use it for rows and regions; `Button` is for ordinary compact actions. */
export { RowButton } from '@/components/ui/row-button'
/** The sanctioned embed primitive for external web content: a sandboxed
 *  iframe (opaque origin, `allow-scripts` by default) — never a raw
 *  `<webview>`, which would land on the app's own preview partition. */
export { SandboxedFrame, type SandboxedFrameProps } from '@/components/ui/sandboxed-frame'
export { ScrollArea } from '@/components/ui/scroll-area'
export { SearchField } from '@/components/ui/search-field'
export { SegmentedControl } from '@/components/ui/segmented-control'
export { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
export { Separator } from '@/components/ui/separator'
export { Skeleton } from '@/components/ui/skeleton'
export { Switch } from '@/components/ui/switch'
export { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
export { Textarea } from '@/components/ui/textarea'
export { Tip, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
export type { GatewayEventListener } from '@/contrib/events'
/** Mount-scoped contribution: while the rendering component is mounted, its
 *  children render in the target area's slot; unmount disposes it. Use for
 *  page-owned chrome (a page's titlebar control leaves with the page) —
 *  `ctx.register` stays the door for permanent contributions. Namespace the
 *  id with your plugin slug (`kanban:board-switcher`). */
export { Contribute, type ContributeProps } from '@/contrib/react/contribute'

// -- contracts ----------------------------------------------------------------

/** Settings ▸ Plugins entries (`ctx.registerSettingsPage`); `pluginSettingsHref` deep-links one. */
export { pluginSettingsHref, SETTINGS_PLUGINS_AREA } from '@/contrib/settings-pages'
export type { Contribution } from '@/contrib/types'
/** The live gateway instance type — for typing the `gateway` prop `ConnectorsTab`
 *  takes; obtain the instance from `host.getGateway()`. */
export type { HermesGateway } from '@/hermes'
/** Grab-to-pan for overflow containers (boards, timelines, wide tables) —
 *  the shared scrub primitive; don't hand-roll drag-to-scroll. */
export { type GrabScroll, useGrabScroll } from '@/hooks/use-grab-scroll'
/** Localized copy. `useI18n` reuses the app's strings; `usePluginI18n(id)` +
 *  `ctx.i18n.register` let a plugin ship its OWN locale bundles, scoped like
 *  `ctx.storage` and resolved against the app's active locale — no core edit.
 *  `translateNow` is the one-shot form for the places a hook can't reach —
 *  notably a `ctx.register` pane `title`, which is read at registration time
 *  and is why plugin pane titles otherwise strand as hardcoded English. It
 *  samples the locale at call time, so React should still use the hooks. A
 *  pane whose label must track the locale pairs that `title` with
 *  `data.tabTitle: () => <LocalizedTabTitle select={t => ...} />`. */
export {
  type AppLocaleRegistration,
  type BundledLocale,
  type LanguageOption,
  type Locale,
  LocalizedTabTitle,
  type PluginI18n,
  type PluginLocaleBundles,
  type PluginMessages,
  type PluginMessageValue,
  type PluginTranslate,
  translateNow,
  useI18n,
  usePluginI18n
} from '@/i18n'
/** THE way to run a decorative rAF animation (avatars, shimmer, sprites):
 *  fps budget + hidden/minimized/unfocused pause + idle dormancy + teardown.
 *  Plugins must route animation clocks through this instead of raw rAF loops
 *  so a disabled plugin or an empty roster costs zero frames. */
export { type BudgetedLoop, type BudgetedLoopOptions, createBudgetedLoop } from '@/lib/budgeted-loop'
/** The blank transcript as a contribution area: claim the sessions you own and
 *  render what stands in the gap. Core's own splash keeps a fresh draft. */
export { CHAT_EMPTY_AREA, type ChatEmptyContribution, type ChatEmptyProps } from '@/lib/chat-empty'
/** THE copy-to-clipboard path (CopyButton's): Electron's IPC first, the Clipboard API, and a
 *  selection copy where an insecure origin has no Clipboard API. Never call
 *  `navigator.clipboard.writeText` directly. */
export { writeClipboardText } from '@/lib/clipboard'
/** THE confirm flow for guarded model switches — when a gateway model-switch
 *  RPC answers `confirm_required` (data-policy / expensive-model guard),
 *  route it through this shared applier instead of forking a per-surface
 *  dialog: it asks through the app's ConfirmDialog (Switch anyway / Keep
 *  current model) and only a confirmed answer resends with
 *  `confirm_expensive_model: true` (#95293, #112458). */
export {
  type GuardedModelSwitchResult,
  surfaceModelSwitchConfirm,
  type SurfaceModelSwitchConfirmOptions
} from '@/lib/guarded-model-switch'
export { triggerHaptic as haptic } from '@/lib/haptics'
export type { HermesOpenTarget } from '@/lib/hermes-open-target'
/** The app's lucide icon set (RefreshCw, LayoutDashboard, Activity, …). */
export * as icons from '@/lib/icons'
/** IME-aware Enter: true only for a real submit Enter, never a CJK composition
 *  commit (`isComposing` or the legacy keyCode 229). Use it on every plugin
 *  text field whose bare Enter performs an action. */
export { isSubmitEnter } from '@/lib/ime'
export { type KeybindContribution, KEYBINDS_AREA, PLUGIN_APP_ACTIONS } from '@/lib/keybinds/actions'
export { formatModifierToken } from '@/lib/keybinds/combo'
/** A `Map` with a ceiling, for the module-level caches a plugin keeps across
 *  a renderer that stays open for days. Only for values that can be
 *  regenerated — eviction costs a recompute or a refetch, never correctness. */
export { LruCache } from '@/lib/lru-cache'
/** Capture a gateway file download alongside a REST read (see the SDK guide). */
export { captureGatewayFileDownload } from '@/lib/media'
/** True when a saved provider id names this `model.options` row: its slug,
 *  display name, or a custom-provider alias (`custom:<key>` vs the bare key). */
export { catalogProviderMatches } from '@/lib/model-options'
/** The app's deterministic identity color for a name (profiles, assignees,
 *  authors), its translucent tag fill, and the curated picker swatches — so
 *  plugin-rendered identities read the same hue as everywhere else. The
 *  swatches share the deterministic palette's saturation/lightness, so a
 *  hand-picked color still sits with the generated ones; reach for them
 *  instead of literal hex, which can't follow the theme. */
export { PROFILE_SWATCHES, profileColor, profileColorSoft } from '@/lib/profile-color'
/** The shared client itself, for invalidation OUTSIDE React (e.g. a
 *  `ctx.socket` frame invalidating a query). Inside components keep using
 *  `useQueryClient`. */
export { queryClient } from '@/lib/query-client'

/** Compact labels for the reasoning levels exported from @hermes/shared, so a
 *  plugin surfacing a thinking depth uses the same spelling as the app. */
export { reasoningEffortLabel } from '@/lib/reasoning-effort'

/** The app's own gateway-readiness evaluation (setup.status +
 *  setup.runtime_check, reconciled) — pass `host.request`. Don't hand-roll
 *  readiness from raw RPC shapes. */
export { evaluateRuntimeReadiness, type RuntimeReadinessResult } from '@/lib/runtime-readiness'
/** Row-decoration slots: register a `data` contribution with a `render` for
 *  `SESSION_ROW_AREAS.leading` / `.trailing` to decorate sidebar session rows
 *  (the props carry the row's stored session id). */
export { SESSION_ROW_AREAS, type SessionRowSlotContribution, type SessionRowSlotProps } from '@/lib/session-row-slots'
/** A sibling WebSocket beside the route's `/api/ws` (voice PCM, Bot Screen RFB):
 *  same origin, same auth resolution as chat. */
export { resolveSiblingWsUrl, type SiblingWsRoute } from '@/lib/sibling-ws-url'
/** Canonical time formatting — every surface pulls from here so timestamps read
 *  the same app-wide. For a row's AGE, bucket with `coarseElapsed` and render
 *  the compact suffixes (`t.sidebar.row.ageMin` → "52m"), which is what the
 *  session rows beside you do; `formatAgo` is the same buckets with an " ago"
 *  suffix. `relativeTime` is the bidirectional Intl form ("in 14 hr") — use it
 *  for a scheduled next-run, not for an age. */
export { type AgoLabels, coarseElapsed, fmtDateTime, fmtDayTime, formatAgo, relativeTime } from '@/lib/time'
/** The transcript as a contribution area: register a named `::directive{...}`
 *  and the model can render your component inline in assistant messages. */
export {
  TRANSCRIPT_DIRECTIVE_AREA,
  type TranscriptDirectiveContribution,
  type TranscriptDirectiveProps
} from '@/lib/transcript-directives'
export { cn } from '@/lib/utils'
export { gatewayActivationEpoch, useGatewayActivationEpoch } from '@/store/gateway'
/** THE unread store behind `SessionStatusDot`'s emerald dot. A plugin that
 *  learns out-of-band that a session produced something the user hasn't seen
 *  (a roster poll's activity watermark, say) writes HERE rather than keeping
 *  its own unread map — core's dot only paints what this store claims, and a
 *  parallel map means a second badge that drifts. Works for sessions core
 *  cannot see: a hidden session is never in the session list, so the backend
 *  watermark can never claim it, but the transient marker resolves to the id
 *  you pass. Key every call by the SAME stored id you hand the dot.
 *  `markSessionUnreadFinished` lights it, `ackStoredSessionId` clears it when
 *  the user opens the session, `forgetSessionUnread` drops it when the session
 *  is gone. Pass the owning profile — a hidden session has no row to read it
 *  from, and the persisted half is bucketed per profile. */
export { ackStoredSessionId, forgetSessionUnread, markSessionUnreadFinished } from '@/store/session-unread'
/** `sidebarNav.prefs`: hide / re-order the sidebar's nav rows by CONTRIBUTING a
 *  preference (union of hides, `capabilities` never hidden; the first order
 *  in registry area order — lowest `order`, then registration — wins). A
 *  contribution, not a `host.sidebar` verb, so it is attributed and dropped
 *  on disable. */
export { SIDEBAR_NAV_PREFS_AREA, type SidebarNavPrefsContribution } from '@/store/sidebar-nav'
/** Live accent override — set a hex and the ACTIVE theme repaints with its
 *  accent family re-seeded from it (see `retintTheme`); `null` restores the
 *  authored palette. Deliberately not persisted: it is an authoring knob, not
 *  a setting, so a plugin that sets it must clear it on dispose. */
export { $accentOverride, setAccentOverride } from '@/themes/accent-override'
/** OKLCH colour maths, for anything deriving a palette rather than hardcoding
 *  one: perceptual conversion, the sRGB gamut boundary, and hue-stable
 *  blending. `readableOn` is the SDK's public name for the desktop's ink pick
 *  (`#161616` or `#ffffff`, whichever measures better on the background). */
export {
  hexToOklch,
  hueDelta,
  maxChroma,
  mixOklab,
  normalizeHex,
  type Oklch,
  oklchToHex,
  oklchToSrgb255,
  readableInk as readableOn
} from '@/themes/color'
/** The painted theme, its name, and the appearance it resolved to — plus
 *  `setTheme` / `setMode` to change it from a component. */
export { useTheme } from '@/themes/context'
/** Switch the theme from outside React (a gateway event, a connection coming
 *  up, any callback with no component around it). Returns false and leaves the
 *  appearance alone when the name doesn't resolve, so it doubles as the "is
 *  this theme installed?" check. */
export { requestTheme } from '@/themes/request'
export { retintTheme, themeHue } from '@/themes/retint'
export type { DesktopTheme, DesktopThemeColors } from '@/themes/types'
export { THEMES_AREA } from '@/themes/user-themes'
export type { StatusResponse } from '@/types/hermes'
/** Public SDK name for the shared gateway wire event; kept stable for plugins. */
export type { GatewayEvent as RpcEvent } from '@hermes/shared'
/** Bot Screen wire shapes, generated from `tui_gateway/contracts/display.py`. */
export type { DisplayLease, DisplayObserveResult, DisplayStatus, DisplayThumbnailResult } from '@hermes/shared'
/** `session.list` / `profiles.list` session rows, generated from `tui_gateway/contracts`. */
export type { ProfileSessionPreview, SessionListRow } from '@hermes/shared'
/** THE compact-number formatter — every user-facing count/token figure goes
 *  through here (1230 → "1.2k", 1_500_000 → "1.5M"). Don't hand-roll `/1000`. */
export { compactNumber } from '@hermes/shared'
/** Client deadline for `approval.respond`: matches the backend's
 *  `approvals.timeout` (300s) so a plugin answering an approval never rejects
 *  its own RPC while the backend still applies the decision (#60654). */
export { APPROVAL_RESPOND_TIMEOUT_MS } from '@hermes/shared'
/** THE id minter: a v4 UUID on every origin. `crypto.randomUUID` exists only in secure contexts,
 *  so a Webapp opened over plain HTTP from another machine has none. */
export { randomUuid } from '@hermes/shared'
/** Hermes' reasoning levels, so a plugin surfacing a thinking depth uses the
 *  same scale as the rest of the app (labels: `reasoningEffortLabel`). */
export {
  DEFAULT_REASONING_EFFORT,
  REASONING_EFFORT_VALUES,
  REASONING_EFFORTS,
  type ReasoningEffort
} from '@hermes/shared'
/** WCAG contrast, from the sRGB primitives shared with the TUI (`null` for
 *  an unparseable colour, never a fake 0). */
export { contrastRatio } from '@hermes/shared/color'
/** Subscribe a component to a `host.state` atom. */
export { useStore as useValue } from '@nanostores/react'
/** The app's data-fetching layer. Plugins share the ONE QueryClient mounted at
 *  the app root, so their queries cache, dedupe, poll (`refetchInterval`), and
 *  invalidate exactly like core screens — no hand-rolled atoms or polls. */
export { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
/** Deterministic soft-body avatars from any string (name → face). String
 *  renderer for rasterization; React component for live rendering. */
export { blobatar as blobatarSvg } from 'blobatar/blob'
export { Blobatar } from 'blobatar/react'
/** Plugin-local reactive state (share between a trigger and its panel, poll
 *  loops, cross-component signals) — the same primitive `host.state` uses. */
export { atom, computed } from 'nanostores'
/** Markdown renderer (same pipeline core chat surfaces use) so plugins render
 *  message text as a preview instead of raw Markdown source. */
export { Streamdown } from 'streamdown'