SDK Backend API
2026-11-15
API reference for the plugin backend (a Node process): the context object, document and resource access, services and scheduled tasks. For concepts and the task model see Plugin SDK Overview.
The PluginContext
definePlugin(activate) receives a context and may return a cleanup function (sync or async) that runs on deactivation:
export default definePlugin((context: PluginContext) => {
// register every command and service declared in the manifest
return async () => {
// release connections, listeners, etc.
}
})
| Property | Type | Notes |
|---|---|---|
| apiVersion | 1 | API major version |
| apiRevision | number | API revision supported by the host |
| pluginId | string | Plugin identity assigned at install |
| generation | string | Activation generation; changes after fault restarts and invalidates stale responses (STALE_GENERATION) |
| dataDir | string | Private data directory; the host backs it up before updates |
commands
| Method | Signature | Notes |
|---|---|---|
| register | register(id, handler) | Register a command; handler receives (args, invocation). Register everything during activation, matching contributes.commands |
A command's return value becomes the host-held task result, under 1 MiB per call; large documents and images are chunked by the plugin. Task lifecycle is described under "Invocation & task states".
services
| Method | Signature | Notes |
|---|---|---|
| provide | provide(id, methods) | Provide a service; method keys match the manifest, values are (args, invocation) handlers |
| call | call(plugin, service, method, args, invocation?) | Call another plugin's service; passing invocation propagates the call chain |
| list | list() | List currently available services |
Service calls are limited to 20 seconds and depth 8; cycles fail immediately. The shared export contract export.text v1: the service method transform({text, format: 'markdown', filename}, invocation) returns {text}; it is used only after the user picks the provider in the plugin center, and provider failures surface as errors rather than silently falling back.
events
| Method | Signature | Notes |
|---|---|---|
| on | on(name, handler) | Subscribe; handler receives (event, {signal}) with id, name, workspaceId, payload |
| emit | emit(name, payload) | Emit; the plugin namespace is added automatically as plugin:pkgname:name |
Built-in events: startup, workspace.opened, document.committed, plus other plugins' plugin:pkgname:name. Workspace restores also emit open events; document.committed only covers wired commit paths, not every Node file change. When the queue is full events are dropped and logged; delivery is not guaranteed — consumers re-read domain state and keep business checkpoints in storage.
credentials
| Method | Signature | Notes |
|---|---|---|
| get | get(key) | Read a credential, string or null |
| set | set(key, value) | Write a credential |
| delete | delete(key) | Delete a credential |
Credentials live only in the backend process: Windows uses DPAPI bound to the current user, macOS the login Keychain, Linux the system secret service. Credentials must never enter the manifest, sources or page state.
Shared API (same names and semantics in both contexts)
| Namespace | Methods | Notes |
|---|---|---|
| documents | snapshot(target) / export(request) / apply(change) / operation(operationId) | Core document reads and writes; export reads an immutable Markdown snapshot in chunks — see "Document operations" |
| workspace | list() / resources(req) / read(req) / search(req) / import(req) | Workspace and resource files — see "Resources & images" |
| images | list(req) / read(req) | Paged image library and chunked reads — see "Resources & images" |
| storage | get(key, workspaceId?) / set(key, value, workspaceId?) | Plugin KV store with JSON values; with and without workspaceId are separate namespaces |
| views | open(view, options?) | Open a page, returns a ViewSession; the backend also has close(instanceId), which refuses dirty pages |
| ui | notify(message) / openFile(options?) / saveFile(options?) / openExternal(url) / openDocument(target) | System notification; open/save dialogs return the chosen path; openExternal accepts HTTP(S) only and opens the system browser; openDocument (revision 3) locates and opens a document in the main window |
Backend-only: ai.run({conversationId, text}) sends a message into an existing AI conversation and returns a JSON result.
Document operations (documents)
Core documents (chapter text and the like) follow optimistic concurrency in three steps: snapshot first, then apply with revision, draftHash and a unique operationId:
const snap = await ctx.documents.snapshot({
workspaceId, workspaceSession, documentId, editorId, windowId,
})
const op = await ctx.documents.apply({
workspaceId, workspaceSession, documentId, editorId, windowId,
operationId: crypto.randomUUID(),
revision: snap.revision,
draftHash: snap.draftHash,
content: nextText,
})
- The same operationId with the same normalized arguments returns the original record instead of resubmitting; different arguments are rejected (
OPERATION_CONFLICT); - Visible conflicts arise when the document, tags, workspace, draft or persisted version changed, or other dirty editors, external edits or tab switches happened;
- Changes go through the target editor's transaction and the existing save flow, preserving that editor's undo; arbitrary cross-file side effects are not guaranteed reversible;
- After an apply timeout, confirm via
documents.operation(operationId)before retrying; unconfirmed operations after a crash becomeuncertain; - Operation receipts are capped at 10000 in the current log directory; new operations are refused at the cap;
- Writing files directly with Node bypasses all of these guarantees.
For publishing, reading and exporting prefer chunked export (revision 1): documents.export creates an immutable Markdown v1 snapshot returned as UTF-8 byte-offset chunks (96 KiB each, 32 MiB total) with SHA-256; up to 4 unfinished snapshots per plugin and 64 MiB per host, the last chunk releases the snapshot, unfinished snapshots expire after two minutes. The readDocument(documents, target, options) helper wraps chunking and verification and returns the full {content, hash, revision, draftHash, dirty}:
import { readDocument } from 'blc-plugin-sdk'
const doc = await readDocument(ctx.documents, target, { timeoutMs: 30000, signal })
// doc.content is Markdown v1 — no need to understand host Tiptap nodes
Opening a page may unmount the source editor, so capture the document with readDocument first and open the page with views.open afterwards; never rely on the original editorId remaining available.
Resources & images (workspace and images)
| Method | Notes |
|---|---|
| workspace.list() | List workspaces (WorkspaceRecord: id, rootPath, title, createdAt, lastOpenedAt) |
| workspace.read(req) | Read UTF-8 text, returns content and hash (for import's expectedHash); 512 KiB per call, 16 MiB total per text file |
| workspace.resources(req) | List resources by path; entries are ResourceEntry records with the published API 1 casing (Rel, Parent, Name, Title, Kind, Editable, Ext, IsDir, Size, ModTimeUnix, Hash, …) |
| workspace.search(req) | Search resources by keyword |
| workspace.import(req) | Write UTF-8 text: with expectedHash it is a conditional overwrite (mismatch fails); without it a new file is created and existing files cannot be overwritten; 700 KiB per call, operationId required |
| images.list(req) | Paged images, 100 per page, returns {items: {id, name, src, width, height}, total} |
| images.read(req) | Image as data URL in chunks (addressed by src), 384 KiB per chunk, 28 MiB total; pass the first chunk's hash onward, changes report RESOURCE_CHANGED |
ResourceEntry.ModTimeUnix is Unix nanoseconds: divide by 1_000_000 for JavaScript milliseconds and validate before toISOString(). Browser pages bind to their workspace identity automatically and may omit workspaceId/workspaceSession; the Node side must pass them explicitly. After a workspace switch, reads from the old page are rejected. Larger or binary resources go through Node file APIs with your own concurrency handling.
Typical custom-editor write:
const result = await sdk.workspace.import({
workspaceId, workspaceSession, path: 'notes/example.catnote',
expectedHash: loadedHash, content: nextText, operationId: crypto.randomUUID(),
})
Scheduled tasks (schedules)
The manifest declares {id, command, intervalSeconds, catchUp}. Checkpoints live in the install index and survive restarts: past the interval plus a 5-second grace, skip drops the run and once catches up at most once; the same command never overlaps itself. The checkpoint is saved before scheduling — if saving fails nothing runs; a crash between the two steps may skip one round and exactly-once is not guaranteed. Long tasks keep business checkpoints in storage and re-read domain state on activation.