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
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"contractnames the contract version the plugin targets. Any 1.x host runs a 1.0 plugin.entrydefaults toinit.js, the window half. Addapp = "app.js"for an app half.- The
#:schemaline gives TOML editors completion and checks fromplugin.schema.json.
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 underplugins/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.
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.Memowith 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. Useui.hex("#RRGGBB")only for a literal color. - Borders on
ui.box,ui.row, andui.colpaint over the fill without taking layout space. Useui.framewhen a container's border (orborderSides) should take room in layout, snapped to device pixels at every display scale as a CSSborder-boxborder 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.markdownandui.genUi. Get their handles from a service, such asTerminal.CreateorWorkspace.OpenDocument.
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
- Every event source is a
Signal:.Connect,.Onceand.Wait(returns aPromise). Connections end with the half. - Methods named
…Asyncreturn aPromise<T>. Call them withawaitfrom anasynchandler, a signal callback or ataskfunction. - Render callbacks (
render,label,show,match) must be synchronous. Read cached data there, such asServer.Resource. task.delayandawait task.waitcost no CPU while they wait.
| 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 |
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.Tlooks up the plugin'slocales/<lang>.json, falls back tolocales/en.json, then to the host's own message catalog (singular and plural keys), and finally to the key itself. With a numbercount, it picks the plural form the language uses. Built-in plugins whose copy already lives in the host catalog do not need to duplicatelocales/*.jsonfiles.Number,Date,RelativeTime,RelativeDayandListwrite values as the app writes them in the interface language. For currency amounts that should follow the locale's full currency pattern (such as1.234,50 $or1,84 USD) rather than a compact$prefix, passlocalePattern: truetoI18n.Number.I18n.Direction()says whether the language reads right to left. Everything drawn redraws when the language changes; connectI18n.Changedfor state you keep.
Run these from the repository root:
tsc --noEmit -p plugins/tsconfig.json
scripts/guardrails.shplugins/tsconfig.jsonenablesallowJsandcheckJsagainstplugins/opencode.d.tsandplugins/types/*.d.ts, giving VS Code andtscfull IntelliSense and type checking on plain.jsplugin files.- CommonJS modules only: Psychoscript uses
require("./foo")/require("@self/foo")andmodule.exports = .... Do not use ES moduleimport/exportsyntax;scripts/guardrails/arch-check.mjsrejects it on built-in plugins. - JSDoc types: Add
/** @type {DiffMode} */or/** @param {PanelProps} props */whenever you want stricter checking in a.jsfile.
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-indexprints every plugin, where it runs from, its state and what it contributed.
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.