@pi-chamber/web 1.0.7-rc.1 → 1.0.8-rc.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 (212) hide show
  1. package/dist/assets/AgentsSurface-BmHImX8m.js +1 -0
  2. package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
  3. package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
  4. package/dist/assets/{DiffView-C3rA5DfE.js → DiffView-C70pbgk-.js} +6 -6
  5. package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
  6. package/dist/assets/FilesView-nFJYEdRw.js +6 -0
  7. package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
  8. package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
  9. package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
  10. package/dist/assets/{GitView-OpFCss_4.js → GitView-MIDG5RYW.js} +5 -5
  11. package/dist/assets/{IssuesSurface-DD6Gz5Ox.js → IssuesSurface-uNlozeu0.js} +2 -2
  12. package/dist/assets/{JsonTreeView-Dj75jgH6.js → JsonTreeView-CSLsTriz.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-CnIzmT1p.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
  14. package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
  15. package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
  16. package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
  17. package/dist/assets/{SessionSwitcherContent-CUz6Cc1-.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
  18. package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
  19. package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
  20. package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
  21. package/dist/assets/{SettingsWindow-J6YOvGcV.js → SettingsWindow-Cb4st5y5.js} +1 -1
  22. package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
  23. package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
  24. package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
  25. package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
  26. package/dist/assets/{VirtualizedFileDiff-Dq8pyTGy.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
  27. package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
  28. package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
  29. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
  30. package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
  31. package/dist/assets/{computeVirtualFileMetrics-uXZ9uhI_.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
  32. package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
  33. package/dist/assets/{fileTreeStatus-C_7jbeGv.js → fileTreeStatus-CnzR7kxA.js} +2 -2
  34. package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
  35. package/dist/assets/githubLink-QvaLfNNT.js +10 -0
  36. package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
  37. package/dist/assets/index-D3F4JrPN.css +1 -0
  38. package/dist/assets/{index-DD0xW5WE.js → index-DMX9wT1Z.js} +1 -1
  39. package/dist/assets/{main-BnWf2tm9.js → main-BW9J3Y72.js} +2 -2
  40. package/dist/assets/main-BirYxac2.js +137 -0
  41. package/dist/assets/{markdownCore-C-Ulh4n9.js → markdownCore-CxmcPur8.js} +2 -2
  42. package/dist/assets/miniChat-BRB11eEs.js +2 -0
  43. package/dist/assets/{mobile-BuAWpKj9.js → mobile-DJZYYCuB.js} +2 -2
  44. package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
  45. package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
  46. package/dist/assets/{renderDiffWithHighlighter-DD-iWWus.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
  47. package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
  48. package/dist/assets/{renderFileWithHighlighter-B0pofdV1.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
  49. package/dist/assets/{renderMobileApp-B3P_bita.js → renderMobileApp-B7cT7m5b.js} +3 -3
  50. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
  51. package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
  52. package/dist/assets/selection-BTEdLRVK.js +1 -0
  53. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
  54. package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
  55. package/dist/assets/useSwitcherItems-DfLbfX37.js +1 -0
  56. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
  57. package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
  58. package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
  59. package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
  60. package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
  61. package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
  85. package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
  86. package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
  87. package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
  88. package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
  89. package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
  90. package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
  91. package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
  92. package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
  93. package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
  94. package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
  95. package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
  96. package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
  97. package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
  98. package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
  99. package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
  100. package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
  101. package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
  102. package/dist/assets/{web-components-DB-GDG7P.js → web-components-C_DsTJis.js} +4 -4
  103. package/dist/index.html +4 -4
  104. package/dist/mini-chat.html +3 -3
  105. package/dist/mobile.html +3 -3
  106. package/package.json +2 -1
  107. package/plugins/registry.json +7 -0
  108. package/plugins/subagents/LICENSE +25 -0
  109. package/plugins/subagents/agents/planner.md +36 -0
  110. package/plugins/subagents/agents/reviewer.md +34 -0
  111. package/plugins/subagents/agents/scout.md +49 -0
  112. package/plugins/subagents/agents/worker.md +23 -0
  113. package/plugins/subagents/extension.js +631 -0
  114. package/plugins/subagents/extension.test.js +295 -0
  115. package/plugins/subagents/package.json +41 -0
  116. package/plugins/visuals/choices.js +168 -0
  117. package/plugins/visuals/extension.js +87 -0
  118. package/plugins/visuals/files.js +74 -0
  119. package/plugins/visuals/package.json +32 -0
  120. package/server/index.js +20 -0
  121. package/server/lib/github/DOCUMENTATION.md +4 -2
  122. package/server/lib/github/gh-cli.js +35 -9
  123. package/server/lib/github/gh-cli.test.js +122 -0
  124. package/server/lib/notifications/pi-notification-watcher.js +3 -0
  125. package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
  126. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  127. package/server/lib/pi/extension-protocol.js +54 -0
  128. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
  129. package/server/lib/pi/routes-extension-events.test.js +115 -0
  130. package/server/lib/pi/routes.js +307 -5
  131. package/server/lib/pi/routes.test.js +296 -1
  132. package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
  133. package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
  134. package/server/lib/pi/session-daemon/extension-config.js +719 -0
  135. package/server/lib/pi/session-daemon/extension-config.test.js +618 -0
  136. package/server/lib/pi/session-daemon/extension-controls.js +177 -0
  137. package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
  138. package/server/lib/pi/session-daemon/extension-name.js +6 -0
  139. package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
  140. package/server/lib/pi/session-daemon/extension-palette.js +146 -0
  141. package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
  142. package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
  143. package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
  144. package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
  145. package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
  146. package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
  147. package/server/lib/pi/session-daemon/plugin-host.js +245 -0
  148. package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
  149. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
  150. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
  151. package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
  152. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
  153. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
  154. package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
  155. package/server/lib/pi/session-daemon/session-daemon.js +568 -61
  156. package/server/lib/pi/session-daemon/session-daemon.test.js +164 -4
  157. package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
  158. package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
  159. package/server/lib/pi/session-daemon/supervisor.js +22 -3
  160. package/server/lib/pi/settings-store.js +14 -0
  161. package/server/lib/pi/settings-store.test.js +11 -0
  162. package/server/lib/plugins/DOCUMENTATION.md +186 -0
  163. package/server/lib/plugins/daemon-sync.js +78 -0
  164. package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
  165. package/server/lib/plugins/daemon-sync.test.js +96 -0
  166. package/server/lib/plugins/impact.js +139 -0
  167. package/server/lib/plugins/impact.test.js +82 -0
  168. package/server/lib/plugins/manifest.js +195 -0
  169. package/server/lib/plugins/manifest.test.js +118 -0
  170. package/server/lib/plugins/registry.js +59 -0
  171. package/server/lib/plugins/routes.js +92 -0
  172. package/server/lib/plugins/routes.test.js +219 -0
  173. package/server/lib/plugins/service.js +161 -0
  174. package/server/lib/plugins/store.js +261 -0
  175. package/server/lib/plugins/store.test.js +188 -0
  176. package/server/lib/plugins/visuals-extension.test.js +237 -0
  177. package/server/lib/server-browser/DOCUMENTATION.md +32 -7
  178. package/server/lib/server-browser/browser-tab.js +4 -1
  179. package/server/lib/server-browser/downloads.js +261 -34
  180. package/server/lib/server-browser/downloads.test.js +171 -0
  181. package/server/lib/server-browser/runtime.integration.test.js +47 -0
  182. package/server/lib/server-browser/runtime.js +16 -0
  183. package/server/lib/server-browser/server-browser.js +25 -6
  184. package/server/lib/tunnels/executable-search.js +5 -1
  185. package/server/lib/tunnels/executable-search.test.js +26 -0
  186. package/dist/assets/DiagramView-DyF8zzYx.js +0 -1
  187. package/dist/assets/FileSaveConflictDialog-CC4F--8H.js +0 -3
  188. package/dist/assets/FilesView-Dsg-QTJu.js +0 -6
  189. package/dist/assets/GitHubDetailScaffold-C9WuBMGr.js +0 -11
  190. package/dist/assets/GitHubLinkPicker-BkVdYxZT.js +0 -1
  191. package/dist/assets/GitHubListPrimitives-CcVlv_rJ.js +0 -1
  192. package/dist/assets/PatchDiff-DND5RBnF.js +0 -1
  193. package/dist/assets/PierreDiffViewer-Cq5CIrmH.js +0 -147
  194. package/dist/assets/PullRequestsSurface-g8HAvbFg.js +0 -2
  195. package/dist/assets/SessionSwitcherDropdown-COZ50Y5a.js +0 -2
  196. package/dist/assets/SessionUnreadDot-DOUcgBw6.js +0 -1
  197. package/dist/assets/SettingsView-AFymxZYC.js +0 -6
  198. package/dist/assets/ToolOutputDialog-5Tc7HM4z.js +0 -8
  199. package/dist/assets/ToolPartDiffPreview-7GiFbVl7.js +0 -1
  200. package/dist/assets/contextFileOpenGuard-CckKFYjI.js +0 -1
  201. package/dist/assets/gitStatusPredicates-CNLvdt2V.js +0 -1
  202. package/dist/assets/githubLink-0EoMGZKd.js +0 -10
  203. package/dist/assets/index-BaLCg7tL.css +0 -1
  204. package/dist/assets/main-yQe-k30g.js +0 -137
  205. package/dist/assets/miniChat-DKK1hotU.js +0 -2
  206. package/dist/assets/pi-session-focus-preference-DaWQ2rEE.js +0 -9
  207. package/dist/assets/renderElectronMiniChatApp-CKuFQBRo.js +0 -2
  208. package/dist/assets/runtimeEndpointReset-DutinXZK.js +0 -62
  209. package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
  210. package/dist/assets/useAppFontEffects-DQlUEhzN.js +0 -213
  211. package/dist/assets/useGitHubRemoteSearch-BoZvJAk3.js +0 -1
  212. package/dist/assets/useSwitcherItems-Dy2yumiU.js +0 -1
@@ -0,0 +1,118 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { join } from 'node:path';
5
+
6
+ import { defaultPluginState, isValidStateValue, parsePluginPackage } from './manifest.js';
7
+
8
+ const packageDir = '/plugins/demo';
9
+
10
+ const validPackage = (pichamber = {}, extra = {}) => ({
11
+ name: 'demo',
12
+ version: '1.2.3',
13
+ pi: { extensions: ['./extension.js'] },
14
+ ...extra,
15
+ pichamber: {
16
+ apiVersion: 1,
17
+ id: 'demo',
18
+ name: 'Demo',
19
+ description: 'A demo plugin.',
20
+ icon: 'artboard',
21
+ state: {
22
+ on: { type: 'boolean', scope: 'global', default: true, label: 'On' },
23
+ mode: {
24
+ type: 'enum',
25
+ scope: 'project',
26
+ default: 'a',
27
+ label: 'Mode',
28
+ options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }],
29
+ },
30
+ },
31
+ contributes: {
32
+ composerToggles: [{ id: 'demo', state: 'on', label: 'Demo', icon: 'artboard', description: 'Toggle it' }],
33
+ settings: ['mode'],
34
+ ui: 'demo',
35
+ },
36
+ ...pichamber,
37
+ },
38
+ });
39
+
40
+ const reason = (input, options = { packageDir }) => {
41
+ try {
42
+ parsePluginPackage(input, options);
43
+ } catch (error) {
44
+ expect(error.code).toBe('INVALID_PLUGIN_MANIFEST');
45
+ return error.message;
46
+ }
47
+ throw new Error('expected the manifest to be rejected');
48
+ };
49
+
50
+ describe('parsePluginPackage', () => {
51
+ it('normalizes a valid package', () => {
52
+ const manifest = parsePluginPackage(validPackage(), { packageDir, bundled: true });
53
+ expect(manifest).toMatchObject({
54
+ id: 'demo',
55
+ name: 'Demo',
56
+ version: '1.2.3',
57
+ bundled: true,
58
+ defaultEnabled: false,
59
+ replaceable: false,
60
+ entry: '/plugins/demo/extension.js',
61
+ contributes: {
62
+ composerToggles: [{ id: 'demo', state: 'on', label: 'Demo', icon: 'artboard', description: 'Toggle it' }],
63
+ settings: ['mode'],
64
+ ui: 'demo',
65
+ },
66
+ });
67
+ expect(defaultPluginState(manifest)).toEqual({ on: true, mode: 'a' });
68
+ expect(isValidStateValue(manifest.stateSchema.mode, 'b')).toBe(true);
69
+ expect(isValidStateValue(manifest.stateSchema.mode, 'c')).toBe(false);
70
+ expect(isValidStateValue(manifest.stateSchema.on, 'true')).toBe(false);
71
+ });
72
+
73
+ it('parses the bundled Visuals manifest', async () => {
74
+ const dir = fileURLToPath(new URL('../../../plugins/visuals/', import.meta.url));
75
+ const manifest = parsePluginPackage(JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')), { packageDir: dir, bundled: true });
76
+ expect(manifest.id).toBe('visuals');
77
+ expect(manifest.stateSchema.on).toBeUndefined();
78
+ expect(manifest.stateSchema.allowNetwork).toMatchObject({ default: false, scope: 'global' });
79
+ expect(manifest.contributes.composerToggles).toEqual([]);
80
+ expect(manifest.contributes.settings).toEqual(['allowNetwork']);
81
+ });
82
+
83
+ it('fails closed on invalid fields', () => {
84
+ expect(reason(validPackage({ apiVersion: 2 }))).toMatch(/apiVersion/);
85
+ expect(reason(validPackage({ id: 'Bad_Id' }))).toMatch(/id/);
86
+ expect(reason(validPackage({ id: 'a'.repeat(41) }))).toMatch(/id/);
87
+ expect(reason(validPackage({ icon: 'not an icon' }))).toMatch(/icon/);
88
+ expect(reason(validPackage({ name: '' }))).toMatch(/name/);
89
+ expect(reason(validPackage({ state: { on: { type: 'number', scope: 'global', default: 1, label: 'x' } } }))).toMatch(/type/);
90
+ expect(reason(validPackage({ state: { on: { type: 'boolean', scope: 'session', default: true, label: 'x' } } }))).toMatch(/scope/);
91
+ expect(reason(validPackage({ state: { on: { type: 'boolean', scope: 'global', default: 'yes', label: 'x' } } }))).toMatch(/default/);
92
+ expect(reason(validPackage({ state: { m: { type: 'enum', scope: 'global', default: 'z', label: 'x', options: [{ value: 'a', label: 'A' }] } } }))).toMatch(/default/);
93
+ expect(reason(validPackage({ state: { constructor: { type: 'boolean', scope: 'global', default: true, label: 'x' } } }))).toMatch(/constructor/);
94
+ expect(reason(validPackage({ contributes: { composerToggles: [{ id: 'demo', state: 'mode', label: 'x', icon: 'artboard' }] } }))).toMatch(/boolean/);
95
+ expect(reason(validPackage({ contributes: { settings: ['missing'] } }))).toMatch(/unknown/);
96
+ expect(reason(validPackage({ contributes: { settings: ['mode', 'mode'] } }))).toMatch(/repeats/);
97
+ expect(reason(validPackage({ contributes: { composerToggles: [{ id: 'demo', state: 'on', label: 'Demo', icon: 'artboard' }], settings: ['on'] } }))).toMatch(/composer toggle/);
98
+ expect(reason({ ...validPackage(), version: 'latest' })).toMatch(/version/);
99
+ expect(reason(validPackage({}, {}), { packageDir: 'relative' })).toMatch(/folder/);
100
+ });
101
+
102
+ it('keeps the agent half inside the package', () => {
103
+ expect(reason({ ...validPackage(), pi: {} })).toMatch(/pi.extensions/);
104
+ expect(reason({ ...validPackage(), pi: { extensions: ['../other/extension.js'] } })).toMatch(/leaves/);
105
+ expect(reason({ ...validPackage(), pi: { extensions: ['/abs/extension.js'] } })).toMatch(/invalid/);
106
+ expect(reason({ ...validPackage(), pi: { extensions: ['./extension.ts'] } })).toMatch(/JavaScript/);
107
+ });
108
+
109
+ it('requires bundled plugins to ship disabled', () => {
110
+ expect(reason(validPackage({ defaultEnabled: true }), { packageDir, bundled: true })).toMatch(/disabled/);
111
+ expect(parsePluginPackage(validPackage({ defaultEnabled: true }), { packageDir }).defaultEnabled).toBe(true);
112
+ });
113
+
114
+ it('maps replaceable', () => {
115
+ expect(parsePluginPackage(validPackage({ replaceable: true }), { packageDir }).replaceable).toBe(true);
116
+ expect(reason(validPackage({ replaceable: 'yes' }))).toMatch(/replaceable/);
117
+ });
118
+ });
@@ -0,0 +1,59 @@
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, join, relative } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import { parsePluginPackage } from './manifest.js';
6
+
7
+ /** Bundled plugins ship inside the web package, a read root of the nono sandbox. */
8
+ const BUNDLED_PLUGINS_DIR = fileURLToPath(new URL('../../../plugins/', import.meta.url));
9
+
10
+ class PluginRegistryError extends Error {
11
+ constructor(message = 'The bundled plugin list is unreadable.') {
12
+ super(message);
13
+ this.code = 'PLUGINS_UNREADABLE';
14
+ }
15
+ }
16
+
17
+ const isInside = (root, target) => {
18
+ const fromRoot = relative(root, target);
19
+ return fromRoot.length > 0 && !fromRoot.startsWith('..') && !isAbsolute(fromRoot);
20
+ };
21
+
22
+ /**
23
+ * Load `registry.json` and every plugin it lists. An invalid plugin is
24
+ * skipped with a logged reason and never blocks the others. An unreadable or
25
+ * malformed registry file throws: the bundled list is part of the install, so
26
+ * reporting "no plugins" would hide a broken install.
27
+ */
28
+ export const loadBundledPlugins = async ({ pluginsDir = BUNDLED_PLUGINS_DIR, logger = console } = {}) => {
29
+ let listed;
30
+ try {
31
+ const parsed = JSON.parse(await readFile(join(pluginsDir, 'registry.json'), 'utf8'));
32
+ if (parsed?.version !== 1 || !Array.isArray(parsed.plugins)) throw new Error('shape');
33
+ listed = parsed.plugins;
34
+ } catch {
35
+ throw new PluginRegistryError();
36
+ }
37
+ const root = await realpath(pluginsDir);
38
+ const plugins = new Map();
39
+ for (const id of listed) {
40
+ try {
41
+ if (typeof id !== 'string' || id.includes('/') || id.includes('\\') || id.startsWith('.')) {
42
+ throw new Error('listed id is invalid');
43
+ }
44
+ const packageDir = await realpath(join(root, id));
45
+ if (!isInside(root, packageDir)) throw new Error('plugin folder leaves the plugins folder');
46
+ const packageJson = JSON.parse(await readFile(join(packageDir, 'package.json'), 'utf8'));
47
+ const manifest = parsePluginPackage(packageJson, { packageDir, bundled: true });
48
+ if (manifest.id !== id) throw new Error('pichamber.id does not match its registry entry');
49
+ if (plugins.has(id)) throw new Error('listed twice');
50
+ // The entry must resolve, through any links, to a file in the package.
51
+ const entry = await realpath(manifest.entry);
52
+ if (!isInside(packageDir, entry)) throw new Error('pi.extensions[0] leaves the package');
53
+ plugins.set(id, { ...manifest, entry });
54
+ } catch (error) {
55
+ logger.warn?.(`[plugins] skipped bundled plugin ${typeof id === 'string' ? id : '<invalid>'}: ${error?.message ?? 'invalid'}`);
56
+ }
57
+ }
58
+ return plugins;
59
+ };
@@ -0,0 +1,92 @@
1
+ // Authenticated public plugin routes (the global `/api` auth gate applies).
2
+ // Each mutation tells `onChange` after the store commits; the daemon push
3
+ // behind it never delays or fails the request.
4
+
5
+ const STATUS_BY_CODE = {
6
+ PLUGIN_NOT_FOUND: 404,
7
+ INVALID_PLUGIN_REQUEST: 400,
8
+ PLUGINS_UNREADABLE: 500,
9
+ };
10
+
11
+ const sendError = (res, error) => {
12
+ const code = Object.hasOwn(STATUS_BY_CODE, error?.code) ? error.code : 'PLUGINS_UNREADABLE';
13
+ if (code === 'PLUGINS_UNREADABLE' && error?.code !== 'PLUGINS_UNREADABLE') {
14
+ console.warn('[plugins] request failed', error?.code ?? error?.message ?? error);
15
+ }
16
+ res.status(STATUS_BY_CODE[code]).json({ error: { code } });
17
+ };
18
+
19
+ const badRequest = (res) => res.status(400).json({ error: { code: 'INVALID_PLUGIN_REQUEST' } });
20
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
21
+
22
+ export const registerPluginRoutes = (app, { service, onChange = () => {} }) => {
23
+ const changed = () => {
24
+ try {
25
+ onChange();
26
+ } catch (error) {
27
+ console.warn('[plugins] change notification failed', error?.message ?? error);
28
+ }
29
+ };
30
+
31
+ app.get('/api/pi/plugins', async (req, res) => {
32
+ const { directory } = req.query ?? {};
33
+ if (directory !== undefined && typeof directory !== 'string') return badRequest(res);
34
+ try {
35
+ res.json({ plugins: await service.list({ directory }) });
36
+ } catch (error) {
37
+ sendError(res, error);
38
+ }
39
+ });
40
+
41
+ app.put('/api/pi/plugins/:id', async (req, res) => {
42
+ if (!isRecord(req.body) || typeof req.body.enabled !== 'boolean') return badRequest(res);
43
+ try {
44
+ const view = await service.setEnabled(req.params.id, req.body.enabled);
45
+ changed();
46
+ res.json(view);
47
+ } catch (error) {
48
+ sendError(res, error);
49
+ }
50
+ });
51
+
52
+ app.get('/api/pi/plugins/sessions/:sessionId', async (req, res) => {
53
+ try {
54
+ res.json(await service.sessionState(req.params.sessionId));
55
+ } catch (error) {
56
+ sendError(res, error);
57
+ }
58
+ });
59
+
60
+ // A composer switch: one session's own value. `value: null` clears it, so
61
+ // the session follows the plugin's settings again.
62
+ app.put('/api/pi/plugins/:id/sessions/:sessionId', async (req, res) => {
63
+ const body = req.body;
64
+ if (!isRecord(body) || typeof body.key !== 'string'
65
+ || (body.value !== null && typeof body.value !== 'boolean' && typeof body.value !== 'string')) {
66
+ return badRequest(res);
67
+ }
68
+ try {
69
+ const result = await service.setSessionState(req.params.id, req.params.sessionId, { key: body.key, value: body.value });
70
+ changed();
71
+ res.json(result);
72
+ } catch (error) {
73
+ sendError(res, error);
74
+ }
75
+ });
76
+
77
+ app.put('/api/pi/plugins/:id/state', async (req, res) => {
78
+ const body = req.body;
79
+ if (!isRecord(body) || typeof body.key !== 'string'
80
+ || (typeof body.value !== 'boolean' && typeof body.value !== 'string')
81
+ || (body.directory !== undefined && typeof body.directory !== 'string')) {
82
+ return badRequest(res);
83
+ }
84
+ try {
85
+ const view = await service.setState(req.params.id, { key: body.key, value: body.value, directory: body.directory });
86
+ changed();
87
+ res.json(view);
88
+ } catch (error) {
89
+ sendError(res, error);
90
+ }
91
+ });
92
+ };
@@ -0,0 +1,219 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import express from 'express';
3
+ import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+
7
+ import { loadBundledPlugins } from './registry.js';
8
+ import { registerPluginRoutes } from './routes.js';
9
+ import { createPluginService } from './service.js';
10
+ import { createPluginStore } from './store.js';
11
+
12
+ const listen = (app) => new Promise((resolve, reject) => {
13
+ const server = app.listen(0, '127.0.0.1', () => resolve(server));
14
+ server.once('error', reject);
15
+ });
16
+
17
+ const writePlugin = async (root, id, pichamber, { entrySource = 'export default function () {}' } = {}) => {
18
+ const dir = join(root, id);
19
+ await mkdir(dir, { recursive: true });
20
+ await writeFile(join(dir, 'extension.js'), entrySource);
21
+ await writeFile(join(dir, 'package.json'), JSON.stringify({
22
+ version: '1.0.0',
23
+ pi: { extensions: ['./extension.js'] },
24
+ pichamber: { apiVersion: 1, id, name: 'Fixture', description: 'A fixture.', icon: 'artboard', ...pichamber },
25
+ }));
26
+ };
27
+
28
+ describe('plugin registry', () => {
29
+ it('skips an invalid plugin without blocking the others', async () => {
30
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-plugin-registry-'));
31
+ await writePlugin(root, 'good', {});
32
+ await writePlugin(root, 'enabled-by-default', { defaultEnabled: true });
33
+ await writePlugin(root, 'mismatch', { id: 'other' });
34
+ await writeFile(join(root, 'registry.json'), JSON.stringify({ version: 1, plugins: ['good', 'enabled-by-default', 'mismatch', 'missing', '../escape'] }));
35
+ const logger = { warn: vi.fn() };
36
+ const plugins = await loadBundledPlugins({ pluginsDir: root, logger });
37
+ expect([...plugins.keys()]).toEqual(['good']);
38
+ expect(logger.warn).toHaveBeenCalledTimes(4);
39
+ });
40
+
41
+ it('throws when the registry file is malformed', async () => {
42
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-plugin-registry-'));
43
+ await writeFile(join(root, 'registry.json'), '{');
44
+ await expect(loadBundledPlugins({ pluginsDir: root })).rejects.toMatchObject({ code: 'PLUGINS_UNREADABLE' });
45
+ });
46
+ });
47
+
48
+ describe('plugin routes', () => {
49
+ let server;
50
+
51
+ afterEach(async () => {
52
+ await new Promise((resolve) => (server ? server.close(resolve) : resolve()));
53
+ server = undefined;
54
+ });
55
+
56
+ const setup = async ({ loadPlugins } = {}) => {
57
+ const file = join(await mkdtemp(join(tmpdir(), 'pichamber-plugin-routes-')), 'pi', 'plugins.json');
58
+ const onChange = vi.fn();
59
+ const service = createPluginService({
60
+ store: createPluginStore({ file }),
61
+ ...(loadPlugins ? { loadPlugins } : {}),
62
+ });
63
+ const app = express();
64
+ app.use(express.json());
65
+ registerPluginRoutes(app, { service, onChange });
66
+ server = await listen(app);
67
+ const base = `http://127.0.0.1:${server.address().port}`;
68
+ const call = async (method, path, body) => {
69
+ const response = await fetch(`${base}${path}`, {
70
+ method,
71
+ headers: body === undefined ? {} : { 'content-type': 'application/json' },
72
+ body: body === undefined ? undefined : JSON.stringify(body),
73
+ });
74
+ return { status: response.status, body: await response.json() };
75
+ };
76
+ return { call, onChange, file };
77
+ };
78
+
79
+ it('lists the bundled plugins, off, with defaults and measured impact', async () => {
80
+ const { call } = await setup();
81
+ const { status, body } = await call('GET', '/api/pi/plugins');
82
+ expect(status).toBe(200);
83
+ expect(body.plugins.map((plugin) => plugin.id)).toEqual(['visuals', 'subagents']);
84
+ expect(body.plugins[0]).toMatchObject({
85
+ id: 'visuals',
86
+ name: 'Visuals',
87
+ icon: 'artboard',
88
+ version: '1.1.0',
89
+ bundled: true,
90
+ enabled: false,
91
+ state: { allowNetwork: false },
92
+ contributes: {
93
+ composerToggles: [],
94
+ settings: ['allowNetwork'],
95
+ ui: 'visuals',
96
+ },
97
+ impact: {
98
+ tools: [
99
+ { name: 'render_html', exposure: 'direct', tokens: expect.any(Number) },
100
+ { name: 'render_choices', exposure: 'direct', tokens: expect.any(Number) },
101
+ ],
102
+ hooks: [],
103
+ commands: [],
104
+ },
105
+ });
106
+ expect(body.plugins[0]).not.toHaveProperty('entry');
107
+ expect(body.plugins[0]).not.toHaveProperty('packageDir');
108
+ expect(body.plugins[0]).not.toHaveProperty('impactError');
109
+ expect(body.plugins[1]).toMatchObject({
110
+ id: 'subagents',
111
+ bundled: true,
112
+ enabled: false,
113
+ state: { on: true },
114
+ contributes: {
115
+ composerToggles: [{ id: 'subagents', state: 'on', label: 'Sub-agents', icon: 'robot-2', description: 'Let the agent hand tasks to sub-agents' }],
116
+ settings: [],
117
+ ui: 'subagents',
118
+ },
119
+ impact: { tools: [{ name: 'subagent', exposure: 'direct', tokens: expect.any(Number) }], hooks: [], commands: [] },
120
+ });
121
+ });
122
+
123
+ it('enables, sets state, and notifies after each committed change', async () => {
124
+ const { call, onChange } = await setup();
125
+ const enabled = await call('PUT', '/api/pi/plugins/visuals', { enabled: true });
126
+ expect(enabled).toMatchObject({ status: 200, body: { id: 'visuals', enabled: true } });
127
+ expect(onChange).toHaveBeenCalledTimes(1);
128
+ const state = await call('PUT', '/api/pi/plugins/visuals/state', { key: 'allowNetwork', value: true });
129
+ expect(state).toMatchObject({ status: 200, body: { state: { allowNetwork: true } } });
130
+ expect(onChange).toHaveBeenCalledTimes(2);
131
+ const listed = await call('GET', '/api/pi/plugins?directory=/some/project');
132
+ expect(listed.body.plugins[0]).toMatchObject({ enabled: true, state: { allowNetwork: true } });
133
+ });
134
+
135
+ it('resolves project-scoped values for the requested directory', async () => {
136
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-plugin-routes-fixture-'));
137
+ await writePlugin(root, 'scoped', {
138
+ state: { mode: { type: 'enum', scope: 'project', default: 'a', label: 'Mode', options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }] } },
139
+ });
140
+ await writeFile(join(root, 'registry.json'), JSON.stringify({ version: 1, plugins: ['scoped'] }));
141
+ const { call } = await setup({ loadPlugins: () => loadBundledPlugins({ pluginsDir: root }) });
142
+ expect(await call('PUT', '/api/pi/plugins/scoped/state', { key: 'mode', value: 'b' })).toMatchObject({ status: 400, body: { error: { code: 'INVALID_PLUGIN_REQUEST' } } });
143
+ expect(await call('PUT', '/api/pi/plugins/scoped/state', { key: 'mode', value: 'b', directory: '/p' })).toMatchObject({ status: 200, body: { state: { mode: 'b' } } });
144
+ expect((await call('GET', '/api/pi/plugins?directory=/p')).body.plugins[0].state).toEqual({ mode: 'b' });
145
+ expect((await call('GET', '/api/pi/plugins?directory=/q')).body.plugins[0].state).toEqual({ mode: 'a' });
146
+ expect((await call('GET', '/api/pi/plugins')).body.plugins[0].state).toEqual({ mode: 'a' });
147
+ });
148
+
149
+ it('answers stable errors and never notifies on failure', async () => {
150
+ const { call, onChange, file } = await setup();
151
+ expect(await call('PUT', '/api/pi/plugins/missing', { enabled: true })).toEqual({ status: 404, body: { error: { code: 'PLUGIN_NOT_FOUND' } } });
152
+ expect(await call('PUT', '/api/pi/plugins/visuals', { enabled: 'yes' })).toEqual({ status: 400, body: { error: { code: 'INVALID_PLUGIN_REQUEST' } } });
153
+ expect(await call('PUT', '/api/pi/plugins/visuals/state', { key: 'allowNetwork', value: 1 })).toEqual({ status: 400, body: { error: { code: 'INVALID_PLUGIN_REQUEST' } } });
154
+ expect(await call('PUT', '/api/pi/plugins/visuals/state', { key: 'nope', value: true })).toEqual({ status: 400, body: { error: { code: 'INVALID_PLUGIN_REQUEST' } } });
155
+ expect(await call('GET', '/api/pi/plugins?directory=relative')).toEqual({ status: 400, body: { error: { code: 'INVALID_PLUGIN_REQUEST' } } });
156
+ await mkdir(join(file, '..'), { recursive: true });
157
+ await writeFile(file, '{broken');
158
+ expect(await call('GET', '/api/pi/plugins')).toEqual({ status: 500, body: { error: { code: 'PLUGINS_UNREADABLE' } } });
159
+ expect(await call('PUT', '/api/pi/plugins/visuals', { enabled: true })).toEqual({ status: 500, body: { error: { code: 'PLUGINS_UNREADABLE' } } });
160
+ expect(onChange).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it('builds the daemon config from enabled plugins only', async () => {
164
+ const file = join(await mkdtemp(join(tmpdir(), 'pichamber-plugin-config-')), 'plugins.json');
165
+ const service = createPluginService({ store: createPluginStore({ file }) });
166
+ expect(await service.daemonConfig()).toEqual({ plugins: [] });
167
+ await service.setEnabled('visuals', true);
168
+ await service.setState('visuals', { key: 'allowNetwork', value: true });
169
+ expect(await service.daemonConfig()).toEqual({
170
+ plugins: [{
171
+ id: 'visuals',
172
+ entry: expect.stringMatching(/plugins[\\/]visuals[\\/]extension\.js$/),
173
+ replaceable: false,
174
+ state: { global: { allowNetwork: true }, projects: {}, sessions: {} },
175
+ }],
176
+ });
177
+ });
178
+
179
+ it('keeps a composer switch to one session and leaves the settings alone', async () => {
180
+ const { call, onChange } = await setup();
181
+ await call('PUT', '/api/pi/plugins/subagents', { enabled: true });
182
+ onChange.mockClear();
183
+ expect(await call('GET', '/api/pi/plugins/sessions/s-1')).toEqual({ status: 200, body: { sessionId: 's-1', overrides: {} } });
184
+ expect(await call('PUT', '/api/pi/plugins/subagents/sessions/s-1', { key: 'on', value: false }))
185
+ .toEqual({ status: 200, body: { id: 'subagents', sessionId: 's-1', overrides: { on: false } } });
186
+ expect(onChange).toHaveBeenCalledTimes(1);
187
+ expect((await call('GET', '/api/pi/plugins/sessions/s-1')).body.overrides).toEqual({ subagents: { on: false } });
188
+ expect((await call('GET', '/api/pi/plugins/sessions/s-2')).body.overrides).toEqual({});
189
+ expect((await call('GET', '/api/pi/plugins')).body.plugins[1].state).toEqual({ on: true });
190
+ expect(await call('PUT', '/api/pi/plugins/subagents/sessions/s-1', { key: 'on', value: null }))
191
+ .toEqual({ status: 200, body: { id: 'subagents', sessionId: 's-1', overrides: {} } });
192
+
193
+ // Only keys a composer toggle names, valid values, and plain session ids.
194
+ for (const [path, body] of [
195
+ ['/api/pi/plugins/visuals/sessions/s-1', { key: 'allowNetwork', value: true }],
196
+ ['/api/pi/plugins/subagents/sessions/s-1', { key: 'on', value: 'yes' }],
197
+ ['/api/pi/plugins/subagents/sessions/s-1', { key: 'on' }],
198
+ ['/api/pi/plugins/subagents/sessions/bad%20id', { key: 'on', value: false }],
199
+ ]) {
200
+ expect(await call('PUT', path, body)).toEqual({ status: 400, body: { error: { code: 'INVALID_PLUGIN_REQUEST' } } });
201
+ }
202
+ expect(await call('PUT', '/api/pi/plugins/missing/sessions/s-1', { key: 'on', value: false })).toMatchObject({ status: 404 });
203
+ expect(await call('GET', '/api/pi/plugins/sessions/bad%20id')).toMatchObject({ status: 400 });
204
+ // The set and the clear; no failed request notified.
205
+ expect(onChange).toHaveBeenCalledTimes(2);
206
+ });
207
+
208
+ it('sends session values to the daemon and forgets a deleted session', async () => {
209
+ const file = join(await mkdtemp(join(tmpdir(), 'pichamber-plugin-config-')), 'plugins.json');
210
+ const service = createPluginService({ store: createPluginStore({ file }) });
211
+ await service.setEnabled('subagents', true);
212
+ await service.setSessionState('subagents', 's-1', { key: 'on', value: false });
213
+ const [subagents] = (await service.daemonConfig()).plugins;
214
+ expect(subagents.state).toEqual({ global: { on: true }, projects: {}, sessions: { 's-1': { on: false } } });
215
+ expect(await service.forgetSession('s-1')).toBe(true);
216
+ expect((await service.daemonConfig()).plugins[0].state.sessions).toEqual({});
217
+ expect(await service.forgetSession('s-1')).toBe(false);
218
+ });
219
+ });
@@ -0,0 +1,161 @@
1
+ import { createImpactCache } from './impact.js';
2
+ import { loadBundledPlugins } from './registry.js';
3
+ import {
4
+ createPluginStore,
5
+ isPluginEnabled,
6
+ normalizePluginDirectory,
7
+ normalizePluginSessionId,
8
+ PluginStoreError,
9
+ resolvePluginState,
10
+ resolveSessionOverrides,
11
+ } from './store.js';
12
+
13
+ const pluginNotFound = () => new PluginStoreError('PLUGIN_NOT_FOUND', 'No plugin has that id.');
14
+
15
+ /**
16
+ * One owner for plugin manifests, stored choices, measured impact, and the
17
+ * config the daemon receives. Routes and the daemon sync stay thin.
18
+ */
19
+ export const createPluginService = ({
20
+ store = createPluginStore(),
21
+ loadPlugins = () => loadBundledPlugins(),
22
+ impactCache = createImpactCache(),
23
+ } = {}) => {
24
+ // Bundled manifests do not change while the server runs. A failed load is
25
+ // not cached, so the next request retries.
26
+ let pluginsPromise = null;
27
+ const plugins = () => {
28
+ if (!pluginsPromise) {
29
+ pluginsPromise = loadPlugins().catch((error) => {
30
+ pluginsPromise = null;
31
+ throw error;
32
+ });
33
+ }
34
+ return pluginsPromise;
35
+ };
36
+
37
+ const manifestFor = async (id) => {
38
+ const manifest = typeof id === 'string' ? (await plugins()).get(id) : undefined;
39
+ if (!manifest) throw pluginNotFound();
40
+ return manifest;
41
+ };
42
+
43
+ const view = async (manifest, snapshot, directory) => {
44
+ const measured = await impactCache.get(manifest);
45
+ return {
46
+ id: manifest.id,
47
+ name: manifest.name,
48
+ description: manifest.description,
49
+ icon: manifest.icon,
50
+ version: manifest.version,
51
+ bundled: manifest.bundled,
52
+ enabled: isPluginEnabled(manifest, snapshot),
53
+ state: resolvePluginState(manifest, snapshot, directory),
54
+ stateSchema: manifest.stateSchema,
55
+ contributes: manifest.contributes,
56
+ impact: measured.impact,
57
+ ...(measured.impactError ? { impactError: measured.impactError } : {}),
58
+ };
59
+ };
60
+
61
+ /** `directory` is optional; an invalid one is a request error, not "no project". */
62
+ const resolveDirectory = (directory) => {
63
+ if (directory === undefined || directory === null || directory === '') return null;
64
+ const normalized = normalizePluginDirectory(directory);
65
+ if (!normalized) throw new PluginStoreError('INVALID_PLUGIN_REQUEST', 'The directory is invalid.');
66
+ return normalized;
67
+ };
68
+
69
+ const list = async ({ directory } = {}) => {
70
+ const target = resolveDirectory(directory);
71
+ const [manifests, snapshot] = await Promise.all([plugins(), store.read()]);
72
+ return Promise.all([...manifests.values()].map((manifest) => view(manifest, snapshot, target)));
73
+ };
74
+
75
+ const setEnabled = async (id, enabled) => {
76
+ const manifest = await manifestFor(id);
77
+ const snapshot = await store.setEnabled(manifest, enabled);
78
+ return view(manifest, snapshot, null);
79
+ };
80
+
81
+ const setState = async (id, { key, value, directory }) => {
82
+ const manifest = await manifestFor(id);
83
+ const target = resolveDirectory(directory);
84
+ const snapshot = await store.setState(manifest, { key, value, directory: target ?? undefined });
85
+ return view(manifest, snapshot, target);
86
+ };
87
+
88
+ const sessionIdOrThrow = (sessionId) => {
89
+ const id = normalizePluginSessionId(sessionId);
90
+ if (!id) throw new PluginStoreError('INVALID_PLUGIN_REQUEST', 'The session id is invalid.');
91
+ return id;
92
+ };
93
+
94
+ /** A session's own values, `{ [pluginId]: { [key]: value } }`, for plugins that have any. */
95
+ const sessionState = async (sessionId) => {
96
+ const id = sessionIdOrThrow(sessionId);
97
+ const [manifests, snapshot] = await Promise.all([plugins(), store.read()]);
98
+ const overrides = {};
99
+ for (const manifest of manifests.values()) {
100
+ const values = resolveSessionOverrides(manifest, snapshot, id);
101
+ if (Object.keys(values).length > 0) overrides[manifest.id] = values;
102
+ }
103
+ return { sessionId: id, overrides };
104
+ };
105
+
106
+ /** Set or clear (`null`) one session's own value; answers that plugin's values for the session. */
107
+ const setSessionState = async (pluginId, sessionId, { key, value }) => {
108
+ const manifest = await manifestFor(pluginId);
109
+ const id = sessionIdOrThrow(sessionId);
110
+ const snapshot = await store.setSessionState(manifest, { sessionId: id, key, value });
111
+ return { id: manifest.id, sessionId: id, overrides: resolveSessionOverrides(manifest, snapshot, id) };
112
+ };
113
+
114
+ /** Resolves whether a deleted session had values to drop. Never throws. */
115
+ const forgetSession = async (sessionId) => {
116
+ try {
117
+ return await store.forgetSession(sessionId);
118
+ } catch {
119
+ return false;
120
+ }
121
+ };
122
+
123
+ /**
124
+ * Payload for the daemon's `plugins.configure`: enabled plugins only, each
125
+ * with its module path and the state it needs to resolve values for any
126
+ * directory: `global` is every key resolved without a project (defaults
127
+ * filled in), `projects[dir]` only the project-scoped values that differ,
128
+ * `sessions[sessionId]` a session's own values. The daemon resolves
129
+ * `{ ...global, ...projects[dir], ...sessions[sessionId] }`.
130
+ */
131
+ const daemonConfig = async () => {
132
+ const [manifests, snapshot] = await Promise.all([plugins(), store.read()]);
133
+ const configured = [];
134
+ for (const manifest of manifests.values()) {
135
+ if (!isPluginEnabled(manifest, snapshot)) continue;
136
+ const global = resolvePluginState(manifest, snapshot, null);
137
+ const projects = {};
138
+ for (const directory of Object.keys(snapshot.state[manifest.id]?.projects ?? {})) {
139
+ const resolved = resolvePluginState(manifest, snapshot, directory);
140
+ const projectValues = Object.fromEntries(Object.entries(manifest.stateSchema)
141
+ .filter(([key, field]) => field.scope === 'project' && resolved[key] !== global[key])
142
+ .map(([key]) => [key, resolved[key]]));
143
+ if (Object.keys(projectValues).length > 0) projects[directory] = projectValues;
144
+ }
145
+ const sessions = {};
146
+ for (const sessionId of Object.keys(snapshot.state[manifest.id]?.sessions ?? {})) {
147
+ const values = resolveSessionOverrides(manifest, snapshot, sessionId);
148
+ if (Object.keys(values).length > 0) sessions[sessionId] = values;
149
+ }
150
+ configured.push({
151
+ id: manifest.id,
152
+ entry: manifest.entry,
153
+ replaceable: manifest.replaceable,
154
+ state: { global, projects, sessions },
155
+ });
156
+ }
157
+ return { plugins: configured };
158
+ };
159
+
160
+ return { list, setEnabled, setState, sessionState, setSessionState, forgetSession, daemonConfig };
161
+ };