Skip to content

Latest commit

 

History

History
234 lines (187 loc) · 11.4 KB

writing-a-plugin.md

File metadata and controls

234 lines (187 loc) · 11.4 KB

Writing a plugin

An OpenCode plugin is a folder of CommonJS JavaScript (Psychoscript) source and a plugin.toml. There is nothing to compile: the app loads the source directly, and saving a file reloads the plugin in place. The full API is in the reference; every name below links into it.

flowchart LR
  subgraph Folder["plugins/<id>/"]
    TOML["plugin.toml"]
    WIN["init.js<br/>window half"]
    APP["app.js<br/>app half (optional)"]
    MOD["*.js<br/>local modules"]
  end
  WIN -->|"ctx.Add*"| HOST["Host: contributions,<br/>services, native nodes"]
  APP -->|"ctx.Add*"| HOST
  WIN <-->|"Contracts.Provide / Use"| APP
  WIN -->|"require('./…')"| MOD
Loading

1. Lay out the folder

plugins/session-stats/
  plugin.toml
  init.js
  format.js
#:schema ../plugin.schema.json
id = "session-stats"
name = "Session stats"
version = "1.0.0"
contract = "1.15"
description = "A session's tokens, spend and last 20 tool calls"

[[stores]]
name = "show-spend"
  • contract names the contract version the plugin targets. Any 1.x host runs a 1.0 plugin.
  • entry defaults to init.js, the window half. Add app = "app.js" for an app half.
  • The #:schema line gives TOML editors completion and checks from plugin.schema.json.

2. Define a half

const plugin = require("@opencode/plugin");
const ui = require("@opencode/ui");

module.exports = plugin.defineWindow((ctx) => {
    const Layout = ctx.GetService("Layout");

    ctx.AddCommand({
        id: "open",
        title: "Session stats: Toggle panel",
        bind: "mod+shift+s",
        slash: { name: "stats" },
        run: () => {
            Layout.TogglePanel("main");
        },
    });

    ctx.AddPanel({
        id: "main",
        title: "Session stats",
        render: (view, props) => {
            return ui.text(`Session ${props.sessionId}`, { color: "text-weak" });
        },
    });
});
Half Defined with Runs Use it for
Window plugin.defineWindow in init.js Once per window UI: panels, pills, dialogs, commands
App plugin.defineApp in app.js Once per process Processes, server sources, menu bar items, shared state
  • ctx.GetService("Name") returns a typed service. A typo in the name is a TypeScript type error under plugins/tsconfig.json.
  • Each ctx.Add* call adds a contribution. The host withdraws it when the half goes away.
  • The halves share values through Contracts: Contracts.Provide("my-plugin", api) in one, Contracts.Use("my-plugin") in the other.

3. Build UI with ui.*

render: (view, props) => {
    return view.Memo("panel", `${props.sessionId}:${changed.Version()}`, () =>
        ui.col({ w: "full", pad: 16, gap: 12, fill: "bg-base" }, [
            ui.text("Context tokens", { size: 12, color: "text-weak" }),
            ui.metric({ value: total, text: format.int(total), weight: "semibold" }),
            ui.button({
                text: "Compact",
                size: "small",
                onPress: view.Handler(() => {
                    Commands.Run("session.compact");
                }),
            }),
        ])
    );
},
  • Nodes are declarative: build the tree you want, return it, and never mutate it.
  • Wrap each render in view.Memo with a version that changes only when the output should. An unchanged frame then runs no JavaScript at all.
  • Colors are semantic tokens such as "surface-1" or "status-danger". They follow the theme. Use ui.hex("#RRGGBB") only for a literal color.
  • Borders on ui.box, ui.row, and ui.col paint over the fill without taking layout space. Use ui.frame when a container's border (or borderSides) should take room in layout, snapped to device pixels at every display scale as a CSS border-box border does.
  • Long lists go in ui.virtualList, which uses 0-based indices (0..count - 1) and builds only the rows on screen.
  • Heavy views are native nodes: ui.terminalSurface, ui.browserSurface, ui.codeView, ui.diffView, ui.fileTree, ui.markdown and ui.genUi. Get their handles from a service, such as Terminal.Create or Workspace.OpenDocument.

4. React to events and do async work

Request a redraw when what you draw changes. A render can read a local variable, but the host cannot observe writes to it. After changing a value used by a panel, label, badge, menu, or command's enabled or hidden callback, fire a signal created with ctx.CreateSignal() or call .Refresh() on the contribution. Include the signal's .Version() in any view.Memo that reads the value. Update the value before notifying the host. Do not request a redraw for a retry deadline, a cache fill that nobody displays, or a duplicate answer.

const changed = ctx.CreateSignal();
let title = "";
function setTitle(nextTitle) {
    if (title === nextTitle) return;
    title = nextTitle;
    changed.Fire();
}

Reactive service reads keep their own invalidation: for example, a render that reads Terminal.List can follow a host-side title change. If you copy the title into plugin state and draw that copy instead, notify on changes to the copy.

const Server = ctx.GetService("Server");
const changed = ctx.CreateSignal();

Server.OnEvent("session.updated").Connect((event) => {
    changed.Fire(); // redraws, and bumps changed.Version()
});

function refresh(sessionId) {
    task.spawn(async () => {
        const res = await Server.RequestAsync("GET", `/api/session/${sessionId}`);
        if (res.ok) {
            changed.Fire();
        }
    });
}
sequenceDiagram
  participant H as Async handler or task
  participant S as Host service
  participant W as Worker thread
  H->>S: await Server.RequestAsync(...)
  S->>W: send off the UI thread
  Note over H: Promise pending, the frame goes on
  W-->>S: response
  S-->>H: resolve with ServerResponse
  H->>H: changed.Fire() redraws
Loading
  • Every event source is a Signal: .Connect, .Once and .Wait (returns a Promise). Connections end with the half.
  • Methods named …Async return a Promise<T>. Call them with await from an async handler, a signal callback or a task function.
  • Render callbacks (render, label, show, match) must be synchronous. Read cached data there, such as Server.Resource.
  • task.delay and await task.wait cost no CPU while they wait.

5. Keep state

State Use
Saved with the app, shared by every window Store.Value and Store.SessionValue; declare the names under [[stores]]
Text the user types ctx.CreateEditor with ui.field; text, caret and undo survive a reload
Plain JS objects Locals in the setup function; ctx.BindHotState carries them across a hot reload

6. Speak the user's language

Put a catalog per language in locales/<id>.json, flat objects of message keys in the app's format: {{name}} placeholders, and plural forms as key.one, key.other (CLDR categories).

{ "stats.title": "Session stats", "calls.one": "{{count}} tool call", "calls.other": "{{count}} tool calls" }
const I18n = ctx.GetService("I18n");
ui.text(I18n.T("stats.title"));
ui.text(I18n.T("calls", { count: calls.length }));
ui.text(I18n.Number(cost, { style: "currency" }));
ui.text(I18n.Date(session.created, "dateTime"));
  • I18n.T looks up the plugin's locales/<lang>.json, falls back to locales/en.json, then to the host's own message catalog (singular and plural keys), and finally to the key itself. With a number count, it picks the plural form the language uses. Built-in plugins whose copy already lives in the host catalog do not need to duplicate locales/*.json files.
  • Number, Date, RelativeTime, RelativeDay and List write values as the app writes them in the interface language. For currency amounts that should follow the locale's full currency pattern (such as 1.234,50 $ or 1,84 USD) rather than a compact $ prefix, pass localePattern: true to I18n.Number.
  • I18n.Direction() says whether the language reads right to left. Everything drawn redraws when the language changes; connect I18n.Changed for state you keep.

7. Check it

Run these from the repository root:

tsc --noEmit -p plugins/tsconfig.json
scripts/guardrails.sh
  • plugins/tsconfig.json enables allowJs and checkJs against plugins/opencode.d.ts and plugins/types/*.d.ts, giving VS Code and tsc full IntelliSense and type checking on plain .js plugin files.
  • CommonJS modules only: Psychoscript uses require("./foo") / require("@self/foo") and module.exports = .... Do not use ES module import / export syntax; scripts/guardrails/arch-check.mjs rejects it on built-in plugins.
  • JSDoc types: Add /** @type {DiffMode} */ or /** @param {PanelProps} props */ whenever you want stricter checking in a .js file.

8. Run and install it

A plugin is its folder and nothing else: plugin.toml, *.js, locales/*.json and icons/*.svg. The app reads no other file in it, and never loads native code from it.

Where How it runs
opencode-desktop --plugin-dir <folder> A plugin folder, or a folder of them, for this launch. It runs without asking.
<data>/plugins/<id>/ Installed for every launch. The first run asks. It can't take a built-in's id.
<config>/plugins-override/<id>/ Replaces the built-in with the same id. The first run asks.

<data> and <config> are %APPDATA%\rune-opencode on Windows and ~/Library/Application Support/rune-opencode on macOS; Linux follows XDG.

  • Trust. A plugin can read and change files, run programs and reach the network through its services. Before an installed or overriding plugin first runs, the app asks Enable plugin ""?. The answer holds for the plugin's files as they are: the app remembers their SHA-256, and a changed file asks again, also when you reload the plugin after editing it. The plugin runs once the answer is saved, so a crash can't run it under an OK the app then forgets. Not now asks again on the next launch. Turning the plugin off in Settings forgets the OK: turning it on asks again.
  • Reload. Saving a file reloads the plugin in place in a development build, or in any build started with --plugin-hot. Settings › Extensions › Plugins also has Reload, and a switch that turns the plugin off.
  • Inspect. opencode-desktop --plugin-index prints every plugin, where it runs from, its state and what it contributed.

Change the contract

contract.json is the single source of truth. After you edit it, regenerate everything and check that nothing drifted:

cargo run -p opencode-plugin-spec -- --write
cargo run -p opencode-plugin-spec -- --check
Output Read by
plugins/opencode.d.ts, plugins/types/*.d.ts, plugins/tsconfig.json TypeScript (tsc) and VS Code IntelliSense
plugins/plugin.schema.json TOML editors
crates/opencode-plugin-spec/docs/api.md People and models
crates/opencode-plugin-spec/src/generated/*.rs The host: tokens, enums, spec records, node props, registry, manifest

Keep a change within the versioning rules: a 1.x contract only adds.