The plugin API

A plugin is an ES module whose default export is the plugin: definePlugin({...}), or runPlugin(...) for one written with Effect. It runs in a Bun process of its own under an OS sandbox the app compiles from its grants (../AGENTS.md, One runtime): one runtime per plugin, so no two plugins share globals or native access. It never draws; it pushes element trees and the kernel renders them with GPUI.

// main.tsx
import { definePlugin } from "divergence";

export default definePlugin({
  views: {
    hello: {
      slot: "right",
      title: "Hello",
      state: { count: 0 },
      render: ({ state, set }) => (
        <column padding="medium">
          <text style="heading">Hello</text>
          <text style="body">Clicked {state.count} times</text>
          <button id="hello-click" label="Click me" onClick={() => set({ count: state.count + 1 })} />
        </column>
      ),
    },
  },
});

The manifest says "pluginApi": ">=5 <6" and "main": "main.tsx". examples/hello-panel is this plugin with a command and a slash command.

A plugin may split its code over sibling modules and import them by relative path (import { fold } from "./grouping.ts"), and import its .json files as default exports. The runtime has the plugin's own modules, the built-in modules divergence, divergence/jsx-runtime, divergence/effect, divergence/services, zod and effect/<Module> (effect/Effect, effect/Schema, ...; not the effect barrel), and the npm packages the plugin ships in its node_modules (declared in its package.json, pinned by its committed bun.lock, installed for production with no install scripts when the plugin is packaged). A package that is not there fails the load with its name. Everything reloads when a file is saved: each load runs a new copy of the plugin's files (a source generation), and a reload checks the new version first without running any of it.

TypeScript (.ts, .mts, .tsx) and JSX (.jsx, .tsx) are compiled by Bun, and errors point at the source's lines. Types from another module come with import type; a .d.ts file has no code and is never loaded. tsconfig.json type-checks the plugins (pnpm -C plugins exec tsc -p tsconfig.json).

What the sandbox means

The helper process can open no file, socket or program, whatever the code in it does (macOS: Seatbelt; Linux: Landlock, seccomp and namespaces; Windows has no sandbox yet, and Settings says "Sandbox not available"). Everything a plugin does outside its own views goes through the host, which checks the plugin's grants first:

  • files, the network, programs and the environment through api.fs, api.net, api.process and api.env (below);
  • the app's data through api.host.* (host-api.md);
  • the window through api.host.kernel(...), api.notify, api.openUrl and the pickers.

There is no fetch, require, process or fs global; the API objects are always there, and a call without the grant rejects at once with PermissionNotGranted (see Permissions).

TypeScript and Effect

A plugin may run its work as an Effect program. Its entry is the default export runPlugin(program) (or runPlugin(layers, program)), and its views are registered through the Views service with the same definitions definePlugin takes:

// main.tsx
import * as Effect from "effect/Effect";
import { Plugin, Views, runPlugin } from "divergence/effect";

const program = Effect.gen(function* () {
  const plugin = yield* Plugin;
  const views = yield* Views;
  yield* views.add("hello", {
    slot: "right",
    title: plugin.name,
    state: { count: 0 },
    render: ({ state, set }) => (
      <column padding="medium">
        <text style="heading">Hello</text>
        <text style="body">Clicked {state.count} times</text>
        <button id="hi" label="Click" onClick={() => set({ count: state.count + 1 })} />
      </column>
    ),
  });
});

export default runPlugin(program);

divergence/effect provides one service per thing the api offers: Plugin, Host, Kernel, Events, App, Views, Layouts, Commands, Slash, Palette, Tools, Agents, Hooks, Fs, Net, Process, Env, Storage, Settings, Notify and Services. Every registration is scoped: when the plugin unloads or reloads the scope closes, and each view, listener, process and fork is released, so there is no api.onUnload bookkeeping. A handler in a tree runs an effect with ctx.run(effect). The official plugins are written this way; plans/typed-plugins/STYLE.md is the style guide, and plugins/examples/counter-service with counter-panel is a complete provider and consumer pair.

Plugin code never calls Effect.runPromise or Effect.runFork itself: runPlugin owns the runtime. Host failures are the tagged errors PermissionNotGranted, NeedsReview and HostCallFailed.

Tests run in Node, not in the sandbox. plugins/testing/register.mjs is a resolver hook (pnpm -C plugins test, or node --import plugins/testing/register.mjs --test <files>) that compiles .tsx and .jsx modules with esbuild (automatic JSX, import source divergence), picks up *.test.tsx as well, and resolves divergence and divergence/jsx-runtime to the real element factories and divergence/effect, divergence/services and divergence/effect/testing to the built-in sources, with zod and effect/* from plugins/node_modules at the versions the helper bundles. testLayer({ host?, fs?, process?, net?, storage?, settings? }) from divergence/effect/testing replaces the host side with in-memory fakes that record every call.

Imports follow the same rules as everywhere else: own modules with their extension (./views.ts), another plugin's contract only with import type, and the effect barrel is refused (effect/Effect, never effect).

api

Member Description
api.plugin this plugin's name (its folder)
api.id its manifest id (local:<folder> without one)
api.host the host API (see host-api.md); every call returns a Promise and needs the permission listed there (see Permissions below)
api.host.kernel(method, params) kernel calls: pick_folder, pick_images, copy_text, save_text, open_in.apps, open_in, attach_image, image_data, forget_image, editor.file, plugins, reload_plugin, set_plugin_enabled, quit, commands, run_command, keybindings.change, keybindings.open, keys.record, keys.record_cancel, context.set, context.layout, notification.show, menu.entries, palette.providers, palette.search, palette.run, settings_view, theme, themes, and the terminals and system notifications below (see Commands and keys, Settings)
api.fs, api.net, api.process, api.env files, network, programs and environment (see below)
api.app.onChange(fn) receive the new app state on local changes and kernel pushes; returns an unsubscribe
api.host.call(method, params, { signal }) call a host wire method; abort cancels the outstanding request
api.host.kernel(method, params, { signal }) call a kernel method; abort cancels the outstanding request
api.app.state() { workspaceId, chatId, route, shared }
api.app.update(patch) patch the app state (shared merges); this plugin reads its own change back at once, every other plugin a moment later
api.app.select(chatId, workspaceId) focus a chat and route to chat
api.app.bind(key, value) an opaque component boolean resolved from native app state; optional on older hosts, so fall back to the current boolean
api.app.project({ key, cases, default? }) a scalar read whose render dependency is its evaluated output; optional on older hosts
api.app.bind({ key, cases, default? }) the same finite projection bound to a native property; available when app.project exists
api.app.route(name) change the center route
api.app.share(key, value) put a value in shared for other plugins
api.notify(message, level?) in-app notification (info, warning, error)
api.toast(id, message, action, onDismiss?) temporary, replaceable toast with a button; the action has label and onClick
api.dismissToast(id) dismisses the plugin’s toast without calling its handlers
api.focus(id, option?) give the keyboard to an input, editor, tree or focusable element (a button, a div with focusable or onKeyDown) of this plugin's tree, by node id; one not drawn yet takes it when it is. The current runtime and kernel apply view updates requested before focus first. A combobox or select on screen opens instead, as a press on its trigger does, and with option the submenu of the row whose value that is (older apps reach only inputs and editors, ignore option and leave a combobox or select closed)
api.openUrl(url) open an http, https or mailto link in the system browser, in answer to the user (see Permissions); resolves { opened: true }, or { opened: false, reason } for a link the kernel kept closed
api.pickFolder() native folder picker; resolves { path }
api.sleep(ms) resolves after ms milliseconds (a timer)
api.pickImages() native file picker; resolves { paths }
api.attachImage(path) hold an image file; resolves { id, name, mimeType, bytes, path }
api.attachImageData(base64, name) the same for bytes (an image already in a transcript)
api.imageData(id) the held bytes as { mimeType, name, data } (base64), for a prompt block
api.forgetImage(id) let a held image go
api.slashCommands() every plugin's /command: [{ name, plugin, description, inputHint }]
api.runSlash(name, input, context) run one in its plugin; resolves `{ action: "prompt"
api.toolRenderers() every plugin's tool renderers: [{ plugin, name, kind }]
api.renderTool(call) <tool_view call={call} id={call.id} /> when a plugin renders that call, else null
api.artifactRenderers() every plugin's document renderers: [{ plugin, type, version }]
api.views.add(key, definition) register a view made later (one per pane, per open item); returns { id, update(), remove() }. The definition is a view's (slot, render, state, on, order, title, flyout), and key is its identity across reloads (see Views)
api.layouts this plugin's tabs and the layout they live in: open, close, current, onChange, split, place, focus, viewName, kinds, redraw (see Tabs and layouts)
api.on(event, fn, options?) listen to host events ("*" for all); for "agent", options.kinds names the agent event kinds wanted; returns a function that stops listening
api.onUnload(fn) run fn({ reloading }) when the plugin unloads or reloads (see Cleanup); returns a function that removes it
api.command({ id, run(api, { applied, phase }) }) runs a command the manifest declares (contributes.commands, with its title, key, when and optional held lifecycle); an id the manifest does not declare throws (see Commands and keys); returns { remove() }
api.settings the plugin's own settings: get(key?), set(key, value), onChange(fn), secret(key) (see Settings)
api.context.set(key, value) a context key when expressions read, named <plugin name>.<key>
api.palette.provider({ id, prefix, title?, search(query), run(item) }) a mode of the command palette (see Commands and keys)
api.slash({ name, description?, inputHint?, run(input, context, api) }) composer /name; returns { remove() }
api.toolRenderer({ kind?, name?, render(call) }) draw the tool calls of that name or kind (see Tool renderers)
api.artifactRenderer({ type, version, render(artifact, ctx) }) draw this plugin's saved documents in native views; returns { remove() } (see Artifact renderers)
api.tools.register(tool) a tool every agent can call (tools.md); needs tools.provide. Its run(input, ctx) can show subagents under the call with ctx.subagent.start(...) (tools.md, Subagents)
api.models.list(options?), api.models.prompt(options) the enabled agents with their models and efforts, and one prompt through one of them in a hidden session (see Models and subagents); need models.use
api.subagents.defineType(type), .types(), .run({ type, input }, ctx) subagent types the main agent can start (see Models and subagents); defineType and run need models.use
api.mentions.set(list), api.mentions.list() what this plugin offers after @ in the composer, and every plugin's offers (see Composer mentions)
api.hooks.on(hook, fn) before_prompt, after_turn, tool_call, tool_approval (see Hooks)
api.agents.register(agent) an agent (see Agents); needs agents.provide. Returns { emit(event), unregister() }
api.agents.unregister(id) remove an agent this plugin registered; the host stops it and its sessions end. Returns whether it was registered
api.services.provide(def, impl) register a service the manifest declares in provides; resolves { error(tag, fields), emit(event, payload), remove() } (see Services)
api.services.get(name) a declared service's client: client.method(params, { signal }?) calls it (and client.method.result(...) resolves `{ ok, value
api.services.available(name) whether a provider runs, as the host last said
api.services.when(name, fn) run fn(client) on every change of the service's availability; what it returns cleans up the previous run. Returns the unsubscribe
api.paths.data the absolute path of the plugin's own data folder (the data scope of its fs grants); null in a runtime that has none

The web globals a plugin may expect are there: setTimeout, clearTimeout, setInterval, clearInterval, queueMicrotask, TextEncoder, TextDecoder (UTF-8), atob, btoa, AbortController, AbortSignal, Headers, performance.now(), console, structuredClone (plain values, arrays, Date, RegExp, Map, Set, typed arrays, ArrayBuffer and errors, with cycles; a function or a symbol throws DataCloneError) and crypto: crypto.randomUUID() (a version 4 UUID) and crypto.getRandomValues(typedArray) (an integer typed array of at most 65 536 bytes). Their random values come from a ChaCha20 generator the host seeds with 32 bytes of the operating system's randomness at every load, so they are as good as the system's for ids, nonces and secrets.

Terminals

The kernel runs the shells; a plugin owns the interface around them (plugins/terminal/ is the built-in one). A build without terminal support answers unknown kernel method, so a plugin that may run on an older build should call terminal.list once before it registers its views.

Call Answer
terminal.create({ cwd, workspaceId, title?, command?, args? }) the new terminal: { id, title, cwd, workspaceId, running, exitCode }
terminal.list() { terminals: [...] }
terminal.close({ id }) ends the shell and everything it started
terminal.rename({ id, title }) a name of the user's own; an empty title gives the shell's own back
terminal.write({ id, data }) writes to the shell's input
terminal.focus({ id }) gives it the keyboard the next time it is drawn

What happens to terminals arrives as the host event terminal (events.md).

A toast belongs to the plugin and its id. Showing it again replaces the previous toast and restarts its countdown. Clicking its button runs onClick once; expiration or dismissal runs onDismiss once. Both close the toast in every window. A callback from a replaced toast is ignored. Older app runtimes do not expose toast or dismissToast, so plugins supporting them must check for these methods.

System notifications

notification.show({ chatId, title, body, unlessFocused? }) posts a system notification about a chat, with title over body, and needs chats.read, since it shows the chat outside the window. Clicking it brings the window forward and opens the chat; a newer notification about the same chat replaces the older one, and coming back to the window takes away the ones posted while the user was elsewhere. With unlessFocused: true nothing is posted while a window of the app has the focus, which is what a plugin asks for a chat the user already sees. On macOS the first notification asks the user for permission, and none shows while it is not granted; on Linux and Windows the call does nothing for now. An older app answers method not found: kernel/notification.show, which a plugin takes as no notification. The chat plugin uses it for chats that finish, fail or ask something while the user cannot see them (plugins/chat/notifications.ts).

Views

A view is a definition under a key: views in definePlugin, or api.views.add(key, definition) for one made later.

definePlugin({
  views: {
    chats: { slot: "left", order: 0, title: "Chats", on: ["chat_changed"], state: { filter: "" }, render: (ctx) => <ChatList {...ctx} /> },
  },
});

ctx.state is the view's state: it starts as the definition's state and survives draws and reloads. It is read-only; ctx.set(patch) merges a patch into it and draws the view again, and a patch that changes nothing draws nothing. ctx.update() draws the view again for state the view reads from somewhere else. ctx.app is the app state. on lists the host events that draw the view again; "app_state" draws it on app state changes; with no list, every non-agent host event and every app state change draws it. Agent events (agent) only draw views that ask for them, and agent-only renders batch for up to 16 ms. User callbacks, app state and other non-agent messages make pending rendering immediately eligible; later agent events cannot postpone it. Input callbacks, commands and app-state dispatch promote the views they touch synchronously; ordinary host notifications and replies preserve pending render order, so repeated redraws cannot overtake unfinished views. Messages retain FIFO order. The runtime alternates bounded message and render work, reuses a view's latest state and carries unfinished rendering to the next service turn. Each part yields after four milliseconds of complete entries or views, so an indivisible expensive handler or view can take longer. Views in the same slot stack top to bottom in order.

An app state change draws a view again only when its last render read what changed: the runtime records what the render reads of ctx.app (and of api.app.state() while it renders), by key: route, chatId, workspaceId, and each key of shared. A view that reads ctx.app.shared.rightPanel does not draw again when the rail's hovered icon (shared.rightPanelPreview) changes. Listing the keys of shared (Object.keys, a spread) depends on all of shared, and listing the state's own keys on everything. A value the view keeps from an app state it read elsewhere (an api.app.onChange listener) is not tracked: call ctx.update() or the handle's update() when it changes.

The runtime decides when a view renders, and sends each new tree to the kernel. A view id is unique in the app (each plugin has its own range), so <view view={id} /> can draw another plugin's view, and <view plugin="tabs" name={name} /> finds one by its plugin and key (a tab another plugin draws; see Tabs and layouts).

A retained view can be selected locally with <view view={fallback.id} select={{ key: "chatId", cases: { [chatId]: { view: pane.id, focus: "prompt-id" } } }} />. The key is route, workspaceId or chatId. The renderer reads that field from its current app state and chooses the matching view during the input frame, without waiting for another plugin tree. The optional focus names the input that receives the keyboard when that selection becomes visible or changes; unrelated app-state updates do not move focus. Nested selectors can choose a route and then a chat. A missing case uses select.default when supplied, otherwise the ordinary static view reference, so the plugin still owns loading and error presentation. A default of { view: 0 } hides that branch, for example when a route selector leaves the chat route. Older renderers ignore select and use that same static reference. Every case keeps the callbacks and retained state of its own registered view; removing a case does not remove that view's handle. A root view reference preserves its selected view's shell layout: title regions still span their panes, overlays stay outside the strip's flow, and panes keep their own surface.

Return null to render nothing.

A view in the right slot is also what the rail shows when its plugin's icon is hovered. By default that fly-out has the shape of the docked column; flyout gives it one of its own:

api.views.add("pad", { slot: "right", render, flyout: { width: 864, height: 468, align: "bottom" } });

align is top (level with the top of the rail icon) or bottom (level with its foot, for an icon low on the rail). The kernel keeps the window inside the app window. A fly-out with a shape of its own can show beside a pinned panel. Every fly-out closes a moment after the pointer leaves it, even while the keyboard is inside it; the keyboard is let go with it.

A reload keeps a view when the new code registers it again under the same key. The view keeps its id, what the kernel holds for it (text in inputs, the keyboard focus, open lists, scroll) and its state: a field the old state has keeps its value, a field only the new definition has takes its starting value, and a field the new definition dropped goes away. Until the reloaded plugin's host calls settle (at most one second), its runtime sends no trees and the kernel keeps the old ones on screen, so a plugin that loads its data again does not show an empty frame. Its views still render in that time, so data a render asks for loads too. An input whose live text differs from the value the first new tree passes keeps the live text and the caret, and reports the text through onChange.

A view may be registered at any time, not only when the plugin loads, and the handle's remove() unregisters it. A view in a slot the shell does not place (the chat plugin uses pane) is drawn only where another view embeds it with <view view={handle.id} />. Each view is its own render unit: its own dirty flag, its own retained transcript, markdown and split state. That is how a task's panes re-render one pane while a chat streams into it.

One plugin API

The app runs plugin API 5 and nothing else. A manifest whose pluginApi range does not admit 5, or that has none, fails to load with "this plugin was written for plugin API <n>; this app runs plugin API 5", and Settings shows that under the plugin. The entry module's default export must come from definePlugin(...) or runPlugin(...); any other fails the load with "the entry module's default export must be definePlugin(...) or runPlugin(...)".

definePlugin takes views (by key), commands (handlers by the command id the manifest declares), slash (slash commands by name), tabs (tab kinds by name, see Tabs and layouts) and activate(api), which runs after everything else in the object is registered and is where events, services, tools, hooks, agents and views made later go. What activate returns, if a function (or a Promise of one), runs at unload.

Views in JSX and div

A module whose name ends in .tsx or .jsx may contain JSX. The runtime compiles it with the automatic JSX transform and the import source divergence, whatever configuration the plugin ships, so there is nothing to set up and no build step. JSX ends in h(type, props, ...children), the factory every tree comes from, so a view in JSX produces the plain objects the kernel reads.

const row = (item: Item) => (
  <div key={item.id} display="flex" alignItems="center" gap={6} padding="small" borderRadius="sm" cursor="pointer" hover={{ background: "hover" }} onClick={() => open(item)}>
    <icon name="file" small tone="muted" />
    <text style="body" size="xs" truncate>{item.name}</text>
  </div>
);

A lower-case tag is a node the kernel draws (div, text, button, scroller, split, tool_view and the rest of JSX.IntrinsicElements), with the props its interface in divergence.d.ts gives it, so a misspelled tag or prop is a type error. A capitalised tag is a component: a function h calls with { ...props, children }. A component of the ui plugin (<item>, <card>, Components below) is a lower-case tag like a native node, because the kernel expands it. Text and {expressions} between tags are children; null, undefined, false and true draw nothing, and arrays are flattened. key (or a string id) keeps a child's identity when the list around it changes; write it before any spread (<div key={k} {...props}>), since Bun refuses a key after one. <>...</> groups children without a node of its own. A style object spreads into the props, so style={{ padding: 8 }} and padding={8} are the same. A string child is a text node that takes the text style of the div around it; <text> takes its text from its children.

<column> is a div with display="flex", flexDirection="column" and gap="small", and <row> the same with flexDirection="row" and alignItems="center". Both take every div prop and override any of the three; they have no other defaults.

div is the one general container. Props, all optional:

  • Layout: display (flex|grid|block|none), flexDirection (row|column|row-reverse|column-reverse), flexWrap, flexGrow, flexShrink, flexBasis, alignItems, alignSelf (start|center|end|stretch|baseline), justifyContent (start|center|end|between|around|evenly), gap, rowGap, columnGap; simple grid: gridTemplateColumns (a count of equal columns, or a list of tracks such as [120, "1fr", "auto"]: pixels, a share of the rest, the width of the cell's content, row by row) and gridColumn on a child (a span: 2, "span 2").
  • Aligning: measured notes a div's box (by its id) every frame; a div with alignTo (the id of a measured div, in any view) takes that box's left edge and width inside its nearest measured ancestor, and stays inside it, so a row of tab strips in the title strip sits over the panes it belongs to and moves with them in the same frame; alignToEnd runs it on to that ancestor's right edge instead of the target's (the last strip, whose buttons run up to the title strip's own).
  • Size: width, height, minWidth, minHeight, maxWidth, maxHeight: a number (px), "50%", "auto" or "fill" (100%).
  • Spacing: padding, paddingTop|Right|Bottom|Left, paddingX, paddingY, and the same for margin (which also takes "auto"): numbers, or the steps none|small|medium|large. The most specific side wins.
  • Position: position (relative|absolute), top, right, bottom, left, zIndex (orders absolutely placed siblings; it never lifts anything out of the view).
  • Paint: background (a color, or { linearGradient: { angle, stops: [[color, at], ...] } }, drawn from its first to its last stop), color, opacity, border and borderTop|Right|Bottom|Left ({ width, color }), borderRadius (sm|md|lg|xl|xxl|full or px; xl is concentric with a filled button "medium" inside a 0.75px edge) or per corner (borderTopLeftRadius, ...), shadow (a list of { x, y, blur, spread, color, inset }, at most 4), backdrop ({ blur, fade, fadeColor }: a Gaussian blur of what is drawn under the box, blur its sigma as one number or [top, bottom], which changes row by row between the edges, a true progressive blur; then a mix towards fadeColor, the background by default, by fade [top, bottom], where an end above 1 reaches the full fade before that edge; ground, taken as fade is, fades into the window's ground instead, for a footer on the sidebar, since no colour names the ground (over Liquid Glass it is a shade); a translucent background tints the blur), elevation (raised: the panes' fine edge, 0.75px inside the box, and their shadow; edge: the edge alone; none: a transparent edge of the same width, for a box whose edge comes and goes; the kernel picks the colours for the theme's light or dark appearance), edgeOpen (top|right|bottom|left: the side an edge elevation leaves open, where the box joins the surface it stands on, such as a selected tab drawn as the top of its pane), tabShape ({ radius, flare, join? }: the box drawn as a selected tab, one shape in the pane's surface with the edge 0.75px inside it as on the panes, so the two meet in one colour, its top corners radius, its sides bending out at its foot into the pane's top edge in reverse curves of flare that reach past the box, its foot join px over the pane's edge), overflow, overflowX, overflowY (visible|hidden|scroll), cursor (default|pointer|text|grab|grabbing| move|not-allowed|crosshair|ew-resize|ns-resize), visibility.
  • Text inside: fontFamily (sans, mono, or a bundled family), fontSize (px or xs|sm|base|lg|xl|2xl), fontWeight (a number or normal|medium|semibold|bold), lineHeight, textAlign, lineClamp, whiteSpace (normal|nowrap), truncate.
  • States: hover, active, focus and disabled hold paint and text props (background, color, opacity, border, borderColor, shadow, fontWeight, visibility, underline) and display that apply in that state, so a hover can put a div into the layout or take it out; disabled applies while isDisabled is true, which also stops the div's events. group: "name" names a hover group, and groupHover: { group, ...state } applies while the pointer is on that group's div. focusWithin applies while the div or anything inside it (a native button, say) has the keyboard; unlike focus, the div itself does not take the keyboard.
  • Behavior: id (a stable id of your own), focusable, stopPropagation (a pointer event handled here does not reach the divs around it), followEnd (with overflowY: "scroll"), reveal (with overflowX: "scroll": the index of the child to keep in view), onInView({ ids }) (with overflowX: "scroll", on a kernel whose api.uiCapabilities includes inView: the ids of the children wholly inside the box, in order, after the box is laid out and whenever a scroll, a resize or a change of children changes them; a child without an id is never named; the chat numbers the tabs Alt and a digit show from it), drag, drop, onPaste, celebrate (see the old container props below).

Colors are theme tokens or hex (#rgb, #rrggbb, #rrggbbaa). The tokens are the surfaces and tones of DESIGN.md: background, card, muted, subtle, sidebar, popover, accent (the selected surface), stage, bubble, hover, foreground, mutedForeground, faint, primary, primaryForeground, info, success, warning, warningForeground, danger, border, edge (the raised surfaces' fine edge, for a shape that continues one), transparent. A token takes a fade: "danger/35" is the danger tone at 35%. With tokens a plugin follows the theme and its light and dark modes by default.

Events

Handlers stay in your plugin. The tree the kernel gets says only that a handler exists; when the event happens the kernel sends it back as data and the runtime calls your function. A handler may be a new function on every render: that costs nothing. On a div:

Event Payload
onClick, onDoubleClick { x, y, button, count, modifiers }
onSecondaryClick (a right-click; it does not reach the divs around) { x, y, button, modifiers }
onPress (the left button going down: a menu's anchor) { x, y, button, modifiers }
onPointerDown, onPointerUp { x, y, button, count?, modifiers }; onPointerDown hears a press anywhere inside the div, a text field and a part that blocks the mouse (a floating footer) included, but not a press on a floating layer drawn over it (a fly-out, a popover, an overlay, a dropdown list, a security card); it arrives once the press has been dispatched
onPointerMove (one per frame, the latest) { x, y, button, modifiers }
onPointerEnter, onPointerLeave {}
onWheel { x, y, dx, dy, modifiers } (pixels)
onKeyDown, onKeyUp (the div needs focusable; a click focuses it) { key, code, char, modifiers, repeat }
onModifiersChanged (window-wide, regardless of focus; on mount and change, cleared when the window deactivates) { modifiers }
onFocus, onBlur {}

x and y are inside the div, from its top left corner. button is 0 (left), 1 (middle) or 2 (right); modifiers is { shift, ctrl, alt, meta, secondary }, where meta is the Command key on a Mac and the Super (Windows) key elsewhere, and secondary is the key shortcuts use: Command on a Mac and Ctrl on Linux and Windows. Drag and drop is the explicit drag and drop pair, never the platform's (files dragged in from outside excepted).

canvas

<canvas width height commands> paints a draw list inside its box, clipped to it. It takes a div's props, events included, so pointer events come back with coordinates in the canvas. Optional viewBox: { width, height } fits logical coordinates into the native box without distortion, centering the drawing. Dimensions are 1–10000. Pointer coordinates use the inverse fit, so painting and hit testing agree when the box resizes. Without viewBox, coordinates remain native pixels.

onResize({ width, height }) reports the actual drawing layer's size in logical native pixels (not device pixels or viewBox coordinates). It fires after the first measured layout and actual width/height changes, with only the latest size delivered per frame. Unchanged dimensions, movement and scrolling do not fire it, so a handler may save the size and ctx.update() to lay out a chart at its real pixel size without starting a render loop. Choose the canvas's layout size independently of that chart's draw commands. Delivery is outside painting and is not a user gesture. Normal patches and handler replacement preserve measurement state and pending reports use the current handler; removing the handler or canvas, or reloading the plugin, cancels pending reports. Reattaching starts with a fresh layout report.

Commands:

  • shapes, which become the current shape: { op: "rect", x, y, width, height }, { op: "roundRect", ..., radius }, { op: "path", d: [["moveTo", x, y], ["lineTo", x, y], ["quadTo", cx, cy, x, y], ["cubicTo", c1x, c1y, c2x, c2y, x, y], ["close"]] }; each also takes fill, stroke and lineWidth to paint at once;
  • { op: "fill", color } and { op: "stroke", color, width } paint the current shape;
  • { op: "text", x, y, text, size, color, background?, align: "left|center|right", baseline: "top|middle|bottom", weight, font }: one line, y its top by default. Optional background fills the aligned, shaped line box without a border; it follows the text's transform and clip and leaves the current shape unchanged;
  • { op: "image", id, x, y, width, height, radius }: an image the kernel holds (an attachment id);
  • { op: "clip", x, y, width, height }, { op: "save" }, { op: "restore" }, { op: "translate", x, y }, { op: "scale", x, y? }.

Colors in commands are the same tokens and hex values as a div's, faded tokens included ("primary/55"). plugins/examples/chart draws a bar and a line chart this way: its canvas reports onPointerMove and onPointerLeave, the plugin works out the day under the pointer, and a div placed over the canvas (position: "absolute" inside a relative div) shows the tooltip.

Motion

motion: { to, duration, easing, delay, repeat, alternate, onDone } on a div animates it in the kernel; no JavaScript runs per frame. to names opacity, width, height, top, left, right, bottom (pixels), x and y (an offset from where layout puts the div), scale (the div's pixel width and height around its centre; its content keeps its size) and background. duration and delay are milliseconds (200 and 0 by default); easing is linear|easeIn|easeOut|easeInOut|spring (easeOut by default); repeat is a number of further plays or true for ever, and alternate runs every other play backwards. The motion starts from where the div is; a new to starts from where the running one has got to. onDone is called once, when the last play ends. The app's reduced motion setting jumps to the end.

<div width={0} height={8} background="success" borderRadius="full" motion={{ to: { width: 240 * share }, duration: 700, easing: "spring" }} />

The bar grows from 0 to its share; when share changes it grows or shrinks from where it is.

layoutMotion: true on a div, or a component such as an item or a card, with a stable id moves it smoothly whenever the layout moves it: a new row above it, a row that left, or the div itself moving to another place in the tree (a chat checked off into another section). The kernel notes where the div was drawn and glides it to its new place on a critically damped spring (most of the way in about 150ms, settled within about 400ms, with no overshoot). A glide sent somewhere else before it ends carries on from where it is at the speed it had. One that arrives among divs already in place fades in (180ms, ease-out). The window moves the div at each frame it shows, without drawing the view again, so a glide costs the view nothing; the div takes the pointer at its new place from the start. Scrolling, the whole view moving, and the view being given another size (the sidebar or the window resized) move nothing. A view as tall as its content, such as a transcript row, still glides what moves inside it when it grows or shrinks with that content; only a change of its width, which wraps its text anew, moves nothing. A div with layoutMotion that grows takes its new height at once, since what it holds is drawn at its new place at once and would otherwise hang below its edge until the box caught up; one that shrinks glides to its new height. Among a scroller's rows, a row that grows takes its new height at once and the rows under it move with it at once, because what grew shows at once and a row gliding down would be drawn over it (the line saying the agent is working, over a reply still streaming in); a row that shrinks or leaves still lets the rows under it glide up into the room. Leave it off where the layout changes as fast as the user types (a filtered list while a search is typed). The app's reduced motion setting jumps. A view that comes back on screen after it was out of sight (a chat switched back to) shows what changed meanwhile at once: nothing glides or fades in, and a motion that began meanwhile has already ended.

travels: true on a div with a stable id glides it when it moves to another place in the tree (the nearest ancestor with an id changes): the first frame draws it where it was, its box (background, border and clip) at the width it had, and it glides to its new place while the box takes the width its new parent gives it (on the same spring). Its content is laid out at the new width from the first frame. A div with the same id in the new place carries on from where the old one was drawn, so a zero-size div can mark where something starts. Moves inside its parent, and the pane changing size, jump. The chat's first prompt uses it: the prompt box goes from the centre of the new chat page to the transcript's foot, and the sent text rises from the prompt into its message. The app's reduced motion setting jumps.

ambient: "fog" | "contours" | "caustics" on a div draws a living background under its children with one GPU shader, run by the kernel with no JavaScript per frame: light warped through layered noise under film grain (fog), the level lines of a slowly moving terrain (contours), or light moving on a pool floor (caustics). The pointer is a light that bends each of them, and a click on the background sends a ring through it. The colours come from the theme's stage and info colour. Give the div a stable id so the animation keeps its place across renders. It draws at a lower rate while the pointer is still, stops in an inactive window and draws one still frame under reduced motion; "off" (or a value the kernel does not know) draws nothing. The chat's landing page uses it.

grain: true on a div draws the same film grain, still, over the theme's background and under the div's children: a texture for a surface on the pane's background, with no animation and no cost between frames. The chat transcript, the landing page without an animated background and the settings page use it when Settings > Chat > Film grain is on (off by default).

themeBackdrop: "<place>" on a div draws the theme's backdrop for that place under the div's children, in place of the div's ambient and grain, while the theme in use has one; otherwise the div draws as it says. A theme's tokens hold the backdrops by place (ThemeTokens.backdrop in types/divergence.d.ts): a moving scene ({ scene, color?, speed? }, one of the ambient looks in the theme's hue and speed), a still { fill } (a colour or a linear gradient) or a picture ({ image }, cropped to fill the place, an animated one still on its first frame), each with an optional glass veil ({ tint?, opacity?, blur? }) that keeps text readable over it. The chat plugin names newChat (the new chat page) and chat (a chat); the themes plugin's editor sets both. A plugin ships themes as files named in contributes.themes, each one preset { name, mode, tokens } with its pictures as paths relative to the file inside the plugin's folder; api.host.kernel("themes", {}) answers { themes: [{ id, plugin, name, mode, tokens }], problems } for the enabled plugins, the pictures as absolute paths, and the themes plugin offers them in Settings > Themes.

follows: "<id>" draws a div over the box of the div with that id, at its place and size, and takes no room where it is. Put it before the div it follows (in an ancestor they share): it is drawn under that div and everything after it. With layoutMotion, naming another id, or the box moving, glides it there and resizes it on the way, as a shared element does in a view transition. The sidebar's selected-chat fill is one:

<div id="chat-selection" follows={`row-${chatId}`} width="100%" height="100%" background="accent" borderRadius="sm" layoutMotion />

Give the row it follows a transparent background so the fill shows through it.

How a tree reaches the kernel

The runtime keeps the last tree of each view and sends only what changed (ui/patch { view, ops }: create, setProps, setText, appendText, insert, move, remove, root); the kernel keeps its own copy and draws from it. A text that only grew at its end (a streamed reply in <markdown id={id} text={text} />) goes as appendText with what it gained, so a long reply costs its delta, not its whole text, on every frame. Children are matched by key (a string id stands in for a missing one), then by type and position, so give rows of a list that changes a key. An element that is the same object the last render drew in its place is taken as unchanged, and the runtime does not compare it or anything inside it again. A view with a long list can keep the elements of rows that did not change and return them again, so a render costs only the rows that did (the chat plugin keeps its transcript rows this way). Never change an element after returning it: make a new one instead. Events come back as ui/event { view, node, event, payload, seq }; if the two copies ever disagree the kernel asks for the whole view again (ui/resync). Each patch names the last event the runtime had handled (seen). An input's value drawn before the plugin handled the user's latest edit is a step behind, so the input keeps the user's text and caret; a value drawn after it replaces the text. An onChange handler should therefore store the value before it awaits anything.

Checking a view

A change that must not change what a view shows (a refactor, a move to JSX) is checked without a window. Copy the plugin's folder to <folder>/<name> before the change, then run DIVERGENCE_UI_BASELINE=<folder> cargo test -p divergence-kernel --test plugin_equivalence: it runs the old and the new copy in the runtime side by side, with fixed chats, transcripts, settings, git status, terminals and app state, a fixed clock and fixed randomness. It records every view's tree as the kernel holds it, fires every handler the views show (and what those bring on screen), and requires the trees, the app state and the host calls to be equal after every step. A difference the change means to make is listed in the test's normalize, with its reason. The built-in plugins have tests there; a plugin of your own gets one by adding a run(...) with its fixtures.

Elements

Containers: <column> and <row> (above) take the div props, and a few props of their own that read more easily in a view. Props: gap (none|small|medium|large, or a number of pixels when the layout has to line up with a control's own inset), padding, paddingX, paddingY (the same values), fill (grow), full (fill both axes), scroll, scrollX (scroll sideways, for a strip of tabs: children keep their width and a vertical wheel moves the strip), reveal (with scrollX and an id, the index of the child to keep in view whenever it changes: the active tab), followEnd (with scroll and a stable id, keep following appended children while already at the end; a reader who scrolls up stays put; a capped ordinary vertical column with followEnd is a virtual list whose direct children are its rows, so only visible and nearby rows are laid out and drawn), onSecondaryClick (a right-click, which is how a plugin opens a context menu: hold the menu open in the plugin's own state and draw it with ui.popover), surface (background|card|muted|subtle|sidebar|popover|accent|bubble|stage|tint; tint fills with the container's tone), rounded or radius (sm|md|lg|xl|xxl|full), bordered with tone, wrap, align/justify (start|center|end|between), width, height, maxWidth (px), maxHeight (px; with scroll the box scrolls past it), center (centre a capped box), stack (children drawn over each other, centred), id (a stable element id for a container that scrolls or is dragged), stopClick (the click ends here instead of also reaching the row around), floatEnd (floats over the end of the parent, taking no space: hover actions), celebrate: { token, onDone } (a short burst around the container, once per token, then onDone; needs id), drag: { type, data, label, onEnd() } (the container can be picked up: a copy of it, glass and raised, follows the pointer from where it was grabbed while the container keeps its place in the layout but draws nothing there; label is the chip an older kernel draws instead; onEnd fires once the drag is over, dropped or not, after the drop's onDrop) and drop: { types, zones, files, onDrop(e), onOver(e) } (a target for dragged values of those types; zones is single, bands for before | into | after (the top quarter, the middle half and the bottom quarter of its height), or edges for left | right | top | bottom | center; e is { type, data, zone }. With reorder: "horizontal" | "vertical" the target is one item of a list that reorders in that direction: the zone is before or after by the half the pointer is in, and a line at that edge shows where the item goes instead of a fill over the target. An older kernel ignores reorder and reports into, so treat into as taking the target's place. onOver(e) hears a drag of one of types while it is on: e is { type, data, zone } when the pointer comes onto the target or into another of its zones, and zone is null when it leaves; a target covered where the pointer is, such as a list row under the scroller's floating footer, hears the pointer leave, so only the target on top hears it; a target with onOver draws neither the line nor a fill, since its plugin shows where the item goes, usually by moving the dragged item's place there so the list makes way for it. The runtime's LIVE_DRAG is defined where the kernel carries containers and tells onOver and onEnd. With files: true the target also takes files dragged in from outside the app, which arrive as { type: "files", paths, zone }), onPaste(e) (a paste inside the container that carries images or file paths rather than text: e is { images: [{ id, name, mimeType, bytes }], paths, refused }, the images already held by the kernel (TIFF and BMP as PNG), and refused the reason for each pasted image it could not hold. A plain text paste is not intercepted and reaches the input it landed in; so is a copy whose app put its text before an image, such as spreadsheet cells with a picture of them), hideOnHover, opacity, textSize and lineHeight (px, inherited by everything inside, markdown included), revealOnHover (hidden until the pointer is on the nearest hover or onClick ancestor), and onClick with hover for clickable rows. onPress is the same callback on the press rather than the release; use it for a menu or popover trigger, which should open under the finger, and keep onClick for an action, which the user must be able to call off by sliding away. radius also takes a number of pixels. Children may be strings, elements, arrays, or null.

Text: <text style truncate tone size bold weight lineHeight center> with style body|muted|heading|title|mono|small|section (a text without style has no style of its own and takes the div's, and takes a div's text props: color, fontSize, fontWeight, fontFamily, textAlign, lineClamp, whiteSpace), tone foreground|muted|faint|primary|info|success|warning|danger, size xs|sm|base|lg|xl|xxl or a number of pixels, weight a font weight number (400, 500, 560, 600) and lineHeight in px; <markdown text>, <code language>{text}</code>, <diagram id source language> (the diagram a markdown fence of that language, mermaid, draws, fitted to its whole place with zoom buttons and its downloads; a pinch, the wheel and a drag zoom and move it), <diff path diff>, <badge text variant> (default|info|success|warning|danger), <icon name> (Lucide names such as plus, folder, search, and the kernel's plus-large, a plus as wide as the icons beside it in a row, folder-solid, a filled folder, and divergence, the app's logo, which keeps its own colours and ignores tone and color; color gives an icon one of the preset colours), <image id path width height maxHeight radius zoomable> (a picture: id is an attachment the kernel holds, path a file on disk the plugin may read with its fs.read grant, else a placeholder is drawn, except a workspace's icon, which any plugin may draw; sizes are pixels). An attachment with maxHeight and no fixed dimensions fits the available width and height cap without enlarging or cropping it. Setting both width and height fills that fixed box with a cropped thumbnail. With zoomable a press opens the picture full size in the kernel's image viewer over the window, where a pinch, the wheel, a drag, a double click and the zoom buttons zoom and move it and Escape closes it; the viewer reads the file with the same grant, so a picture the plugin may not draw does not open. An older kernel ignores zoomable.

Controls (all need a stable id):

  • <button id label icon variant small disabled loading active tooltip badge iconSize onClick> with variant default|primary|ghost|danger|outline|chip|accent — a component (below), the one control that needs no id. onClick supplies { modifiers } (absent on older kernels). badge is a short count drawn on the button's corner; iconSize (px) draws its icon larger or smaller than usual, for a glyph that reads narrower than its neighbours' (the rail's files and source control icons beside the reload button); accent is filled with the active selection colour (list.active), for a panel's one action (Commit).
  • <input id value placeholder multiline submitOnEnter ghost onChange onSubmit onBlur> (onChange hears { value }, and onBlur hears { value } when a single-line field loses the keyboard, which older kernels never send) — submission supplies { value, secondary, shift }; secondary means ⌘ on macOS and Ctrl elsewhere. Multiline submits on ⌘⏎/Ctrl+Enter, or on ⏎ with submitOnEnter (⇧⏎ inserts a newline). Existing handlers may ignore the extra fields. The kernel reports modifiers, not send/queue policy. Stock chat maps plain Enter to Send/Steer and secondary Enter to Queue; picker Enter accepts its selection first. ghost drops the frame (only for an input inside a surface that already frames it: the composer, a picker's search); icon draws a Lucide icon inside the field before the text, and gives the field a list row's label type and corner (it heads rows, as the sidebar's search does) catchTyping: true gives this input whatever the user types while nothing else has the keyboard: the window focuses it and replays the keystroke, so a thought can be typed without clicking first. This is the main prompt box: one input per window should claim it, and only while its view is on screen (in a slot, or embedded in a view that is). The kernel reads the claim from each new tree, not from what it last drew, so a plugin with several panes (the chat plugin, one per kept chat) claims it only in the shown one and draws the others again without it when the shown one changes. keys: ["up", "down", "tab", "escape"] with onKey(e) (a key event, as onKeyDown's) hands those plain keys to the plugin instead of the field while it has the keyboard: a picker drawn over the field moves and accepts with them. The field binds these keys itself and acts on them before any onKeyDown around it sees them, so a container's onKeyDown never gets them. Pass them only while the picker is open; older kernels ignore both. arrowsAtEdges on a multiline input leaves Up and Down listed in keys to the field while they move its caret, and hands one to onKey only when the caret is already on the field's first row (Up) or its last (Down), wrapped rows counted as drawn, so a prompt history can go through earlier prompts without taking the arrows from a text of several lines; a picker's keys go without it. Older kernels ignore it and hand the listed arrows over wherever the caret is. tokens: [{ id, start, end, label, icon?, svg?, file? }] on a multiline input draws those parts of its text as pills: each is one piece (the caret steps over it, a deletion that touches it takes all of it, undo brings it back) with its mark (file, the file tree's icon for that name, else svg, else the Lucide icon), its label and an x that takes it out. Offsets are UTF-16 units, a JavaScript string's. The field keeps its pills while the user edits and reads tokens only when value replaces its text, and when it is made; caret (UTF-16 units) is where the caret goes then, the end of the text without it. A multiline input's onChange event carries caret and tokens: [{ id, start, end }], the pills it has now, so a picker can complete the word at the caret and the plugin can follow its pills. Older kernels ignore both props and send only value. keywords: [{ word, tooltip? }] on a multiline input draws each word in rainbow colours wherever it stands as a whole word (in any case, never inside a path, a flag or a file name such as /ultracode, --ultracode or ultracode.ts), and the pointer over one shows its tooltip; the field finds them itself as the user types, so the plugin need not draw again for them. The chat plugin passes the agent's promptKeywords. Older kernels ignore it. masked on a single-line input shows its text as dots, for an answer an agent asked to keep secret; the plugin still hears what is typed (unlike secret_input), and older kernels ignore it.
  • <checkbox id label checked disabled onChange>, <switch> with the same props (onChange hears { value })
  • <select id value options placeholder small ghost disabled tooltip onChange>, an option { value, label, svg? } — optional svg markup appears in both the trigger and menu rows
  • <combobox id look multiple value values label detail marks placeholder tooltip disabled chevron options search all actions width empty onChange onStar onRemove> — every dropdown (select is drawn as one). look: field (default), compact, toolbar (a frameless label, the composer's pickers) or row (an item's metrics, the sidebar). An option is { value, label, description?, detail?, image?|svg?|icon?, color?, group?, starred?, remove?, switch?, disabled?, reason?, submenu? } (color: one of the preset colours, for an icon mark: a workspace's folder-solid): group puts consecutive rows under a heading that folds (shown with two or more groups), starred shows a star reporting onStar({ value, option? }), remove ({ tooltip, confirm? }) shows a remove button while the pointer is on the row that reports onRemove({ value, option? }) (with confirm, the first press only shows that text in red in place of the description and the second removes; the pointer leaving the row cancels), detail is muted text at the row's end, switch (a boolean) ends the row in a switch, on when true, whose press or Enter reports onChange({ value: <the new state>, option }) with option the row's value and leaves the list open (older kernels draw a plain row), and submenu ({ value, options, search?, width?, empty?, context? }) opens a list beside the row whose choice reports onChange({ value, option }) with option the row's value; a context submenu opens on a right click, a Control-click or Right only, never on hover, and the row's plain click stays its own choice (a workspace's look in the sidebar's list). One value: onChange({ value }) and the list closes. multiple: a check at the end of each chosen row, the list stays open, onChange({ values }) in the options' order, all names a first row standing for every option (no values means all). actions ([{ label, icon?, onClick }]) are rows under a line that close the list. The trigger shows label (else the chosen labels, else placeholder), then detail fainter, after marks (else the chosen option's), then a chevron unless chevron is false. A list taller than 320px scrolls and shows its scrollbar. Keys: up, down, Enter, Right into a submenu, Left and Escape out.
  • <tabs id tabs active segmented onChange>, a tab { id, label } — segmented draws a segmented control (a few choices of one setting) instead of a tab bar
  • <text keys>{label}</text> — a key binding (⇧⌘P, strokes of a chord separated by a space: ⌘K ⌘S) drawn as key caps Components. Their look is the ui plugin's (plugins/ui, Components below): give them content and behaviour, and change how they look there, for the whole app, rather than per use. Any other prop you give one (an id, onClick, width, drag) lands on its root div and wins over the look's own.
  • <item id label sublabel sublabelTone stacked icon iconSvg iconTone busy hoverIcon onIconClick selected lift opens strike strong badge actions onClick>…</item> — a list row: a leading mark, the label and an optional second line, the children at its end (centred on the label's line, never making the row taller), and actions ([{ icon, tooltip, onClick }]) on the label's line, shown in place of the children while the pointer is on the row; they keep no room at rest, and under the pointer the label truncates where they start, so they never cover it. stacked (a chat row) puts the mark level with the label and the second line under the label rather than the mark, with the children and the actions at the second line's end, so the label runs the whole row. A <slot name="leading"> child replaces the icon, and a <slot name="menu"> child is laid over the row from its top left corner, where a right-click menu opens at the pointer. With onIconClick the mark is a button of its own, showing hoverIcon only while the pointer is on the mark (a chat row's check-off circle). lift raises the row (a fine edge and a soft shadow) while it is selected, as the sidebar's open chat is, and gives it the raised look's transparent edge otherwise, so selecting it moves nothing. opens marks a row that opens a page (a chat, Settings), which alone takes the pointer cursor; every other row keeps the arrow. The div props (id, drag, drop, celebrate, onClick, …) work as on a div.
  • <card divided>…</card> — a raised surface holding rows; divided draws a line between them.
  • <panel>…</panel> — an inset muted surface (a log, a note inside a card).
  • <bubble received>…</bubble> — a message sent into a transcript, in the prompt's type: the user's own on the bubble surface, one another agent sent (received) on card.
  • <reply>…</reply> — an agent's reply in a transcript: no surface, the transcript's body type, inset to line up with activity rows.
  • <setting title description stacked>control</setting> — a labelled setting with its control beside it (under it when stacked).
  • <callout tone title text icon>actions</callout> — a message with a tone (info, success, warning, danger).
  • <progress value tone /> — a bar; no value for work of unknown length.
  • <button>, <badge text variant>, <empty text>, <divider>, <spacer> — as above.
  • <block>, <blockHeader>, <blockBody> — the raised container of a code block, a table or a diagram, its header row and its body, as markdown draws them.
  • <table>, <tableRow head> and <tableCell head align> — a table's grid, row and cell, as markdown draws its tables. The tableCell definition's columnMinWidth and columnMaxWidth props bound a column's width (it is as wide as its longest cell between them, and longer text wraps). A table with overflowX: "scroll" keeps its columns that wide and scrolls sideways when they do not fit; otherwise the columns share the table's width out and their text wraps.
  • <tabs segmented …>, <text keys>⇧⌘P</text> and <input icon="search"> — see the controls above.

A kernel draws a node type it does not know (one from a newer kernel) as nothing, so the rest of the view still draws.

Components

A component is the look of a part every plugin draws, written once in the ui plugin (divergence/ui) the way a shadcn project keeps its copied components: one file per component in plugins/ui/components/, the set in plugins/ui/components.ts. Change a file and the whole app draws with it at once; add one and its name is a new tag every plugin may use. The plugin sends the set with kernel/components.set (settings.write); the kernel checks it whole, answers every problem by component and path, keeps the stock look of any component the set leaves out, and saves the set so the next launch draws with it from the first frame.

export const badge = component({
  props: { text: "", variant: "default" },
  template: (
    <div paddingX="0.375rem" borderRadius="sm" fontSize="xs" background="mutedForeground/12" color="mutedForeground" $when={variants({ variant: { danger: { background: "danger/12", color: "danger" } } })}>
      <text text={prop("text")} />
    </div>
  ),
});

A template is a tree of div, text, icon, spinner, canvas, other components, and <slot /> (where the instance's children go; <slot name="leading" /> takes a <slot name="leading"> child). It runs no code, so it cannot reach data or call a handler of its own. It reads the instance's props with prop("label") ({ $: "label" }; map, else and as: "percent"), keeps a node by $if, merges props by $when (each entry whose $if holds, a later one over an earlier one, an object prop such as hover one level deep; variants() writes them cva-style) and repeats a node over a list by $each (item.<field> and index inside). A condition is a prop that is set ("icon"), unset ("!label"), any of several ("icon|iconSvg"), props equal to values ({ variant: ["primary", "accent"] }) or a list that must all hold; children and slot.<name> say what the instance holds. A handler is only passed on from the instance (onClick=${prop("item.onClick")}), so every event still goes to the plugin that drew it. Sizes may name the theme ("density.fieldHeight", "type.labelSize + 4"), so a component follows the theme as the kernel's own controls do.

The kernel expands an instance where it builds the view's tree, once per change, into plain divs: drawing one costs what drawing those divs costs, and a component's children are moved over unchanged as under any div. A div with role="button" is a Tab stop that Enter and Space click, with the kernel's focus ring, which no look can remove; tooltip, label (what a screen reader says) and divide (a line between the children) are div props for components and plugins alike. The fields, dropdowns, tabs, trees, editors and the security cards stay native.

  • <collapsible id title open onToggle>{children}</collapsible> (onToggle hears { open })
  • <popover id open align side at width onDismiss>{anchor}{content}</popover> with align start|center|end — the anchor stays in the flow; while open, the content floats below it (above it when the anchor is in the lower half of the window, so it never covers the anchor; beside it, its top level with the anchor's, with side="right", as the sidebar's row preview does) over everything else (taking no space) and a press outside it or Escape calls onDismiss. With at: { input, offset }, naming an input inside the anchor and a character of its text in UTF-16 units, the content floats beside that character instead: above its line (below it when the anchor is in the upper half of the window), its left edge on the character's, as the composer's pickers open at the @, / or $ that opened them. An older kernel ignores at. Give a popover the user opens by pressing its anchor onToggle: the kernel then opens or closes it on the press of the anchor (or Enter or Space on it) in that same frame, as it does a combobox's list, and reports { open }, the state it now shows; the plugin sets its open to match. The kernel also closes the content at once on a dismissal, before onDismiss reaches the plugin. The plugin's open is followed again whenever it changes, so the plugin can still open or close the popover itself (a route change closing a menu). A press on the anchor itself is not "outside", so the toggle is a real toggle. On a host whose kernel predates it (POPOVER_TOGGLE from divergence is undefined), onToggle is ignored, so keep the anchor's own toggle there: onClick={kit.POPOVER_TOGGLE ? undefined : toggle}. A popover that opens for another reason (a hover, typing) has no onToggle, and its plugin owns open alone.
  • <overlay id open width top height backdrop cover keys hold onRelease onDismiss>{content}</overlay> — a panel over the whole window, centred, width pixels wide (544 by default) and top of the way down it (a fraction of the window height, 0.14 by default). Without height it is as tall as its content; with it (in pixels) the content is a column of that height, so a child that grows fills it. A width or height bigger than the window shrinks to fit it with a 24 px margin and the panel moves up as far as it must, so width: 1400, height: 1000, top: 0.06 is a big modal that still fits a small window. backdrop dims the window behind the panel, for a dialog rather than a picker; a press on the dim calls onDismiss like any press outside. With cover it is the whole window instead: the ground hides the sidebar, the panes and the rail, the title strip still moves the window, and the content fills one pane where the panes sit (a first-run guide); width, top, height and backdrop do not apply. Lists and popovers opened inside an overlay show above it. It takes no space where it is written, so it can sit anywhere in a view that is always drawn. While open it holds the keyboard: it takes focus and gives it back when it closes, keys maps a key name (up, down, left, right, enter, escape, or the character itself) to a callback, and a press outside it or the window going behind calls onDismiss. hold names a modifier (ctrl, alt, shift, cmd) whose release calls onRelease, which is how a Ctrl+Tab cycle commits. The kernel draws the card (surface, border, shadow, radius); the content is yours. The plugin owns open.
  • <view view> draws another registered view in place, and <view plugin name> one by its plugin and key. <split id direction sizes minSizes gap onResize>{children}</split> is a resizable group of two or more children side by side (direction="horizontal") or stacked ("vertical"): sizes are their shares of the whole, minSizes their preferred drag minima in pixels (160 by default), gap the room between them, and onResize hears { sizes } after a drag. Direct resizing respects each minimum while the group has room; a smaller container compresses non-fixed children to fit instead of letting them overlap. A group whose children change in number starts again from sizes.
  • <pane>{children}</pane> draws its children in a pane, the raised surface the center slot draws on the ground; a center view whose root is a pane or a split draws its own panes and is not wrapped in one. <region over="center">{children}</region> as the root of a title view places it in the title strip over the center slot, clear of the controls at the strip's start, so a task's tab strips sit over their panes. A div in the region with alignTo="title-lead" is placed in the room the sidebar leaves after its toggle, before the center slot; the room has no width while the sidebar is hidden or peeked, so a canvas with onResize inside the div tells the plugin how much room there is (the runtime's TITLE_LEAD_ROOM is defined where the kernel works this way). Give the region an in-flow child as tall as the strip, since the aligned div takes no room and a view with no height is not drawn. The sidebar puts its top row there. An older kernel draws nothing aligned to title-lead while the room is less than one 30px control.
  • A div with clampLines={n} and a px lineHeight shows at most n of those lines of what it holds (clampOpen shows it all), and its onClamp hears { clamped } each time whether those lines cut the content off changes, measured as laid out at its width with wrapped lines counted. Offer a Read more only when it says clamped: true; an older kernel ignores the props and never sends the event.
  • <list id items>, an item { id, label, sublabel, icon, tone, strike, selected, badge, onClick, actions: [{ icon, tooltip, onClick }] }. A list is a menu: the kernel draws its rows as a dropdown list's (28px, 6px corners, the mark in a 16px box, the badge as trailing muted text and a check on the selected row), so a menu in a popover matches the comboboxes.
  • <icon name small tone svg file size> — size is its size in px, over small; svg draws inline SVG markup in place of the named icon (currentColor follows the text colour, currentMuted the muted surface), and file takes a file's name and draws the icon and colour the file tree gives it

Layout: <divider>, <spacer>, <spinner>, <empty text>.

A spinner says the view waits for something to load, and the performance hook counts it as a loader (perf/README.md). One that says something is at work instead, such as an agent running, is an activity indicator: <spinner activity /> (h("spinner", { activity: true })). It looks the same and is not counted as a loader; an app older than this ignores activity and draws a plain spinner.

A secret's field: <secret_input id plugin setting placeholder onSaved> is the kernel's own masked input with a Save button. What is typed goes straight to the system credential store for the setting setting of the plugin in the folder plugin (not key, which a template keeps for the element's own key); onSaved hears { ok, error? }, never the value. A plugin draws it for its own secrets; the settings page (plugins.manage) for any plugin's.

Security cards: <security_card kind="approval" chatId id>, <security_card kind="request" id>, <security_card kind="publish" chatId id> or <security_card kind="report" id> marks the place of a card that only the app draws: an agent's approval (id is the approval's id), a plugin that waits to be enabled or to get more permissions, the publish row, or a report to the marketplace (id is a SecurityRequest id, see host-api.md). The plugin chooses only where the card goes; its content comes from the host, and other props are dropped. A publish row is drawn only where it is placed as publish, and request draws the enable, permission, report and bug report cards. A fix's attach row (kind: "attach_fix" in the request) takes the publish row's place below a fix chat's latest response and is placed as publish (or request). The kernel draws nothing there once the approval is answered or the request is resolved, for an id it does not know, inside a tool renderer, and for a request without a chatId (that one is a modal the shell shows over the window). The card paints above every plugin layer, popovers and overlays included, but keeps the clip of the place it sits in; its buttons that act work once it has been in view, unmoved and whole in width, for 600 ms (Cancel, Not now and Never act at once: saying no is never the risk). The chat plugin puts approvals where its transcript ends, requests after their afterItemId item, and the publish row below the latest response once the turn is over (security.pending gives them when a chat loads; security_request and security_resolved keep them current).

The publish row shows the plugin, what the turn changed of it and its permissions, with "Publish…" (a small form: visibility, the people to share with, and a sign-in when nobody is signed in; basedOn is filled in from where the plugin came from), "Not now" and "Never for this plugin" (kept as the plugin's publish setting in its install record, never in its folder). The report card shows the listing id, the version, the reason, the files and lines, who reports and the registry it goes to: exactly the body that is sent.

Links: divergence://market/<publisher>/<name>[@version] (from a web page, a terminal, another app) routes the center to market and shares marketOpen: { id, version, nonce } in the app state; the marketplace plugin opens that listing when the nonce changes. A link only navigates: it never installs, scans or starts an agent.

Stateful primitives (state retained per id):

  • <markdown id text> keeps the rendered state and appends streamed text cheaply. Its text selects with a drag, across blocks and from one markdown into the next, and Cmd+C copies it. With onQuote a selection that has let go of the pointer gets a small bar over its first line: Reply (also the R key, even while the prompt box has the keyboard), Copy as Markdown and Copy as plain text. Reply calls onQuote({ text }) with the selection written back as Markdown and clears the selection; the chat quotes it into the prompt box. Markdown read from a file takes that file's path, as the workspace names it, so a relative link in it names a file beside it (01-model.md in specs/tasks/README.md opens specs/tasks/01-model.md), as on GitHub; without path a relative link is relative to the workspace. With find={{ query, current, reveal }} it marks a search: every place query occurs in the text as drawn, ignoring case, gets a highlight, and the match numbered current (from 0, in reading order: a table's head, then its rows, cell by cell; a link's address and a chart's source hold none) a stronger one, which scrolls into view, in the markdown and in every list or box that scrolls around it, whenever reveal changes. The chat's Find in Chat counts the matches of each message the same way. An older kernel ignores find. A link titled divergence:pill:<icon> draws as a pill, the way the prompt box draws a tag: its label in the text's font on a rounded fill, after the icon of that Lucide name, or after the icon of the file the label names when the icon is file. Its address still opens on a click, and an empty one ([name](<> "divergence:pill:folder")) makes a pill that opens nothing. An older kernel ignores the title and draws the link.
  • <scroller id>{items}</scroller> is a virtualized list that keeps following its end while items are appended. A last child <slot name="footer"> is not an item: it floats over the bottom of the list (full width), the list leaves its height free at its end so the last item can scroll above it, and the jump-to-latest button sits above it. The chat's composer is the transcript's footer. onReachStart({ missing }) fires once per row count when less than a screen of items is above the top of the list, for the plugin to put the page before them; missing is how many rows of the room for unread history (below) lie between the top and the first item, 0 while the top is on the items, so a jump far up can be caught up in one read. rowsUnloaded holds room before every item, sent or left out, for about that many rows of history the plugin has not read yet, each as tall as the list's rows are on average: the list and its scrollbar are as tall as the whole history from the first page, a page read later takes room that was there instead of making the list taller, and onReachStart counts from the first item rather than the top of that room. Keep the rate of rows per unread item fixed, so each page changes the room by about the rows it brings; onReachStart fires again whenever that room changes. A scroller with onReachStart keeps a list shorter than the pane against its end instead of its top, so the page drawn first stays where it is as the rows before it arrive, and it stays there after they have. A list too long to send whole is sent as a window of its rows: rowsBefore and rowsAfter count the rows left out before and after the items sent, and the list has room for them, each as tall as its rows are on average, so it scrolls and sizes its scrollbar as the whole list. onRange({ first, rows }) gives the row at the top (counted over every row, sent or not, but not the room for unread history) and how many rows the list has: once when the list is first drawn (a kernel that calls it draws windows), and once per tree while the top is within 150 rows of a row left out, for the plugin to send the rows around it before they come on screen. Moving the window keeps the reader where they are, and so do rows put before it. Rows with stable ids retain their measured heights through rebuilds unless their content changes. Unseen rows occupy estimated space and are measured only when they enter the viewport or its fixed overdraw; replacing an estimate keeps the reading anchor or followed tail in place. While the list follows its end, items added there glide in: the list eases to its new end (on the same spring) instead of jumping, accounting for footer height changes in the same layout without reversing direction, and an added item with an id the list did not have fades in. An item that is a div, an item or a card with an id and layoutMotion moves at once with the items above it when they grow, so it never covers what they gained, and glides when they shrink, measured in the list's content, so scrolling moves nothing; a layoutMotion div that arrives inside an item fades in, and the list glides to its new end for it as for an added item.

A bounded tail-following <div> supports the same rowsBefore, rowsAfter and onRange({ first, rows }) contract when api.uiCapabilities?.includes("boundedDivRows") === true. The read-only api.uiCapabilities list comes from the native load handshake before activate; an absent list or missing feature means the plugin sends every child. boundedDivRows requires a stable id, followEnd, vertical scrolling, a definite maxHeight, no explicit height, and an ordinary vertical flex stack: no wrapping, grid, distributed alignment, dividers, positioned children, or children whose layout depends on an eager parent. Ineligible window props produce an explicit node error. The existing container remains the only scroll owner, keeps its natural height when short, includes its padding inside the height cap, and suppresses its scrollbar and jump button; omitted logical rows retain estimated space and range callbacks request their content before it is needed.

  • A scroller with followEnd={false} (spread the runtime's LIST) is a plain list: it opens at its first item, stays where it is scrolled, and has no jump-to-latest button. Use it for any list that can grow long (the sidebar's chats): only the items on screen are laid out and drawn, while a div with overflowY="scroll" lays out and draws all of its children in every frame of a scroll. Divs with follows that lead a scroller's children are not items: each is drawn under the items, over the item whose id it follows (the selected row's fill), moves with it as the list scrolls, glides to another item it is given to follow (with layoutMotion), and is not drawn while that item is out of sight. A host whose kernel predates this leaves LIST undefined. In such a list a change that moves the rows on screen glides each from where it was drawn, including a change of scroll position the change causes (the list grown shorter than where it was scrolled); only the reader's own scrolling moves the rows at once. A list at its very top stays there when rows are put before its first one. A row the list did not have, or one moved two or more places past rows that kept their order, fades in where it lands, and a row that comes into view under a gliding row glides with it. follows takes an api.app.bind projection, so the selected row's fill moves without the view drawing again.

  • <sticky top> inside a scroller's row (a row with an id) is that row's header: what stays at the top of the list while the rows after it pass under it, up to the next row with a sticky. The chat pins each of your prompts this way over its reply. It is never drawn in its row; there it stands for the div it is in, and its bottom stands for that div's bottom, so its children should draw what the div shows, laid out the way the row lays the div out, at the full width of a row. It rests top pixels below the list's top. Scrolling up slides it into view and scrolling down slides it out, like a phone browser's address bar: the scroll starts the slide, which runs on its own. The next row's header pushes it up as it comes, and a header lands on its own row as you scroll back to it, so the handoff never jumps; both follow the scrolling. It is drawn only while it is away from its own row, never when it is taller than half the list, and while it is in view the rows under it take no presses while the wheel still scrolls them. Its buttons work as their originals do. Give it no ids that its original also has: it is drawn while the original is too. A carried sticky stands for a row before its own that the list does not have, such as a prompt left out of a window or not read yet: it heads its row and the rows after it as a header whose row is above the list, and never lands; the chat puts its prompt's copy on the first row it sends when that row is not the prompt. A kernel that predates it draws nothing for it.

  • A scroller moves when the plugin asks, through three props. scrollTo contains a row id and a revision; each changed request smoothly scrolls that row to the top, with an optional inset in pixels, including when a later request names the same row. In a windowed list, index gives the row’s index among all loaded rows, so the list can reach it without discarding the current window. A wheel or scrollbar gesture interrupts the scroll; reduced motion places the row immediately. reveal is the id of a row to bring into view whenever it changes, and a row already in full view stays put; the sidebar names the selected chat's row, so a chat chosen with a shortcut comes into sight. toEnd is any string: whenever it changes to a new value, the list goes to its end and follows it again; the chat changes it for every message sent, so the message shows even when the reader had scrolled up. A list drawn for the first time only notes both: it opens where it always does. An older kernel ignores them.

  • <tree id items selected onSelect>, an item { id, label, icon, openIcon, children, open, status, badge, hint, actions }, onSelect hearing { id, folder, expanded } — the file tree (Files and Git panels): a chevron per folder, a file icon in its language's colour, a faint guide per level, status (modified, added, deleted, renamed, untracked, ignored, conflict) as the name's colour with badge (its letter) at the end, hint as faint text after the name, and actions while the pointer is on a row. Give files: [{ path, label, status, badge, hint, actions }] instead of items and the kernel makes the folders (openFolders opens them all; a folder's id is its path with a /). fit makes the tree as tall as its open rows, for a tree among other content. A folder follows its open when it is new to the tree and whenever the plugin changes open; otherwise it stays as the user left it, so drawing the tree again never undoes a click. The tree reports every folder the user opens or closes, by pointer or keyboard, as onSelect with folder: true and expanded (an older app sends only clicks, without expanded); keep them and pass them back as open to restore the folders when the tree is drawn anew, as when its panel shows again. A file is reported as the mouse button goes down on it, and with Enter or Space while it is selected. selected moves the selection when it names another row and scrolls that row into view once it is there; otherwise the selection is the user's. With the keyboard, Up and Down move the selection, Right opens a folder and then steps into it, and Left closes the folder or the one holding the selection.

  • <editor id text language readOnly onChange onSave> is a highlighted inline editor with line numbers. The kernel keeps what is typed, and a new text replaces it, so a plugin passes the saved text rather than each edit back. onChange hears { value } after each edit and onSave hears { value } when Cmd+S (Ctrl+S) is pressed in the editor.

  • A file-backed editor is available when the side-effect-free editor.file {} probe answers { version: 1 }. It takes file={{ workspaceId, path }}, a numeric revision, presentation="editor" | "markdown" and onFileState; do not pass text, onChange or onSave with file. The kernel owns the rope, reads and writes the file through the plugin's permissions, and reports only { state: "loading" | "ready" | "error", dirty, error? }. Changing revision requests a reload: it replaces a clean buffer and preserves a dirty one. Changing presentation renders the same rope as highlighted code or Markdown, so unsaved edits remain visible. Cmd+S saves natively; if another edit arrives while a save is in flight, that save writes its own snapshot and the later edit remains dirty. An older kernel rejects the probe, so a plugin that supports it keeps using the inline contract instead.

  • With onQuote, either editor mode gives a selection the same bar as markdown's while the editor has the keyboard; Reply calls onQuote({ text, lines }) with the selected code in a fence of its language and its first and last line. R replies only in a read-only inline editor, since an editable one types it.

  • <diff path diff> or <diff path oldText newText maxLines> draws a diff the way Zed does: syntax colours on both sides, a bar beside each changed line over a faint tint, and the changed words emphasized. The kernel reads loose patches (no file header, counts that are off, several edits of one file numbered from 1 each) and makes old and new text into one. With maxLines it is as tall as its lines, at most that many, without line numbers (an agent's edit numbers the lines of the fragment it replaced), for a card; without, it fills its place, scrolls, numbers its lines and folds long unchanged runs, so a whole-file patch (git.diff with wholeFile, or old and new text) shows the changes with the rest folded around them and is highlighted as the whole file. id keeps its scroll and folds while the patch changes. With onQuote a selection of text or of lines (from the line numbers) gets the reply bar, and Reply calls onQuote({ text, path, side, lines }): the code fenced, its file, original or modified, and its first and last line on that side.

  • <terminal terminal> draws a shell the kernel runs. It paints no background of its own, so it takes the colour of the surface it is placed on. terminal is the id terminal.create returned. The session is not part of the tree: it keeps running while nothing draws it, and several views may show it.

  • <chart kind="line" labels={months} series={[{ name: "Revenue", values }]} />: one of the kernel's chart families (GPUI Kit's line, bar, area, pie, donut, radar, candlestick and sankey, and scatter, heatmap, range, waterfall and boxplot drawn on the Kit's plot primitives) with their entrance, hover tooltips and the theme's chart colours. labels are the categories; each series has one value per label (bar, pie, donut and waterfall draw the first; a heatmap's series are its rows); x is a scatter's x value per label; candles are [open, high, low, close], ranges [low, high] and boxes [min, q1, median, q3, max] per label; links are { source, target, value } between sankey labels; title, height (120 to 600) and horizontal (bars) are optional. ChartProps in types/divergence.d.ts has the shape.

Markdown fences

A plugin can define a markdown fence type, so agents write a chart where it belongs in a reply without a tool call:

"contributes": {
  "fences": [{ "lang": "chart", "schema": "chart.schema.json", "draws": "chart" }]
}

A fence whose info string is lang holds one JSON document. The kernel checks it natively against the JSON Schema (draft 2020-12) in the plugin's schema file, then draws it as the draws component (chart, with the document as its props); no plugin code runs per fence. While the fence streams it is a quiet placeholder; a closed fence that fails shows its source with the error. A completed fence is not checked again. The types belong to enabled plugins; the first to declare a lang keeps it. Put the fence's format in the plugin's rules so agents know it.

A fence type with "draws": "svg" has no schema: the plugin turns the fence's text into SVG and the kernel draws it natively (shapes as paths, text in the app's faces, var(--pele-*) colours as theme colours). The plugin registers the renderer with api.fences.svg(lang, render); render(source, { fontSize, measurer }) returns the SVG, laid out with measurer.width(text, size, style), which measures the app's own faces (style 1 is bold, 4 is mono). A throw is the error the closed fence shows. The visuals plugin draws mermaid fences this way, with Pele.

Nothing else is native: the transcript, composer, file tree and file viewer are plugin code in plugins/chat/ and plugins/files/.

Inputs are controlled: pass the value you last received in onChange back as value; passing a different value (for example "" after sending) replaces the text.

Files, network, programs, environment

The host does these for the plugin, inside its grants (../AGENTS.md, Permissions). A call without the grant rejects at once with PermissionNotGranted; the host checks every call again.

api.fs (fs.read, fs.write)

Call Answer
read(path, { encoding?, workspaceId? }) the text (utf8, the default), a base64 string (base64) or a Uint8Array (binary)
write(path, data, { encoding?, workspaceId? }) writes a string or bytes
list(path) `[{ name, kind: file
stat(path) { kind, size, modified } (modified in milliseconds since 1970)
mkdir(path, { recursive = true }), remove(path, { recursive }), rename(from, to)
watch(path, fn) calls fn(paths) when something under path changes; resolves { close() }

A relative path with workspaceId is inside that workspace. The grant's scope decides the rest: workspace, plugin (the plugin's own folder), data (a folder of its own the host keeps for it, at api.paths.data, made before the plugin loads) or a path glob. A path counts by where it lands: a symlink is followed and the file it leads to must be covered by a grant, so a link inside a granted folder that points outside it is refused unless another grant names its target (list the target's folder too, as the Claude provider does with ~/.agents/skills/**). A .. or a link that leaves the folder the grant names after the check is refused too. list shows a link as symlink without following it.

api.net (net)

const response = await api.net.fetch("https://api.github.com/repos/x/y", { headers: { accept: "application/json" } });
if (response.ok) console.log((await response.json()).stargazers_count);
for await (const { event, data } of api.net.sse("https://example.com/events")) { /* ... */ }
const socket = await api.net.websocket("wss://example.com/live");
socket.send("hello");
for await (const message of socket) { /* a string, or a Uint8Array */ }

fetch(url, { method, headers, body, signal }) resolves a Response with ok, status, statusText, url, headers, text(), json(), bytes()/arrayBuffer() (a Uint8Array) and body, an async iterable of chunks with text(), json() and lines(). body may be a string, bytes, or an iterable of them (sent as it is read). A host is reached only when the grant names it, and every address it resolves to must be public: a name that resolves to 127.0.0.1 or a private network is refused unless the grant is localhost:<port>. Each redirect (at most 5) is checked again. Aborting signal before the response headers arrive gives up the request itself (the host stops it, and fetch rejects with the signal's reason, an AbortError); after them it stops the body.

api.process (process, process.any)

const child = await api.process.start("gh", ["pr", "list", "--json", "title"], { cwd: "/path/to/repo", outsideSandbox: true });
const out = await child.stdout.text();
const { code } = await child.exited;

start(program, args, { cwd, env, outsideSandbox: true }) resolves { pid, stdin, stdout, stderr, exited, kill(signal) }: stdin.write(data) and stdin.close(), stdout and stderr streams like a response body, exited resolves { code, signal }. process grants bare program names only, found on the login PATH; a path, or an interpreter (sh, node, python, ...), needs process.any. A child runs in its own process group with the login environment plus env, and is killed when the plugin unloads. What a child writes reaches the plugin whole, also after the child exited: the host reads its output through a buffer of 4 MiB (macOS) or a pipe grown to 1 MiB (Linux), so a program that writes without blocking and then exits (Node, Bun) loses nothing.

which(program) resolves { path, realPath }: the file spawn would run for program, and that file with its links followed (both null when it is not there). It needs what spawn of that program needs.

Writes to one stream (a child's input, a request body, a socket) reach it in the order the plugin made them, whether or not it waited for each.

api.env (env)

get(name) resolves the variable from the login environment, or null. Only the names the grant lists.

Streams are flow controlled: the host sends at most 1 MiB ahead of what the plugin has read, so a stream nobody reads waits and the others go on.

Commands and keys

A command is declared in the manifest and run by code:

"contributes": {
  "commands": [
    { "id": "pr-tools.open", "title": "Open pull request", "category": "PR tools",
      "key": "cmd+alt+o", "when": "workspaceOpen && !pr-tools.busy" }
  ]
}
api.command({ id: "pr-tools.open", run: (api) => open(api.app.state().workspaceId) });
  • id is <plugin name>.<command>. The manifest declares every command api.command registers (an undeclared one throws), so the palette and the Keyboard Shortcuts section know all commands before any plugin loads. The title, the category, the key and the when are the manifest's; what the code passes besides id and run is ignored.
  • key is a chord: modifiers (cmd, ctrl, alt, shift, fn) and a key joined by + or -, strokes separated by a space (cmd+k cmd+s). A key is a character or a name (enter, escape, tab, space, backspace, delete, up, down, left, right, home, end, pageup, pagedown, f1–f24). cmd is the platform's primary modifier: Command on macOS and Ctrl on Linux and Windows, so one cmd+n works everywhere. Off the Mac the Super key is super, and a chord that starts with Ctrl and a letter alone does nothing while the terminal has the keyboard, which keeps it for the shell; nor do Ctrl+Shift+C and Ctrl+Shift+V, the terminal's copy and paste there.
  • when is an expression over context keys: !, &&, ||, parentheses, and == / != against a literal (pr-tools.mode == 'review'), at most 1024 bytes long and 32 levels of ( and ! deep. While it is false the key is not the command's (it reaches whatever else takes it, an input types it) and the palette hides the command. The kernel sets composerFocused (the chat composer, the input with catchTyping, has the keyboard), terminalFocused, transcriptFocused (the center shows a chat and no input, terminal or overlay has the keyboard), workspaceOpen and overlayOpen, and from the chat plugin's report the layout keys tabKind, tabInSideSplit, paneCount and taskOnScreen (Tabs and layouts). A plugin sets keys of its own with api.context.set(key, value), named <plugin name>.<key> (kernel/context.set; another plugin's name is refused); null removes one, and a plugin's keys go when it unloads.
  • A command whose whole visible effect is a change of app state can declare it, so that its key shows the change on its own frame instead of after a trip through the plugin: api.commandAction(id, patch) sets what the command does as an api.app.update patch (null for nothing), and the plugin calls it again whenever that changes (the sidebar keeps the chat each of ⌘1…⌘9 opens up to date this way, and the draft ⌘N opens, which it readies with host/chats.reserve). The kernel applies the patch when the command runs, then runs run(api, { applied: true }), which still does everything the command does: on a host without declared actions api.commandAction is absent, and run alone does the work. It returns false for a command that is not registered.
  • A command that cycles while a modifier is held may add its id to contributes.heldCommands, for example "chat.switchNext": { "modifier": "ctrl", "group": "switcher" }. Commands in the same plugin and group form one episode. Their handlers receive ordered phase values: one or more press calls followed by exactly one release, or cancel after Escape, a pointer-down or window deactivation. A palette or direct invocation receives a press and release together. The manifest contract exists before activation, so the first quick tap waits for a lazy plugin to register instead of being lost. The contribution section is forward-compatible: older hosts ignore this map and omit phase, so the plugin keeps its ordinary one-shot or view-level fallback for them.
  • A clickable container may declare onClickAction as an app-state patch. A newer kernel applies it before onClick and passes event.applied: true; the callback does its remaining work but must apply the same patch itself only when applied is absent. Pair a component boolean such as an item's selected with api.app.bind?.("chatId", id) ?? currentBoolean when the visual state must change in that same input frame. The binding is resolved before the component template expands, so every $when branch sees the native boolean. It is not a second app-state copy and cannot run a command. A finite projection uses key: "route" | "workspaceId" | "chatId", a record of string cases, and a scalar default (null when omitted). Results may be null, a boolean, a finite number or a string. api.app.project(definition) records only its evaluated scalar during rendering, so a raw key change with the same result does not redraw that view. api.app.bind(definition) places that same definition in a native prop, including native elements such as a scroller's reveal; the arena owns its parsed definition and invalidates only when its output changes. Keep app_state subscriptions and any other raw reads the view needs. Check for app.project before using the scalar overload, and compute the value normally on an older runtime. Projection definitions are finite data and cannot execute expressions or commands.
  • A command runs in its plugin, with that plugin's permissions only. kernel/run_command { id } runs one: free for the plugin's own, commands.run for another's (the palette). The kernel's own keys are commands too: kernel.openSettings (⌘,), kernel.toggleSidebar (⌘B), kernel.reloadPlugins (⌘⇧R), kernel.quit (⌘Q), and the keys that scroll the chat on screen while no control takes them, kernel.scrollPageUp (Page Up), kernel.scrollPageDown (Page Down), kernel.scrollToStart (⌘↑) and kernel.scrollToEnd (⌘↓); they move the list that holds the input offered with catchTyping, which hands Page Up and Page Down to that list as well. The side split's ⌘⇧B is the chat plugin's chat.toggleSideSplit.

The user's keys are in <data dir>/keybindings.json, which the Keyboard Shortcuts section of the settings page writes and anyone may edit (comments and trailing commas are fine; the section rewrites the file without them):

[ { "command": "pr-tools.open", "key": "cmd+k cmd+o" },
  { "command": "-sidebar.newChat", "key": "cmd+n" } ]   // "-" removes a binding; without a key, all of them

Every change to a manifest, to which plugins are enabled, or to the file rebinds the whole keymap. Who gets a key:

  1. The user's entry always wins.
  2. Without one, a default of the app or an official plugin wins over a third-party default; between two third-party plugins the one installed first keeps it. The other command is not bound, and Settings shows the conflict with an Assign button.
  3. A third-party default needs cmd, ctrl or alt (F1–F12 need nothing), and cmd+q, cmd+,, cmd+shift+p and cmd+p are the app's. The user can still bind any key by hand.

kernel/commands answers every command with its keys: { commands: [{ id, title, category, plugin, pluginTitle, official, kernel, key (the default as written), defaultKey, keys, labels (as a keyboard shows them: ⇧⌘P), source: default | user | none, conflict: { key, label, with, withTitle } | null, problem, when, enabled (its when holds now), registered (its plugin runs) }], errors, file }. The settings page changes keys with keybindings.change { command, change: set | unbind | reset, key? } and keybindings.open (settings.write), and records one with keys.record (the next keystroke, before any binding takes it: { key, label }, { key: null } for Escape; plugins.manage).

The command palette

The official palette plugin opens with ⌘⇧P (commands: fuzzy over the title and the category, recently run first, each with its key and plugin, those whose when is false hidden; a command whose default key another command has shows "Conflict" and Assign, which opens Keyboard Shortcuts searched for it through the divergence/settings service's showShortcuts) and ⌘P (chats by title and workspace, the most recently active first, with the fuzzy matcher the sidebar's search shares; > there lists commands). A plugin adds a mode:

api.palette.provider({
  id: "files", prefix: "@", title: "Files",
  search: async (query) => [{ id: "src/main.rs", title: "main.rs", detail: "src" }],
  run: (item) => api.services.get("divergence/tabs").open({ kind: "file", workspaceId, path: item.id }),
});

Typing the prefix in ⌘P searches the mode; run gets the item the user picked, in the plugin that offers it, with its permissions. The palette reaches providers through kernel/palette.providers, palette.search { plugin, id, query } and palette.run { plugin, id, item }: free for a plugin's own, commands.run for another's.

Agents cannot run commands. A plugin with both commands.run and tools.provide can offer commands as tools (tools.md); its enable card shows both, so a user who wants that installs it on purpose.

Settings

A plugin declares its settings; the settings page draws them as the plugin's own section, with its commands and keys and its permissions (plugins/examples/hello-settings has one of each type):

"contributes": {
  "settings": {
    "title": "PR tools",
    "properties": {
      "serverUrl":  { "type": "url", "default": "https://api.github.com", "title": "API server", "description": "…" },
      "token":      { "type": "secret", "title": "Access token" },
      "maxResults": { "type": "number", "default": 20, "minimum": 1, "maximum": 100 },
      "mode":       { "type": "select", "options": ["fast", "full"], "default": "fast" },
      "labels":     { "type": "multiSelect", "options": ["bug", { "value": "feature", "label": "Features" }] },
      "cacheDir":   { "type": "path", "kind": "folder" },
      "accent":     { "type": "color" },
      "enabled":    { "type": "boolean", "default": true }
    },
    "view": "settings.js"
  }
}
  • Types: boolean, string, number (minimum, maximum), select and multiSelect (options), path (kind: file or folder; kept absolute, ~/ expanded), url (http, https, ws or wss, no user name or password), host (a whole host name, or localhost:<port>), color (#rgb, #rrggbb, #rrggbbaa), secret. Each takes title, description, default and placeholder. The manifest check refuses a default that does not fit its type, and a secret with a default.
  • view is a module of the plugin: its render(ctx, api) (or default) export draws the custom part of the section, below the fields (kernel/settings_view { plugin } gives the settings page its view id).
  • Values live in <data dir>/plugin-settings/<id>.json (the id with / as __), never in the plugin's folder, so they are never published and an update does not replace them. After an update the values of keys that still exist stay, new keys take their defaults, and gone keys are dropped; a value that no longer fits its type goes back to the default, with a notice in the section.
  • api.settings.get(key) gives one value (null when unset and without a default), get() all of them; both are copies, read at once. onChange(fn) calls fn(values) after every change and returns a function that stops it; views draw again by themselves. set(key, value) writes one (null goes back to the default) and resolves the value kept. None needs a permission (settings.own).
  • A secret never reaches the values: the settings page draws the kernel's native field (ui.secretInput), and what the user types goes from the kernel straight into the system credential store (the Keychain, the Secret Service, the Credential Manager), for this plugin and key. Only this plugin reads it: await api.settings.secret(key). A bug report's configuration carries settings, never secrets.

Settings in permissions

A permission can take a setting's value as one whole scope entry:

"permissions": {
  "net": { "hosts": ["${settings.serverUrl}"], "reason": "Talk to your API server" },
  "process": { "programs": ["gh", "${settings.binary}"], "reason": "Run the GitHub CLI you choose" }
}
  • Only a typed setting fills a permission: url or host for net (a URL gives its host, localhost:<port> for a loopback one), path for fs.read and fs.write (a folder gives <folder>/**), and for process a select whose options are program names or a path of kind: "file", whose absolute path is then what may run (an interpreter is refused, as always). The template is the whole entry: *.${…} or /Users/${…} fail the manifest.
  • Grants store the value, parsed, not the template. A value the user did not approve is not granted, whoever wrote it (an edit of the file by hand or by an agent asks for a new grant, which waits for "Review permissions…"); an official plugin gets only its default without a card.
  • Only the user changes such a setting: api.settings.set refuses it. When the user saves a new value that needs a grant, the app shows its change card ("API server changed: api.github.com → api.example.com"), and the old grant stays until the user answers; Cancel puts the old value back.
  • A value that does not parse (a URL with a password in it, a path with ..) asks for nothing: the permission is off, and the section says why.
  • An unset setting (no value, no default) asks for nothing.

Tools, hooks and agents

Tools every agent can call: api.tools.register, in tools.md.

Hooks

api.hooks.on("before_prompt", ({ text, context }) => ({ text: `${text}\n\nAnswer in French.` }));
api.hooks.on("after_turn", ({ outcome, context, workspaceId, changedPaths }) => { /* ... */ });
api.hooks.on("tool_call", ({ call, context }) => { /* ... */ });

A manifest entry is a hook name or { "hook": "tool_approval", "order": -10 }. The default order is 0; lower orders run first, with ties by plugin name. The host calls only handlers whose manifest lists the hook and whose grants cover it. api.hooks.on returns an unsubscribe.

Hook Mode Permission Result
before_prompt waterfall, each receives the previous text chats.control string or { text }; nothing keeps the text
after_turn parallel notification chats.read ignored
tool_call parallel notification chats.read ignored
tool_approval ordered gate approvals.auto (dangerous) { decision: "allow" | "deny" | "ask", reason? }

after_turn receives { outcome, context, workspaceId, changedPaths, itemId }; changedPaths and itemId are null without a checkpoint. tool_call receives { call, context }. Notification handlers log errors and ignore answers.

api.hooks.on("tool_approval", ({ approval, chatId, workspaceId, agentId }) =>
  ({ decision: "deny", reason: "Workspace policy" }));

Every gate handler runs in order. Any deny wins; otherwise the first allow wins, and with no allow the user decides. Throws, malformed answers and handlers that take over 10 seconds count as ask and are logged. The gate never fails open. Automatic answers use the first allow_once or reject_once option; if that option is absent or answering fails, the user sees the approval card. The gate runs outside the event loop while later events of that session wait in order. Automatic decisions are persisted as notices with approval metadata (id, decision, decidedBy, reason?) and shown as “Allowed by <plugin>” or “Denied by <plugin>: <reason>”.

Agents

api.agents.register({
  id: "echo", name: "Echo",
  initialize: () => ({ id: "echo", name: "Echo", capabilities: {}, authMethods: [], status: { state: "ready" } }),
  create_session: () => ({ sessionId: `s${Date.now()}` }),
  prompt({ sessionId, input }, { emit }) {
    emit({ sessionId, event: "text_delta", itemId: "a1", text: input.blocks[0].text });
    emit({ sessionId, event: "run_finished", outcome: { status: "completed" } });
    return { runId: "r1" };
  },
});

The host calls the handler named after each agent/<method> of agent-protocol.md (create_session or createSession), with the params and { agentId, emit }; emit(event) sends an agent event. A method the agent has no handler for fails with "does not answer". Agents registered in activate are listed once the plugin has loaded; ones registered or removed later (accounts read from storage, api.agents.unregister) reach the host by themselves: the runtime tells it (host/agents.changed) and it lists them again, serving the new ones and stopping the removed ones. Needs agents.provide, and the id must not be another plugin's.

name, icon (inline SVG), description and registry describe the agent before it has been started, in the host's list of agents the user may turn on; initialize answers for it afterwards and should say the same. registry: true marks an agent from the provider's registry of extra agents, which Settings lists under More agents (AgentInfo.registry, agent-protocol.md).

Models and subagents

A plugin with models.use runs prompts through the user's own enabled agents: no API keys, and the user's accounts pay. The host creates a hidden session for each prompt (no chat, no plugin tools, so a subagent cannot start subagents without end), and closes it after.

const { agents } = await api.models.list();
// [{ id, name, icon?, model, effort, models: [{ value, name, group?, efforts: [{ value, name }] }], error? }]

const answer = await api.models.prompt({
  agentId: "codex", model: "gpt-5.5", effort: "high",  // model and effort: the agent's default without them
  prompt: "Summarize src/lib.rs",                       // or blocks: [...]
  workspaceId,                                          // the chat's, the focused chat's, or the first workspace without it
  onEvent: (event) => {},                               // every agent event of the run (agent-protocol.md)
  signal,                                               // abort: the host cancels the run and closes the session
  subagent,                                             // a ctx.subagent handle: the run shows in it
});
// { text, usage, status: "completed" | "cancelled" | "failed", message?, agentId, model, effort }

text is the agent's last message. A model or effort the agent does not offer fails with the ones it does. With subagent (a handle from a tool call's ctx.subagent.start, tools.md) the host shows the run in that subagent as it streams, the subagent's stop button stops the run, and the run's approvals and questions go to the user's cards in the chat, marked with the subagent. Without one, nobody can answer them: the host refuses an approval and dismisses a question.

A subagent type is a kind of subagent the main agent can start by name through the subagents plugin's spawn_subagent tool (its type):

api.subagents.defineType({
  id: "reviewer", title: "Reviewer", description: "Reviews the change for bugs",
  inputSchema: { type: "object", properties: { focus: { type: "string" } } },
  async run(input, ctx) {                 // input: { prompt, ...what the agent passed }
    const sub = await ctx.subagent.start({ title: "Review", agent: "claude" });
    const r = await api.models.prompt({ agentId: "claude", prompt: input.prompt, subagent: sub });
    sub.end({ status: r.status, summary: r.text });
    return r.text;                         // the tool's result
  },
});

ctx is a tool call's (tools.md): the subagents it shows nest under the agent's spawn_subagent call. Types are listed with the plugin's tools (tools/list answers subagentTypes); api.subagents.types() lists every plugin's, [{ plugin, id, title, description, inputSchema }], and api.subagents.run({ type, input }, ctx) runs one (id, or plugin/id when two plugins use the id) and resolves with what its run returned.

Composer mentions

A plugin offers entries for the composer's @ picker, next to files:

api.mentions.set([
  { token: "codex/gpt-5.5/high", label: "Codex · GPT-5.5 · High", detail: "Subagent on GPT-5.5",
    icon: "bot", keywords: "codex gpt high",
    prompt: "The part tagged {token} is for a subagent: call spawn_subagent with agent \"codex\" ... The part: {part}" },
]);
api.mentions.list(); // every plugin's, each with its `plugin`

set replaces the plugin's list (at most 2000 entries reach the others); the host pushes every plugin's to every plugin. The chat plugin shows the matching ones after @; a chosen one is @<token> in the text, one segment (deleting into it deletes it all) with a chip that names it. On send the message carries each tag's prompt after the text, with {token} and {part} (the text after the tag up to the next one, or the text before it when it ends the message) filled in. The official subagents plugin offers one entry per agent/model/effort of the enabled agents.

Services

Plugins talk to each other through typed services: a provider owns a service (publisher/name, declared in the manifest's provides with the contract module that defines it), a consumer declares it in inject (needed: the plugin waits, shown as Waiting, until a provider runs a matching version) or optional (used when it is there). One plugin is the provider of a name; when two offer one, the user's choice (the serviceProviders setting) wins, then an official plugin, then the first by name.

// The provider: the contract is JSON Schema 2020-12. `impl[method]`
// answers `services/call` with `(params, { caller, signal })`.
const svc = await api.services.provide(
  { name: "alice/board", version: "1.0.0", access: "any", // or "official", or ["alice/ui"]
    json: { methods: { open: { params: { type: "object" }, result: { type: "object" } } },
            events: { changed: { type: "object" } } } },
  { open: async (params) => ({ ok: true }) },
);
svc.emit("changed", { n: 1 });                 // to the subscribed declarers
throw svc.error("NoBoard", { id });            // a declared error (list it in `errors`)
throw { _tag: "NoBoard", id };                 // the same, as its tagged value (also an Effect failure)

// The consumer (declares alice/board in `inject` or `optional`):
const board = api.services.get("alice/board");
await board.open({ id: "x" }, { signal });     // params validated by the host
const off = board.on("changed", (payload) => {});
api.services.when("alice/board", (client) => { /* a provider came */ return () => {}; });

The host enforces the contract: params, results, event payloads and errors are validated against the schemas, a caller must have declared the service and be allowed by the provider's access, and failures come back as errors named for their tag (ServiceUnavailable, NotAllowed, InvalidParams, ContractViolation, Interrupted). A provider that reloads holds calls for at most a second; a consumer whose inject provider goes away returns to Waiting.

Limits

A view may draw at most 50 000 nodes and hold at most 20 000 canvas commands and 100 000 path points. Canvas numbers and composed transforms must be finite and at most 1 000 000 in magnitude. A node may carry at most 4 shadows and 1 MiB of text. A view over a limit shows what went over instead of its tree, until it is under again. Its content is clipped to the view (with 8 px to spare at the edges, for a badge on a button); popovers and overlays are drawn by the kernel, above the view and below the security cards.

A plugin may use 2048 MiB of memory (official plugins) or 1024 MiB (every other), counted over its whole runtime process (the engine itself takes about 50 MiB). A plugin that goes over it is stopped at once, whatever its try/catch does: its views go, and Settings > Plugins shows it failed with Stopped: too much memory and a "Start again" button (plugins.reload). It is not restarted by itself. Nothing limits how long JavaScript runs: a plugin that loops freezes only itself (it runs in a process of its own), and the user reloads it (Settings > Plugins), which ends a runtime that does not answer. That reload does not wait for the turns of a provider's agents, as a reload on save does: they end as stopped, and the provider starts again. Long work waits on the host (await) instead of looping.

Events

api.on(name, fn) receives the JSON from events.md. Async handlers are fine; errors are logged. A plugin that needs only some agent events passes their kinds, api.on("agent", fn, { kinds: ["run_finished"] }) or events.stream("agent", { kinds: ["run_finished"] }) in the Effect form, and the host sends that listener no others, which spares the plugin every word an agent streams. An older runtime ignores kinds and sends every agent event, so such a listener should still check the kind. A plugin gets only the events it holds the permission for (events.md): the host does not send it the others.

Permissions

A plugin runs only after the user enabled it, and it can do only what its manifest asks for and the user granted (see ../AGENTS.md). The kernel and the host check each call:

  • Host calls need the permission host-api.md lists for the method; so do api.fs, api.net, api.process and api.env, whose calls are host calls.
  • Kernel calls: pick_folder, sleep, pick_images, image_data, forget_image, editor.file, themes and commands need nothing. A file-backed editor's reads and writes still require the calling plugin's matching fs.read and fs.write grants. copy_text and save_text need nothing but a click or key in the plugin in the last five seconds; save_text writes only where the user chooses in the save panel, and only if the plugin is still the same running, enabled plugin when the panel closes. open_in.apps needs nothing: it answers the editors, terminals and file manager on this machine that a workspace can open in ({ apps: [{ id, name, icon? }] }, editors first, icon a host-published PNG file for an image node or a combobox row that needs no filesystem grant), found off the window's thread from a fixed list of apps the kernel knows (off macOS only the file manager). open_in { app, workspaceId } opens a workspace's folder in one of them and needs nothing but a click or key in the plugin in the last five seconds; it fails with the reason when the app is not one the kernel knows, the workspace is unknown, or the system could not open it. An older kernel answers both with method not found, so a plugin that offers them shows nothing in their place there. attach_image needs nothing for bytes, or for a path the kernel gave this plugin (a pick, a drop, a paste); any other path needs fs.read covering it. theme, keybindings.change and keybindings.open need settings.write; keys.record and keys.record_cancel need plugins.manage. context.set, menu.entries, palette.providers and settings_view need nothing; context.layout needs chats.control. run_command, palette.search and palette.run need nothing for the plugin's own command or palette mode and commands.run for another plugin's. terminal.* needs terminal. plugins, reload_plugin, set_plugin_enabled and quit need plugins.manage. An unknown method fails with unknown kernel method <method>.
  • Views in the shell slots (left, center, right, rail, bottom, status, title) are placed for every plugin: ui.slots is always granted, like storage, and no card asks for it. A manifest may still list the slots it uses in ui.slots, which the marketplace shows.
  • api.openUrl(url) opens only http, https and mailto links, and only within five seconds after the user clicked, typed, dropped or pasted in one of the plugin's views, when the plugin's net grant covers the link's host, or (an http or https link of a plugin with agents.provide) while the user signs in to one of its agents: from the moment the host calls the agent's authenticate until it answers. A provider has no view to click in, and the sign-in is the user's own action. Otherwise the link stays closed, a notice says why, and the call resolves { opened: false, reason }. A popover dismissed by a click elsewhere, a timer, and window callbacks do not count as the user's action.

A refused call rejects with an Error whose name is PermissionNotGranted and whose permission and scope say what was missing; its message reads like PermissionNotGranted: files has no grant for fs.read /etc/hosts. NeedsReview is the name when a plugin can only be enabled from its card (plugins.setEnabled). Every other failure is named Error:

try {
  await api.host.fs.read({ path: "/etc/hosts" });
} catch (e) {
  if (e.name === "PermissionNotGranted") api.notify(`Needs ${e.permission} ${e.scope ?? ""}`, "warning");
  else throw e;
}

Managing plugins

plugins.manage is for official plugins only (the settings page). It gives api.host.plugins.* (see host-api.md): list, requestEnable({ name, chatId? }), setEnabled({ name, enabled }), revoke({ name, permission, scope? }) and reload({ name }). None of them grants anything. requestEnable asks the app to show its native card, and only the user's answer on that card enables a plugin or grants it more: setEnabled turns a plugin off, or back on when it was enabled before and asks for nothing new; otherwise it rejects with NeedsReview and the page calls requestEnable. The host loads or unloads the plugin when it is turned on or off (access_changed follows), and reload loads it again.

Tool renderers

api.toolRenderer({ kind: "execute", render: (call) => <column><code language="bash">{call.title}</code></column> });

call is a ToolCall (see agent-protocol.md); a renderer matches by name (the tool's name) or kind. A plugin draws another plugin's tool calls with <tool_view call id>: the kernel asks the plugin that registered a renderer for the call to render it, in its own runtime, and draws that plugin's tree in place (its callbacks go to that plugin). id tells two cards of one tree apart; a card goes when the tree no longer places it. api.toolRenderers() lists what every plugin renders, and the chat plugin uses <tool_view> for those calls and its own card for the rest.

Artifact renderers

Documents published by tools (tools.md, Transcript artifacts) become standalone role: "artifact" transcript items, not tool-call output. They carry { owner, type, version, title, summary, data } and the originating userItemId. The host stamps owner with the plugin folder.

api.artifactRenderer({
  type: "comparison", version: 1,
  render: (artifact, ctx) => <text style="body">{artifact.summary}</text>,
});
// A transcript view places the saved document with its own readable fallback:
<artifact_view id={item.id} artifact={item.artifact} chatId={chatId}><text style="body">{item.artifact.summary}</text></artifact_view>;

Only that folder's renderer for the exact type/version can draw the document. It receives an ordinary ViewContext with independent retained state and callbacks per placement. artifact.item is the transcript item the kernel placed it as, and artifact.chatId that item's chat when the placing view names it. Registration removal, unload and reload release embedded views; stale asynchronous responses cannot replace them. api.artifactRenderers() is separate from api.toolRenderers().

The kernel renders the returned declarative tree using Rust native components. It shows loading or renderer errors explicitly, and retains the placing view's fallback children when the renderer is missing, disabled, unsupported or failed. The saved data survives these states. The chat plugin's fallback offers the title, summary and highlighted JSON. Hosts without artifactRenderer cannot render artifacts; plugins requiring it should fail activation with an update message before registering tools.

Live HTML documents

<web_document id height item file revision mcpApp> shows an HTML page live: a saved html v1 page, an HTML file of a workspace, or an MCP App of a chat's tool call.

The page runs in the system's web view, in the engine's own sandboxed process (crates/host/src/web), and behaves the same on every platform:

  • On macOS it is WKWebView, and on Windows WebView2 (the Microsoft Edge WebView2 Runtime, which Windows 10 and 11 include). The kernel places the native view over the window where the element is drawn, so the page takes the pointer, the keyboard, text input, the clipboard and scrolling directly, at the display's own frame rate.

  • On Linux it is WebKitGTK (libwebkit2gtk-4.1, which the package depends on). The page is laid out off screen and the kernel draws its pixels where the element is, passing the pointer, the wheel, keys and an input method's committed text on to it, so it works the same under Wayland and X11. Being drawn by the app, it sits in the window's own layers, and a <select> opens its list drawn by the app. An input method's text in composition is not shown in the page, only what it commits. Pointer-lock requests are denied because the app owns pointer input and the offscreen web view cannot capture the system pointer.

  • In an artifact renderer the element is that artifact's own transcript item, whatever item or file says. Elsewhere (a tab's view) item names the transcript item, and the host runs it only if the view's plugin owns it. A page never names its own source.

  • height (80 to 2000 CSS pixels) is the frame's height until the page has measured itself; the frame then follows the page's own height, so a saved page never scrolls inside it (up to 8000 CSS pixels, a bound for a page whose height follows its frame), as wide as the element.

  • mcpApp: { chatId, toolCallId, index } (instead of item or file) shows the MCP App of the mcp_app block at index of that tool call, for a plugin with chats.read. The host reads the page through the chat's agent and runs it in a sandboxed frame of an opaque origin under the MCP Apps extension's restrictive content security policy, answering the app's messages itself (agent-protocol.md, MCP Apps). A new revision tells the app its tool's result once the call has ended. Older kernels ignore it.

  • file: { workspaceId, path } (outside an artifact renderer, instead of item) shows a workspace's HTML file, which the host opens only if the view's plugin may read it with fs.read. The page fills the element and scrolls itself, and height does not apply. The stylesheets, scripts, images and other files it names by relative URL load from the same workspace, each read under the plugin's fs.read grant at the moment it loads, so the page reaches what the plugin could read itself, never anything above the workspace or through a link out of it. Its links may lead to other files of the workspace. The file is shown as written: no theme stylesheet is added, and only the app's light or dark appearance (prefers-color-scheme) follows the app. A new revision loads the page again with every file it names read afresh; the divergence/tabs plugin's HTML preview raises it whenever it reads or saves the file.

  • The page is offline: every URL with an authority (http:, https:, ws:, file: and the rest) is blocked, it keeps no data between loads, and no plugin grant reaches it. The theme stylesheet names the bundled Inter and JetBrains Mono faces, which the web view answers from fixed files, so a page that inherits --font-sans and --font-mono is set like the app; a page's own family wins. Clicking a link navigates nowhere.

  • The page follows the element after every frame: it is cut to the element's clip, and anything the window draws over the element later (a control laid on the page, a popover, an overlay) covers it, where the window's content shows and takes clicks (a native view gets a hole there). It hides while a security card is up and whenever the element is not drawn. The document and its JavaScript keep running, and a theme change restyles the same document.

  • A wheel turn over a saved page that fits its frame scrolls what is under the pointer, as it does over the rest of the chat; a page that is taller than its frame, and a workspace page, scroll themselves.

  • It closes when the element leaves the tree, the item leaves the transcript or the plugin stops (a workspace file's page when the element leaves the tree or the plugin stops), and its view goes at once.

  • When the web view cannot start (WebKitGTK or the WebView2 Runtime is missing, or there is no display), the element says why.

Cleanup

What the runtime registered for a plugin goes when it unloads or reloads: its views, listeners, commands, tools, hooks, agents and timers. What the plugin started elsewhere does not: a program it spawned, a watch or a stream it opened through the host, state it shared. It takes those down itself:

export default definePlugin({
  activate(api) {
    const child = startServer(api);
    api.onUnload(({ reloading }) => child.kill());
    // Or: return the cleanup, or a Promise of it (an async activate).
    return () => stopPolling();
  },
});

api.onUnload(fn) registers fn; the function it returns removes it. activate may return a function, or a Promise that resolves to one, and it is registered the same way. On unload the handlers run first, while everything the plugin registered is still there, the last registered first, each with { reloading } (true when new code loads next). A handler that throws is logged and the others still run. Handlers are synchronous: a Promise one returns is not waited for. A cleanup that an async activate resolves to after its plugin was unloaded runs at once.

A reload runs the new code in the same runtime as the old, and a module is never unloaded, so whatever a module holds at its top level stays as long as the runtime does. Keep elements, handlers and anything else that reaches the plugin's state on that state (a controller, a view's data), never in a cache at module level, even a WeakMap: such a cache keeps every earlier version of the plugin in memory until the runtime passes its memory limit. plugins/testing/module-caches.test.ts refuses one in the official plugins.

Console and errors

console.log/warn/error go to the app log. An exception while the plugin loads (in activate, or in the program runPlugin runs) fails the plugin and shows the error in Settings > Plugins. An exception in a view shows the message in that view's slot. A call refused for want of a grant rejects as described under Permissions; the rest of the plugin keeps running. A promise that fails with nothing to catch it is logged.

Tabs and layouts

The window shows one task at a time: a row of the sidebar, laid out as panes side by side or stacked, each with its tabs in a strip over it. A chat is a tab, and so is anything a plugin draws there: a file, a diff, a terminal, a subagent's transcript. Beside the task, the side split holds the tabs that belong to no chat or to the task on screen, and the chat plugin's chat.toggleSideSplit (⌘⇧B) hides and shows it. The host keeps the tasks, their layouts and the side split (host-api.md, tasks.* and layouts.*; the events task_changed, task_removed and side_split_changed); the chat plugin draws the panes and their strips, and the sidebar draws the rows.

A plugin adds a kind of tab under tabs in its definition (the Effect form's Layouts.kinds):

export default definePlugin({
  tabs: {
    report: {
      title: (key) => `Report ${key}`,
      icon: "file-text",
      needsChat: true,
      opens: "beside",
      render: ({ key, chatId }) => <Report id={key} chat={chatId} />,
    },
  },
  commands: {
    "reports.open": (api) => api.layouts.open({ kind: "report", key: "weekly", where: "beside" }),
  },
});

title and icon are fixed or worked out from the tab's key. needsChat marks a kind that only makes sense with a chat: its tab belongs to the chat it was opened with and moves with that chat's task. opens is where open puts a new tab when the call does not say: side (the side split, the default) or beside (the focused pane of the task on screen). render gets a view context with the tab's key, its chatId and visible, which is true while the tab is the one its pane shows on screen (the host tells the owner, tab/visible, and the tab draws again when it changes); each open tab is a view of its own named api.layouts.viewName(kind, chatId, key), which <view plugin name> draws, and its state survives draws and reloads as any view's does.

api.layouts:

Member What it does
open({ kind, key, chatId?, where? }) opens a tab of one of this plugin's kinds, or shows it if it is open, and answers { itemId, paneId }. A tab whose kind names its workspace (workspace(key), as a file's or a terminal's) shows in the side split only beside a task with a chat of that workspace. where is side, beside or { paneId, index?, split? }, where split (right or down) opens it in a new pane split off that one. A tab opened without a recent user action waits in its strip, marked, instead of taking the pane
close(itemId) closes one of this plugin's tabs; answers whether it was open
current() { task, side }: the task on screen with its layout (which names the focused pane) and the side split (chats.read)
onChange(fn) hears every change to what current answers; returns the unsubscribe (chats.read)
split(paneId, direction), place(tab, target), focus(paneId, tab?) what the split buttons, drags and clicks do: split a pane right or down, move a tab to a strip, an edge of a pane, another task or a row of its own, focus a pane (chats.control when a chat moves)
viewName(kind, chatId, key) the name of the view that draws a tab
kinds(tabs) declares tab kinds; definePlugin({ tabs }) calls it
redraw() draws every open tab of this plugin's kinds again, after what they show changed

A kind may define file(key), the name of the file a tab of it shows (or null): its tab draws the file tree's icon and colour for that name instead of icon, as the tabs plugin's file and diff tabs do. A kind may define beforeClose(ctx), which answers a question to ask before the user closes a tab of it, or null to close at once; it reads the tab's state, so it runs no draw. When the user closes such a tab, the host asks the owner's runtime first (tab/before_close), host/layouts.close_tab answers { question } without closing, and the chat plugin shows the question with Cancel and Close, which closes with confirmed: true. api.layouts.close of a tab whose kind asks answers false and leaves the tab while the chat plugin shows the question (the host event tab_close_asked), and Close Other Tabs closes the rest and shows the first such question. The tabs plugin's file kind asks before discarding unsaved changes.

A tab whose plugin is turned off stays in its strip with its last title and icon, and its pane shows a placeholder (item-placeholder-<itemId>) with Turn On, which asks for the app's enable card. A <view plugin name> draws its children while that plugin is off, and nothing while it runs and the view is on its way.

Menus. A right-click menu opens with its top left corner where the pointer was, each entry with its icon. Right-clicking a tab opens its menu (tab-menu): Close, Close Other Tabs, Split Right, Split Down, Move to the Side Split (or Move into the Task), then the plugins' entries after a line. Right-clicking a sidebar row opens row-menu: Show Chats on a task row, Pin, Snooze (or Unsnooze), Rename, Mark Done and Archive, and on a child row Rename, Separate from Task, Archive and Close. A plugin places its declared commands in them with contributes.menus:

"contributes": {
  "commands": [{ "id": "notes.attach", "title": "Attach Note to Chat" }],
  "menus": {
    "tab": [{ "command": "notes.attach", "when": "tabKind == 'chat'" }],
    "row": [{ "command": "notes.attach" }]
  }
}

A menu entry must name a command the same manifest declares. The plugin that draws the menu asks kernel/menu.entries { place, keys } for the entries whose when holds for what the menu opens on, which runs no plugin code, and runs the chosen one with kernel/run_command { id, target }; the command's handler gets run(api, { applied, target }), with target { kind: "tab", tab, paneId } or { kind: "row", taskId, chatId? }. examples/note-tab declares a kind, a command that opens it beside the chat and a tab menu entry. A row entry's command can move its row through the sidebar's divergence/sidebar service (declare it optional with "^1"): snooze({ taskId, until }) puts the row in Snoozed until until (epoch milliseconds), or until it is unsnoozed when until is null, and fails UnknownRow for a row the list does not have; unsnooze({ taskId }) puts a snoozed row back where its state puts it.

Keys. The chat plugin reports the focused pane to the kernel (kernel/context.layout, which needs chats.control), so when reads tabKind (chat, or the focused tab's <plugin>.<kind>), tabInSideSplit, paneCount and taskOnScreen. A command bound with "when": "tabKind == 'notes.note'" takes its key only while a note has the focus.

Drags. The three drag types are public: divergence/chat ({ chatId }, from tabs, sidebar rows, child rows and the popover), divergence/task ({ taskId, chatId }, a task row, which only moves in the list) and divergence/item ({ kind, key, chatId?, itemId? }). Panes and strips take chats and items; an item no tab shows yet (no itemId) opens where it lands through its owner (host/layouts.drop_item, then tab/open in the owner's runtime, which counts as a gesture; the kernel sends the tabs plugin the same request without a target for a linked file clicked in Markdown, and the tab opens where its kind opens). A <tree> with rowDrag: { type, itemKind, keyPrefix } lets each file row be carried as type with { kind: itemKind, key: keyPrefix + id }; the Files tree drags its files as the tabs plugin's file tabs. The sidebar takes a chat of a task of several on the middle of a row to join that row's task, and such a chat let go elsewhere in the list leaves its task as a row of its own; a carried row of the list (a chat row, a task row, or the tab of a chat that is a row of its own) only moves in the list. While the side split is hidden, a chat or an item resting 400ms on the 24px band at the main area's right edge (side-edge) shows it.

The tabs plugin's own kinds are file, diff, terminal and diagram. It provides them to other plugins through the divergence/tabs service (declare it optional with "^2"): open(tab) opens a tab and answers { id }, close({ kind, path, workspaceId? }) closes one, active() answers the visible tab ({ kind, path, workspaceId }, or null), and the activeChanged event follows it. A tab is known by its kind, path and workspace, since two workspaces can hold the same relative path; a ref without workspaceId names the first tab of that kind and path. file takes workspaceId, path, focus? (with focus: true the file's editor takes the keyboard once it shows, for a file the user picked), diff takes workspaceId, path, diff, staged? (give the whole file as context and the tab folds it; with staged, false for the working tree or true for the index, the tab reads the file's diff again whenever the file or the index changes, and without it the diff is a snapshot), terminal takes workspaceId, path: id, title, and diagram takes workspaceId, path: key, title, source, language (the diagram of a markdown fence, which the kernel opens when the reader expands one in a reply). With chatId the tab belongs to that chat's task, as a diff from one of its tool calls does. A plugin that wants a tab of its own declares a kind instead of borrowing one.

Code selected in a file or a diff tab gets the reply bar. Reply quotes it in the open chat's prompt box, after the file's path and the lines it is on, through the chat plugin's divergence/chat service (quote({ text }), which fails NoOpenChat when no chat is open).

A file tab of a Markdown or HTML file offers Preview beside its editor. On a kernel with file-backed editors, Markdown changes the editor's presentation and draws the same native rope, including unsaved edits, without another file read; the editor id stays mounted. The inline compatibility path draws Markdown from its draft as before. An HTML file runs live in the system web view (<web_document> with file), as saved, with the stylesheets, scripts and images it names loaded from the workspace, and it loads again whenever the tab reads or saves the file.

// The consumer (declares divergence/tabs in `optional`):
const tabs = api.services.get("divergence/tabs");
await tabs.open({ kind: "file", workspaceId, path: "src/main.ts" });
api.services.when("divergence/tabs", (client) => {
  if (!client) return;
  const off = client.on("activeChanged", (tab) => {});
  return off;
});

Source: plugins/docs/ui-plugins.md in the Divergence repository, built with this site.