@microvac/plugin-sdk 0.0.0-stage → 0.1.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1630 -2
  3. package/dist/.paperclip-build-complete +1 -0
  4. package/dist/bundlers.d.ts +57 -0
  5. package/dist/bundlers.d.ts.map +1 -0
  6. package/dist/bundlers.js +106 -0
  7. package/dist/bundlers.js.map +1 -0
  8. package/dist/define-plugin.d.ts +444 -0
  9. package/dist/define-plugin.d.ts.map +1 -0
  10. package/dist/define-plugin.js +37 -0
  11. package/dist/define-plugin.js.map +1 -0
  12. package/dist/dev-cli.d.ts +3 -0
  13. package/dist/dev-cli.d.ts.map +1 -0
  14. package/dist/dev-cli.js +49 -0
  15. package/dist/dev-cli.js.map +1 -0
  16. package/dist/dev-server.d.ts +34 -0
  17. package/dist/dev-server.d.ts.map +1 -0
  18. package/dist/dev-server.js +194 -0
  19. package/dist/dev-server.js.map +1 -0
  20. package/dist/environment-acquire-error.d.ts +19 -0
  21. package/dist/environment-acquire-error.d.ts.map +1 -0
  22. package/dist/environment-acquire-error.js +44 -0
  23. package/dist/environment-acquire-error.js.map +1 -0
  24. package/dist/environment-creation-cleanup.d.ts +45 -0
  25. package/dist/environment-creation-cleanup.d.ts.map +1 -0
  26. package/dist/environment-creation-cleanup.js +105 -0
  27. package/dist/environment-creation-cleanup.js.map +1 -0
  28. package/dist/environment-resume-error.d.ts +35 -0
  29. package/dist/environment-resume-error.d.ts.map +1 -0
  30. package/dist/environment-resume-error.js +67 -0
  31. package/dist/environment-resume-error.js.map +1 -0
  32. package/dist/environment-runner-ingress-error.d.ts +13 -0
  33. package/dist/environment-runner-ingress-error.d.ts.map +1 -0
  34. package/dist/environment-runner-ingress-error.js +39 -0
  35. package/dist/environment-runner-ingress-error.js.map +1 -0
  36. package/dist/environment-stop-error.d.ts +14 -0
  37. package/dist/environment-stop-error.d.ts.map +1 -0
  38. package/dist/environment-stop-error.js +44 -0
  39. package/dist/environment-stop-error.js.map +1 -0
  40. package/dist/environment-sync-error.d.ts +25 -0
  41. package/dist/environment-sync-error.d.ts.map +1 -0
  42. package/dist/environment-sync-error.js +125 -0
  43. package/dist/environment-sync-error.js.map +1 -0
  44. package/dist/environment-task-error.d.ts +25 -0
  45. package/dist/environment-task-error.d.ts.map +1 -0
  46. package/dist/environment-task-error.js +73 -0
  47. package/dist/environment-task-error.js.map +1 -0
  48. package/dist/environment-tasks.d.ts +565 -0
  49. package/dist/environment-tasks.d.ts.map +1 -0
  50. package/dist/environment-tasks.js +269 -0
  51. package/dist/environment-tasks.js.map +1 -0
  52. package/dist/host-client-factory.d.ts +336 -0
  53. package/dist/host-client-factory.d.ts.map +1 -0
  54. package/dist/host-client-factory.js +754 -0
  55. package/dist/host-client-factory.js.map +1 -0
  56. package/dist/idle-drain.d.ts +14 -0
  57. package/dist/idle-drain.d.ts.map +1 -0
  58. package/dist/idle-drain.js +72 -0
  59. package/dist/idle-drain.js.map +1 -0
  60. package/dist/idle-drain.test.d.ts +2 -0
  61. package/dist/idle-drain.test.d.ts.map +1 -0
  62. package/dist/idle-drain.test.js +52 -0
  63. package/dist/idle-drain.test.js.map +1 -0
  64. package/dist/index.d.ts +110 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +97 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/invocation-tracer.d.ts +10 -0
  69. package/dist/invocation-tracer.d.ts.map +1 -0
  70. package/dist/invocation-tracer.js +61 -0
  71. package/dist/invocation-tracer.js.map +1 -0
  72. package/dist/protocol.d.ts +2519 -0
  73. package/dist/protocol.d.ts.map +1 -0
  74. package/dist/protocol.duplex-channel.test.d.ts +2 -0
  75. package/dist/protocol.duplex-channel.test.d.ts.map +1 -0
  76. package/dist/protocol.duplex-channel.test.js +229 -0
  77. package/dist/protocol.duplex-channel.test.js.map +1 -0
  78. package/dist/protocol.js +368 -0
  79. package/dist/protocol.js.map +1 -0
  80. package/dist/testing.d.ts +258 -0
  81. package/dist/testing.d.ts.map +1 -0
  82. package/dist/testing.js +2624 -0
  83. package/dist/testing.js.map +1 -0
  84. package/dist/types.d.ts +2028 -0
  85. package/dist/types.d.ts.map +1 -0
  86. package/dist/types.js +23 -0
  87. package/dist/types.js.map +1 -0
  88. package/dist/ui/clipboard.d.ts +8 -0
  89. package/dist/ui/clipboard.d.ts.map +1 -0
  90. package/dist/ui/clipboard.js +12 -0
  91. package/dist/ui/clipboard.js.map +1 -0
  92. package/dist/ui/components.d.ts +518 -0
  93. package/dist/ui/components.d.ts.map +1 -0
  94. package/dist/ui/components.js +135 -0
  95. package/dist/ui/components.js.map +1 -0
  96. package/dist/ui/hooks.d.ts +155 -0
  97. package/dist/ui/hooks.d.ts.map +1 -0
  98. package/dist/ui/hooks.js +195 -0
  99. package/dist/ui/hooks.js.map +1 -0
  100. package/dist/ui/index.d.ts +55 -0
  101. package/dist/ui/index.d.ts.map +1 -0
  102. package/dist/ui/index.js +52 -0
  103. package/dist/ui/index.js.map +1 -0
  104. package/dist/ui/runtime.d.ts +3 -0
  105. package/dist/ui/runtime.d.ts.map +1 -0
  106. package/dist/ui/runtime.js +30 -0
  107. package/dist/ui/runtime.js.map +1 -0
  108. package/dist/ui/types.d.ts +423 -0
  109. package/dist/ui/types.d.ts.map +1 -0
  110. package/dist/ui/types.js +17 -0
  111. package/dist/ui/types.js.map +1 -0
  112. package/dist/worker-rpc-host.d.ts +93 -0
  113. package/dist/worker-rpc-host.d.ts.map +1 -0
  114. package/dist/worker-rpc-host.js +2086 -0
  115. package/dist/worker-rpc-host.js.map +1 -0
  116. package/dist/workspace-operation-error.d.ts +46 -0
  117. package/dist/workspace-operation-error.d.ts.map +1 -0
  118. package/dist/workspace-operation-error.js +78 -0
  119. package/dist/workspace-operation-error.js.map +1 -0
  120. package/dist/workspace-provider.d.ts +395 -0
  121. package/dist/workspace-provider.d.ts.map +1 -0
  122. package/dist/workspace-provider.js +182 -0
  123. package/dist/workspace-provider.js.map +1 -0
  124. package/package.json +85 -4
package/README.md CHANGED
@@ -1,3 +1,1631 @@
1
- # Temporary Holding Version
1
+ # `@paperclipai/plugin-sdk`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official TypeScript SDK for Paperclip plugin authors.
4
+
5
+ - **Worker SDK:** `@paperclipai/plugin-sdk` — `definePlugin`, context, lifecycle
6
+ - **UI SDK:** `@paperclipai/plugin-sdk/ui` — React hooks and slot props
7
+ - **Testing:** `@paperclipai/plugin-sdk/testing` — in-memory host harness
8
+ - **Bundlers:** `@paperclipai/plugin-sdk/bundlers` — esbuild/rollup presets
9
+ - **Dev server:** `@paperclipai/plugin-sdk/dev-server` — static UI server + SSE reload
10
+
11
+ Reference: `doc/plugins/PLUGIN_SPEC.md`
12
+
13
+ ## Package surface
14
+
15
+ | Import | Purpose |
16
+ |--------|--------|
17
+ | `@paperclipai/plugin-sdk` | Worker entry: `definePlugin`, `runWorker`, context types, protocol helpers |
18
+ | `@paperclipai/plugin-sdk/ui` | UI entry: hooks, host navigation, HTTP-safe clipboard copy, shared components, and slot prop types |
19
+ | `@paperclipai/plugin-sdk/ui/hooks` | Hooks only |
20
+ | `@paperclipai/plugin-sdk/ui/types` | UI types and slot prop interfaces |
21
+ | `@paperclipai/plugin-sdk/testing` | `createTestHarness` for unit/integration tests |
22
+ | `@paperclipai/plugin-sdk/bundlers` | `createPluginBundlerPresets` for worker/manifest/ui builds |
23
+ | `@paperclipai/plugin-sdk/dev-server` | `startPluginDevServer`, `getUiBuildSnapshot` |
24
+ | `@paperclipai/plugin-sdk/protocol` | JSON-RPC protocol types and helpers (advanced) |
25
+ | `@paperclipai/plugin-sdk/types` | Worker context and API types (advanced) |
26
+
27
+ ## Manifest entrypoints
28
+
29
+ In your plugin manifest you declare:
30
+
31
+ - **`entrypoints.worker`** (required) — Path to the worker bundle (e.g. `dist/worker.js`). The host loads this and calls `setup(ctx)`.
32
+ - **`entrypoints.ui`** (required if you use UI) — Path to the UI bundle directory. The host loads components from here for slots and launchers.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pnpm add @paperclipai/plugin-sdk
38
+ ```
39
+
40
+ ## Current deployment caveats
41
+
42
+ The SDK is stable enough for local development and first-party examples, but the runtime deployment model is still early.
43
+
44
+ - Plugin workers and plugin UI should both be treated as trusted code today.
45
+ - Plugin UI bundles run as same-origin JavaScript inside the main Paperclip app. They can call ordinary Paperclip HTTP APIs with the board session, so manifest capabilities are not a frontend sandbox.
46
+ - Local-path installs and the repo example plugins are development workflows. They assume the plugin source checkout exists on disk.
47
+ - For deployed plugins, publish an npm package and install that package into the Paperclip instance at runtime.
48
+ - The current host runtime expects a writable filesystem, `npm` available at runtime, and network access to the package registry used for plugin installation.
49
+ - Dynamic plugin install is currently best suited to single-node persistent deployments. Multi-instance cloud deployments still need a shared artifact/distribution model before runtime installs are reliable across nodes.
50
+ - The host ships a small shared React component kit through `@paperclipai/plugin-sdk/ui`. Use it for native Paperclip controls; custom React and CSS are still supported.
51
+ - `ctx.assets` is not part of the supported runtime in this build. Do not depend on asset upload/read APIs yet.
52
+
53
+ If you are authoring a plugin for others to deploy, treat npm-packaged installation as the supported path and treat repo-local example installs as a development convenience.
54
+
55
+ ## Runner ingress failures
56
+
57
+ Environment providers can throw `PluginEnvironmentRunnerIngressError` from
58
+ `onEnvironmentRunnerIngressEndpoint` with a validated SDK HTTP status and one
59
+ closed phase: `sandbox_lookup`, `sandbox_start`, `sandbox_refresh` or
60
+ `private_preview`. The worker forwards only this closed status/phase envelope.
61
+ It omits response bodies, URLs, headers and causes. The host independently
62
+ validates it with `readEnvironmentRunnerIngressFailure`. Do not derive a status
63
+ from error text. Unknown and configuration failures keep their normal errors.
64
+ The envelope alone grants no retry, accounting or cleanup authority; native
65
+ execution also requires its complete, current controller checkpoint proof.
66
+
67
+ ## Stop failures
68
+
69
+ Environment providers can throw `PluginEnvironmentStopError` from
70
+ `onEnvironmentStopLease` when they cannot stop a resource that is in a provider
71
+ error state. The error takes one closed reason:
72
+
73
+ - `resource_unrecoverable`: the provider reports that the resource cannot recover.
74
+ - `recovery_failed`: the resource is in an error state again after one recovery attempt.
75
+ - `recovery_incomplete`: recovery did not finish before the stop deadline.
76
+
77
+ The worker forwards only the reason. It omits messages, provider error text and
78
+ causes. The host reads it with `readEnvironmentStopFailure`, which derives the
79
+ `terminal` flag from the reason. The first two reasons are terminal: another
80
+ automatic attempt cannot succeed without provider or operator action. The host
81
+ escalates a terminal failure at once and retries it at its slowest cleanup
82
+ interval. It never abandons the pending cleanup. Other stop errors keep their
83
+ normal retry behavior.
84
+
85
+ ## Worker quick start
86
+
87
+ ```ts
88
+ import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
89
+
90
+ const plugin = definePlugin({
91
+ async setup(ctx) {
92
+ ctx.events.on("issue.created", async (event) => {
93
+ ctx.logger.info("Issue created", { issueId: event.entityId });
94
+ });
95
+
96
+ ctx.data.register("health", async () => ({ status: "ok" }));
97
+ ctx.actions.register("ping", async () => ({ pong: true }));
98
+
99
+ ctx.tools.register("calculator", {
100
+ displayName: "Calculator",
101
+ description: "Basic math",
102
+ parametersSchema: {
103
+ type: "object",
104
+ properties: { a: { type: "number" }, b: { type: "number" } },
105
+ required: ["a", "b"]
106
+ }
107
+ }, async (params) => {
108
+ const { a, b } = params as { a: number; b: number };
109
+ return { content: `Result: ${a + b}`, data: { result: a + b } };
110
+ });
111
+ },
112
+ });
113
+
114
+ export default plugin;
115
+ runWorker(plugin, import.meta.url);
116
+ ```
117
+
118
+ ### Connectors
119
+
120
+ Prefer a connector over top-level `tools` for new plugins. Declare it in the
121
+ manifest `apps` (requires `connectors.provide`) with a method that uses
122
+ `transport: "plugin"`, then serve its tools from the worker:
123
+
124
+ ```ts
125
+ // manifest: apps: [{ slug: "records", ..., methods: [{ key: "default", transport: "plugin",
126
+ // auth: "none", settingsSchema: {...}, timeoutMs: 30000, tools: { kind: "static", list: [
127
+ // { name: "lookup_record", risk: "read", parametersSchema: {...} },
128
+ // { name: "build_report", risk: "read", parametersSchema: {...}, timeoutMs: 60000 }] } }] }]
129
+ ctx.connectors.register("records", "lookup_record", async (params, runCtx) => {
130
+ // runCtx.connection: { id, appSlug, methodKey, grantId, settings, credential? }
131
+ return { content: `Record for ${runCtx.connection.settings.region}` };
132
+ });
133
+ // For `tools: { kind: "dynamic" }`, list tools per connection:
134
+ ctx.connectors.listTools("records", async (connection) => [
135
+ { name: "lookup_record", risk: "read", parametersSchema: { type: "object" } },
136
+ ]);
137
+ ```
138
+
139
+ A connector behaves like a built-in one: enabling the plugin only adds it to
140
+ the Connectors catalog, and agents get its tools only from a connection
141
+ installed for them or for the whole company. The host validates settings
142
+ against `settingsSchema`, resolves the connection's credential (`api_key`
143
+ methods) for each call only, and passes the run context from the gateway
144
+ session; tool arguments cannot change it. Every static tool needs a
145
+ registered handler before `setup` returns, or the worker fails to start.
146
+
147
+ The gateway waits 30 s for a plugin connector tool by default. If your
148
+ backend legitimately takes longer, declare `timeoutMs` (1000–60000 ms) on the
149
+ method, or on a single static tool to override the method's value. Values
150
+ outside that range fail manifest validation; 60 s is the gateway's ceiling.
151
+ A call that a person approved under an "ask first" policy always gets the
152
+ gateway's fixed 60 s approved-execution budget, whatever the tool declares.
153
+
154
+ Top-level `tools` with `ctx.tools.register` stay supported as legacy. The host
155
+ offers them as one implicit connector named after the plugin: installations
156
+ that existed before connectors keep them for every agent, and new
157
+ installations get them through an install of that connector.
158
+
159
+ **Note:** `runWorker(plugin, import.meta.url)` must be called so that when the host runs your worker (e.g. `node dist/worker.js`), the RPC host starts and the process stays alive. When the file is imported (e.g. for tests), the main-module check prevents the host from starting.
160
+
161
+ ### Worker lifecycle and context
162
+
163
+ **Lifecycle (definePlugin):**
164
+
165
+ | Hook | Purpose |
166
+ |------|--------|
167
+ | `setup(ctx)` | **Required.** Called once at startup. Register event handlers, jobs, data/actions/tools, etc. |
168
+ | `onHealth?()` | Optional. Return `{ status, message?, details? }` for health dashboard. |
169
+ | `onConfigChanged?(newConfig)` | Optional. Apply new config without restart; if omitted, host restarts worker. |
170
+ | `onShutdown?()` | Optional. Clean up before process exit (limited time window). |
171
+ | `onValidateConfig?(config)` | Optional. Return `{ ok, warnings?, errors? }` for settings UI / Test Connection. |
172
+ | `onWebhook?(input)` | Optional. Handle `POST /api/plugins/:pluginId/webhooks/:endpointKey`; required if webhooks declared. |
173
+
174
+ **Context (`ctx`) in setup:** `config`, `localFolders`, `events`, `jobs`, `launchers`, `http`, `secrets`, `activity`, `state`, `entities`, `projects`, `companies`, `issues`, `agents`, `goals`, `access`, `authorization`, `data`, `actions`, `streams`, `tools`, `metrics`, `logger`, `manifest`. Worker-side host APIs are capability-gated; declare capabilities in the manifest.
175
+
176
+ **Agents:** `ctx.agents.invoke(agentId, companyId, opts)` for one-shot invocation. `ctx.agents.sessions` for two-way chat: `create`, `list`, `sendMessage` (with streaming `onEvent` callback), `close`. See the [Plugin Authoring Guide](../../doc/plugins/PLUGIN_AUTHORING_GUIDE.md#agent-sessions-two-way-chat) for details.
177
+
178
+ **Jobs:** Declare in `manifest.jobs` with `jobKey`, `displayName`, `schedule` (cron). Register handler with `ctx.jobs.register(jobKey, fn)`. **Webhooks:** Declare in `manifest.webhooks` with `endpointKey`; handle in `onWebhook(input)`. **State:** `ctx.state.get/set/delete(scopeKey)`; scope kinds: `instance`, `company`, `project`, `project_workspace`, `agent`, `issue`, `goal`, `run`.
179
+
180
+ **Trusted local folders:** Declare `manifest.localFolders[]` and the `local.folders` capability when a plugin needs an operator-configured company-scoped folder. Use `ctx.localFolders.configure()`, `status()`, `readText()`, and `writeTextAtomic()` instead of resolving arbitrary filesystem paths yourself. The host validates absolute roots, read/write access, required relative folders/files, traversal attempts, symlink escapes, and writes through temp-file-plus-rename atomic replacement.
181
+
182
+ ## Events
183
+
184
+ Subscribe in `setup` with `ctx.events.on(name, handler)` or `ctx.events.on(name, filter, handler)`. Emit plugin-scoped events with `ctx.events.emit(name, companyId, payload)` (requires `events.emit`).
185
+
186
+ **Core domain events (subscribe with `events.subscribe`):**
187
+
188
+ | Event | Typical entity |
189
+ |-------|-----------------|
190
+ | `company.created`, `company.updated` | company |
191
+ | `project.created`, `project.updated` | project |
192
+ | `project.workspace_created`, `project.workspace_updated`, `project.workspace_deleted` | project_workspace |
193
+ | `issue.created`, `issue.updated`, `issue.comment.created` | issue |
194
+ | `issue.document.created`, `issue.document.updated`, `issue.document.deleted` | issue |
195
+ | `issue.relations.updated`, `issue.checked_out`, `issue.released`, `issue.assignment_wakeup_requested` | issue |
196
+ | `agent.created`, `agent.updated`, `agent.status_changed` | agent |
197
+ | `agent.run.started`, `agent.run.finished`, `agent.run.failed`, `agent.run.cancelled` | run |
198
+ | `goal.created`, `goal.updated` | goal |
199
+ | `approval.created`, `approval.decided` | approval |
200
+ | `budget.incident.opened`, `budget.incident.resolved` | budget_incident |
201
+ | `cost_event.created` | cost |
202
+ | `activity.logged` | activity |
203
+
204
+ **Plugin-to-plugin:** Subscribe to `plugin.<pluginId>.<eventName>` (e.g. `plugin.acme.linear.sync-done`). Emit with `ctx.events.emit("sync-done", companyId, payload)`; the host namespaces it automatically.
205
+
206
+ **Filter (optional):** Pass a second argument to `on()`: `{ projectId?, companyId?, agentId? }` so the host only delivers matching events.
207
+
208
+ **Company context:** Events still carry `companyId` for company-scoped data, but plugin installation and activation are instance-wide in the current runtime. Access and authorization host services require an active company-scoped invocation such as an event, API route, tool run, environment call, or UI bridge call; the requested `companyId` must match that active scope.
209
+
210
+ ## Scheduled (recurring) jobs
211
+
212
+ Plugins can declare **scheduled jobs** that the host runs on a cron schedule. Use this for recurring tasks like syncs, digest reports, or cleanup.
213
+
214
+ 1. **Capability:** Add `jobs.schedule` to `manifest.capabilities`.
215
+ 2. **Declare jobs** in `manifest.jobs`: each entry has `jobKey`, `displayName`, optional `description`, and `schedule` (a 5-field cron expression).
216
+ 3. **Register a handler** in `setup()` with `ctx.jobs.register(jobKey, async (job) => { ... })`.
217
+
218
+ **Cron format** (5 fields: minute, hour, day-of-month, month, day-of-week):
219
+
220
+ | Field | Values | Example |
221
+ |-------------|----------|---------|
222
+ | minute | 0–59 | `0`, `*/15` |
223
+ | hour | 0–23 | `2`, `*` |
224
+ | day of month | 1–31 | `1`, `*` |
225
+ | month | 1–12 | `*` |
226
+ | day of week | 0–6 (Sun=0) | `*`, `1-5` |
227
+
228
+ Examples: `"0 * * * *"` = every hour at minute 0; `"*/5 * * * *"` = every 5 minutes; `"0 2 * * *"` = daily at 2:00.
229
+
230
+ **Job handler context** (`PluginJobContext`):
231
+
232
+ | Field | Type | Description |
233
+ |-------------|----------|-------------|
234
+ | `jobKey` | string | Matches the manifest declaration. |
235
+ | `runId` | string | UUID for this run. |
236
+ | `trigger` | `"schedule" \| "manual" \| "retry"` | What caused this run. |
237
+ | `scheduledAt` | string | ISO 8601 time when the run was scheduled. |
238
+
239
+ Runs can be triggered by the **schedule**, **manually** from the UI/API, or as a **retry** (when an operator re-runs a job after a failure). Re-throw from the handler to mark the run as failed; the host records the failure. The host does not automatically retry—operators can trigger another run manually from the UI or API.
240
+
241
+ Example:
242
+
243
+ **Manifest** — include `jobs.schedule` and declare the job:
244
+
245
+ ```ts
246
+ // In your manifest (e.g. manifest.ts):
247
+ const manifest = {
248
+ // ...
249
+ capabilities: ["jobs.schedule", "plugin.state.write"],
250
+ jobs: [
251
+ {
252
+ jobKey: "heartbeat",
253
+ displayName: "Heartbeat",
254
+ description: "Runs every 5 minutes",
255
+ schedule: "*/5 * * * *",
256
+ },
257
+ ],
258
+ // ...
259
+ };
260
+ ```
261
+
262
+ **Worker** — register the handler in `setup()`:
263
+
264
+ ```ts
265
+ ctx.jobs.register("heartbeat", async (job) => {
266
+ ctx.logger.info("Heartbeat run", { runId: job.runId, trigger: job.trigger });
267
+ await ctx.state.set({ scopeKind: "instance", stateKey: "last-heartbeat" }, new Date().toISOString());
268
+ });
269
+ ```
270
+
271
+ ## UI slots and launchers
272
+
273
+ Slots are mount points for plugin React components. Launchers are host-rendered entry points (buttons, menu items) that open plugin UI. Declare slots in `manifest.ui.slots` with `type`, `id`, `displayName`, `exportName`; for context-sensitive slots add `entityTypes`. Declare launchers in `manifest.ui.launchers` (or legacy `manifest.launchers`).
274
+
275
+ ### Slot types / launcher placement zones
276
+
277
+ Slot types describe where a component mounts. Most values also exist as launcher placement zones.
278
+
279
+ | Slot type / placement zone | Scope | Entity types (when context-sensitive) |
280
+ |----------------------------|-------|---------------------------------------|
281
+ | `page` | Global | — |
282
+ | `sidebar` | Global | — |
283
+ | `routeSidebar` | Global | — |
284
+ | `sidebarPanel` | Global | — |
285
+ | `settingsPage` | Global | — |
286
+ | `dashboardWidget` | Global | — |
287
+ | `globalToolbarButton` | Global | — |
288
+ | `appShellOverlay` (slot only) | Signed-in application shell | — |
289
+ | `detailTab` | Entity | `project`, `issue`, `agent`, `goal`, `run` |
290
+ | `taskDetailView` | Entity | (task/issue context) |
291
+ | `commentAnnotation` | Entity | `comment` |
292
+ | `commentContextMenuItem` | Entity | `comment` |
293
+ | `projectSidebarItem` | Entity | `project` |
294
+ | `toolbarButton` | Entity | varies by host surface |
295
+ | `contextMenuItem` | Entity | varies by host surface |
296
+
297
+ **Scope** describes whether the slot requires an entity to render. **Global** slots render without a specific entity but still receive the active `companyId` through `PluginHostContext` — use it to scope data fetches to the current company. **Entity** slots additionally require `entityId` and `entityType` (e.g. a detail tab on a specific issue).
298
+
299
+ **Entity types** (for `entityTypes` on slots): `project` \| `issue` \| `agent` \| `goal` \| `run` \| `comment`. Full list: import `PLUGIN_UI_SLOT_TYPES` and `PLUGIN_UI_SLOT_ENTITY_TYPES` from `@paperclipai/plugin-sdk`.
300
+
301
+ ### Slot component descriptions
302
+
303
+ #### `page`
304
+
305
+ A full-page extension mounted at `/plugins/:pluginId` (global) or `/:company/plugins/:pluginId` (company-context route). Use this for rich, standalone plugin experiences such as dashboards, configuration wizards, or multi-step workflows. Receives `PluginPageProps` with `context.companyId` set to the active company. Requires the `ui.page.register` capability.
306
+
307
+ #### `sidebar`
308
+
309
+ Adds a navigation-style entry to the main company sidebar navigation area, rendered alongside the core nav items (Dashboard, Issues, Goals, etc.). Use this for lightweight, always-visible links or status indicators that feel native to the sidebar. Receives `PluginSidebarProps` with `context.companyId` set to the active company. Requires the `ui.sidebar.register` capability.
310
+
311
+ #### `routeSidebar`
312
+
313
+ A contextual sidebar shown while the current route is a plugin page route with the same `routePath`. Use this for full-page plugin workspaces that need their own local navigation. The host displays it in the sidebar area using the active app layout. Receives `PluginRouteSidebarProps` with `context.companyId` and `context.companyPrefix` set to the active company. Requires the `ui.sidebar.register` capability.
314
+
315
+ #### `sidebarPanel`
316
+
317
+ Renders richer inline content in a dedicated panel area below the company sidebar navigation sections. Use this for mini-widgets, summary cards, quick-action panels, or at-a-glance status views that need more vertical space than a nav link. Receives `context.companyId` set to the active company via `useHostContext()`. Requires the `ui.sidebar.register` capability.
318
+
319
+ #### `settingsPage`
320
+
321
+ Replaces the auto-generated JSON Schema settings form with a custom React component. Use this when the default form is insufficient — for example, when your plugin needs multi-step configuration, OAuth flows, "Test Connection" buttons, or rich input controls. Receives `PluginSettingsPageProps` with `context.companyId` set to the active company. The component is responsible for reading and writing config through the bridge (via `usePluginData` and `usePluginAction`).
322
+
323
+ #### `dashboardWidget`
324
+
325
+ A card or section rendered on the main dashboard. Use this for at-a-glance metrics, status indicators, or summary views that surface plugin data alongside core Paperclip information. Receives `PluginWidgetProps` with `context.companyId` set to the active company. Requires the `ui.dashboardWidget.register` capability.
326
+
327
+ #### `detailTab`
328
+
329
+ An additional tab on a project, issue, agent, goal, or run detail page. Rendered when the user navigates to that entity's detail view. Receives `PluginDetailTabProps` with `context.companyId` set to the active company and `context.entityId` / `context.entityType` guaranteed to be non-null, so you can immediately scope data fetches to the relevant entity. Specify which entity types the tab applies to via the `entityTypes` array in the manifest slot declaration. Requires the `ui.detailTab.register` capability.
330
+
331
+ Agent detail tabs can also appear in task side panels. `taskSidePanel` makes the
332
+ view available for manual selection with the running or assigned agent. Manual
333
+ selection mounts the same component as the agent detail page, including while
334
+ the task is idle. An optional activity mapping also opens it automatically:
335
+
336
+ ```ts
337
+ taskSidePanel: {
338
+ availabilityPath: "/agents/:entityId/view/availability",
339
+ activation: { namespace: "example.runtime", activityKey: "desktop.used" },
340
+ }
341
+ ```
342
+
343
+ Declare the exact availability path as a board-only GET API route with
344
+ `companyResolution: { from: "agent", param: "entityId" }`. Core maps the declared
345
+ namespace/activity pair to installed agent detail tabs. Runner knows no plugin
346
+ or UI slot. Declarations without `activation` support manual task-panel selection.
347
+ Activity controls automatic opening and grants no access permission.
348
+
349
+ #### Runtime activity recording
350
+
351
+ A runtime client captures Runner's opaque activity context before an eligible
352
+ operation, then sends a structured notification after successful use:
353
+
354
+ ```sh
355
+ context=$("$PAPERCLIP_RUNTIME_NOTIFICATION_HELPER" notification-context)
356
+ # Perform the operation; notify only on success.
357
+ "$PAPERCLIP_RUNTIME_NOTIFICATION_HELPER" record-activity "$context" example.runtime desktop.used
358
+ ```
359
+
360
+ Runner supplies the matching absolute executable as
361
+ `PAPERCLIP_RUNTIME_NOTIFICATION_HELPER` and an atomic endpoint descriptor as
362
+ `PAPERCLIP_RUNTIME_NOTIFICATION_CONTEXT`. Configured task environment cannot
363
+ override them. Provider launch boundaries preserve both values. Codex receives
364
+ read access to the helper, descriptor and publisher lock, plus write access to
365
+ one named pipe. The pipe and lock live in a private temporary directory, outside
366
+ durable Runner state. The enclosing directories remain protected.
367
+
368
+ The helper captures context locally. After success, it publishes newline-delimited
369
+ JSON through a nonblocking pipe. A leading newline terminates an interrupted
370
+ previous write. A read-only file lock serializes publishers with a 500 ms deadline.
371
+ Runner reuses its bounded line reader: 2 KiB per record, 128 queued records and
372
+ 16 records per control-loop iteration. Idle transport blocks; cleanup removes
373
+ only its pipe, lock and empty private directory.
374
+
375
+ A successful helper exit means publication to the pipe. Runner validates context
376
+ against the active run, deduplicates up to 128 activity pairs per authority, and
377
+ persists `runtime.activity.recorded` through its authenticated event stream.
378
+ Warm attachment and process recovery rotate context. The helper accepts no run
379
+ identity. Clients treat this hint as best effort, including with older runtimes.
380
+ Notify only after successful use; exclude help, schema discovery, status probes
381
+ and failures. No agent instruction is required.
382
+
383
+ Identifiers are 1–160 Unicode code points, excluding C0 controls and DEL.
384
+ Core maps declared activity identifiers to its consumers and applies their
385
+ existing discovery, authorization and availability checks.
386
+
387
+ Core reads durable activity on mount/reconnect and uses the existing live stream.
388
+ The authorized run binding identifies company, task and agent; caller payloads
389
+ cannot override them. Core replaces `:entityId` with the running agent ID, adds
390
+ `runId` and `issueId`, and requires `{ available: true }`. History/live hints merge
391
+ without losing earlier activity. Only matching current-task activity can open a
392
+ panel automatically.
393
+ Readiness and transient discovery failures get at most three attempts; authorization
394
+ failures are not retried. No periodic readiness polling is added. Dismissal stays
395
+ scoped to the current run. Only tab identity is stored in browser state; activity
396
+ remains in the authorized run log. Failed history reads, unavailable views and
397
+ access failures prevent automatic opening. Manual selection uses the viewer's
398
+ own authorization and status handling. Missing or disabled plugins add no view.
399
+ The plugin owns labels, content and controls. No private integration identifier
400
+ belongs in Core.
401
+
402
+ #### `taskDetailView`
403
+
404
+ A specialized slot rendered in the context of a task or issue detail view. Similar to `detailTab` but designed for inline content within the task detail layout rather than a separate tab. Receives `context.companyId`, `context.entityId`, and `context.entityType` like `detailTab`. Requires the `ui.detailTab.register` capability.
405
+
406
+ #### `projectSidebarItem`
407
+
408
+ A link or small component rendered **once per project** under that project's row in the sidebar Projects list. Use this to add project-scoped navigation entries (e.g. "Files", "Linear Sync") that deep-link into a plugin detail tab: `/:company/projects/:projectRef?tab=plugin:<key>:<slotId>`. Receives `PluginProjectSidebarItemProps` with `context.companyId` set to the active company, `context.entityId` set to the project id, and `context.entityType` set to `"project"`. Use the optional `order` field in the manifest slot to control sort position. Requires the `ui.sidebar.register` capability.
409
+
410
+ #### `globalToolbarButton`
411
+
412
+ A button rendered in the global top bar (breadcrumb bar) that appears on every page. Use this for company-wide actions that are not scoped to a specific entity — for example, a universal search trigger, a global sync status indicator, or a floating action that applies across the whole workspace. Receives only `context.companyId` and `context.companyPrefix`; no entity context is available. Requires the `ui.action.register` capability.
413
+
414
+ #### `toolbarButton`
415
+
416
+ A button rendered in the toolbar of an entity page (e.g. project detail, issue detail). Use this for short-lived, contextual actions scoped to the current entity — like triggering a project sync, opening a picker, or running a quick command on that entity. The component can open a plugin-owned modal internally for confirmations or compact forms. Receives `context.companyId`, `context.entityId`, and `context.entityType`; declare `entityTypes` in the manifest to control which entity pages the button appears on. Requires the `ui.action.register` capability.
417
+
418
+ #### `contextMenuItem`
419
+
420
+ An entry added to a right-click or overflow context menu on a host surface. Use this for secondary actions that apply to the entity under the cursor (e.g. "Copy to Linear", "Re-run analysis"). Receives `context.companyId` set to the active company; entity context varies by host surface. Requires the `ui.action.register` capability.
421
+
422
+ #### `commentAnnotation`
423
+
424
+ A per-comment annotation region rendered below each individual comment in the issue detail timeline. Use this to augment comments with parsed file links, sentiment badges, inline actions, or any per-comment metadata. Receives `PluginCommentAnnotationProps` with `context.entityId` set to the comment UUID, `context.entityType` set to `"comment"`, `context.parentEntityId` set to the parent issue UUID, `context.projectId` set to the issue's project (if any), and `context.companyPrefix` set to the active company slug. Requires the `ui.commentAnnotation.register` capability.
425
+
426
+ #### `commentContextMenuItem`
427
+
428
+ A per-comment context menu item rendered in the "more" dropdown menu (⋮) on each comment in the issue detail timeline. Use this to add per-comment actions such as "Create sub-issue from comment", "Translate", "Flag for review", or custom plugin actions. Receives `PluginCommentContextMenuItemProps` with `context.entityId` set to the comment UUID, `context.entityType` set to `"comment"`, `context.parentEntityId` set to the parent issue UUID, `context.projectId` set to the issue's project (if any), and `context.companyPrefix` set to the active company slug. Plugins can open drawers, modals, or popovers scoped to that comment. The ⋮ menu button only appears on comments where at least one plugin renders visible content. Requires the `ui.action.register` capability.
429
+
430
+ ### Launcher actions and render options
431
+
432
+ | Launcher action | Description |
433
+ |-----------------|-------------|
434
+ | `navigate` | Navigate to a route (plugin or host). |
435
+ | `openModal` | Open a modal. |
436
+ | `openDrawer` | Open a drawer. |
437
+ | `openPopover` | Open a popover. |
438
+ | `performAction` | Run an action (e.g. call plugin). |
439
+ | `deepLink` | Deep link to plugin or external URL. |
440
+
441
+ | Render option | Values | Description |
442
+ |---------------|--------|-------------|
443
+ | `environment` | `hostInline`, `hostOverlay`, `hostRoute`, `external`, `iframe` | Container the launcher expects after activation. |
444
+ | `bounds` | `inline`, `compact`, `default`, `wide`, `full` | Size hint for overlays/drawers. |
445
+
446
+ ### Capabilities
447
+
448
+ Declare in `manifest.capabilities`. Grouped by scope:
449
+
450
+ | Scope | Capability |
451
+ |-------|------------|
452
+ | **Company** | `companies.read` |
453
+ | | `projects.read` |
454
+ | | `project.workspaces.read` |
455
+ | | `issues.read` |
456
+ | | `issue.comments.read` |
457
+ | | `issue.documents.read` |
458
+ | | `issue.relations.read` |
459
+ | | `issue.subtree.read` |
460
+ | | `agents.read` |
461
+ | | `goals.read` |
462
+ | | `goals.create` |
463
+ | | `goals.update` |
464
+ | | `activity.read` |
465
+ | | `costs.read` |
466
+ | | `issues.orchestration.read` |
467
+ | | `access.members.read` |
468
+ | | `access.invites.read` |
469
+ | | `authorization.grants.read` |
470
+ | | `authorization.policies.read` |
471
+ | | `authorization.audit.read` |
472
+ | | `database.namespace.read` |
473
+ | | `issues.create` |
474
+ | | `issues.update` |
475
+ | | `issues.checkout` |
476
+ | | `issues.wakeup` |
477
+ | | `issue.comments.create` |
478
+ | | `issue.comments.create_human_attributed` |
479
+ | | `issue.documents.write` |
480
+ | | `issue.relations.write` |
481
+ | | `activity.log.write` |
482
+ | | `metrics.write` |
483
+ | | `telemetry.track` |
484
+ | | `database.namespace.migrate` |
485
+ | | `database.namespace.write` |
486
+ | | `external.objects.detect` |
487
+ | | `external.objects.read` |
488
+ | | `external.objects.write` |
489
+ | | `external.objects.refresh` |
490
+ | **Instance** | `instance.settings.register` |
491
+ | | `plugin.state.read` |
492
+ | | `plugin.state.write` |
493
+ | **Runtime** | `events.subscribe` |
494
+ | | `events.emit` |
495
+ | | `jobs.schedule` |
496
+ | | `webhooks.receive` |
497
+ | | `api.routes.register` |
498
+ | | `http.outbound` |
499
+ | | `secrets.read-ref` |
500
+ | | `environment.drivers.register` |
501
+ | | `local.folders` |
502
+ | **Agent** | `agent.tools.register` |
503
+ | **Connectors** | `connectors.provide` |
504
+ | | `agents.invoke` |
505
+ | | `access.members.write` |
506
+ | | `access.invites.write` |
507
+ | | `authorization.grants.write` |
508
+ | | `authorization.policies.write` |
509
+ | | `agent.sessions.create` |
510
+ | | `agent.sessions.list` |
511
+ | | `agent.sessions.send` |
512
+ | | `agent.sessions.close` |
513
+ | **UI** | `ui.sidebar.register` |
514
+ | | `ui.page.register` |
515
+ | | `ui.detailTab.register` |
516
+ | | `ui.dashboardWidget.register` |
517
+ | | `ui.commentAnnotation.register` |
518
+ | | `ui.action.register` |
519
+
520
+ Full list in code: import `PLUGIN_CAPABILITIES` from `@paperclipai/plugin-sdk`.
521
+
522
+ ### External Object Reference Providers
523
+
524
+ Trusted connector plugins can declare generic external object providers in the
525
+ manifest. The host owns URL scanning, sanitized canonical URLs, core storage,
526
+ normalized status rendering, and issue/comment/document write durability. The
527
+ plugin only identifies provider-owned objects and resolves board-safe status
528
+ metadata.
529
+
530
+ ```ts
531
+ objectReferences: [
532
+ {
533
+ providerKey: "mocktracker",
534
+ displayName: "Mock Tracker",
535
+ objectTypes: ["ticket"],
536
+ urlPatterns: ["https://mock.example/tickets/:id"],
537
+ refreshPolicy: { defaultTtlSeconds: 300, staleAfterSeconds: 1800 },
538
+ },
539
+ ],
540
+ capabilities: ["external.objects.detect", "external.objects.read"],
541
+ ```
542
+
543
+ Implement `onDetectExternalObjects()` to map sanitized URL candidates to
544
+ `providerKey`, `objectType`, provider-stable `externalId`, and optional display
545
+ metadata such as `displayKey`/`iconKey`. Implement `onResolveExternalObject()`
546
+ to return a normalized snapshot with `statusCategory`, `statusTone`,
547
+ `statusLabel`, optional `statusIconKey`, board-safe `data`, and freshness
548
+ metadata. Slow or failing plugins are isolated: Paperclip logs the failure and
549
+ continues saving the source issue, comment, or document.
550
+
551
+ MVP security posture: provider plugins are trusted installs. Manifest
552
+ capabilities gate host APIs and provider invocation paths, but they are not a
553
+ sandbox boundary for untrusted marketplace code. Plugin UI is same-origin
554
+ JavaScript and must not be mounted inline in markdown; inline external-object
555
+ rendering uses host-owned metadata only. Treat untrusted providers as future work
556
+ that requires worker sandboxing plus isolated plugin UI.
557
+
558
+ ### Restricted Database Namespace
559
+
560
+ Trusted orchestration plugins can declare a host-owned PostgreSQL namespace:
561
+
562
+ ```ts
563
+ database: {
564
+ migrationsDir: "migrations",
565
+ coreReadTables: ["issues"],
566
+ }
567
+ ```
568
+
569
+ Declare `database.namespace.migrate` and `database.namespace.read`; add
570
+ `database.namespace.write` when the worker needs runtime writes. Migrations run
571
+ before worker startup, are checksum-recorded, and may create or alter objects
572
+ only inside the plugin namespace. Runtime `ctx.db.query()` allows `SELECT` from
573
+ `ctx.db.namespace` plus manifest-whitelisted `public` core tables. Runtime
574
+ `ctx.db.execute()` allows `INSERT`, `UPDATE`, and `DELETE` only against the
575
+ plugin namespace.
576
+
577
+ ### Trusted Local Folders
578
+
579
+ Trusted local plugins can request operator-configured folders per company:
580
+
581
+ ```ts
582
+ export const manifest = {
583
+ // ...
584
+ capabilities: ["local.folders"],
585
+ localFolders: [
586
+ {
587
+ folderKey: "content-root",
588
+ displayName: "Content root",
589
+ access: "readWrite",
590
+ requiredDirectories: ["sources", "pages"],
591
+ requiredFiles: ["schema.md"],
592
+ },
593
+ ],
594
+ };
595
+ ```
596
+
597
+ The host stores the selected path in company-scoped plugin settings and exposes
598
+ readiness through:
599
+
600
+ - `GET /api/plugins/:pluginId/companies/:companyId/local-folders`
601
+ - `GET /api/plugins/:pluginId/companies/:companyId/local-folders/:folderKey/status`
602
+ - `POST /api/plugins/:pluginId/companies/:companyId/local-folders/:folderKey/validate`
603
+ - `PUT /api/plugins/:pluginId/companies/:companyId/local-folders/:folderKey`
604
+
605
+ Worker code should access files through `ctx.localFolders.readText()` and
606
+ `ctx.localFolders.writeTextAtomic()`. Relative paths must stay inside the
607
+ configured root; symlinks that escape the root are rejected.
608
+
609
+ ### Scoped API Routes
610
+
611
+ Manifest-declared `apiRoutes` expose JSON routes under
612
+ `/api/plugins/:pluginId/api/*` without letting a plugin claim core paths:
613
+
614
+ ```ts
615
+ apiRoutes: [
616
+ {
617
+ routeKey: "initialize",
618
+ method: "POST",
619
+ path: "/issues/:issueId/smoke",
620
+ auth: "board-or-agent",
621
+ capability: "api.routes.register",
622
+ checkoutPolicy: "required-for-agent-in-progress",
623
+ companyResolution: { from: "issue", param: "issueId" },
624
+ },
625
+ ]
626
+ ```
627
+
628
+ Implement `onApiRequest(input)` in the worker to handle the route. The host
629
+ performs auth, company access, capability, route matching, and checkout policy
630
+ before dispatch. The worker receives route params, query, parsed JSON body,
631
+ sanitized headers, actor context, and `companyId`; responses are JSON `{ status?,
632
+ headers?, body? }`.
633
+
634
+ ## Issue Orchestration APIs
635
+
636
+ Workflow plugins can use `ctx.issues` for orchestration-grade issue operations without importing host server internals.
637
+
638
+ A child issue always gets its own execution workspace, realized from the project base. It keeps the parent's project and workspace strategy, never the parent's checkout, branch or unmerged changes. `inheritExecutionWorkspaceFromIssueId` likewise copies only the source issue's project and workspace strategy.
639
+
640
+ Expanded create/update fields include blockers, billing code, board or agent assignees, labels, namespaced plugin origins, request depth, and safe execution workspace fields:
641
+
642
+ ```ts
643
+ const child = await ctx.issues.create({
644
+ companyId,
645
+ parentId: missionIssueId,
646
+ title: "Implement feature slice",
647
+ status: "todo",
648
+ assigneeAgentId: workerAgentId,
649
+ billingCode: "mission:alpha",
650
+ originKind: "plugin:paperclip.missions:feature",
651
+ originId: "mission-alpha:feature-1",
652
+ blockedByIssueIds: [planningIssueId],
653
+ });
654
+ ```
655
+
656
+ If `originKind` is omitted, the host stores `plugin:<pluginKey>`. Plugins may use sub-kinds such as `plugin:<pluginKey>:feature`, but the host rejects attempts to set another plugin's namespace.
657
+
658
+ Blocker relationships are also exposed as first-class helpers:
659
+
660
+ ```ts
661
+ const relations = await ctx.issues.relations.get(child.id, companyId);
662
+ await ctx.issues.relations.setBlockedBy(child.id, [planningIssueId], companyId);
663
+ await ctx.issues.relations.addBlockers(child.id, [validationIssueId], companyId);
664
+ await ctx.issues.relations.removeBlockers(child.id, [planningIssueId], companyId);
665
+ ```
666
+
667
+ Subtree reads can include just the issue tree, or compact related data for orchestration dashboards:
668
+
669
+ ```ts
670
+ const subtree = await ctx.issues.getSubtree(missionIssueId, companyId, {
671
+ includeRoot: true,
672
+ includeRelations: true,
673
+ includeDocuments: true,
674
+ includeActiveRuns: true,
675
+ includeAssignees: true,
676
+ });
677
+ ```
678
+
679
+ Agent-run actions can assert checkout ownership before mutating in-progress work:
680
+
681
+ ```ts
682
+ await ctx.issues.assertCheckoutOwner({
683
+ issueId,
684
+ companyId,
685
+ actorAgentId: runCtx.agentId,
686
+ actorRunId: runCtx.runId,
687
+ });
688
+ ```
689
+
690
+ Plugins can request assignment wakeups through the host so budget stops, execution locks, blocker checks, and heartbeat policy still apply:
691
+
692
+ ```ts
693
+ await ctx.issues.requestWakeup(child.id, companyId, {
694
+ reason: "mission_advance",
695
+ contextSource: "missions.advance",
696
+ });
697
+
698
+ await ctx.issues.requestWakeups([featureIssueId, validationIssueId], companyId, {
699
+ reason: "mission_advance",
700
+ contextSource: "missions.advance",
701
+ idempotencyKeyPrefix: `mission:${missionIssueId}:advance`,
702
+ });
703
+ ```
704
+
705
+ Use `ctx.issues.summaries.getOrchestration()` when a workflow needs compact reads across a root issue or subtree:
706
+
707
+ ```ts
708
+ const summary = await ctx.issues.summaries.getOrchestration({
709
+ issueId: missionIssueId,
710
+ companyId,
711
+ includeSubtree: true,
712
+ billingCode: "mission:alpha",
713
+ });
714
+ ```
715
+
716
+ By default, `ctx.issues.createComment` attributes the comment to the calling
717
+ plugin's own agent (`authorAgentId`). A plugin that relays a message a human
718
+ actually sent — a chat gateway bridging Slack/Telegram replies back onto an
719
+ issue, for example — can instead attribute the comment to that person by
720
+ passing `actorUserId`:
721
+
722
+ ```ts
723
+ await ctx.issues.createComment(issueId, replyText, companyId, {
724
+ actorUserId: verifiedSlackUser.paperclipUserId,
725
+ });
726
+ ```
727
+
728
+ This requires the `issue.comments.create_human_attributed` capability in
729
+ addition to `issue.comments.create`. The host independently verifies that
730
+ `actorUserId` is an active human member of the issue's company before
731
+ applying the comment — a plugin cannot forge attribution to an arbitrary or
732
+ inactive user id. When the issue has a non-terminal status and an assigned
733
+ agent, a human-attributed comment also wakes that assignee, the same way a
734
+ board user's comment does in the web app.
735
+
736
+ Required capabilities:
737
+
738
+ | API | Capability |
739
+ |-----|------------|
740
+ | `ctx.issues.relations.get` | `issue.relations.read` |
741
+ | `ctx.issues.relations.setBlockedBy` / `addBlockers` / `removeBlockers` | `issue.relations.write` |
742
+ | `ctx.issues.getSubtree` | `issue.subtree.read` |
743
+ | `ctx.issues.assertCheckoutOwner` | `issues.checkout` |
744
+ | `ctx.issues.createComment` | `issue.comments.create` |
745
+ | `ctx.issues.createComment` with `actorUserId` | `issue.comments.create` + `issue.comments.create_human_attributed` |
746
+ | `ctx.issues.requestWakeup` / `requestWakeups` | `issues.wakeup` |
747
+ | `ctx.issues.summaries.getOrchestration` | `issues.orchestration.read` |
748
+
749
+ Plugin-originated mutations are logged with `actorType: "plugin"` and details fields `sourcePluginId`, `sourcePluginKey`, `initiatingActorType`, `initiatingActorId`, and `initiatingRunId` when a user or agent run initiated the plugin work.
750
+
751
+ ## UI quick start
752
+
753
+ ```tsx
754
+ import { usePluginData, usePluginAction } from "@paperclipai/plugin-sdk/ui";
755
+
756
+ export function DashboardWidget() {
757
+ const { data } = usePluginData<{ status: string }>("health");
758
+ const ping = usePluginAction("ping");
759
+ return (
760
+ <div style={{ display: "grid", gap: 8 }}>
761
+ <strong>Health</strong>
762
+ <div>{data?.status ?? "unknown"}</div>
763
+ <button onClick={() => void ping()}>Ping</button>
764
+ </div>
765
+ );
766
+ }
767
+ ```
768
+
769
+ ### Hooks reference
770
+
771
+ #### `usePluginData<T>(key, params?)`
772
+
773
+ Fetches data from the worker's registered `getData` handler. Re-fetches when `params` changes. Returns `{ data, loading, error, refresh }`.
774
+
775
+ ```tsx
776
+ import { usePluginData } from "@paperclipai/plugin-sdk/ui";
777
+
778
+ interface SyncStatus {
779
+ lastSyncAt: string;
780
+ syncedCount: number;
781
+ healthy: boolean;
782
+ }
783
+
784
+ export function SyncStatusWidget({ context }: PluginWidgetProps) {
785
+ const { data, loading, error, refresh } = usePluginData<SyncStatus>("sync-status", {
786
+ companyId: context.companyId,
787
+ });
788
+
789
+ if (loading) return <div>Loading…</div>;
790
+ if (error) return <div>Error: {error.message}</div>;
791
+
792
+ return (
793
+ <div>
794
+ <p>Status: {data!.healthy ? "Healthy" : "Unhealthy"}</p>
795
+ <p>Synced {data!.syncedCount} items</p>
796
+ <p>Last sync: {data!.lastSyncAt}</p>
797
+ <button onClick={refresh}>Refresh</button>
798
+ </div>
799
+ );
800
+ }
801
+ ```
802
+
803
+ #### `usePluginAction(key)`
804
+
805
+ Returns an async function that calls the worker's `performAction` handler. Throws `PluginBridgeError` on failure.
806
+
807
+ ```tsx
808
+ import { useState } from "react";
809
+ import { usePluginAction, type PluginBridgeError } from "@paperclipai/plugin-sdk/ui";
810
+
811
+ export function ResyncButton({ context }: PluginWidgetProps) {
812
+ const resync = usePluginAction("resync");
813
+ const [busy, setBusy] = useState(false);
814
+ const [error, setError] = useState<string | null>(null);
815
+
816
+ async function handleClick() {
817
+ setBusy(true);
818
+ setError(null);
819
+ try {
820
+ await resync({ companyId: context.companyId });
821
+ } catch (err) {
822
+ setError((err as PluginBridgeError).message);
823
+ } finally {
824
+ setBusy(false);
825
+ }
826
+ }
827
+
828
+ return (
829
+ <div>
830
+ <button onClick={handleClick} disabled={busy}>
831
+ {busy ? "Syncing..." : "Resync Now"}
832
+ </button>
833
+ {error && <p style={{ color: "red" }}>{error}</p>}
834
+ </div>
835
+ );
836
+ }
837
+ ```
838
+
839
+ #### `useHostContext()`
840
+
841
+ Reads the active company, project, entity, and user context. Use this to scope data fetches and actions.
842
+
843
+ ```tsx
844
+ import { useHostContext, usePluginData } from "@paperclipai/plugin-sdk/ui";
845
+ import type { PluginDetailTabProps } from "@paperclipai/plugin-sdk/ui";
846
+
847
+ export function IssueLinearLink({ context }: PluginDetailTabProps) {
848
+ const { companyId, entityId, entityType } = context;
849
+ const { data } = usePluginData<{ url: string }>("linear-link", {
850
+ companyId,
851
+ issueId: entityId,
852
+ });
853
+
854
+ if (!data?.url) return <p>No linked Linear issue.</p>;
855
+ return <a href={data.url} target="_blank" rel="noopener">View in Linear</a>;
856
+ }
857
+ ```
858
+
859
+ #### `useHostNavigation()`
860
+
861
+ Routes Paperclip-internal plugin links through the host router without a full document reload. Use `linkProps()` for anchors so the browser still gets a real `href` for copy-link, modifier-click, middle-click, and open-in-new-tab behavior.
862
+
863
+ ```tsx
864
+ import { useHostNavigation } from "@paperclipai/plugin-sdk/ui";
865
+
866
+ export function WikiSidebarLink() {
867
+ const hostNavigation = useHostNavigation();
868
+ return <a {...hostNavigation.linkProps("/wiki")}>Wiki</a>;
869
+ }
870
+ ```
871
+
872
+ `linkProps("/wiki")` resolves against the active company prefix, so in company `PAP` it renders `href="/PAP/wiki"`. Already-prefixed paths such as `/PAP/wiki` are not prefixed again. For button-style commands, call `hostNavigation.navigate("/issues/PAP-123")`.
873
+
874
+ Avoid raw same-origin `href`s or `window.location.assign()` for Paperclip-internal navigation from plugin UI. Those bypass the host router and can reload the whole app. External links should keep normal anchors with `target="_blank"` and `rel="noopener noreferrer"` as appropriate.
875
+
876
+ #### `usePluginStream<T>(channel, options?)`
877
+
878
+ Subscribes to a real-time event stream pushed from the plugin worker via SSE. The worker pushes events using `ctx.streams.emit(channel, event)` and the hook receives them as they arrive. Returns `{ events, lastEvent, connecting, connected, error, close }`.
879
+
880
+ ```tsx
881
+ import { usePluginStream } from "@paperclipai/plugin-sdk/ui";
882
+
883
+ interface ChatToken {
884
+ text: string;
885
+ }
886
+
887
+ export function ChatMessages({ context }: PluginWidgetProps) {
888
+ const { events, connected, close } = usePluginStream<ChatToken>("chat-stream", {
889
+ companyId: context.companyId ?? undefined,
890
+ });
891
+
892
+ return (
893
+ <div>
894
+ {events.map((e, i) => <span key={i}>{e.text}</span>)}
895
+ {connected && <span className="pulse" />}
896
+ <button onClick={close}>Stop</button>
897
+ </div>
898
+ );
899
+ }
900
+ ```
901
+
902
+ The SSE connection targets `GET /api/plugins/:pluginId/bridge/stream/:channel?companyId=...`. The host bridge manages the EventSource lifecycle; `close()` terminates the connection.
903
+
904
+ ### UI authoring note
905
+
906
+ The host provides selected shared UI components through `@paperclipai/plugin-sdk/ui`.
907
+ Plugins can also use normal React components, their own CSS, or small design
908
+ primitives inside the plugin package.
909
+
910
+ Use `copyTextToClipboard` for every plugin copy action. The host selects the
911
+ modern Clipboard API in secure contexts and a compatible fallback in plain-HTTP
912
+ deployments.
913
+
914
+ ```tsx
915
+ import { copyTextToClipboard } from "@paperclipai/plugin-sdk/ui";
916
+
917
+ await copyTextToClipboard("text to copy");
918
+ ```
919
+
920
+ Use the shared components when the plugin needs to look and behave like a native
921
+ Paperclip surface:
922
+
923
+ | Component | Use when |
924
+ |---|---|
925
+ | `MarkdownBlock` | Rendering markdown from plugin or host data |
926
+ | `MarkdownEditor` | Editing markdown with the host editor treatment |
927
+ | `FileTree` | Showing serializable workspace/wiki/import paths |
928
+ | `IssuesList` | Embedding a company-scoped native issue list |
929
+ | `AssigneePicker` | Selecting an agent or board user with the same picker as the new issue pane |
930
+ | `ProjectPicker` | Selecting a project with the same picker as the new issue pane |
931
+ | `ManagedRoutinesList` | Showing plugin-managed routines in settings UI |
932
+
933
+ #### Shared Markdown Components
934
+
935
+ Plugin UI can render markdown and edit markdown using the same host components
936
+ used by Paperclip issue comments and documents:
937
+
938
+ ```tsx
939
+ import { MarkdownBlock, MarkdownEditor } from "@paperclipai/plugin-sdk/ui";
940
+
941
+ export function WikiPageEditor() {
942
+ const [body, setBody] = useState("# Wiki page");
943
+
944
+ return (
945
+ <>
946
+ <MarkdownBlock content={body} />
947
+ <MarkdownEditor value={body} onChange={setBody} bordered />
948
+ </>
949
+ );
950
+ }
951
+ ```
952
+
953
+ `MarkdownBlock` can opt into Obsidian-style wikilinks when a plugin owns the
954
+ target URL shape:
955
+
956
+ ```tsx
957
+ <MarkdownBlock
958
+ content={"See [[wiki/entities/paperclip|Paperclip]]."}
959
+ enableWikiLinks
960
+ wikiLinkRoot="/wiki/page"
961
+ />
962
+ ```
963
+
964
+ #### Shared FileTree
965
+
966
+ Plugin UI can render the host file tree without importing host internals:
967
+
968
+ ```tsx
969
+ import { FileTree, type FileTreeNode } from "@paperclipai/plugin-sdk/ui";
970
+
971
+ const nodes: FileTreeNode[] = [
972
+ { name: "AGENTS.md", path: "AGENTS.md", kind: "file", children: [] },
973
+ {
974
+ name: "wiki",
975
+ path: "wiki",
976
+ kind: "dir",
977
+ children: [
978
+ { name: "index.md", path: "wiki/index.md", kind: "file", children: [] },
979
+ ],
980
+ },
981
+ ];
982
+
983
+ export function WikiFiles() {
984
+ return (
985
+ <FileTree
986
+ nodes={nodes}
987
+ expandedPaths={["wiki"]}
988
+ selectedFile="wiki/index.md"
989
+ onToggleDir={(path) => console.log("toggle", path)}
990
+ onSelectFile={(path) => console.log("select", path)}
991
+ />
992
+ );
993
+ }
994
+ ```
995
+
996
+ #### Shared Assignee and Project Pickers
997
+
998
+ Use `AssigneePicker` and `ProjectPicker` when a plugin needs to create, filter,
999
+ or configure work against Paperclip entities. Both are controlled components and
1000
+ load their options from the host for the provided company.
1001
+
1002
+ ```tsx
1003
+ import { AssigneePicker, ProjectPicker } from "@paperclipai/plugin-sdk/ui";
1004
+
1005
+ export function AssignmentControls({ companyId }: { companyId: string }) {
1006
+ const [assignee, setAssignee] = useState("");
1007
+ const [projectId, setProjectId] = useState("");
1008
+
1009
+ return (
1010
+ <>
1011
+ <AssigneePicker
1012
+ companyId={companyId}
1013
+ value={assignee}
1014
+ onChange={(value, selection) => {
1015
+ setAssignee(value);
1016
+ console.log(selection.assigneeAgentId, selection.assigneeUserId);
1017
+ }}
1018
+ />
1019
+ <ProjectPicker
1020
+ companyId={companyId}
1021
+ value={projectId}
1022
+ onChange={setProjectId}
1023
+ />
1024
+ </>
1025
+ );
1026
+ }
1027
+ ```
1028
+
1029
+ ### Slot component props
1030
+
1031
+ Each slot type receives a typed props object with `context: PluginHostContext`. Import from `@paperclipai/plugin-sdk/ui`.
1032
+
1033
+ | Slot type | Props interface | `context` extras |
1034
+ |-----------|----------------|------------------|
1035
+ | `page` | `PluginPageProps` | — |
1036
+ | `sidebar` | `PluginSidebarProps` | — |
1037
+ | `routeSidebar` | `PluginRouteSidebarProps` | — |
1038
+ | `settingsPage` | `PluginSettingsPageProps` | — |
1039
+ | `dashboardWidget` | `PluginWidgetProps` | — |
1040
+ | `globalToolbarButton` | `PluginGlobalToolbarButtonProps` | — |
1041
+ | `detailTab` | `PluginDetailTabProps` | `entityId: string`, `entityType: string` |
1042
+ | `toolbarButton` | `PluginToolbarButtonProps` | `entityId: string`, `entityType: string` |
1043
+ | `commentAnnotation` | `PluginCommentAnnotationProps` | `entityId: string`, `entityType: "comment"`, `parentEntityId: string`, `projectId`, `companyPrefix` |
1044
+ | `commentContextMenuItem` | `PluginCommentContextMenuItemProps` | `entityId: string`, `entityType: "comment"`, `parentEntityId: string`, `projectId`, `companyPrefix` |
1045
+ | `projectSidebarItem` | `PluginProjectSidebarItemProps` | `entityId: string`, `entityType: "project"` |
1046
+
1047
+ Example detail tab with entity context:
1048
+
1049
+ ```tsx
1050
+ import type { PluginDetailTabProps } from "@paperclipai/plugin-sdk/ui";
1051
+ import { usePluginData } from "@paperclipai/plugin-sdk/ui";
1052
+
1053
+ export function AgentMetricsTab({ context }: PluginDetailTabProps) {
1054
+ const { data, loading } = usePluginData<Record<string, string>>("agent-metrics", {
1055
+ agentId: context.entityId,
1056
+ companyId: context.companyId,
1057
+ });
1058
+
1059
+ if (loading) return <div>Loading…</div>;
1060
+ if (!data) return <p>No metrics available.</p>;
1061
+
1062
+ return (
1063
+ <dl>
1064
+ {Object.entries(data).map(([label, value]) => (
1065
+ <div key={label}>
1066
+ <dt>{label}</dt>
1067
+ <dd>{value}</dd>
1068
+ </div>
1069
+ ))}
1070
+ </dl>
1071
+ );
1072
+ }
1073
+ ```
1074
+
1075
+ ## Launcher surfaces and modals
1076
+
1077
+ V1 does not provide a dedicated `modal` slot. Plugins can either:
1078
+
1079
+ - declare concrete UI mount points in `ui.slots`
1080
+ - declare host-rendered entry points in `ui.launchers`
1081
+
1082
+ Supported launcher placement zones currently mirror the major host surfaces such as `projectSidebarItem`, `globalToolbarButton`, `toolbarButton`, `detailTab`, `settingsPage`, and `contextMenuItem`. Plugins may still open their own local modal from those entry points when needed.
1083
+
1084
+ Declarative launcher example:
1085
+
1086
+ ```json
1087
+ {
1088
+ "ui": {
1089
+ "launchers": [
1090
+ {
1091
+ "id": "sync-project",
1092
+ "displayName": "Sync",
1093
+ "placementZone": "toolbarButton",
1094
+ "entityTypes": ["project"],
1095
+ "action": {
1096
+ "type": "openDrawer",
1097
+ "target": "sync-project"
1098
+ },
1099
+ "render": {
1100
+ "environment": "hostOverlay",
1101
+ "bounds": "wide"
1102
+ }
1103
+ }
1104
+ ]
1105
+ }
1106
+ }
1107
+ ```
1108
+
1109
+ The host returns launcher metadata from `GET /api/plugins/ui-contributions` alongside slot declarations.
1110
+
1111
+ When a launcher opens a host-owned overlay or page, `useHostContext()`,
1112
+ `usePluginData()`, and `usePluginAction()` receive the current
1113
+ `renderEnvironment` through the bridge. Use that to tailor compact modal UI vs.
1114
+ full-page layouts without adding custom route parsing in the plugin.
1115
+
1116
+ ## Project sidebar item
1117
+
1118
+ Plugins can add a link under each project in the sidebar via the `projectSidebarItem` slot. This is the recommended slot-based launcher pattern for project-scoped workflows because it can deep-link into a richer plugin tab. The component is rendered once per project with that project’s id in `context.entityId`. Declare the slot and capability in your manifest:
1119
+
1120
+ ```json
1121
+ {
1122
+ "ui": {
1123
+ "slots": [
1124
+ {
1125
+ "type": "projectSidebarItem",
1126
+ "id": "files",
1127
+ "displayName": "Files",
1128
+ "exportName": "FilesLink",
1129
+ "entityTypes": ["project"]
1130
+ }
1131
+ ]
1132
+ },
1133
+ "capabilities": ["ui.sidebar.register", "ui.detailTab.register"]
1134
+ }
1135
+ ```
1136
+
1137
+ Minimal React component that links to the project’s plugin tab (see project detail tabs in the spec):
1138
+
1139
+ ```tsx
1140
+ import {
1141
+ useHostNavigation,
1142
+ type PluginProjectSidebarItemProps,
1143
+ } from "@paperclipai/plugin-sdk/ui";
1144
+
1145
+ export function FilesLink({ context }: PluginProjectSidebarItemProps) {
1146
+ const hostNavigation = useHostNavigation();
1147
+ const projectId = context.entityId;
1148
+ const projectRef = projectId; // or resolve from host; entityId is project id
1149
+ return (
1150
+ <a {...hostNavigation.linkProps(`/projects/${projectRef}?tab=plugin:your-plugin:files`)}>
1151
+ Files
1152
+ </a>
1153
+ );
1154
+ }
1155
+ ```
1156
+
1157
+ Use optional `order` in the slot to sort among other project sidebar items. See §19.5.1 in the plugin spec and project detail plugin tabs (§19.3) for the full flow.
1158
+
1159
+ ## Toolbar launcher with a local modal
1160
+
1161
+ Two toolbar slot types are available depending on where the button should appear:
1162
+
1163
+ - **`globalToolbarButton`** — renders in the top bar on every page, scoped to the company. No entity context. Use for workspace-wide actions.
1164
+ - **`toolbarButton`** — renders on entity detail pages (project, issue, etc.). Receives `entityId` and `entityType`. Declare `entityTypes` to control which pages the button appears on.
1165
+
1166
+ For short-lived actions, mount the appropriate slot type and open a plugin-owned modal inside the component. Use `useHostContext()` to scope the action to the current company or entity.
1167
+
1168
+ Project-scoped example (appears only on project detail pages):
1169
+
1170
+ ```json
1171
+ {
1172
+ "ui": {
1173
+ "slots": [
1174
+ {
1175
+ "type": "toolbarButton",
1176
+ "id": "sync-toolbar-button",
1177
+ "displayName": "Sync",
1178
+ "exportName": "SyncToolbarButton",
1179
+ "entityTypes": ["project"]
1180
+ }
1181
+ ]
1182
+ },
1183
+ "capabilities": ["ui.action.register"]
1184
+ }
1185
+ ```
1186
+
1187
+ ```tsx
1188
+ import { useState } from "react";
1189
+ import {
1190
+ useHostContext,
1191
+ usePluginAction,
1192
+ } from "@paperclipai/plugin-sdk/ui";
1193
+
1194
+ export function SyncToolbarButton() {
1195
+ const context = useHostContext();
1196
+ const syncProject = usePluginAction("sync-project");
1197
+ const [open, setOpen] = useState(false);
1198
+ const [submitting, setSubmitting] = useState(false);
1199
+ const [errorMessage, setErrorMessage] = useState<string | null>(null);
1200
+
1201
+ async function confirm() {
1202
+ if (!context.projectId) return;
1203
+ setSubmitting(true);
1204
+ setErrorMessage(null);
1205
+ try {
1206
+ await syncProject({ projectId: context.projectId });
1207
+ setOpen(false);
1208
+ } catch (err) {
1209
+ setErrorMessage(err instanceof Error ? err.message : "Sync failed");
1210
+ } finally {
1211
+ setSubmitting(false);
1212
+ }
1213
+ }
1214
+
1215
+ return (
1216
+ <>
1217
+ <button type="button" onClick={() => setOpen(true)}>
1218
+ Sync
1219
+ </button>
1220
+ {open ? (
1221
+ <div
1222
+ role="dialog"
1223
+ aria-modal="true"
1224
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
1225
+ onClick={() => !submitting && setOpen(false)}
1226
+ >
1227
+ <div
1228
+ className="w-full max-w-md rounded-lg bg-background p-4 shadow-xl"
1229
+ onClick={(event) => event.stopPropagation()}
1230
+ >
1231
+ <h2 className="text-base font-semibold">Sync this project?</h2>
1232
+ <p className="mt-2 text-sm text-muted-foreground">
1233
+ Queue a sync for <code>{context.projectId}</code>.
1234
+ </p>
1235
+ {errorMessage ? (
1236
+ <p className="mt-2 text-sm text-destructive">{errorMessage}</p>
1237
+ ) : null}
1238
+ <div className="mt-4 flex justify-end gap-2">
1239
+ <button type="button" onClick={() => setOpen(false)}>
1240
+ Cancel
1241
+ </button>
1242
+ <button type="button" onClick={() => void confirm()} disabled={submitting}>
1243
+ {submitting ? "Running…" : "Run sync"}
1244
+ </button>
1245
+ </div>
1246
+ </div>
1247
+ </div>
1248
+ ) : null}
1249
+ </>
1250
+ );
1251
+ }
1252
+ ```
1253
+
1254
+ Prefer deep-linkable tabs and pages for primary workflows. Reserve plugin-owned modals for confirmations, pickers, and compact editors.
1255
+
1256
+ ## Real-time streaming (`ctx.streams`)
1257
+
1258
+ Plugins can push real-time events from the worker to the UI using server-sent events (SSE). This is useful for streaming LLM tokens, live sync progress, or any push-based data.
1259
+
1260
+ ### Worker side
1261
+
1262
+ In `setup()`, use `ctx.streams` to open a channel, emit events, and close when done:
1263
+
1264
+ ```ts
1265
+ const plugin = definePlugin({
1266
+ async setup(ctx) {
1267
+ ctx.actions.register("chat", async (params) => {
1268
+ const companyId = params.companyId as string;
1269
+ ctx.streams.open("chat-stream", companyId);
1270
+
1271
+ for await (const token of streamFromLLM(params.prompt as string)) {
1272
+ ctx.streams.emit("chat-stream", { text: token });
1273
+ }
1274
+
1275
+ ctx.streams.close("chat-stream");
1276
+ return { ok: true };
1277
+ });
1278
+ },
1279
+ });
1280
+ ```
1281
+
1282
+ **API:**
1283
+
1284
+ | Method | Description |
1285
+ |--------|-------------|
1286
+ | `ctx.streams.open(channel, companyId)` | Open a named stream channel and associate it with a company. Sends a `streams.open` notification to the host. |
1287
+ | `ctx.streams.emit(channel, event)` | Push an event to the channel. The `companyId` is automatically resolved from the prior `open()` call. |
1288
+ | `ctx.streams.close(channel)` | Close the channel and clear the company mapping. Sends a `streams.close` notification. |
1289
+
1290
+ Stream notifications are fire-and-forget JSON-RPC messages (no `id` field). They are sent via `notifyHost()` synchronously during handler execution.
1291
+
1292
+ ### UI side
1293
+
1294
+ Use the `usePluginStream` hook (see [Hooks reference](#usepluginstreamtchannel-options) above) to subscribe to events from the UI.
1295
+
1296
+ ### Host-side architecture
1297
+
1298
+ The host maintains an in-memory `PluginStreamBus` that fans out worker notifications to connected SSE clients:
1299
+
1300
+ 1. Worker emits `streams.emit` notification via stdout
1301
+ 2. Host (`plugin-worker-manager`) receives the notification and publishes to `PluginStreamBus`
1302
+ 3. SSE endpoint (`GET /api/plugins/:pluginId/bridge/stream/:channel?companyId=...`) subscribes to the bus and writes events to the response
1303
+
1304
+ The bus is keyed by `pluginId:channel:companyId`, so multiple UI clients can subscribe to the same stream independently.
1305
+
1306
+ ### Streaming agent responses to the UI
1307
+
1308
+ `ctx.streams` and `ctx.agents.sessions` are complementary. The worker sits between them, relaying agent events to the browser in real time:
1309
+
1310
+ ```
1311
+ UI ──usePluginAction──▶ Worker ──sessions.sendMessage──▶ Agent
1312
+ UI ◀──usePluginStream── Worker ◀──onEvent callback────── Agent
1313
+ ```
1314
+
1315
+ The agent doesn't know about streams — the worker decides what to relay. Encode the agent ID in the channel name to scope streams per agent.
1316
+
1317
+ **Worker:**
1318
+
1319
+ ```ts
1320
+ ctx.actions.register("ask-agent", async (params) => {
1321
+ const { agentId, companyId, prompt } = params as {
1322
+ agentId: string; companyId: string; prompt: string;
1323
+ };
1324
+
1325
+ const channel = `agent:${agentId}`;
1326
+ ctx.streams.open(channel, companyId);
1327
+
1328
+ const session = await ctx.agents.sessions.create(agentId, companyId);
1329
+
1330
+ await ctx.agents.sessions.sendMessage(session.sessionId, companyId, {
1331
+ prompt,
1332
+ onEvent: (event) => {
1333
+ ctx.streams.emit(channel, {
1334
+ type: event.eventType, // "chunk" | "done" | "error"
1335
+ text: event.message ?? "",
1336
+ });
1337
+ },
1338
+ });
1339
+
1340
+ ctx.streams.close(channel);
1341
+ return { sessionId: session.sessionId };
1342
+ });
1343
+ ```
1344
+
1345
+ **UI:**
1346
+
1347
+ ```tsx
1348
+ import { useState } from "react";
1349
+ import { usePluginAction, usePluginStream } from "@paperclipai/plugin-sdk/ui";
1350
+
1351
+ interface AgentEvent {
1352
+ type: "chunk" | "done" | "error";
1353
+ text: string;
1354
+ }
1355
+
1356
+ export function AgentChat({ agentId, companyId }: { agentId: string; companyId: string }) {
1357
+ const askAgent = usePluginAction("ask-agent");
1358
+ const { events, connected, close } = usePluginStream<AgentEvent>(`agent:${agentId}`, { companyId });
1359
+ const [prompt, setPrompt] = useState("");
1360
+
1361
+ async function send() {
1362
+ setPrompt("");
1363
+ await askAgent({ agentId, companyId, prompt });
1364
+ }
1365
+
1366
+ return (
1367
+ <div>
1368
+ <div>{events.filter(e => e.type === "chunk").map((e, i) => <span key={i}>{e.text}</span>)}</div>
1369
+ <input value={prompt} onChange={(e) => setPrompt(e.target.value)} />
1370
+ <button onClick={send}>Send</button>
1371
+ {connected && <button onClick={close}>Stop</button>}
1372
+ </div>
1373
+ );
1374
+ }
1375
+ ```
1376
+
1377
+ ## Agent sessions (two-way chat)
1378
+
1379
+ Plugins can hold multi-turn conversational sessions with agents:
1380
+
1381
+ ```ts
1382
+ // Create a session
1383
+ const session = await ctx.agents.sessions.create(agentId, companyId);
1384
+
1385
+ // Send a message and stream the response
1386
+ await ctx.agents.sessions.sendMessage(session.sessionId, companyId, {
1387
+ prompt: "Help me triage this issue",
1388
+ onEvent: (event) => {
1389
+ if (event.eventType === "chunk") console.log(event.message);
1390
+ if (event.eventType === "done") console.log("Stream complete");
1391
+ },
1392
+ });
1393
+
1394
+ // List active sessions
1395
+ const sessions = await ctx.agents.sessions.list(agentId, companyId);
1396
+
1397
+ // Close when done
1398
+ await ctx.agents.sessions.close(session.sessionId, companyId);
1399
+ ```
1400
+
1401
+ Requires capabilities: `agent.sessions.create`, `agent.sessions.list`, `agent.sessions.send`, `agent.sessions.close`.
1402
+
1403
+ Exported types: `AgentSession`, `AgentSessionEvent`, `AgentSessionSendResult`, `PluginAgentSessionsClient`.
1404
+
1405
+ ## Testing utilities
1406
+
1407
+ ```ts
1408
+ import { createTestHarness } from "@paperclipai/plugin-sdk/testing";
1409
+ import plugin from "../src/worker.js";
1410
+ import manifest from "../src/manifest.js";
1411
+
1412
+ const harness = createTestHarness({ manifest });
1413
+ await plugin.definition.setup(harness.ctx);
1414
+ await harness.emit("issue.created", { issueId: "iss_1" }, { entityId: "iss_1", entityType: "issue" });
1415
+ ```
1416
+
1417
+ ## Bundler presets
1418
+
1419
+ ```ts
1420
+ import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
1421
+
1422
+ const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
1423
+ // presets.esbuild.worker / presets.esbuild.manifest / presets.esbuild.ui
1424
+ // presets.rollup.worker / presets.rollup.manifest / presets.rollup.ui
1425
+ ```
1426
+
1427
+ ## Local dev server (hot-reload events)
1428
+
1429
+ ```bash
1430
+ paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177
1431
+ ```
1432
+
1433
+ Or programmatically:
1434
+
1435
+ ```ts
1436
+ import { startPluginDevServer } from "@paperclipai/plugin-sdk/dev-server";
1437
+ const server = await startPluginDevServer({ rootDir: process.cwd() });
1438
+ ```
1439
+
1440
+ Dev server endpoints:
1441
+ - `GET /__paperclip__/health` returns `{ ok, rootDir, uiDir }`
1442
+ - `GET /__paperclip__/events` streams `reload` SSE events on UI build changes
1443
+
1444
+ ### Persistent application shell contributions
1445
+
1446
+ An `appShellOverlay` slot uses `ui.action.register` and the standard
1447
+ `PluginWidgetProps` context. It survives navigation and unmounts on account or
1448
+ company changes, sign-out and onboarding. Plugins own panel accessibility and
1449
+ request cleanup. See [the distribution and lifecycle contract](../../../doc/plugins/DISTRIBUTION-PLUGINS.md).
1450
+
1451
+ ## Project storage and task workspaces
1452
+
1453
+ A storage provider declares `workspaceProvider: { modes: ["isolated_workspace"],
1454
+ strategies: ["git_worktree"] }`, `workspaces.manage`, and
1455
+ `resourceLifecycle: ["project"]` (with `events.subscribe`). The same plugin must
1456
+ implement `onResourceLifecycle` and `onWorkspaceOperation`. Project lifecycle
1457
+ creates and retains the storage; workspace operations manage task checkouts in
1458
+ that storage. Execution remains a separate environment driver contract.
1459
+
1460
+ `project.executionWorkspacePolicy.storageProviderPluginId` holds a project's storage:
1461
+ an installed plugin's UUID, or `null` or no value for Core/local storage. Core
1462
+ applies the installed company-enabled default once, when it creates the project. A
1463
+ provider claims that default by declaring, for example:
1464
+
1465
+ ```ts
1466
+ workspaceProvider: {
1467
+ modes: ["isolated_workspace", "operator_branch"],
1468
+ strategies: ["git_worktree"],
1469
+ defaultForProjects: { mode: "isolated_workspace", strategy: "git_worktree" },
1470
+ }
1471
+ ```
1472
+
1473
+ The declared defaults must be supported by the provider. Installing a provider
1474
+ does not change existing projects. A Core/local project can move to a provider, and
1475
+ a plugin-backed project stays attached to that plugin: requests to change it fail,
1476
+ and it never falls back to local storage. Core applies missing mode and strategy
1477
+ settings without writing them. Explicit settings remain intact; incompatible
1478
+ settings fail with a configuration error. If more than one enabled provider claims
1479
+ the default, creating a project needs an explicit choice. Core sends a provider
1480
+ project lifecycle events only for projects attached to it, and acknowledges the
1481
+ others on its behalf. No company settings row means enabled, matching the normal
1482
+ plugin contract.
1483
+
1484
+ New and imported tasks leave an unspecified project mode inherited. Provider-owned
1485
+ workspaces retain explicit project and task strategies in shared and operator-branch
1486
+ modes. If neither supplies a strategy, those modes use `project_primary`; an agent's
1487
+ Git strategy remains a fallback only for isolated mode.
1488
+
1489
+ Project responses keep the stored `executionWorkspacePolicy` and expose the
1490
+ separate `workspaceProvider` configuration, including its source, effective policy,
1491
+ provider choices and configuration error. The project configuration UI supports
1492
+ inheritance, explicit plugins and Core/local storage. Conflicts remain readable so
1493
+ operators can resolve them through this flow.
1494
+
1495
+ Core reserves an execution-workspace row and binds the task before calling
1496
+ `onWorkspaceOperation`. Source-free task directories do not prepare project storage. The resolved provider
1497
+ choice, including Core/local, stays fixed through source resolution and preparation.
1498
+ Existing workspaces, including local workspaces, retain their original owner. Changing defaults never migrates, resets or recreates them;
1499
+ normal retirement and cleanup gates still apply on disable/uninstall.
1500
+
1501
+ The hook receives a company, project, source revision, execution-workspace ID,
1502
+ lifecycle generation, deadline, and stable operation ID. Run and agent IDs are
1503
+ optional context. A storage hook must work without an environment lease, a live
1504
+ agent, or a filesystem mount on Core. It must reconcile ambiguous retries before
1505
+ repeating side effects. Use the workspace ID and generation to fence provider
1506
+ operations; the operation ID identifies a retry of the same request.
1507
+ Fresh inspections get a new operation ID so provider result caches cannot reuse
1508
+ an earlier checkout status. Prepare and removal retries retain their IDs.
1509
+
1510
+ - `prepare` creates or restores the checkout. It returns an opaque, durable
1511
+ `WorkspaceProviderBinding`, a branch, and the starting commit. `branchMode:
1512
+ "existing"` must use an existing logical branch and must never reset its history.
1513
+ A provider may materialize a local ref from a confirmed existing remote branch. Retried preparation must keep
1514
+ local work. Providers may reject modes or strategies they do not support.
1515
+ - `inspect` reports tracked, untracked, and ignored/local-only changes, the
1516
+ current commit, merge state, and whether remote storage can recover it. Use
1517
+ `null` when a remote recovery or merge check is unknown.
1518
+ - `remove` checks the expected commit again and confirms removal. Busy, failed,
1519
+ unsafe, and uncertain removal must throw. Core requires a clean checkout and
1520
+ affirmative remote recovery or merge evidence before requesting removal.
1521
+
1522
+ References contain the installed plugin ID, project/source/workspace IDs, source
1523
+ revision, and opaque provider coordinates. They must not contain secrets. Core
1524
+ stores no local `cwd` for managed rows. `/workspaces/<id>` is a logical path in
1525
+ Core's existing run metadata; Core must not use it for filesystem access.
1526
+
1527
+ For the initial execution integration, select a task-capable environment driver
1528
+ from the same plugin. Core validates declared modes and strategies before it
1529
+ reserves a workspace. Core pins the binding on the environment lease and supplies
1530
+ it as `PluginEnvironmentTaskParams.workspace`. The execution hook resolves the
1531
+ provider reference to guest mounts and the actual working directory. Core rejects
1532
+ an execution driver from a different plugin. Native execution also requires the
1533
+ plugin Runner task bridge; Core refuses to fall back to a host Runner when that
1534
+ bridge is unavailable. This does not require merging the
1535
+ storage and execution interfaces.
1536
+
1537
+ Core's existing archive, reopen, and terminal cleanup fences also cover provider
1538
+ workspaces. The plugin must prevent project storage retirement while its task
1539
+ workspaces still contain local data. Repository source and storage owner changes
1540
+ are blocked while live managed workspaces depend on them. An authorized storage
1541
+ owner or source edit retires closed workspaces whose provider removal is confirmed;
1542
+ retired records cannot reopen. Inspection reconciles a pending restoration with
1543
+ its recorded request, advances its generation, and keeps the Core row closed.
1544
+ Cleanup must then inspect that generation afresh; it cannot reuse an earlier
1545
+ removal receipt. Direct removal refuses unresolved restoration intent.
1546
+ Core commits storage intent and recovery results with cleanup notifications so
1547
+ incremental terminal-workspace sweeps revisit changed records.
1548
+ Pending deletion is replayed before inspection, including after a lost removal
1549
+ result. File browsing and
1550
+ other Core-host filesystem operations are unavailable for managed storage.
1551
+
1552
+ Use `createWorkspaceProviderHarness` from `@paperclipai/plugin-sdk/testing` to
1553
+ validate hook inputs and outputs without allocating an execution environment.
1554
+
1555
+
1556
+ ### Private project instance credentials
1557
+
1558
+ Project lifecycle plugins can opt into `projects.instance-secrets` alongside
1559
+ `events.subscribe` and `resourceLifecycle: ["project"]`. Automatic project
1560
+ callbacks receive `event.instanceSecrets`; return an `instanceSecrets` patch
1561
+ with an acknowledged result. Core stores the patch in the existing native
1562
+ instance-secret system and acknowledges the event in one transaction. A null
1563
+ value removes a key. Retry and deferred results do not store patches.
1564
+
1565
+ Each company/project/installed-plugin owns its credentials. Up to 16 lowercase
1566
+ snake_case keys may change per result; nonempty string values are limited to
1567
+ 128 KiB each. Core rejects replies if configuration, project sources, lifecycle
1568
+ state, or secret versions changed during the callback. A duplicate response to
1569
+ an acknowledged event cannot overwrite credentials. Deleted projects allow
1570
+ removal only; their secrets are also deleted by the native owner foreign key.
1571
+
1572
+ Trusted worker code can use
1573
+ `ctx.projects.getInstanceSecrets(projectId, companyId)` during a company-scoped
1574
+ invocation to read its credentials without an external service call. Archived
1575
+ or missing projects cannot be read this way. Values never appear in ordinary
1576
+ lifecycle inbox listings or the company secret catalog. Do not expose values
1577
+ through plugin entities, state, data handlers, UI, or logs. Agent instance
1578
+ secrets retain their existing lifecycle contract. Back up the tenant's existing
1579
+ local secrets master key together with its database.
1580
+
1581
+ ### Project Git credentials
1582
+
1583
+ Trusted workspace providers can declare `projects.git-credentials` and call
1584
+ `ctx.projects.resolveGitCredential(projectId, workspaceId, companyId)` from the
1585
+ matching host-issued project lifecycle or workspace operation. Other invocations
1586
+ cannot obtain credentials through this method. The workspace must be a current
1587
+ repository in that project and company; plugins cannot supply arbitrary URLs.
1588
+
1589
+ Background work uses a project writer's explicit consent to their own personal,
1590
+ company-installed GitHub Connector grant. It does not retain task context. Core
1591
+ checks the exact grant and its owner's active company membership on every use.
1592
+ Foreground preparation uses the active run's identity and trust policy instead.
1593
+ Public repositories return null and require no connection. Private repositories
1594
+ without authorization wait before provisioning. Repository visibility comes from
1595
+ the Connector catalog and retained project selections; legacy URL-only sources
1596
+ use anonymous discovery when visibility is unknown. A revoked or invalid private
1597
+ repository authorization fails closed. There is no fallback to another grant.
1598
+ Project consent follows the connection's current repository access, including
1599
+ sources added later, rather than a separate project repository approval list.
1600
+ The consenting user must retain project read access, and background credential
1601
+ export requires the project's existing trust policy to allow standard execution.
1602
+ Archived projects keep credential access only for host-issued workspace inspection
1603
+ and removal with existing consent; provisioning remains blocked.
1604
+
1605
+ The return value is transient raw credential material with the Connector's
1606
+ existing permissions. This capability is for trusted execution infrastructure,
1607
+ not agent-facing tools or UI. Never expose or persist it. See
1608
+ [GitHub identity](../../../doc/execution-github-identity.md#project-authorization-for-background-repository-work).
1609
+
1610
+ ## Login on an existing computer
1611
+
1612
+ A driver can use the existing login PTY hooks for a login on a saved agent's
1613
+ computer. Core sends `purpose: "login"`, a closed `loginCommandKey`, a stable
1614
+ `creationOperationId`, and an absolute `requestedExpiresAt` to lease acquisition.
1615
+ Release and destroy must retire only that login allocation and preserve the
1616
+ computer. Omitted purpose retains the existing execution behavior.
1617
+
1618
+ Core supplies `expiresAt` to the PTY open and an `inputId` for each input write.
1619
+ Input, stop, and close retain the opening company context so provider callbacks
1620
+ can use company-scoped host services during cleanup.
1621
+ A provider that retries delivery must retain the input identity and bytes, and
1622
+ reject reuse of the identity with different input. A failed input call ends the
1623
+ Core login; Core does not silently replay an unconfirmed write.
1624
+
1625
+ Providers can implement `onLoginPtyReadCredential` to export the fixed Codex
1626
+ credential artifact for a bound login lease. The result is
1627
+ `{ kind: "codex-auth-json", authJson }`; the request accepts no path or command.
1628
+ The worker advertises this optional method only when the hook exists. The host
1629
+ must check that method before using this read path, enforce a size limit, and
1630
+ keep credential bytes out of logs and public session responses. Existing sandbox
1631
+ providers can continue to use their descriptor-bound credential read.