@vincenthanxiaodu/pi-web 1.202608.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 (376) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +185 -0
  3. package/dist/cli.js +1149 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/CodeViewer-D_Q6ljLV.js +4 -0
  7. package/dist/client/assets/TerminalPanel-CTGixJIz.js +187 -0
  8. package/dist/client/assets/index-C2phil_t.js +5637 -0
  9. package/dist/client/assets/vendor-editor-core-CXO8gGab.js +12 -0
  10. package/dist/client/assets/vendor-editor-languages-CpW4sJsX.js +46 -0
  11. package/dist/client/assets/vendor-editor-legacy-CYBnW6ZU.js +1 -0
  12. package/dist/client/assets/vendor-terminal-BrP-ENHg.css +1 -0
  13. package/dist/client/assets/vendor-terminal-D8k4UKM2.js +35 -0
  14. package/dist/client/favicon.svg +11 -0
  15. package/dist/client/index.html +124 -0
  16. package/dist/client/manifest.webmanifest +24 -0
  17. package/dist/client/pwa-icon-192.png +0 -0
  18. package/dist/client/pwa-icon-512.png +0 -0
  19. package/dist/config.js +505 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/docker/piWebDockerCommandPlan.js +212 -0
  22. package/dist/docker/piWebDockerCommandPlan.js.map +1 -0
  23. package/dist/environment.js +4 -0
  24. package/dist/environment.js.map +1 -0
  25. package/dist/nativeServices/installedServiceDefinitions.js +602 -0
  26. package/dist/nativeServices/installedServiceDefinitions.js.map +1 -0
  27. package/dist/nativeServices/serviceAction.js +174 -0
  28. package/dist/nativeServices/serviceAction.js.map +1 -0
  29. package/dist/nativeServices/serviceDoctor.js +783 -0
  30. package/dist/nativeServices/serviceDoctor.js.map +1 -0
  31. package/dist/nativeServices/serviceInstall.js +35 -0
  32. package/dist/nativeServices/serviceInstall.js.map +1 -0
  33. package/dist/nativeServices/servicePlan.js +358 -0
  34. package/dist/nativeServices/servicePlan.js.map +1 -0
  35. package/dist/nativeServices/serviceProbe.js +447 -0
  36. package/dist/nativeServices/serviceProbe.js.map +1 -0
  37. package/dist/nativeServices/serviceRendering.js +132 -0
  38. package/dist/nativeServices/serviceRendering.js.map +1 -0
  39. package/dist/pi-web-plugins/git/browser/git-contract.js +108 -0
  40. package/dist/pi-web-plugins/git/browser/git-panel.js +609 -0
  41. package/dist/pi-web-plugins/git/browser/gitFileList.js +43 -0
  42. package/dist/pi-web-plugins/git/browser/gitFileShared.js +16 -0
  43. package/dist/pi-web-plugins/git/browser/gitFileTree.js +81 -0
  44. package/dist/pi-web-plugins/git/browser/gitFileViewPreference.js +35 -0
  45. package/dist/pi-web-plugins/git/browser/gitRoute.js +42 -0
  46. package/dist/pi-web-plugins/git/browser/pi-web-plugin.js +10 -0
  47. package/dist/pi-web-plugins/git/browser/unifiedDiff.js +301 -0
  48. package/dist/pi-web-plugins/git/git-backend.js +439 -0
  49. package/dist/pi-web-plugins/git/package.json +16 -0
  50. package/dist/pi-web-plugins/git/server-plugin.js +176 -0
  51. package/dist/pi-web-plugins/info/infoInternals.js +222 -0
  52. package/dist/pi-web-plugins/info/package.json +9 -0
  53. package/dist/pi-web-plugins/info/pi-web-plugin.js +48 -0
  54. package/dist/pi-web-plugins/relays/markdownDocument.js +81 -0
  55. package/dist/pi-web-plugins/relays/package.json +9 -0
  56. package/dist/pi-web-plugins/relays/pi-web-plugin.js +44 -0
  57. package/dist/pi-web-plugins/relays/relayDiscovery.js +228 -0
  58. package/dist/pi-web-plugins/relays/relaysPanelElement.js +550 -0
  59. package/dist/pi-web-plugins/relays/vendor/README.md +24 -0
  60. package/dist/pi-web-plugins/relays/vendor/marked.esm.js +76 -0
  61. package/dist/pi-web-plugins/updates/package.json +9 -0
  62. package/dist/pi-web-plugins/updates/pi-web-plugin.js +185 -0
  63. package/dist/pi-web-plugins/updates/updatesLogic.js +97 -0
  64. package/dist/pi-web-plugins/workspace-tasks/config.js +91 -0
  65. package/dist/pi-web-plugins/workspace-tasks/package.json +9 -0
  66. package/dist/pi-web-plugins/workspace-tasks/pi-web-plugin.js +48 -0
  67. package/dist/pi-web-plugins/workspace-tasks/taskRunner.js +12 -0
  68. package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +288 -0
  69. package/dist/pi-web-plugins/workspace-tasks/workspaceTasksClient.js +47 -0
  70. package/dist/piWebVersionReport.js +278 -0
  71. package/dist/piWebVersionReport.js.map +1 -0
  72. package/dist/plugin-api.d.ts +222 -0
  73. package/dist/pluginRecoveryCli.js +172 -0
  74. package/dist/pluginRecoveryCli.js.map +1 -0
  75. package/dist/server/activeAgentProfileProvider.js +25 -0
  76. package/dist/server/activeAgentProfileProvider.js.map +1 -0
  77. package/dist/server/activity/workspaceActivityService.js +106 -0
  78. package/dist/server/activity/workspaceActivityService.js.map +1 -0
  79. package/dist/server/app.js +218 -0
  80. package/dist/server/app.js.map +1 -0
  81. package/dist/server/browserMessageProjection.js +54 -0
  82. package/dist/server/browserMessageProjection.js.map +1 -0
  83. package/dist/server/configRoutes.js +293 -0
  84. package/dist/server/configRoutes.js.map +1 -0
  85. package/dist/server/diagnostics/nodePtyNativeModule.js +36 -0
  86. package/dist/server/diagnostics/nodePtyNativeModule.js.map +1 -0
  87. package/dist/server/diagnostics/nodePtySpawnHelper.js +135 -0
  88. package/dist/server/diagnostics/nodePtySpawnHelper.js.map +1 -0
  89. package/dist/server/git/gitEnv.js +15 -0
  90. package/dist/server/git/gitEnv.js.map +1 -0
  91. package/dist/server/goals/goalArchive.js +184 -0
  92. package/dist/server/goals/goalArchive.js.map +1 -0
  93. package/dist/server/goals/goalFile.js +200 -0
  94. package/dist/server/goals/goalFile.js.map +1 -0
  95. package/dist/server/goals/goalStore.js +65 -0
  96. package/dist/server/goals/goalStore.js.map +1 -0
  97. package/dist/server/index.js +7 -0
  98. package/dist/server/index.js.map +1 -0
  99. package/dist/server/machines/machineClient.js +191 -0
  100. package/dist/server/machines/machineClient.js.map +1 -0
  101. package/dist/server/machines/machinePluginProxyRoutes.js +247 -0
  102. package/dist/server/machines/machinePluginProxyRoutes.js.map +1 -0
  103. package/dist/server/machines/machineProxyRoutes.js +318 -0
  104. package/dist/server/machines/machineProxyRoutes.js.map +1 -0
  105. package/dist/server/machines/machineRoutes.js +56 -0
  106. package/dist/server/machines/machineRoutes.js.map +1 -0
  107. package/dist/server/machines/machineService.js +274 -0
  108. package/dist/server/machines/machineService.js.map +1 -0
  109. package/dist/server/machines/machineStore.js +143 -0
  110. package/dist/server/machines/machineStore.js.map +1 -0
  111. package/dist/server/piPackageRoutes.js +91 -0
  112. package/dist/server/piPackageRoutes.js.map +1 -0
  113. package/dist/server/piPackageService.js +101 -0
  114. package/dist/server/piPackageService.js.map +1 -0
  115. package/dist/server/piWebPluginCatalog.js +584 -0
  116. package/dist/server/piWebPluginCatalog.js.map +1 -0
  117. package/dist/server/piWebPluginLifecycle.js +162 -0
  118. package/dist/server/piWebPluginLifecycle.js.map +1 -0
  119. package/dist/server/piWebPluginService.js +224 -0
  120. package/dist/server/piWebPluginService.js.map +1 -0
  121. package/dist/server/piWebReleaseLookupCache.js +37 -0
  122. package/dist/server/piWebReleaseLookupCache.js.map +1 -0
  123. package/dist/server/piWebStatus.js +624 -0
  124. package/dist/server/piWebStatus.js.map +1 -0
  125. package/dist/server/piWebStatusCache.js +45 -0
  126. package/dist/server/piWebStatusCache.js.map +1 -0
  127. package/dist/server/plugins/pluginBackendProxyRoutes.js +69 -0
  128. package/dist/server/plugins/pluginBackendProxyRoutes.js.map +1 -0
  129. package/dist/server/plugins/serverPluginExec.js +184 -0
  130. package/dist/server/plugins/serverPluginExec.js.map +1 -0
  131. package/dist/server/plugins/serverPluginRuntime.js +480 -0
  132. package/dist/server/plugins/serverPluginRuntime.js.map +1 -0
  133. package/dist/server/projectTrustRoutes.js +80 -0
  134. package/dist/server/projectTrustRoutes.js.map +1 -0
  135. package/dist/server/projects/directorySuggestions.js +207 -0
  136. package/dist/server/projects/directorySuggestions.js.map +1 -0
  137. package/dist/server/projects/projectService.js +33 -0
  138. package/dist/server/projects/projectService.js.map +1 -0
  139. package/dist/server/realtime/sessionEventHub.js +93 -0
  140. package/dist/server/realtime/sessionEventHub.js.map +1 -0
  141. package/dist/server/requestCancellation.js +32 -0
  142. package/dist/server/requestCancellation.js.map +1 -0
  143. package/dist/server/sessiond/agentHttpDispatcher.js +108 -0
  144. package/dist/server/sessiond/agentHttpDispatcher.js.map +1 -0
  145. package/dist/server/sessiond/agentProcessEnvironment.js +61 -0
  146. package/dist/server/sessiond/agentProcessEnvironment.js.map +1 -0
  147. package/dist/server/sessiond/pluginBackendRoutes.js +64 -0
  148. package/dist/server/sessiond/pluginBackendRoutes.js.map +1 -0
  149. package/dist/server/sessiond/sessionDaemonShutdown.js +31 -0
  150. package/dist/server/sessiond/sessionDaemonShutdown.js.map +1 -0
  151. package/dist/server/sessiond/sessionProxyRoutes.js +61 -0
  152. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -0
  153. package/dist/server/sessiond/sessionServiceDependencies.js +34 -0
  154. package/dist/server/sessiond/sessionServiceDependencies.js.map +1 -0
  155. package/dist/server/sessiond/sessiondStateOwnership.js +235 -0
  156. package/dist/server/sessiond/sessiondStateOwnership.js.map +1 -0
  157. package/dist/server/sessiond/workspaceCatalogRoutes.js +31 -0
  158. package/dist/server/sessiond/workspaceCatalogRoutes.js.map +1 -0
  159. package/dist/server/sessiond/workspaceRemovalRoutes.js +41 -0
  160. package/dist/server/sessiond/workspaceRemovalRoutes.js.map +1 -0
  161. package/dist/server/sessiond.js +387 -0
  162. package/dist/server/sessiond.js.map +1 -0
  163. package/dist/server/sessions/askUserTool.js +102 -0
  164. package/dist/server/sessions/askUserTool.js.map +1 -0
  165. package/dist/server/sessions/attachmentService.js +119 -0
  166. package/dist/server/sessions/attachmentService.js.map +1 -0
  167. package/dist/server/sessions/authProviderOptions.js +50 -0
  168. package/dist/server/sessions/authProviderOptions.js.map +1 -0
  169. package/dist/server/sessions/authRoutes.js +59 -0
  170. package/dist/server/sessions/authRoutes.js.map +1 -0
  171. package/dist/server/sessions/authService.js +122 -0
  172. package/dist/server/sessions/authService.js.map +1 -0
  173. package/dist/server/sessions/builtinCommands.js +27 -0
  174. package/dist/server/sessions/builtinCommands.js.map +1 -0
  175. package/dist/server/sessions/dockerEnvironmentFacts.js +254 -0
  176. package/dist/server/sessions/dockerEnvironmentFacts.js.map +1 -0
  177. package/dist/server/sessions/editPreview.js +196 -0
  178. package/dist/server/sessions/editPreview.js.map +1 -0
  179. package/dist/server/sessions/extensionDialogWaiters.js +76 -0
  180. package/dist/server/sessions/extensionDialogWaiters.js.map +1 -0
  181. package/dist/server/sessions/globalProviderPolicy.js +167 -0
  182. package/dist/server/sessions/globalProviderPolicy.js.map +1 -0
  183. package/dist/server/sessions/interruptedRunStore.js +147 -0
  184. package/dist/server/sessions/interruptedRunStore.js.map +1 -0
  185. package/dist/server/sessions/messagePaging.js +43 -0
  186. package/dist/server/sessions/messagePaging.js.map +1 -0
  187. package/dist/server/sessions/modelCatalogRefresher.js +193 -0
  188. package/dist/server/sessions/modelCatalogRefresher.js.map +1 -0
  189. package/dist/server/sessions/oauthLoginFlowService.js +346 -0
  190. package/dist/server/sessions/oauthLoginFlowService.js.map +1 -0
  191. package/dist/server/sessions/pendingAskStore.js +275 -0
  192. package/dist/server/sessions/pendingAskStore.js.map +1 -0
  193. package/dist/server/sessions/pendingExtensionDialogStore.js +196 -0
  194. package/dist/server/sessions/pendingExtensionDialogStore.js.map +1 -0
  195. package/dist/server/sessions/piSessionManagerGateway.js +246 -0
  196. package/dist/server/sessions/piSessionManagerGateway.js.map +1 -0
  197. package/dist/server/sessions/piSessionService.js +4059 -0
  198. package/dist/server/sessions/piSessionService.js.map +1 -0
  199. package/dist/server/sessions/plainTextTheme.js +112 -0
  200. package/dist/server/sessions/plainTextTheme.js.map +1 -0
  201. package/dist/server/sessions/sessionArchiveStore.js +273 -0
  202. package/dist/server/sessions/sessionArchiveStore.js.map +1 -0
  203. package/dist/server/sessions/sessionArchiveTree.js +35 -0
  204. package/dist/server/sessions/sessionArchiveTree.js.map +1 -0
  205. package/dist/server/sessions/sessionCleanup.js +157 -0
  206. package/dist/server/sessions/sessionCleanup.js.map +1 -0
  207. package/dist/server/sessions/sessionCommandService.js +336 -0
  208. package/dist/server/sessions/sessionCommandService.js.map +1 -0
  209. package/dist/server/sessions/sessionEnvironmentFacts.js +48 -0
  210. package/dist/server/sessions/sessionEnvironmentFacts.js.map +1 -0
  211. package/dist/server/sessions/sessionFileFormat.js +27 -0
  212. package/dist/server/sessions/sessionFileFormat.js.map +1 -0
  213. package/dist/server/sessions/sessionFileHeader.js +104 -0
  214. package/dist/server/sessions/sessionFileHeader.js.map +1 -0
  215. package/dist/server/sessions/sessionModelScope.js +141 -0
  216. package/dist/server/sessions/sessionModelScope.js.map +1 -0
  217. package/dist/server/sessions/sessionNameGenerator.js +90 -0
  218. package/dist/server/sessions/sessionNameGenerator.js.map +1 -0
  219. package/dist/server/sessions/sessionNotificationStore.js +484 -0
  220. package/dist/server/sessions/sessionNotificationStore.js.map +1 -0
  221. package/dist/server/sessions/sessionRoutes.js +744 -0
  222. package/dist/server/sessions/sessionRoutes.js.map +1 -0
  223. package/dist/server/sessions/sessionRuntimeStore.js +2 -0
  224. package/dist/server/sessions/sessionRuntimeStore.js.map +1 -0
  225. package/dist/server/sessions/sessionService.js +2 -0
  226. package/dist/server/sessions/sessionService.js.map +1 -0
  227. package/dist/server/sessions/sessionSummaryScanner.js +491 -0
  228. package/dist/server/sessions/sessionSummaryScanner.js.map +1 -0
  229. package/dist/server/sessions/sessionTreeProjection.js +250 -0
  230. package/dist/server/sessions/sessionTreeProjection.js.map +1 -0
  231. package/dist/server/sessions/sessionUnreadStore.js +520 -0
  232. package/dist/server/sessions/sessionUnreadStore.js.map +1 -0
  233. package/dist/server/sessions/shutdownDrain.js +73 -0
  234. package/dist/server/sessions/shutdownDrain.js.map +1 -0
  235. package/dist/server/sessions/spawnSessionTool.js +48 -0
  236. package/dist/server/sessions/spawnSessionTool.js.map +1 -0
  237. package/dist/server/sessions/spawnSubsessionTool.js +216 -0
  238. package/dist/server/sessions/spawnSubsessionTool.js.map +1 -0
  239. package/dist/server/sessions/spawnTargetResolver.js +23 -0
  240. package/dist/server/sessions/spawnTargetResolver.js.map +1 -0
  241. package/dist/server/sessions/subsessionTranscript.js +235 -0
  242. package/dist/server/sessions/subsessionTranscript.js.map +1 -0
  243. package/dist/server/status/machineStatusRoutes.js +8 -0
  244. package/dist/server/status/machineStatusRoutes.js.map +1 -0
  245. package/dist/server/status/machineStatusService.js +181 -0
  246. package/dist/server/status/machineStatusService.js.map +1 -0
  247. package/dist/server/status/workspaceAttribution.js +87 -0
  248. package/dist/server/status/workspaceAttribution.js.map +1 -0
  249. package/dist/server/storage/projectStore.js +88 -0
  250. package/dist/server/storage/projectStore.js.map +1 -0
  251. package/dist/server/terminalProxyRoutes.js +141 -0
  252. package/dist/server/terminalProxyRoutes.js.map +1 -0
  253. package/dist/server/terminals/terminalRoutes.js +155 -0
  254. package/dist/server/terminals/terminalRoutes.js.map +1 -0
  255. package/dist/server/terminals/terminalService.js +305 -0
  256. package/dist/server/terminals/terminalService.js.map +1 -0
  257. package/dist/server/terminals/terminalSize.js +17 -0
  258. package/dist/server/terminals/terminalSize.js.map +1 -0
  259. package/dist/server/types.js +2 -0
  260. package/dist/server/types.js.map +1 -0
  261. package/dist/server/updates/fleetRoutes.js +111 -0
  262. package/dist/server/updates/fleetRoutes.js.map +1 -0
  263. package/dist/server/updates/restartRoutes.js +48 -0
  264. package/dist/server/updates/restartRoutes.js.map +1 -0
  265. package/dist/server/updates/selfUpdateRoutes.js +145 -0
  266. package/dist/server/updates/selfUpdateRoutes.js.map +1 -0
  267. package/dist/server/webSocketBridge.js +32 -0
  268. package/dist/server/webSocketBridge.js.map +1 -0
  269. package/dist/server/workingDirectory.js +44 -0
  270. package/dist/server/workingDirectory.js.map +1 -0
  271. package/dist/server/workspaceExplorerRoutes.js +147 -0
  272. package/dist/server/workspaceExplorerRoutes.js.map +1 -0
  273. package/dist/server/workspaces/effectivePathAccess.js +8 -0
  274. package/dist/server/workspaces/effectivePathAccess.js.map +1 -0
  275. package/dist/server/workspaces/fileContentService.js +190 -0
  276. package/dist/server/workspaces/fileContentService.js.map +1 -0
  277. package/dist/server/workspaces/filePreviewResponseHeaders.js +18 -0
  278. package/dist/server/workspaces/filePreviewResponseHeaders.js.map +1 -0
  279. package/dist/server/workspaces/filePreviewResponsePolicy.js +55 -0
  280. package/dist/server/workspaces/filePreviewResponsePolicy.js.map +1 -0
  281. package/dist/server/workspaces/filePreviewService.js +81 -0
  282. package/dist/server/workspaces/filePreviewService.js.map +1 -0
  283. package/dist/server/workspaces/fileSuggestions.js +520 -0
  284. package/dist/server/workspaces/fileSuggestions.js.map +1 -0
  285. package/dist/server/workspaces/fileTreeService.js +35 -0
  286. package/dist/server/workspaces/fileTreeService.js.map +1 -0
  287. package/dist/server/workspaces/pathAccessPolicy.js +90 -0
  288. package/dist/server/workspaces/pathAccessPolicy.js.map +1 -0
  289. package/dist/server/workspaces/pathSafety.js +45 -0
  290. package/dist/server/workspaces/pathSafety.js.map +1 -0
  291. package/dist/server/workspaces/projectPiWebConfig.js +61 -0
  292. package/dist/server/workspaces/projectPiWebConfig.js.map +1 -0
  293. package/dist/server/workspaces/projectWorkspaceCwds.js +17 -0
  294. package/dist/server/workspaces/projectWorkspaceCwds.js.map +1 -0
  295. package/dist/server/workspaces/sessionDaemonWorkspaceCatalog.js +402 -0
  296. package/dist/server/workspaces/sessionDaemonWorkspaceCatalog.js.map +1 -0
  297. package/dist/server/workspaces/workspaceCatalog.js +47 -0
  298. package/dist/server/workspaces/workspaceCatalog.js.map +1 -0
  299. package/dist/server/workspaces/workspaceContext.js +6 -0
  300. package/dist/server/workspaces/workspaceContext.js.map +1 -0
  301. package/dist/server/workspaces/workspaceDeletionRoutes.js +49 -0
  302. package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -0
  303. package/dist/server/workspaces/workspaceProviderRegistry.js +651 -0
  304. package/dist/server/workspaces/workspaceProviderRegistry.js.map +1 -0
  305. package/dist/server/workspaces/workspaceRemovalService.js +256 -0
  306. package/dist/server/workspaces/workspaceRemovalService.js.map +1 -0
  307. package/dist/server/workspaces/workspaceRouteErrors.js +7 -0
  308. package/dist/server/workspaces/workspaceRouteErrors.js.map +1 -0
  309. package/dist/server/workspaces/worktreePreRemoveHook.js +39 -0
  310. package/dist/server/workspaces/worktreePreRemoveHook.js.map +1 -0
  311. package/dist/server-plugin-api.d.ts +140 -0
  312. package/dist/server-plugin-api.js +2 -0
  313. package/dist/server-plugin-api.js.map +1 -0
  314. package/dist/serverPluginRecovery.js +138 -0
  315. package/dist/serverPluginRecovery.js.map +1 -0
  316. package/dist/sessiond/activeAgentProfile.js +12 -0
  317. package/dist/sessiond/activeAgentProfile.js.map +1 -0
  318. package/dist/sessiond/config.js +20 -0
  319. package/dist/sessiond/config.js.map +1 -0
  320. package/dist/sessiond/sessionDaemonClient.js +105 -0
  321. package/dist/sessiond/sessionDaemonClient.js.map +1 -0
  322. package/dist/shared/activeAgentProfile.js +37 -0
  323. package/dist/shared/activeAgentProfile.js.map +1 -0
  324. package/dist/shared/activity.js +16 -0
  325. package/dist/shared/activity.js.map +1 -0
  326. package/dist/shared/apiTypes.js +41 -0
  327. package/dist/shared/apiTypes.js.map +1 -0
  328. package/dist/shared/capabilities.js +37 -0
  329. package/dist/shared/capabilities.js.map +1 -0
  330. package/dist/shared/federatedRoutes.js +127 -0
  331. package/dist/shared/federatedRoutes.js.map +1 -0
  332. package/dist/shared/machinePluginIds.js +43 -0
  333. package/dist/shared/machinePluginIds.js.map +1 -0
  334. package/dist/shared/machineStatus.js +94 -0
  335. package/dist/shared/machineStatus.js.map +1 -0
  336. package/dist/shared/piWebStatusParsing.js +141 -0
  337. package/dist/shared/piWebStatusParsing.js.map +1 -0
  338. package/dist/shared/pluginApiTypes.d.ts +150 -0
  339. package/dist/shared/pluginApiTypes.js +3 -0
  340. package/dist/shared/pluginApiTypes.js.map +1 -0
  341. package/dist/shared/pluginBackendProtocol.js +110 -0
  342. package/dist/shared/pluginBackendProtocol.js.map +1 -0
  343. package/dist/shared/pluginIds.js +10 -0
  344. package/dist/shared/pluginIds.js.map +1 -0
  345. package/dist/shared/pluginRecoveryCommands.js +14 -0
  346. package/dist/shared/pluginRecoveryCommands.js.map +1 -0
  347. package/dist/shared/promptAttachments.js +92 -0
  348. package/dist/shared/promptAttachments.js.map +1 -0
  349. package/dist/shared/selfUpdate.js +3 -0
  350. package/dist/shared/selfUpdate.js.map +1 -0
  351. package/dist/shared/thinkingLevels.js +31 -0
  352. package/dist/shared/thinkingLevels.js.map +1 -0
  353. package/dist/shared/workspaceDeletion.js +12 -0
  354. package/dist/shared/workspaceDeletion.js.map +1 -0
  355. package/dist/shared/workspaceFiles.js +42 -0
  356. package/dist/shared/workspaceFiles.js.map +1 -0
  357. package/dist/shared/workspaceRemovalProtocol.js +24 -0
  358. package/dist/shared/workspaceRemovalProtocol.js.map +1 -0
  359. package/docs/assets/favicon.svg +11 -0
  360. package/docs/assets/pi-web-banner.png +0 -0
  361. package/docs/assets/pi-web-desktop.png +0 -0
  362. package/docs/assets/pi-web-mobile.png +0 -0
  363. package/docs/assets/pi-web-tablet.png +0 -0
  364. package/docs/config.md +444 -0
  365. package/docs/plugins.md +1305 -0
  366. package/examples/workspace-provider-plugin/README.md +52 -0
  367. package/examples/workspace-provider-plugin/package.json +25 -0
  368. package/examples/workspace-provider-plugin/src/browser/index.ts +69 -0
  369. package/examples/workspace-provider-plugin/src/server.ts +64 -0
  370. package/examples/workspace-provider-plugin/tsconfig.json +21 -0
  371. package/extensions/README-pi-web-restart-migration.md +45 -0
  372. package/extensions/pi-web.ts +324 -0
  373. package/install.sh +5 -0
  374. package/package.json +173 -0
  375. package/plugin-api.d.ts +1 -0
  376. package/server-plugin-api.d.ts +1 -0
@@ -0,0 +1,1305 @@
1
+ # PI WEB plugin API
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.
4
+
5
+ Plugins can currently:
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.
14
+
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
+ 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.
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ 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).
32
+
33
+ ## Pi extension dialogs in PI WEB
34
+
35
+ 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.
36
+
37
+ - **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.
38
+ - **`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.
39
+ - **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.
40
+ - **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.
41
+ - **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.
42
+ - **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.
43
+ - **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.
44
+
45
+ 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.
46
+
47
+ ## Trust model
48
+
49
+ Treat every plugin package as trusted code:
50
+
51
+ - browser entries can call browser APIs, read workspace files, start terminal commands through helpers, and render arbitrary UI;
52
+ - 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;
53
+ - 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;
54
+ - 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;
55
+ - plugins should not be installed from untrusted sources.
56
+
57
+ 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 `@vincenthanxiaodu/pi-web/server-plugin-api`. Private routes, runtime objects, and source-internal imports are experimental and may change or disappear.
58
+
59
+ ## Workspace providers and replacement ownership
60
+
61
+ Sessiond is the single authority for project workspace discovery and spawned-session target validation. One active plugin exclusively owns a project's workspace semantics:
62
+
63
+ 1. Healthy or degraded primary providers probe first.
64
+ 2. If exactly one primary returns `"claim"`, it owns the project.
65
+ 3. If no primary claims, fallback providers probe. Bundled Git is a fallback provider.
66
+ 4. Multiple claimants in the winning tier produce a visible conflict; PI WEB does not select by plugin id or import order.
67
+ 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.
68
+
69
+ 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.
70
+
71
+ ## What to ask AI to build
72
+
73
+ 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.
74
+
75
+ Good plugin requests:
76
+
77
+ - "Show a workspace badge with the dev server URL from `.env`."
78
+ - "Add a workspace panel with links to logs, dashboards, and local services for this repo."
79
+ - "Add an action-palette command that starts a standard code-review prompt."
80
+ - "Show whether the current workspace is a git worktree, main checkout, staging env, or feature branch."
81
+ - "Add a compact status badge based on a project health file or command output saved in the repo."
82
+
83
+ Copy-paste prompt for creating a plugin:
84
+
85
+ ```text
86
+ Build a PI WEB plugin for this project.
87
+ Goal: <describe the UI behavior>.
88
+ Before coding, read the PI WEB plugin docs:
89
+ https://pi-web.dev/plugins
90
+ Full API reference:
91
+ https://pi-web.dev/plugins.md
92
+ Create it as a local plugin under ~/.pi-web/plugins/<plugin-id>.
93
+ Use the appropriate extension points from the docs.
94
+ Validate by checking /pi-web-plugins/manifest.json and explain how to reload/debug it.
95
+ Do not modify PI WEB itself.
96
+ ```
97
+
98
+ Copy-paste prompt for modifying a plugin:
99
+
100
+ ```text
101
+ Improve the PI WEB plugin at <path>.
102
+ Before coding, read the PI WEB plugin docs:
103
+ https://pi-web.dev/plugins
104
+ Full API reference:
105
+ https://pi-web.dev/plugins.md
106
+ Keep the browser entry on API v2 and any server entry on API v1.
107
+ After editing, check the manifest endpoint and browser-console failure cases.
108
+ ```
109
+
110
+ ## Canonical example: bundled Info plugin
111
+
112
+ 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.
113
+
114
+ 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.
115
+
116
+ Source files:
117
+
118
+ ```text
119
+ pi-web-plugins/info/package.json
120
+ pi-web-plugins/info/pi-web-plugin.ts
121
+ pi-web-plugins/info/infoInternals.ts
122
+ ```
123
+
124
+ `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.
125
+
126
+ Built module:
127
+
128
+ ```text
129
+ dist/pi-web-plugins/info/pi-web-plugin.js
130
+ ```
131
+
132
+ Package metadata:
133
+
134
+ ```json
135
+ {
136
+ "name": "@pi-web/info-plugin",
137
+ "private": true,
138
+ "piWeb": {
139
+ "plugins": [
140
+ { "id": "info", "browserRoot": ".", "module": "pi-web-plugin.js" }
141
+ ]
142
+ }
143
+ }
144
+ ```
145
+
146
+ Module shape excerpt:
147
+
148
+ ```js
149
+ export default {
150
+ apiVersion: 2,
151
+ name: "Info Plugin",
152
+ activate: ({ html, svg }) => ({
153
+ contributions: {
154
+ actions: [/* action definitions */],
155
+ workspaceLabels: [/* compact label definitions */],
156
+ workspacePanels: [/* panel definitions using html, optional icons using svg */],
157
+ },
158
+ }),
159
+ };
160
+ ```
161
+
162
+ When copying the Info plugin, choose a new plugin id so it does not conflict with the bundled `info` plugin.
163
+
164
+ 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.
165
+
166
+ 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.
167
+
168
+ ## Canonical dual-entry provider: bundled Git
169
+
170
+ 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:
171
+
172
+ ```text
173
+ pi-web-plugins/git/package.json
174
+ pi-web-plugins/git/browser/pi-web-plugin.ts
175
+ pi-web-plugins/git/server-plugin.ts
176
+ ```
177
+
178
+ 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.
179
+
180
+ Its TypeScript entries import declarations only from the published package subpaths:
181
+
182
+ ```ts
183
+ import type { PiWebPlugin } from "@vincenthanxiaodu/pi-web/plugin-api";
184
+ import type { PiWebServerPlugin, WorkspaceProvider } from "@vincenthanxiaodu/pi-web/server-plugin-api";
185
+ ```
186
+
187
+ 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.
188
+
189
+ ## Copyable standalone workspace-provider example
190
+
191
+ 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.
192
+
193
+ 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.
194
+
195
+ Copy the example from a checkout or from `node_modules/@vincenthanxiaodu/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.
196
+
197
+ ## Local plugin usage
198
+
199
+ 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.
200
+
201
+ Symlink a plugin folder into PI WEB's local plugin directory:
202
+
203
+ ```bash
204
+ mkdir -p ~/.pi-web/plugins
205
+ ln -s /path/to/plugin-folder ~/.pi-web/plugins/plugin-id
206
+ ```
207
+
208
+ 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.
209
+
210
+ ## Remote machine plugins
211
+
212
+ 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:
213
+
214
+ - actions, workspace panels, and workspace labels appear only for the applicable selected machine;
215
+ - file and terminal helpers run against that machine;
216
+ - `context.backend.request()` is routed through the gateway to the current workspace owner on that machine;
217
+ - 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;
218
+ - 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;
219
+ - remote theme contributions are ignored for now because themes are app-wide.
220
+
221
+ 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.
222
+
223
+ 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.
224
+
225
+ 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.
226
+
227
+ Plugin package metadata may set `machineSpecific: true` when the plugin's meaning is tied to the selected PI WEB machine:
228
+
229
+ - Omitted or `false`: valid for browser-only plugins; use the gateway copy when the same id is present remotely.
230
+ - `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.
231
+
232
+ For portable plugin assets, prefer URLs relative to the plugin module:
233
+
234
+ ```js
235
+ const url = new URL("./asset.json", import.meta.url);
236
+ ```
237
+
238
+ 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.
239
+
240
+ 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.
241
+
242
+ ## Manage PI WEB plugins
243
+
244
+ 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.
245
+
246
+ 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.
247
+
248
+ ```json
249
+ {
250
+ "plugins": {
251
+ "git": {
252
+ "enabled": true,
253
+ "settings": {}
254
+ },
255
+ "info": {
256
+ "enabled": false
257
+ }
258
+ }
259
+ }
260
+ ```
261
+
262
+ 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.
263
+
264
+ ### Desired versus active state
265
+
266
+ 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.
267
+
268
+ Use this sequence:
269
+
270
+ 1. Install or update the package on the target machine.
271
+ 2. Set the desired plugin enablement/settings.
272
+ 3. For a browser-only plugin, reload the browser tab.
273
+ 4. For a server-backed plugin, manually restart sessiond, wait for it to become available, then reload the browser tab.
274
+
275
+ > **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.
276
+
277
+ ### Offline disable and safe start
278
+
279
+ 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`.
280
+
281
+ ```bash
282
+ pi-web plugins disable <plugin-id> --restart
283
+ pi-web plugins safe-start show
284
+ pi-web plugins safe-start set bundled-only --restart
285
+ pi-web plugins safe-start set none --restart
286
+ pi-web plugins safe-start clear --restart
287
+ ```
288
+
289
+ - `disable` sets that plugin's desired `enabled` value to `false` while preserving unrelated config.
290
+ - `bundled-only` persists safe start and filters discovery before external local or Pi-package server modules are considered.
291
+ - `none` persists the emergency level and imports no server plugins; the kernel folder workspace remains available.
292
+ - `clear` returns the next startup to ordinary configured discovery.
293
+ - `--restart` requests an automatic restart only when PI WEB recognizes a safe installed-service action. Otherwise the command prints manual guidance.
294
+
295
+ 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.
296
+
297
+ 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.
298
+
299
+ ## Built-in plugins
300
+
301
+ PI WEB ships core, discoverable plugins in the main `@vincenthanxiaodu/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.
302
+
303
+ Built-in plugins can be managed from **Settings → PI WEB plugins** or with the top-level `plugins` config key.
304
+
305
+ ### Git
306
+
307
+ **Plugin id:** `git`
308
+ **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.
309
+
310
+ 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.
311
+
312
+ ### Updates
313
+
314
+ **Plugin id:** `updates`
315
+ **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.
316
+
317
+ 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.
318
+
319
+ 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:
320
+
321
+ ```json
322
+ {
323
+ "plugins": {
324
+ "updates": { "enabled": false }
325
+ }
326
+ }
327
+ ```
328
+
329
+ ### Workspace Tasks
330
+
331
+ **Plugin id:** `workspace-tasks`
332
+ **Config file:** `.pi-web/tasks.json`
333
+ **What it does:** adds a **Tasks** workspace tab for running configured shell commands in dedicated PI WEB terminals.
334
+
335
+ Workspace Tasks is enabled by default. To hide it, disable `workspace-tasks` in **Settings → PI WEB plugins** or set:
336
+
337
+ ```json
338
+ {
339
+ "plugins": {
340
+ "workspace-tasks": { "enabled": false }
341
+ }
342
+ }
343
+ ```
344
+
345
+ Configure workspace tasks in `.pi-web/tasks.json`:
346
+
347
+ ```json
348
+ {
349
+ "version": 1,
350
+ "tasks": [
351
+ {
352
+ "id": "app.start",
353
+ "title": "Start app",
354
+ "group": "Development",
355
+ "description": "Start the local development server.",
356
+ "command": "npm run dev"
357
+ },
358
+ {
359
+ "id": "db.reset",
360
+ "title": "Reset DB",
361
+ "group": "Database",
362
+ "command": "go -C klingit-go run ./cli db reset",
363
+ "confirm": true
364
+ }
365
+ ]
366
+ }
367
+ ```
368
+
369
+ 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.
370
+
371
+ Task fields:
372
+
373
+ - `version`: must be `1`.
374
+ - `tasks`: array of task definitions.
375
+ - `id`: stable task id, matching `^[a-z][a-z0-9.-]*$`.
376
+ - `title`: button label.
377
+ - `command`: literal shell command sent to the terminal.
378
+ - `description`: optional explanatory text.
379
+ - `group`: optional group heading.
380
+ - `confirm`: optional boolean. When true, the browser asks before dispatching the command.
381
+
382
+ Review task configs before running them, especially in shared projects. Workspace Tasks runs trusted shell commands from your repositories.
383
+
384
+ ### Relays
385
+
386
+ **Plugin id:** `relays`
387
+ **What it does:** 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.
388
+
389
+ 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.
390
+
391
+ 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.
392
+
393
+ 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.
394
+
395
+ Relays is enabled by default. To hide it, disable `relays` in **Settings → PI WEB plugins** or set:
396
+
397
+ ```json
398
+ {
399
+ "plugins": {
400
+ "relays": { "enabled": false }
401
+ }
402
+ }
403
+ ```
404
+
405
+ ## Discovery and packaging
406
+
407
+ 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`:
408
+
409
+ 1. Bundled plugins in the PI WEB package:
410
+
411
+ ```text
412
+ pi-web-plugins/<plugin-package>/
413
+ ```
414
+
415
+ 2. User-local plugins:
416
+
417
+ ```text
418
+ ~/.pi-web/plugins/<plugin-package>/
419
+ ```
420
+
421
+ Entries may be real directories or symlinks. This is the recommended development workflow.
422
+
423
+ 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.
424
+
425
+ 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.
426
+
427
+ Plugin package directory names and plugin ids must be valid identifiers:
428
+
429
+ ```text
430
+ ^[a-z][a-z0-9.-]*$
431
+ ```
432
+
433
+ A package can expose one or more PI WEB plugin entries. There is exactly one supported `package.json` metadata shape:
434
+
435
+ ```json
436
+ {
437
+ "private": true,
438
+ "type": "module",
439
+ "piWeb": {
440
+ "plugins": [
441
+ {
442
+ "id": "review",
443
+ "browserRoot": "dist/review",
444
+ "module": "dist/review/index.js"
445
+ },
446
+ {
447
+ "id": "workspaces",
448
+ "browserRoot": "dist/browser",
449
+ "module": "dist/browser/index.js",
450
+ "serverModule": "dist/server.js",
451
+ "machineSpecific": true
452
+ },
453
+ { "id": "server-only", "serverModule": "dist/server-only.js" }
454
+ ]
455
+ }
456
+ }
457
+ ```
458
+
459
+ Rules:
460
+
461
+ - `piWeb.plugins` must be an array of objects.
462
+ - Each entry must have an explicit `id` and at least one of `module` or `serverModule`.
463
+ - `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.
464
+ - 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.
465
+ - 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.
466
+ - 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.
467
+ - `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`.
468
+ - `plugins.<id>.settings` must be JSON-compatible for server entries; sessiond captures a private copy at startup and diagnostics expose only a fingerprint.
469
+ - 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.
470
+ - Legacy shortcuts such as `piWeb.plugin`, string entries in `piWeb.plugins`, `piWeb.id` fallback ids, and no-`package.json` fallbacks are not supported.
471
+
472
+ 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.
473
+
474
+ ### Manifest and assets
475
+
476
+ 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:
477
+
478
+ ```json
479
+ {
480
+ "lifecycleVersion": 1,
481
+ "plugins": [
482
+ {
483
+ "id": "workspaces",
484
+ "module": "/pi-web-plugins/workspaces/dist/browser/index.js?v=<content-revision>",
485
+ "backendRevision": "<active-server-revision>",
486
+ "source": "local",
487
+ "scope": "local",
488
+ "machineSpecific": true
489
+ }
490
+ ]
491
+ }
492
+ ```
493
+
494
+ 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.
495
+
496
+ `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.
497
+
498
+ At an origin-root deployment, a browser-public file is available under its package-relative path:
499
+
500
+ ```text
501
+ /pi-web-plugins/<plugin-id>/<package-relative-path-under-browserRoot>
502
+ ```
503
+
504
+ 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.
505
+
506
+ 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:
507
+
508
+ ```js
509
+ const iconUrl = new URL("./assets/icon.svg", import.meta.url);
510
+ ```
511
+
512
+ 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.
513
+
514
+ 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.
515
+
516
+ ## Browser module shape and v2 migration
517
+
518
+ TypeScript browser entries should use a type-only import from the published declaration entrypoint. The built JavaScript must not import PI WEB source internals:
519
+
520
+ ```ts
521
+ import type { PiWebPlugin } from "@vincenthanxiaodu/pi-web/plugin-api";
522
+
523
+ const plugin: PiWebPlugin = {
524
+ apiVersion: 2,
525
+ name: "My Plugin",
526
+ activate: ({ pluginId, runtimePluginId, html }) => ({
527
+ contributions: {
528
+ actions: [{
529
+ id: "workspace.open",
530
+ title: "Open my panel",
531
+ run: ({ selectWorkspaceTool }) => {
532
+ selectWorkspaceTool(`${runtimePluginId}:workspace.my-panel`);
533
+ },
534
+ }],
535
+ workspacePanels: [{
536
+ id: "workspace.my-panel",
537
+ title: "My panel",
538
+ visible: ({ workspace }) => workspace.provider?.pluginId === pluginId,
539
+ render: ({ workspace }) => html`<p>${workspace.label}</p>`,
540
+ }],
541
+ },
542
+ }),
543
+ };
544
+
545
+ export default plugin;
546
+ ```
547
+
548
+ The activation boundary is:
549
+
550
+ ```ts
551
+ interface PiWebPlugin {
552
+ apiVersion: 2;
553
+ name: string;
554
+ activate(context: PluginActivationContext): PluginActivationResult;
555
+ }
556
+
557
+ interface PluginActivationContext {
558
+ readonly apiVersion: 2;
559
+ readonly pluginId: string;
560
+ readonly runtimePluginId: string;
561
+ readonly html: HtmlTemplateTag;
562
+ readonly svg: SvgTemplateTag;
563
+ }
564
+ ```
565
+
566
+ `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.
567
+
568
+ 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 `@vincenthanxiaodu/pi-web/plugin-api/unstable` type path is not part of v2 and is no longer exported.
569
+
570
+ Contribution ids authored in arrays remain local to the plugin. PI WEB qualifies them internally under the runtime identity:
571
+
572
+ ```text
573
+ <runtime-plugin-id>:<local-contribution-id>
574
+ ```
575
+
576
+ 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.
577
+
578
+ ## Server module and workspace provider shape
579
+
580
+ TypeScript server entries import the separately published Node declarations with `import type`:
581
+
582
+ ```ts
583
+ import type {
584
+ PiWebServerPlugin,
585
+ WorkspaceProvider,
586
+ } from "@vincenthanxiaodu/pi-web/server-plugin-api";
587
+
588
+ const provider: WorkspaceProvider = {
589
+ async probe(project, signal) {
590
+ // Return "claim" only when this provider owns the project's semantics.
591
+ return await projectIsSupported(project, signal) ? "claim" : "pass";
592
+ },
593
+ async list(project, signal) {
594
+ return await listProviderWorkspaces(project, signal);
595
+ },
596
+ async request({ project, workspace, operation, input, signal }) {
597
+ return await handleProviderOperation({ project, workspace, operation, input, signal });
598
+ },
599
+ };
600
+
601
+ const plugin: PiWebServerPlugin = {
602
+ apiVersion: 1,
603
+ name: "My Workspace Provider",
604
+ activate(context) {
605
+ return {
606
+ workspaceProvider: provider,
607
+ health: async (signal) => ({ status: "healthy" }),
608
+ stop: async (signal) => { /* release plugin-owned resources */ },
609
+ };
610
+ },
611
+ };
612
+
613
+ export default plugin;
614
+ ```
615
+
616
+ The default export has `apiVersion: 1`, a non-empty `name`, and `activate(context)`. The activation result can contain:
617
+
618
+ ```ts
619
+ interface ServerPluginActivation {
620
+ workspaceProvider?: WorkspaceProvider;
621
+ start?(signal: AbortSignal): void | Promise<void>;
622
+ stop?(signal: AbortSignal): void | Promise<void>;
623
+ health?(signal: AbortSignal): ServerPluginHealth | Promise<ServerPluginHealth>;
624
+ }
625
+ ```
626
+
627
+ 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.
628
+
629
+ 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.
630
+
631
+ 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.
632
+
633
+ ### Workspace provider contract
634
+
635
+ ```ts
636
+ interface WorkspaceProvider {
637
+ fallback?: boolean;
638
+ probe(project: ProjectInput, signal: AbortSignal): Promise<"claim" | "pass">;
639
+ list(project: ProjectInput, signal: AbortSignal): Promise<ProviderWorkspace[]>;
640
+ request?(context: ProviderRequestContext): Promise<JsonValue>;
641
+ prepareRemove?(context: ProviderRemoveContext): Promise<WorkspaceRemovePlan>;
642
+ }
643
+
644
+ interface ProviderWorkspace {
645
+ key: string;
646
+ path: string;
647
+ label: string;
648
+ isMain: boolean;
649
+ data?: JsonValue;
650
+ publicMetadata?: JsonObject;
651
+ removal?: { actionLabel: string; confirmation: string };
652
+ }
653
+ ```
654
+
655
+ - `probe()` must return only `"claim"` or `"pass"`. Leave `fallback` unset/false for a replacement that should run before bundled Git.
656
+ - `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.
657
+ - `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.
658
+ - `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.
659
+ - `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.
660
+ - `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.
661
+ - Provider failures and conflicts are diagnostics. A claimant that fails `list()` does not permit fallback takeover for the same resolution.
662
+
663
+ The only supported plugin type entrypoints are the type-only package exports `@vincenthanxiaodu/pi-web/plugin-api` and `@vincenthanxiaodu/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.
664
+
665
+ ## Contributions
666
+
667
+ The workspace-related contribution arrays returned by `activate()` are:
668
+
669
+ ```ts
670
+ interface PluginContributions {
671
+ actions?: PluginAction[];
672
+ workspacePanels?: WorkspacePanelContribution[];
673
+ workspaceLabels?: WorkspaceLabelContribution[];
674
+ }
675
+ ```
676
+
677
+ ### Actions
678
+
679
+ Actions appear in the action palette. They can inspect app state and call UI/runtime helpers.
680
+
681
+ ```js
682
+ actions: [
683
+ {
684
+ id: "copy-diagnostics",
685
+ title: "Copy PI WEB Diagnostics",
686
+ description: "Copy version, installation, and status details for this machine",
687
+ group: "Info",
688
+ run: async (context) => {
689
+ const version = context.state.piWebStatus?.components.web.runtimeVersion ?? "unknown";
690
+ await navigator.clipboard.writeText(`PI WEB ${version}`);
691
+ },
692
+ },
693
+ ]
694
+ ```
695
+
696
+ Action type:
697
+
698
+ ```ts
699
+ interface PluginAction {
700
+ id: string;
701
+ title: string;
702
+ description?: string;
703
+ shortcut?: string;
704
+ shortcutAliases?: QualifiedContributionId[];
705
+ group?: string;
706
+ enabled?: (context: PluginRuntimeContext) => boolean;
707
+ disabledReason?: (context: PluginRuntimeContext) => string | undefined;
708
+ run: (context: PluginRuntimeContext) => void | Promise<void>;
709
+ }
710
+ ```
711
+
712
+ 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.
713
+
714
+ Stable runtime context fields:
715
+
716
+ ```ts
717
+ interface PluginRuntimeContext {
718
+ state: {
719
+ selectedMachine?: PluginMachine;
720
+ selectedWorkspace?: Workspace;
721
+ selectedSession?: unknown;
722
+ workspaceTool?: string;
723
+ mainView?: string;
724
+ piWebStatus?: PiWebStatusResponse;
725
+ };
726
+ prompt: PluginPromptEditor;
727
+ openActionPalette: () => void;
728
+ focusPrompt: () => void;
729
+ addProject: () => void | Promise<void>;
730
+ configureAuth: () => void | Promise<void>;
731
+ logoutAuth: () => void | Promise<void>;
732
+ openThemePicker: () => void;
733
+ selectMainView: (view: string) => void;
734
+ selectWorkspaceTool: (tool: QualifiedContributionId) => void;
735
+ openTerminal: (options?: { terminalId?: string }) => void;
736
+ refreshFiles: () => void | Promise<void>;
737
+ refreshWorkspacePanels: (panelId?: QualifiedContributionId) => void | Promise<void>;
738
+ refreshAppData: () => void | Promise<void>;
739
+ checkForPiWebUpdates?: () => void | Promise<void>;
740
+ reloadPage: () => void;
741
+ startSession: () => void | Promise<void>;
742
+ archiveSession: () => void | Promise<void>;
743
+ stopActiveWork: () => void | Promise<void>;
744
+ }
745
+ ```
746
+
747
+ Notes:
748
+
749
+ - `state` is a snapshot of current UI state when actions are built.
750
+ - 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.
751
+ - Other `state` fields may exist at runtime, but they are private PI WEB internals that may graduate into stable helpers, change shape, or disappear.
752
+ - `enabled` is evaluated when the action palette asks for actions.
753
+ - `shortcutAliases` is for migration only: list former fully qualified action ids whose saved shortcut preference should still apply to this action.
754
+ - `selectWorkspaceTool()` expects a qualified panel id such as `my-plugin:workspace.info`.
755
+ - `openTerminal()` switches to the built-in terminal panel. Pass `{ terminalId }` to deep-link to a specific terminal.
756
+ - `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.
757
+ - `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.
758
+ - Only fields documented here and declared by `@vincenthanxiaodu/pi-web/plugin-api` are stable public browser API. Anything else is experimental: it may become public API later, change shape, or disappear.
759
+
760
+ ### Prompt editor API
761
+
762
+ The `prompt` helper on `PluginRuntimeContext` and `WorkspacePanelContext` provides stable access to the chat prompt editor:
763
+
764
+ | Method | Description |
765
+ | --- | --- |
766
+ | `insertText(text)` | Insert text at cursor position. When text is selected, replaces the selection. Focuses the editor first if not focused. |
767
+ | `getText()` | Returns the full prompt text. |
768
+ | `getSelection()` | Returns `{ start, end, text }` if text is selected, or `null`. |
769
+
770
+ Usage:
771
+
772
+ ```js
773
+ // Insert text at the cursor (e.g. a file mention)
774
+ context.prompt.insertText("@file.txt");
775
+
776
+ // Read the current prompt and selection
777
+ const text = context.prompt.getText();
778
+ const selection = context.prompt.getSelection(); // { start, end, text } | null
779
+ ```
780
+
781
+ 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.
782
+
783
+ #### Keyboard shortcuts
784
+
785
+ - 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.
786
+ - `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.
787
+ - Use modified shortcuts such as `mod+shift+p`; plain letter shortcuts are intentionally ignored so normal typing is never captured.
788
+ - 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.
789
+ - Choose shortcuts carefully to avoid conflicts. There is no user-facing shortcut override or conflict resolver yet.
790
+ - 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.
791
+
792
+ ### Workspace panels
793
+
794
+ 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.
795
+
796
+ ```js
797
+ workspacePanels: [
798
+ {
799
+ id: "workspace.info",
800
+ title: "Info",
801
+ icon: svg`
802
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
803
+ <circle cx="12" cy="12" r="9"></circle>
804
+ <path d="M12 10v6"></path>
805
+ <path d="M12 7h.01"></path>
806
+ </svg>
807
+ `,
808
+ order: 100,
809
+ visible: ({ workspace }) => workspace.isMain,
810
+ render: ({ workspace }) => html`
811
+ <section class="toolbar"><strong>Info</strong></section>
812
+ <section class="viewer">
813
+ <p class="muted">${workspace.label}</p>
814
+ <p class="muted">${workspace.path}</p>
815
+ </section>
816
+ `,
817
+ },
818
+ ]
819
+ ```
820
+
821
+ Panel type:
822
+
823
+ ```ts
824
+ interface WorkspacePanelContribution {
825
+ id: string;
826
+ title: string;
827
+ icon?: TemplateResult;
828
+ order?: number;
829
+ routeAliases?: string[];
830
+ visible?: (context: WorkspacePanelContext) => boolean;
831
+ badge?: (context: WorkspacePanelContext) => string | number | TemplateResult | undefined;
832
+ onInvalidate?: (context: WorkspacePanelContext) => void | Promise<void>;
833
+ render: (context: WorkspacePanelContext) => TemplateResult;
834
+ }
835
+
836
+ interface WorkspacePanelContext {
837
+ machine: PluginMachine;
838
+ workspace: Workspace;
839
+ state?: PluginRuntimeState;
840
+ files: {
841
+ readFile(path: string): Promise<FileContentResponse>;
842
+ listFiles(path: string): Promise<FileTreeResponse>;
843
+ writeFile(path: string, content: string | Uint8Array, options?: WriteWorkspaceFileOptions): Promise<WriteWorkspaceFileResponse>;
844
+ deleteFile(path: string): Promise<DeleteWorkspaceFileResponse>;
845
+ moveFile(fromPath: string, toPath: string, options?: MoveWorkspaceFileOptions): Promise<MoveWorkspaceFileResponse>;
846
+ };
847
+ backend?: {
848
+ request(operation: string, input: JsonValue): Promise<JsonValue>;
849
+ };
850
+ prompt: PluginPromptEditor;
851
+ terminal: {
852
+ open(options?: { terminalId?: string }): void;
853
+ runCommand(input: {
854
+ title: string;
855
+ command: string;
856
+ metadata?: Record<string, string>;
857
+ open?: boolean;
858
+ }): Promise<TerminalCommandRunHandle>;
859
+ };
860
+ host: {
861
+ requestRender(): void;
862
+ };
863
+ }
864
+ ```
865
+
866
+ `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.
867
+
868
+ `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`.
869
+
870
+ Useful workspace and machine shapes:
871
+
872
+ ```ts
873
+ interface PluginMachine {
874
+ id: string;
875
+ name: string;
876
+ kind: "local" | "remote";
877
+ }
878
+
879
+ interface Workspace {
880
+ readonly id: string;
881
+ readonly projectId: string;
882
+ readonly path: string;
883
+ readonly label: string;
884
+ readonly isMain: boolean;
885
+ readonly provider?: {
886
+ readonly pluginId: string;
887
+ readonly capabilities: { readonly request: boolean; readonly remove: boolean };
888
+ readonly metadata?: JsonObject;
889
+ };
890
+ readonly removal?: { readonly actionLabel: string; readonly confirmation: string };
891
+ }
892
+ ```
893
+
894
+ `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.
895
+
896
+ 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.
897
+
898
+ ### Workspace labels
899
+
900
+ Workspace labels add compact inline metadata wherever PI WEB displays a workspace label: workspace list, workspace panel header, and status bar.
901
+
902
+ Use them for short facts like project environment, local URL, branch status, container name, or health state.
903
+
904
+ ```js
905
+ workspaceLabels: [
906
+ {
907
+ id: "dev-url",
908
+ order: 10,
909
+ visible: ({ workspace }) => workspace.path.includes("my-app"),
910
+ items: () => [{
911
+ type: "link",
912
+ text: "web:5173",
913
+ href: "http://localhost:5173",
914
+ title: "Open dev server",
915
+ target: "_blank",
916
+ }],
917
+ },
918
+ ]
919
+ ```
920
+
921
+ Label contribution type:
922
+
923
+ ```ts
924
+ interface WorkspaceLabelContribution {
925
+ id: string;
926
+ order?: number;
927
+ visible?: (context: WorkspaceLabelContext) => boolean;
928
+ items: (context: WorkspaceLabelContext) => WorkspaceLabelItem[];
929
+ }
930
+
931
+ interface WorkspaceLabelContext {
932
+ machine: PluginMachine;
933
+ workspace: Workspace;
934
+ state?: PluginRuntimeState;
935
+ files: {
936
+ readFile(path: string): Promise<FileContentResponse>;
937
+ listFiles(path: string): Promise<FileTreeResponse>;
938
+ writeFile(path: string, content: string | Uint8Array, options?: WriteWorkspaceFileOptions): Promise<WriteWorkspaceFileResponse>;
939
+ deleteFile(path: string): Promise<DeleteWorkspaceFileResponse>;
940
+ moveFile(fromPath: string, toPath: string, options?: MoveWorkspaceFileOptions): Promise<MoveWorkspaceFileResponse>;
941
+ };
942
+ backend?: {
943
+ request(operation: string, input: JsonValue): Promise<JsonValue>;
944
+ };
945
+ host: {
946
+ requestRender(): void;
947
+ };
948
+ }
949
+ ```
950
+
951
+ `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.
952
+
953
+ 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.
954
+
955
+ #### Text items
956
+
957
+ ```js
958
+ { type: "text", text: "staging", title: "Staging workspace" }
959
+ ```
960
+
961
+ #### Link items
962
+
963
+ ```js
964
+ {
965
+ type: "link",
966
+ text: "web:5173",
967
+ href: "http://localhost:5173",
968
+ title: "Open dev server",
969
+ target: "_blank"
970
+ }
971
+ ```
972
+
973
+ 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.
974
+
975
+ #### Render items
976
+
977
+ Use render items when a label contribution needs custom UI, async data, or caching. Render items should stay compact and inline.
978
+
979
+ ```js
980
+ class MyWorkspaceBadge extends HTMLElement {
981
+ set workspace(value) {
982
+ this._workspace = value;
983
+ this.textContent = value?.label ?? "workspace";
984
+ }
985
+ }
986
+
987
+ if (!customElements.get("my-workspace-badge")) {
988
+ customElements.define("my-workspace-badge", MyWorkspaceBadge);
989
+ }
990
+
991
+ export default {
992
+ apiVersion: 2,
993
+ name: "My Plugin",
994
+ activate: ({ html }) => ({
995
+ contributions: {
996
+ workspaceLabels: [
997
+ {
998
+ id: "badge",
999
+ order: 10,
1000
+ items: ({ workspace }) => [{
1001
+ type: "render",
1002
+ render: () => html`<my-workspace-badge .workspace=${workspace}></my-workspace-badge>`,
1003
+ }],
1004
+ },
1005
+ ],
1006
+ },
1007
+ }),
1008
+ };
1009
+ ```
1010
+
1011
+ ## Calling paired workspace backends
1012
+
1013
+ 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:
1014
+
1015
+ ```js
1016
+ if (context.backend === undefined) throw new Error("Workspace backend unavailable");
1017
+ const result = await context.backend.request("summary", {
1018
+ includeIgnored: false,
1019
+ });
1020
+ ```
1021
+
1022
+ 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()`.
1023
+
1024
+ 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.
1025
+
1026
+ 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.
1027
+
1028
+ ## Reading workspace files
1029
+
1030
+ 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.
1031
+
1032
+ ```js
1033
+ workspacePanels: [
1034
+ {
1035
+ id: "workspace.env",
1036
+ title: "Env",
1037
+ render: ({ files }) => html`
1038
+ <my-env-viewer .files=${files}></my-env-viewer>
1039
+ `,
1040
+ },
1041
+ ]
1042
+
1043
+ class MyEnvViewer extends HTMLElement {
1044
+ set files(value) {
1045
+ this._files = value;
1046
+ void this.load();
1047
+ }
1048
+
1049
+ async load() {
1050
+ try {
1051
+ const file = await this._files.readFile(".env.example");
1052
+ this.textContent = file.binary ? "Binary file" : file.content;
1053
+ } catch (error) {
1054
+ this.textContent = error instanceof Error ? error.message : String(error);
1055
+ }
1056
+ }
1057
+ }
1058
+ ```
1059
+
1060
+ Labels should use the same helper through a plugin-owned cache because `items()` itself must return synchronously:
1061
+
1062
+ ```js
1063
+ const envCache = new Map();
1064
+
1065
+ function envKey(machine, workspace) {
1066
+ return `${machine.id}:${workspace.id}:.env.local`;
1067
+ }
1068
+
1069
+ function loadEnvLabel(context) {
1070
+ const key = envKey(context.machine, context.workspace);
1071
+ const cached = envCache.get(key);
1072
+ if (cached !== undefined) return cached;
1073
+
1074
+ const pending = { status: "loading", label: undefined };
1075
+ envCache.set(key, pending);
1076
+ context.files.readFile(".env.local")
1077
+ .then((file) => {
1078
+ pending.status = "ready";
1079
+ pending.label = file.content.match(/^DEV_URL=(.+)$/m)?.[1];
1080
+ context.host.requestRender();
1081
+ })
1082
+ .catch(() => {
1083
+ pending.status = "missing";
1084
+ context.host.requestRender();
1085
+ });
1086
+ return pending;
1087
+ }
1088
+
1089
+ workspaceLabels: [
1090
+ {
1091
+ id: "dev-url",
1092
+ items: (context) => {
1093
+ const cached = loadEnvLabel(context);
1094
+ return cached.label === undefined ? [] : [{
1095
+ type: "link",
1096
+ text: cached.label,
1097
+ href: cached.label,
1098
+ target: "_blank",
1099
+ }];
1100
+ },
1101
+ },
1102
+ ]
1103
+ ```
1104
+
1105
+ 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.
1106
+
1107
+ ## Listing workspace files
1108
+
1109
+ `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.
1110
+
1111
+ ```js
1112
+ const listing = await context.files.listFiles("src");
1113
+ for (const entry of listing.entries) {
1114
+ // entry: { name, path, type: "file" | "directory" | "symlink", size?, modifiedAt? }
1115
+ }
1116
+ ```
1117
+
1118
+ 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.
1119
+
1120
+ `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:
1121
+
1122
+ ```js
1123
+ async function listSubdirectoryNames(context, path) {
1124
+ try {
1125
+ const listing = await context.files.listFiles(path);
1126
+ return listing.entries.filter((entry) => entry.type === "directory").map((entry) => entry.name);
1127
+ } catch {
1128
+ return [];
1129
+ }
1130
+ }
1131
+ ```
1132
+
1133
+ ## Writing, deleting, and moving workspace files
1134
+
1135
+ 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.
1136
+
1137
+ ### Writing files
1138
+
1139
+ ```js
1140
+ workspacePanels: [
1141
+ {
1142
+ id: "workspace.generate",
1143
+ title: "Generate",
1144
+ render: ({ files }) => html`
1145
+ <button @click=${async () => {
1146
+ const result = await files.writeFile("output/result.txt", "Generated content\n");
1147
+ console.log("Wrote", result.path, result.size, "bytes");
1148
+ }}>Generate</button>
1149
+ `,
1150
+ },
1151
+ ]
1152
+ ```
1153
+
1154
+ ### Binary writes
1155
+
1156
+ Pass a `Uint8Array` for binary content such as images:
1157
+
1158
+ ```js
1159
+ const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]);
1160
+ await files.writeFile("screenshots/thumb.png", png);
1161
+ ```
1162
+
1163
+ ### Options
1164
+
1165
+ `files.writeFile` accepts an optional third argument:
1166
+
1167
+ - `createDirs` (default `true`): create intermediate directories, like `mkdir -p`.
1168
+ - `overwrite` (default `true`): overwrite existing files. Set to `false` to throw if the file already exists.
1169
+
1170
+ ```js
1171
+ // Create only — throw if the file already exists
1172
+ await files.writeFile("config/new-config.json", jsonContent, { overwrite: false });
1173
+ ```
1174
+
1175
+ ### Deleting files
1176
+
1177
+ `files.deleteFile` removes a workspace file. It is idempotent: deleting a file that does not exist returns `{ existed: false }` instead of throwing.
1178
+
1179
+ ```js
1180
+ const result = await files.deleteFile("temp/cache.json");
1181
+ console.log(result.existed ? "File deleted" : "File did not exist");
1182
+ ```
1183
+
1184
+ ### Moving files
1185
+
1186
+ `files.moveFile` renames or moves a file within the workspace, like `mv`. The default is safe: it will not overwrite an existing target file.
1187
+
1188
+ ```js
1189
+ // Rename a file
1190
+ await files.moveFile("old-name.txt", "new-name.txt");
1191
+
1192
+ // Move into a subdirectory (creates intermediate dirs by default)
1193
+ await files.moveFile("file.txt", "archive/file.txt");
1194
+
1195
+ // Overwrite an existing target
1196
+ await files.moveFile("incoming.txt", "current.txt", { overwrite: true });
1197
+
1198
+ // Move without creating intermediate directories
1199
+ await files.moveFile("file.txt", "deep/nested/file.txt", { createDirs: false }); // throws if dirs don't exist
1200
+ ```
1201
+
1202
+ `files.moveFile` accepts an optional third argument:
1203
+
1204
+ - `createDirs` (default `true`): create intermediate directories for the target path.
1205
+ - `overwrite` (default `false`): overwrite the target file if it exists. The default is safer than `writeFile` because moving is a more destructive operation.
1206
+
1207
+ ### Error handling
1208
+
1209
+ All file mutations share the same safety layer:
1210
+
1211
+ - `overwrite: false` on `writeFile` or existing target on `moveFile` (default) throws if the file already exists.
1212
+ - Path traversal (e.g., `../../etc/passwd`) is blocked by the workspace safety layer.
1213
+ - Writing to or moving to a path that is a directory returns an error.
1214
+ - Deleting a directory returns an error.
1215
+ - Intermediate directory creation with `createDirs: false` fails if the parent directory does not exist.
1216
+
1217
+ 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.
1218
+
1219
+ ### Security
1220
+
1221
+ 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.
1222
+
1223
+ ## Running workspace terminal commands
1224
+
1225
+ Workspace panels can start terminal commands through the documented `terminal` helper. Commands run in the current workspace on the panel's machine.
1226
+
1227
+ ```js
1228
+ render: ({ terminal }) => html`
1229
+ <button @click=${() => terminal.runCommand({
1230
+ title: "Build",
1231
+ command: "npm run build",
1232
+ open: true,
1233
+ metadata: { "my-plugin.task": "build" },
1234
+ })}>Build</button>
1235
+ `
1236
+ ```
1237
+
1238
+ Review command strings carefully. They are trusted shell commands executed in the workspace terminal.
1239
+
1240
+ ## Private and experimental PI WEB APIs
1241
+
1242
+ 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.
1243
+
1244
+ The stable browser API is the documented helpers and the type-only `@vincenthanxiaodu/pi-web/plugin-api` export; the stable server API is the narrow type-only `@vincenthanxiaodu/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.
1245
+
1246
+ ## Async data and caching
1247
+
1248
+ PI WEB does not provide a plugin cache/invalidation framework. Keep host callbacks cheap:
1249
+
1250
+ - simple contributions should be synchronous and cheap;
1251
+ - expensive or async work should live inside the plugin;
1252
+ - custom elements in `type: "render"` label items or panels are a good place to own async loading;
1253
+ - dedupe async reads/commands and avoid unbounded polling;
1254
+ - clean up intervals/event listeners in custom elements' `disconnectedCallback()`.
1255
+
1256
+ ## Agent implementation checklist
1257
+
1258
+ If you are an AI agent building or editing a PI WEB plugin, follow this checklist:
1259
+
1260
+ 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`.
1261
+ 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.-]*$`.
1262
+ 3. Import browser types only from `@vincenthanxiaodu/pi-web/plugin-api` and server types only from `@vincenthanxiaodu/pi-web/server-plugin-api`, always with `import type`; do not use private subpaths or source internals.
1263
+ 4. Default-export `{ apiVersion: 2, name, activate }` from a browser entry and `{ apiVersion: 1, name, activate }` from a server entry.
1264
+ 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.
1265
+ 6. Add actions for command-palette operations, panels for larger workspace UI, and labels for compact inline metadata.
1266
+ 7. Return arrays synchronously from workspace label `items()`; return an empty array to render nothing.
1267
+ 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.
1268
+ 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.
1269
+ 10. Make provider claims conservative. Return exactly one main workspace, stable keys, absolute accessible directories, JSON data/metadata, and optional request/removal capabilities.
1270
+ 11. Keep backend operations JSON-only, bounded, and provider-owned. Put no secrets in `publicMetadata`, browser responses, removal wording, or diagnostics.
1271
+ 12. Keep the installed package at or below 4,096 entries and 16 MiB, and keep every browser-public file inside a narrow `browserRoot`.
1272
+ 13. Treat both entries as trusted code. A server module shares sessiond's process and user permissions.
1273
+ 14. For browser-only edits, reload or hard-reload the page. For a server-backed edit, restart sessiond and then reload the page.
1274
+ 15. Warn that restarting `pi-web-sessiond.service` may interrupt active sessions/runtime ownership.
1275
+
1276
+ ## Troubleshooting
1277
+
1278
+ Check discovery:
1279
+
1280
+ ```bash
1281
+ curl http://127.0.0.1:8504/pi-web-plugins/manifest.json
1282
+ ```
1283
+
1284
+ Check a plugin module:
1285
+
1286
+ ```bash
1287
+ curl http://127.0.0.1:8504/pi-web-plugins/my-plugin/pi-web-plugin.js
1288
+ ```
1289
+
1290
+ Common issues:
1291
+
1292
+ - invalid plugin or contribution id;
1293
+ - missing default export, browser `apiVersion: 2` or server `apiVersion: 1`, non-empty `name`, or `activate` function;
1294
+ - 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`;
1295
+ - legacy shortcuts such as `piWeb.plugin`, string plugin entries, or no-`package.json` fallback;
1296
+ - duplicate plugin ids; records are diagnosed, skipped rather than merged, and never renamed;
1297
+ - 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;
1298
+ - package is not installed through Pi or under `$PI_WEB_DATA_DIR/plugins` (`~/.pi-web/plugins` by default);
1299
+ - browser import/activation/render failure; check the browser console;
1300
+ - server state is failed, incompatible, unhealthy, disabled, missing, stale, or conflicted; check **Settings → PI WEB plugins** and `pi-web logs` on the target machine;
1301
+ - 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;
1302
+ - a federated target lacks the lifecycle/backend capability; update and restart PI WEB on that target instead of falling back to the gateway;
1303
+ - recovery is needed before plugin discovery/import; use `pi-web plugins safe-start show`, offline disable, or one of the documented safe-start levels.
1304
+
1305
+ 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.