@jmfederico/pi-web 1.202608.2 → 1.202609.1

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 (233) hide show
  1. package/README.md +3 -3
  2. package/dist/.plugins-ready +1 -0
  3. package/dist/cli.js +5 -2
  4. package/dist/cli.js.map +1 -1
  5. package/dist/client/apple-touch-icon-dev.png +0 -0
  6. package/dist/client/assets/index-AroYaCLx.js +4130 -0
  7. package/dist/client/assets/vendor-editor-core-YWog6mAR.js +10 -0
  8. package/dist/client/assets/vendor-editor-languages-DOCw3vc9.js +28 -0
  9. package/dist/client/favicon-dev.svg +8 -0
  10. package/dist/client/index.html +5 -5
  11. package/dist/client/pwa-icon-dev-192.png +0 -0
  12. package/dist/client/pwa-icon-dev-512.png +0 -0
  13. package/dist/config.js +20 -0
  14. package/dist/config.js.map +1 -1
  15. package/dist/docker/piWebDockerCommandPlan.js +9 -1
  16. package/dist/docker/piWebDockerCommandPlan.js.map +1 -1
  17. package/dist/nativeServices/installedServiceDefinitions.js +25 -19
  18. package/dist/nativeServices/installedServiceDefinitions.js.map +1 -1
  19. package/dist/nativeServices/serviceAction.js +38 -26
  20. package/dist/nativeServices/serviceAction.js.map +1 -1
  21. package/dist/nativeServices/servicePlan.js +3 -3
  22. package/dist/nativeServices/servicePlan.js.map +1 -1
  23. package/dist/pi-packages/captains-log/README.md +11 -0
  24. package/dist/pi-packages/captains-log/dist/browser/channelProtocol.js +29 -0
  25. package/dist/pi-packages/captains-log/dist/browser/index.js +144 -0
  26. package/dist/pi-packages/captains-log/dist/browser/markdown.js +67 -0
  27. package/dist/pi-packages/captains-log/dist/browser/panel.js +105 -0
  28. package/dist/pi-packages/captains-log/dist/browser/protocol.js +26 -0
  29. package/dist/pi-packages/captains-log/dist/companion.js +126 -0
  30. package/dist/pi-packages/captains-log/dist/roundtrip.js +62 -0
  31. package/dist/pi-packages/captains-log/dist/server.js +210 -0
  32. package/dist/pi-packages/captains-log/dist/store.js +75 -0
  33. package/dist/pi-packages/captains-log/docs/usage.md +30 -0
  34. package/dist/pi-packages/captains-log/package.json +35 -0
  35. package/dist/pi-packages/captains-log/tsconfig.json +21 -0
  36. package/dist/pi-packages/captains-log/vite.config.mjs +28 -0
  37. package/dist/pi-packages/relays/package.json +1 -1
  38. package/dist/pi-packages/relays/pi-web-plugin.js +1 -1
  39. package/dist/pi-packages/relays/prompts/relay-worktree.md +13 -142
  40. package/dist/pi-packages/relays/prompts/relay.md +25 -132
  41. package/dist/pi-packages/relays/relayDiscovery.js +2 -2
  42. package/dist/pi-packages/relays/relaysPanelElement.js +1 -1
  43. package/dist/pi-packages/relays/skills/relay/SKILL.md +59 -88
  44. package/dist/pi-packages/relays/skills/relay-runner/SKILL.md +253 -0
  45. package/dist/pi-web-plugins/files/browser/assets/files-icon-DZObYhxb.svg +3 -0
  46. package/dist/pi-web-plugins/files/browser/pi-web-plugin.js +439 -0
  47. package/dist/pi-web-plugins/files/package.json +15 -0
  48. package/dist/pi-web-plugins/git/browser/git-panel.js +54 -24
  49. package/dist/pi-web-plugins/git/browser/pi-web-plugin.js +1 -1
  50. package/dist/pi-web-plugins/git/git-backend.js +5 -5
  51. package/dist/pi-web-plugins/git/server-plugin.js +5 -3
  52. package/dist/pi-web-plugins/info/pi-web-plugin.js +1 -1
  53. package/dist/pi-web-plugins/mermaid/browser/mermaid-engine.js +3590 -0
  54. package/dist/pi-web-plugins/mermaid/browser/pi-web-plugin.js +6 -0
  55. package/dist/pi-web-plugins/mermaid/package.json +13 -0
  56. package/dist/pi-web-plugins/terminal/browser/pi-web-plugin.js +210 -0
  57. package/dist/pi-web-plugins/terminal/package.json +16 -0
  58. package/dist/pi-web-plugins/terminal/server-plugin.js +365 -0
  59. package/dist/{server/terminals → pi-web-plugins/terminal}/terminalService.js +162 -65
  60. package/dist/pi-web-plugins/updates/pi-web-plugin.js +45 -35
  61. package/dist/pi-web-plugins/workspace-tasks/pi-web-plugin.js +1 -1
  62. package/dist/piWebVersionReport.js +12 -4
  63. package/dist/piWebVersionReport.js.map +1 -1
  64. package/dist/plugin-api.d.ts +222 -23
  65. package/dist/plugin-api.js +1 -0
  66. package/dist/pluginRecoveryCli.js +3 -2
  67. package/dist/pluginRecoveryCli.js.map +1 -1
  68. package/dist/server/activity/workspaceActivityService.js.map +1 -1
  69. package/dist/server/app.js +33 -12
  70. package/dist/server/app.js.map +1 -1
  71. package/dist/server/configRoutes.js +6 -1
  72. package/dist/server/configRoutes.js.map +1 -1
  73. package/dist/server/deploymentIdentity.js +67 -0
  74. package/dist/server/deploymentIdentity.js.map +1 -0
  75. package/dist/server/deploymentIdentityRoutes.js +22 -0
  76. package/dist/server/deploymentIdentityRoutes.js.map +1 -0
  77. package/dist/server/knownAutoInstallPiPackages.js +1 -1
  78. package/dist/server/knownAutoInstallPiPackages.js.map +1 -1
  79. package/dist/server/knownPiPackages.js +12 -0
  80. package/dist/server/knownPiPackages.js.map +1 -0
  81. package/dist/server/machines/machineClient.js +2 -2
  82. package/dist/server/machines/machineClient.js.map +1 -1
  83. package/dist/server/machines/machinePluginProxyRoutes.js +53 -11
  84. package/dist/server/machines/machinePluginProxyRoutes.js.map +1 -1
  85. package/dist/server/machines/machineProxyRoutes.js +70 -7
  86. package/dist/server/machines/machineProxyRoutes.js.map +1 -1
  87. package/dist/server/notices/serverNoticeRoutes.js +34 -0
  88. package/dist/server/notices/serverNoticeRoutes.js.map +1 -0
  89. package/dist/server/notices/serverNoticeService.js +26 -0
  90. package/dist/server/notices/serverNoticeService.js.map +1 -0
  91. package/dist/server/notices/serverNoticeStore.js +119 -0
  92. package/dist/server/notices/serverNoticeStore.js.map +1 -0
  93. package/dist/server/piPackageService.js +5 -5
  94. package/dist/server/piPackageService.js.map +1 -1
  95. package/dist/server/piWebPluginCatalog.js +46 -12
  96. package/dist/server/piWebPluginCatalog.js.map +1 -1
  97. package/dist/server/piWebPluginLifecycle.js +26 -3
  98. package/dist/server/piWebPluginLifecycle.js.map +1 -1
  99. package/dist/server/piWebPluginService.js +37 -2
  100. package/dist/server/piWebPluginService.js.map +1 -1
  101. package/dist/server/piWebStatus.js +1 -1
  102. package/dist/server/piWebStatus.js.map +1 -1
  103. package/dist/server/pluginCallbackDrain.js +35 -0
  104. package/dist/server/pluginCallbackDrain.js.map +1 -0
  105. package/dist/server/plugins/pluginBackendChannelProxyAdmission.js +84 -0
  106. package/dist/server/plugins/pluginBackendChannelProxyAdmission.js.map +1 -0
  107. package/dist/server/plugins/pluginBackendChannelProxyCoordinator.js +234 -0
  108. package/dist/server/plugins/pluginBackendChannelProxyCoordinator.js.map +1 -0
  109. package/dist/server/plugins/pluginBackendChannelProxyRoutes.js +52 -0
  110. package/dist/server/plugins/pluginBackendChannelProxyRoutes.js.map +1 -0
  111. package/dist/server/plugins/pluginBackendProxyRoutes.js +38 -31
  112. package/dist/server/plugins/pluginBackendProxyRoutes.js.map +1 -1
  113. package/dist/server/plugins/pluginBackendRegistry.js +740 -0
  114. package/dist/server/plugins/pluginBackendRegistry.js.map +1 -0
  115. package/dist/server/plugins/serverPluginPiSessionEventsCapability.js +34 -0
  116. package/dist/server/plugins/serverPluginPiSessionEventsCapability.js.map +1 -0
  117. package/dist/server/plugins/serverPluginPiSessionsCapability.js +185 -0
  118. package/dist/server/plugins/serverPluginPiSessionsCapability.js.map +1 -0
  119. package/dist/server/plugins/serverPluginRuntime.js +1028 -107
  120. package/dist/server/plugins/serverPluginRuntime.js.map +1 -1
  121. package/dist/server/plugins/serverPluginWorkspacesCapability.js +114 -0
  122. package/dist/server/plugins/serverPluginWorkspacesCapability.js.map +1 -0
  123. package/dist/server/sessiond/pluginBackendChannelRoutes.js +393 -0
  124. package/dist/server/sessiond/pluginBackendChannelRoutes.js.map +1 -0
  125. package/dist/server/sessiond/pluginBackendRoutes.js +10 -7
  126. package/dist/server/sessiond/pluginBackendRoutes.js.map +1 -1
  127. package/dist/server/sessiond/sessionDaemonShutdown.js +9 -2
  128. package/dist/server/sessiond/sessionDaemonShutdown.js.map +1 -1
  129. package/dist/server/sessiond/sessionProxyRoutes.js +2 -0
  130. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
  131. package/dist/server/sessiond/sessionServiceDependencies.js +1 -0
  132. package/dist/server/sessiond/sessionServiceDependencies.js.map +1 -1
  133. package/dist/server/sessiond.js +82 -21
  134. package/dist/server/sessiond.js.map +1 -1
  135. package/dist/server/sessions/attachmentService.js +1 -5
  136. package/dist/server/sessions/attachmentService.js.map +1 -1
  137. package/dist/server/sessions/builtinCommands.js +2 -2
  138. package/dist/server/sessions/builtinCommands.js.map +1 -1
  139. package/dist/server/sessions/clientSessionPreview.js +14 -0
  140. package/dist/server/sessions/clientSessionPreview.js.map +1 -0
  141. package/dist/server/sessions/piSessionEventConnections.js +65 -0
  142. package/dist/server/sessions/piSessionEventConnections.js.map +1 -0
  143. package/dist/server/sessions/piSessionManagerGateway.js +171 -1
  144. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -1
  145. package/dist/server/sessions/piSessionService.js +442 -90
  146. package/dist/server/sessions/piSessionService.js.map +1 -1
  147. package/dist/server/sessions/sessionActivityMarker.js +105 -0
  148. package/dist/server/sessions/sessionActivityMarker.js.map +1 -0
  149. package/dist/server/sessions/sessionEnvironmentFacts.js +5 -4
  150. package/dist/server/sessions/sessionEnvironmentFacts.js.map +1 -1
  151. package/dist/server/sessions/sessionNameGenerator.js +3 -2
  152. package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
  153. package/dist/server/sessions/sessionRoutes.js +18 -0
  154. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  155. package/dist/server/sessions/spawnSessionTool.js +1 -1
  156. package/dist/server/sessions/spawnSessionTool.js.map +1 -1
  157. package/dist/server/sessions/spawnSubsessionTool.js +1 -1
  158. package/dist/server/sessions/spawnSubsessionTool.js.map +1 -1
  159. package/dist/server/sessions/transcriptBranchCache.js +81 -0
  160. package/dist/server/sessions/transcriptBranchCache.js.map +1 -0
  161. package/dist/server/sessions/transcriptMessages.js +54 -0
  162. package/dist/server/sessions/transcriptMessages.js.map +1 -0
  163. package/dist/server/terminals/requiredTerminalService.js +103 -0
  164. package/dist/server/terminals/requiredTerminalService.js.map +1 -0
  165. package/dist/server/webSocketBridge.js +339 -0
  166. package/dist/server/webSocketBridge.js.map +1 -1
  167. package/dist/server/workspaces/projectPiWebConfig.js +6 -1
  168. package/dist/server/workspaces/projectPiWebConfig.js.map +1 -1
  169. package/dist/server/workspaces/sessionDaemonWorkspaceCatalog.js +23 -3
  170. package/dist/server/workspaces/sessionDaemonWorkspaceCatalog.js.map +1 -1
  171. package/dist/server/workspaces/workspaceCatalog.js +3 -1
  172. package/dist/server/workspaces/workspaceCatalog.js.map +1 -1
  173. package/dist/server/workspaces/workspaceProviderRegistry.js +64 -149
  174. package/dist/server/workspaces/workspaceProviderRegistry.js.map +1 -1
  175. package/dist/server/workspaces/workspaceRemovalService.js +38 -5
  176. package/dist/server/workspaces/workspaceRemovalService.js.map +1 -1
  177. package/dist/server-plugin-api.d.ts +216 -22
  178. package/dist/server-plugin-api.js +319 -2
  179. package/dist/server-plugin-api.js.map +1 -1
  180. package/dist/serverPluginRecovery.js +4 -0
  181. package/dist/serverPluginRecovery.js.map +1 -1
  182. package/dist/sessiond/sessionDaemonClient.js +3 -3
  183. package/dist/sessiond/sessionDaemonClient.js.map +1 -1
  184. package/dist/shared/apiTypes.js +1 -1
  185. package/dist/shared/apiTypes.js.map +1 -1
  186. package/dist/shared/federatedRoutes.js +47 -17
  187. package/dist/shared/federatedRoutes.js.map +1 -1
  188. package/dist/shared/machinePluginIds.js +28 -7
  189. package/dist/shared/machinePluginIds.js.map +1 -1
  190. package/dist/shared/pluginApiTypes.d.ts +21 -1
  191. package/dist/shared/pluginApiTypes.js +0 -1
  192. package/dist/shared/pluginBackendProtocol.js +163 -2
  193. package/dist/shared/pluginBackendProtocol.js.map +1 -1
  194. package/dist/shared/pluginIds.js +8 -1
  195. package/dist/shared/pluginIds.js.map +1 -1
  196. package/dist/shared/requiredTerminalPlugin.js +6 -0
  197. package/dist/shared/requiredTerminalPlugin.js.map +1 -0
  198. package/dist/shared/serverNoticeContract.js +88 -0
  199. package/dist/shared/serverNoticeContract.js.map +1 -0
  200. package/dist/shared/sessionDefaults.js +41 -0
  201. package/dist/shared/sessionDefaults.js.map +1 -0
  202. package/docs/config.md +77 -37
  203. package/docs/plugins.md +146 -1213
  204. package/examples/session-bridge-plugin/README.md +20 -0
  205. package/examples/session-bridge-plugin/docs/usage.md +54 -0
  206. package/examples/session-bridge-plugin/package.json +26 -0
  207. package/examples/session-bridge-plugin/src/browser/index.ts +84 -0
  208. package/examples/session-bridge-plugin/src/browser/protocol.ts +24 -0
  209. package/examples/session-bridge-plugin/src/companion.ts +65 -0
  210. package/examples/session-bridge-plugin/src/reviewRun.ts +39 -0
  211. package/examples/session-bridge-plugin/src/server.ts +85 -0
  212. package/examples/session-bridge-plugin/src/store.ts +57 -0
  213. package/examples/session-bridge-plugin/tsconfig.json +21 -0
  214. package/examples/workspace-provider-plugin/README.md +4 -4
  215. package/examples/workspace-provider-plugin/package.json +1 -1
  216. package/examples/workspace-provider-plugin/src/browser/index.ts +9 -9
  217. package/examples/workspace-provider-plugin/src/server.ts +15 -11
  218. package/package.json +17 -11
  219. package/dist/client/assets/CodeViewer-BMWwxG7q.js +0 -4
  220. package/dist/client/assets/TerminalPanel-CacQDIYn.js +0 -187
  221. package/dist/client/assets/index-DUW2xnoV.js +0 -4279
  222. package/dist/client/assets/vendor-editor-core-CXO8gGab.js +0 -12
  223. package/dist/client/assets/vendor-editor-languages-CpW4sJsX.js +0 -46
  224. package/dist/client/assets/vendor-editor-legacy-CYBnW6ZU.js +0 -1
  225. package/dist/client/assets/vendor-terminal-BrP-ENHg.css +0 -1
  226. package/dist/client/assets/vendor-terminal-D8k4UKM2.js +0 -35
  227. package/dist/server/terminalProxyRoutes.js +0 -141
  228. package/dist/server/terminalProxyRoutes.js.map +0 -1
  229. package/dist/server/terminals/terminalRoutes.js +0 -155
  230. package/dist/server/terminals/terminalRoutes.js.map +0 -1
  231. package/dist/server/terminals/terminalService.js.map +0 -1
  232. package/dist/server/terminals/terminalSize.js +0 -17
  233. package/dist/server/terminals/terminalSize.js.map +0 -1
package/docs/plugins.md CHANGED
@@ -1,1315 +1,248 @@
1
- # PI WEB plugin API
1
+ # Plugins and Pi packages
2
2
 
3
- PI WEB plugins are trusted packages that can extend the browser UI, provide workspace semantics in the session daemon, or pair both entries. They are intended for personal, team, and project-local customization, and simple enough for an LLM to create or modify directly.
3
+ Customize PI WEB with workspace tools, useful shortcuts, and integrations. You can install an existing package or ask an agent to build one for your workflow. You do not need to modify PI WEB itself.
4
4
 
5
- Plugins can currently:
5
+ This guide explains what is possible and what to expect. For implementation, use the [public contracts and examples](#agent-development), rather than treating this page as a second API reference.
6
6
 
7
- - add action-palette commands;
8
- - add workspace tools/panels next to Files and Terminal;
9
- - add compact workspace-label items in the workspace list, panel header, and status bar;
10
- - call browser APIs and documented PI WEB plugin context helpers;
11
- - read workspace files and start workspace terminal commands through documented helpers;
12
- - serve browser-public files from an explicitly declared `browserRoot`;
13
- - contribute one server-side workspace provider, with optional JSON backend requests and workspace-removal planning.
7
+ ## What can be built
14
8
 
15
- Browser entries run in the PI WEB page through browser plugin API v2. Declared server entries run in the session daemon through the separate server-plugin API v1. Plugins do not get raw Fastify access, arbitrary routes, concrete core services, a generic event bus, Pi model-provider registration, or a general server-hook API. Neither entry is sandboxed.
16
-
17
- ## Pi packages, Pi extensions, and PI WEB plugins
18
-
19
- **Pi packages** are distribution bundles managed by Pi (`pi install`, `pi remove`, `pi update`). A Pi package can provide Pi extensions, skills, prompt templates, themes, context/system prompt files, and/or PI WEB plugins. Many Pi packages do not include a PI WEB plugin.
20
-
21
- **Pi extensions** are runtime modules loaded by the session daemon. They can register Pi tools, hooks, commands, and model providers. They are not PI WEB plugins and use a different API and lifecycle.
22
-
23
- **PI WEB plugins** are packages discovered from bundled, local, dev, and installed Pi-package sources. A plugin can declare a browser `module`, a sessiond `serverModule`, or both. A server entry can participate only in the documented PI WEB plugin lifecycle and workspace-provider contract; it cannot register Pi model providers or arbitrary hooks.
24
-
25
- Pi loads ordinary Pi resources from installed Pi packages and from its user and project resource locations. PI WEB plugin discovery loads only the browser and server entries declared in `piWeb.plugins`; enabling or disabling a PI WEB plugin does not add or remove the package's Pi extensions, skills, prompt templates, themes, or context/system prompt files.
26
-
27
- Use **Settings → Pi packages** to view configured Pi packages or install/remove/update a package. Enter only the package source, such as `npm:@scope/package`, a git/URL source, or a local path. PI WEB uses Pi's default package location, equivalent to `pi install <source>`, and does not ask for an install location.
28
-
29
- When machine federation is enabled, **Settings → Pi packages** targets the currently selected machine. The panel labels whether changes will run on the local/gateway machine or on a selected remote PI WEB machine.
30
-
31
- Use **Settings → PI WEB plugins** to edit the desired enablement of discovered plugins on the selected machine. Browser-only changes apply after a page reload. A server-backed change also requires a session-daemon restart before its paired browser module can load against the new active revision. If an older or unavailable remote PI WEB server does not support the versioned plugin lifecycle, PI WEB reports plugin settings as unsupported or unavailable instead of silently falling back to the gateway.
32
-
33
- After installing, removing, or updating a Pi package, type `/reload` in each idle PI WEB session on the target machine to refresh ordinary Pi resources such as extensions, skills, prompt templates, themes, and context/system prompt files. For PI WEB plugins, manually restart the target session daemon when the package has a server entry, then reload the browser page. A provider-registering Pi extension follows a separate daemon-start policy; see [Pi extension provider baseline](https://pi-web.dev/config#pi-extension-provider-baseline).
34
-
35
- ## Pi extension dialogs in PI WEB
9
+ | Goal | Plugin feature |
10
+ | --- | --- |
11
+ | Show project health, service links, or environment information | Workspace labels and panels |
12
+ | Add a dashboard, file viewer, or project-specific tool | Workspace panels, file helpers, and browser UI |
13
+ | Make common actions easier to find | Action-palette commands and shortcuts |
14
+ | Run builds, tests, or development servers | Workspace terminal commands |
15
+ | Customize the appearance | Themes and light/dark theme pairs |
16
+ | Preview diagrams or other text formats in chat and Files | Browser content renderers |
17
+ | Read or change workspace files | File listing, reading, writing, moving, deleting, and uploads |
18
+ | Show live backend results | Requests or streaming channels between a plugin's browser and server entries |
19
+ | Save plugin-owned results or preferences | A persistent server-side plugin directory |
20
+ | Start a Pi conversation or collaborate with a Pi extension | Host session capabilities and session-local messaging |
21
+ | Replace Git's workspace discovery with another system | A workspace provider |
36
22
 
37
- Pi extensions running under PI WEB's session daemon can ask the user questions with `ctx.ui.confirm()`, `ctx.ui.select()`, and `ctx.ui.input()`. PI WEB reports `ctx.hasUI === true`, and for these three dialog methods that is true in fact: the call renders a dialog card inline in the session transcript and the returned Promise resolves with the user's actual answer — a boolean for confirm, the chosen option for select, the typed text for input.
23
+ Panels can support deep links and browser history, and refresh when workspace files change or agent work finishes. File and terminal helpers target the panel's machine and workspace, including remote machines.
38
24
 
39
- - **Works from hooks, without the prompt queue.** Answers travel over a dedicated session-daemon channel, so a dialog opened inside an in-flight `tool_call` hook parks safely — the agent loop waits for the hook and the run continues with the answer. Consent-gating a tool from a `tool_call` hook is a supported pattern.
40
- - **`session_start` dialogs are reachable.** A dialog opened from a `session_start` hook is answerable while the session is still starting, both when creating a session and when opening an existing one; startup completes once the dialog settles.
41
- - **Survives browser reloads; first answer wins.** Reloading the browser re-renders open dialogs from the session status. With several tabs on the same session, the first answer settles the dialog and the other tabs re-render the settled card.
42
- - **Settled cards stay until dismissed.** An answered or closed dialog leaves its outcome card in the transcript so the user can see what became of it — answers travel to the extension alone, so the card is the only record of the exchange. The card is browser-local: only a browser that saw the dialog open renders it, and switching sessions or reloading drops it.
43
- - **Timeouts.** The extension's own `timeout` option applies, and the daemon adds an unattended-dialog safety valve, `extensionDialogsTimeoutMs` (default 5 minutes, `0` waits forever — see [Extension dialogs](https://pi-web.dev/config#extension-dialogs)). The effective deadline is the sooner of the two. A dialog that closes without an answer resolves with its kind's cancel value: `false` for confirm, `undefined` for select and input.
44
- - **Abort and runtime replacement.** Aborting the current run settles a dialog opened during that run immediately, at abort-request time, with its cancel value. Replacing the session runtime (`/reload`, session disposal) settles any still-open dialog the same way; hooks on the new runtime open fresh dialogs. The extension's own `AbortSignal` is honored: aborting it dismisses the dialog and resolves with the cancel value.
45
- - **Other UI surfaces are still no-ops.** `ExtensionUIContext` methods beyond the three dialogs (widgets, status, editor, `custom`) remain unimplemented under PI WEB even though `hasUI` is `true`; do not rely on `hasUI` alone to detect them.
25
+ For example, ask an agent to build “a panel that runs our checks and shows their results,” “a badge linking to this workspace's preview deployment,” or “a review tool that starts a conversation and saves its findings.”
46
26
 
47
- One browser-local caveat: reloading the browser while a new session is still being created loses the browser-local pending-start row, so the dialog card disappears from view. The daemon-side dialog still settles at its deadline and the session appears in the sidebar once creation completes.
27
+ ## Pi packages, extensions, and plugins
48
28
 
49
- ## Trust model
29
+ These are related, but serve different purposes:
50
30
 
51
- Treat every plugin package as trusted code:
31
+ - **Pi packages** are installable bundles. They can contain extensions, skills, prompt templates, themes, and PI WEB plugins.
32
+ - **Pi extensions** customize the agent: tools, commands, hooks, model providers, and session behavior.
33
+ - **PI WEB plugins** customize the web application and its workspace integrations.
52
34
 
53
- - browser entries can call browser APIs, read workspace files, start terminal commands through helpers, and render arbitrary UI;
54
- - server entries execute in-process inside sessiond with the PI WEB service user's filesystem, environment, and process permissions, and they share sessiond's event loop;
55
- - a CPU-bound, blocking, or deadlocked callback can stall sessions, terminals, and health endpoints; abort/deadline signals bound only cooperative asynchronous code and cannot preempt code that ignores them;
56
- - ordinary import, activation, start, health, and stop failures are attributed and quarantined where the host can catch them, but this is a stability boundary rather than a security boundary;
57
- - plugins should not be installed from untrusted sources.
35
+ One package can contain all three kinds of customization. Installing a package and enabling its PI WEB plugin are separate decisions. Disabling a PI WEB plugin does not remove the package's Pi extensions, skills, or prompts.
58
36
 
59
- PI WEB's `/api/...` HTTP and WebSocket endpoints are internal implementation details. Browser code should use documented context helpers, including `context.backend.request()` for a paired server entry. Server code should use only `@jmfederico/pi-web/server-plugin-api`. Private routes, runtime objects, and source-internal imports are experimental and may change or disappear.
37
+ Use a Pi extension for agent behavior and a PI WEB plugin for web UI. When a feature needs both, ship them together and let them communicate through the hosted session connection.
60
38
 
61
- ## Workspace providers and replacement ownership
39
+ ## How plugins work
62
40
 
63
- Sessiond is the single authority for project workspace discovery and spawned-session target validation. One active plugin exclusively owns a project's workspace semantics:
41
+ A plugin package declares a browser entry, a server entry, or both:
64
42
 
65
- 1. Healthy or degraded primary providers probe first.
66
- 2. If exactly one primary returns `"claim"`, it owns the project.
67
- 3. If no primary claims, fallback providers probe. Bundled Git is a fallback provider.
68
- 4. Multiple claimants in the winning tier produce a visible conflict; PI WEB does not select by plugin id or import order.
69
- 5. If no provider claims, PI WEB exposes the project folder as the kernel workspace. If a winner claims and then fails to list, PI WEB reports degraded state instead of silently switching owners.
43
+ - **Browser entries** add actions, panels, labels, themes, and content renderers. They use host helpers for workspace files, terminals, and prompt editing.
44
+ - **Server entries** run in the session daemon. They can serve their browser entry, store plugin data, use host capabilities, or provide workspaces.
45
+ - **Package peers** connect a plugin's browser and server entries. The host handles the selected machine and workspace; a plugin does not need to own that workspace to serve it.
46
+ - **Capabilities** let a plugin declare the host or plugin functionality it requires. Dependencies must be available at the requested version before the plugin starts.
70
47
 
71
- PI WEB ships only the bundled Git production provider. Replacement integrations, including Jujutsu providers, are owned and distributed by third parties. An installed and enabled primary provider can claim its projects and suppress fallback Git without any PI WEB core changes; this documentation does not promise or ship a reference replacement.
48
+ Plugins declare contributions in `activate()`, initialize dependency-backed work in `start()`, and release resources in `dispose()`. Long-lived work follows the plugin's `lifetimeSignal`. Simple browser plugins only need to return their contributions.
72
49
 
73
- ## What to ask AI to build
50
+ ### Opening workspace files from chat
74
51
 
75
- Humans should not need to hand-code plugins. Give an AI agent a concrete UI goal and ask it to create or modify a local plugin.
52
+ Chat Markdown links to relative files (including `./file`) or absolute paths inside the session workspace open in the bundled Files panel. The link retains a download URL for modifier/new-tab clicks and when no panel accepts it. File access still uses server-side workspace containment checks.
76
53
 
77
- Good plugin requests:
54
+ A workspace panel can opt in with `fileOpenQuery(context, path)`. This synchronous hook receives its contribution-scoped context and a decoded workspace-relative path; return a navigation query such as `{ file: path }`, or `undefined` to decline. Keep the hook free of side effects: the host opens the first accepting visible, enabled panel for the selected machine, ordered by panel `order` then title, and applies its namespaced query through normal panel navigation. The panel reads the selection from `context.navigation.query`; no Files-plugin dependency is required.
78
55
 
79
- - "Show a workspace badge with the dev server URL from `.env`."
80
- - "Add a workspace panel with links to logs, dashboards, and local services for this repo."
81
- - "Add an action-palette command that starts a standard code-review prompt."
82
- - "Show whether the current workspace is a git worktree, main checkout, staging env, or feature branch."
83
- - "Add a compact status badge based on a project health file or command output saved in the repo."
56
+ ### Panel and tab navigation
84
57
 
85
- Copy-paste prompt for creating a plugin:
58
+ The URL's `view` selects a responsive panel: `navigation`, `chat`, or `workspace`. The independent `tool` parameter selects a workspace tab by contribution ID. Opening a workspace tool sets `view=workspace` and `tool` to its ID; switching to chat keeps the selected tool. Contribution IDs are not accepted in `view`. Browser plugins use `selectMainView("workspace")` to show the workspace panel without changing its selected tab, or `selectWorkspaceTool(panelId)` to select and show a particular tool.
86
59
 
87
- ```text
88
- Build a PI WEB plugin for this project.
89
- Goal: <describe the UI behavior>.
90
- Before coding, read the PI WEB plugin docs:
91
- https://pi-web.dev/plugins
92
- Full API reference:
93
- https://pi-web.dev/plugins.md
94
- Create it as a local plugin under ~/.pi-web/plugins/<plugin-id>.
95
- Use the appropriate extension points from the docs.
96
- Validate by checking /pi-web-plugins/manifest.json and explain how to reload/debug it.
97
- Do not modify PI WEB itself.
98
- ```
60
+ Invalid values remain in the URL rather than triggering a redirect. An invalid `view` shows a warning and displays navigation on mobile; on two-column layouts, navigation remains alongside a valid requested tool or, otherwise, chat. Desktop keeps its normal columns. A valid workspace view with an invalid tool shows an unavailable-tab message inside the workspace panel, without selecting another tab or adding a duplicate warning. Omitted parameters use defaults and are not errors.
99
61
 
100
- Copy-paste prompt for modifying a plugin:
62
+ ### Content previews in chat and Files
101
63
 
102
- ```text
103
- Improve the PI WEB plugin at <path>.
104
- Before coding, read the PI WEB plugin docs:
105
- https://pi-web.dev/plugins
106
- Full API reference:
107
- https://pi-web.dev/plugins.md
108
- Keep the browser entry on API v2 and any server entry on API v1.
109
- After editing, check the manifest endpoint and browser-console failure cases.
110
- ```
111
-
112
- ## Canonical example: bundled Info plugin
64
+ Browser plugins can contribute `contentRenderers` with an `id`, `languages` (Markdown fence labels), `fileExtensions` (without a dot), and a synchronous `render(input)` returning a Lit template. Selectors are case-insensitive and match by language OR file extension. `renderMode?: 'manual' | 'automatic'` defaults to `manual`: raw source and a **Render** button appear without calling the renderer. This is the initial policy, not a restriction on explicit user intent; unrelated prose updates retain activation. Authors may explicitly opt into `automatic` and are responsible for efficient activation and asynchronous work. The same renderer serves chat fences, Files Markdown preview fences, and standalone text files. Selection follows the effective machine's plugin availability and portable/machine-specific precedence. When several renderers match, a chooser lets you compare alternatives for each diagram or file, with only the selected renderer mounted. Choices default to alphabetical source plugin ID order (not remote runtime prefixes), then local contribution ID, using locale-independent, case-sensitive code-unit comparison. The chooser labels identify the plugin and contribution. Chat remembers explicit renderer and Raw/Preview choices per code block in this browser tab for 15 minutes from the last explicit choice. Viewing or remounting never extends that deadline; expiry applies on revisit, without removing a visible preview. Entries are bounded to the 128 most recently chosen blocks and scoped by machine, session, message/entry, part, block and exact source. Changed source or an unavailable selected renderer invalidates the choice and restores the deterministic default and its policy. Automatic rendering alone creates no remembered override. DOM is not cached; previews render again on remount. Reloading or closing the tab clears this memory. Files Markdown previews do not use chat intent memory. For standalone files, the plugin policy supplies the initial default only when no browser-local Raw/Preview preference exists. Saved Preview authorizes all file rendering, including manual renderers inside Markdown fences; saved Raw suppresses previews. Per-block Raw and renderer choices remain available within Markdown Preview. URL mode still takes precedence. Defaults are not automatically saved as explicit choices. Built-in file previews retain their existing defaults. There is no plugin order field or sorting UI.
113
65
 
114
- PI WEB ships a real bundled `info` plugin. Use it as the reference example because it is intentionally small while still exercising all core contribution types: an action, a workspace label, and a workspace panel.
66
+ Chat keeps **Raw**, **Preview**, and **Copy source** available in a toolbar on each supported diagram block. Standalone Files previews use the file header's **Raw**/**Preview** controls beside **Download** and follow the saved file-view mode; diagrams within Markdown files retain per-block controls. Incomplete fences stay raw and copyable; closed fences preview before the message finishes. Appending prose does not restart an unchanged completed block. Preview failure shows the source instead. Unknown formats retain normal code rendering.
115
67
 
116
- Bundled PI WEB plugins are developed as TypeScript in the repository, but their `package.json` metadata still points at built JavaScript because plugins are loaded by the browser as JS ES modules. `npm run dev:web` watches and rebuilds bundled plugin TS into `dist/pi-web-plugins/` during development, and `npm run build` emits the JS before packaging a release.
68
+ `input` contains `text`, an abort `signal`, and `fail(error)`. Render synchronously, own async work in a component, clean up on disconnect or abort, and report asynchronous failures with `fail`. Obsolete failures are ignored. Renderers receive untrusted text: escape or sanitize output, avoid executing source, and do not relax the surrounding Markdown policy. The host skips plugin rendering for truncated input and blocks over 100,000 UTF-16 code units; Files also retains its inline byte-size limit. Ordinary chat Markdown and Files Markdown retain their distinct sanitizers.
117
69
 
118
- Source files:
70
+ A browser consumer such as Files declares the host capability `{ pluginId: "pi-web", id: "content-rendering", version: 1, parse }` in `requires`, then resolves it in `start`. The exported `ContentRenderingCapability` type describes `listRenderers(request)`, `renderText(request)`, and `renderMarkdown({ machineId, text, truncated?, toSafeHtml, allowManualPreview? })`. `listRenderers` returns sorted eligible `{ id, label, renderMode }` choices without invoking renderers. `renderText` accepts an optional `rendererId` only with `controls: "external"`; absent or unavailable IDs select the first match. Embedded controls own their selection and ignore externally supplied IDs. Use `controls: "external"` when the consumer owns the renderer chooser, mode switching, and raw-source access (as Files does in its header beside Download); otherwise controls remain embedded. Consumers own their user-intent policy and may pass `allowManualPreview: true` to `renderText` or `renderMarkdown` to authorize manual previews (for example, an explicit Render click or Files’ saved or URL Preview preference). For Markdown this applies to eligible fences without overriding per-block Raw choices. Omitting it or passing false retains renderer defaults, including automatic previews. Chat never passes this override. External Raw controls must remove the preview. The public capability stores no remembered intent. Chat’s bounded per-block memory is private host policy, not a plugin option. Markdown requests have their own shape without file-path or language selectors; languages come from fences. Creating a `renderText` template does not invoke a renderer. Markdown diagrams each own an independent chooser. Switching renderers cancels the previous preview and clears its failure state. `renderMarkdown` requires the consumer's trusted sanitizer; it is not permission to insert untrusted HTML. See the [Files consumer](https://github.com/jmfederico/pi-web/blob/main/pi-web-plugins/files/pi-web-plugin.ts) and [Mermaid contribution](https://github.com/jmfederico/pi-web/tree/main/pi-web-plugins/mermaid) for complete implementations.
119
71
 
120
- ```text
121
- pi-web-plugins/info/package.json
122
- pi-web-plugins/info/pi-web-plugin.ts
123
- pi-web-plugins/info/infoInternals.ts
124
- ```
72
+ ### Conversations and companion extensions
125
73
 
126
- `pi-web-plugin.ts` is the plugin skeleton: metadata plus contribution definitions. `infoInternals.ts` holds everything the bundled panel and action actually render, so you can ignore or replace it when copying the plugin.
74
+ A server plugin can create a normal, visible Pi conversation, with or without an initial prompt. A companion Pi extension can exchange messages with the backend and use Pi's own APIs to do agent work.
127
75
 
128
- Built module:
76
+ **The conversation belongs to the user once it is published.** Finishing the initial task, closing the browser, or disposing the initiating plugin does not discard it or stop later user work. Users can continue it like any other conversation.
129
77
 
130
- ```text
131
- dist/pi-web-plugins/info/pi-web-plugin.js
132
- ```
78
+ A messaging connection targets a session already hosted on that machine; it does not open saved sessions automatically. Sending a message is not proof that a companion is installed or that its work succeeded. Integrations must report their own progress and results. Connections have no startup-message replay, and closing a connection does not stop agent work.
133
79
 
134
- Package metadata:
80
+ ### Storage and background work
135
81
 
136
- ```json
137
- {
138
- "name": "@pi-web/info-plugin",
139
- "private": true,
140
- "piWeb": {
141
- "plugins": [
142
- { "id": "info", "browserRoot": ".", "module": "pi-web-plugin.js" }
143
- ]
144
- }
145
- }
146
- ```
82
+ Server plugins receive a persistent `dataDirectory`, separate from installed package code. The directory is shared across that plugin's projects on the machine. Plugins own their data format, migrations, and cleanup; there is no host storage API to learn.
147
83
 
148
- Module shape excerpt:
149
-
150
- ```js
151
- export default {
152
- apiVersion: 2,
153
- name: "Info Plugin",
154
- activate: ({ html, svg }) => ({
155
- contributions: {
156
- actions: [/* action definitions */],
157
- workspaceLabels: [/* compact label definitions */],
158
- workspacePanels: [/* panel definitions using html, optional icons using svg */],
159
- },
160
- }),
161
- };
162
- ```
84
+ Requests and channels are bounded and can fail, time out, or disconnect. A successful send does not guarantee delivery, and the host does not automatically retry uncertain work. Long-running jobs should maintain their own state and let the UI reconnect without accidentally starting the job twice.
163
85
 
164
- When copying the Info plugin, choose a new plugin id so it does not conflict with the bundled `info` plugin.
86
+ ### Workspace providers
165
87
 
166
- The Info panel doubles as an always-available PI WEB status view: it renders the host-provided `context.state.piWebStatus` (PI WEB and Pi versions, installation, release state, machine, and workspace details) without issuing its own requests, and its action copies a plain-text diagnostics summary suitable for bug reports.
88
+ A provider decides which workspaces belong to a project. A primary provider can replace bundled Git for projects it claims. Git is the fallback; without a claimant, the project folder remains usable as a workspace.
167
89
 
168
- PI WEB also ships an `updates` plugin that demonstrates dynamic `visible` and `badge` callbacks for tabs that only appear when the host has status messages or needs extra install visibility.
90
+ Conflicting claims produce a visible error. A provider that claims a project and then fails does not silently hand ownership to another provider. Providers can also offer workspace removal, which runs as a visible terminal operation.
169
91
 
170
- ## Canonical dual-entry provider: bundled Git
92
+ Workspace discovery must be available before host session services start. If a package needs both a provider and session-backed features, use two plugin entries in the same package. There is no need to split the distribution into separate packages.
171
93
 
172
- The bundled `git` plugin is the production example for a paired browser module and workspace-provider server module. Both entries use the same public contracts available to an installed plugin:
94
+ ## Install and manage
173
95
 
174
- ```text
175
- pi-web-plugins/git/package.json
176
- pi-web-plugins/git/browser/pi-web-plugin.ts
177
- pi-web-plugins/git/server-plugin.ts
178
- ```
96
+ Use **Settings → Pi packages** to install, update, or remove a package. Enter its npm, git/URL, or local package source. Use **Settings → PI WEB plugins** to enable or disable its web integration and see whether it is active or needs a restart.
179
97
 
180
- Its built `.js` server entry is a Node ES module, so its package declares `"type": "module"`. Do the same for an installed provider whose `serverModule` ends in `.js`, or emit `.mjs`; do not rely on Node's typeless-module reparsing.
98
+ | Change | What to do next |
99
+ | --- | --- |
100
+ | Install or edit a browser-only plugin | Reload the browser page |
101
+ | Install, update, configure, enable, or disable a server-backed plugin | Restart the target session daemon, then reload the browser |
102
+ | Change ordinary Pi resources such as extensions, skills, or prompts | Run `/reload` in each idle session |
103
+ | Change an extension that registers model providers | Follow the separate [provider restart guidance](https://pi-web.dev/config#pi-extension-provider-baseline) |
181
104
 
182
- Its TypeScript entries import declarations only from the published package subpaths:
105
+ **Restarting the session daemon may interrupt active sessions and terminals.** Inspect active work first and restart from outside the sessions it hosts. For the native systemd user install:
183
106
 
184
- ```ts
185
- import type { PiWebPlugin } from "@jmfederico/pi-web/plugin-api";
186
- import type { PiWebServerPlugin, WorkspaceProvider } from "@jmfederico/pi-web/server-plugin-api";
107
+ ```sh
108
+ systemctl --user restart pi-web-sessiond
187
109
  ```
188
110
 
189
- Git declares `machineSpecific: true`, contributes a fallback workspace provider, and implements its status/diff backend and removal plan through the public provider callbacks. It receives no raw routes or private PI WEB services. Use it to understand the demonstrated contract, not as a template for Git-specific fields: replacement providers define their own private data, public metadata, backend operations, and removal wording.
111
+ A browser reload, web/API restart, or Pi's `/reload` does not activate server-plugin changes. Until the daemon restarts, Settings can show different desired and active states. A paired browser entry is withheld when it no longer matches the active server entry, rather than running incompatible code.
190
112
 
191
- ## Copyable standalone workspace-provider example
113
+ Most plugins are enabled by default. Packages can opt out, and Settings can override the default. Plugin settings live in the normal [PI WEB configuration](https://pi-web.dev/config), not inside the package's installed files.
192
114
 
193
- The repository and published npm package include [`examples/workspace-provider-plugin/`](https://github.com/jmfederico/pi-web/tree/main/examples/workspace-provider-plugin), a small standalone package you can copy without PI WEB source imports. It includes package metadata, a strict NodeNext TypeScript configuration, browser and server source, and build/install instructions.
115
+ ### Local development
194
116
 
195
- The example uses browser API v2 and server API v1. Its browser entry compares `workspace.provider.pluginId` with the stable source `pluginId`, uses `runtimePluginId` only to open its qualified panel, displays non-secret `publicMetadata`, and calls the backend owned by the selected workspace. Its server provider conservatively claims only projects containing `.pi-web/example-workspace-provider`. The explicit `browserRoot: "dist/browser"` keeps `dist/server.js`, source, package metadata, and dependencies outside browser asset routes.
117
+ An agent can develop a package anywhere and symlink it into the local plugin directory:
196
118
 
197
- Copy the example from a checkout or from `node_modules/@jmfederico/pi-web/examples/workspace-provider-plugin`, then follow its README. It deliberately does not advertise removal; use the removal contract below when adding that capability.
198
-
199
- ## Local plugin usage
200
-
201
- This works with the production native-service install. PI WEB discovers packages from `~/.pi-web/plugins/<plugin-package>/`; if `PI_WEB_DATA_DIR` is set, use `$PI_WEB_DATA_DIR/plugins` instead. No PI WEB rebuild is required.
202
-
203
- Symlink a plugin folder into PI WEB's local plugin directory:
204
-
205
- ```bash
119
+ ```sh
206
120
  mkdir -p ~/.pi-web/plugins
207
- ln -s /path/to/plugin-folder ~/.pi-web/plugins/plugin-id
208
- ```
209
-
210
- For a browser-only package, reload the PI WEB tab after installing or editing it. PI WEB uses a package-content revision in the module URL; hard reload if an already-open page still holds old JavaScript. For a package with `serverModule`, restart sessiond to activate the startup snapshot, then reload the browser. Editing files alone never hot-reloads or unloads server code.
211
-
212
- ## Remote machine plugins
213
-
214
- When [machine federation](https://pi-web.dev/machines) is enabled, PI WEB loads the selected remote machine's compatible browser plugins through the gateway and runs its server entries in that remote machine's session daemon. Contributions and helpers are machine-scoped:
215
-
216
- - actions, workspace panels, and workspace labels appear only for the applicable selected machine;
217
- - file and terminal helpers run against that machine;
218
- - `context.backend.request()` is routed through the gateway to the current workspace owner on that machine;
219
- - a server-backed browser module is published only when its package source, scope, settings fingerprint, browser revision, and backend revision match the active sessiond snapshot and the backend is not unhealthy;
220
- - if gateway and remote packages share an original id, `machineSpecific` controls whether the portable gateway copy is reused or the selected machine's own copy is required;
221
- - remote theme contributions are ignored for now because themes are app-wide.
222
-
223
- The remote manifest and backend bridge use a versioned lifecycle contract. A future/unsupported lifecycle version, a missing backend route, or a mismatched frontend/backend revision produces an explicit compatibility error; PI WEB does not silently run an unpaired server-backed UI.
224
-
225
- Plugin/provider compatibility is intentionally all-or-nothing during a mixed-version fleet rollout. A newer gateway rejects an older target's whole remote plugin manifest when the target lacks the current lifecycle contract, so even that target's browser-only plugin contributions and Git panel are unavailable. In the other upgrade order, an older gateway still calls the legacy core Git routes removed by an updated target, so remote Git status/diff requests return `404`. Upgrade the gateway and target together, restart their updated web/API processes and the target session daemon, then reload the gateway tab. Other machine features remain subject to their own capability negotiation.
226
-
227
- Remote desired enablement is stored in the remote machine's PI WEB config. Select that machine in **Settings → PI WEB plugins** to edit it, or open the machine directly/edit its config. Browser-only changes need a page reload. Server-backed changes need a restart of that remote session daemon followed by a page reload.
228
-
229
- Plugin package metadata may set `machineSpecific: true` when the plugin's meaning is tied to the selected PI WEB machine:
230
-
231
- - Omitted or `false`: valid for browser-only plugins; use the gateway copy when the same id is present remotely.
232
- - `true`: the gateway copy appears only for the local machine, and a selected remote machine uses only its own copy. Dual browser/server entries are always machine-specific; omitting the field defaults them to `true`, while explicitly setting `false` is invalid.
233
-
234
- For portable plugin assets, prefer URLs relative to the plugin module:
235
-
236
- ```js
237
- const url = new URL("./asset.json", import.meta.url);
238
- ```
239
-
240
- In browser API v2, activation `pluginId` is always the stable package/source id, locally and through federation. Compare it directly with `workspace.provider.pluginId` for ownership. `runtimePluginId` is the separately named host-unique id for qualified contribution references such as `${runtimePluginId}:workspace.panel`; a remote host may machine-scope it.
241
-
242
- Do not construct absolute plugin asset routes from either identity. Module-relative URLs keep the host-selected runtime scope and deployment base automatically; hard-coded `/pi-web-plugins/...` paths can point at the wrong machine or break nested deployments.
243
-
244
- ## Manage PI WEB plugins
245
-
246
- Open **Settings → PI WEB plugins** to compare desired package/config state with the active sessiond startup snapshot on the selected machine. The list includes bundled, local, dev, and Pi-package-supplied plugins, disabled discovered entries, and entries known only to the still-active snapshot. It reports browser-only, active, failed, incompatible, disabled, not-active, unknown, conflict, stale-revision, health, safe-mode, and restart-required states. Settings and diagnostics expose fingerprints and revisions, not plugin setting values.
247
-
248
- Plugin enablement is separate from package installation. Use **Settings → Pi packages** to install, remove, or update a Pi package. The PI WEB plugin panel writes the selected machine's top-level `plugins` config key. It remains possible to edit desired config while sessiond is unavailable, although active state cannot then be verified.
249
-
250
- ```json
251
- {
252
- "plugins": {
253
- "git": {
254
- "enabled": true,
255
- "settings": {}
256
- },
257
- "info": {
258
- "enabled": false
259
- }
260
- }
261
- }
262
- ```
263
-
264
- Plugins are enabled by default. `plugins.<id>.enabled: false` removes a browser-only entry on the next page load and prevents a server entry from loading on the next sessiond start. The optional `settings` object must be JSON-compatible and is captured for a server entry only at sessiond startup.
265
-
266
- ### Desired versus active state
267
-
268
- Sessiond resolves one immutable enabled server-plugin snapshot at startup and remains the workspace authority for its lifetime. Saving config or replacing package files changes **desired** state only. The existing backend can remain active until sessiond restarts; conversely, its paired browser module is withheld when active and desired revisions no longer match. A web/API restart or browser reload does not change sessiond's active provider registry.
269
-
270
- Use this sequence:
271
-
272
- 1. Install or update the package on the target machine.
273
- 2. Set the desired plugin enablement/settings.
274
- 3. For a browser-only plugin, reload the browser tab.
275
- 4. For a server-backed plugin, manually restart sessiond, wait for it to become available, then reload the browser tab.
276
-
277
- > **Manual session-daemon restart:** for the native systemd user service, run `systemctl --user restart pi-web-sessiond` (the unit is `pi-web-sessiond.service`). Restarting sessiond may interrupt active sessions and runtime ownership. Web/UI autoreload, restarting only the web/API service, browser reload, and Pi's `/reload` command do not activate server-plugin changes.
278
-
279
- ### Offline disable and safe start
280
-
281
- Recovery commands edit global PI WEB config without contacting sessiond, discovering packages, or importing plugin code. Run them on the affected target machine. Add `--config /path/to/config.json` when its services use a non-default `PI_WEB_CONFIG`.
282
-
283
- ```bash
284
- pi-web plugins disable <plugin-id> --restart
285
- pi-web plugins safe-start show
286
- pi-web plugins safe-start set bundled-only --restart
287
- pi-web plugins safe-start set none --restart
288
- pi-web plugins safe-start clear --restart
121
+ ln -s /path/to/plugin-folder ~/.pi-web/plugins/my-plugin
289
122
  ```
290
123
 
291
- - `disable` sets that plugin's desired `enabled` value to `false` while preserving unrelated config.
292
- - `bundled-only` persists safe start and filters discovery before external local or Pi-package server modules are considered.
293
- - `none` persists the emergency level and imports no server plugins; the kernel folder workspace remains available.
294
- - `clear` returns the next startup to ordinary configured discovery.
295
- - `--restart` requests an automatic restart only when PI WEB recognizes a safe installed-service action. Otherwise the command prints manual guidance.
296
-
297
- An unsupported `serverPlugins.safeStart` shape or value in otherwise valid JSON fails closed as effective `none`: sessiond imports no server plugins and reports a diagnostic. Use `safe-start show`, then `set` or `clear`, to repair it offline. Recovery config is written before an automatic restart is attempted; if that service-manager command fails, restart sessiond manually.
298
-
299
- Ordinary plugin failures are normally quarantined, but safe start provides a recovery path for code that blocks or terminates sessiond before normal containment can help. Any restart can interrupt active sessions/runtime ownership; inspect active work before using `--restart` or running the manual service command.
300
-
301
- ## Built-in plugins
302
-
303
- PI WEB ships core, discoverable plugins in the main `@jmfederico/pi-web` npm package. No separate `pi install` step is required. After updating PI WEB, manually restart sessiond so bundled server entries use the installed revision, then reload the browser tab. Browser-only bundled entries need only the tab reload.
304
-
305
- Built-in plugins can be managed from **Settings → PI WEB plugins** or with the top-level `plugins` config key.
306
-
307
- ### Git
124
+ If `PI_WEB_DATA_DIR` is set, use `$PI_WEB_DATA_DIR/plugins` instead. No PI WEB rebuild is required. The package must contain its built JavaScript; PI WEB does not compile arbitrary installed plugin source.
308
125
 
309
- **Plugin id:** `git`
310
- **What it does:** claims Git projects as a fallback workspace provider, discovers worktrees, supplies provider-owned removal plans, and adds the Git status/diff workspace panel through its paired backend.
126
+ ## Remote machines
311
127
 
312
- Git is enabled by default and is the only production workspace provider bundled with PI WEB. An enabled primary third-party provider can claim a project before Git. Disabling `git` and restarting sessiond leaves the kernel project-folder workspace available; reload the browser afterward so Git contributions disappear. The generic Files, Terminal, and Session features continue to work in that folder workspace.
128
+ Plugin installation and settings target the machine selected in Settings. A remote plugin's server code runs on that remote machine; its browser UI appears through the gateway.
313
129
 
314
- ### Updates
130
+ File, terminal, and peer helpers keep operations on the selected machine. Plugins tied to a particular machine use that machine's own installation. Portable browser-only plugins can reuse a gateway copy; themes remain app-wide and remote theme contributions are ignored.
315
131
 
316
- **Plugin id:** `updates`
317
- **What it does:** adds a conditional **Updates** workspace tab with PI WEB update, restart, and installed-service guidance, plus a **Check for PI WEB Updates** action for the selected machine.
132
+ Keep gateways and targets compatible. During this plugin API transition, upgrade them together, restart the updated web/API processes and affected session daemons, then reload the browser. Mixed versions can make remote plugins and Git unavailable; PI WEB does not silently substitute a gateway backend.
318
133
 
319
- While a browser tab is connected, PI WEB refreshes the selected machine's status every 15 minutes. npm release lookups are cached on that machine for six hours, so the automatic refresh normally contacts npm at most once in that window. Run **Check for PI WEB Updates** from the action palette to bypass both caches and check immediately. Operator settings that skip remote version checks, such as `PI_WEB_OFFLINE`, are still respected.
134
+ ## Included tools and optional packages
320
135
 
321
- Updates is enabled by default. It declares `machineSpecific: true` so the gateway Updates tab and action only appear for the local machine; while a remote machine is selected, that remote machine's Updates plugin is used if available. To hide it, disable `updates` in **Settings → PI WEB plugins** or set:
322
-
323
- ```json
324
- {
325
- "plugins": {
326
- "updates": { "enabled": false }
327
- }
328
- }
329
- ```
136
+ - **Terminal** supplies terminals and command runs. It is required in normal operation; disable it only through emergency safe start.
137
+ - **Files** supplies file browsing, previews, and uploads. Disabling its panel does not remove other plugins' file helpers.
138
+ - **Git** discovers Git workspaces and provides status/diff. Disabling it leaves the project-folder workspace available unless another provider takes over.
139
+ - **Mermaid** uses the default manual mode: choose **Render** to preview `mermaid` fences and `.mmd`/`.mermaid` text files. Its bundled engine runs locally in an opaque-origin sandbox with network access blocked; no diagram service receives your source. Interactive links and external resources are intentionally unavailable. Disable Mermaid in plugin Settings to keep plain code rendering. Only a browser reload is needed after changing this browser-only plugin.
140
+ - **Info** displays PI WEB status and copyable diagnostics.
141
+ - **Updates** shows update/restart guidance when relevant and offers a manual update check.
142
+ - **Workspace Tasks** turns project commands into runnable buttons.
330
143
 
331
144
  ### Workspace Tasks
332
145
 
333
- **Plugin id:** `workspace-tasks`
334
- **Config file:** `.pi-web/tasks.json`
335
- **What it does:** adds a **Tasks** workspace tab for running configured shell commands in dedicated PI WEB terminals.
336
-
337
- Workspace Tasks is enabled by default. To hide it, disable `workspace-tasks` in **Settings → PI WEB plugins** or set:
338
-
339
- ```json
340
- {
341
- "plugins": {
342
- "workspace-tasks": { "enabled": false }
343
- }
344
- }
345
- ```
346
-
347
- Configure workspace tasks in `.pi-web/tasks.json`:
146
+ Create `.pi-web/tasks.json` in a project:
348
147
 
349
148
  ```json
350
149
  {
351
150
  "version": 1,
352
151
  "tasks": [
353
- {
354
- "id": "app.start",
355
- "title": "Start app",
356
- "group": "Development",
357
- "description": "Start the local development server.",
358
- "command": "npm run dev"
359
- },
360
- {
361
- "id": "db.reset",
362
- "title": "Reset DB",
363
- "group": "Database",
364
- "command": "go -C klingit-go run ./cli db reset",
365
- "confirm": true
366
- }
152
+ { "id": "app.start", "title": "Start app", "command": "npm run dev" },
153
+ { "id": "db.reset", "title": "Reset database", "command": "npm run db:reset", "confirm": true }
367
154
  ]
368
155
  }
369
156
  ```
370
157
 
371
- Open a workspace, choose the **Tasks** tab, and click **Run** next to a task. Commands run in the workspace root because PI WEB creates the terminal for that workspace.
372
-
373
- Task fields:
374
-
375
- - `version`: must be `1`.
376
- - `tasks`: array of task definitions.
377
- - `id`: stable task id, matching `^[a-z][a-z0-9.-]*$`.
378
- - `title`: button label.
379
- - `command`: literal shell command sent to the terminal.
380
- - `description`: optional explanatory text.
381
- - `group`: optional group heading.
382
- - `confirm`: optional boolean. When true, the browser asks before dispatching the command.
383
-
384
- Review task configs before running them, especially in shared projects. Workspace Tasks runs trusted shell commands from your repositories.
158
+ Open the **Tasks** tab to run a command in a workspace terminal. Tasks can also have a `description`. Review commands before running them, especially in shared repositories. Disabling the plugin hides the tab without changing the project file.
385
159
 
386
160
  ### Relays
387
161
 
388
- **Plugin id:** `relays`
389
- **What it does:** the `@jmfederico/pi-relay` Pi package supplies the generic Relay workflow through the `/relay` and `/relay-worktree` prompt templates and the `relay` skill. Its browser-only `relays` PI WEB plugin adds a read-only **Relays** workspace tab for browsing the workspace's relays, plus an **Open Workspace Relays** action for the selected workspace that opens the same tab.
390
-
391
- A relay is a directory of markdown notes under `.pi-web/relays/<name>/` in the workspace root — the convention used by the Relay method for chaining agent sessions. The tab lists each relay's documents with `status.md`, `charter.md`, and `log.md` first (in that order), followed by any other files alphabetically, and opens `status.md` by default. Markdown documents render as sanitized HTML; other files render as preformatted text, and binary files have no preview. Truncated documents show a notice, and **Refresh** re-scans the workspace and reloads the open document.
392
-
393
- Documents in subfolders are listed too. Folders appear as chips in the document strip, and expanding one inserts its files inline right after it — accordion-style, so expanding a folder collapses its siblings on the same level. An expanded folder wraps its chip and documents in a group bubble, so nested entries stay visually contained. Collapsing the folder that holds the open document keeps the selection and highlights the folder instead. Relay trees deeper than five levels, larger than 200 documents, or with more than 50 folders are listed partially, with a notice.
394
-
395
- With several relays, a picker pre-selects the most recently modified one; a single relay opens directly. A workspace without `.pi-web/relays/` shows an empty state explaining the convention. The tab never creates, edits, or deletes relay files.
396
-
397
- Relay ships as a standalone Pi package: its source lives at `pi-packages/relays/` and its built copy ships inside `@jmfederico/pi-web` at `dist/pi-packages/relays/`, alongside (but outside) the bundled plugins in `pi-web-plugins/`/`dist/pi-web-plugins/`. PI WEB does not discover it from those plugin directories. Installing `@jmfederico/pi-relay` for the active Pi agent profile lets Pi load its two prompt templates and skill and lets PI WEB discover its browser plugin, just as it would for any other installed Pi package (see [Discovery and packaging](#discovery-and-packaging) and [Pi packages shipped alongside bundled plugins](#pi-packages-shipped-alongside-bundled-plugins)). After installing or removing the package, use `/reload` in each idle session to refresh Pi's resources and reload the browser page to refresh the plugin catalog.
398
-
399
- Once the package is installed, `plugins.relays.enabled` controls only the Relays browser panel and action. Disabling it and reloading the page hides those PI WEB contributions without removing `/relay`, `/relay-worktree`, or the `relay` skill; re-enabling it restores the browser contributions without changing Pi's resources. Because the plugin is browser-only, changing this setting does not require a session-daemon restart.
400
-
401
- PI WEB keeps the default setup zero-extra-steps: sessiond installs `@jmfederico/pi-relay` automatically for the active agent profile at startup if it is not already configured for that profile. Removing it from **Settings → Pi packages** removes the Pi resources and browser plugin and is remembered per profile (see [Pi packages shipped alongside bundled plugins](#pi-packages-shipped-alongside-bundled-plugins)), so a manual removal is not silently reinstalled later. A user who changes their mind can reinstall it again with one click from the same Settings screen, with no path to type.
402
-
403
- ## Discovery and packaging
404
-
405
- The web/API catalog and sessiond startup catalog use the same package sources. The browser manifest includes only compatible entries that declare `module`; sessiond considers enabled entries that declare `serverModule`:
406
-
407
- 1. Bundled plugins in the PI WEB package:
408
-
409
- ```text
410
- pi-web-plugins/<plugin-package>/
411
- ```
412
-
413
- 2. User-local plugins:
414
-
415
- ```text
416
- ~/.pi-web/plugins/<plugin-package>/
417
- ```
418
-
419
- Entries may be real directories or symlinks. This is the recommended development workflow.
420
-
421
- 3. Installed Pi packages that expose PI WEB plugin metadata. Pi packages may be user or project scoped. Installing/removing/updating Pi packages is done from **Settings → Pi packages** (or Pi's package manager), not from the PI WEB plugin enable/disable list.
422
-
423
- Remote machines expose their versioned browser manifests through the gateway at `/api/machines/<machine-id>/pi-web-plugins/manifest.json`. Those plugin modules are rewritten to gateway-scoped asset URLs and registered under machine-scoped runtime ids so package copies on different machines do not collide.
424
-
425
- Plugin package directory names and plugin ids must be valid identifiers:
426
-
427
- ```text
428
- ^[a-z][a-z0-9.-]*$
429
- ```
430
-
431
- A package can expose one or more PI WEB plugin entries. There is exactly one supported `package.json` metadata shape:
432
-
433
- ```json
434
- {
435
- "private": true,
436
- "type": "module",
437
- "piWeb": {
438
- "plugins": [
439
- {
440
- "id": "review",
441
- "browserRoot": "dist/review",
442
- "module": "dist/review/index.js"
443
- },
444
- {
445
- "id": "workspaces",
446
- "browserRoot": "dist/browser",
447
- "module": "dist/browser/index.js",
448
- "serverModule": "dist/server.js",
449
- "machineSpecific": true
450
- },
451
- { "id": "server-only", "serverModule": "dist/server-only.js" }
452
- ]
453
- }
454
- }
455
- ```
456
-
457
- Rules:
458
-
459
- - `piWeb.plugins` must be an array of objects.
460
- - Each entry must have an explicit `id` and at least one of `module` or `serverModule`.
461
- - `id` must match `^[a-z][a-z0-9.-]*$`. Externally declared ids `core`, `themes`, and every `machine.*` id are reserved for the host and rejected with an attributed package diagnostic.
462
- - Both module paths must be safe canonical relative paths to existing files inside the package root. Backslashes, absolute or Windows drive-qualified paths, and empty, `.`, `..`, `.git`, or `node_modules` segments are rejected.
463
- - Every browser entry must declare `browserRoot`; a server-only entry must not. The root is `.` or a safe canonical package-relative directory with no empty, `.`, `..`, `.git`, or `node_modules` segment; Windows drive-qualified roots are rejected. It must resolve inside the package, and the browser module must remain inside it both logically and after symlink resolution.
464
- - Server entries are imported as Node ES modules. When a `serverModule` uses a `.js` path, declare `"type": "module"` in that plugin package; `.mjs` is the explicit-extension alternative.
465
- - `machineSpecific` is optional and must be boolean. Browser-only and server-only entries default to `false`. Dual browser/server entries default to `true` and cannot explicitly set it to `false`.
466
- - `plugins.<id>.settings` must be JSON-compatible for server entries; sessiond captures a private copy at startup and diagnostics expose only a fingerprint.
467
- - A plugin id has one package owner across its browser and server capabilities. Duplicates are diagnosed and never merged or auto-renamed; later package records are skipped.
468
- - Legacy shortcuts such as `piWeb.plugin`, string entries in `piWeb.plugins`, `piWeb.id` fallback ids, and no-`package.json` fallbacks are not supported.
469
-
470
- Discovery hashes the package (without traversing `.git` or `node_modules`) to produce one package-wide revision and enforce one package-wide artifact budget. A package is rejected when the scan exceeds **4,096 directory entries** or **16 MiB of file content**. These limits include files outside `browserRoot`, even though those files are not served. Keep generated caches and unrelated large artifacts out of the installed plugin package.
471
-
472
- ### Manifest and assets
473
-
474
- The manifest contains a lifecycle version and each publishable browser module. Current PI WEB releases emit `module` as a leading application-root reference and include `backendRevision` only for a paired active server entry:
475
-
476
- ```json
477
- {
478
- "lifecycleVersion": 1,
479
- "plugins": [
480
- {
481
- "id": "workspaces",
482
- "module": "/pi-web-plugins/workspaces/dist/browser/index.js?v=<content-revision>",
483
- "backendRevision": "<active-server-revision>",
484
- "source": "local",
485
- "scope": "local",
486
- "machineSpecific": true
487
- }
488
- ]
489
- }
490
- ```
491
-
492
- The browser maps leading application-root references into the current application base, so the same manifest works at the origin root or under a reverse-proxy path prefix. Federated gateways additionally accept explicit manifest-relative references such as `./my-plugin/pi-web-plugin.js` and legacy plugin-root-relative references such as `nested/pi-web-plugin.js`; all accepted forms are rewritten to deployment-portable, gateway-relative references.
493
-
494
- `source` describes where the plugin came from (`bundled`, `local`, or the Pi package source). `scope` is `bundled`, `local`, `user`, or `project`. `machineSpecific` controls whether the gateway copy is valid for remote machines or only each selected machine's own copy can appear. A server-only entry has no browser manifest record. A dual entry is omitted unless sessiond reports the exact active, compatible, non-unhealthy package pairing.
495
-
496
- At an origin-root deployment, a browser-public file is available under its package-relative path:
497
-
498
- ```text
499
- /pi-web-plugins/<plugin-id>/<package-relative-path-under-browserRoot>
500
- ```
501
-
502
- Only files logically inside `browserRoot` and canonically inside that same directory after symlink resolution are captured and served. Files elsewhere in the package—including a sibling server module, source, metadata, and dependencies—return not found through plugin asset routes. Declaring `browserRoot: "."` therefore makes almost the whole scanned package browser-public; prefer a narrow output directory and never place secrets inside it. Unsafe, missing, package-escaping, or module-excluding roots fail discovery with an attributed diagnostic.
503
-
504
- Prefer module-relative asset URLs so they also work for remote machine plugins and nested deployments. For example, a built plugin module can reference an SVG shipped beside it:
505
-
506
- ```js
507
- const iconUrl = new URL("./assets/icon.svg", import.meta.url);
508
- ```
509
-
510
- The final installed plugin package must contain `assets/icon.svg` at that path relative to the final built module and inside `browserRoot`. PI WEB serves files that already exist in the package; it does not copy a source `public/` directory or apply Vite-style public-directory semantics. Configure the plugin build and package contents to emit or copy the asset into its final module-relative location.
162
+ The shipped Relay package adds agent prompts and skills for carrying work across sessions, plus a read-only **Relays** tab for inspecting plans and progress under `.pi-web/relays/`. The tab does not start or edit a relay.
511
163
 
512
- PI WEB returns executable JavaScript MIME types for both `.js` and `.mjs`. JSON, CSS, HTML, and SVG receive their corresponding content types; unknown file types are served as octet-stream.
164
+ PI WEB installs Relay automatically for the active agent profile if it is not configured. Removing it through **Settings → Pi packages** is remembered; it will not be silently reinstalled. Reinstall from **Available packages** if you change your mind. Disabling just the Relays plugin hides its tab but leaves its agent resources available.
513
165
 
514
- ## Pi packages shipped alongside bundled plugins
166
+ ### Try Captain's Log
515
167
 
516
- `pi-packages/` ships real, independently identified Pi packages inside `@jmfederico/pi-web`'s npm package, built into `dist/pi-packages/<name>/` alongside — but separate from — the bundled PI WEB plugins in `pi-web-plugins/`/`dist/pi-web-plugins/`. A package shipped this way is *not* discovered by PI WEB's bundled/local directory scan; it only becomes an active PI WEB plugin once it is installed as a Pi package for the active agent profile, exactly like an externally published one (see [Discovery and packaging](#discovery-and-packaging)).
168
+ Captain's Log is an optional example that retells a conversation's latest assistant reply as a pirate briefing. It demonstrates a browser panel, backend, and Pi companion working together.
517
169
 
518
- `pi-packages/relays/` is shaped this way: its `package.json` carries the real package identity `@jmfederico/pi-relay` alongside its `piWeb.plugins` entry, and its `prompts/` and `skills/` directories already follow pi's package conventions. Installing it as a Pi package — with a plain `pi install <path-to-dist/pi-packages/relays>`, through **Settings → Pi packages**' existing free-text install form, or with the one-click **Available packages** install button described below — makes `/relay`, `/relay-worktree`, and the `relay` skill available in any `pi` session, and makes the Relays PI WEB plugin (its browser tab and workspace action) available once installed for the active agent profile. Publishing the package to npm remains deferred follow-up work; today, installing it uses its local shipped path.
170
+ 1. On the target machine, install **Captain's Log** from **Settings → Pi packages → Available packages**.
171
+ 2. Enable it in **Settings → PI WEB plugins**.
172
+ 3. Restart that machine's session daemon when safe, then reload the browser.
173
+ 4. Select a conversation, open **Captain's Log**, and choose **Let the Captain tell it**.
519
174
 
520
- **Automatic install, with opt-out.** For a plain `pi` user this package is only ever installed by explicit `pi install`. For PI WEB, though, the session daemon reconciles a small registry of known auto-installable Pi packages (currently just `@jmfederico/pi-relay`) at startup, for the active agent profile: if a package matching one of these by its own declared `package.json` name is not already configured for that profile, sessiond installs it from its shipped local path automatically, the same way the Settings UI's Install action would. This reconciliation is best-effort — a failure (offline, a read-only agent directory, a package-manager error) is logged and never blocks or crashes session-daemon startup.
175
+ The package is prebuilt; no compilation is required. It reads the source reply without modifying that conversation and uses a separate pirate conversation. Model credentials are required, and the source text goes to the pirate's model provider. Previous results are saved. After a daemon restart, open the previous pirate conversation in Sessions if you want to reuse its context.
521
176
 
522
- **Dismissal is remembered per profile.** Removing a known auto-installable package from **Settings → Pi packages** records that removal in a small store under `$PI_WEB_DATA_DIR` (state, not user-editable configuration — alongside `projects.json`/`machines.json`, not in `$PI_WEB_CONFIG`), keyed by the active agent profile directory and the package's declared name. Once dismissed for a profile, startup reconciliation does not reinstall it again for that profile; only an explicit reinstall brings it back.
177
+ See the [Captain's Log usage guide](https://github.com/jmfederico/pi-web/blob/main/pi-packages/captains-log/docs/usage.md) for the demo's behavior and troubleshooting.
523
178
 
524
- **One-click reinstall.** A profile that dismissed (or never installed) a known auto-installable package can install it again from **Settings → Pi packages** without typing its on-disk path: an **Available packages** section lists every known package not currently configured for the selected target, each with an **Install** button that installs it from its shipped location directly. The section disappears once every known package is configured.
179
+ ## Pi extension dialogs
525
180
 
526
- ## Browser module shape and v2 migration
181
+ Pi extensions can ask for confirmation, a selection, or text input. PI WEB shows these questions inline in the conversation, including during session startup or while a tool is waiting. They remain answerable after a browser reload, and the first answer wins across tabs.
527
182
 
528
- TypeScript browser entries should use a type-only import from the published declaration entrypoint. The built JavaScript must not import PI WEB source internals:
183
+ Dialogs use the extension's timeout and the host's configured [dialog timeout](https://pi-web.dev/config#extension-dialogs). Aborting work or replacing its runtime closes the relevant outstanding questions. Answered cards are browser-local and need not survive a reload. Reloading while a new session is still being created can temporarily lose its question card; the pending question still has its deadline.
529
184
 
530
- ```ts
531
- import type { PiWebPlugin } from "@jmfederico/pi-web/plugin-api";
185
+ These three dialog methods are supported; other Pi extension UI surfaces, such as custom editors and widgets, are not. An extension should not assume every UI feature works just because `hasUI` is true.
532
186
 
533
- const plugin: PiWebPlugin = {
534
- apiVersion: 2,
535
- name: "My Plugin",
536
- activate: ({ pluginId, runtimePluginId, html }) => ({
537
- contributions: {
538
- actions: [{
539
- id: "workspace.open",
540
- title: "Open my panel",
541
- run: ({ selectWorkspaceTool }) => {
542
- selectWorkspaceTool(`${runtimePluginId}:workspace.my-panel`);
543
- },
544
- }],
545
- workspacePanels: [{
546
- id: "workspace.my-panel",
547
- title: "My panel",
548
- visible: ({ workspace }) => workspace.provider?.pluginId === pluginId,
549
- render: ({ workspace }) => html`<p>${workspace.label}</p>`,
550
- }],
551
- },
552
- }),
553
- };
187
+ ## Agent development
554
188
 
555
- export default plugin;
556
- ```
557
-
558
- The activation boundary is:
559
-
560
- ```ts
561
- interface PiWebPlugin {
562
- apiVersion: 2;
563
- name: string;
564
- activate(context: PluginActivationContext): PluginActivationResult;
565
- }
566
-
567
- interface PluginActivationContext {
568
- readonly apiVersion: 2;
569
- readonly pluginId: string;
570
- readonly runtimePluginId: string;
571
- readonly html: HtmlTemplateTag;
572
- readonly svg: SvgTemplateTag;
573
- }
574
- ```
575
-
576
- `activate()` is called once when the UI loads the plugin. Keep it cheap and synchronous: define contributions there, but move expensive or async work into actions, custom elements, or explicit user interactions.
577
-
578
- Browser API v2 is a deliberate break: the host rejects browser v1 entries with the plugin/module identity and expected version; there is no v1 compatibility shim. Migrate a browser entry by setting `apiVersion: 2`, using stable `pluginId` for package/provider ownership, and using `runtimePluginId` when constructing a host-qualified contribution reference. Replace browser-v1 `refreshGit` with `refreshWorkspacePanels()` plus panel `onInvalidate()`. The browser-v1 `isGitRepo`, `isGitWorktree`, and top-level `workspace.branch` aliases were removed; use the provider-authored `workspace.label` for generic presentation, and keep provider-specific facts in `workspace.provider.metadata` or the owning backend. The former `@jmfederico/pi-web/plugin-api/unstable` type path is not part of v2 and is no longer exported.
579
-
580
- Contribution ids authored in arrays remain local to the plugin. PI WEB qualifies them internally under the runtime identity:
189
+ Give the agent a goal, the data it should use, and the actions it may take:
581
190
 
582
191
  ```text
583
- <runtime-plugin-id>:<local-contribution-id>
584
- ```
585
-
586
- For a local plugin the runtime and source ids are normally equal. A federated registration may machine-scope `runtimePluginId`, while `pluginId` and `workspace.provider.pluginId` remain the same source id.
587
-
588
- ## Server module and workspace provider shape
589
-
590
- TypeScript server entries import the separately published Node declarations with `import type`:
591
-
592
- ```ts
593
- import type {
594
- PiWebServerPlugin,
595
- WorkspaceProvider,
596
- } from "@jmfederico/pi-web/server-plugin-api";
597
-
598
- const provider: WorkspaceProvider = {
599
- async probe(project, signal) {
600
- // Return "claim" only when this provider owns the project's semantics.
601
- return await projectIsSupported(project, signal) ? "claim" : "pass";
602
- },
603
- async list(project, signal) {
604
- return await listProviderWorkspaces(project, signal);
605
- },
606
- async request({ project, workspace, operation, input, signal }) {
607
- return await handleProviderOperation({ project, workspace, operation, input, signal });
608
- },
609
- };
610
-
611
- const plugin: PiWebServerPlugin = {
612
- apiVersion: 1,
613
- name: "My Workspace Provider",
614
- activate(context) {
615
- return {
616
- workspaceProvider: provider,
617
- health: async (signal) => ({ status: "healthy" }),
618
- stop: async (signal) => { /* release plugin-owned resources */ },
619
- };
620
- },
621
- };
622
-
623
- export default plugin;
624
- ```
625
-
626
- The default export has `apiVersion: 1`, a non-empty `name`, and `activate(context)`. The activation result can contain:
627
-
628
- ```ts
629
- interface ServerPluginActivation {
630
- workspaceProvider?: WorkspaceProvider;
631
- start?(signal: AbortSignal): void | Promise<void>;
632
- stop?(signal: AbortSignal): void | Promise<void>;
633
- health?(signal: AbortSignal): ServerPluginHealth | Promise<ServerPluginHealth>;
634
- }
635
- ```
636
-
637
- A server plugin may contribute at most one `workspaceProvider`. The host-owned frozen activation context contains its `pluginId`, `packageRoot`, JSON settings snapshot, scoped logger, activation `AbortSignal`, and an argv-based `execFile()` helper. `execFile()` has host-owned timeout/output bounds; pass the current callback's signal into every command request. The API exposes no shell parser, Fastify instance, route registration, concrete service, event bus, or service locator.
638
-
639
- Every activation, lifecycle, provider, and request signal is scoped to that one invocation. The host aborts it when the invocation times out or settles. Do not retain a signal as a plugin-lifetime shutdown notification; release plugin-owned resources in the explicit `stop()` callback. Deadlines remain cooperative, so plugins must observe each supplied signal.
640
-
641
- Sessiond resolves the enabled catalog once per process start. It imports, validates, activates, and starts each server entry before publishing its contribution. A failed entry is attributed and skipped without aborting ordinary activation of other plugins; a failed `start` is rolled back with `stop` when available. Successful plugins stop in reverse activation order. Sessiond inspects each optional `health()` callback once while building the startup workspace authority; an unhealthy provider is excluded, a degraded provider remains eligible, and that inspection is not polled again during the process lifetime. Server entries are never hot-reloaded or unloaded after config/package edits.
642
-
643
- ### Workspace provider contract
644
-
645
- ```ts
646
- interface WorkspaceProvider {
647
- fallback?: boolean;
648
- probe(project: ProjectInput, signal: AbortSignal): Promise<"claim" | "pass">;
649
- list(project: ProjectInput, signal: AbortSignal): Promise<ProviderWorkspace[]>;
650
- request?(context: ProviderRequestContext): Promise<JsonValue>;
651
- prepareRemove?(context: ProviderRemoveContext): Promise<WorkspaceRemovePlan>;
652
- }
653
-
654
- interface ProviderWorkspace {
655
- key: string;
656
- path: string;
657
- label: string;
658
- isMain: boolean;
659
- data?: JsonValue;
660
- publicMetadata?: JsonObject;
661
- removal?: { actionLabel: string; confirmation: string };
662
- }
663
- ```
664
-
665
- - `probe()` must return only `"claim"` or `"pass"`. Leave `fallback` unset/false for a replacement that should run before bundled Git.
666
- - `list()` runs only for the selected owner. Return stable provider-local keys, accessible absolute directory paths, unique paths/keys, non-empty labels, and exactly one main workspace.
667
- - `data` is round-tripped privately to that provider during the current resolution. `publicMetadata` appears under `workspace.provider.metadata` and is visible to **all browser code and API consumers**. Never put secrets in `publicMetadata` or removal wording.
668
- - `request()` is optional and receives a host-validated frozen current owner/workspace projection plus a bounded operation id, JSON input, and operation-scoped abort signal. It must return JSON.
669
- - `removal` is display text only and requires `prepareRemove()`. It advertises removal for that specific workspace; browser `workspace.provider.capabilities.remove` is true only when that workspace advertises it and the owning provider implements removal.
670
- - `prepareRemove()` returns a plan for a visible host-owned terminal run; returning the plan approves the operation but does **not** mean removal has completed. `command` is shell source interpreted by the host's login shell. The host chooses a safe current working directory outside the target, so the provider must use the supplied absolute `workspace.path`, shell-quote it, and keep removal in the foreground. The host records completion when the shell exits, with exit status 0 meaning success.
671
- - Provider failures and conflicts are diagnostics. A claimant that fails `list()` does not permit fallback takeover for the same resolution.
672
-
673
- The only supported plugin type entrypoints are the type-only package exports `@jmfederico/pi-web/plugin-api` and `@jmfederico/pi-web/server-plugin-api`. Use them with `import type`; there is no runtime JavaScript export. Private `dist/**` deep imports and any other plugin API subpath are not part of the package contract.
674
-
675
- ## Contributions
676
-
677
- The workspace-related contribution arrays returned by `activate()` are:
678
-
679
- ```ts
680
- interface PluginContributions {
681
- actions?: PluginAction[];
682
- workspacePanels?: WorkspacePanelContribution[];
683
- workspaceLabels?: WorkspaceLabelContribution[];
684
- }
685
- ```
686
-
687
- ### Actions
688
-
689
- Actions appear in the action palette. They can inspect app state and call UI/runtime helpers.
690
-
691
- ```js
692
- actions: [
693
- {
694
- id: "copy-diagnostics",
695
- title: "Copy PI WEB Diagnostics",
696
- description: "Copy version, installation, and status details for this machine",
697
- group: "Info",
698
- run: async (context) => {
699
- const version = context.state.piWebStatus?.components.web.runtimeVersion ?? "unknown";
700
- await navigator.clipboard.writeText(`PI WEB ${version}`);
701
- },
702
- },
703
- ]
704
- ```
705
-
706
- Action type:
707
-
708
- ```ts
709
- interface PluginAction {
710
- id: string;
711
- title: string;
712
- description?: string;
713
- shortcut?: string;
714
- shortcutAliases?: QualifiedContributionId[];
715
- group?: string;
716
- enabled?: (context: PluginRuntimeContext) => boolean;
717
- disabledReason?: (context: PluginRuntimeContext) => string | undefined;
718
- run: (context: PluginRuntimeContext) => void | Promise<void>;
719
- }
720
- ```
721
-
722
- If an action is disabled and returns `disabledReason`, PI WEB can keep it visible in the action palette with that explanation instead of hiding it.
723
-
724
- Stable runtime context fields:
725
-
726
- ```ts
727
- interface PluginRuntimeContext {
728
- state: {
729
- selectedMachine?: PluginMachine;
730
- selectedWorkspace?: Workspace;
731
- selectedSession?: unknown;
732
- workspaceTool?: string;
733
- mainView?: string;
734
- piWebStatus?: PiWebStatusResponse;
735
- };
736
- prompt: PluginPromptEditor;
737
- openActionPalette: () => void;
738
- focusPrompt: () => void;
739
- addProject: () => void | Promise<void>;
740
- configureAuth: () => void | Promise<void>;
741
- logoutAuth: () => void | Promise<void>;
742
- openThemePicker: () => void;
743
- selectMainView: (view: string) => void;
744
- selectWorkspaceTool: (tool: QualifiedContributionId) => void;
745
- openTerminal: (options?: { terminalId?: string }) => void;
746
- refreshFiles: () => void | Promise<void>;
747
- refreshWorkspacePanels: (panelId?: QualifiedContributionId) => void | Promise<void>;
748
- refreshAppData: () => void | Promise<void>;
749
- checkForPiWebUpdates?: () => void | Promise<void>;
750
- reloadPage: () => void;
751
- startSession: () => void | Promise<void>;
752
- archiveSession: () => void | Promise<void>;
753
- stopActiveWork: () => void | Promise<void>;
754
- }
192
+ Build a PI WEB plugin for this project.
193
+ Goal: <describe the workflow and expected UI>.
194
+ Read https://pi-web.dev/plugins.md, then follow its public-contract
195
+ and example links for the PI WEB version installed here.
196
+ Use supported plugin APIs; do not modify PI WEB or call private routes.
197
+ Explain installation, any permissions or model use, and how to reload it.
198
+ Test the behavior, including failures and cleanup.
755
199
  ```
756
200
 
757
- Notes:
758
-
759
- - `state` is a snapshot of current UI state when actions are built.
760
- - The stable state fields are `state.selectedMachine`, `state.selectedWorkspace`, `state.selectedSession`, `state.workspaceTool`, `state.mainView`, and `state.piWebStatus`. `state.selectedMachine` identifies the currently selected machine. `state.piWebStatus` describes the currently selected machine's PI WEB runtime, or the gateway/local runtime when the local machine is selected.
761
- - Other `state` fields may exist at runtime, but they are private PI WEB internals that may graduate into stable helpers, change shape, or disappear.
762
- - `enabled` is evaluated when the action palette asks for actions.
763
- - `shortcutAliases` is for migration only: list former fully qualified action ids whose saved shortcut preference should still apply to this action.
764
- - `selectWorkspaceTool()` expects a qualified panel id such as `my-plugin:workspace.info`.
765
- - `openTerminal()` switches to the built-in terminal panel. Pass `{ terminalId }` to deep-link to a specific terminal.
766
- - `refreshWorkspacePanels()` invokes `onInvalidate` for the selected workspace, either for every plugin panel or for one qualified `panelId`. The callback owns its refresh and should request a render when its visible state changes.
767
- - `checkForPiWebUpdates()` forces a fresh update check on the selected machine and refreshes `state.piWebStatus`. It is optional so plugins remain compatible with older PI WEB hosts.
768
- - Only fields documented here and declared by `@jmfederico/pi-web/plugin-api` are stable public browser API. Anything else is experimental: it may become public API later, change shape, or disappear.
769
-
770
- ### Prompt editor API
201
+ ### Where to implement
771
202
 
772
- The `prompt` helper on `PluginRuntimeContext` and `WorkspacePanelContext` provides stable access to the chat prompt editor:
203
+ Use the smallest example that fits. Source links below track development on `main`; **use the tag or installed declarations matching your PI WEB version** when implementing against a release.
773
204
 
774
- | Method | Description |
205
+ | Need | Start here |
775
206
  | --- | --- |
776
- | `insertText(text)` | Insert text at cursor position. When text is selected, replaces the selection. Focuses the editor first if not focused. |
777
- | `getText()` | Returns the full prompt text. |
778
- | `getSelection()` | Returns `{ start, end, text }` if text is selected, or `null`. |
779
-
780
- Usage:
781
-
782
- ```js
783
- // Insert text at the cursor (e.g. a file mention)
784
- context.prompt.insertText("@file.txt");
785
-
786
- // Read the current prompt and selection
787
- const text = context.prompt.getText();
788
- const selection = context.prompt.getSelection(); // { start, end, text } | null
789
- ```
790
-
791
- Use `focusPrompt()` on `PluginRuntimeContext` to move focus to the prompt editor. Workspace panels can call `context.prompt.insertText()` from explicit user interactions such as button clicks; panel contexts target the currently selected session's mounted prompt editor.
792
-
793
- #### Keyboard shortcuts
794
-
795
- - App-level keyboard shortcuts must be attached to actions. PI WEB does not support standalone plugin keyboard commands; contribute an action first, then add a `shortcut` if it needs a keybinding.
796
- - `shortcut` is the action's default keybinding. It is displayed in the action palette and handled by the global shortcut dispatcher when the action is enabled.
797
- - Use modified shortcuts such as `mod+shift+p`; plain letter shortcuts are intentionally ignored so normal typing is never captured.
798
- - Future PI WEB versions may allow users to override or disable action shortcuts by action id, so plugins should treat `shortcut` as a default rather than a guaranteed final binding.
799
- - Choose shortcuts carefully to avoid conflicts. There is no user-facing shortcut override or conflict resolver yet.
800
- - Local text input, terminal input, list navigation, and dialog keys such as Enter, Escape, and arrow keys do not need to be plugin actions unless they are app-level commands.
801
-
802
- ### Workspace panels
803
-
804
- Workspace panels add tools next to built-in workspace tools. They render inside the workspace side panel on desktop and as mobile tabs on smaller screens.
805
-
806
- ```js
807
- workspacePanels: [
808
- {
809
- id: "workspace.info",
810
- title: "Info",
811
- icon: svg`
812
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
813
- <circle cx="12" cy="12" r="9"></circle>
814
- <path d="M12 10v6"></path>
815
- <path d="M12 7h.01"></path>
816
- </svg>
817
- `,
818
- order: 100,
819
- visible: ({ workspace }) => workspace.isMain,
820
- render: ({ workspace }) => html`
821
- <section class="toolbar"><strong>Info</strong></section>
822
- <section class="viewer">
823
- <p class="muted">${workspace.label}</p>
824
- <p class="muted">${workspace.path}</p>
825
- </section>
826
- `,
827
- },
828
- ]
829
- ```
830
-
831
- Panel type:
832
-
833
- ```ts
834
- interface WorkspacePanelContribution {
835
- id: string;
836
- title: string;
837
- icon?: TemplateResult;
838
- order?: number;
839
- routeAliases?: string[];
840
- visible?: (context: WorkspacePanelContext) => boolean;
841
- badge?: (context: WorkspacePanelContext) => string | number | TemplateResult | undefined;
842
- onInvalidate?: (context: WorkspacePanelContext) => void | Promise<void>;
843
- render: (context: WorkspacePanelContext) => TemplateResult;
844
- }
845
-
846
- interface WorkspacePanelContext {
847
- machine: PluginMachine;
848
- workspace: Workspace;
849
- state?: PluginRuntimeState;
850
- files: {
851
- readFile(path: string): Promise<FileContentResponse>;
852
- listFiles(path: string): Promise<FileTreeResponse>;
853
- writeFile(path: string, content: string | Uint8Array, options?: WriteWorkspaceFileOptions): Promise<WriteWorkspaceFileResponse>;
854
- deleteFile(path: string): Promise<DeleteWorkspaceFileResponse>;
855
- moveFile(fromPath: string, toPath: string, options?: MoveWorkspaceFileOptions): Promise<MoveWorkspaceFileResponse>;
856
- };
857
- backend?: {
858
- request(operation: string, input: JsonValue): Promise<JsonValue>;
859
- };
860
- prompt: PluginPromptEditor;
861
- terminal: {
862
- open(options?: { terminalId?: string }): void;
863
- runCommand(input: {
864
- title: string;
865
- command: string;
866
- metadata?: Record<string, string>;
867
- open?: boolean;
868
- }): Promise<TerminalCommandRunHandle>;
869
- };
870
- host: {
871
- requestRender(): void;
872
- };
873
- }
874
- ```
875
-
876
- `icon` is optional and is used in the compact mobile tab bar. Prefer an SVG rendered with the `svg` helper from `PluginActivationContext`; use `currentColor` so PI WEB themes can style it. If `icon` is omitted, mobile tabs fall back to initials from the panel title, or to the full title when initials collide.
877
-
878
- `machine`, `workspace`, `files`, optional `backend`, `prompt`, `terminal`, and `host` are documented as stable for panel callbacks. The `files` helper supports `readFile`, `listFiles`, `writeFile`, `deleteFile`, and `moveFile` — see [Reading workspace files](#reading-workspace-files), [Listing workspace files](#listing-workspace-files), and [Writing, deleting, and moving workspace files](#writing-deleting-and-moving-workspace-files). A browser entry with a paired active provider uses `backend.request()` instead of constructing API routes — see [Calling paired workspace backends](#calling-paired-workspace-backends). The `prompt` helper supports panel interactions that insert workspace context into the current prompt — see [Prompt editor API](#prompt-editor-api). Use `terminal.open()` to switch to the built-in terminal panel; pass `{ terminalId }` to deep-link to a specific terminal. `routeAliases` is only for migrating former URL tool/view values. Implement `onInvalidate()` to refresh plugin-owned panel data when an action or host refresh calls `refreshWorkspacePanels()`; call `host.requestRender()` when async state changes should make PI WEB re-evaluate `badge`, `visible`, or `render`.
879
-
880
- Useful workspace and machine shapes:
881
-
882
- ```ts
883
- interface PluginMachine {
884
- id: string;
885
- name: string;
886
- kind: "local" | "remote";
887
- }
888
-
889
- interface Workspace {
890
- readonly id: string;
891
- readonly projectId: string;
892
- readonly path: string;
893
- readonly label: string;
894
- readonly isMain: boolean;
895
- readonly provider?: {
896
- readonly pluginId: string;
897
- readonly capabilities: { readonly request: boolean; readonly remove: boolean };
898
- readonly metadata?: JsonObject;
899
- };
900
- readonly removal?: { readonly actionLabel: string; readonly confirmation: string };
901
- }
902
- ```
903
-
904
- `machine.id` is included in panel contexts so plugins can keep caches machine-scoped. Do not infer the selected machine from global browser state. Use the provider-authored `workspace.label` for provider-neutral presentation. `workspace.provider.pluginId` is the stable source id, and provider-published details such as Git status live in `workspace.provider.metadata`, which the server provider fills from browser-public `publicMetadata`. Provider-specific browser code may interpret metadata it owns; PI WEB core does not assign branch semantics to the generic workspace shape. `capabilities.remove` describes only this workspace, not the provider in general. The browser-v1 `isGitRepo`, `isGitWorktree`, and top-level `branch` aliases were removed.
905
-
906
- Use existing classes such as `toolbar`, `viewer`, `empty`, and `muted` for panel content when possible. Do not assume a panel owns the whole page; keep layout contained.
907
-
908
- ### Workspace labels
909
-
910
- Workspace labels add compact inline metadata wherever PI WEB displays a workspace label: workspace list, workspace panel header, and status bar.
911
-
912
- Use them for short facts like project environment, local URL, branch status, container name, or health state.
913
-
914
- ```js
915
- workspaceLabels: [
916
- {
917
- id: "dev-url",
918
- order: 10,
919
- visible: ({ workspace }) => workspace.path.includes("my-app"),
920
- items: () => [{
921
- type: "link",
922
- text: "web:5173",
923
- href: "http://localhost:5173",
924
- title: "Open dev server",
925
- target: "_blank",
926
- }],
927
- },
928
- ]
929
- ```
930
-
931
- Label contribution type:
932
-
933
- ```ts
934
- interface WorkspaceLabelContribution {
935
- id: string;
936
- order?: number;
937
- visible?: (context: WorkspaceLabelContext) => boolean;
938
- items: (context: WorkspaceLabelContext) => WorkspaceLabelItem[];
939
- }
940
-
941
- interface WorkspaceLabelContext {
942
- machine: PluginMachine;
943
- workspace: Workspace;
944
- state?: PluginRuntimeState;
945
- files: {
946
- readFile(path: string): Promise<FileContentResponse>;
947
- listFiles(path: string): Promise<FileTreeResponse>;
948
- writeFile(path: string, content: string | Uint8Array, options?: WriteWorkspaceFileOptions): Promise<WriteWorkspaceFileResponse>;
949
- deleteFile(path: string): Promise<DeleteWorkspaceFileResponse>;
950
- moveFile(fromPath: string, toPath: string, options?: MoveWorkspaceFileOptions): Promise<MoveWorkspaceFileResponse>;
951
- };
952
- backend?: {
953
- request(operation: string, input: JsonValue): Promise<JsonValue>;
954
- };
955
- host: {
956
- requestRender(): void;
957
- };
958
- }
959
- ```
960
-
961
- `machine`, `workspace`, `files`, optional `backend`, and `host` are documented as stable for label callbacks. The `files` helper supports `readFile`, `listFiles`, `writeFile`, `deleteFile`, and `moveFile` — see [Reading workspace files](#reading-workspace-files), [Listing workspace files](#listing-workspace-files), and [Writing, deleting, and moving workspace files](#writing-deleting-and-moving-workspace-files). A browser entry with a paired active provider can call `backend.request()` from a label-owned async cache after checking that the optional helper is present. Include `machine.id` in caches that depend on workspace data. Call `host.requestRender()` when async plugin-owned state changes should make PI WEB re-evaluate label `visible` or `items` callbacks.
962
-
963
- Items are sorted by `order` and then id. Return an empty array to render nothing. Keep callbacks synchronous and lightweight; start async work from the callback, return cached items, then call `host.requestRender()` when the cache changes.
964
-
965
- #### Text items
966
-
967
- ```js
968
- { type: "text", text: "staging", title: "Staging workspace" }
969
- ```
970
-
971
- #### Link items
972
-
973
- ```js
974
- {
975
- type: "link",
976
- text: "web:5173",
977
- href: "http://localhost:5173",
978
- title: "Open dev server",
979
- target: "_blank"
980
- }
981
- ```
982
-
983
- PI WEB renders the anchor and adds safe defaults such as `rel="noopener noreferrer"` for `_blank` links. `javascript:` and `data:` links are rendered as plain text instead of links.
984
-
985
- #### Render items
986
-
987
- Use render items when a label contribution needs custom UI, async data, or caching. Render items should stay compact and inline.
988
-
989
- ```js
990
- class MyWorkspaceBadge extends HTMLElement {
991
- set workspace(value) {
992
- this._workspace = value;
993
- this.textContent = value?.label ?? "workspace";
994
- }
995
- }
207
+ | Browser contributions and helpers | [`plugin-api.ts`](https://github.com/jmfederico/pi-web/blob/main/src/plugin-api.ts), published as `@jmfederico/pi-web/plugin-api` |
208
+ | Server lifecycle, peers, providers, and host capabilities | [`server-plugin-api.ts`](https://github.com/jmfederico/pi-web/blob/main/src/server-plugin-api.ts), published as `@jmfederico/pi-web/server-plugin-api` |
209
+ | A small browser plugin | [Info](https://github.com/jmfederico/pi-web/tree/main/pi-web-plugins/info) |
210
+ | A standalone browser/server package | [Workspace-provider example](https://github.com/jmfederico/pi-web/tree/main/examples/workspace-provider-plugin) |
211
+ | A production workspace provider and paired UI | [Git](https://github.com/jmfederico/pi-web/tree/main/pi-web-plugins/git) |
212
+ | Hosted sessions, live updates, and a Pi companion | [Captain's Log](https://github.com/jmfederico/pi-web/tree/main/pi-packages/captains-log) |
213
+ | A simpler initial-prompt workflow | [Workspace Reviews example](https://github.com/jmfederico/pi-web/tree/main/examples/session-bridge-plugin) |
214
+ | Package discovery rules and diagnostics | [Plugin catalog](https://github.com/jmfederico/pi-web/blob/main/src/server/piWebPluginCatalog.ts) |
996
215
 
997
- if (!customElements.get("my-workspace-badge")) {
998
- customElements.define("my-workspace-badge", MyWorkspaceBadge);
999
- }
1000
-
1001
- export default {
1002
- apiVersion: 2,
1003
- name: "My Plugin",
1004
- activate: ({ html }) => ({
1005
- contributions: {
1006
- workspaceLabels: [
1007
- {
1008
- id: "badge",
1009
- order: 10,
1010
- items: ({ workspace }) => [{
1011
- type: "render",
1012
- render: () => html`<my-workspace-badge .workspace=${workspace}></my-workspace-badge>`,
1013
- }],
1014
- },
1015
- ],
1016
- },
1017
- }),
1018
- };
1019
- ```
1020
-
1021
- ## Calling paired workspace backends
1022
-
1023
- Workspace panel and label contexts include an optional JSON-only backend helper. It is present only for a browser entry paired with an active server backend:
1024
-
1025
- ```js
1026
- if (context.backend === undefined) throw new Error("Workspace backend unavailable");
1027
- const result = await context.backend.request("summary", {
1028
- includeIgnored: false,
1029
- });
1030
- ```
1031
-
1032
- PI WEB binds the request to the browser module's original package id and active backend revision, plus the callback's selected machine, project, and workspace. The host resolves the current workspace owner again before dispatch. The call succeeds only when that same active plugin still owns the workspace and implements `WorkspaceProvider.request()`.
1033
-
1034
- Operation ids must match `^[a-z][a-z0-9.-]*$` and be at most 128 characters. Inputs and results must contain only finite JSON values; functions, classes, `undefined`, cycles, and non-finite numbers are rejected. Requests, responses, owner resolution, and provider callbacks are size- and time-bounded.
1035
-
1036
- The same helper works locally and through machine federation. It preserves machine scoping and active frontend/backend revision pairing, so browser plugins must not construct `/api/plugin-backends/...` or `/api/machines/...` URLs themselves. Missing/inactive backends, stale revisions/workspaces, ownership changes/conflicts, unsupported operations, invalid JSON, failures, and timeouts reject the promise with an attributed error.
1037
-
1038
- ## Reading workspace files
1039
-
1040
- Workspace panels and workspace labels can read files through the documented `files` helper. PI WEB binds this helper to the callback's machine and workspace, so it works the same for local and federated machines.
1041
-
1042
- ```js
1043
- workspacePanels: [
1044
- {
1045
- id: "workspace.env",
1046
- title: "Env",
1047
- render: ({ files }) => html`
1048
- <my-env-viewer .files=${files}></my-env-viewer>
1049
- `,
1050
- },
1051
- ]
1052
-
1053
- class MyEnvViewer extends HTMLElement {
1054
- set files(value) {
1055
- this._files = value;
1056
- void this.load();
1057
- }
1058
-
1059
- async load() {
1060
- try {
1061
- const file = await this._files.readFile(".env.example");
1062
- this.textContent = file.binary ? "Binary file" : file.content;
1063
- } catch (error) {
1064
- this.textContent = error instanceof Error ? error.message : String(error);
1065
- }
1066
- }
1067
- }
1068
- ```
1069
-
1070
- Labels should use the same helper through a plugin-owned cache because `items()` itself must return synchronously:
1071
-
1072
- ```js
1073
- const envCache = new Map();
1074
-
1075
- function envKey(machine, workspace) {
1076
- return `${machine.id}:${workspace.id}:.env.local`;
1077
- }
1078
-
1079
- function loadEnvLabel(context) {
1080
- const key = envKey(context.machine, context.workspace);
1081
- const cached = envCache.get(key);
1082
- if (cached !== undefined) return cached;
1083
-
1084
- const pending = { status: "loading", label: undefined };
1085
- envCache.set(key, pending);
1086
- context.files.readFile(".env.local")
1087
- .then((file) => {
1088
- pending.status = "ready";
1089
- pending.label = file.content.match(/^DEV_URL=(.+)$/m)?.[1];
1090
- context.host.requestRender();
1091
- })
1092
- .catch(() => {
1093
- pending.status = "missing";
1094
- context.host.requestRender();
1095
- });
1096
- return pending;
1097
- }
1098
-
1099
- workspaceLabels: [
1100
- {
1101
- id: "dev-url",
1102
- items: (context) => {
1103
- const cached = loadEnvLabel(context);
1104
- return cached.label === undefined ? [] : [{
1105
- type: "link",
1106
- text: cached.label,
1107
- href: cached.label,
1108
- target: "_blank",
1109
- }];
1110
- },
1111
- },
1112
- ]
1113
- ```
1114
-
1115
- The file response includes fields such as `path`, `content`, `truncated`, and `binary`. Be careful with sensitive files such as `.env`: browser entries are trusted code, and file contents are exposed to the plugin.
1116
-
1117
- ## Listing workspace files
1118
-
1119
- `files.listFiles(path)` lists the entries of a workspace directory. Pass `""` for the workspace root. Like `readFile`, PI WEB binds the call to the callback's machine and workspace, so it works the same for local and federated machines.
1120
-
1121
- ```js
1122
- const listing = await context.files.listFiles("src");
1123
- for (const entry of listing.entries) {
1124
- // entry: { name, path, type: "file" | "directory" | "symlink", size?, modifiedAt? }
1125
- }
1126
- ```
1127
-
1128
- The listing response includes `path`, `entries`, `scannedAt`, and `truncated`. When `truncated` is true, the server cut the listing short, so treat the entries as partial.
1129
-
1130
- `listFiles` rejects when the directory does not exist or cannot be read, matching `readFile` error behavior. When a directory is optional, catch the error and treat it as an empty listing:
1131
-
1132
- ```js
1133
- async function listSubdirectoryNames(context, path) {
1134
- try {
1135
- const listing = await context.files.listFiles(path);
1136
- return listing.entries.filter((entry) => entry.type === "directory").map((entry) => entry.name);
1137
- } catch {
1138
- return [];
1139
- }
1140
- }
1141
- ```
1142
-
1143
- ## Writing, deleting, and moving workspace files
1144
-
1145
- Workspace panels and workspace labels can write, delete, and move files through the documented `files` helper. Like `readFile`, PI WEB binds these helpers to the callback's machine and workspace, so they work the same for local and federated machines.
1146
-
1147
- ### Writing files
1148
-
1149
- ```js
1150
- workspacePanels: [
1151
- {
1152
- id: "workspace.generate",
1153
- title: "Generate",
1154
- render: ({ files }) => html`
1155
- <button @click=${async () => {
1156
- const result = await files.writeFile("output/result.txt", "Generated content\n");
1157
- console.log("Wrote", result.path, result.size, "bytes");
1158
- }}>Generate</button>
1159
- `,
1160
- },
1161
- ]
1162
- ```
1163
-
1164
- ### Binary writes
1165
-
1166
- Pass a `Uint8Array` for binary content such as images:
1167
-
1168
- ```js
1169
- const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]);
1170
- await files.writeFile("screenshots/thumb.png", png);
1171
- ```
1172
-
1173
- ### Options
1174
-
1175
- `files.writeFile` accepts an optional third argument:
1176
-
1177
- - `createDirs` (default `true`): create intermediate directories, like `mkdir -p`.
1178
- - `overwrite` (default `true`): overwrite existing files. Set to `false` to throw if the file already exists.
216
+ The current browser contract is **API v4** and the server contract is **API v3**. Older entries need migration; there is no compatibility shim. The public source contracts and their tests are the reference for signatures, validation, limits, and lifecycle details.
1179
217
 
1180
- ```js
1181
- // Create only — throw if the file already exists
1182
- await files.writeFile("config/new-config.json", jsonContent, { overwrite: false });
1183
- ```
1184
-
1185
- ### Deleting files
1186
-
1187
- `files.deleteFile` removes a workspace file. It is idempotent: deleting a file that does not exist returns `{ existed: false }` instead of throwing.
1188
-
1189
- ```js
1190
- const result = await files.deleteFile("temp/cache.json");
1191
- console.log(result.existed ? "File deleted" : "File did not exist");
1192
- ```
1193
-
1194
- ### Moving files
1195
-
1196
- `files.moveFile` renames or moves a file within the workspace, like `mv`. The default is safe: it will not overwrite an existing target file.
1197
-
1198
- ```js
1199
- // Rename a file
1200
- await files.moveFile("old-name.txt", "new-name.txt");
1201
-
1202
- // Move into a subdirectory (creates intermediate dirs by default)
1203
- await files.moveFile("file.txt", "archive/file.txt");
1204
-
1205
- // Overwrite an existing target
1206
- await files.moveFile("incoming.txt", "current.txt", { overwrite: true });
1207
-
1208
- // Move without creating intermediate directories
1209
- await files.moveFile("file.txt", "deep/nested/file.txt", { createDirs: false }); // throws if dirs don't exist
1210
- ```
1211
-
1212
- `files.moveFile` accepts an optional third argument:
1213
-
1214
- - `createDirs` (default `true`): create intermediate directories for the target path.
1215
- - `overwrite` (default `false`): overwrite the target file if it exists. The default is safer than `writeFile` because moving is a more destructive operation.
1216
-
1217
- ### Error handling
1218
-
1219
- All file mutations share the same safety layer:
1220
-
1221
- - `overwrite: false` on `writeFile` or existing target on `moveFile` (default) throws if the file already exists.
1222
- - Path traversal (e.g., `../../etc/passwd`) is blocked by the workspace safety layer.
1223
- - Writing to or moving to a path that is a directory returns an error.
1224
- - Deleting a directory returns an error.
1225
- - Intermediate directory creation with `createDirs: false` fails if the parent directory does not exist.
1226
-
1227
- After any mutation (`writeFile`, `deleteFile`, or `moveFile`), the File Explorer updates automatically. No explicit `refreshFiles()` call is needed from plugin code. For label and badge updates, call `context.host.requestRender()` if the UI should reflect the change.
1228
-
1229
- ### Security
218
+ A few design boundaries matter before implementation:
1230
219
 
1231
- Browser plugin entries are trusted code. File writes go through the same path safety validation as reads — paths are resolved and checked to stay inside the workspace root.
220
+ - Declare entries in `package.json` under `piWeb.plugins`; copy packaging from a standalone example. A package can contain multiple entries.
221
+ - Use only the public package entrypoints. Internal routes, services, and `dist/**` imports are not supported APIs.
222
+ - Keep browser assets in a narrow `browserRoot`: everything inside it is browser-public. Include the built dependencies and assets it needs, and keep secrets outside it. The installed plugin package is limited to 4,096 entries and 16 MiB, excluding `.git` and `node_modules`.
223
+ - Use host helpers for machine/workspace operations and module-relative URLs for plugin assets. Avoid hard-coded application paths.
224
+ - Rendering can happen repeatedly without a panel being mounted again. Own asynchronous state and use ordinary component lifecycle cleanup for connections, timers, and listeners.
225
+ - Keep workspace discovery separate from session-backed features, and keep agent behavior in a Pi companion rather than importing host internals.
1232
226
 
1233
- ## Running workspace terminal commands
227
+ ## Trust and recovery
1234
228
 
1235
- Workspace panels can start terminal commands through the documented `terminal` helper. Commands run in the current workspace on the panel's machine.
229
+ **Install only trusted plugins.** Browser entries run in your page. Server entries run inside the session daemon with its filesystem, environment, and process permissions. They are not sandboxed; blocking or faulty server code can affect every session on that daemon. Timeouts help with cooperative work but cannot stop blocking code.
1236
230
 
1237
- ```js
1238
- render: ({ terminal }) => html`
1239
- <button @click=${() => terminal.runCommand({
1240
- title: "Build",
1241
- command: "npm run build",
1242
- open: true,
1243
- metadata: { "my-plugin.task": "build" },
1244
- })}>Build</button>
1245
- `
1246
- ```
1247
-
1248
- Review command strings carefully. They are trusted shell commands executed in the workspace terminal.
1249
-
1250
- ## Private and experimental PI WEB APIs
1251
-
1252
- PI WEB's `/api/...` HTTP and WebSocket routes, runtime-only browser fields, source files, Fastify instance, and internal services are private implementation details. They are outside the supported browser-v2 and server-v1 package contracts and may change or disappear.
1253
-
1254
- The stable browser API is the documented helpers and the type-only `@jmfederico/pi-web/plugin-api` export; the stable server API is the narrow type-only `@jmfederico/pi-web/server-plugin-api` export. Use `context.backend.request()` for paired browser/server work. If browser code intentionally relies on another private surface, keep that dependency local and expect to revisit it after PI WEB upgrades. A server plugin must not import PI WEB source internals or private `dist/**` declarations.
1255
-
1256
- ## Async data and caching
1257
-
1258
- PI WEB does not provide a plugin cache/invalidation framework. Keep host callbacks cheap:
1259
-
1260
- - simple contributions should be synchronous and cheap;
1261
- - expensive or async work should live inside the plugin;
1262
- - custom elements in `type: "render"` label items or panels are a good place to own async loading;
1263
- - dedupe async reads/commands and avoid unbounded polling;
1264
- - clean up intervals/event listeners in custom elements' `disconnectedCallback()`.
1265
-
1266
- ## Agent implementation checklist
1267
-
1268
- If you are an AI agent building or editing a PI WEB plugin, follow this checklist:
231
+ If a plugin is missing or fails, first check **Settings → PI WEB plugins** on the affected machine. Confirm it is installed, enabled, compatible, and active. Check the browser console for browser failures and `pi-web logs` on the target for server failures. A restart-required or stale state usually needs a session-daemon restart followed by a browser reload.
1269
232
 
1270
- 1. Create or update a package folder with `package.json` and at least one built JavaScript entry. Declare `"type": "module"` when a `.js` server entry is present, or emit it as `.mjs`.
1271
- 2. Use `piWeb.plugins` entries shaped as `{ id, browserRoot?, module?, serverModule?, machineSpecific? }`; declare at least one module, give every browser entry a safe root containing its module, and use non-reserved ids matching `^[a-z][a-z0-9.-]*$`.
1272
- 3. Import browser types only from `@jmfederico/pi-web/plugin-api` and server types only from `@jmfederico/pi-web/server-plugin-api`, always with `import type`; do not use private subpaths or source internals.
1273
- 4. Default-export `{ apiVersion: 2, name, activate }` from a browser entry and `{ apiVersion: 1, name, activate }` from a server entry.
1274
- 5. In a browser entry, use source `pluginId` for ownership and `runtimePluginId` for qualified contribution references; return contributions synchronously and use the activation context's `html`/`svg` tags.
1275
- 6. Add actions for command-palette operations, panels for larger workspace UI, and labels for compact inline metadata.
1276
- 7. Return arrays synchronously from workspace label `items()`; return an empty array to render nothing.
1277
- 8. Use documented browser helpers first: `files`, `terminal`, `backend`, `host.requestRender`, `workspace`, `machine`, `state`, and `prompt`. Never construct PI WEB backend, federation, or absolute asset URLs.
1278
- 9. In a server entry, return only the demonstrated lifecycle callbacks and at most one `workspaceProvider`; treat every supplied `AbortSignal` as operation-scoped and forward it to bounded work.
1279
- 10. Make provider claims conservative. Return exactly one main workspace, stable keys, absolute accessible directories, JSON data/metadata, and optional request/removal capabilities.
1280
- 11. Keep backend operations JSON-only, bounded, and provider-owned. Put no secrets in `publicMetadata`, browser responses, removal wording, or diagnostics.
1281
- 12. Keep the installed package at or below 4,096 entries and 16 MiB, and keep every browser-public file inside a narrow `browserRoot`.
1282
- 13. Treat both entries as trusted code. A server module shares sessiond's process and user permissions.
1283
- 14. For browser-only edits, reload or hard-reload the page. For a server-backed edit, restart sessiond and then reload the page.
1284
- 15. Warn that restarting `pi-web-sessiond.service` may interrupt active sessions/runtime ownership.
233
+ When the UI cannot recover, run these commands on the affected machine:
1285
234
 
1286
- ## Troubleshooting
1287
-
1288
- Check discovery:
1289
-
1290
- ```bash
1291
- curl http://127.0.0.1:8504/pi-web-plugins/manifest.json
235
+ ```sh
236
+ pi-web plugins disable <plugin-id> --restart
237
+ pi-web plugins safe-start show
238
+ pi-web plugins safe-start set bundled-only --restart
239
+ pi-web plugins safe-start set none --restart
240
+ pi-web plugins safe-start clear --restart
1292
241
  ```
1293
242
 
1294
- Check a plugin module:
1295
-
1296
- ```bash
1297
- curl http://127.0.0.1:8504/pi-web-plugins/my-plugin/pi-web-plugin.js
1298
- ```
243
+ - **Disable** keeps a named optional plugin from loading on the next daemon start.
244
+ - **Bundled-only** excludes external server plugins while retaining bundled tools.
245
+ - **None** imports no server plugins. Diagnosis and project-folder workspaces remain available, but Terminal and terminal-backed workflows do not.
246
+ - **Clear** restores ordinary startup after you repair or remove the problem package.
1299
247
 
1300
- Common issues:
1301
-
1302
- - invalid plugin or contribution id;
1303
- - missing default export, browser `apiVersion: 2` or server `apiVersion: 1`, non-empty `name`, or `activate` function;
1304
- - missing `package.json`, incorrect `piWeb.plugins` metadata, neither module declared, missing/unsafe `browserRoot`, a browser module outside its root, a `.js` server entry without `"type": "module"`, or a dual entry explicitly marked `machineSpecific: false`;
1305
- - legacy shortcuts such as `piWeb.plugin`, string plugin entries, or no-`package.json` fallback;
1306
- - duplicate plugin ids; records are diagnosed, skipped rather than merged, and never renamed;
1307
- - entry/root path is unsafe, points outside the package, enters `.git`/`node_modules`, does not exist, or the package exceeds 4,096 entries/16 MiB;
1308
- - package is not installed through Pi or under `$PI_WEB_DATA_DIR/plugins` (`~/.pi-web/plugins` by default);
1309
- - browser import/activation/render failure; check the browser console;
1310
- - server state is failed, incompatible, unhealthy, disabled, missing, stale, or conflicted; check **Settings → PI WEB plugins** and `pi-web logs` on the target machine;
1311
- - a server-backed browser entry is absent because sessiond is unavailable or its active source/settings/revisions do not match desired package state; restart sessiond, then reload the tab;
1312
- - a federated target lacks the lifecycle/backend capability; update and restart PI WEB on that target instead of falling back to the gateway;
1313
- - recovery is needed before plugin discovery/import; use `pi-web plugins safe-start show`, offline disable, or one of the documented safe-start levels.
1314
-
1315
- A manual restart of `pi-web-sessiond.service` may interrupt active sessions/runtime ownership. Inspect active work first and do not assume a web/UI restart is sufficient.
248
+ Safe start remains set until cleared. `--restart` restarts only when PI WEB recognizes a safe installed-service action; otherwise it prints manual instructions. These commands edit configuration without loading plugin code. Use `--config /path/to/config.json` for a non-default configuration, and inspect active work before any restart.