Skip to content

The agent that grows with you

17.4 KB
Raw Blame
/**
 * The plugin authoring contract. A plugin is a file that default-exports a
 * `HermesPlugin`; it never touches the registry directly — it receives a
 * scoped `PluginContext` whose `register` auto-tags provenance
 * (`source: 'plugin:<id>'`) and namespaces the contribution id
 * (`<id>:<localId>`), so authors write plain contributions and collisions
 * between plugins are impossible.
 *
 * Bundled plugins live in `src/plugins/<name>/plugin.tsx` and are discovered
 * by `discoverBundledPlugins()` (contrib/plugins.ts) — no import, no registry
 * edit. Runtime-fetched third-party plugins will drive the SAME contract
 * through the plugin host loader (next phase); this is that seam.
 */

import type { ReadableAtom } from 'nanostores'

import { pluginRest, type PluginRestOptions, pluginSocket } from '@/hermes'
import { createPluginI18n, type PluginI18n } from '@/i18n'
import {
  listPluginAppActions,
  type PluginAppActionId,
  type PluginAppActionInfo,
  type PluginRunActionResult,
  runPluginAppAction
} from '@/lib/keybinds/plugin-actions'
import { readKey, writeKey } from '@/lib/storage'
import { dispatchPluginNativeNotification, type PluginNativeNotificationInput } from '@/store/native-notifications'
import { $petActive } from '@/store/pet'
import { clearPetMessages, type PetSayOptions, sayPetMessage } from '@/store/pet-plugin-messages'

import { type GatewayEventListener, onGatewayEvent } from './events'
import { createPluginFiles, type PluginFiles } from './plugin-files'
import { createPluginPreview, type PluginPreview } from './plugin-preview'
import { $pluginRecords } from './plugins-store'
import { registry } from './registry'
import { type PluginSettingsPage, settingsPageContribution } from './settings-pages'

export type { PluginFileEntry, PluginFiles, PluginFilesResult, PluginFolder } from './plugin-files'
export type { PluginPreview } from './plugin-preview'
import type { Contribution } from './types'

export type { PluginSettingsPage, PluginSettingsSubpage } from './settings-pages'
export type { PluginRestOptions } from '@/hermes'
export type { HermesOpenTarget } from '@/lib/hermes-open-target'
export type { PluginAppActionId, PluginAppActionInfo, PluginRunActionResult } from '@/lib/keybinds/plugin-actions'
export type { PluginNativeNotificationInput, PluginNotificationAction } from '@/store/native-notifications'
export type { PetMessageTone, PetSayOptions } from '@/store/pet-plugin-messages'

/** A contribution as a plugin author writes it — provenance + id scoping are
 *  the host's job, so those fields are off-limits here. */
export type PluginContribution = Omit<Contribution, 'source' | 'id'> & { id: string }

/** Namespaced JSON persistence (the VS Code `globalState` analog). Keys live
 *  under `hermes.plugin.<id>.` — plugins can't read or clobber each other. */
export interface PluginStorage {
  get<T>(key: string, fallback: T): T
  set(key: string, value: unknown): void
  remove(key: string): void
}

/** The curated OS door — every way a plugin reaches outside the app window,
 *  in one attributed namespace instead of the raw `window.hermesDesktop`
 *  bridge. Every member resolves a result instead of throwing when the
 *  capability can't apply (no Electron shell, older desktop build), so
 *  callers branch on the return value rather than sniffing the bridge. */
export interface PluginOs {
  /** Native OS notification (Electron), attributed to this plugin. Gated by
   *  Settings ▸ Notifications ▸ "Plugin notifications" and fires only while
   *  the user is away from Hermes — use `host.notify` for the in-app toast.
   *  Throttled per plugin; reserve it for genuinely notable events.
   *  Supports `icon`, `activate` (e.g. `hermes://index-network/intent/1`),
   *  action buttons, and renderer `onActivate` / `onAction` callbacks. */
  notify: (input: PluginNativeNotificationInput) => void
  /** Open a URL with the OS default handler (browser, mail client, custom
   *  schemes like `spotify:`). Resolves false when the shell can't. */
  openExternal: (url: string) => Promise<boolean>
  /** Reveal a path in the OS file manager (Finder / Explorer). Resolves
   *  false when unavailable. */
  revealPath: (path: string) => Promise<boolean>
  /** Native save dialog. Resolves the chosen path, or null on cancel /
   *  when unavailable. The path is on the BACKEND's filesystem, so hand it
   *  to a `rest` call rather than trying to write it from the renderer. */
  pickSavePath: (options?: PluginFileDialogOptions) => Promise<null | string>
  /** Native open dialog, single file. Resolves the chosen path, or null on
   *  cancel / when unavailable. */
  pickOpenPath: (options?: PluginFileDialogOptions) => Promise<null | string>
  /** Write text to the system clipboard. Resolves false when unavailable. */
  writeClipboard: (text: string) => Promise<boolean>
}

/** The pet door: short lines in the core pet's speech bubble, attributed to
 *  this plugin, instead of locating the pet in the app DOM and drawing over
 *  it. The host renders them in the in-window pet and the pop-out overlay;
 *  they show only while the user has a pet visible. */
export interface PluginPet {
  /** Show one plain-text line (no HTML; control characters stripped, capped
   *  at 120 chars) with this plugin's name as a small label. Lasts `ttlMs`
   *  (default 6 s, clamped 1–30 s); the same `id` replaces in place. Core
   *  error / waiting-on-you states keep priority over it. Rate-limited per
   *  plugin. Returns a disposer that removes the line early. */
  say: (text: string, options?: PetSayOptions) => () => void
  /** Remove one line by `id`, or every line this plugin has up. */
  clear: (id?: string) => void
  /** True while a pet is installed and shown (in-window or popped out). A
   *  plugin can fall back to its own chip or pane while this is false. */
  visible: ReadableAtom<boolean>
}

export interface PluginFileDialogOptions {
  defaultPath?: string
  filters?: Array<{ extensions: string[]; name: string }>
  title?: string
}

export interface PluginContext {
  /** The resolved plugin source tag, e.g. `'plugin:cost-meter'`. */
  readonly source: string
  /** Register one contribution (id namespaced, source stamped). */
  register: (c: PluginContribution) => () => void
  /** Register several at once; the returned disposer removes all of them. */
  registerMany: (cs: PluginContribution[]) => () => void
  /** Add this plugin's page (and optional sub-pages) to Settings ▸ Plugins.
   *  Removed with the plugin on disable/unload. Feature-detect on older hosts:
   *  `ctx.registerSettingsPage?.(...)`. */
  registerSettingsPage: (page: PluginSettingsPage) => () => void
  /** Register an arbitrary cleanup to run on unload/disable — for side effects
   *  that aren't contributions or sockets (store subscriptions, timers). Runs
   *  alongside every other disposer when the plugin deactivates. */
  onDispose: (fn: () => void) => void
  /** Hear the gateway stream by event type (`'*'` = everything). Tracked like
   *  every other registration: unload/reload/disable removes the listener, so
   *  a subscription made after `register()` returns (a timer, a socket
   *  callback) can never outlive the plugin the way a bare `host.onEvent`
   *  there would. */
  onEvent: (type: string, listener: GatewayEventListener) => () => void
  /** Scoped timers: cleared when the plugin unloads/reloads/disables, so a
   *  poller cannot outlive the plugin the way a bare `setInterval` does (the
   *  host never sees a bare global — it is the author's leak). Each returns
   *  a disposer that cancels early. */
  setTimeout: (fn: () => void, ms: number) => () => void
  setInterval: (fn: () => void, ms: number) => () => void
  /** Scoped `addEventListener` on any target (window, document, a node):
   *  removed on unload/reload/disable. Returns a disposer. */
  addEventListener: (
    target: EventTarget,
    type: string,
    listener: EventListenerOrEventListenerObject,
    options?: AddEventListenerOptions | boolean
  ) => () => void
  /** REST to this plugin's own backend namespace (`/api/plugins/<id>`); `path`
   *  is relative ('/board'). The sanctioned door for a plugin that ships a
   *  `plugin_api.py` — profile-aware, namespace-scoped by construction. Use
   *  `host.request` for gateway JSON-RPC. */
  rest: <T>(path: string, opts?: PluginRestOptions) => Promise<T>
  /** Live twin of `rest`: a WebSocket to this plugin's own namespace
   *  ('/events'), JSON frames to `onMessage`, auto-reconnect, disposer
   *  returned. Resolves to a no-op on OAuth remotes — treat it as an
   *  accelerator over your polling, never a replacement. */
  socket: (path: string, onMessage: (data: unknown) => void) => () => void
  /** The curated OS door: native notification, open-external, reveal-in-file-
   *  manager, clipboard — attributed to this plugin, result-shaped (never
   *  throws for a missing capability). */
  os: PluginOs
  /** The pet door: lines in the core pet's speech bubble, attributed to this
   *  plugin and cleared when it unloads. Feature-detect on older hosts:
   *  `ctx.pet?.say(...)`. */
  pet: PluginPet
  /** Run a built-in app action (toggle the browser panel, open Settings,
   *  focus the composer, …) through the same handler its keyboard shortcut
   *  and palette entry use, so rebinding or unbinding the shortcut changes
   *  nothing. Only view / navigation actions are allowed (`listActions()`);
   *  an unknown or denied id is refused with `{ ok: false, error }` and a
   *  console warning, never thrown. Feature-detect on older hosts:
   *  `ctx.runAction?.('view.showBrowser')`. */
  runAction: (id: PluginAppActionId) => PluginRunActionResult
  /** The actions `runAction` accepts, with their localized labels. */
  listActions: () => PluginAppActionInfo[]
  /** Run JavaScript in the preview Browser page. Closed unless the plugin
   *  declares `capabilities: ['preview.executeJavaScript']`, and even then
   *  the app asks the user once per page origin before anything runs.
   *  Feature-detect on older hosts: `ctx.preview?.executeJavaScript`. */
  preview: PluginPreview
  /** Plugin-scoped persistence. */
  storage: PluginStorage
  /** Folder-scoped file access: this plugin's own data folder plus folders
   *  the user grants it through the app's picker, by relative path. The app
   *  checks every call; nothing outside those folders (or inside Hermes'
   *  own data) is reachable. Feature-detect on older hosts: `ctx.files?.…`. */
  files: PluginFiles
  /** Plugin-scoped i18n: ship + register locale bundles under this plugin,
   *  resolved against the app's active locale — no core `en.ts` edit. */
  i18n: PluginI18n
}

export interface HermesPlugin {
  /** Stable slug — becomes the `plugin:<id>` source and the id namespace. */
  id: string
  /** Human name for settings / about UI. */
  name?: string
  /** One-liner for the settings inventory (what the plugin adds). */
  description?: string
  /** Registers on load when the user hasn't chosen (default true). Set false
   *  for opt-in plugins: they inventory in Capabilities ▸ Plugins, off until the
   *  user flips the switch. */
  defaultEnabled?: boolean
  /** Sensitive doors this plugin uses, declared up front so the app can show
   *  them and gate them. Today: `'preview.executeJavaScript'` (`ctx.preview`).
   *  A door the plugin did not declare refuses every call. */
  capabilities?: readonly string[]
  /** Called once at load; wire contributions through `ctx`. */
  register: (ctx: PluginContext) => void
}

function createPluginStorage(pluginId: string): PluginStorage {
  const scoped = (key: string) => `hermes.plugin.${pluginId}.${key}`

  return {
    get(key, fallback) {
      const raw = readKey(scoped(key))

      if (raw === null) {
        return fallback
      }

      try {
        return JSON.parse(raw)
      } catch {
        return fallback
      }
    },
    set: (key, value) => writeKey(scoped(key), JSON.stringify(value)),
    remove: key => writeKey(scoped(key), null)
  }
}

// Never throws for a missing capability: the renderer can outlive an older
// Electron shell (or run in a plain browser), so every door degrades to a
// false result the plugin can branch on.
function createPluginOs(pluginId: string): PluginOs {
  const attempt = async (run: (bridge: NonNullable<typeof window.hermesDesktop>) => Promise<boolean>) => {
    const bridge = typeof window === 'undefined' ? undefined : window.hermesDesktop

    if (!bridge) {
      return false
    }

    try {
      return await run(bridge)
    } catch {
      return false
    }
  }

  // Same shape as `attempt`, for the pickers that answer with a path.
  const attemptPath = async (run: (bridge: NonNullable<typeof window.hermesDesktop>) => Promise<null | string>) => {
    const bridge = typeof window === 'undefined' ? undefined : window.hermesDesktop

    if (!bridge) {
      return null
    }

    try {
      return await run(bridge)
    } catch {
      return null
    }
  }

  return {
    notify: input => dispatchPluginNativeNotification(pluginId, input),
    openExternal: url =>
      attempt(async bridge => {
        await bridge.openExternal(url)

        return true
      }),
    pickOpenPath: options =>
      attemptPath(async bridge => {
        const picked = await bridge.selectPaths?.({ ...options, multiple: false })

        return picked?.[0] ?? null
      }),
    pickSavePath: options => attemptPath(async bridge => (await bridge.selectSavePath?.(options)) ?? null),
    revealPath: path => attempt(async bridge => (bridge.revealPath ? bridge.revealPath(path) : false)),
    writeClipboard: text => attempt(bridge => bridge.writeClipboard(text))
  }
}

// Lines are attributed by the inventory name the loader published before
// register() ran; the id is the fallback. Every line this plugin still has up
// is cleared with it on unload/disable (tracked on first use).
function createPluginPet(pluginId: string, track: (dispose: () => void) => () => void): PluginPet {
  let tracked = false

  return {
    clear: id => clearPetMessages(pluginId, id),
    say: (text, options) => {
      if (!tracked) {
        tracked = true
        track(() => clearPetMessages(pluginId))
      }

      return sayPetMessage(pluginId, $pluginRecords.get()[pluginId]?.name ?? pluginId, text, options)
    },
    visible: $petActive
  }
}

/** Timers and DOM listeners a plugin takes out through `ctx`, retired as ONE
 *  tracked disposer. A fired timeout drops out of the set on its own, so a
 *  long-lived plugin firing many one-shots does not accumulate cleanups. */
function createPluginLifetime(track: (dispose: () => void) => () => void) {
  const cleanups = new Set<() => void>()
  let tracked = false

  const scoped = (cleanup: () => void) => {
    // Registered with the host on first use, so a plugin that never takes a
    // timer or listener out adds nothing to its disposer list.
    if (!tracked) {
      tracked = true
      track(() => {
        cleanups.forEach(pending => pending())
        cleanups.clear()
      })
    }

    cleanups.add(cleanup)

    return () => {
      cleanups.delete(cleanup)
      cleanup()
    }
  }

  return {
    setTimeout: (fn: () => void, ms: number) => {
      const clear = () => globalThis.clearTimeout(id)

      const id = globalThis.setTimeout(() => {
        cleanups.delete(clear)
        fn()
      }, ms)

      return scoped(clear)
    },
    setInterval: (fn: () => void, ms: number) => {
      const id = globalThis.setInterval(fn, ms)

      return scoped(() => globalThis.clearInterval(id))
    },
    addEventListener: (
      target: EventTarget,
      type: string,
      listener: EventListenerOrEventListenerObject,
      options?: AddEventListenerOptions | boolean
    ) => {
      target.addEventListener(type, listener, options)

      return scoped(() => target.removeEventListener(type, listener, options))
    }
  }
}

/** The declared capabilities of a plugin export, strings only. */
export function declaredCapabilities(plugin: Pick<HermesPlugin, 'capabilities'>): string[] {
  return Array.isArray(plugin.capabilities)
    ? plugin.capabilities.filter((entry): entry is string => typeof entry === 'string')
    : []
}

/** Build the scoped context handed to a plugin's `register`. `onDispose`
 *  receives every registration's disposer (the loader's unload/reload hook);
 *  `capabilities` is what the plugin declared (`declaredCapabilities`). */
export function createPluginContext(
  pluginId: string,
  onDispose?: (dispose: () => void) => void,
  capabilities: readonly string[] = []
): PluginContext {
  const source = `plugin:${pluginId}`
  const scope = (c: PluginContribution): Contribution => ({ ...c, id: `${pluginId}:${c.id}`, source })

  const track = (dispose: () => void) => {
    onDispose?.(dispose)

    return dispose
  }

  return {
    source,
    register: c => track(registry.register(scope(c))),
    registerMany: cs => track(registry.registerMany(cs.map(scope))),
    registerSettingsPage: page => track(registry.register(scope(settingsPageContribution(page)))),
    onDispose: fn => void track(fn),
    onEvent: (type, listener) => track(onGatewayEvent(type, listener)),
    ...createPluginLifetime(track),
    rest: <T>(path: string, opts?: PluginRestOptions) => pluginRest<T>(pluginId, path, opts),
    socket: (path, onMessage) => track(pluginSocket(pluginId, path, onMessage)),
    os: createPluginOs(pluginId),
    pet: createPluginPet(pluginId, track),
    runAction: id => runPluginAppAction(pluginId, id),
    listActions: listPluginAppActions,
    preview: createPluginPreview(pluginId, capabilities),
    storage: createPluginStorage(pluginId),
    files: createPluginFiles(pluginId),
    i18n: createPluginI18n(pluginId, track)
  }
}