# Writing a Hatch plugin

Hatch's own features are plugins. The slash menu, outline, backlinks, tags, word count, daily notes and templates all use the API on this page.

## The shortest plugin

```ts
import { definePlugin } from '@hatch/plugin-api'

export default definePlugin({
  id: 'hello',
  name: 'Hello',
  permissions: ['ui'],
  activate(ctx) {
    ctx.ui.addCommand({
      id: 'say-hello',
      title: 'Say hello',
      hotkey: 'Mod-Shift-h',
      run: () => ctx.workspace.notify('Hello from a plugin'),
    })
  },
})
```

`ctx` only has what you ask for. With `permissions: ['ui']`, `ctx.ui` is typed and present, and `ctx.vault` does not exist. Ask for more and TypeScript knows.

## Permissions

| Permission | What it gives you |
| --- | --- |
| `ui` | `ctx.ui`: commands, side panels, status bar items, settings tabs, themes |
| `editor` | `ctx.editor`: editor extensions, the active editor, edit events |
| `vault:read` | `ctx.vault`: notes, search, backlinks, tags, link resolution |
| `vault:write` | `ctx.vaultWrite`: create and change notes (includes read) |
| `network` | Lets a community plugin reach `https:` addresses. Without it, its frame has no network at all |
| `site` | `ctx.site`: components and looks for blogs and portfolios (see below) |
| `live` | `ctx.live`: live channels to other devices and people on the vault (see below) |
| `agent` | `ctx.agent`: tools and instructions for Hatch's AI chat (see below) |

People see the permissions before they turn a community plugin on. The manifest decides what a plugin gets, not its code.

## What you can add

- **Commands** with optional hotkeys. They show up in the palette (`⌘K`, then `>`).
- **Views**: a screen of your own in the main area, with its own address (see below).
- **Panels** in the right sidebar. You get a DOM element and return a cleanup function. Use any framework or none.
- **Status bar items** that re-read their text after edits, debounced.
- **Settings tabs**, rendered into Settings under "Plugin options".
- **Themes** from a token object.
- **Editor extensions**: nodes, marks, input rules, keymaps and ProseMirror plugins, through `defineExtension` from `@hatch/editor`. The slash menu is one.

- **Components and site looks**, with the `site` permission. Both are data, not code: a component is the same YAML as a file in `.hatch/components/`, and a look is the same as a template in `.hatch/site-templates/`. They're checked the same way before anything uses them, so nothing a plugin adds runs on a published site.

```ts
export default definePlugin({
  id: 'newsprint',
  name: 'Newsprint',
  permissions: ['site'],
  activate(ctx) {
    ctx.site.addLook({ id: 'newsprint', name: 'Newsprint', base: 'essay', style: { size: 19, dropCap: 'show' } })
    ctx.site.addComponent({ name: 'author-card', source: authorCardYaml })
  },
})
```

  The look shows with the templates in Publish > Look, and its components work in notes, slots and pages. A vault's own component or template with the same name wins, and a look with problems (a value out of range, an unknown setting) is left out.

Anything you register is removed when the plugin is turned off. Push your own cleanups onto `ctx.subscriptions`.

## Building an app on Hatch

Hatch can't have every feature. Like Vite, it has a few general hooks, and a chat, a task board or a tracker is a plugin built on them. The plan behind them is `docs/plans/extension-api.md`.

Two complete apps, written to be read and copied (or handed to an agent): `examples/plugins/chat` and `examples/plugins/tasks`. Hatch lists both in every vault's Settings, Plugins, off until you turn them on (the showcase build starts with them on), so trying one takes a switch. To change one, copy its folder into a vault's `.hatch/plugins/`: the vault's copy takes the place of Hatch's. Agents writing a plugin should follow `.claude/skills/hatch-plugin/SKILL.md`.

### A screen of your own

```ts
ctx.ui.addView({
  id: 'board',
  title: 'Tasks',
  render(el, { arg }) {
    el.textContent = `Tasks in ${arg}`
    return () => el.replaceChildren()
  },
})
ctx.ui.openView('board', 'Projects/Cabin')
```

The view fills the main area. Its address is `/view/<plugin>/<id>/<arg>`, so Back, Forward and copied links work. When the plugin is off, the address shows a page that says so.

### Live channels

```ts
const room = ctx.live.channel('general')
room.on((data, from) => console.log(from.name, data))
room.send({ type: 'posted' })
room.peers() // [{ id, name, self }]
```

- A message is up to 16 KB of JSON and goes to everyone else with the channel open. Nothing is kept: write the record to a note, then say on the channel what changed.
- On a vault that syncs, messages go through the Hatch server, sealed with the vault key when it's end-to-end encrypted. Channel names are hashed, so the server never sees them. Without sync, other windows on the same device still get them.
- Channels belong to the plugin: two plugins can use the same name without hearing each other.
- A channel opened before signing in stays on this device until the plugin starts again.

### Safe writes

```ts
await ctx.vaultWrite.append('Chat/general/2026-12-04.md', '\n###### Alex · 09:12 ^m-1\n\nHello\n')
await ctx.vaultWrite.update('Tasks/CAB-3 Porch.md', (text) => text?.replace('status: todo', 'status: done') ?? null)
```

Both start from what the note says right now, unsaved typing in an open editor included, and go one at a time with the app's own writes, so a change made at the same moment is never lost. `update` returning `null` writes nothing.

### The AI chat

```ts
ctx.agent.addTool({
  name: 'create_task',
  description: 'Make a task with the next free id',
  parameters: { type: 'object', properties: { title: { type: 'string' } }, required: ['title'] },
  run: async ({ title }) => `Created ${title}`,
})
ctx.agent.addInstructions('Tasks are notes in Tasks/. Use tasks__create_task to make one.')
```

- The chat sees the tool as `<plugin>__<name>`, beside the vault tools, and shows each call in the conversation.
- Agents outside Hatch can't run plugin code. Put an `AGENTS.md` with your note formats beside `manifest.json`: the MCP `vault_guide` includes it, and agents follow it with the plain note tools.

## Reading the API

The API is documented in the source, so you don't need a separate reference.

- Every export of `@hatch/plugin-api`, `@hatch/editor`, `@hatch/theme` and `@hatch/blocks` has a TSDoc comment.
- The comments show in editor hovers and autocomplete. Hover `definePlugin` or `ctx.ui.addCommand` to read them.
- The main entry points have an `@example` you can copy.
- A test, `packages/plugin-api/src/docs.test.ts`, fails if a public export has no comment. Add one when you export something new.

## Shipping a community plugin

Put two files in the vault:

```
.hatch/plugins/<id>/manifest.json
.hatch/plugins/<id>/main.js
```

`manifest.json`:

```json
{
  "id": "word-goal",
  "name": "Word goal",
  "version": "1.0.0",
  "description": "Progress toward a word goal in the status bar.",
  "permissions": ["ui", "editor"]
}
```

`main.js` is a plain ES module whose default export has an `activate(ctx)` function. The demo vault ships a complete example in `fixtures/demo-vault/.hatch/plugins/word-goal`.

Two rules keep this safe:

1. Hatch reads only the manifest when a vault opens. `main.js` loads the first time someone turns the plugin on.
2. Choices are per vault. Turning a plugin on in one vault does not turn it on anywhere else.

## The sandbox

Community plugins never run inside the app. Each one gets sandboxed iframes with an opaque origin and its own Content-Security-Policy:

- A hidden **main frame** holds its commands, status items and themes.
- **One frame per open panel or settings tab** renders that view. It looks native because the app's theme comes in as CSS variables.

From inside its frames, a plugin can't touch:
- the app's DOM, storage, sync keys or account token
- the internet, unless it asked for `network`

Every request it makes goes to the app as a message. The app carries it out with the same permission-checked context built-in plugins get.

Some parts work differently from built-in plugins:

- `ctx.vault.notes()`, `get()`, `ctx.workspace.activeNote()` and the open note's text are mirrored into the frame, so you can read them synchronously.
- `search`, `backlinks`, `resolveLink`, `findPath`, `attachments`, `tags` and `tree` return promises. `await` them; it works the same against the built-in API.
- Views, live channels, agent tools, `append` and `update` all work. A view is one frame that fills the main area. `update` reads, changes and writes only if the note didn't change in between, and tries again if it did. Agent tools run in the main frame and have a minute to answer.
- `ctx.editor.active()` gives you `getMarkdown()`, `getFrontmatter()`, `setFrontmatter()`, `setMarkdown()` and `insertText()`. Editor extensions are not available to community plugins yet.
- Settings are stored per plugin, as before.

If a plugin's `main.js` or its permissions change on disk, Hatch turns it off and asks again before it runs.
