Skip to content

The agent that grows with you

26.6 KB
Raw Blame
import { JsonRpcGatewayError, type PluginsManageParams } from '@hermes/shared'
import { atom } from 'nanostores'

import { notifyError } from '@/store/notifications'

/**
 * Feature store for backend (agent) plugins — the native Hermes plugins plus
 * portable Agent Plugins v1 packages the backend discovers on disk. Settings
 * renders this next to the desktop (renderer) plugin inventory so every plugin
 * the user has is discoverable and toggleable from one page, whatever process
 * it runs in.
 *
 * Backed by the gateway's `plugins.manage` RPC — the same list/toggle
 * primitives `hermes plugins` and the dashboard use, so all surfaces agree on
 * what's installed and what's enabled. Works against every backend topology
 * (local spawn, SSH, URL+token) because it rides the session's own transport.
 */

export type AgentPluginServerState =
  | 'connected'
  | 'app_not_running'
  | 'hermes_not_connected'
  | 'endpoint_unavailable'
  | 'no_interactive_session'
  | 'version_too_old'
  | 'missing_app'
  | 'unsupported_gpu'
  | 'unknown'

export interface AgentPluginServer {
  name: string
  state: AgentPluginServerState
  sentence: string
}

export interface AgentPluginRow {
  name: string
  /** Canonical registry key (e.g. `image_gen/fal`) — absent on legacy backends. */
  key?: string
  version: string
  description: string
  /** 'bundled' | 'user' | 'git' | 'project' | 'entrypoint' */
  source: string
  status: 'enabled' | 'disabled' | 'not enabled'
  /** Agent Plugins v1 package (portable skills/MCP format) vs native Hermes. */
  portable?: boolean
  /** Curated-catalog provenance (from the install sidecar), when present. */
  catalog_name?: string
  catalog_tier?: string
  installed_sha?: string
  /** Current catalog pin for this entry (backend-computed). */
  catalog_sha?: string
  /** Human label the catalog attaches to that pin ("1.4.0"); shown on the Update button when present. */
  catalog_version?: string | null
  /** An update is available: the catalog pin moved past the installed SHA, or (git installs) the last
   *  update check found a newer remote commit. */
  update_available?: boolean
  /** Git installs: what the last update check found to move to (a commit or a feed version). */
  update_target?: string
  /** Full commit SHA a `--ref` install is pinned to (custom sources; refuses `update`). */
  pinned_sha?: string
  /** The package folder also ships `desktop/plugin.js` (unified agent+desktop package). */
  has_desktop_half?: boolean
  /** Absolute install dir on the backend (informational). */
  install_dir?: string
  /** Manifest `config_schema` rendered as a settings form (with current values). */
  settings_schema?: PluginSettingField[]
  /** Full snapshot of declared application-backed MCP servers. */
  servers?: AgentPluginServer[]
}

export type PluginSettingFieldType = 'boolean' | 'enum' | 'json' | 'number' | 'secret' | 'string'

/** One `config_schema` key of a plugin manifest. Secrets never carry a value:
 *  `env` names the `.env` variable, `has_value` whether it is set. */
export interface PluginSettingField {
  key: string
  type: PluginSettingFieldType
  label: string
  description: string
  required: boolean
  value?: unknown
  default?: unknown
  choices?: string[]
  env?: string
  has_value?: boolean
}

export const normalizeAgentPluginRow = (row: AgentPluginRow): AgentPluginRow => ({
  ...row,
  servers: row.servers ?? []
})

/** A `--ref` pin is a full 40-hex commit SHA; branches and tags are refused server-side. */
export const COMMIT_SHA_RE = /^[0-9a-f]{40}$/i

export type AgentPluginsStatus = 'idle' | 'loading' | 'ready' | 'error'

/** The recovering `requestGateway` from `useGatewayRequest`. */
export type GatewayRequest = <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>

export const $agentPlugins = atom<AgentPluginRow[]>([])
export const $agentPluginsStatus = atom<AgentPluginsStatus>('idle')
export const $agentPluginsError = atom<string | null>(null)
/** The profile `$agentPlugins` was loaded for (`null` = the backend's launch
 *  profile; `undefined` = nothing loaded yet). Surfaces that write a row's
 *  settings must check it: the list is shared, and a scope switch keeps the
 *  previous profile's rows on screen until the new list lands. */
export const $agentPluginsProfile = atom<null | string | undefined>(undefined)
/** Best available address of the row whose toggle RPC is in flight. */
export const $agentPluginBusy = atom<string | null>(null)

// Rows the Plugins page actually lists (and search should surface): plugins
// the USER installed, plus the few repo-bundled lifecycle plugins that use the
// ordinary enable/disable contract and have no settings surface of their own
// (#98861). Every other built-in (providers, platforms, browser/web backends,
// dashboard auth, observability, unknown future keys) ships enabled-by-default
// and is configured from its own surface, so it's pure noise here. The prefix
// list is the fallback for older backends whose rows predate a reliable
// `source` field — same curation stance as desktop-slash-commands.ts.
const HIDDEN_KEY_PREFIXES = ['dashboard_auth/', 'model-providers/', 'platforms/']
const MANAGEABLE_BUNDLED_KEYS = new Set(['disk-cleanup', 'security-guidance'])

export const isDesktopRelevantPlugin = (row: AgentPluginRow): boolean => {
  if (row.source === 'bundled') {
    return MANAGEABLE_BUNDLED_KEYS.has(row.key ?? row.name)
  }

  const key = row.key

  return !key || !HIDDEN_KEY_PREFIXES.some(prefix => key.startsWith(prefix))
}

let inflight: Promise<void> | null = null
let inflightProfile: string | null = null
// Bumped per load so a slow response from a previous profile scope can't
// overwrite the newer scope's list (async results can land out of order).
let loadGeneration = 0

/** Scope a `plugins.manage` payload to a profile. Omitted (null) = the
 *  backend's launch profile — older backends ignore the extra param. */
const withProfile = (params: Record<string, unknown>, profile?: string | null) =>
  profile ? { ...params, profile } : params

/** Fetch the backend plugin list, optionally scoped to another profile's
 *  HERMES_HOME. Always refetches (it's a cheap local disk scan on the
 *  backend); concurrent callers for the SAME profile share one in-flight
 *  request — a different profile starts fresh so a scope switch can't get a
 *  stale list. */
export function loadAgentPlugins(request: GatewayRequest, profile?: string | null): Promise<void> {
  const scope = profile ?? null

  if (inflight && inflightProfile === scope) {
    return inflight
  }

  const generation = ++loadGeneration

  inflightProfile = scope
  inflight = (async () => {
    if ($agentPluginsStatus.get() !== 'ready') {
      $agentPluginsStatus.set('loading')
    }

    try {
      const result = await request<{ plugins?: AgentPluginRow[] }>(
        'plugins.manage',
        withProfile({ action: 'list' }, scope)
      )

      if (generation !== loadGeneration) {
        return
      }

      $agentPlugins.set((result?.plugins ?? []).map(normalizeAgentPluginRow))
      $agentPluginsProfile.set(scope)
      $agentPluginsStatus.set('ready')
      $agentPluginsError.set(null)
    } catch (e) {
      if (generation !== loadGeneration) {
        return
      }

      $agentPluginsError.set(e instanceof Error ? e.message : String(e))
      $agentPluginsStatus.set('error')
    } finally {
      if (generation === loadGeneration) {
        inflight = null
        inflightProfile = null
      }
    }
  })()

  return inflight
}

/** Flip a backend plugin on/off and patch the row from the RPC's refreshed
 *  copy. Addressed by canonical key ONLY — bare names collide across category
 *  dirs (image_gen/fal vs video_gen/fal), which is exactly why the backend
 *  moved to key-addressed toggles. Rows without a key (pre-contract-v6
 *  backends) render read-only instead of falling back to the collision-prone
 *  name protocol; the backend-contract skew toast points the user at the
 *  update. Returns whether the toggle stuck. */
export async function toggleAgentPlugin(
  request: GatewayRequest,
  key: string,
  enable: boolean,
  failMessage: string,
  profile?: string | null
): Promise<boolean> {
  $agentPluginBusy.set(key)

  try {
    const result = await request<{ ok?: boolean; plugin?: AgentPluginRow | null }>(
      'plugins.manage',
      withProfile(
        {
          action: 'toggle',
          key,
          enable
        },
        profile
      )
    )

    if (!result?.ok) {
      throw new Error(failMessage)
    }

    const refreshed = result.plugin

    // Patch only a list loaded for the profile this toggle targeted.
    if (refreshed && $agentPluginsProfile.get() === (profile ?? null)) {
      const snapshot = normalizeAgentPluginRow(refreshed)

      $agentPlugins.set($agentPlugins.get().map(row => (row.key === key ? { ...row, ...snapshot } : row)))
    } else {
      await loadAgentPlugins(request, profile)
    }

    return true
  } catch (e) {
    notifyError(e, failMessage)

    return false
  } finally {
    $agentPluginBusy.set(null)
  }
}

export interface AgentPluginInstallResult {
  ok: boolean
  /** The client stopped waiting; the backend may still finish the install. */
  timedOut?: boolean
  /** Refused: the source moved off the reviewed commit (`isSourceMovedRefusal`). */
  sourceMoved?: boolean
  /** Refused at admission by a backend that predates `inspected_sha`: nothing was installed, and an install
   *  there cannot be held to the reviewed commit. Only the user may choose to install without it. */
  inspectedShaUnsupported?: boolean
  pluginName?: string
  warnings?: string[]
  missingEnv?: string[]
  /** Whether the install turned the plugin on (`enabled` in the backend result). */
  enabled?: boolean
  /** The `<namespace>:<skill>` names the model can now load (`activation.live_now.skills`). */
  skillIds?: string[]
  error?: string
  /** What became usable in open chats of the profile (`activation.live_now`). */
  live: AgentPluginLiveNow
  /** Python tools or prompt sections that wait for the next chat (`activation.deferred`). */
  nextChat: boolean
}

export interface AgentPluginLiveServer {
  name: string
  connected: boolean
  tools: string[]
  error?: string | null
}

export interface AgentPluginLiveNow {
  mcpServers: AgentPluginLiveServer[]
  skills: string[]
}

const NO_LIVE: AgentPluginLiveNow = { mcpServers: [], skills: [] }

// Installing a catalog package can clone a repository and resolve Python dependencies.
// The ordinary Desktop RPC deadline is 30s, which can expire after the backend
// has already begun an install that will succeed. Keep this wait bounded while
// giving normal installs time to return their authoritative result.
const PLUGIN_INSTALL_REQUEST_TIMEOUT_MS = 120_000

interface InstallReply {
  ok?: boolean
  plugin_name?: string
  warnings?: string[]
  missing_env?: string[]
  enabled?: boolean
  activation?: {
    live_now?: {
      mcp_servers?: AgentPluginLiveServer[]
      skills?: { name: string }[]
    } | null
    deferred?: Record<string, string[]>
  } | null
  error?: string
}

/** The message `tui_gateway/contracts/registry.py::validate_params` opens its admission refusal with. */
const INSPECTED_SHA_ADMISSION_REFUSAL = 'invalid params for plugins.manage: inspected_sha: '

/** A backend predating `inspected_sha` (native Desktop on an older SSH/URL/Cloud runtime) refuses the
 *  whole install at admission (code 4000, handler never ran). Installing there without the field takes
 *  whatever the source holds at that moment, so the dialog asks the user first; nothing resends on its
 *  own. Only that refusal qualifies: the code AND a message that OPENS with the admission prefix. Any
 *  other error (a 5026 install failure echoing a git server's text included) is an ordinary failure.
 *  Delete once no supported backend predates the field. */
function backendPredatesInspectedSha(params: Record<string, unknown>, error: unknown): boolean {
  return (
    'inspected_sha' in params &&
    error instanceof JsonRpcGatewayError &&
    error.code === 4000 &&
    error.message.startsWith(INSPECTED_SHA_ADMISSION_REFUSAL)
  )
}

/** The backend refused because the source is no longer at the commit the dialog reviewed
 *  (`tui_gateway/methods_tools.py::_source_moved_data`): read it again, never resend that commit. */
export function isSourceMovedRefusal(error: unknown): boolean {
  const data = error instanceof JsonRpcGatewayError ? (error.data as { reason?: unknown } | undefined) : undefined

  return data?.reason === 'source_moved'
}

export async function installAgentPlugin(
  request: GatewayRequest,
  opts: {
    identifier: string
    force?: boolean
    enable?: boolean
    /** Curated-catalog install: the backend resolves repo + pinned SHA from
     *  its own plugin-catalog and records provenance in the sidecar. */
    catalogName?: string
    /** Pin a custom source to one full commit SHA (team-wide reproducible install). */
    ref?: string
    /** The commit the install dialog inspected: a custom source with no `ref` whose branch moved since is
     *  refused by the backend, never installed at the new tip. */
    inspectedSha?: string
    /** Target profile's HERMES_HOME (null/undefined = backend launch profile). */
    profile?: string | null
  }
): Promise<AgentPluginInstallResult> {
  const params = withProfile(
    {
      action: 'install',
      identifier: opts.identifier,
      force: Boolean(opts.force),
      enable: opts.enable ?? true,
      ...(opts.catalogName ? { catalog_name: opts.catalogName } : {}),
      ...(opts.ref ? { ref: opts.ref } : {}),
      ...(!opts.ref && opts.inspectedSha ? { inspected_sha: opts.inspectedSha } : {})
    },
    opts.profile
  )

  try {
    const result = await request<InstallReply>('plugins.manage', params, PLUGIN_INSTALL_REQUEST_TIMEOUT_MS)

    if (!result?.ok) {
      return { ok: false, error: result?.error || 'Install failed', live: NO_LIVE, nextChat: false }
    }

    const liveSkills = result.activation?.live_now?.skills ?? []

    return {
      ok: true,
      pluginName: result.plugin_name,
      warnings: result.warnings,
      missingEnv: result.missing_env,
      enabled: result.enabled,
      skillIds: liveSkills.map(skill => skill.name),
      live: {
        mcpServers: result.activation?.live_now?.mcp_servers ?? [],
        // `<namespace>:<skill>` is what the model loads; the toast shows the skill's own name.
        skills: liveSkills.map(skill => skill.name.split(':').pop() ?? skill.name)
      },
      nextChat: Object.keys(result.activation?.deferred ?? {}).length > 0
    }
  } catch (e) {
    const message = e instanceof Error ? e.message : String(e)

    return {
      ok: false,
      timedOut: /^request timed out after \d+s: plugins\.manage$/.test(message),
      sourceMoved: isSourceMovedRefusal(e),
      inspectedShaUnsupported: backendPredatesInspectedSha(params, e),
      error: message,
      live: NO_LIVE,
      nextChat: false
    }
  }
}

/** What a repository holds, the shape native Desktop's `probePluginRepo` answers. `unavailable`: the
 *  backend cannot inspect at all (it predates `plugins.manage inspect`), which no retry changes. */
export interface AgentPluginInspection {
  ok: boolean
  agent: boolean
  desktop: boolean
  agentName?: string | null
  desktopName?: string | null
  warnings: string[]
  insecure?: boolean
  /** The commit the backend read; absent when it reported none or not a full SHA. */
  sha?: string
  /** Read at the catalog entry's pin, as a catalog install checks it out: `sha` is what that install must be. */
  catalogPin?: boolean
  unavailable?: boolean
  error?: string
}

// `_run_action`'s unknown action, and JSON-RPC's unknown method.
const INSPECT_UNSUPPORTED_CODES = new Set([4017, -32601])
/** A backend that predates `install_desktop`: it answers the action as unknown (4017). */
const INSTALL_DESKTOP_UNSUPPORTED_CODES = new Set([4017, -32601])

/** Inspect a source through the backend (`plugins.manage inspect`): it clones into a temp folder and
 *  reports which halves ship, installing and running nothing. For a renderer with no Git of its own
 *  (the browser-hosted app); native Desktop inspects in Electron. Never rejects. */
export async function inspectAgentPlugin(
  request: GatewayRequest,
  opts: { identifier: string; catalogName?: string; profile?: string | null }
): Promise<AgentPluginInspection> {
  try {
    const result = await request<{
      ok?: boolean
      agent?: boolean
      desktop?: boolean
      agent_name?: string | null
      desktop_name?: string | null
      sha?: string | null
      warnings?: string[]
      insecure?: boolean
      error?: string
    }>(
      'plugins.manage',
      withProfile(
        {
          action: 'inspect',
          identifier: opts.identifier,
          ...(opts.catalogName ? { catalog_name: opts.catalogName } : {})
        },
        opts.profile
      ),
      // A clone runs on the backend, as an install's does. One that outlasts this wait keeps running
      // there, and Retry collects its answer instead of starting another clone.
      PLUGIN_INSTALL_REQUEST_TIMEOUT_MS
    )

    const ok = Boolean(result?.ok)

    return {
      ok,
      agent: ok && Boolean(result.agent),
      desktop: ok && Boolean(result.desktop),
      agentName: result?.agent_name ?? null,
      desktopName: result?.desktop_name ?? null,
      warnings: result?.warnings ?? [],
      insecure: Boolean(result?.insecure),
      ...(ok && typeof result.sha === 'string' && COMMIT_SHA_RE.test(result.sha)
        ? { sha: result.sha.toLowerCase() }
        : {}),
      ...(ok && opts.catalogName ? { catalogPin: true } : {}),
      ...(ok ? {} : { error: result?.error || 'Inspection failed' })
    }
  } catch (e) {
    return {
      ok: false,
      agent: false,
      desktop: false,
      warnings: [],
      unavailable: e instanceof JsonRpcGatewayError && INSPECT_UNSUPPORTED_CODES.has(e.code ?? 0),
      error: e instanceof Error ? e.message : String(e)
    }
  }
}

/** Install a repository's desktop half onto the host that serves this client (`plugins.manage
 *  install_desktop`). Native Desktop clones one itself; a browser-hosted renderer has no disk of its
 *  own, so it asks the backend that serves the tab and the plugin appears in the folder the Webapp
 *  already loads. Never rejects. */
export async function installDesktopPluginHalf(
  request: GatewayRequest,
  opts: { identifier: string; catalogName?: string; force?: boolean; profile?: string | null; ref?: string }
): Promise<{
  ok: boolean
  pairedWithAgent?: boolean
  pluginName?: string
  /** The backend predates the action: no retry changes that (a build older than this one). */
  unsupported?: boolean
  /** Refused: the source moved off the reviewed commit (`isSourceMovedRefusal`). */
  sourceMoved?: boolean
  warnings: string[]
  error?: string
}> {
  try {
    const result = await request<{
      ok?: boolean
      plugin_name?: string
      paired_with_agent?: boolean
      warnings?: string[]
      error?: string
    }>(
      'plugins.manage',
      withProfile(
        {
          action: 'install_desktop',
          identifier: opts.identifier,
          force: Boolean(opts.force),
          ...(opts.catalogName ? { catalog_name: opts.catalogName } : {}),
          ...(opts.ref ? { ref: opts.ref } : {})
        },
        opts.profile
      ),
      PLUGIN_INSTALL_REQUEST_TIMEOUT_MS
    )

    if (!result?.ok) {
      return { ok: false, warnings: [], error: result?.error || 'Desktop plugin install failed' }
    }

    return {
      ok: true,
      pluginName: result.plugin_name,
      pairedWithAgent: Boolean(result.paired_with_agent),
      warnings: result.warnings ?? []
    }
  } catch (e) {
    return {
      ok: false,
      unsupported: e instanceof JsonRpcGatewayError && INSTALL_DESKTOP_UNSUPPORTED_CODES.has(e.code ?? 0),
      sourceMoved: isSourceMovedRefusal(e),
      warnings: [],
      error: e instanceof Error ? e.message : String(e)
    }
  }
}

/** Remove one installed desktop plugin folder from the host that serves this client
 *  (`plugins.manage remove_desktop`); a package's own half is refused by the backend unless forced.
 *  Never rejects. */
export async function removeDesktopPluginHalf(
  request: GatewayRequest,
  opts: { force?: boolean; name: string; profile?: string | null }
): Promise<{ ok: boolean; error?: string }> {
  try {
    const result = await request<{ ok?: boolean; error?: string }>(
      'plugins.manage',
      withProfile({ action: 'remove_desktop', name: opts.name, force: Boolean(opts.force) }, opts.profile)
    )

    return result?.ok ? { ok: true } : { ok: false, error: result?.error || 'Desktop plugin removal failed' }
  } catch (e) {
    return { ok: false, error: e instanceof Error ? e.message : String(e) }
  }
}

/** One security-scan finding on an update the scan blocked. */
export interface AgentPluginScanFinding {
  severity: string
  category: string
  file: string
  line: number
  description: string
}

/** Outcome of `updateAgentPlugin`: `applied` when the update landed, `unchanged`
 *  when already current, `consent` when a new catalog pin widens the plugin
 *  (retry with `acceptCapabilities`), `scan` when the security scan blocked the
 *  new code (a `caution` verdict can be retried with `force`). The backend
 *  changed nothing for `consent` and `scan`. */
export type AgentPluginUpdateOutcome =
  | { kind: 'applied' | 'unchanged' | 'failed' }
  | { kind: 'consent'; sha: string; deltaLines: string[] }
  | { kind: 'scan'; verdict: string; findings: AgentPluginScanFinding[] }

export interface AgentPluginUpdateOptions {
  /** Apply a catalog re-pin the user confirmed after a `consent` outcome. */
  acceptCapabilities?: boolean
  /** Apply an update whose scan returned caution, after the user saw the findings. */
  force?: boolean
}

/** Update an installed plugin (backend `plugins.manage update`): a catalog install
 *  re-pins to the current catalog SHA, a git install pulls. Refreshes the list on
 *  success. */
export async function updateAgentPlugin(
  request: GatewayRequest,
  name: string,
  failMessage: string,
  profile?: string | null,
  options: AgentPluginUpdateOptions = {}
): Promise<AgentPluginUpdateOutcome> {
  $agentPluginBusy.set(name)

  const params: PluginsManageParams = { action: 'update', name }

  if (options.acceptCapabilities) {
    params.accept_capabilities = true
  }

  if (options.force) {
    params.force = true
  }

  try {
    const result = await request<{
      ok?: boolean
      unchanged?: boolean
      consent_required?: boolean
      sha?: string
      delta_lines?: string[]
      scan_blocked?: boolean
      scan_verdict?: string
      scan_findings?: AgentPluginScanFinding[]
    }>('plugins.manage', withProfile({ ...params }, profile), PLUGIN_INSTALL_REQUEST_TIMEOUT_MS)

    if (result?.consent_required) {
      return { kind: 'consent', sha: (result.sha ?? '').slice(0, 8), deltaLines: result.delta_lines ?? [] }
    }

    if (result?.scan_blocked) {
      return { kind: 'scan', verdict: result.scan_verdict ?? 'dangerous', findings: result.scan_findings ?? [] }
    }

    if (!result?.ok) {
      throw new Error(failMessage)
    }

    await loadAgentPlugins(request, profile)

    return { kind: result.unchanged ? 'unchanged' : 'applied' }
  } catch (e) {
    notifyError(e, failMessage)

    return { kind: 'failed' }
  } finally {
    $agentPluginBusy.set(null)
  }
}

/** Uninstall a user-installed agent plugin (backend `plugins.manage remove`;
 *  deletes `<HERMES_HOME>/plugins/<name>` and its install metadata). Drops the
 *  row locally on success — callers rescan so a unified package's desktop half
 *  is pruned too. Returns whether the plugin was removed. */
export async function removeAgentPlugin(
  request: GatewayRequest,
  name: string,
  failMessage: string,
  profile?: string | null
): Promise<boolean> {
  $agentPluginBusy.set(name)

  try {
    const result = await request<{ ok?: boolean }>('plugins.manage', withProfile({ action: 'remove', name }, profile))

    if (!result?.ok) {
      throw new Error(failMessage)
    }

    $agentPlugins.set($agentPlugins.get().filter(row => row.name !== name))

    return true
  } catch (e) {
    notifyError(e, failMessage)

    return false
  } finally {
    $agentPluginBusy.set(null)
  }
}

export interface SaveAgentPluginSettingsOptions {
  /** Canonical plugin key (`plugins.entries.<key>`). */
  key: string
  /** Non-secret `config_schema` values, already coerced to their wire types. */
  values: Record<string, unknown>
  /** Secret fields: `.env` variable name → new value (blank = unchanged, never sent). */
  secrets: Record<string, string>
  /** Writes ONE secret through the credential route (`PUT /api/env`, profile-scoped
   *  by the caller) — secrets never ride the config.yaml RPC. */
  writeSecret: (env: string, value: string) => Promise<unknown>
  failMessage: string
  profile?: string | null
}

/** Persist a plugin's manifest-declared settings: values through
 *  `plugins.manage settings` (the backend writes `plugins.entries.<key>.settings`
 *  with the same writer `ctx.set_config` uses), secrets through `writeSecret`.
 *  Patches the row from the RPC's refreshed copy so the form re-reads what
 *  landed. Returns whether everything saved. */
export async function saveAgentPluginSettings(
  request: GatewayRequest,
  opts: SaveAgentPluginSettingsOptions
): Promise<boolean> {
  $agentPluginBusy.set(opts.key)

  try {
    for (const [env, value] of Object.entries(opts.secrets)) {
      if (value) {
        await opts.writeSecret(env, value)
      }
    }

    // A secret-only save still makes the (empty) settings call: the backend's save is what tells a
    // Desktop half `plugin.<id>.settings.changed`, and a new API key is the change it most needs.
    const wroteSecret = Object.values(opts.secrets).some(Boolean)

    const result =
      Object.keys(opts.values).length > 0 || wroteSecret
        ? await request<{ ok?: boolean; plugin?: AgentPluginRow | null }>(
            'plugins.manage',
            withProfile({ action: 'settings', key: opts.key, values: opts.values }, opts.profile)
          )
        : null

    if (result && !result.ok) {
      throw new Error(opts.failMessage)
    }

    // The shared list may belong to another profile by now (a scope switch
    // mid-save): only a list loaded for the profile this save targeted takes
    // its refreshed row, and a refetch would hijack the other profile's view.
    const ownsList = $agentPluginsProfile.get() === (opts.profile ?? null)

    if (ownsList && result?.plugin) {
      const refreshed = result.plugin

      $agentPlugins.set($agentPlugins.get().map(row => (row.key === opts.key ? { ...row, ...refreshed } : row)))
    } else if (ownsList) {
      await loadAgentPlugins(request, opts.profile)
    }

    return true
  } catch (e) {
    notifyError(e, opts.failMessage)

    return false
  } finally {
    $agentPluginBusy.set(null)
  }
}