Skip to main content

Host API

The PluginHostApi contract: plugin identity, lifecycle, panel pushes and status surfaces, agent observation and input, notifications and tasks, provider and service registration, accounts, artifacts, and capability-gated process, filesystem, Git and clipboard access.

Updated
Reviewed

The host API is the runtime surface a plugin's activate function receives. It exposes Daintree's state and lets a plugin register behavior that the manifest cannot describe statically. Where the manifest and contribution points declare what a plugin is, the host API is what it does once it is running.

Types come from @daintreehq/plugin-sdk. The only npm release is still 0.1.0, from September 22, 2026; the SDK in the app repository is 0.2.0. Much of this page is newer than the npm types: databases, documents, the host.agents and host.terminals namespaces, panel menus and reload, the newer status surfaces, notifications and tasks, accounts, services, artifacts, the newer provider registrations, and project- and host-targeted dispatch. The running app provides all of them, but their types are only in the source SDK until the next release. Older members such as registerForgeProvider, registerFileDecorationProvider, getAgentState, sendToActiveAgent, and setPanelBadge are already typed in 0.1.0. See Building & Distributing for what that means in practice.

Filtering needs JavaScript. The contents list works without it, and so does your browser's find-in-page — every section on this page is in the document.

The activation contract

A plugin's main module exports an activate function. It may return a cleanup function, which runs when the plugin is unloaded: on hot reload, disable, uninstall, or app quit.

import type { PluginHostApi } from "@daintreehq/plugin-sdk";

export async function activate(host: PluginHostApi) {
  await host.registerAction(
    { id: "sync-now", title: "Sync Now", description: "Refresh project data.", category: "Dashboard", kind: "command", danger: "safe" },
    async (args) => ({ ok: true })
  );

  return () => {
    // optional cleanup: runs on unload, uninstall, dev reload, or app quit
  };
}

Activation is lazy by default. Nothing imports main until one of the plugin's contributions is first used: a command is dispatched, a contributed panel is opened, a forge operation reaches one of its providers, or a file-decoration pull matches one of its scopes. Listing "onStartupFinished" in activationEvents is the single eager trigger, and it fires once startup has settled rather than on the boot path.

A plugin that only needs to react to a few events can stay lazy with the manifest's top-level eventRoutes: each entry names an event (agentWaiting, worktreeAdded, worktreeRemoved, or projectForeground) and one of the plugin's commands. When the event happens the host activates the plugin if needed and runs the command with one PluginEventRouteWake object: { event, agent }, { event, presence }, or { event, worktrees, change }. One route per event; the command must be one the manifest declares and not danger: "confirm", and agentWaiting needs agent:read. Unlike a live subscription, a route holds no worker open, so an idle plugin can still be disposed. Wakes are best effort: bursts coalesce, a plugin is woken at most about once a second, and nothing is replayed on load.

The activation timeout is 5000 ms. If activate has not resolved by then, the plugin is marked failed and a toast surfaces. Keep activation to registration and cheap setup; defer real work into command handlers and subscription callbacks.

Anything registered through the host is torn down for you. If activate throws after it has already registered handlers, actions, or subscriptions, the host rolls all of them back. Cleanup is host-owned, including the registrations tracked on behalf of a user-installed plugin's worker. Do not try to undo your own registrations in a catch; let the error propagate.

The API surface

The outline below groups common members by purpose; it is not a substitute for the complete public type definitions and generated SDK declaration report.

interface PluginHostApi {
  readonly pluginId: string;
  readonly pluginInfo: PluginIdentity;
  panelKindId(bareId: string): string;

  // Registration: activation window only
  registerAction(descriptor, handler): Promise<void>;
  registerHandler(channel, schema, handler, options?): Promise<void>;
  broadcastToRenderer(channel, payload): Promise<void>;
  registerForgeProvider(descriptor, impl): Promise<() => void>;
  registerFileDecorationProvider(descriptor, impl): Promise<() => void>;
  registerSearchProvider(id, provider): Promise<() => void>;
  registerContextProvider(descriptor, impl): Promise<() => void>;
  registerWorktreeSetupStep(stepId, handler): Promise<() => void>;
  registerWorktreeDeleteNotesProvider(descriptor, impl): Promise<() => void>;
  registerCloudProvider(descriptor, impl): Promise<() => void>;
  registerService(name, handlers): Promise<() => void>;
  readonly mcp: { registerTools(endpointId, tools) };          // mcp:expose

  // Observation: subscribe during activate, react for the plugin's lifetime
  onDidChangeActiveWorktree(cb, options?): Promise<() => void>;
  onDidChangeWorktrees(cb, options?): Promise<() => void>;
  onDidChangeAgentState(cb, options?): Promise<() => void>;   // agent:read
  onDidChangeTerminalLifecycle(cb): Promise<() => void>;      // agent:read
  onDidChangeAllAgents(cb, options?): Promise<() => void>;    // agent:read, installed only
  onDidChangeFocusedPanel(cb, options?): Promise<() => void>; // panel:focus-read
  onDidChangeProjectPresence(cb, options?): Promise<() => void>;
  onDidChangePanelLifecycle(cb): Promise<() => void>;
  onDidWake(cb): Promise<() => void>;

  // Reads: callable for the plugin's whole lifetime
  getActiveWorktree(): Promise<PluginWorktreeSnapshot | null>;
  getWorktrees(): Promise<PluginWorktreeSnapshot[]>;
  getWorktreesResult(): Promise<PluginWorktreesResult>;
  getWorktreeStatus(path, options?): Promise<PluginWorktreeStatus | null>;
  getAgentState(): Promise<PluginAgentSnapshot | null>;      // agent:read
  readonly agents: PluginAgentsApi;      // list, listAll: agent:read; interrupt, sendKeys, submit: agent:input
  readonly terminals: { readScreen(terminalId, options?) };  // terminal:read
  readonly remoteHosts: { list() };                          // host:dispatch, installed only

  // Live runtime surface: callable for the plugin's whole lifetime
  postToPanel(channel, payload, panelId?): Promise<void>;
  hasListeners?(channel): boolean;
  onDidChangeListeners?(channel, cb): () => void;
  setPanelBadge(panelId, badge): Promise<void>;
  setPanelMenuItems(panelId, items): Promise<void>;
  setPanelActivity(panelId, activity): Promise<void>;
  setToolbarButtonBadge(buttonId, badge): Promise<void>;
  setToolbarButtonState(buttonId, state): Promise<void>;
  setContext(key, value): Promise<void>;
  setWorktreeCardStatus(worktreeId, status): Promise<void>;
  setWorktreeReviewChecks(worktreeId, checks): Promise<void>;
  setTerminalStatus(terminalId, status): Promise<void>;      // agent:read
  reloadPanel(panelId): Promise<PanelReloadResult>;
  restartWorker(): Promise<WorkerRestartResult>;
  invalidateFileDecorations(scope, paths?): Promise<void>;
  dispatch(actionId, args?, { projectId?, hostId? }?): Promise<ActionDispatchResult>;
  readonly actions: PluginHostActionsApi;
  sendToActiveAgent(text, options?): Promise<void>;          // agent:input
  sendToAgent(text, options?, callOptions?): Promise<PluginSendToAgentResult>; // agent:input
  runRecipe(recipeId, options?, callOptions?): Promise<PluginRunRecipeResult>;
  showToast(options): Promise<void>;
  notify(options): Promise<PluginNotifyResult>;
  showQuickPick(items, options?, callOptions?): Promise<...>;
  showInputBox(options?, callOptions?): Promise<string | undefined>;
  showConfirm(options, callOptions?): Promise<boolean>;

  readonly settings: SettingsApi;
  readonly account: PluginAccountApi;      // contributes.account / connections
  readonly services: PluginServicesApi;    // contributes.services.requires
  readonly storage: StorageApi;
  readonly db: PluginDatabaseApi;          // contributes.databases
  readonly logger: PluginLogger;
  readonly process: PluginProcessApi;      // shell:exec
  readonly tasks: PluginTaskApi;
  readonly fs: PluginFsApi;                // fs:*
  readonly git: PluginGitApi;              // git:*
  readonly clipboard: PluginClipboardApi;  // clipboard:*
  readonly system: PluginSystemApi;        // fs:* (openExternal: per-site consent)
  readonly documents: PluginDocumentsApi;  // fs:*-write
  readonly artifacts: PluginArtifactApi;   // artifact:store
}

Host operations are asynchronous. This changed when plugins moved out of process: operations and registrations are bridged over a MessagePort, so registrations resolve Promise<void> and the subscription and register*Provider methods resolve Promise<() => void> rather than returning a disposer synchronously. await a registration for its local result or disposer, and a subscription to get its disposer. From a worker, registerAction and registerSearchProvider resolve once sent and the host validates them afterwards; a refusal fails activation, so a successful activation is the confirmation. pluginInfo is immutable identity data and panelKindId() is a synchronous helper. logger is also synchronous: its info / warn / error calls return void and never throw. hasListeners and onDidChangeListeners are synchronous too, so a producer can check them on every push; they are optional in the type, so call them optionally. Two listeners return a disposer synchronously and may be added at any time: host.account.onDidChange and a database handle's onDidChange.

Subscriptions whose events arrive in bursts (the worktree list, the active worktree, agent state, the all-agents list, project presence) are coalesced by default: a burst becomes a trailing callback carrying the latest value for each key (per terminal for agent state, per project for presence), with a 100 ms window (250 ms for focused-panel changes). A steady stream still delivers at least every four windows. Pass { debounceMs: 0 } as the subscription's options to receive every event. onDidChangeWorktrees also passes a second argument naming the worktree ids added, removed, and changed since the previous delivery. Terminal lifecycle events are never coalesced.

Revoke-guarded versus the live runtime surface

The single most load-bearing distinction in the API is when a method may be called. Registration closes when activate() resolves or times out. The runtime methods remain usable while the plugin is loaded; the word “revoked” here refers to that activation window, not to a user revoking project trust.

GroupMethodsRule
Revoke-guarded (activation window)registerAction, registerHandler, broadcastToRenderer, every register*Provider, registerWorktreeSetupStep, registerService, mcp.registerTools, every host.onDidChange* subscription except onDidChangeListeners, onDidWake, settings.onDidChange, storage.onDidChangeMust be called during activate(). They throw once the host is revoked.
Live runtime surfacepostToPanel, hasListeners, onDidChangeListeners, every set* status call, reloadPanel, restartWorker, invalidateFileDecorations, getActiveWorktree, getWorktrees, getWorktreesResult, getWorktreeStatus, getAgentState, agents.*, terminals.readScreen, remoteHosts.list, dispatch, actions, sendToActiveAgent, sendToAgent, runRecipe, showToast, notify and the prompts, tasks.start, process.spawn, fs.*, git.*, clipboard.*, system.*, documents.*, artifacts.*, db.*, account.*, services.*, settings.get / set / unset / open / missingRequired, storage, loggerCallable for the plugin's whole lifetime, from timers and subscription callbacks. After unload they become a silent no-op, resolve an empty or "unavailable" answer, or reject, depending on the method: process.spawn, fs, git, clipboard, system, documents, artifacts, account, and db.open reject.

Subscribing to a host event counts as an activation-window operation even though the callback fires much later; the account and database-handle listeners are the exceptions. The shape a plugin should settle into is: register everything during activate(), then react for the rest of its life. postToPanel is the canonical post-activation push: activate() subscribes once, and the plugin streams live data into its panels forever afterward.

Always await host calls so validation and worker-bridge errors surface at the call site.

A liveness no-op (the plugin already unloaded) still resolves cleanly. Only a genuine validation error (an empty channel, a malformed badge) rejects. The split is encoded in the types, not just in prose: the revoke-guarded methods are factored into a PluginActivationApi sub-interface, each carrying a @throws tag that shows up on hover.

Actions and keyboard shortcuts

Most plugins expose their behavior as actions. Manifest-declared contributes.commands covers the static case; registerAction binds a handler with the live host. A lazy plugin must also declare a discoverable command or another activation trigger; a dynamic command created only inside an unreachable activate() will never appear.

await host.registerAction(
  {
    id: "plan-from-issue",           // no plugin prefix, the host adds it
    title: "Plan From Issue",
    description: "Turn a Linear issue into a branch and agent session.",
    category: "Linear Planner",
    kind: "command",
    danger: "confirm",               // "restricted" is rejected
    keywords: ["linear", "plan"],
  },
  async (args) => {
    return { ok: true };
  }
);

The descriptor id must not carry the plugin prefix. Daintree namespaces it to publisher.name.id at runtime. Re-registering an id replaces the prior registration. Colliding with a built-in action id is a load error.

A plugin may register safe or confirm actions; restricted is reserved for Daintree itself and rejected. The renderer reads effectiveDanger, not the declared danger. The host derives it and may only raise, never lower. Holding a high-risk capability raises every action the plugin registers, which is why requires exists on individual commands. See Trust & Capabilities.

Plugin actions are ordinary actions once registered: they appear in the launcher, they can be bound to a key from Settings > Keyboard, and a plugin can ship its own default bindings through contributes.keybindings.

dispatch runs any action (the plugin's own, another plugin's, or a built-in) through Daintree's audited dispatch path with a "plugin" source. There is no bypass: a confirm action returns CONFIRMATION_REQUIRED rather than executing.

const result = await host.dispatch("git.commit", { message: "fix: typo" });
if (!result.ok) {
  // result.error.code: "RESTRICTED" | "CONFIRMATION_REQUIRED" | "PLUGIN_UNLOADED" | ...
}

// Pre-flight instead of guessing:
const entry = await host.actions.get("git.commit");        // null if unknown or restricted
if ((await host.actions.canDispatch("git.commit")) === "confirm") {
  // dispatch will return CONFIRMATION_REQUIRED; it does not show a prompt itself
}

By default a dispatch runs in the focused project's view (a project-bound plugin's in its own project's). Pass { projectId } as the third argument to run it in a named project instead, with ids from host.dispatch("project.getAll"). An app-global plugin must declare project:dispatch and the user must turn on Allow project targeting for it, or the call rejects with PERMISSION_REQUIRED. A project-bound plugin (a repository plugin, or an installed package with "instanceMode": "project") may name only its own project, and needs neither. A project with no live view rejects with PROJECT_VIEW_UNAVAILABLE: nothing opens or wakes a closed project. When the project is on a host nobody is driving, a dispatch answers NO_FRONTEND_ATTACHED. The one exception is an app-global plugin's targeted terminal.close, which Daintree runs itself and answers with { closedIds }.

Add hostId beside projectId to run the action in a project on a Remote Host this machine drives. That needs the host:dispatch capability and the user's Allow host targeting switch, and only an app-global plugin can have it. host.remoteHosts.list(), under the same gate, returns the hosts this machine drives, each with its connection state (connected, connecting, or disconnected) and its projects, which is null when they could not be read in time. The remote host admits the call as this plugin from this machine and holds it to a plugin dispatch's rules there: built-in actions only, nothing restricted or confirm-gated, and its own setting for accepting tools run from other machines.

Pushing data into panels

registerHandler and broadcastToRenderer are the low-level IPC pair, registered during activation. The callback receives (ctx, args): host context first, the caller payload second. The typed registerHandler overload takes a schema with Zod args / result shapes plus a requires capability list; the host rejects registration when a required capability is missing, validates args before the handler runs, and validates the result before it returns. Failures carry a SCHEMA_ERROR: or PERMISSION_REQUIRED: prefix that the renderer hook discriminates on.

postToPanel is the post-activation sibling of broadcastToRenderer. It fans out over the same transport but stays callable for the plugin's whole lifetime, which makes it the channel a plugin actually streams over.

// main: from a timer, a poll, or a subscription callback
setInterval(async () => {
  const status = await fetchBuildStatus();
  await host.postToPanel("build-status", status);        // every open instance
  await host.postToPanel("build-status", status, panelId); // one instance
}, 5000);
// view: bundled with @daintreehq/plugin-vite
import { usePluginEvent, usePluginPanelEvent } from "@daintreehq/plugin-sdk/react";

usePluginEvent<BuildStatus>(pluginId, "build-status", setBuildStatus);
usePluginPanelEvent<BuildStatus>(pluginId, "build-status", panelId, setBuildStatus);

Omit panelId (or pass null) to broadcast to this plugin's subscribers for the channel. Pass a non-empty panelId to target one instance, so two open copies of the same panel no longer both receive every push. An empty-string panelId is rejected. Delivery is fire-and-forget: there is no acknowledgement, and a panel that is not mounted simply does not receive the payload. Pushes go only to windows whose views subscribe to that channel (or that panel), and pushes queued within one tick reach a window as a single batched message, in order, with nothing dropped.

hasListeners(channel) says whether any view in scope currently subscribes to a channel, and onDidChangeListeners(channel, cb) reports when that flips. Use them to skip producing pushes nobody is listening to, but only for state a view can recover by pulling when it mounts: a skipped push is gone for good.

Transport limits

The bridge enforces a few limits, each failing the call with a named error rather than degrading the app:

LimitValue
Invoke deadline5 minutes by default. A typed registerHandler can set its own timeoutMs, or 0 for none. An expired call rejects with PLUGIN_INVOKE_TIMEOUT and aborts the signal handed to a worker handler.
Invoke arguments4 MiB serialized.
Invoke result16 MiB serialized.
One push payload1 MiB serialized.
Host calls from a worker60 seconds by default. 120 seconds for fs.walk, git.status, git.diff, and a dispatch to a Remote Host; 6 minutes for a dispatch that names an agent preset, and for a call that may first wait on a consent dialog or keychain prompt, such as git.add, git.commit, fs.writeFile, and the agent input calls. No deadline for the three prompts, an untargeted sendToAgent, runRecipe, and artifact transfers; services.call waits for its own timeout plus a short grace. Enforced in the worker, so it fires even when the main process stops answering. An expired call rejects with code TIMEOUT, which never proves the host did nothing.

Oversized or uncloneable payloads fail with PLUGIN_PAYLOAD_TOO_LARGE or PLUGIN_PAYLOAD_UNCLONEABLE. Separate performance budgets (activation time, view load and paint, commit time, invoke latency, push rate, worker memory) are measured and shown to authors and users but never enforced; see Plugin UI Kit & Styling.

Panel badges

setPanelBadge overlays a small live indicator on a panel's title chrome, keyed by panel id. It exists so per-worktree or per-agent state (notes present, CI passing, review outstanding) surfaces without the user opening the panel.

await host.setPanelBadge(panelId, { kind: "dot", color: "warning", tooltip: "CI running" });
await host.setPanelBadge(panelId, { kind: "label", text: "3", color: "error" });
await host.setPanelBadge(panelId, null); // clear

Two shapes: a bare status dot, or a short label whose text is capped at six characters host-side so it cannot overflow the header. Color is semantic (default, success, warning, error) rather than a raw hex value, so badges stay consistent across themes. Pass null to clear. Badges are keyed by plugin and panel, so two plugins never overwrite each other's. A badge on a panel kind your plugin did not contribute is drawn neutral and names your plugin. A plugin badges at most 256 panels at once; a new panel past that rejects, while an update or a clear always goes through.

Panel menus, toolbars, and reload

A panel's ⋯ and right-click menus can carry your own actions from three sources, shown in this order inside your plugin's group: the manifest's menu entries, entries the view publishes with setMenuItems (or the SDK's usePanelMenuItems hook), and entries the worker publishes with host.setPanelMenuItems. Daintree's own entries keep their place.

// worker: the only way a PTY-backed panel, which has no view, gets entries
await host.setPanelMenuItems(panelId, [
  { actionId: "acme.ledger.export-month", label: "Export this month" },
]);
await host.setPanelMenuItems(panelId, null); // clear

Each call replaces your list for that panel. Every actionId must be one of your own actions, written publisher.name.id; an entry shows while its action is registered, is dispatched with { panelId } through the action's own danger tier, and labels default to the action's title and are cut at 80 characters. At most five entries per publisher. The list is not persisted: clear it when the panel reports removed, and publish again after a restart.

The manifest's panel toolbar buttons get their live state from the view: setToolbarItemState (or usePanelToolbarItem) sets busy, disabled, a warning or danger tone, a short status text, an updatedAt age drawn as "Updated 3h ago", and a tooltip. Independently, a header button shows busy while its action's handler is running, however that run was triggered, and the view sees the running set in runningActions (or useActionRunning).

A plugin panel can be reloaded from its menu, by the view with requestReload(), or by the worker with host.reloadPanel(panelId): the current view attempt is discarded and a fresh one mounts on the module already loaded, without restarting the worker. A view that holds work a reload would lose calls setHasUnsavedChanges(true), and a user or agent reload then asks first. Reloads share a per-panel budget of three per rolling 30 seconds, after which the view is stopped until the user reloads it. reloadPanel resolves a scheduling acknowledgment, not confirmation of a render, and a panel that is not mounted resolves "not-mounted". While a view has unsaved changes, closing its panel asks first too.

host.restartWorker() is the same restart as the Restart plugin button, for a plugin whose host calls keep timing out: panels rebind to the new worker rather than closing, and every call still outstanding in the old worker is abandoned. It resolves "scheduled" before the restart begins, "rate-limited" within 30 seconds of an accepted one, or "unavailable" for a built-in plugin, which has no worker.

Status surfaces and context keys

Beyond panel badges, a plugin can put its state where the user already looks, without opening its panel. Each call is a live push like setPanelBadge: not revoke-guarded, a silent no-op after unload, and a rejection for an invalid argument. The exception is from a worker: setPanelBadge and setToolbarButtonBadge reject only an empty id there, and a bad badge shape, a foreign button, or the panel cap is logged in the host's diagnostics after the call has resolved. None of them is persisted, and all are cleared when the plugin unloads or its worker is replaced, so republish after a restart. Every mark is attributed to the plugin.

CallWhere it showsLimits
setToolbarButtonBadge(buttonId, badge)One of your own toolbarButtons: in full on its tray row and in the overflow menu; as a count pill (capped at 9+) or a pip on a promoted button.Same badge shape as setPanelBadge.
setToolbarButtonState(buttonId, state)The same button: pressed for a toggle, disabled with a required disabledReason, busy, a replacement tooltip or iconId, and a replacement menu. Each call replaces the whole state; null returns to the manifest defaults. The label never changes, and a disabled or busy button still leaves its action dispatchable elsewhere.Tooltip and reason up to 200 characters.
setContext(key, value)Your own when-clause key, namespaced under your manifest name: setContext("needsYou", true) from acme.beads is read as acme.beads.needsYou. Keybindings and context menus can then follow your state. Application menuItems do not see it.32 keys per plugin, keys up to 64 characters with no dots, string values up to 256.
setWorktreeCardStatus(worktreeId, status)A chip on a worktree card, one per plugin per worktree.Label up to 32 characters, tooltip up to 512.
setWorktreeReviewChecks(worktreeId, checks)Advisory checks in the Review Hub's readiness rail and in the worktree.reviewReadiness tool. They never change whether commit or push is ready.Up to 10 checks, each warning or info, label up to 120 characters, detail up to 2048.
setTerminalStatus(terminalId, status)A colorless chip on an agent terminal's header. Requires agent:read; ids come from agents.list().Same label and tooltip limits as a card status; 256 per project.
setPanelActivity(panelId, activity)One of your own panels, drawn the way agent activity is: working, waiting, finished, or failed, with an optional one-line reason. Only for a panel kind declared with reportsActivity: true.Reason up to 120 characters; 256 panels.

A card status, a review check, and a terminal status can carry a command: one of your own actions, written publisher.name.id, which turns the mark into a button. A click dispatches it with { worktreeId } (or { terminalId, worktreeId? } for a terminal), so a declared inputSchema must accept that. Until the action is registered the mark stays plain text. Worktree ids must be ones the host can see right now, from getWorktreesResult().

Panel lifecycle

onDidChangePanelLifecycle reports what happens to the plugin's own panel instances. No capability is required: the host resolves ownership from its own kind registry, so a plugin only ever receives events for kinds it contributed.

export async function activate(host: PluginHostApi) {
  const servers = new Map<string, DevServer>();

  await host.onDidChangePanelLifecycle((event) => {
    if (event.phase === "removed") {
      servers.get(event.panelId)?.stop();
      servers.delete(event.panelId);
    }
  });
}
PhaseMeaning
mountedA view for this panel is rendered.
hiddenThe panel record is live but no view is mounted: a sibling pane was maximized, its dock tab is inactive, its project view is cached, or a retry is loading. Not a close.
backgroundedThe panel is in the background location.
trashedSoft close. Recoverable from the trash bin, so not permanent disposal.
restoredOne-shot edge out of the trash, emitted immediately before the phase the panel landed in.
removedTerminal. The panel is gone and will not return under this id.
render-failedThe current view attempt hit the host's error boundary. Cleared by a successful retry.

This is where durable resources belong. Keep spawned processes and long-lived sessions in the worker, keyed by panelId, and release them on "removed". A plugin that instead tears down on unmount kills work the user still wants back: maximizing a neighboring pane unmounts every other grid panel, and that must not stop a running dev server.

On subscribe the host replays the current phase of every live panel the plugin owns. That matters because activation is lazy: opening a view is usually what triggers activate(), so without replay you would never see that panel's mounted. One-shot and terminal transitions are not replayed. A renderer being destroyed or evicted never synthesizes removed. A cached project view says nothing about whether the user closed anything.

Placeholder panels and persisted state

Panel instances carry an opaque extensionState bag that survives session save/restore and project switches. When a panel's kind is no longer registered, because the contributing plugin was disabled or uninstalled, Daintree does not drop the panel. It renders a placeholder with a puzzle icon, a "Plugin unavailable" heading, the plugin id, and a Remove panel button, and it keeps extensionState on disk. Re-enable or reinstall the plugin and the panel comes back exactly as it was; a restored panel also recovers on its own once the plugin activates, rather than staying stuck until it is closed and reopened.

A newly invalid manifest registers no new panel kind. An already saved panel whose kind is missing can still show the placeholder, including after a previously valid plugin becomes invalid.

Workspace context

Read-only access to Daintree's worktree state through an explicit allowlist, so internal shape changes do not leak into plugins.

const active = await host.getActiveWorktree();       // or null
const all = await host.getWorktrees();
const status = await host.getWorktreeStatus("/Users/me/project/.worktrees/feature-x");

const dispose = await host.onDidChangeActiveWorktree((snapshot) => {
  if (snapshot) host.logger.info(`now on ${snapshot.name}`);
});
interface PluginWorktreeSnapshot {
  readonly id: string;
  readonly worktreeId: string;
  readonly path: string;
  readonly name: string;
  readonly customTitle: string | null;
  readonly isCurrent: boolean;
  readonly branch?: string;
  readonly isMainWorktree?: boolean;
  readonly aheadCount?: number;
  readonly behindCount?: number;
  readonly linked: PluginWorktreeLinked | null;
  readonly status: PluginWorktreeStatus | null;
  readonly headOid: string | null;
  readonly gitOperation: "merge" | "rebase" | "cherry-pick" | "revert" | "am" | null;
  readonly setup: PluginWorktreeSetup | null;
  readonly mood?: "stable" | "active" | "stale" | "error";
  readonly lastActivityTimestamp?: number | null;
  readonly createdAt?: number;
}

interface PluginWorktreeLinked {
  readonly providerId: string;
  readonly issue?: { ref: ResourceRef; title?: string };
  readonly pr?: {
    ref: ResourceRef;
    title?: string;
    url: string;
    state: NormalizedPRState;
    ciStatus?: CIStatus;
    baseRef?: string;
    mergeIntent?: PRMergeIntent | null;
  };
}

Every snapshot is frozen; mutating one throws. getWorktrees() returns the worktrees of the owning project for a project plugin, or the focused window's project for an installed plugin and is empty when no window resolves.

linked is a provider-agnostic projection of the worktree's linked forge resources. It replaced the GitHub-shaped issueNumber / prUrl / prState fields entirely: route through linked.providerId and the shared ResourceRef shape so a plugin works against any forge provider. baseRef is the branch the PR merges into, which is what drives base-branch divergence display.

lastActivityTimestamp is the canonical activity time in epoch milliseconds: the newer of HEAD's committer time and the newest dirty file's modification time, or null when neither has a valid time.

customTitle is the title the user gave the worktree, or null. headOid is the commit HEAD points at, sampled by the same status poll: a new value means HEAD moved, but a move that returns to the same commit between polls is not seen, and it holds its last value while a git operation pauses polling. gitOperation names a blocking merge, rebase, cherry-pick, revert, or am in progress; detection fails open, so null is an observation, not a promise that git is idle. setup reports post-create setup as a state (pending, running, ready, failed, timed-out, or needs-approval) and the stage running or failed; null means unknown, never ready.

status projects the host's already-polled worktree changes: a files array of path plus one of added, modified, deleted, untracked, renamed, a changedFileCount, and per-state counts. Reading it never shells out to a fresh git status. getWorktreeStatus(path) returns the same projection for a worktree you already have a path for, which is the common case when a context-menu dispatch handed you one. For staged-versus-unstaged detail or a real diff, use host.git.

Worktree subscriptions registered before the workspace service is ready are queued until it is available. Subscribe during activation and pull a snapshot when initializing a view; do not treat subscription setup as a historical event log.

Identity and project binding

host.pluginInfo exposes instanceId, manifestId, origin, projectId, and projectRoot. Throughout this page, a project-bound plugin is a repository plugin or an installed package with "instanceMode": "project", and an app-global plugin is any other. For a project-bound plugin, host.pluginId is an instance key; never parse it to recover identity. host.panelKindId("overview") qualifies an owned bare panel id for panel.openPluginPanel.

Project plugins bind dispatch, prompts, worktree reads, filesystem tokens, settings, storage, and renderer pushes to their owning project. An unavailable bound renderer does not fall back to the focused project. See project binding and persistence and the binding tests.

Unavailable is not empty

getWorktrees() returns an empty list both for a project with no worktrees and when no answer is available. Prefer getWorktreesResult() when the distinction drives a decision: it returns status: "ok" with projectId and worktrees, or status: "unavailable" with a reason. Do not delete a saved binding because an unavailable read looks empty.

onDidChangeWorktrees supports subscription options for coalescing updates. onDidWake lets background work revalidate after a machine resumes. Register it during activation; it needs no capability, is not replayed, and describes machine wake rather than a project change. Wake delivery follows the host's best-effort recovery attempt, which can itself have failed.

Project presence

onDidChangeProjectPresence reports where projects are: "foreground" while a window shows the project, "background" while it is open behind another one, and "closed" when it closes or is put to sleep. It needs no capability. A project-bound plugin hears only about its own project, and is unloaded as that project closes, so it may never see "closed"; an app-global plugin hears about every open project, never a scratch workspace. The current state is delivered once after subscribing, then each change, coalesced per project. Presence follows the project a window has switched to, not the user's attention: a project in an unfocused window is still "foreground". Use onDidChangeFocusedPanel for focus. A view reads its own project's presence with the SDK's useProjectPresence hook, for example to slow a poll while the project is in the background.

Agent state and agent input

getAgentState and onDidChangeAgentState observe agent activity and are gated on the agent:read capability. A state snapshot carries the agent's state and previous state, a waiting reason, session cost and tokens on completion, and the terminalId and workspaceId it belongs to. Coalescing delivers each terminal's latest transition in a burst, so previousState is the state just before that transition, not necessarily the last one you were told about.

Two more reads sit behind the same capability:

  • agents.list(): the live agent panes in the plugin's project, in grid order, each with its terminal id, title, agent id, worktree, observed state, focus, and whether it can take a draft.
  • agents.listAll() and onDidChangeAllAgents: every agent run across every open project and scratch workspace, including projects whose view is not loaded. App-global plugins only; a project-bound plugin is refused. Subscribe before the first listAll() so no change between the two is missed; a snapshot is degraded until the host has read the fleet once.
  • onDidChangeTerminalLifecycle: every terminal, plain shells included, starting (spawned), exited with its exit code, trashed, restored, and rate-limit-observed when an agent's rate-limit banner appears. One event per change, in order, never coalesced and never replayed, so there is no snapshot of terminals already open. An app-global plugin sees every workspace; a project-bound plugin sees its own project. Observation only: nothing here starts or stops a terminal.

Driving agents a plugin launched

A plugin that starts an agent itself, with host.dispatch("agent.launch", …), can keep driving it. Three methods on host.agents reach only the agents this plugin launched. A reload, or an upgrade of an app-global plugin, keeps that reach, and a local pane restored under the same id after an app restart regains it; any other unload ends it. Anything else answers not-found, as does an agent outside a project-bound plugin's own project or a launch that passed its own requestedId.

  • interrupt(terminalId) sends the agent's cancel keystrokes to stop the current turn, keeping the pane and conversation. An idle agent is refused rather than reported stopped.
  • sendKeys(terminalId, { keys } | { choose }) presses 1 to 16 named keys, one at a time, or chooses an option by its text: usually to answer the CLI's own trust or permission prompt.
  • submit(terminalId, text) submits one prompt or slash command with one Enter. It resolves once the input is queued, not once the agent reads it.

All three are gated on agent:input with the same first-use consent as sendToActiveAgent, which a call that would answer not-found never raises. They resolve sent, refused with a reason, not-found, or unavailable. Pass { hostId } to reach an agent this plugin launched on a Remote Host; that record lives only in memory, so it does not survive a restart. Launching on one of the person's agent presets needs the agent:launch-preset capability, and each preset asks once on first use.

host.runRecipe(recipeId, { variables, worktreeId }) offers to run one of the plugin's own recipes, filling its {{plugin.<name>}} variables. Nothing starts until the user confirms a preview showing every step with its prompts and arguments resolved. It needs no capability, never turns agent tools on for a recipe that requires them, and resolves ran with spawned and failed counts, cancelled, or refused with a reason.

Reading terminal screens

host.terminals.readScreen(terminalId, { lines }) returns the last 1 to 100 lines (default 20) of one terminal's current screen as plain text with no ANSI, capped at 16 KiB, never its scrollback. It is gated on terminal:read with its own first-use consent prompt, because a screen routinely shows tokens and environment dumps. Take ids from agents.list() or listAll(). A project plugin reads only its own project's terminals. The result is ok, exited, not-found, or unavailable (worth retrying). Calls are limited to 60 a second per plugin; past that they reject with RATE_LIMITED: rather than queueing. The host neither logs nor stores the text.

Observing panel focus

onDidChangeFocusedPanel, gated on panel:focus-read, reports which kind of panel has focus (a terminal, a browser panel, a diff), whether it is an agent, and its worktree id, never a panel's id, title, URL, or content. kind is null while Daintree is not the foreground window or nothing that is a panel has focus. A project plugin sees focus only inside its own project. The current focus is delivered once after subscribing, then every change, coalesced to 250 ms by default. PluginFocusedPanelKind still lists "portal" so an older plugin that compares against it compiles, but Daintree never reports it: the Portal it stood for is gone.

Sending text to an agent

sendToActiveAgent is the sanctioned injection path, gated on agent:input. The raw terminal.sendCommand action is closed to plugin dispatch specifically so plugins stop reinventing brittle terminal-selection heuristics.

// Stage the text for review: the default, no Enter appended
await host.sendToActiveAgent("Summarize the failing test and propose a fix.");

// Submit it immediately
await host.sendToActiveAgent("/compact", { submit: true });

The host resolves the target itself: the focused or visible agent terminal first, then a waiting agent, then the most recently active agent terminal in the active project. It never crosses a project boundary. submit defaults to false: the stage-only, default-safe mode that pastes the text for the user to review. First use raises a just-in-time consent prompt. It throws PERMISSION_REQUIRED: without the capability or on denial, and NO_ACTIVE_AGENT: when no agent terminal can receive input.

sendToAgent(text, options) is the hand-off for a view that wants the user to choose. The text is appended to an agent's visible draft as a fenced block headed by options.title and your plugin's name, below anything the user already typed, and nothing is ever submitted: there is no submit option. With terminalId the draft goes straight to that pane; without it the user picks from the project's agents grouped by worktree (an agent in options.worktreeId is preselected), or starts a new agent in that worktree or a new one. It uses the same agent:input consent, never moves focus, takes up to 32,768 characters, and resolves drafted, cancelled, or refused with a reason. drafted means the text is in the agent's input, not that anyone is working on it.

A view can also hand work over by drag, with no worker code and no capability: mark the element draggable and put an application/x-daintree-agent-context payload on the drag. Dropping it on an agent terminal lands the text in that agent's draft the same way.

Native prompts

A command often needs one more piece of information mid-flight. Rather than every plugin building its own modal inside a panel, the host exposes Daintree's own dialogs, so a plugin prompt looks and behaves like a native one.

const picked = await host.showQuickPick(
  [
    { id: "eng", label: "Engineering", description: "12 open issues" },
    { id: "des", label: "Design", detail: "Owned by @sam" },
  ],
  { title: "Pick a team", matchOnDescription: true }
);

const branch = await host.showInputBox({
  title: "Branch name",
  prompt: "Where should the worktree be created?",
  validationPattern: "^[a-z0-9/-]+$",
  validationMessage: "Lowercase, digits, slashes and hyphens only.",
});

const ok = await host.showConfirm({
  title: "Delete 'stale-cache'?",
  message: "The cache directory and its 412 entries are removed.",
  confirmLabel: "Delete cache",
  destructive: true,
});
  • showQuickPick: a searchable list. Items are plain id / label / description / detail strings. canSelectMany changes the resolved value to an array; matchOnDescription widens the fuzzy match beyond the label. Resolves undefined when dismissed.
  • showInputBox: a single-line input with an optional prompt, placeholder, pre-filled value, and password masking. validationPattern is checked client-side at submit time, so there is no per-keystroke IPC round trip; an invalid pattern is ignored rather than blocking the user.
  • showConfirm: a yes/no gate. title is required and should be a sentence-case question naming the entity. Set destructive for an irreversible action and give confirmLabel a verb-noun label, never a bare "OK".
  • showToast: fire-and-forget notification. The host prefixes the message with the plugin's display name (never the id, which for a project plugin is an instance key) so users can tell which plugin raised it. Messages are strings up to 2000 characters; type is info, success, warning, or error; durationMs is capped at 60 s. Toasts route through Daintree's normal notification path, so quiet hours and the inbox apply. The rate limit is per plugin, shared with notify, so a noisy plugin cannot suppress anyone else's toasts; past it a toast is dropped quietly. A plugin the user silenced, or a project the user muted, sends nothing.

The three prompts take a trailing callOptions. Aborting its signal dismisses the prompt and resolves the dismiss value rather than rejecting. When the project lives on a host nobody is attached to, a prompt rejects with NO_FRONTEND_ATTACHED: by default, so "nobody was there" never reads as "the person said no"; pass whenNoFrontend: "queue" to show it once a window attaches instead.

Notifications with actions

host.notify({ title, body, severity?, delivery?, target?, actions?, os?, dedupeKey? }) raises a notification through the same path, with up to two buttons, each running one of the plugin's own actions with optional args. An error must carry exactly one action, the way out of it. delivery: "passive" keeps it to the inbox. A target (one of the plugin's panels, or a worktree it can see) gives the inbox row a Go to source. A later call with the same dedupeKey replaces the earlier one instead of stacking, except in a window driving the project from another machine, which gets a plain toast without buttons or a replacement key. os: true also asks for an OS banner, which carries no buttons: clicking it brings the plugin's project forward and runs the first action. Without the notification:os capability, os: true rejects; with it declared, banners still stay off until the user turns on Allow OS notifications for the plugin, and the host drops them during quiet hours, while the user is looking at the plugin's project, or when the plugin pages too often. In each case the in-app notification still goes out.

Background tasks

host.tasks.start({ title, detail?, cancellable?, fraction?, retry }) shows long-running work in Daintree's own background-work readout, with Cancel when the task allows it. It needs no capability. The handle's report({ fraction?, detail? }) can be called on every item, since reports are coalesced before they cross a process boundary, and finish({ outcome: "succeeded" }) ends it; the other results are { outcome: "failed", message } and { outcome: "cancelled" }. A failed task raises an error notification naming the plugin with a Retry that runs retry.actionId, one of the plugin's own actions; a success shows at most a passive inbox entry. The handle's signal aborts when the user cancels or the plugin unloads, with signal.reason.cause saying which, and tasks still running at unload are marked interrupted. A plugin holds at most 16 unfinished tasks. The SDK's /operations entry builds durable, resumable remote operations on top of tasks and a host.db journal.

Note
A lazily-imported, filesystem-convention command handler receives args only: there is no second host argument, because that convention does not pass a host object. If your command needs to prompt, register it imperatively in activate() so the handler closes over the live host.

Capability-gated surfaces

The following host surfaces apply runtime policy rather than merely disclosing intent. Each is the sanctioned path for something a plugin would otherwise do by reaching for Node directly.

host.process: managed child processes

Gated on shell:exec. Like the other capability-gated surfaces, a spawn from a plugin that did not declare the capability rejects with PERMISSION_REQUIRED:.

const handle = await host.process.spawn("npm", {
  args: ["run", "dev"],
  cwd: "/path/to/project",   // defaults to the active worktree, then the host cwd
  env: { PORT: "5173" },     // applied over a minimal allowlist, not the host env
  panelId,                   // omit to broadcast the stream to every panel
});

handle.onData(({ stream, chunk }) => parseLine(chunk));
handle.onExit(({ exitCode, signal }) => host.logger.info("exited", { exitCode, signal }));
handle.onCrash(() => host.showToast({ message: "Dev server crashed", type: "error" }));

await handle.restart();
await handle.kill();

The host passes executable and arguments directly without implicitly invoking a shell. A plugin that explicitly launches a shell remains responsible for the command it passes. The handle carries a stable id, kill() (clean SIGTERM, then SIGKILL after a grace period), restart() (same command, same id, incremented restart counter), and onExit / onCrash subscriptions carrying the real exit code and signal. onCrash fires only on a termination you did not ask for. Output reaches the plugin's panels over postToPanel("process", …) keyed by handle id, and the plugin's own code via onData, which buffers output produced before the first subscriber attaches so a daemon that greets immediately is not missed.

The default mode is "pipe", with stdin closed. Pass mode: "duplex" for a piped child with a writable stdin, such as a language server or any stdio protocol.

Interactive processes get a real PTY. Pass mode: "pty" and the handle widens with write() and resize().

const pty = await host.process.spawn("claude", {
  mode: "pty",
  args: ["--resume"],
  cols: 120,
  rows: 40,
});

await pty.write("continue\n");
await pty.resize(160, 48);

A pseudo-terminal merges stdout and stderr, so PTY output arrives as a single data stream rather than the stdout / stderr pair. A panel rendering process output should handle all three kinds. The PTY is allocated in Daintree's crash-isolated pty-host process, so a native failure cannot take the app down. A resize() issued while a restart() is still allocating the replacement is retained and folded into the new PTY's initial size.

The child does not inherit Daintree's environment. It is built from a fixed allowlist of essentials (PATH, HOME, locale, temp directory, and the Windows keys a child cannot run without) plus whatever the call passes in env. This avoids copying the main process's entire environment into a shell:exec child. Anything else the command needs must be handed to it explicitly; take care with secrets supplied in env. cwd is a process concern, not a filesystem scope: it is not contained to scopes.fs.allowedPaths.

Every spawned process is tied to the plugin's lifetime. On unload, disable, or revoke the host terminates all of them, including the processes they started in turn, so a dev server cannot leak past a reload. At most eight run at once per plugin; a spawn past the cap rejects rather than queueing. Spawns are recorded in the plugin audit trail, and running plugin workers and their child processes are listed under Running processes in the sidebar footer's resource popover.

host.fs and host.git

const text = await host.fs.readFile("/Users/me/.acme/data/notes.md");
await host.fs.writeFile("/Users/me/.acme/data/out.json", JSON.stringify(result));
const dispose = await host.fs.watch(["/Users/me/.acme/data"], (changedPath) => { /* … */ });

const status = await host.git.status("/Users/me/project");
await host.git.add("/Users/me/project", ["src/index.ts"]);   // worktree-relative paths only
const { commit, preview } = await host.git.commit("/Users/me/project", {
  message: "fix: typo",   // required. There is no derived-message fallback
});

Both are contained: every path argument is realpath-resolved against the plugin's declared scopes.fs.allowedPaths, and a traversal or a symlink that escapes a root rejects with PATH_NOT_ALLOWED:. Reads gate on fs:project-read / fs:user-data-read, writes on the matching -write token. Unlike the app's internal file read, host.fs.readFile carries no size or binary cap. It is a deliberate plugin API. Writes are audited, and watchers are torn down on unload.

host.git runs over Daintree's existing hardened git layer, scoped to a worktree inside the same allowed paths. Reads gate on git:read, mutations on git:write; commit also requires git:read to produce its staged-diff preview. Pathspecs must be worktree-relative: an absolute path, a .. segment, or git pathspec magic is rejected, because git would otherwise resolve them against the whole repository. Paths are matched literally, not as globs, so a filename containing * or brackets resolves to itself; expand any pattern yourself. commit enforces the change-preview safeguard at the host layer: it refuses without an explicit non-empty message and computes the real staged diff as a preview before mutating, returning it so your UI can show what happened.

host.git covers status, diff (optionally for one file), add, and commit; host.fs covers readFile, readFileBytes, readFileWithRevision, readFiles, readdir, walk, stat, watch, writeFile, appendFile, and mkdir. For binary content, use fs.readFileBytes(); UTF-8 readFile() would corrupt image or archive bytes. readdir(path, { detail: true }) returns metadata and symlink classifications with directories-first, numeric-aware ordering, avoiding a round trip per entry. A link classified external is outside the allowed root used for that listing; unknown is a different state from an established scope escape.

The filesystem surface also covers the work a data-backed tool does next to agents editing the same files:

  • Conflict-checked writes. Every writeFile serializes per path, re-proves containment after the consent prompt, refuses a symlink target, and replaces the file atomically. It resolves the new file's revision (the SHA-256 of the bytes written). readFileWithRevision returns text plus its revision; pass that as expectedRevision and the write rejects with REVISION_MISMATCH instead of clobbering a change made in between. expectedRevision: null is an exclusive create. It is not a lock against an uncooperative external process.
  • appendFile adds to the end through one append descriptor, so concurrent appenders such as an agent writing to the same JSONL log each land at the end. mkdir creates missing directories one component at a time, each contained and audited.
  • readFiles reads up to 1024 paths in one round trip with up to 8 MiB of content, failing per entry rather than per call. walk lists a tree in one call, breadth-first, without following symlinks, respecting .gitignore by default, and bounded so a huge tree truncates predictably.

The SDK's /data entry wraps these in helpers for data kept as files (front matter, JSONL, and a retrying read, transform, conditional write loop). It is newer than the 0.1.0 SDK on npm, but a zero-build worker can import it from the app's own copy.

Read operations and Git calls accept trailing cancellation options where declared in the SDK; fs.writeFile does not offer a cancellation signal. A project plugin without explicit filesystem roots defaults to its bound project root; a declared allowlist replaces that default. The SDK /files entry supplies file-tree and Git-status helpers without importing React.

host.clipboard and host.system

host.clipboard runs in the main process, so it works from a headless plugin with no focused document. writeText is gated on clipboard:write and rejects above 8 MiB; writeImage takes PNG bytes under the same token and rejects above 20 MiB. readText is gated on clipboard:read and resolves to an empty string when the clipboard holds non-text content. Reads are text-only by design: there is no readImage, readHtml, or readFiles, because the read side is where richer payload types would let a plugin pull out more than it declared.

host.system.openPath and showItemInFolder hand a file to the OS, scoped to the plugin's own filesystem roots plus its implicit plugin-data namespace. The plugin id is bound when the host is built rather than passed as an argument, so one plugin can never name another's namespace. openPath refuses executable file types, checked on both the path passed and its realpath target so a benignly-named symlink cannot become a launch primitive.

host.system.openExternal(url) opens a web page in the user's browser on this machine; for a project driven from another machine it rejects before asking. It takes only https: URLs of at most 2048 characters without embedded credentials, is rate limited per plugin, and asks the user the first time a plugin opens a link to a given site; an allowed site is remembered for that plugin until it is uninstalled or replaced. Built-in plugins are not asked.

host.artifacts: large files

Gated on artifact:store. Artifacts are files the host holds for the plugin so bytes never cross the plugin's channel: import({ path }) copies a scoped file (needing the matching fs:*-read token), download({ url, headers? }) streams a provider file into the cache and upload(artifactId, { url, method?, headers? }) sends one as a request body (both needing network:fetch and a URL under scopes.network.allowedUrls), and stat, list, and release manage what is held. The plugin keeps metadata-only handles that never carry a path, URL, or bytes. A view plays or previews an artifact with the kit's MediaPlayer and MediaThumbnail, and takes the user's files in with FileDropzone.

Artifacts live for the session, for 1 minute to 24 hours (ttlMs), and go when they expire, are released, their project closes, the plugin unloads, or the cache needs room; a restart starts empty. A download retries up to three attempts, resuming where the provider supports ranges, and exists only once every byte has arrived. Request headers are dropped on any redirect that leaves the original origin and are never stored or logged. Every rejection carries a code such as ARTIFACT_NOT_FOUND, ARTIFACT_TOO_LARGE, ARTIFACT_QUOTA_EXCEEDED, or ARTIFACT_URL_NOT_ALLOWED.

Databases and documents

host.db opens the SQLite files declared in contributes.databases, by id. Queries run in the plugin's own process over Node's built-in node:sqlite; the host only resolves and contains the location.

const db = await host.db.open("ledger", {
  migrations: [
    "CREATE TABLE tx (id INTEGER PRIMARY KEY, cents INTEGER NOT NULL, note TEXT)",
  ],
});
const rows = await db.query("SELECT * FROM tx ORDER BY id DESC LIMIT ?", [50]);
await db.transaction(async (tx) => {
  await tx.run("INSERT INTO tx (cents, note) VALUES (?, ?)", [1250, "Groceries"]);
});
const off = db.onDidChange(({ origin }) => host.postToPanel("ledger-changed", origin));
  • Opening. migrations run in order against PRAGMA user_version, each in its own transaction; append new ones and never edit shipped ones. A file written by a newer copy of the plugin rejects with DB_SCHEMA_TOO_NEW. definitions re-applies idempotent views and triggers whenever their text changes. readonly: true never creates the file, raises no write consent, and suits a dashboard over data agents write.
  • Statements. query, get, run, and columns each take exactly one statement; exec runs a batch with no parameters. transaction(fn) wraps BEGIN IMMEDIATE; use the tx it hands you, since calling the outer handle inside it deadlocks.
  • Connection policy. Foreign keys are enforced, the busy timeout is five seconds, and a handle reopens transparently when the file is replaced underneath it. Calls are serialized per handle. Handles close when the plugin unloads.
  • Changes. onDidChange fires after commits, including ones by other processes such as an agent using the sqlite3 CLI, coalesced to 50 ms windows and labeled "self" or "external".
  • Writes and backups. Opening a project database for writing asks for fs:project-write consent the first time. backup(destPath) writes a consistent snapshot under the same rules as host.fs.writeFile.

host.documents.renderPdf renders HTML to a PDF file in the main process, in a hidden, sandboxed window with JavaScript disabled and the network cut off: only data: URIs and file: URLs inside a root the plugin can read load. The output path is gated exactly like host.fs.writeFile. Renders run two at a time across all plugins, time out after 30 seconds, and reject above 50 MiB, each with a named error.

Serving tools to agents

host.mcp.registerTools(endpointId, tools) binds the tool roster for a worker-implemented endpoint declared in contributes.agentMcp. It requires mcp:expose and must be called during activate(). It resolves a disposer; calling it again replaces the roster, and every roster is dropped on unload. For an endpoint whose source bridges one of the plugin's mcpServers, Daintree registers the server's tools and rejects this call.

await host.mcp.registerTools("data", {
  list_transactions: {
    description: "A page of this project's ledger transactions, newest first.",
    inputSchema: {
      type: "object",
      properties: { limit: { type: "integer", minimum: 1, maximum: 200 } },
      additionalProperties: false,
    },
    async execute(args, caller, signal) {
      const limit = typeof args.limit === "number" ? args.limit : 50;
      return { transactions: await readTransactions(caller.projectId, limit, signal) };
    },
  },
});
  • Up to 16 tools per endpoint, counting the manifest's declared database queries, whose names a tool may not reuse. Names are 1 to 32 characters of lowercase letters, digits, and underscores, starting with a letter; descriptions are at most 400 bytes and each schema at most 8 KiB. A roster breaking any limit is rejected whole.
  • When the endpoint declares tool groups (up to eight), every tool must name one in group, and it is listed and callable only where the user allowed that group. A replacement roster that moves tools between groups revokes the credentials agents hold for the plugin's groups.
  • Arguments are checked against inputSchema before execute runs and arrive exactly as the agent sent them. A declared outputSchema is enforced on the result. Results are JSON, at most 256 KiB, and a thrown error becomes a tool error.
  • caller carries the credential id, project id, and terminal id, plus consumer: "assistant" when the credential was issued to the project's Daintree Assistant. It is provenance, not identity: scope every query by caller.projectId when an installed plugin keeps per-project data.
  • signal aborts on the 60-second timeout, cancellation, revocation, or a roster change.
  • Annotations may only add caution (destructiveHint: true, openWorldHint: true, idempotentHint); a roster claiming a tool is read-only or safe is rejected, because agent clients ask less for tools described that way.

Registering tools does not expose them. The user decides per project in Project settings > Plugins > Agent tools; see Trust & Capabilities.

Providers bound at activation

Several contribution points are declared in the manifest, so Daintree can list them before any code runs, and answered by an implementation the worker binds in activate(). Each registration names a declared id (an undeclared one is rejected), resolves a disposer, replaces an earlier binding for the same id, and is dropped on unload. Context providers, delete notes, and cloud providers activate a plugin that is not running so it can answer; deadlines include that activation.

RegistrationAnswersDeadline and rules
registerSearchProvider(id, provider)A kind: "runtime" entry of searchProviders, asked while the user types in the quick switcher.One second; a late answer is dropped and recorded in the plugin's diagnostics, and context.signal aborts when the query is superseded. An unscoped search only asks a plugin that is already running. Results naming a target outside the plugin are dropped.
registerContextProvider({ id }, impl)A contextProviders entry: search(query, { signal }) when the user types @prefix: in an agent composer, and resolve(itemId, { signal }) for each chip when the draft is sent, so the agent reads the item as it is then.Three seconds for a search; five seconds shared by every chip in one draft. At most 50 matches shown; resolved content up to 32,768 characters.
registerWorktreeSetupStep(stepId, handler)A worktreeSetupSteps entry, run for each new worktree after the project's own setup script succeeds and once the user has allowed the step for that project. The handler gets the project, worktree id and path, branch, and a signal.Steps run one at a time, in plugin-id then declaration order, and one failing does not stop the next. Timeout 5 minutes by default, 1 second to 30 minutes. It is not a teardown hook.
registerWorktreeDeleteNotesProvider({ id }, impl)The one worktreeDeleteNotes entry: provideNotes while a delete confirmation is being prepared or shown (so a call does not mean the delete was approved), from the dialog, bulk remove, an agent, or with no window open.Three seconds, activation included. Up to three notes of 200 characters each, warning or info. Notes never change the delete or its confirmation; a late or invalid answer shows as "didn't answer", and the user can turn a plugin's notes off.
registerCloudProvider({ id }, impl)A cloudProviders entry: every credential check, catalog read, and machine operation.30 seconds per call, activation included. See Cloud providers.
registerForgeProvider, registerFileDecorationProviderForge backends and file-row decorations.See Contribution Points. Forge providers only bind in a built-in plugin.

Services between plugins

A plugin can expose named, versioned methods to other plugins. The provider declares contributes.services.provides entries named publisher.name.service, each with a semver version and its methods, and binds exactly those methods with host.registerService(name, handlers). Each method receives the arguments and a context carrying the caller's manifest id and project and a signal. A consumer declares contributes.services.requires entries with a semver range (and optional when it can work without one), then calls:

const result = await host.services.call("acme.jira.issues", "search", { text: "login" });
if (result.ok) render(result.value);
else host.logger.warn(result.message, { reason: result.reason }); // "unavailable", "incompatible", "timeout", …

const status = await host.services.status("acme.jira.issues"); // without starting the provider

The host resolves each call to the provider instance bound to the caller's project, else the app-global one, and starts it if it is not running. Expected failures resolve with a reason and never reject. Calls default to a 30-second deadline (at most 120), arguments are capped at 256 KiB and results at 1 MiB, a provider runs at most 32 calls at once, and a call that would re-enter a service already waiting on it fails as cycle. Calls made before the caller's activate() returns resolve unavailable. Nothing is installed, enabled, or ordered from these declarations, and calling a provider grants the caller none of its capabilities.

Host-managed accounts

A plugin that declares contributes.account (or several named connections) lets Daintree run the sign-in: an OAuth 2 authorization-code flow with PKCE, or a pasted API token. Signing in and out happens only from the host's own settings row. The plugin reads the result through host.account: getState() says whether it is connected and as whom, getAccessToken() returns { accessToken, expiresAt } (refreshed first when it is about to expire), null when the account is not connected, or rejects when a refresh fails for a reason that may pass, and onDidChange(cb) fires on connect, disconnect, a new identity, or a project rebinding the connection. Ask for a token each time you need one rather than keeping it; the refresh token never leaves the host. Each call takes an optional { connection, projectId }: an installed plugin serving several projects passes the project whose binding applies.

Settings and storage

Two persistence surfaces with different audiences. settings holds user-facing values declared in contributes.settings and rendered as a generated form. storage is the machine-owned counterpart: a plugin's own working state, not surfaced in the settings UI and not requiring a manifest declaration.

const token = await host.settings.get<string>("linear.apiToken");
await host.settings.set("linear.defaultTeam", "engineering");
await host.settings.unset("linear.defaultTeam");              // back to the default
const dispose = await host.settings.onDidChange("linear.apiToken", reconnect);

await host.storage.set("lastSyncCursor", cursor);            // "user" scope by default
await host.storage.set("draft", text, "worktree");           // tracks the active worktree
const cursor = await host.storage.get<string>("lastSyncCursor");
await host.storage.delete("draft", "worktree");

settings follows each declared field's scope: user, repository project, or machine-and-project local. Undeclared keys default to user scope when allowed; an explicit scope conflicting with a declared key is rejected. A project plugin resolves its own bound project, while an installed plugin resolves the current project. storage supports user, project, and worktree scopes and keeps reads coherent across a switch by invalidating the cache itself. Both reject undefined and non-serializable values, and both onDidChange methods fire only on in-process writes.

settings.missingRequired() lists the declared required settings that are still unset (a default never counts, and secrets are checked for presence without being decrypted). settings.open(key?) takes the user to the plugin's settings, in the Plugin Manager for an installed plugin or Project settings > Plugins for a project plugin, and highlights key when it names a declared setting. Together they make a "needs setup" path from inside a view.

Warning
storage is plaintext JSON with no encryption. Never put credentials in it. Use a type: "secret" setting instead, which is encrypted through the OS keychain where one exists. Where no keychain exists the secret is not saved; Trust & Capabilities covers the details.

logger writes to a bounded per-plugin ring buffer (roughly the last 500 entries) and mirrors to the host console prefixed with the plugin id. Calls return void and never throw: an unserializable payload is coerced to a string. Every line is secret-scrubbed before it reaches either sink.

The view component contract

A panel's React component is the default export of the module named by contributes.views[].componentPath. The host lazy-imports it over the plugin:// protocol and mounts it under an error boundary and a suspense boundary.

Read the file-tree sample view for a concrete component, or the view contract for host interaction. Styling, the host UI kit, and performance are on Plugin UI Kit & Styling. A view pulls initial data from registered channels and subscribes to pushes; there is no automatic worktree channel or HTTP API under plugin://.

PropTypeWhat it is
panelIdstringRuntime id of this panel instance. The routing key for per-instance pushes, and a good key for panel-scoped local state.
pluginIdstringThe runtime plugin id: manifest name for installed plugins, instance key for project plugins. Pass it unchanged to SDK hooks and the bridge.
disposeSignalAbortSignalLifetime of this mounted view attempt. Aborts on unmount, on "Try again", and when the panel kind disappears. A temporary unmount aborts it too.
panelRemovedSignalAbortSignalLifetime of the panel record. The same object is handed to every mount of a given panelId, so it survives remounts, retries, trash-then-restore, and plugin upgrades. Aborts exactly once, on permanent removal.
initialArgsrecord, optionalThe saved state snapshot at mount, initially seeded when the panel opens and subsequently updated through persistState. It is not a live value while the component remains mounted.
openRequest{ seq, args }, optionalThe latest panel.openPluginPanel call that reused this panel and supplied initialArgs; a reuse without arguments leaves it alone. Live: the view re-renders with it and keeps its state. seq is new on every such reuse, so key an effect on the request itself. Delivered once; persist whatever it changed if that should survive a remount.
persistStatefunction, optionalMerges JSON patches into the saved panel state; undefined removes a key. Rejects a resulting bag above 64 KB or an unserializable patch, returning false. true means accepted and scheduled. Outside the grid (a Home surface, a sidebar view, a settings section, a toolbar popover) the bag goes to a per-view store instead, written without a debounce so it survives the renderer going away; false also means storage refused it, and the least recently written bags beyond 200 are dropped, so treat it as state you can rebuild. The state is stored as plaintext JSON, so keep secrets out of it.
stateVersionnumber, optionalWhich version of the panel's declared stateVersion schema initialArgs was written with. Migrate forward from it and persist the result. Absent when the panel declares none.
requestReloadfunction, optionalDiscard this view attempt and mount a fresh one. See reload.
setHasUnsavedChangesfunction, optionalWhile true, a user or agent reload, and closing the panel, ask before discarding the view. It also holds off automatic sleep and cache eviction of the project's renderer, so prefer persisting a draft.
setToolbarItemStatefunction, optionalSets the live state of one of the panel's manifest toolbar buttons.
setMenuItemsfunction, optionalPublishes up to five of your own actions on the panel's menus.
setTitlefunction, optionalNames this panel on its tab, header, dock chip, and dialog, so three record panels read "Record #42", "#43", and "#44". null returns to the kind's name, a name the user typed wins, and the title is cut at 80 characters.
runningActionsstring array, optionalYour actions whose handlers are running right now, however they were dispatched.
hostContextobject, optionalWhere the view is mounted: kind is panel, surface, settings, sidebar, fileEditor, popover, or canopy, with a close() where the view may dismiss its own host, such as a toolbar popover. Give an unrecognized kind a sensible default; treat a missing one as a panel.
settingsContextobject, optionalPresent only for a location: "settings" view: which settings home it is mounted in.
fileDocumentobject, optionalPresent only for a file editor view: the host-owned file, read and saved by revision, with setDraft for unsaved text so the host's dirty indicator and close prompt apply.
navigationobject, optionalPresent only in a project application that declares navigation: the shared location across its sidebar, Home, and panels, with back and forward.
styleRootAttributesrecordSpread onto a portalled container to preserve the host's scoped runtime Tailwind styling.
worktreeIdstring, optionalThe worktree the panel instance belongs to, recorded at spawn time. Lets a view reconstruct its own context rather than asking for the visible worktree, which is the wrong answer for a background or restored panel.

The optional functions are absent where the host offers nothing for them, such as a project surface, which has no header, menu, or reload; call them optionally. Each setter belongs to the view attempt that received it, so a call held past that attempt's teardown does nothing.

Which signal to use

A panel outlives its views, and conflating the two is the single most common plugin bug.

  • View-scoped work (in-flight fetches, DOM observers, panel subscriptions, UI timers) belongs on disposeSignal.
  • Panel-scoped work (anything that should survive being backgrounded but not survive the panel) belongs on panelRemovedSignal.
  • Durable resources (spawned processes, long-lived sessions, anything expensive to restart) belong in the worker, released from onDidChangePanelLifecycle on "removed". The worker observes the panel across every remount; the view cannot, because it is gone during exactly the teardown that matters.

The error boundary renders a diagnostics pane with Try again, Close panel, Copy diagnostics, and View logs. "Try again" mints a fresh lazy reference so the dynamic import is genuinely re-evaluated rather than returning the cached failed promise.

React hooks and the raw bridge

The @daintreehq/plugin-sdk/react subpath carries the renderer hooks. It is a separate import path so a plugin's main does not pull React into the main-process bundle.

  • useHostChannel(pluginId, channel): the pull half. Binds a single-flight invoke(args) to the plugin's registerHandler. It resolves with the validated result, or undefined when the host rejected the call, surfacing the rejection on error rather than throwing. loading reflects only the latest call; a second invoke drops the stale earlier one.
  • usePluginEvent(pluginId, channel, handler): the push half, receiving broadcasts. The handler is kept ref-stable, so an inline closure does not re-subscribe on every render.
  • usePluginPanelEvent(pluginId, channel, panelId, handler): the same, narrowed to pushes targeted at one panel instance.

The source SDK adds hooks for panel chrome (usePanelMenuItems, usePanelToolbarItem, useActionRunning), useProjectPresence, useNow for one shared clock, createViewScope for releasing a view's listeners, timers, observers, and workers when it is disposed, and a set of performance hooks described on Plugin UI Kit & Styling. The 0.1.0 SDK on npm has only the three hooks above and loadDocumentPackage.

In a window attached to another machine, the plugin's host code runs there and the link can drop. A call that never reached the host fails with HostDisconnectedError and is safe to retry; one whose answer was lost after it was sent fails with OutcomeUnknownError, because it may have run. Check the effect, or make the call idempotent, before repeating anything that changes state. useHostChannel sets disconnected until a later call gets through, so a view can show a quiet offline state.

Where the hooks come from. The @daintreehq/plugin-vite preset bundles the SDK into the plugin's output, so a bundled view keeps the version it was built against. A raw, un-bundled plugin:// view can bare-import @daintreehq/plugin-sdk/react too: the host import map serves the running app's copy to raw views only, one instance per document. Hand-authored views can also use the bridge the hooks wrap, typed by @daintreehq/plugin-sdk/view-globals in the source SDK.

// Push half: mirrors usePluginEvent. Returns an unsubscribe function.
const off = window.electron.plugin.on(pluginId, "build-status", (status) => {
  setBuildStatus(status);
});

// Panel-targeted push half: mirrors usePluginPanelEvent.
const offPanel = window.electron.plugin.onPanel(pluginId, "build-status", panelId, setBuildStatus);

// Pull half: mirrors useHostChannel's invoke().
const result = await window.electron.plugin.invoke(pluginId, "sync-now", { team: "engineering" });

Module generations

Chromium caches ESM module records by URL and offers no eviction API, so re-importing the same plugin:// specifier returns the module already in memory no matter how thoroughly a panel remounts. Daintree closes that gap by stamping a per-load generation segment into the view URL.

plugin://<host-minted-authority>/__dtv-7/dist/dashboard.js

Every time a plugin is loaded (install, replacement install, enable, app start, a project-folder reload, or a settled rebuild under daintree-plugin dev) a new generation is minted. That is a specifier the renderer has never imported, so the new bundle is genuinely fetched and evaluated, and open panels remount onto it automatically. No force reload, and no hand-versioned bundle filenames.

One consequence: relative imports inside the entry module inherit the generation, so a multi-chunk bundle refreshes as a unit, but an absolute plugin:// import written by hand does not, and keeps resolving to the first version imported in that session.

The dev loop and project-folder reloads both reconcile the whole plugin: the manifest is re-read, contributions are re-registered, views are republished under a fresh generation, and the worker is replaced. The generation segment is virtual: it never exists on disk, and the protocol handler strips it before resolving the file. Treat that prefix as a reserved top-level directory name.

What the host does not expose

  • Other plugins' state or handlers. There is no direct API for another plugin's private storage or channel handlers. Action dispatch still follows the shared action rules.
  • The user's AI provider keys. A plugin that needs AI calls ships its own secret setting.
  • Control of agents the plugin did not start. Driving, pausing, or reading back an arbitrary agent session stays gated. The sanctioned paths are narrow: sendToActiveAgent and sendToAgent for input (the latter never submits), agents.interrupt, sendKeys, and submit only for agents the plugin launched itself, and terminals.readScreen for a consented read of what a terminal currently shows. For everything else, dispatch into an existing action.
  • An inbound webhook or host-side HTTP listener. Deferred.
  • Daintree's internal event bus. Only the specific subscriptions above are exposed, so internal shape changes stay free to happen.
  • Raw Electron main-process APIs. The contained equivalents (process, fs, git, clipboard, system) are the audited path. A plugin can still import Node modules directly; the host does not intercept that, and is honest about it in Trust & Capabilities.
Warning
registerForgeProvider is a no-op for every user-installed plugin. A forge provider's parseRemote and URL builders are synchronous and cannot cross the worker's async MessagePort, so only Daintree's built-in plugins, which activate in-process, can register one. Packaging and installing does not restore it; it is an architectural gap, not a dev-mode limitation.

Testing against a mock host

createMockHost, from @daintreehq/plugin-sdk/testing, returns a PluginHostApi that mirrors production argument validation and capability gating, so a unit test can run activate() and assert what it called. It validates the same things the real host does (toast bounds, badge shape, channel format, quick-pick item arrays), so a malformed call fails the test the way it would fail in the app. Recording arrays expose every host call in order, and passing a narrower capabilities list lets you assert the PERMISSION_REQUIRED rejection a missing capability produces. It does not model processes, filesystem containment, Git, or the manifest gates. See Building & Distributing.

Implementation references: host construction, worker proxy, renderer bridge, and the mock host, pinned to the November 20, 2026 revision.