An OpenCode plugin is a folder of --!strict Luau source and a plugin.toml. There is nothing to compile: the app loads the source, 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.luau<br/>window half"]
APP["app.luau<br/>app half (optional)"]
MOD["*.luau<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('@self/…')"| MOD
plugins/session-stats/
plugin.toml
init.luau
format.luau
#:schema ../plugin.schema.json
id = "session-stats"
name = "Session stats"
version = "1.0.0"
contract = "1.0"
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.luau, the window half. Addapp = "app.luau"for an app half.- The
#:schemaline gives TOML editors completion and checks fromplugin.schema.json.
--!strict
local plugin = require("@opencode/plugin")
local ui = require("@opencode/ui")
return plugin.defineWindow(function(ctx)
local Layout = ctx:GetService("Layout")
ctx:AddCommand({
id = "open",
title = "Session stats: Toggle panel",
bind = "mod+shift+s",
slash = { name = "stats" },
run = function()
Layout:TogglePanel("main")
end,
})
ctx:AddPanel({
id = "main",
title = "Session stats",
render = function(view, props)
return ui.text(`Session {props.sessionId}`, { color = "text-weak" })
end,
})
end)| Half | Defined with | Runs | Use it for |
|---|---|---|---|
| Window | plugin.defineWindow in init.luau |
Once per window | UI: panels, pills, dialogs, commands |
| App | plugin.defineApp in app.luau |
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 type error.- 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 = function(view, props)
return view:Memo("panel", `{props.sessionId}:{changed:Version()}`, function()
return 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(function()
Commands:Run("session.compact")
end),
}),
})
end)
end,- 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 Luau 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 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 Luau local, but the host cannot observe writes to that local. 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.
local changed = ctx:CreateSignal()
local title = ""
local function setTitle(nextTitle: string)
if title == nextTitle then return end
title = nextTitle
changed:Fire()
endReactive 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. A coroutine resuming is not a redraw request. Installed plugins, override folders, and --plugin-dir plugins using contract 1.0 keep their legacy implicit invalidation; they do not need to migrate to keep working. Do not rely on that fallback in new code.
local Server = ctx:GetService("Server")
local changed = ctx:CreateSignal()
Server:OnEvent("session.updated"):Connect(function(event)
changed:Fire() -- redraws, and bumps changed:Version()
end)
local function refresh(sessionId: string)
task.spawn(function()
local res = Server:RequestAsync("GET", `/api/session/{sessionId}`)
if res.ok then
changed:Fire()
end
end)
endsequenceDiagram
participant H as Handler or task
participant S as Host service
participant W as Worker thread
H->>S: Server:RequestAsync(...)
S->>W: send off the UI thread
Note over H: coroutine yields, the frame goes on
W-->>S: response
S-->>H: resume with ServerResponse
H->>H: changed:Fire() redraws
- Every event source is a
Signal::Connect,:Onceand:Wait. Connections end with the half. - Methods named
…Asyncyield. Call them from a handler, a signal callback or ataskfunction. - Render callbacks (
render,label,show,match) must not yield. Read cached data there, such asServer:Resource. task.delayandtask.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 Luau tables | 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" }local I18n = ctx:GetService("I18n")
ui.text(I18n:T("stats.title"))
ui.text(I18n:T("calls", { count = #calls }))
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:
luau-lsp analyze --platform=standard --definitions=@opencode=plugins/opencode.d.luau plugins
selene plugins
stylua --check --glob "**/*.luau" --glob "!**/*.d.luau" pluginsluau-lsp1.70 or later checks types under both of Luau's solvers. In an editor, addplugins/opencode.d.luauto theluau-lsp.types.definitionFilessetting.plugins/.luaurcalready turns on strict mode and maps@opencode/*.- Module
requirepaths (@self/vs./): the host follows Luau's standard require-by-string rules (the same rulesluau-lspuses). Becauseinit.luaurepresents its folder as a module,@self/formatresolves a child inside the plugin folder (format.luau), while./formatfrominit.luausteps to the folder's parent and fails. Inside a sibling module such asview.luau, the module itself is already a child of the folder, so./formatresolves a peer in the same folder (format.luau), while@self/formatwould look forview/format.luauand fail. - Luau's older type solver widens string unions in two places. Annotate the local (
local mode: DiffMode = store:Get()), and cast a union-typed store throughany:Store:Value("mode", "split" :: any) :: StoreValue<DiffMode>.
The samples in samples/ pass all three checks: session-stats (command, setting, panel, virtual list), goal (composer pill and popover, server events), workbench (every native node, MCP tool, link handler) and wsl-lite (app half, processes, server source, dialog).
The built-in plugins/usage/ plugin implements a complete pure-UI modal dialog (command palette entry, live HTTP fetch with cached refresh and timeout, explicit state machine, localized formatting, countdown ticking, and model-picker budget badges) without any Rust feature crate:
plugins/usage/
plugin.toml # contract = "1.5", zero [[stores]]
init.luau # window half: command + dialog wiring, async fetch, timeout, countdown ticker, model badges
machine.luau # explicit state machine (loading | refreshing | ready | signed-out | failed)
limits.luau # wire JSON parser, model-budget calculation, and sorted view model (stable tie-breaking via index)
view.luau # declarative ui.* layout over semantic tokens (using ui.frame for border-box panels)
--!strict
local plugin = require("@opencode/plugin")
local ui = require("@opencode/ui")
local machine = require("@self/machine")
local view = require("@self/view")
return plugin.defineWindow(function(ctx)
local I18n = ctx:GetService("I18n")
local Composer = ctx:GetService("Composer")
local Server = ctx:GetService("Server")
local Dialog = ctx:GetService("Dialog")
local System = ctx:GetService("System")
local changed = ctx:CreateSignal()
local openState: machine.OpenState? = nil
local timeoutThread: thread? = nil
local function sync(effect: machine.Effect)
local cur = openState
if cur == nil then return end
if not Server:IsLive() then
machine.step(cur, { type = "loaded", attempt = effect.attempt, info = nil })
changed:Fire()
return
end
timeoutThread = task.delay(machine.TIMEOUT_S, function()
if openState ~= nil then
machine.step(openState, { type = "timed-out", attempt = effect.attempt })
changed:Fire()
end
end)
task.spawn(function()
local res = Server:RequestAsync("GET", `/api/experimental/usage/limits?location%5Bdirectory%5D={Server:EncodeUri(cur.directory)}`)
-- Guard against stale attempts and closed dialogs before mutating openState.
if openState == cur then
machine.step(cur, res.ok and parseEvent(res, effect.attempt) or { type = "failed", attempt = effect.attempt })
changed:Fire()
end
end)
end
local cmdReg: Contribution? = nil
local dlgReg: Contribution? = nil
local function register()
if cmdReg then cmdReg:Withdraw() end
if dlgReg then dlgReg:Withdraw() end
cmdReg = ctx:AddCommand({
id = "view",
title = I18n:T("command.usage.view"),
description = I18n:T("command.usage.view.description"),
order = 560,
enabled = function() return Composer:Active() end,
run = function()
local state, effect = machine.open(Composer:Directory(), Composer:Model())
openState = state
changed:Fire()
Dialog:Open("main")
sync(effect)
end,
})
dlgReg = ctx:AddDialog({
id = "main",
title = I18n:T("usage.title"),
size = "normal",
layer = "standard",
radius = 12,
hideScrollbar = true,
render = function(v, props)
if openState == nil then return nil end
local nowMs = System:Now()
return v:Memo("usage-dialog-body", `{changed:Version()}:{openState.load.status}:{I18n:Locale().id}`, function()
return view.render(I18n, openState.load, nowMs, {
onRetry = v:Handler(function() ... end),
})
end)
end,
onDismiss = function()
openState = nil
if timeoutThread then task.cancel(timeoutThread) end
end,
})
end
register()
I18n.Changed:Connect(register)
end)Key patterns from this port:
- Overlay stack, layer, and focus restoration are host-managed. Calling
Dialog:Open("main")pushes the dialog onto the shell'sOverlayStack(so pressingEscapeover Settings or another modal pops only the top dialog and restores focus to where it was before the dialog opened). Setlayer = "standard"onDialogSpecfor ordinary dialogs that should sit beneath elevated system recovery and server dialogs (the default"elevated"stays above them). Useui.dialogHeaderfor the standard title bar and close button. - Explicit state machine + attempt fencing. Every async fetch carries a monotonically increasing
attemptnumber checked inmachine.stepso slow responses or expiredtask.delaytimeouts from earlier attempts cannot overwrite a retry or a closed dialog. - Offline/fixture detection. Check
Server:IsLive()before issuing HTTP requests so offline fixture windows skip network calls and immediately show their offline state. - Runtime language updates. Because
CommandSpec.title/descriptionandDialogSpec.titleare evaluated when registered, wrap registration in a helper and re-run it onI18n.Changedafter calling:Withdraw()on the previousContributionhandles. - Host catalog reuse. Because all
usage.*andcommand.usage.*strings already live in the host's catalog (crates/opencode-i18n),plugins/usage/ships nolocales/*.jsonfiles and letsI18n:Tfall back directly to the host catalog. - Border-box panels across DPI scales. Panels use
ui.frameso their0.5pt border participates in layout and snaps to whole device pixels identically at 1x, 1.25x, 1.5x, and 2x display scales. - Model-picker annotations from one source of truth. The plugin connects to
Composer.PickerChanged, refreshes limits when"model"opens, and publishes inline model badges viaModels:SetBadgesoverModels:List(), sharing one fetch, parser, and cache between the dialog and the model picker. - JSON
nullvs missing fields. Luau represents JSONnullasnil, so a server response of{"data": null}looks identical to{}inres.json; inspectres.textwhen an explicitnullcarries semantic meaning (such as signed-out vs malformed response). - Stable sorting. Luau's
table.sortis not guaranteed stable; tie-break equal keys on their original 1-based index when order matters.
A plugin is its folder and nothing else: plugin.toml, *.luau, .luaurc, 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.luau, plugins/types/*.luau, plugins/.luaurc |
luau-lsp and editors |
plugins/plugin.schema.json |
TOML editors |
plugins/opencode-selene.yml |
selene |
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.