Skip to content

Backend: main process

Your backend is loaded into the host's main (Node.js) process. It must default-export a definePluginMain() result. You author ESM, and the build emits CJS (esbuild via lore-plugin build; tsc when working inside the Lore Desktop repository) because the plugin loader calls require(). See Build and tsconfig for the full two-tier pipeline.

The three-phase lifecycle

register()  →  activate()  →  deactivate()

definePluginMain requires all three callbacks and throws at construction if any is missing. definePluginRenderer requires only register.

The factory you pass to definePluginMain runs as soon as the host require()s your module, before register() and whether or not the plugin ever activates. Put setup in activate(), not in the factory closure.

register(reg)

  • Synchronous. The return type is undefined.
  • The declared undefined return type (rather than void) exists to make async register() a compile error. TypeScript lets a void-returning callback return anything, so void would silently accept a Promise. Omitting the return statement is fine; a function with no return implicitly returns undefined.
  • Pure declaration. No I/O, no subscriptions, no data, no events, no commands. The registrar exposes only reg.log and reg.activateEagerly().
  • Call reg.activateEagerly() if your plugin needs to run at boot rather than waiting for a page navigation or an on-demand wake.

activate(ctx)

  • May be async. The host awaits it.
  • This is where side effects live: subscribe to events, expose data, register domains, spawn processes.
  • ctx is a MainActivationContext. It carries data, events, commands, register(domain), log, pluginId, pluginVersion, pluginPath, pluginDataPath, and source.

deactivate(ctx)

  • May be async. The host awaits it, with a guard timeout of 3 seconds.
  • deactivate() also runs when activate() throws or rejects, so it must tolerate state that activate() only partly set up.
  • The host automatically disposes everything registered through ctx. Event subscriptions are disposed before deactivate() runs. Domain and data registrations are disposed after it settles, so outbound calls still work during teardown.
  • Use deactivate() only for resources the host cannot see: timers, caches, child processes, file handles.

Example:

// ── main side ──
deactivate(ctx) {
  if (debounceTimer !== undefined) {
    clearTimeout(debounceTimer);
    debounceTimer = undefined;
  }
  diagnosticsHandle = undefined;
  summaryHandle = undefined;
  repositoryRoot = undefined;
  clearEslintCache();
  ctx.log.info("deactivated");
},

Nothing else is needed.

Design rationale

The three-phase split exists because declaration and side effects are different concerns. register() is where a plugin says what it provides, and activate() is where it starts doing work. The host can inspect every plugin's contributions before any I/O runs, which enables dependency ordering, UI pre-rendering, and safe partial startup.

The host owns the lifetime of everything registered through ctx, so deactivate() only needs to clean up resources the host can't see.

Complete backend skeleton

Here is a complete backend. The sections below explain each part.

// ── main side ──
import { definePluginMain, defineDomain, payload } from "@lore-vcs/desktop-plugins-sdk";
import type { MyContract } from "./contract";

export default definePluginMain<MyContract>(() => ({
  register(reg) {
    reg.activateEagerly();
    reg.log.info("registered");
  },

  activate(ctx) {
    const handle = ctx.data.expose("myKey", initialValue);

    const domain = defineDomain({
      events: {
        "plugin:@acme/my-plugin/thingDone": payload<{ id: string }>(),
      },
      commands: {
        "plugin:@acme/my-plugin/doThing": async (args, invCtx) => {
          const result = { done: true };
          ctx.events.emit("thingDone", { id: args.id });
          return result;
        },
      },
    });
    ctx.register(domain);

    ctx.events.on("repository.opened", (payloads) => {
      for (const { path, name } of payloads) {
        ctx.log.info(`opened ${name} at ${path}`);
      }
    });

    ctx.data.on("repository.current", (repo) => {
      if (repo) {
        ctx.log.info(`repo: ${repo.path}`);
      }
    });
  },

  deactivate(ctx) {
    ctx.log.info("deactivated");
  },
}));

Typed contracts

The PluginContract generic parameter gives end-to-end type safety across the bridge. Data-shape mismatches between your plugin and the host are caught at compile time, not at runtime:

import type { PluginContract } from "@lore-vcs/desktop-plugins-sdk";

export interface MyContract extends PluginContract {
  main: {
    data: {
      myKey: MyDataType;
    };
    commands: {
      doThing: { args: { id: string }; result: ThingResult };
    };
  };
}

Pass this type to definePluginMain<MyContract>() and definePluginRenderer<MyContract>(). The SDK enforces that your activate() exposes the declared data keys and that your domain commands match the declared signatures.

Wake on call: activation rules

A plugin either activates eagerly (opt in via reg.activateEagerly() inside register) or is woken lazily. The rule:

Note

Invocations and reads wake a plugin; subscriptions don't.

  • commands.call or commands.stream targeting a dormant plugin wakes it.
  • data.get targeting a dormant plugin's key wakes it.
  • data.on or events.on targeting a dormant plugin parks the subscription without waking the plugin.

A call or data read that reaches a plugin that is shutting down (deactivating or dead) fails immediately instead of waiting out the 30 s call timeout. Your own host-data subscriptions (ctx.data.on on host keys) are re-established when the app's renderer reloads, so you do not need to resubscribe.

Commands are registered in activate(), not register(), so a dormant plugin has none yet. This is not a chicken-and-egg problem: the host routes on the plugin id embedded in the command key, wakes the target plugin, and only then resolves the command. Waking always precedes resolution. If the command still is not registered after waking, the caller gets a distinct "unknown command" error rather than an activation failure.

Activation is trigger-agnostic. Your activate() may run because a page mounted, the app launched, another plugin called one of your commands, or another plugin read your data. Don't assume a reason, a caller, or any UI state.

defineDomain: declaring events and commands

defineDomain() bundles the declaration and implementation of both events and commands into a single domain object. You register the result with ctx.register(domain) inside activate().

// ── main side ──
import { defineDomain, payload } from "@lore-vcs/desktop-plugins-sdk";

const domain = defineDomain({
  events: {
    "plugin:@acme/my-plugin/analysisComplete": payload<{ fileCount: number }>(),
    "plugin:@acme/my-plugin/error": payload<{ message: string }>(),
  },
  commands: {
    "plugin:@acme/my-plugin/refresh": async () => { /* ... */ },
    "plugin:@acme/my-plugin/getInfo": (args: { id: string }) => { /* ... */ },
  },
});
ctx.register(domain);

Both sections are optional. A domain with only commands or only events is valid. The PluginDomainInput type is:

interface PluginDomainInput {
  readonly events?: Record<PluginKey, EventPayloadDecl<unknown>>;
  readonly commands?: Record<PluginKey, PluginCommandImpl>;
}

Data is the exception. Data keys are not declared in a domain. You expose them imperatively with ctx.data.expose(key, initialValue), which returns a live handle you write to over time. A domain declares things with implementations; a data key is a mutable value, not a declaration.

Contract section to API

PluginContract section Declared in Registered or exposed via
events defineDomain({ events }) ctx.register(domain) in activate()
main.commands defineDomain({ commands }) ctx.register(domain) in activate()
main.data n/a ctx.data.expose(key, initial) in activate()
renderer.data n/a createPluginDataHook / renderer store

Namespace and uniqueness

Registering a command outside your namespace throws CommandNamespaceViolation. Registering the same command twice throws CommandAlreadyRegistered.

The lending rule

Your commands run with your grants. When another plugin calls your command, your handler executes under your plugin's access grants, not the caller's. The caller only needs the call: grant to reach your command.

invCtx.caller

invCtx.caller lets you check who called and decide whether to proceed:

// ── main side ──
const domain = defineDomain({
  commands: {
    "plugin:@acme/my-plugin/sensitiveOp": async (args, invCtx) => {
      if (invCtx.caller && invCtx.caller !== "@acme/trusted-partner") {
        throw new Error("not authorized");
      }
      // ... proceed
    },
  },
});

Key facts about caller:

  • It is the calling plugin's claimed id. It is policy-grade, not proof-grade, and is not cryptographically verified.
  • All native plugins share one renderer process, and the preload exposes ipcRenderer with no per-plugin channel allowlist, so a plugin can post using another plugin's id.
  • It is safe for logging, metrics, and soft policy. It is not safe as an authorization check.
  • It is present on cross-plugin calls and undefined for host-provided (main-domain) commands.
  • The host never invokes plugin-registered commands directly. Every invocation originates from a plugin (its own backend, its own renderer, or another plugin).

Node features in packaged builds

Packaged builds turn off some Node features through Electron fuses. pnpm dev keeps them, so test a packaged build before you ship:

  • child_process.fork() starts another Lore Desktop, not a Node child. Use Electron's utilityProcess.fork() or worker_threads.
  • NODE_OPTIONS and NODE_EXTRA_CA_CERTS are ignored, so Node's fetch() behind a TLS-intercepting proxy fails unless the proxy's certificate is trusted some other way.
  • --inspect flags are ignored, so a debugger cannot attach to the main process.

Where plugin data goes: ctx.pluginDataPath

Warning

ctx.pluginDataPath resolves to a data folder inside the plugin directory. In development that is inside the plugin's source tree, and in a packaged build it is inside the signed application bundle. Neither is a safe place to write.

Workaround: write to the OS temp directory, keyed by a hash of the repository path. The pattern is an atomic write (temp file plus rename) with a TTL ceiling:

// ── main side ──
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

const CACHE_DIR = join(tmpdir(), "my-plugin-cache");
const MAX_AGE_MS = 24 * 60 * 60 * 1000;

function repoHash(repoPath: string): string {
  return createHash("sha256").update(repoPath).digest("hex").slice(0, 12);
}

function cachePath(repoPath: string): string {
  return join(CACHE_DIR, `data-${repoHash(repoPath)}.json`);
}

Implement readCache and writeCache using atomic writes (temp file plus rename) with a TTL ceiling.

Your backend exposes data and handles commands, but the user sees your plugin through its renderer contributions. The next page covers pages and slots.

Renderer slots and pages →