• English
  • JavaScript plugins

    Soma supports trusted local .mjs plugins with server and client entries. Server entries run in a persistent Node process per session; client entries run in the browser. Node.js 22.13 or newer is required only for enabled server entries. The npm launcher uses its own Node executable; direct binary users can set SOMA_NODE or make node available on PATH.

    Configure a plugin

    Create ~/.soma/plugins.toml ($SOMA_HOME/plugins.toml when overridden):

    timeout_ms = 10000
    
    [[plugins]]
    id = "project-policy"
    enabled = true
    server = "/absolute/path/to/policy.mjs"
    
    [plugins.config]
    blockedTools = ["shell_command"]

    Relative module paths resolve beside plugins.toml. The optional node field selects an executable instead of SOMA_NODE or PATH. timeout_ms bounds startup and each event's complete callback sequence; its range is 1–120000 milliseconds. Up to 16 local plugins may be configured. Missing configuration starts no plugin process. Server configuration changes apply before the next turn, including in existing sessions. Active turns retain their current configuration.

    Save the module:

    export default {
      name: "project-policy",
      hooks: {
        async PreToolUse(event, ctx) {
          if (ctx.config.blockedTools?.includes(event.toolName)) {
            return {
              kind: "block",
              reason: "Tool disabled by project policy.",
            };
          }
          return { kind: "continue" };
        },
        PostToolUse(event, ctx) {
          ctx.log("Completed %s", event.toolName);
        },
      },
    };

    Each server module must export a unique nonempty name and a hooks object. Supported callbacks are optional; unknown event names are errors. A module may also export an asynchronous dispose() method on its default object for graceful shutdown. The shutdown deadline is two seconds per session, then the host is terminated.

    Hook contract

    Each callback receives (event, ctx) and may return a promise. event and ctx.config are deeply frozen JSON snapshots. ctx.signal is an AbortSignal; callbacks should observe it when awaiting cancellable work. ctx.log(...) and console produce bounded debug tracing records under soma_hooks. Direct writes to stdout are prohibited because stdout carries IPC frames.

    Common event fields are threadId (string), turnId, stepId, cwd, model, and localToolsMode. Execution uses the session's canonical cwd.

    HookAdditional event fieldsMeaning of block
    PreToolUsetoolName, toolCallId, toolInputSkip the tool and return its reason to the model as an error
    PostToolUseThe tool fields plus toolResult: { output, isError: false }Replace the result with error feedback; the tool has already executed
    StoplastAssistantMessage, stopHookActiveRecord attributed feedback and continue the current turn

    Function tools expose their parsed JSON arguments as toolInput; freeform tools such as apply_patch expose their original input string. PostToolUse runs only after successful execution and receives the bounded model-facing output. Unavailable tools and invalid payload kinds fail before PreToolUse. Hosted provider tools, including web search, do not pass through these local hooks.

    Return one of:

    { kind: "continue" }
    { kind: "block", reason: "A nonempty explanation" }

    Returning undefined also continues. Other return shapes are errors. A block reason is limited to 8192 UTF-8 bytes. Callbacks run in configuration order; all blocking reasons are retained and a later continuation cannot override a block. Hooks cannot grant unavailable tools, rewrite arguments, or mutate core state.

    Completion checks

    Stop runs when the model finishes and no steering input is already queued. Blocking keeps the same turn open; feedback is appended after the assistant's answer and included in the next model request. For example:

    Stop(event) {
      if (!event.stopHookActive) {
        return { kind: "block", reason: "Check the requested deliverables once more." };
      }
      return { kind: "continue" };
    }

    Only one hook-driven continuation is permitted per turn. Blocking again fails the turn instead of looping indefinitely. The normal step limit and user interruption still apply. Stop does not run on provider failure or interruption.

    Lifecycle and failures

    A plugin module loads once per session and retains its JS state across turns and provider changes. Each new or forked session loads independent modules; plugin state and Stop feedback are not inherited. Changing enabled server entries, their configuration, the executable, or timeout replaces the host at the next turn and resets its JS state. Unchanged configuration preserves state. Editing module source alone does not reload it. Model-tool registration is not supported.

    Startup errors fail the turn before sampling. Callback exceptions and invalid decisions become visible tool errors, or fail the turn for Stop. Timeouts, cancellation, malformed IPC, and disconnection terminate the host; start a new session or explicitly change hook configuration to run plugins again. Soma does not automatically retry an invocation whose side effects may already have happened. Completed tool effects and history are retained on interruption.

    Plugins have Node's local file, process, and network access. This is process isolation, not a security sandbox. Use dispose() to clean up resources created by a plugin; terminating the Node host does not guarantee cleanup of arbitrary descendant processes.

    See ADR 0041 for the ownership and IPC decision.

    Plugin settings

    Open Settings → Plugins to enable or disable built-in and configured plugins. Changes are saved in plugins.toml, shared across browsers, and survive server restart. Client changes apply immediately; server changes apply before the next turn. Other open browsers refresh on focus and every five seconds.

    Trajectory, Session statistics, and Call inspector are default-enabled built-in plugins. Call inspector renders Activity as a single vertical timeline in the right panel, combining LLM and tool calls with execution notices while Chat stays visible. Activity omits user messages and assistant replies; Chat retains them. Icons distinguish activity types; each call expands its request and response in place. Activity has no event log or split detail pane. Disabling Call inspector removes inspection actions while retaining tool summaries and recorded exchange bodies. Disabling Trajectory returns its open view to Chat. Disabling Session statistics removes the composer readings and any open detail popover. Conversation history and provider measurements remain available when either plugin is enabled again.

    [builtin]
    trajectory = false
    session_stats = false
    call_inspector = false

    Every local entry needs a unique id of 1–64 lowercase letters, digits, or hyphens; trajectory, session-stats, and call-inspector are reserved. Add id to existing server entries when upgrading. Optional name supplies the settings label. An entry must specify server for a Node entry, client for a browser bundle, or both. Disabled entries are listed without loading their modules. The catalog does not send server configuration or module paths to the browser.

    Use server and client in both plugins.toml and package metadata. Rename existing path/ui configuration fields and hooks/ui package fields; old entry names are rejected. The server module's hooks callback object and the client context's ui component library retain their names.

    Install packages from npm or Git

    In Settings → Plugins, enter a source and select Install plugin:

    • npm: @scope/soma-plugin@1.2.3 (a version, tag, or range is optional).
    • Git: git+https://host/owner/repo.git#main or git+ssh://git@host/owner/repo.git#v1.
    • Local Git repository: git+file:///absolute/path/to/plugin#main.

    Git accepts a branch, tag, or commit; omitting it selects HEAD. Only committed files are installed. npm requires npm on the server's PATH and uses its registry configuration; Git requires Git and uses its configured credentials.

    A package must implement Soma's plugin contract and include prebuilt entries:

    {
      "name": "@scope/soma-counter",
      "version": "1.0.0",
      "type": "module",
      "files": ["dist"],
      "soma": {
        "id": "counter",
        "name": "Counter",
        "client": "dist/client.mjs",
        "server": "dist/server.mjs"
      }
    }

    Declare server, client, or both under one plugin ID and version. Paths must stay inside the package. Client entries use the contract below; server entries use the hook contract above. Bundle runtime dependencies into the entries, sharing React through the client context. Installation does not install dependencies or run lifecycle/build scripts. Git repositories must commit their built entries; npm packages must include them in the published archive. Packages containing symlinks or other nonregular entries are rejected.

    Successful installation copies the package under SOMA_HOME/plugins, records the exact npm version or Git commit and local entries in plugins.toml, and enables it. Client activation is immediate; server entries load at the next turn. Existing plugin IDs are rejected. Failed installs leave the existing configuration intact. Disable installed packages using the same settings switches as local plugins.

    The HTTP equivalent is POST /api/plugins/install with {"source":"@scope/soma-plugin@1.2.3"}. The response is the updated plugin inventory. Packages execute with the same trusted-code access as local plugins.

    Client plugins

    Client entries use ctx.slots.register(options, Component); update older registerView({ id, title, component }) calls to the example below.

    Built-in client plugins are separate workspace packages under plugins/. plugins/ui-trajectory owns Trajectory; plugins/ui-session-stats owns statistics calculations, composer readings, and translations. plugins/ui-call-inspector owns call lists, exchange bodies, and their translations. Each imports browser contracts from @soma-ai/plugin-sdk and shared primitives from @soma-ai/ui; the Web host lazy-loads package entries on activation. Private workspace source packages are compiled by the Web build. Check them independently with pnpm -r run typecheck.

    Configure a bundled browser ESM entry:

    [[plugins]]
    id = "turn-counter"
    name = "Turn counter"
    enabled = true
    client = "/absolute/path/to/turn-counter.mjs"
    export default {
      activate({ React, ui, slots, signal }) {
        slots.register(
          {
            name: "conversation.view",
            id: "counter",
            order: 10,
            label: { en: "Turn counter", "zh-CN": "Turn counter" },
          },
          function Counter({ thread }) {
            return React.createElement(
              ui.Chip,
              { variant: "soft" },
              `${thread?.turns.length ?? 0} turns`,
            );
          },
        );
        // Observe signal for cancellable work; return cleanup for owned resources.
        return () => {};
      },
    };

    activate(ctx) may return a cleanup function or a promise of one. Its scope owns at most eight entries per slot. ctx.slots.register(options, Component) returns an unregister function. Disabling aborts ctx.signal, removes all entries, and runs cleanup; late async activation is disposed. Failed activation or rendering removes that plugin's entries and displays the error in settings. Toggle off and on to retry.

    Client UI positions follow dsh's named-slot registration pattern. The host owns each render position; options.name selects it. Supported slots:

    SlotPositionAdditional props
    activity.panel.tabContent inside the right-hand Activity panelselection, selectCall(identity or null)
    conversation.viewMain content, selected through a topbar view buttonNone
    conversation.composer.dockBottom of the composer, below directory and keyboard hintsNone
    sidebar.footer.actionActions above Settings in the left sidebarNone
    sidebar.right.pane.tabRight panel, opened through a topbar buttonclose()
    conversation.chat.assistant-actionsActions beneath each finalized assistant messagemessage: { turnId, stepId, output }

    Activity selection is a frozen call identity (threadId, turnId, stepId, kind, and callId for tools). Register with inspectCalls: true to connect conversation call actions to the Activity tab. selectCall(identity) opens a call in place; selectCall(null) collapses its details. Unloading its selected contribution selects another registered view, or closes Activity when none remain. Activity has no event log; a single contribution renders without a tab bar.

    Set id to a unique value within the plugin and slot. order defaults to zero; lower values appear first, with ties retaining registration order. Views and panels require label, either a string or a dictionary for both locales. Unknown slots, duplicate IDs within a slot, and invalid labels are rejected. A panel closes with its close button, Escape, or the supplied close() callback; unloading its plugin also closes it.

    All components receive { thread, locale }. thread and message context are frozen copies of public snapshots, updated as execution events arrive; locale is en or zh-CN. Message actions are instantiated separately for each assistant message. Switching the selected thread remounts plugin components. This is a named-slot subset; it does not implement dsh's service injection, child-slot declarations, store framework, or plugin compatibility.

    Session statistics folds thread.turns[].steps[].output.metrics. Core records provider token usage and model/tool timing; the plugin owns aggregation and presentation. No Node hook or second event subscription is needed. The composer slot follows deepseek-harness revision 639ed015397290b3745d163aafe02ffee4aa3f84, packages/client/ui-chat/src/client/apply.ts and chat/StatsPills.tsx.

    The shared React instance supports hooks. ui exposes HeroUI v3 Button, Chip, Checkbox, Input, Label, TextArea, TextField, Alert, Tabs, Popover, and ProgressCircle using Soma's design tokens. Use their upstream compound APIs (for example, Alert.Description and Tabs.Panel) and props such as onPress, isDisabled, and isSelected.

    The server serves only the enabled entry file, up to 4 MiB. Bundle dependencies into that .mjs file; relative imports, asset directories, Node APIs, and bare package imports are not served. Use the supplied React and components rather than bundling another React runtime. Source edits require a browser reload. Client plugins run with Soma's browser origin privileges and are trusted code, not isolated sandboxes. No CSP relaxation or injected stylesheet is required.

    See ADR 0042 for the catalog and browser lifecycle boundaries.