Skip to main content

Host API

The PluginHostApi contract: plugin identity, lifecycle, panel menus and pushes, terminal screens, agent observation, project dispatch, databases, 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, published to npm as 0.1.0 on September 22, 2026. That release predates most of the members added in app 0.38 to 0.43 (databases, documents, the agent and terminal APIs, panel menus and reload, the extra filesystem calls, project-targeted dispatch, and focus observation): the running app provides them, but their types are only in the SDK source until the next release. 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.

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>;
  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
  onDidChangeAllAgents(cb, options?): Promise<() => void>;    // agent:read, installed only
  onDidChangeFocusedPanel(cb, options?): Promise<() => void>; // panel:focus-read
  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): Promise<PluginWorktreeStatus | null>;
  getAgentState(): Promise<PluginAgentSnapshot | null>;      // agent:read
  readonly agents: { list(); listAll() };                   // agent:read
  readonly terminals: { readScreen(terminalId, options?) };  // terminal:read

  // 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>;
  reloadPanel(panelId): Promise<PanelReloadResult>;
  invalidateFileDecorations(scope, paths?): Promise<void>;
  dispatch(actionId, args?, { projectId }?): Promise<ActionDispatchResult>;
  readonly actions: PluginHostActionsApi;
  sendToActiveAgent(text, options?): Promise<void>;          // agent:input
  sendToAgent(text, options?): Promise<PluginSendToAgentResult>; // agent:input
  showToast(options): Promise<void>;
  showQuickPick(items, options?): Promise<...>;
  showInputBox(options?): Promise<string | undefined>;
  showConfirm(options): Promise<boolean>;

  readonly settings: SettingsApi;
  readonly storage: StorageApi;
  readonly db: PluginDatabaseApi;          // contributes.databases
  readonly logger: PluginLogger;
  readonly process: PluginProcessApi;      // shell:exec
  readonly fs: PluginFsApi;                // fs:*
  readonly git: PluginGitApi;              // git:*
  readonly clipboard: PluginClipboardApi;  // clipboard:*
  readonly system: PluginSystemApi;        // fs:*
  readonly documents: PluginDocumentsApi;  // fs:*-write
}

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 methods resolve Promise<() => void> rather than returning a disposer synchronously. Always await a registration before assuming it took effect, and await a subscription to get its disposer. 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.

Subscriptions whose events arrive in bursts (the worktree list, the active worktree, agent state, the all-agents list) are coalesced by default: a burst becomes one trailing callback carrying the latest value, with a 100 ms window (250 ms for focused-panel changes). 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.

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, registerForgeProvider, registerFileDecorationProvider, mcp.registerTools, onDidChangeActiveWorktree, onDidChangeWorktrees, onDidChangeAgentState, onDidChangeAllAgents, onDidChangeFocusedPanel, onDidChangePanelLifecycle, onDidWake, settings.onDidChange, storage.onDidChangeMust be called during activate(). They throw once the host is revoked.
Live runtime surfacepostToPanel, hasListeners, onDidChangeListeners, setPanelBadge, setPanelMenuItems, reloadPanel, invalidateFileDecorations, getActiveWorktree, getWorktrees, getWorktreesResult, getWorktreeStatus, getAgentState, agents.*, terminals.readScreen, dispatch, actions, sendToActiveAgent, sendToAgent, showToast and the other prompts, process.spawn, fs.*, git.*, clipboard.*, system.*, documents.*, db.*, settings.get / set / 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 (for process.spawn, fs, git, and documents) reject.

Subscribing counts as an activation-window operation even though the callback fires much later. 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 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 installed 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 plugin may only name its own project. A project with no live view rejects with PROJECT_VIEW_UNAVAILABLE: nothing opens or wakes a closed project.

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.

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.

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".

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 isCurrent: boolean;
  readonly branch?: string;
  readonly isMainWorktree?: boolean;
  readonly aheadCount?: number;
  readonly behindCount?: number;
  readonly linked: PluginWorktreeLinked | null;
  readonly status: PluginWorktreeStatus | 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;
  };
}

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.

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. For a project 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.

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. Installed and built-in plugins only; a project 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.

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, the Portal), 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.

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 id so users can tell which plugin raised it. Messages are strings up to 2000 characters; durationMs is capped at 60 s. Toasts route through Daintree's normal notification path, so quiet hours and the inbox apply, and the rate-limit bucket is per plugin so a noisy plugin cannot suppress anyone else's toasts.
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.

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.

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 the endpoint declared in contributes.agentMcp. It requires mcp:expose and must be called during activate(); calling it again replaces the roster, and every roster is dropped on unload.

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. 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.
  • 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. 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.

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");
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");

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.
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. 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 asks before discarding the view.
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.
runningActionsstring array, optionalYour actions whose handlers are running right now, however they were dispatched.
settingsContextobject, optionalPresent only for a location: "settings" view: which settings home it is mounted in.
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), 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.

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.
  • Full control of a running agent. Driving, pausing, or reading back an agent session stays gated. The sanctioned paths are narrow: sendToActiveAgent and sendToAgent for input (the latter never submits), 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 October 13, 2026 audit.