refern.
Extensions

SDK and CLI reference

Copy-pasteable reference for @refern/plugin-sdk, its UI controls, the format decoder ABI, @refern/sdk (the Local API client) and @refern/cli.

PackageUse it for
@refern/plugin-sdkCode that runs inside refern, in an app extension's frame: the refern client.
@refern/plugin-sdk/uiThe refern desktop controls (buttons, switches, menus) for those frames, compiled to ESM.
@refern/sdkScripts and tools that run outside refern on the same computer, over the Local API.
@refern/cli (refern-cli)Validate and pack extensions; automate the library from a terminal.

Install (Node 20 or later):

 npm install @refern/plugin-sdk react react-dom # an app extension npm install --save-dev @refern/cli # refern-cli in package.json scripts npm install @refern/sdk # a script that talks to refern 

@refern/plugin-sdk

ImportWhat it holds
@refern/plugin-sdkrefern, the client of this frame; PluginRpcError; all types below
@refern/plugin-sdk/uiThe refern desktop controls, PluginShell, usePluginContext
@refern/plugin-sdk/ui.cssThe theme tokens plus the styles of those controls (import once)
@refern/plugin-sdk/theme.cssThe theme tokens only
@refern/plugin-sdk/tailwind-themeThe Tailwind 3 theme, for an extension that runs Tailwind itself
@refern/plugin-sdk/manifestManifest types and validatePluginManifest (no DOM, no Node)
@refern/plugin-sdk/protocolThe postMessage messages between a frame and refern

Start-up

Importing the SDK sends refern:ready to refern. refern answers with refern:init and applies the user's theme to the frame's <html> (--color-* tokens as "R G B" triplets, data-theme, data-reduced-motion). The SDK accepts messages only from the parent frame.

 import { refern } from "@refern/plugin-sdk" ; const init = await refern. ready (); // init.pluginId, init.frameId ("entry", "dialog:<id>", "panel:<id>", // "overlay:<id>", "viewer"), init.locale, init.workspaceId, init.context 

init.context is what refern opened the frame with: a command's { commandId, args }, a sidebar panel's { workspaceId, entityIds } or { workspaceId, selectionCount }, an import source's { importSourceId, folderId }, or the context you passed to refern.ui.openDialog.

Outside refern (a normal browser tab), refern.client.inHost is false and every call fails with code: "no_host".

Calls, limits and errors

Each method is one request to refern, checked against the scopes the user granted. Every method returns a promise.

  • At most 16 calls wait at once per frame; the SDK queues the rest.
  • Parameters are at most 2 MiB.
  • A call times out after 30 seconds (code: "timeout"), except net.fetch (35 s), imports.enqueueUrls (90 s), viewer.readCurrentFile (60 s), ui.pickExportFolder (10 minutes), tools.exiftool.inspect (20 s) and tools.exiftool.write (30 minutes).
  • ArrayBuffers move without a copy (net.fetch bodies, thumbnails, viewer files).
 import { PluginRpcError, refern } from "@refern/plugin-sdk" ; try { await refern.tags. create ({ name: "reference" }); } catch (error) { if (error instanceof PluginRpcError && error.code === "scope_required" ) { // The manifest does not ask for "write", or the user did not grant it. } } 

Common error codes: scope_required, forbidden, not_found, invalid_request, invalid_field, limit_exceeded, needs_user_action (the call needs a recent click or key press), no_workspace, workspace_changed, unavailable, busy, network_refused, timeout, internal. error.details may say more.

Library (Local API operations)

These run the same operations as the Local API, with the same checks, undo history and limits. Answers never hold a path on this disk: every path field is null, and folderPath is relative to the library.

MethodScopeReturns
items.get({ id, include? })read{ item }
items.batch({ ids, include? }) (up to 200 ids)read{ items, missing }
items.list({ folderId?, rootId?, kinds?, include?, cursor?, limit? })read{ items, nextCursor }
items.update({ itemIds, set?, tags?, links?, createMissing?, dryRun? }) (up to 500 items)write{ changeId, ... }
items.similar({ id, mode? }) ("visual" or "meaning")read{ items }
items.getThumbnail({ id, maxEdge? }) (16 to 2048, default 512)read{ bytes, mimeType, width, height }
folders.list({ parentId?, rootId?, includeHidden?, cursor?, limit? })read{ folders, nextCursor }
folders.get({ id })read{ folder }
folders.create({ parentId? or rootId?, name })writewrite result
tags.list({ query?, cursor? }) / tags.get({ id })read{ tags, nextCursor } / { tag }
tags.create({ name, ... })writewrite result
tags.edit({ id, set }) / tags.delete({ ids })organizewrite result
creators.list({ query?, cursor? })read{ creators, nextCursor }
creators.create({ name, url? })writewrite result
creators.setForItem({ id, creatorIds })writewrite result
groups.get({ id })read{ group, members, membersTruncated }
groups.create, groups.edit, groups.merge, groups.dissolve({ id })writewrite result
links.add(...), links.remove(...)writewrite result
smartFolders.get()read{ smartFolders, revision }
search.text({ text?, tagNames?, tagIds?, tagMode?, folderId?, recursive?, kinds?, favourite?, ratingMin?, colorLabels?, sort?, direction?, limit?, ... })read{ items, truncated }
search.semantic({ text, limit? })read{ items }
search.color({ color, folderId?, limit? })read{ items }
changes.list({ cursor? })read{ changes, nextCursor }
changes.undo({ changeId })writewrite result

include is a list of "metadata", "appearance", "links", "inferred", "preset" or "all". Parameters follow the Local API operations (list_items, get_items, update_items, search and the rest); unknown fields are refused with invalid_field. The changes an extension makes are listed with the Local API's recent changes, where the user can undo them.

 // Tag every selected image "reference" (needs the "write" scope). const selection = await refern.selection. current (); if (selection) { let cursor : string | null = null ; do { const page = await refern.selection. page ({ selection: selection.handle, cursor, limit: 500 , }); const ids = page.items. filter (( i ) => i.kind === "image" ). map (( i ) => i.id); if (ids. length > 0 ) await refern.items. update ({ itemIds: ids, tags: { add: [ "reference" ] }, createMissing: true , }); cursor = page.cursor; } while (cursor); await refern.selection. release ({ selection: selection.handle }); } 

Selection

A selection can hold millions of items, so it is a handle (a lease), read in pages.

MethodScopeReturns
selection.current()read{ handle, count, workspaceId }, or null
selection.page({ selection, cursor?, limit? }) (up to 500, default 100)read{ items, cursor } (cursor is null after the last page)
selection.release({ selection })nonenull

A handle ends after 5 idle minutes, when its frame closes, or when another library opens (workspace_changed). A frame holds at most 8 handles.

UI

MethodReturnsNotes
ui.toast({ message, kind? })nullkind: "info", "success", "error". At most 200 characters and 3 toasts every 5 s. refern shows your extension's name first.
ui.openDialog({ panelId, context? })nullA dialog panel of this extension. Needs a recent click or key press.
ui.closeOverlay()nullCloses this frame's dialog or overlay.
ui.openExternal({ url })nullhttps: only. refern asks the user first. Needs a recent click.
ui.pickExportFolder(){ folder, name } or nullA folder the user picks: folder is an opaque token, name its last part. Needs a recent click.

"A recent click or key press" means one in this frame or in refern within the last 5 seconds; otherwise the call fails with needs_user_action.

Commands

MethodReturnsNotes
commands.list()CommandInfo[]The app commands this extension's scopes allow: { id, title, category?, shortcut? }.
commands.execute(commandId, args?)unknownRuns an app command, or plugin:<id>:<command> (that needs a recent click). args: flat JSON values only.

Settings, storage and network

MethodReturnsNotes
settings.getAll()Record<string, unknown>Every non-secret setting: the stored value, else the default, else null.
settings.getSecret({ key })string or nullA secret setting of this extension, from the credential store.
storage.get({ key })unknownnull when not set.
storage.set({ key, value })nullJSON values; keys 1 to 256 characters; at most 4 MiB per extension.
storage.delete({ key }), storage.keys()null, string[]
net.fetch(url, init?){ status, headers, body }See below. body is an ArrayBuffer.

net.fetch is the only way to the network. refern makes the request:

  • https: on the default port only, to a host in permissions.network (checked again on each redirect, at most 5).
  • Never to this computer or the local network: names that resolve to loopback, private, link-local or similar addresses connect nowhere.
  • init: method (GET, HEAD, POST, PUT, PATCH, DELETE), headers (at most 32; not Host, Cookie, Origin, Referer, Connection, Content-Length, Proxy-*, Sec-* and other connection headers), body (a string or ArrayBuffer, at most 2 MiB).
  • The answer body is at most 32 MiB; the request ends after 30 seconds.
  • {{secret:<key>}} in a header value is replaced with that secret setting, so the key never enters the frame.
 const response = await refern.net. fetch ( "https://api.example.com/v1/search?q=sky" , { headers: { Authorization: "Client-ID {{secret:apiKey}}" } }, ); if (response.status === 200 ) { const json = JSON . parse ( new TextDecoder (). decode (response.body)); } 

Imports, viewer and Managed ExifTool

MethodNeedsReturns
imports.enqueueUrls({ folderId?, items: [{ url, tags? }], tags?, createMissing? })write and an importSources entry{ status, importId?, results }
imports.checkOrigins({ origins: [{ source, item }] })read{ present: [{ source, item, itemId }] }
viewer.readCurrentFile()a formats[].viewer frame{ bytes, name, extension }
tools.exiftool.status({ entityId? })managedTools: ["exiftool"]{ installed, version, canWrite?, canInspect? }
tools.exiftool.inspect({ entityId })exiftool and readall embedded tags of one file
tools.exiftool.write({ selection? or entityIds?, fields, mode, exportFolder?, descriptionSource? })exiftool and write{ updated, skippedReadOnly, skippedUnsupported, skippedPlaceholder, failed }

tools.exiftool.status with entityId also says whether your extension can read (canInspect) and write (canWrite) that item's file now: a live file on this computer (not online only or a cloud placeholder), and for a write a format ExifTool writes, a file not marked read-only and the write grant. Offer a write only when canWrite is true.

imports.enqueueUrls downloads https: addresses only; an extension cannot import local files. For tools.exiftool.write, fields names what to write (keywords, hierarchicalKeywords, creators, description, rating, source, copyright), and mode is "inPlace" or "exportCopies" (with exportFolder from ui.pickExportFolder()). refern reads the values from the library and runs ExifTool itself; an extension never passes arguments or paths.

Events

 const stop = refern. on ( "selection.changed" , ( payload ) => { const { count } = payload as { count : number }; }); stop (); // unsubscribe 
EventPayloadWhen
selection.changed{ count }The user selected other items.
items.changed{ kinds }The Local API or an extension changed the library (not edits made in refern's own panels).
settings.changednullThe user changed one of this extension's settings.
workspace.changed{ workspaceId }Another library opened (or none).
command.run{ commandId, args }The entry frame only: a command of this extension ran.

refern.client.onTheme(handler) runs after each theme change the SDK applied.

Hidden entry page that answers commands

 // src/entry.ts, built to the page the manifest's "entry" names. import { refern } from "@refern/plugin-sdk" ; refern. on ( "command.run" , async ( payload ) => { const { commandId } = payload as { commandId : string ; args : unknown }; if (commandId !== "countSelection" ) return ; const selection = await refern.selection. current (); await refern.ui. toast ({ message: `${ selection ?. count ?? 0 } items selected.` , kind: "info" , }); }); 

Register the listener at the top level: commands that arrive before the page is ready wait and are delivered after the handshake.

@refern/plugin-sdk/ui

The refern desktop controls, already compiled to plain ESM (no workspace packages, no Lingui transform). React 19 is a peer dependency.

 import { refern } from "@refern/plugin-sdk" ; import { FButton, FSwitch, PluginShell, usePluginContext, } from "@refern/plugin-sdk/ui" ; import "@refern/plugin-sdk/ui.css" ; import { createRoot } from "react-dom/client" ; function App () { const { init } = usePluginContext (); return ( < div style = {{ padding: 16 , color: "rgb(var(--color-on-background))" }}> < FButton variant = "primary" size = "sm" onClick = {() => refern.ui. closeOverlay ()} > Done </ FButton > </ div > ); } createRoot (document. getElementById ( "root" ) ! ). render ( < PluginShell fallback = { null }> < App /> </ PluginShell >, ); 
ExportNotes
PluginShellThe root: waits for refern:init, re-renders on theme changes, provides tooltips.
usePluginContext(){ init, theme } inside PluginShell.
FButtonvariant: "filled" (default), "primary", "outline", "danger", "ghost"; size: "xs", "sm", "md".
IconButton, MenuButton, DropdownMenuIcon buttons and menus (DropdownItem type).
FSwitch, FCheckbox, FSlider, FToggleGroupFSwitch: checked, onCheckedChange, size.
FTextFieldA text input (multiline for a textarea); size: "sm", "md".
SearchField, TagChip, LabelBadge, ProgressBar, Collapsible, Tooltip, TooltipProvider
iconsThe refern icons: icons.IconRefresh, icons.IconTag, icons.IconImage, ...

The controls hold no translations: pass your own labels as props.

Colors in your own CSS: rgb(var(--color-surface)), rgb(var(--color-on-surface) / 0.6). Tokens: background, surface, surface-elevated, surface-raised, border, shadow, on-background, on-surface, muted, primary, on-primary, secondary, accent, neutral, info, success, warning, danger (each with on-*), favourite, rating, focus-ring, drop, drop-fill, highlight.

To use Tailwind classes of your own, run Tailwind 3 in your build with the refern theme:

 // tailwind.config.js import theme from "@refern/plugin-sdk/tailwind-theme" ; export default { content: [ "./src/**/*.{ts,tsx}" , "./*.html" ], theme }; 

@refern/plugin-sdk/manifest

 import { validatePluginManifest, parseWhenExpression, isSafePackagePath, isNetworkHostPattern, manifestFilePaths, PLUGIN_API_VERSION, // 1 } from "@refern/plugin-sdk/manifest" ; const result = validatePluginManifest (json); // strict by default if ( ! result.ok) console. error (result.errors); // [{ path, message }] 

Types: AnyPluginManifest, PluginManifest, ThemeManifest, PluginPermissions, PluginScope, PluginContributions, PluginCommandContribution, PluginPanelContribution, PluginOverlayContribution, PluginImportSourceContribution, PluginFormatContribution, PluginSettingDef, WhenExpression.

@refern/plugin-sdk/protocol

For a frame written without the SDK: send { type: "refern:ready", protocol: 1 } to window.parent; refern answers refern:init. A call is { type: "refern:rpc", id, method, params }, answered by { type: "refern:rpc-result", id, ok, result | error }. Events arrive as { type: "refern:event", event, payload } and theme changes as refern:theme. Accept messages only when event.source === window.parent.

Format decoder ABI

A format extension's .wasm module (target wasm32-unknown-unknown) must import nothing and export:

 memory refern_alloc(len: u32) -> u32 refern_dealloc(ptr: u32, len: u32) // optional: refern never calls it refern_decode(in_ptr: u32, in_len: u32, max_edge: u32, cfg_ptr: u32, cfg_len: u32) -> u64 

For each file, in a fresh instance with 500,000,000 instructions of fuel and 128 MiB of memory, refern:

  1. calls refern_alloc for the file's bytes (at most maxInputBytes, 64 MiB) and writes them; then the same for the settings JSON (cfg);
  2. calls refern_decode. max_edge is the longest preview edge it wants (refern passes 2560). The result packs the header's byte length (32) in the high 32 bits and its address in the low 32 bits;
  3. reads the header, 8 little-endian u32 values:
OffsetFieldMeaning
0status0 preview, 1 unsupported (try the OS preview), 2 corrupt (no preview)
4preview_w1 to 4096
8preview_h1 to 4096
12canvas_wThe file's own width (0: the preview's)
16canvas_hThe file's own height (0: the preview's)
20flagsBit 0: pixelated (scale without smoothing)
24rgba_ptrStraight RGBA, row by row
28rgba_lenExactly preview_w * preview_h * 4

A trap (panic, out-of-bounds access, out of fuel or memory) or a header that breaks these rules counts as no preview, and after 5 traps in one preview pass refern skips the extension until the next pass. The template wasm-decoder-starter holds this ABI in src/abi.rs, a checker that runs a module the way refern does (check-decoder.mjs) and a fuel meter (fuel-check/).

@refern/sdk (the Local API client)

For scripts and tools outside refern, on the same computer. It needs a Local API token: in refern, Settings > Local API, switch the API on and create a token (scope read, write or organize). Node 20+, Bun and Deno; no dependencies.

 import { RefernClient } from "@refern/sdk" ; // Token: REFERN_API_TOKEN, or { token }. Address: REFERN_API_URL, or found. const refern = await RefernClient. connect (); console. log (refern.workspace?.name); const { items } = await refern.search. text ({ text: "sky" , limit: 20 }); await refern.tags. add ( items. map (( item ) => item.id), [ "sky" ], true , ); await refern.imports. enqueueUrls ({ folderId: "<folder id>" , urls: [ "https://example.com/a.jpg" ], }); 

How it connects:

  1. The address is baseUrl, else REFERN_API_URL, else the port in refern's server-port.txt, else each port from 7733 to 7743 on 127.0.0.1.
  2. Before it sends the token, it asks the listener for /proof: a hash bound to the stored token hash, a fresh nonce and the port, which only refern can compute. A listener that fails never sees the token (RefernConnectError, with reason: not_refern, api_off, unknown_token or wrong_token).
  3. It reads GET /v1 once. Writes use that library's id unless they name another, so if the user opens another library, a write fails with workspace_changed instead of changing the wrong one.

Namespaces: items (get, batch, list, listAll, update, similar, thumbnail, file, rename, move, copy, trash, restore), search (text, semantic, color), folders, tags (including add and remove on items), creators, links, groups, smartFolders, imports (import, enqueueUrls, get), changes (list, undo). API errors are RefernApiError (status, code, details). client.request(method, path, { query, body, idempotencyKey }) reaches any other endpoint.

@refern/cli (refern-cli)

The command is refern-cli (refern is the app itself). Install globally with npm install -g @refern/cli or run with npx @refern/cli (0.3.0+ for the directory commands, Node 20+, one file, no runtime dependencies). Exit codes: 0 done, 1 failed, 2 wrong usage. --json prints JSON.

Extension commands

 refern-cli plugin init < di r > [--template app | theme | wasm-format] [--id < i d > ] [--name < nam e > ] refern-cli plugin validate < di r > refern-cli plugin pack < di r > [--out < fil e > ] 
  • init writes a small skeleton into an empty folder (app is the default). The starter templates (theme-starter, app-plugin-starter, wasm-decoder-starter) are fuller, working examples.
  • validate checks manifest.json strictly, each theme file with the app's theme validator (colors, contrast, fonts) and that the files the manifest names exist. A file a build makes (dist/..., decoder.wasm) is a warning until it exists. Exit code 1 on any error.
  • pack validates, refuses missing files, and writes <id>-<version>.refernplugin (see Packaging). It prints the file's size and SHA-256.

Extension directory commands

 refern-cli plugin submit < di r > --registry < checkou t > /registry --release < owner/repo@ta g > [--category < name > ] ... [--tag < wor d > ]... [--license < spd x > ] [--payment free | needs-paid-service] [--support-url < url > ] [--owner < github-login > ] ... [--listing < images di r > ] [--index < file | url > ] refern-cli plugin check-entry < registry/ < i d >> [--package < fil e > ] [--version < v > ] [--index < file | url > ] [--app-version < v > ] [--save-package < file > ] 

See Publish to the extension directory for the whole flow.

  • submit reads the GitHub release (owner/repo@tag, or the release page URL), downloads its <id>-<version>.refernplugin asset, and writes registry/<id>/entry.json in your clone of the registry: the pin (SHA-256, size, permissions, minAppVersion) and the listing facts. For a listed extension it moves the listed version into versions. It copies icon.png and screenshot-<n>.* from --listing (default <dir>/listing), runs check-entry (with --index when given), and prints the git and gh steps for the pull request. It reads from GitHub and writes nothing there. GITHUB_TOKEN is used when set; GITHUB_API_URL changes the API host.
  • check-entry runs every directory check that needs no pull request: the entry's shape, the removed IDs and the kill list, look-alike IDs (and names, with --index: the directory's index.json, a file or a URL such as https://dl.refern.app/plugins/index.json; a name within one letter of a listed one fails), then the package itself. It downloads the pinned asset (or reads --package), checks the SHA-256 and size, and runs the package checks refern uses for its built-in extensions: the strict manifest, ZIP safety, files the manifest names, decoders that import nothing, pages that load nothing from outside the package, theme contrast, and permissions equal to the pin. Then the README and the listing images. --version checks an earlier version of the entry. Exit code 1 on any error.

Library commands

These need refern running with the Local API on and a token in REFERN_API_TOKEN (or --token). --url or REFERN_API_URL sets the address.

 refern-cli status # the open library and the token's scope refern-cli workspaces # the open library and its folders on disk refern-cli search sunset --tag sky --kind image --limit 50 refern-cli tag add < item-i d > < item-i d > --tag reference --create refern-cli tag remove < item-i d > --tag reference refern-cli import https://example.com/a.jpg --folder < folder-i d > --tag sky 

refern-cli api <method> </v1/path> sends any Local API request and prints the JSON answer. Use it for what the commands above do not cover.

 refern-cli api GET /v1/folders --query limit= 10 refern-cli api POST /v1/items/trash --body '{"itemIds":["<item-id>"]}' refern-cli api PATCH /v1/items --body @update.json # a JSON file; --body - reads stdin refern-cli api GET /v1/items/ < item-i d > /thumbnail --out thumb.webp 

--query <key=value> can be given more than once. --idempotency-key <key> makes a retried write safe. --out <file> saves a byte answer (GET only). A write may name workspaceId (from refern-cli status), so that it fails with workspace_changed if another library is open. Git Bash on Windows turns /v1/... into a Windows path, so there write v1/folders.

Manifest reference

Every key of a refern extension's manifest.json (apiVersion 1), its limits and checks, contribution points, and .refernplugin packaging.

Security model

How refern isolates the three extension tiers: validated theme data, sandboxed app frames with host-mediated network, and fuel-limited WebAssembly decoders with no imports.

On this page

@refern/plugin-sdkStart-upCalls, limits and errorsLibrary (Local API operations)SelectionUICommandsSettings, storage and networkImports, viewer and Managed ExifToolEventsHidden entry page that answers commands@refern/plugin-sdk/ui@refern/plugin-sdk/manifest@refern/plugin-sdk/protocolFormat decoder ABI@refern/sdk (the Local API client)@refern/cli (refern-cli)Extension commandsExtension directory commandsLibrary commands