Paperclip V1 explicitly excludes a plugin framework in [doc/SPEC-implementation.md](../SPEC-implementation.md), but the long-horizon spec says the architecture should leave room for extensions. This report studies the `opencode` plugin system and translates the useful patterns into a Paperclip-shaped design.
Assumption for this document: Paperclip is a single-tenant operator-controlled instance. Plugin installation should therefore be global across the instance. "Companies" are still first-class Paperclip objects, but they are organizational records, not tenant-isolation boundaries for plugin trust or installation.
## Executive Summary
`opencode` has a real plugin system already. It is intentionally low-friction:
- plugins are plain JS/TS modules
- they load from local directories and npm packages
- they can hook many runtime events
- they can add custom tools
- they can extend provider auth flows
- they run in-process and can mutate runtime behavior directly
That model works well for a local coding tool. It should not be copied literally into Paperclip.
The main conclusion is:
- Paperclip should copy `opencode`'s typed SDK, deterministic loading, low authoring friction, and clear extension surfaces.
- Paperclip should not copy `opencode`'s trust model, project-local plugin loading, "override by name collision" behavior, or arbitrary in-process mutation hooks for core business logic.
- Paperclip should use multiple extension classes instead of one generic plugin bag:
- trusted in-process modules for low-level platform concerns like agent adapters, storage providers, secret providers, and possibly run-log backends
- out-of-process plugins for most third-party integrations like Linear, GitHub Issues, Grafana, Stripe, and schedulers
- file browser / terminal / git workflow / child process tracking become workspace plugins that resolve paths from the host and handle OS operations directly
`opencode` exposes a small package, `@opencode-ai/plugin`, with a typed `Plugin` function and a typed `tool()` helper.
Core shape:
- a plugin is an async function that receives a context object
- the plugin returns a `Hooks` object
- hooks are optional
- plugins can also contribute tools and auth providers
The plugin init context includes:
- an SDK client
- current project info
- current directory
- current git worktree
- server URL
- Bun shell access
That is important: `opencode` gives plugins rich runtime power immediately, not a narrow capability API.
## 2. Hook model
The hook set is broad. It includes:
- event subscription
- config-time hook
- message hooks
- model parameter/header hooks
- permission decision hooks
- shell env injection
- tool execution before/after hooks
- tool definition mutation
- compaction prompt customization
- text completion transforms
The implementation pattern is very simple:
- core code constructs an `output` object
- each matching plugin hook runs sequentially
- hooks mutate the `output`
- final mutated output is used by core
This is elegant and easy to extend.
It is also extremely powerful. A plugin can change auth headers, model params, permission answers, tool inputs, tool descriptions, and shell environment.
## 3. Plugin discovery and load order
`opencode` supports two plugin sources:
- local files
- npm packages
Local directories:
-`~/.config/opencode/plugins/`
-`.opencode/plugins/`
Npm plugins:
- listed in config under `plugin: []`
Load order is deterministic and documented:
1. global config
2. project config
3. global plugin directory
4. project plugin directory
Important details:
- config arrays are concatenated rather than replaced
- duplicate plugin names are deduplicated with higher-precedence entries winning
- internal first-party plugins and default plugins are also loaded through the plugin pipeline
This gives `opencode` a real precedence model rather than "whatever loaded last by accident."
## 4. Dependency handling
For local config/plugin directories, `opencode` will:
- ensure a `package.json` exists
- inject `@opencode-ai/plugin`
- run `bun install`
That lets local plugins and local custom tools import dependencies.
This is excellent for local developer ergonomics.
It is not a safe default for an operator-controlled control plane server.
## 5. Error handling
Plugin load failures do not hard-crash the runtime by default.
Instead, `opencode`:
- logs the error
- publishes a session error event
- continues loading other plugins
That is a good operational pattern. One bad plugin should not brick the entire product unless the operator has explicitly configured it as required.
## 6. Tools are a first-class extension point
`opencode` has two ways to add tools:
- export tools directly from a plugin via `hook.tool`
- define local files in `.opencode/tools/` or global tools directories
The tool API is strong:
- tools have descriptions
- tools have Zod schemas
- tool execution gets context like session ID, message ID, directory, and worktree
- tools are merged into the same registry as built-in tools
- tool definitions themselves can be mutated by a `tool.definition` hook
The most aggressive part of the design:
- custom tools can override built-in tools by name
That is very powerful for a local coding assistant.
However, the concept of plugins contributing agent-usable tools is very valuable for Paperclip — as long as plugin tools are namespaced (cannot shadow core tools) and capability-gated.
| Workspace plugin | file browser, terminal, git workflow, child process/server tracking | out-of-process, direct OS access | medium | resolves workspace paths from host, owns filesystem/git/PTY/process logic directly |
| UI contribution | dashboard widgets, settings forms, company panels | plugin-shipped React bundles in host extension slots via bridge | medium | plugins own their rendering; host controls slot placement and bridge access |
Plugins ship their own React UI as a bundled module inside `dist/ui/`. The host loads plugin components into designated **extension slots** (pages, tabs, widgets, sidebar entries) and provides a **bridge** for the plugin frontend to talk to its own worker backend and to access host context.
1. The plugin's UI exports named components for each slot it fills (e.g. `DashboardWidget`, `IssueDetailTab`, `SettingsPage`).
2. The host mounts the plugin component into the correct slot, passing a bridge object with hooks like `usePluginData(key, params)` and `usePluginAction(key)`.
3. The plugin component fetches data from its own worker via the bridge and renders it however it wants.
4. The host enforces capability gates through the bridge — if the worker doesn't have a capability, the bridge rejects the call.
**What the host controls:** where plugin components appear, the bridge API, capability enforcement, and shared UI primitives (`@paperclipai/plugin-sdk/ui`) with design tokens and common components.
**What the plugin controls:** how to render its data, what data to fetch, what actions to expose, and whether to use the host's shared components or build entirely custom UI.
Later, if untrusted third-party plugins become common, the host can move to iframe-based isolation without changing the plugin's source code (the bridge API stays the same).
`opencode` makes tools a first-class extension point. This is one of the highest-value surfaces for Paperclip too.
A Linear plugin should be able to contribute a `search-linear-issues` tool that agents use during runs. A git plugin should contribute `create-branch` and `get-diff`. A file browser plugin should contribute `read-file` and `list-directory`.
The key constraints:
- plugin tools are namespaced by plugin ID (e.g. `linear:search-issues`) so they cannot shadow core tools
- plugin tools require the `agent.tools.register` capability
- tool execution goes through the same worker RPC boundary as everything else
- tool results appear in run logs
This is a natural fit — the plugin already has the SDK context, the external API credentials, and the domain logic. Wrapping that in a tool definition is minimal additional work for the plugin author.
## 8. Support plugin-to-plugin events
Plugins should be able to emit custom events that other plugins can subscribe to. For example, the git plugin detects a push and emits `plugin.@paperclip/plugin-git.push-detected`. The GitHub Issues plugin subscribes to that event and updates PR links.
This avoids plugins needing to coordinate through shared state or external channels. The host routes plugin events through the same event bus with the same delivery semantics as core events.
Plugin events use a `plugin.<pluginId>.*` namespace so they cannot collide with core events.
## 9. Auto-generate settings UI from config schema
Plugins that declare an `instanceConfigSchema` should get an auto-generated settings form for free. The host renders text inputs, dropdowns, toggles, arrays, and secret-ref pickers directly from the JSON Schema.
For plugins that need richer settings UX, they can declare a `settingsPage` extension slot and ship a custom React component. Both approaches coexist.
This matters because settings forms are boilerplate that every plugin needs. Auto-generating them from the schema that already exists removes a significant chunk of authoring friction.
## 10. Design for graceful shutdown and upgrade
The spec should be explicit about what happens when a plugin worker stops — during upgrades, uninstalls, or instance restarts.
The recommended policy:
- send `shutdown()` with a configurable deadline (default 10 seconds)
- SIGTERM after deadline, SIGKILL after 5 more seconds
- in-flight jobs marked `cancelled`
- in-flight bridge calls return structured errors to the UI
For upgrades specifically: the old worker drains, the new worker starts. If the new version adds capabilities, it enters `upgrade_pending` until the operator approves.
## 11. Define uninstall data lifecycle
When a plugin is uninstalled, its data (`plugin_state`, `plugin_entities`, `plugin_jobs`, etc.) should be retained for a grace period (default 30 days), not immediately deleted. The operator can reinstall within the grace period and recover state, or force-purge via CLI.
This matters because accidental uninstalls should not cause irreversible data loss.
## 12. Invest in plugin observability
Plugin logs via `ctx.logger` should be stored and queryable from the plugin settings page. The host should also capture raw `stdout`/`stderr` from the worker process as fallback.
The plugin health dashboard should show: worker status, uptime, recent logs, job success/failure rates, webhook delivery rates, and resource usage. The host should emit internal events (`plugin.health.degraded`, `plugin.worker.crashed`) that other plugins or dashboards can consume.
This is critical for operators. Without observability, debugging plugin issues requires SSH access and manual log tailing.
## 13. Ship a test harness and starter template
A `@paperclipai/plugin-test-harness` package should provide a mock host with in-memory stores, synthetic event emission, and `getData`/`performAction`/`executeTool` simulation. Plugin authors should be able to write unit tests without a running Paperclip instance.
A `create-paperclip-plugin` CLI should scaffold a working plugin with manifest, worker, UI bundle, test file, and build config.
Low authoring friction was called out as one of `opencode`'s best qualities. The test harness and starter template are how Paperclip achieves the same.
## 14. Support hot plugin lifecycle
Plugin install, uninstall, upgrade, and config changes should take effect without restarting the Paperclip server. This is critical for developer workflow and operator experience.
The out-of-process worker architecture makes this natural:
- **Hot install**: spawn a new worker, register its event subscriptions, job schedules, webhook endpoints, and agent tools in live routing tables, load its UI bundle into the extension slot registry.
- **Hot uninstall**: graceful shutdown of the worker, remove all registrations from routing tables, unmount UI components, start data retention grace period.
- **Hot upgrade**: shut down old worker, start new worker, atomically swap routing table entries, invalidate UI bundle cache so the frontend loads the updated bundle.
- **Hot config change**: write new config to `plugin_config`, notify the running worker via IPC (`configChanged`). The worker applies the change without restarting. If it doesn't handle `configChanged`, the host restarts just that worker.
Frontend cache invalidation uses versioned or content-hashed bundle URLs and a `plugin.ui.updated` event that triggers re-import without a full page reload.
Each worker process is independent — starting, stopping, or replacing one worker never affects any other plugin or the host itself.
## 15. Define SDK versioning and compatibility
`opencode` does not have a formal SDK versioning story because plugins run in-process and are effectively pinned to the current runtime. Paperclip's out-of-process model means plugins may be built against one SDK version and run on a host that has moved forward. This needs explicit rules.
Recommended approach:
- **Single SDK package**: `@paperclipai/plugin-sdk` with subpath exports — root for worker code, `/ui` for frontend code. One dependency, one version, one changelog.
- **SDK major version = API version**: `@paperclipai/plugin-sdk@2.x` targets `apiVersion: 2`. Plugins built with SDK 1.x declare `apiVersion: 1` and continue to work.
- **Host multi-version support**: The host supports at least the current and one previous `apiVersion` simultaneously with separate IPC protocol handlers per version.
- **`sdkVersion` in manifest**: Plugins declare a semver range (e.g. `">=1.4.0 <2.0.0"`). The host validates this at install time.
- **Deprecation timeline**: Previous API versions get at least 6 months of continued support after a new version ships. The host logs deprecation warnings and shows a banner on the plugin settings page.
- **Migration guides**: Each major SDK release ships with a step-by-step migration guide covering every breaking change.
- **UI surface versioned with worker**: Both worker and UI surfaces are in the same package, so they version together. Breaking changes to shared UI components require a major version bump just like worker API changes.
- **Published compatibility matrix**: The host publishes a matrix of supported API versions and SDK ranges, queryable via API.
Plugins resolve workspace paths through host APIs (`ctx.projects` provides workspace metadata including `cwd`, `repoUrl`, etc.) and then operate on the filesystem, spawn processes, shell out to `git`, or open PTY sessions using standard Node APIs or any libraries they choose.
The host does not wrap or proxy these operations. This keeps the core lean — no need to maintain a parallel API surface for every OS-level operation a plugin might need. Plugins own their own implementations.
This is enough for many connectors before allowing custom tables.
Examples:
- Linear external IDs keyed by `issue`
- GitHub sync cursors keyed by `project`
- file browser preferences keyed by `project_workspace`
- git branch metadata keyed by `project_workspace`
- process metadata keyed by `project_workspace` or `run`
## 4. `plugin_jobs`
Scheduled job and run tracking.
Suggested fields:
-`id`
-`plugin_id`
-`scope_kind` nullable
-`scope_id` nullable
-`job_key`
-`status`
-`last_started_at`
-`last_finished_at`
-`last_error`
## 5. `plugin_webhook_deliveries`
If plugins expose webhooks, delivery history is worth storing.
Suggested fields:
-`id`
-`plugin_id`
-`scope_kind` nullable
-`scope_id` nullable
-`endpoint_key`
-`status`
-`received_at`
-`response_code`
-`error`
## 6. Maybe later: `plugin_entities`
If generic plugin state becomes too limiting, add a structured, queryable entity table for connector records before allowing arbitrary plugin migrations.
Suggested fields:
-`id`
-`plugin_id`
-`entity_type`
-`scope_kind`
-`scope_id`
-`external_id`
-`title`
-`status`
-`data_json`
-`updated_at`
This is a useful middle ground:
- much more queryable than opaque key/value state
- still avoids letting every plugin create its own relational schema immediately
This plugin lets the board inspect project workspaces, agent workspaces, generated artifacts, and issue-related files without dropping to the shell. It is useful for:
- browsing files inside project workspaces
- debugging what an agent changed
- reviewing generated outputs before approval
- attaching files from a workspace to issues
- understanding repo layout for a company
- inspecting agent home workspaces in local-trusted mode
The plugin resolves workspace paths through `ctx.projects` and handles all filesystem operations (read, write, stat, search, list directory) directly using Node APIs.
The plugin resolves workspace paths through `ctx.projects` and handles all git operations (status, diff, log, branch create, commit, worktree create, push) directly using git CLI or a git library.
The git plugin can emit `plugin.@paperclip/plugin-git.push-detected` events that other plugins (e.g. GitHub Issues) subscribe to for cross-plugin coordination.
The plugin resolves workspace paths through `ctx.projects` and handles process management (register, list, terminate, restart, read logs, health probes) directly using Node APIs.
Workspace plugins do not require additional host APIs — they resolve workspace paths through `ctx.projects` and handle filesystem, git, PTY, and process operations directly.
## Phase 2: Consider richer UI and plugin packaging
3. Build a typed domain event bus around existing activity/live-event patterns, with server-side event filtering and a `plugin.*` namespace for cross-plugin events. Keep core invariants non-hookable.
11. Build workspace plugins (file browser, terminal, git, process tracking) that resolve workspace paths from the host and handle OS-level operations directly.