@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.
- package/dist/assets/AgentsSurface-BmHImX8m.js +1 -0
- package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
- package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
- package/dist/assets/{DiffView-C3rA5DfE.js → DiffView-C70pbgk-.js} +6 -6
- package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
- package/dist/assets/FilesView-nFJYEdRw.js +6 -0
- package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
- package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
- package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
- package/dist/assets/{GitView-OpFCss_4.js → GitView-MIDG5RYW.js} +5 -5
- package/dist/assets/{IssuesSurface-DD6Gz5Ox.js → IssuesSurface-uNlozeu0.js} +2 -2
- package/dist/assets/{JsonTreeView-Dj75jgH6.js → JsonTreeView-CSLsTriz.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CnIzmT1p.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
- package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
- package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
- package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
- package/dist/assets/{SessionSwitcherContent-CUz6Cc1-.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
- package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
- package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
- package/dist/assets/{SettingsWindow-J6YOvGcV.js → SettingsWindow-Cb4st5y5.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
- package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
- package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
- package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-Dq8pyTGy.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
- package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
- package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
- package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
- package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-uXZ9uhI_.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
- package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
- package/dist/assets/{fileTreeStatus-C_7jbeGv.js → fileTreeStatus-CnzR7kxA.js} +2 -2
- package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
- package/dist/assets/githubLink-QvaLfNNT.js +10 -0
- package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
- package/dist/assets/index-D3F4JrPN.css +1 -0
- package/dist/assets/{index-DD0xW5WE.js → index-DMX9wT1Z.js} +1 -1
- package/dist/assets/{main-BnWf2tm9.js → main-BW9J3Y72.js} +2 -2
- package/dist/assets/main-BirYxac2.js +137 -0
- package/dist/assets/{markdownCore-C-Ulh4n9.js → markdownCore-CxmcPur8.js} +2 -2
- package/dist/assets/miniChat-BRB11eEs.js +2 -0
- package/dist/assets/{mobile-BuAWpKj9.js → mobile-DJZYYCuB.js} +2 -2
- package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
- package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
- package/dist/assets/{renderDiffWithHighlighter-DD-iWWus.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-B0pofdV1.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
- package/dist/assets/{renderMobileApp-B3P_bita.js → renderMobileApp-B7cT7m5b.js} +3 -3
- package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
- package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
- package/dist/assets/selection-BTEdLRVK.js +1 -0
- package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
- package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
- package/dist/assets/useSwitcherItems-DfLbfX37.js +1 -0
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
- package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
- package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
- package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
- package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
- package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
- package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
- package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
- package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
- package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
- package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
- package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
- package/dist/assets/{web-components-DB-GDG7P.js → web-components-C_DsTJis.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -1
- package/plugins/registry.json +7 -0
- package/plugins/subagents/LICENSE +25 -0
- package/plugins/subagents/agents/planner.md +36 -0
- package/plugins/subagents/agents/reviewer.md +34 -0
- package/plugins/subagents/agents/scout.md +49 -0
- package/plugins/subagents/agents/worker.md +23 -0
- package/plugins/subagents/extension.js +631 -0
- package/plugins/subagents/extension.test.js +295 -0
- package/plugins/subagents/package.json +41 -0
- package/plugins/visuals/choices.js +168 -0
- package/plugins/visuals/extension.js +87 -0
- package/plugins/visuals/files.js +74 -0
- package/plugins/visuals/package.json +32 -0
- package/server/index.js +20 -0
- package/server/lib/github/DOCUMENTATION.md +4 -2
- package/server/lib/github/gh-cli.js +35 -9
- package/server/lib/github/gh-cli.test.js +122 -0
- package/server/lib/notifications/pi-notification-watcher.js +3 -0
- package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
- package/server/lib/open-url/DOCUMENTATION.md +1 -1
- package/server/lib/pi/extension-protocol.js +54 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
- package/server/lib/pi/routes-extension-events.test.js +115 -0
- package/server/lib/pi/routes.js +307 -5
- package/server/lib/pi/routes.test.js +296 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
- package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
- package/server/lib/pi/session-daemon/extension-config.js +719 -0
- package/server/lib/pi/session-daemon/extension-config.test.js +618 -0
- package/server/lib/pi/session-daemon/extension-controls.js +177 -0
- package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
- package/server/lib/pi/session-daemon/extension-name.js +6 -0
- package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
- package/server/lib/pi/session-daemon/extension-palette.js +146 -0
- package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
- package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
- package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
- package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
- package/server/lib/pi/session-daemon/plugin-host.js +245 -0
- package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
- package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
- package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
- package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
- package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
- package/server/lib/pi/session-daemon/session-daemon.js +568 -61
- package/server/lib/pi/session-daemon/session-daemon.test.js +164 -4
- package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
- package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
- package/server/lib/pi/session-daemon/supervisor.js +22 -3
- package/server/lib/pi/settings-store.js +14 -0
- package/server/lib/pi/settings-store.test.js +11 -0
- package/server/lib/plugins/DOCUMENTATION.md +186 -0
- package/server/lib/plugins/daemon-sync.js +78 -0
- package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
- package/server/lib/plugins/daemon-sync.test.js +96 -0
- package/server/lib/plugins/impact.js +139 -0
- package/server/lib/plugins/impact.test.js +82 -0
- package/server/lib/plugins/manifest.js +195 -0
- package/server/lib/plugins/manifest.test.js +118 -0
- package/server/lib/plugins/registry.js +59 -0
- package/server/lib/plugins/routes.js +92 -0
- package/server/lib/plugins/routes.test.js +219 -0
- package/server/lib/plugins/service.js +161 -0
- package/server/lib/plugins/store.js +261 -0
- package/server/lib/plugins/store.test.js +188 -0
- package/server/lib/plugins/visuals-extension.test.js +237 -0
- package/server/lib/server-browser/DOCUMENTATION.md +32 -7
- package/server/lib/server-browser/browser-tab.js +4 -1
- package/server/lib/server-browser/downloads.js +261 -34
- package/server/lib/server-browser/downloads.test.js +171 -0
- package/server/lib/server-browser/runtime.integration.test.js +47 -0
- package/server/lib/server-browser/runtime.js +16 -0
- package/server/lib/server-browser/server-browser.js +25 -6
- package/server/lib/tunnels/executable-search.js +5 -1
- package/server/lib/tunnels/executable-search.test.js +26 -0
- package/dist/assets/DiagramView-DyF8zzYx.js +0 -1
- package/dist/assets/FileSaveConflictDialog-CC4F--8H.js +0 -3
- package/dist/assets/FilesView-Dsg-QTJu.js +0 -6
- package/dist/assets/GitHubDetailScaffold-C9WuBMGr.js +0 -11
- package/dist/assets/GitHubLinkPicker-BkVdYxZT.js +0 -1
- package/dist/assets/GitHubListPrimitives-CcVlv_rJ.js +0 -1
- package/dist/assets/PatchDiff-DND5RBnF.js +0 -1
- package/dist/assets/PierreDiffViewer-Cq5CIrmH.js +0 -147
- package/dist/assets/PullRequestsSurface-g8HAvbFg.js +0 -2
- package/dist/assets/SessionSwitcherDropdown-COZ50Y5a.js +0 -2
- package/dist/assets/SessionUnreadDot-DOUcgBw6.js +0 -1
- package/dist/assets/SettingsView-AFymxZYC.js +0 -6
- package/dist/assets/ToolOutputDialog-5Tc7HM4z.js +0 -8
- package/dist/assets/ToolPartDiffPreview-7GiFbVl7.js +0 -1
- package/dist/assets/contextFileOpenGuard-CckKFYjI.js +0 -1
- package/dist/assets/gitStatusPredicates-CNLvdt2V.js +0 -1
- package/dist/assets/githubLink-0EoMGZKd.js +0 -10
- package/dist/assets/index-BaLCg7tL.css +0 -1
- package/dist/assets/main-yQe-k30g.js +0 -137
- package/dist/assets/miniChat-DKK1hotU.js +0 -2
- package/dist/assets/pi-session-focus-preference-DaWQ2rEE.js +0 -9
- package/dist/assets/renderElectronMiniChatApp-CKuFQBRo.js +0 -2
- package/dist/assets/runtimeEndpointReset-DutinXZK.js +0 -62
- package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
- package/dist/assets/useAppFontEffects-DQlUEhzN.js +0 -213
- package/dist/assets/useGitHubRemoteSearch-BoZvJAk3.js +0 -1
- package/dist/assets/useSwitcherItems-Dy2yumiU.js +0 -1
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Finds which PiChamber plugins and Pi built-ins a live runtime left out
|
|
2
|
+
// because another extension registers the same tool, command, or flag.
|
|
3
|
+
//
|
|
4
|
+
// Pi drops a `replaceable` extension in `omitReplacedExtensions`
|
|
5
|
+
// (core/resource-loader.js) and keeps no record for plugins. This module is
|
|
6
|
+
// pure: it reads the runtime's loaded extensions and the names each plugin
|
|
7
|
+
// registered, and reports paths for the caller to turn into path-free ids.
|
|
8
|
+
// Recheck it against that function on every SDK upgrade.
|
|
9
|
+
|
|
10
|
+
import { resolveExtensionName } from './extension-name.js';
|
|
11
|
+
|
|
12
|
+
const PLUGIN_PATH_PREFIX = '<inline:pichamber:';
|
|
13
|
+
const BUILTIN_PATH_PREFIX = 'builtin:';
|
|
14
|
+
const KIND_ORDER = ['tool', 'command', 'flag'];
|
|
15
|
+
|
|
16
|
+
// Pi's warning for a dropped built-in:
|
|
17
|
+
// "Extension <path> registers <kind> `<name>`, so built-in extension `<id>` was not loaded. ..."
|
|
18
|
+
const BUILTIN_WARNING_PATTERN = /^Extension (.+) registers (tool|command|flag) `([^`]+)`, so built-in extension `([^`]+)` was not loaded\./;
|
|
19
|
+
|
|
20
|
+
const namesOf = (extension) => [
|
|
21
|
+
...[...(extension?.tools?.keys?.() ?? [])].map((name) => `tool:${name}`),
|
|
22
|
+
...[...(extension?.commands?.keys?.() ?? [])].map((name) => `command:${name}`),
|
|
23
|
+
...[...(extension?.flags?.keys?.() ?? [])].map((name) => `flag:${name}`),
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
const splitName = (qualified) => {
|
|
27
|
+
const index = qualified.indexOf(':');
|
|
28
|
+
return { kind: qualified.slice(0, index), name: qualified.slice(index + 1) };
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Plugins that are configured, did not load, and share a name with a loaded
|
|
33
|
+
* extension Pi does not allow to be replaced.
|
|
34
|
+
*
|
|
35
|
+
* `loaded`: the runtime's `getExtensions().extensions`.
|
|
36
|
+
* `configuredPluginIds`: ids of the plugins the host has configured.
|
|
37
|
+
* `registeredNames`: Map of plugin id to `['tool:x', 'command:y', ...]`.
|
|
38
|
+
* Returns `[{ id, registers: { kind, name }, byLoadedPath }]`.
|
|
39
|
+
*/
|
|
40
|
+
export const findReplacedPlugins = ({ loaded, configuredPluginIds, registeredNames }) => {
|
|
41
|
+
const extensions = Array.isArray(loaded) ? loaded : [];
|
|
42
|
+
const loadedPaths = new Set(extensions.map((extension) => extension?.path));
|
|
43
|
+
// Same table Pi builds: a later extension's name overwrites an earlier one.
|
|
44
|
+
const taken = new Map();
|
|
45
|
+
for (const extension of extensions) {
|
|
46
|
+
if (!extension || extension.replaceable) continue;
|
|
47
|
+
for (const name of namesOf(extension)) taken.set(name, extension);
|
|
48
|
+
}
|
|
49
|
+
const replaced = [];
|
|
50
|
+
for (const id of configuredPluginIds ?? []) {
|
|
51
|
+
if (loadedPaths.has(`${PLUGIN_PATH_PREFIX}${id}>`)) continue;
|
|
52
|
+
const names = registeredNames?.get?.(id) ?? [];
|
|
53
|
+
const ordered = KIND_ORDER.flatMap((kind) => names.filter((name) => name.startsWith(`${kind}:`)));
|
|
54
|
+
const shared = ordered.find((name) => taken.has(name));
|
|
55
|
+
// Missing with nothing shared: it failed for another reason.
|
|
56
|
+
if (shared === undefined) continue;
|
|
57
|
+
const winner = taken.get(shared);
|
|
58
|
+
replaced.push({
|
|
59
|
+
id,
|
|
60
|
+
registers: splitName(shared),
|
|
61
|
+
byLoadedPath: winner.path,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return replaced;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Built-ins Pi reports as dropped. The fact is the warning's `path`
|
|
69
|
+
* (`builtin:<name>`); package and install warnings use other paths. The
|
|
70
|
+
* warning text only fills the optional details, left out when it does not
|
|
71
|
+
* match. Returns `[{ path, registers?, byPath? }]`.
|
|
72
|
+
*/
|
|
73
|
+
export const findReplacedBuiltins = ({ warnings }) => {
|
|
74
|
+
const found = new Map();
|
|
75
|
+
for (const warning of Array.isArray(warnings) ? warnings : []) {
|
|
76
|
+
if (typeof warning?.path !== 'string' || !warning.path.startsWith(BUILTIN_PATH_PREFIX)) continue;
|
|
77
|
+
const entry = { path: warning.path };
|
|
78
|
+
const match = typeof warning.warning === 'string' ? BUILTIN_WARNING_PATTERN.exec(warning.warning) : null;
|
|
79
|
+
if (match && `${BUILTIN_PATH_PREFIX}${match[4]}` === warning.path) {
|
|
80
|
+
const [, byPath, kind, shown] = match;
|
|
81
|
+
const name = kind === 'command' ? shown.replace(/^\//, '') : kind === 'flag' ? shown.replace(/^--/, '') : shown;
|
|
82
|
+
if (name.length > 0) {
|
|
83
|
+
entry.registers = { kind, name };
|
|
84
|
+
entry.byPath = byPath;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
found.set(warning.path, entry);
|
|
88
|
+
}
|
|
89
|
+
return [...found.values()];
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Both lists for one runtime's `getExtensions()` result, each winner as
|
|
94
|
+
* `by: { path, name }`. `path` is the loaded file (for the caller to map to an
|
|
95
|
+
* item id and then drop); `name` is `nameOf(loadedPath)`, path-free.
|
|
96
|
+
*/
|
|
97
|
+
export const findReplacements = ({ extensionsResult, configuredPluginIds, registeredNames, nameOf }) => {
|
|
98
|
+
const loaded = Array.isArray(extensionsResult?.extensions) ? extensionsResult.extensions : [];
|
|
99
|
+
const winner = (loadedPath) => {
|
|
100
|
+
const match = loaded.find((extension) => extension?.path === loadedPath);
|
|
101
|
+
return {
|
|
102
|
+
path: typeof match?.resolvedPath === 'string' ? match.resolvedPath : loadedPath,
|
|
103
|
+
name: nameOf(loadedPath),
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
plugins: findReplacedPlugins({ loaded, configuredPluginIds, registeredNames }).map(({ id, registers, byLoadedPath }) => ({
|
|
108
|
+
id,
|
|
109
|
+
registers,
|
|
110
|
+
by: winner(byLoadedPath),
|
|
111
|
+
})),
|
|
112
|
+
builtins: findReplacedBuiltins({ warnings: extensionsResult?.warnings }).map(({ path, registers, byPath }) => ({
|
|
113
|
+
path,
|
|
114
|
+
...(registers ? { registers } : {}),
|
|
115
|
+
...(byPath ? { by: winner(byPath) } : {}),
|
|
116
|
+
})),
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* `findReplacements` for a live Pi session. Returns `undefined` when the
|
|
122
|
+
* session has no loaded extension result (unknown, not "nothing replaced").
|
|
123
|
+
*/
|
|
124
|
+
export const describeRuntimeReplacements = ({ session, configuredPluginIds, registeredNames }) => {
|
|
125
|
+
let extensionsResult;
|
|
126
|
+
try {
|
|
127
|
+
extensionsResult = session?.resourceLoader?.getExtensions?.();
|
|
128
|
+
} catch {
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
if (!extensionsResult || !Array.isArray(extensionsResult.extensions)) return undefined;
|
|
132
|
+
return findReplacements({
|
|
133
|
+
extensionsResult,
|
|
134
|
+
configuredPluginIds,
|
|
135
|
+
registeredNames,
|
|
136
|
+
nameOf: (path) => resolveExtensionName(session, path),
|
|
137
|
+
});
|
|
138
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
describeRuntimeReplacements,
|
|
5
|
+
findReplacedBuiltins,
|
|
6
|
+
findReplacedPlugins,
|
|
7
|
+
findReplacements,
|
|
8
|
+
} from './extension-replacements.js';
|
|
9
|
+
|
|
10
|
+
const extension = (path, { tools = [], commands = [], flags = [], replaceable = false } = {}) => ({
|
|
11
|
+
path,
|
|
12
|
+
resolvedPath: path,
|
|
13
|
+
replaceable,
|
|
14
|
+
tools: new Map(tools.map((name) => [name, {}])),
|
|
15
|
+
commands: new Map(commands.map((name) => [name, {}])),
|
|
16
|
+
flags: new Map(flags.map((name) => [name, {}])),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const names = new Map([['subagents', ['tool:subagent', 'command:agents']], ['visuals', ['tool:render_html']]]);
|
|
20
|
+
|
|
21
|
+
describe('findReplacedPlugins', () => {
|
|
22
|
+
it('reports a plugin a user extension replaced, with the shared name and the winner', () => {
|
|
23
|
+
const loaded = [extension('/agent/extensions/mine.ts', { tools: ['subagent'] })];
|
|
24
|
+
expect(findReplacedPlugins({ loaded, configuredPluginIds: ['subagents'], registeredNames: names })).toEqual([
|
|
25
|
+
{ id: 'subagents', registers: { kind: 'tool', name: 'subagent' }, byLoadedPath: '/agent/extensions/mine.ts' },
|
|
26
|
+
]);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('does not report a plugin that is loaded', () => {
|
|
30
|
+
const loaded = [
|
|
31
|
+
extension('<inline:pichamber:subagents>', { tools: ['subagent'], replaceable: true }),
|
|
32
|
+
extension('/agent/extensions/mine.ts', { tools: ['other'] }),
|
|
33
|
+
];
|
|
34
|
+
expect(findReplacedPlugins({ loaded, configuredPluginIds: ['subagents'], registeredNames: names })).toEqual([]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('does not report a missing plugin when nothing shares a name', () => {
|
|
38
|
+
const loaded = [extension('/agent/extensions/mine.ts', { tools: ['unrelated'] })];
|
|
39
|
+
expect(findReplacedPlugins({ loaded, configuredPluginIds: ['subagents', 'visuals'], registeredNames: names })).toEqual([]);
|
|
40
|
+
expect(findReplacedPlugins({ loaded, configuredPluginIds: ['subagents'], registeredNames: new Map() })).toEqual([]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('never names a replaceable extension as the winner', () => {
|
|
44
|
+
const loaded = [extension('builtin:other', { tools: ['subagent'], replaceable: true })];
|
|
45
|
+
expect(findReplacedPlugins({ loaded, configuredPluginIds: ['subagents'], registeredNames: names })).toEqual([]);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('matches by command and flag names, preferring tools first', () => {
|
|
49
|
+
const loaded = [extension('/a/one.ts', { commands: ['agents'] }), extension('/a/two.ts', { tools: ['subagent'] })];
|
|
50
|
+
expect(findReplacedPlugins({ loaded, configuredPluginIds: ['subagents'], registeredNames: names })[0])
|
|
51
|
+
.toMatchObject({ registers: { kind: 'tool', name: 'subagent' }, byLoadedPath: '/a/two.ts' });
|
|
52
|
+
const onlyCommand = [extension('/a/one.ts', { commands: ['agents'] })];
|
|
53
|
+
expect(findReplacedPlugins({ loaded: onlyCommand, configuredPluginIds: ['subagents'], registeredNames: names })[0])
|
|
54
|
+
.toMatchObject({ registers: { kind: 'command', name: 'agents' } });
|
|
55
|
+
const flagNames = new Map([['p', ['flag:plan']]]);
|
|
56
|
+
expect(findReplacedPlugins({ loaded: [extension('/a/f.ts', { flags: ['plan'] })], configuredPluginIds: ['p'], registeredNames: flagNames })[0])
|
|
57
|
+
.toMatchObject({ registers: { kind: 'flag', name: 'plan' } });
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('tolerates missing input', () => {
|
|
61
|
+
expect(findReplacedPlugins({})).toEqual([]);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
describe('findReplacedBuiltins', () => {
|
|
66
|
+
const text = (path, kind, shown, name) => `Extension ${path} registers ${kind} \`${shown}\`, so built-in extension \`${name}\` was not loaded. To use \`${name}\`, run \`pi config\`.`;
|
|
67
|
+
|
|
68
|
+
it('reads the fact from the warning path and the details from its text', () => {
|
|
69
|
+
const warnings = [
|
|
70
|
+
{ path: 'builtin:mcp', warning: text('/agent/extensions/my mcp/index.ts', 'command', '/mcp', 'mcp') },
|
|
71
|
+
{ path: 'builtin:codemode', warning: text('/a/b.ts', 'flag', '--code', 'codemode') },
|
|
72
|
+
{ path: 'builtin:tool-search', warning: text('/a/c.ts', 'tool', 'tool_search', 'tool-search') },
|
|
73
|
+
];
|
|
74
|
+
expect(findReplacedBuiltins({ warnings })).toEqual([
|
|
75
|
+
{ path: 'builtin:mcp', registers: { kind: 'command', name: 'mcp' }, byPath: '/agent/extensions/my mcp/index.ts' },
|
|
76
|
+
{ path: 'builtin:codemode', registers: { kind: 'flag', name: 'code' }, byPath: '/a/b.ts' },
|
|
77
|
+
{ path: 'builtin:tool-search', registers: { kind: 'tool', name: 'tool_search' }, byPath: '/a/c.ts' },
|
|
78
|
+
]);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('leaves details out when the text does not match, and ignores other warnings', () => {
|
|
82
|
+
const warnings = [
|
|
83
|
+
{ path: 'builtin:mcp', warning: 'something else entirely' },
|
|
84
|
+
{ path: 'builtin:codemode', warning: text('/a/b.ts', 'tool', 'x', 'other-name') },
|
|
85
|
+
{ path: '/pkg/package.json', warning: 'Host-provided extension packages must be declared in peerDependencies' },
|
|
86
|
+
{ path: 'npm:thing', warning: 'failed to install (x)' },
|
|
87
|
+
null,
|
|
88
|
+
];
|
|
89
|
+
expect(findReplacedBuiltins({ warnings })).toEqual([{ path: 'builtin:mcp' }, { path: 'builtin:codemode' }]);
|
|
90
|
+
expect(findReplacedBuiltins({})).toEqual([]);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe('findReplacements and describeRuntimeReplacements', () => {
|
|
95
|
+
const result = {
|
|
96
|
+
extensions: [{ ...extension('/agent/extensions/mine.ts', { tools: ['subagent'] }), resolvedPath: '/real/mine.ts' }],
|
|
97
|
+
warnings: [{ path: 'builtin:mcp', warning: 'Extension /agent/extensions/mine.ts registers command `/mcp`, so built-in extension `mcp` was not loaded.' }],
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
it('returns each winner as its resolved path and a path-free name', () => {
|
|
101
|
+
const out = findReplacements({ extensionsResult: result, configuredPluginIds: ['subagents'], registeredNames: names, nameOf: () => 'mine' });
|
|
102
|
+
expect(out).toEqual({
|
|
103
|
+
plugins: [{ id: 'subagents', registers: { kind: 'tool', name: 'subagent' }, by: { path: '/real/mine.ts', name: 'mine' } }],
|
|
104
|
+
builtins: [{ path: 'builtin:mcp', registers: { kind: 'command', name: 'mcp' }, by: { path: '/real/mine.ts', name: 'mine' } }],
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('is unknown for a session without a loaded extension result', () => {
|
|
109
|
+
expect(describeRuntimeReplacements({ session: {}, configuredPluginIds: [], registeredNames: new Map() })).toBeUndefined();
|
|
110
|
+
expect(describeRuntimeReplacements({
|
|
111
|
+
session: { resourceLoader: { getExtensions: () => { throw new Error('x'); } } }, configuredPluginIds: [], registeredNames: new Map(),
|
|
112
|
+
})).toBeUndefined();
|
|
113
|
+
const session = { resourceLoader: { getExtensions: () => result } };
|
|
114
|
+
expect(describeRuntimeReplacements({ session, configuredPluginIds: ['subagents'], registeredNames: names }).plugins[0].by.name).toBe('mine');
|
|
115
|
+
});
|
|
116
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
/** The mode extensions see by default: PiChamber hosts `ctx.ui.custom()`. */
|
|
5
|
+
export const DEFAULT_EXTENSION_MODE = 'tui';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The `ctx.mode` a session's extensions are bound with, from the PiChamber
|
|
9
|
+
* "Extension interface" setting (`extensionUi` in `<dataDir>/pi/settings.json`,
|
|
10
|
+
* written by settings-store.js).
|
|
11
|
+
*
|
|
12
|
+
* - `terminal` (or unset): `tui`, so extensions draw their own terminal UI.
|
|
13
|
+
* - `dialogs`: `rpc`, Pi's mode for frontends, so an extension that branches
|
|
14
|
+
* on `ctx.mode` uses Pi's standard dialogs instead. `custom()` stays hosted
|
|
15
|
+
* either way; this only changes what extensions are told.
|
|
16
|
+
*
|
|
17
|
+
* Read once per binding: Pi keeps a session's mode until the session is
|
|
18
|
+
* created again (reload keeps it), so a change applies to sessions started
|
|
19
|
+
* afterwards. A missing or unreadable file means the default; the settings
|
|
20
|
+
* page reports an invalid file itself when it loads.
|
|
21
|
+
*/
|
|
22
|
+
export const resolveExtensionMode = ({ dataDir, readFile = readFileSync } = {}) => {
|
|
23
|
+
if (!dataDir) return DEFAULT_EXTENSION_MODE;
|
|
24
|
+
try {
|
|
25
|
+
const settings = JSON.parse(readFile(join(dataDir, 'pi', 'settings.json'), 'utf8'));
|
|
26
|
+
return settings?.extensionUi === 'dialogs' ? 'rpc' : DEFAULT_EXTENSION_MODE;
|
|
27
|
+
} catch {
|
|
28
|
+
return DEFAULT_EXTENSION_MODE;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { describe, expect, it } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { resolveExtensionMode } from './extension-ui-mode.js';
|
|
8
|
+
|
|
9
|
+
const dataDirWith = async (contents) => {
|
|
10
|
+
const dataDir = await mkdtemp(join(tmpdir(), 'pichamber-extension-ui-'));
|
|
11
|
+
if (contents !== undefined) {
|
|
12
|
+
await mkdir(join(dataDir, 'pi'), { recursive: true });
|
|
13
|
+
await writeFile(join(dataDir, 'pi', 'settings.json'), contents);
|
|
14
|
+
}
|
|
15
|
+
return dataDir;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
describe('resolveExtensionMode', () => {
|
|
19
|
+
it('reports the terminal UI when nothing is set', async () => {
|
|
20
|
+
expect(resolveExtensionMode({ dataDir: await dataDirWith(undefined) })).toBe('tui');
|
|
21
|
+
expect(resolveExtensionMode({ dataDir: await dataDirWith('{"version":1}') })).toBe('tui');
|
|
22
|
+
expect(resolveExtensionMode({})).toBe('tui');
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('maps the two settings to Pi modes', async () => {
|
|
26
|
+
expect(resolveExtensionMode({ dataDir: await dataDirWith('{"version":1,"extensionUi":"dialogs"}') })).toBe('rpc');
|
|
27
|
+
expect(resolveExtensionMode({ dataDir: await dataDirWith('{"version":1,"extensionUi":"terminal"}') })).toBe('tui');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('keeps the default for an unreadable file or an unknown value', async () => {
|
|
31
|
+
expect(resolveExtensionMode({ dataDir: await dataDirWith('{not json') })).toBe('tui');
|
|
32
|
+
expect(resolveExtensionMode({ dataDir: await dataDirWith('{"extensionUi":"rpc"}') })).toBe('tui');
|
|
33
|
+
});
|
|
34
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// PiChamber's own dialog calls (`choose`, `form`, `openUrl`) live on a
|
|
2
|
+
// `pichamber` object, not on Pi's `ctx.ui`, so a method Pi adds later with
|
|
3
|
+
// the same name and another shape cannot be shadowed by ours.
|
|
4
|
+
//
|
|
5
|
+
// The session's ui context carries the working implementations under a
|
|
6
|
+
// Symbol key. A Symbol cannot collide with any name Pi adds, and Pi's runner
|
|
7
|
+
// copies the ui context with an object spread, which keeps own symbol
|
|
8
|
+
// properties. `pichamber.ui.x(ctx, ...)` reads them back from `ctx.ui`, so no
|
|
9
|
+
// session lookup is needed: `ctx` already identifies the session.
|
|
10
|
+
|
|
11
|
+
export const PICHAMBER_UI = Symbol.for('pichamber.ui');
|
|
12
|
+
|
|
13
|
+
const NAMES = ['choose', 'form', 'openUrl'];
|
|
14
|
+
|
|
15
|
+
const missingContext = (name) => new TypeError(
|
|
16
|
+
`pichamber.ui.${name} needs the tool or handler \`ctx\` of a PiChamber session as its first argument.`,
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `{ choose, form, openUrl }`, each taking `ctx` first. Every call returns a
|
|
21
|
+
* promise; a `ctx` with no PiChamber session behind it rejects with a
|
|
22
|
+
* `TypeError` and never throws synchronously.
|
|
23
|
+
*/
|
|
24
|
+
export const createPichamberUi = () => {
|
|
25
|
+
const ui = {};
|
|
26
|
+
for (const name of NAMES) {
|
|
27
|
+
ui[name] = async (ctx, ...args) => {
|
|
28
|
+
const impl = ctx?.ui?.[PICHAMBER_UI]?.[name];
|
|
29
|
+
if (typeof impl !== 'function') throw missingContext(name);
|
|
30
|
+
return impl(...args);
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return Object.freeze(ui);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Stand-in `ui` whose calls resolve with nothing, for measuring a plugin
|
|
38
|
+
* without a session (`openUrl` resolves `false`).
|
|
39
|
+
*/
|
|
40
|
+
export const createInertPichamberUi = () => Object.freeze({
|
|
41
|
+
choose: async () => undefined,
|
|
42
|
+
form: async () => undefined,
|
|
43
|
+
openUrl: async () => false,
|
|
44
|
+
});
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
|
+
import { createPichamberUi } from './pichamber-ui.js';
|
|
5
|
+
|
|
6
|
+
// Holds the PiChamber plugins the server configured through the private
|
|
7
|
+
// `plugins.configure` command and turns the enabled ones into Pi extension
|
|
8
|
+
// factories. The daemon never reads plugin state or the enabled set from
|
|
9
|
+
// disk: it may run in a sandbox without access to PiChamber's data folder.
|
|
10
|
+
// Until the server configures it, the host has no plugins.
|
|
11
|
+
|
|
12
|
+
/** Bundled plugin code lives in the web package, a read root of the sandbox. */
|
|
13
|
+
const BUNDLED_PLUGINS_ROOT = fileURLToPath(new URL('../../../../plugins/', import.meta.url));
|
|
14
|
+
|
|
15
|
+
const ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
16
|
+
const MAX_PLUGINS = 64;
|
|
17
|
+
const MAX_DIRECTORIES = 4096;
|
|
18
|
+
const MAX_SESSIONS = 4096;
|
|
19
|
+
const MAX_SESSION_ID_LENGTH = 256;
|
|
20
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
21
|
+
|
|
22
|
+
class PluginHostError extends Error {
|
|
23
|
+
constructor(message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.code = 'INVALID_ARGUMENT';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const invalid = (message = 'The plugin configuration is invalid.') => new PluginHostError(message);
|
|
30
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
31
|
+
|
|
32
|
+
const parseValues = (value) => {
|
|
33
|
+
if (!isRecord(value)) throw invalid();
|
|
34
|
+
const values = {};
|
|
35
|
+
for (const [key, stored] of Object.entries(value)) {
|
|
36
|
+
if (FORBIDDEN_KEYS.has(key) || (typeof stored !== 'boolean' && typeof stored !== 'string')) throw invalid();
|
|
37
|
+
values[key] = stored;
|
|
38
|
+
}
|
|
39
|
+
return values;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const parseState = (value) => {
|
|
43
|
+
if (!isRecord(value)) throw invalid();
|
|
44
|
+
const projectsInput = value.projects ?? {};
|
|
45
|
+
if (!isRecord(projectsInput) || Object.keys(projectsInput).length > MAX_DIRECTORIES) throw invalid();
|
|
46
|
+
const projects = new Map();
|
|
47
|
+
for (const [directory, values] of Object.entries(projectsInput)) {
|
|
48
|
+
if (!isAbsolute(directory)) throw invalid();
|
|
49
|
+
projects.set(resolve(directory), parseValues(values));
|
|
50
|
+
}
|
|
51
|
+
const sessionsInput = value.sessions ?? {};
|
|
52
|
+
if (!isRecord(sessionsInput) || Object.keys(sessionsInput).length > MAX_SESSIONS) throw invalid();
|
|
53
|
+
const sessions = new Map();
|
|
54
|
+
for (const [sessionId, values] of Object.entries(sessionsInput)) {
|
|
55
|
+
if (sessionId.length === 0 || sessionId.length > MAX_SESSION_ID_LENGTH || FORBIDDEN_KEYS.has(sessionId)) throw invalid();
|
|
56
|
+
sessions.set(sessionId, parseValues(values));
|
|
57
|
+
}
|
|
58
|
+
return { global: parseValues(value.global ?? {}), projects, sessions };
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Validate the `plugins.configure` payload. Throws INVALID_ARGUMENT. */
|
|
62
|
+
export const parsePluginConfig = (payload) => {
|
|
63
|
+
if (!isRecord(payload) || !Array.isArray(payload.plugins) || payload.plugins.length > MAX_PLUGINS) throw invalid();
|
|
64
|
+
const seen = new Set();
|
|
65
|
+
return payload.plugins.map((plugin) => {
|
|
66
|
+
if (!isRecord(plugin) || typeof plugin.id !== 'string' || plugin.id.length > 40 || !ID_PATTERN.test(plugin.id)) throw invalid();
|
|
67
|
+
if (seen.has(plugin.id)) throw invalid();
|
|
68
|
+
seen.add(plugin.id);
|
|
69
|
+
if (typeof plugin.entry !== 'string' || !isAbsolute(plugin.entry)) throw invalid();
|
|
70
|
+
if (plugin.replaceable !== undefined && typeof plugin.replaceable !== 'boolean') throw invalid();
|
|
71
|
+
return {
|
|
72
|
+
id: plugin.id,
|
|
73
|
+
entry: resolve(plugin.entry),
|
|
74
|
+
replaceable: plugin.replaceable === true,
|
|
75
|
+
state: parseState(plugin.state ?? {}),
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const sortedEntries = (map) => [...map.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
81
|
+
const stateKey = (state) => JSON.stringify([state.global, sortedEntries(state.projects), sortedEntries(state.sessions)]);
|
|
82
|
+
|
|
83
|
+
const isInside = (root, target) => {
|
|
84
|
+
const fromRoot = relative(root, target);
|
|
85
|
+
return fromRoot.length > 0 && !fromRoot.startsWith('..') && !isAbsolute(fromRoot);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export const createPluginHost = ({
|
|
89
|
+
pluginsRoot = BUNDLED_PLUGINS_ROOT,
|
|
90
|
+
importModule = (entry) => import(pathToFileURL(entry).href),
|
|
91
|
+
logger = console,
|
|
92
|
+
} = {}) => {
|
|
93
|
+
// id -> { id, entry, replaceable, state, factory, listeners: Set<Set<fn>> }
|
|
94
|
+
let loaded = new Map();
|
|
95
|
+
let queue = Promise.resolve();
|
|
96
|
+
// id -> Set of `tool:x`, `command:y`, `flag:z`, as the plugin's factory
|
|
97
|
+
// registered them in any runtime. Lets the daemon tell which extension took
|
|
98
|
+
// a plugin's place when Pi drops it. Kept while the plugin stays configured.
|
|
99
|
+
const registered = new Map();
|
|
100
|
+
|
|
101
|
+
// Only modules under the plugins root may load. The server is trusted, but
|
|
102
|
+
// the check keeps a daemon from importing arbitrary files by IPC.
|
|
103
|
+
const loadFactory = async (entry) => {
|
|
104
|
+
const [root, real] = await Promise.all([realpath(pluginsRoot), realpath(entry)]);
|
|
105
|
+
if (!isInside(root, real)) throw new Error('the plugin is outside the plugins folder');
|
|
106
|
+
const module = await importModule(real);
|
|
107
|
+
if (typeof module?.default !== 'function') throw new Error('the plugin has no default export');
|
|
108
|
+
return { entry: real, factory: module.default };
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// Session value over project value over global value.
|
|
112
|
+
const resolveState = (plugin, directory, sessionId) => {
|
|
113
|
+
const project = typeof directory === 'string' && isAbsolute(directory)
|
|
114
|
+
? plugin.state.projects.get(resolve(directory))
|
|
115
|
+
: undefined;
|
|
116
|
+
const session = typeof sessionId === 'string' ? plugin.state.sessions.get(sessionId) : undefined;
|
|
117
|
+
return { ...plugin.state.global, ...(project ?? {}), ...(session ?? {}) };
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const notify = (plugin) => {
|
|
121
|
+
for (const runtimeListeners of plugin.listeners) {
|
|
122
|
+
for (const listener of runtimeListeners) {
|
|
123
|
+
try {
|
|
124
|
+
const result = listener();
|
|
125
|
+
if (result && typeof result.catch === 'function') result.catch(() => {});
|
|
126
|
+
} catch {
|
|
127
|
+
// One listener must not stop the others.
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const applyConfig = async (payload) => {
|
|
134
|
+
const requested = parsePluginConfig(payload);
|
|
135
|
+
const next = new Map();
|
|
136
|
+
const results = [];
|
|
137
|
+
for (const plugin of requested) {
|
|
138
|
+
const previous = loaded.get(plugin.id);
|
|
139
|
+
try {
|
|
140
|
+
const { entry, factory } = previous && previous.requestedEntry === plugin.entry
|
|
141
|
+
? previous
|
|
142
|
+
: await loadFactory(plugin.entry);
|
|
143
|
+
next.set(plugin.id, {
|
|
144
|
+
id: plugin.id,
|
|
145
|
+
requestedEntry: plugin.entry,
|
|
146
|
+
entry,
|
|
147
|
+
factory,
|
|
148
|
+
replaceable: plugin.replaceable,
|
|
149
|
+
state: plugin.state,
|
|
150
|
+
// Live runtimes keep their listeners while the plugin stays loaded.
|
|
151
|
+
listeners: previous && previous.entry === entry ? previous.listeners : new Set(),
|
|
152
|
+
});
|
|
153
|
+
results.push({ id: plugin.id, loaded: true });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
logger.warn?.(`[plugins] could not load plugin ${plugin.id}: ${error?.message ?? 'unknown error'}`);
|
|
156
|
+
results.push({ id: plugin.id, loaded: false, error: 'The plugin could not be loaded.' });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const signature = (plugins) => JSON.stringify([...plugins.values()]
|
|
161
|
+
.map(({ id, entry, replaceable }) => [id, entry, replaceable])
|
|
162
|
+
.sort(([a], [b]) => a.localeCompare(b)));
|
|
163
|
+
const enabledChanged = signature(loaded) !== signature(next);
|
|
164
|
+
const previousEntries = new Map([...loaded.values()].map((plugin) => [plugin.id, plugin.entry]));
|
|
165
|
+
const stateChanged = [...next.values()].filter((plugin) => {
|
|
166
|
+
const previous = loaded.get(plugin.id);
|
|
167
|
+
return previous && previous.listeners === plugin.listeners && stateKey(previous.state) !== stateKey(plugin.state);
|
|
168
|
+
});
|
|
169
|
+
loaded = next;
|
|
170
|
+
for (const id of [...registered.keys()]) {
|
|
171
|
+
if (!next.has(id) || loaded.get(id)?.entry !== previousEntries.get(id)) registered.delete(id);
|
|
172
|
+
}
|
|
173
|
+
for (const plugin of stateChanged) notify(plugin);
|
|
174
|
+
return { enabledChanged, plugins: results };
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Apply a new config. Calls are serialized. Resolves
|
|
179
|
+
* `{ enabledChanged, plugins: [{ id, loaded, error? }] }`; the caller
|
|
180
|
+
* recreates runtimes when `enabledChanged`.
|
|
181
|
+
*/
|
|
182
|
+
const configure = (payload) => {
|
|
183
|
+
const task = queue.then(() => applyConfig(payload));
|
|
184
|
+
queue = task.catch(() => {});
|
|
185
|
+
return task;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// Pi's extension API is a plain object of closures, so a Proxy that notes
|
|
189
|
+
// the three registration calls and forwards everything else is safe.
|
|
190
|
+
const REGISTRATIONS = { registerTool: 'tool', registerCommand: 'command', registerFlag: 'flag' };
|
|
191
|
+
const recordRegistrations = (id, pi) => new Proxy(pi, {
|
|
192
|
+
get(target, property, receiver) {
|
|
193
|
+
const value = Reflect.get(target, property, receiver);
|
|
194
|
+
const kind = typeof property === 'string' ? REGISTRATIONS[property] : undefined;
|
|
195
|
+
if (!kind || typeof value !== 'function') return value;
|
|
196
|
+
return (...args) => {
|
|
197
|
+
const result = value.apply(target, args);
|
|
198
|
+
const name = kind === 'tool' ? args[0]?.name : args[0];
|
|
199
|
+
if (typeof name === 'string' && name.length > 0) {
|
|
200
|
+
const names = registered.get(id) ?? new Set();
|
|
201
|
+
names.add(`${kind}:${name}`);
|
|
202
|
+
registered.set(id, names);
|
|
203
|
+
}
|
|
204
|
+
return result;
|
|
205
|
+
};
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Entries for `resourceLoaderOptions.extensionFactories`, added after Pi's
|
|
211
|
+
* built-ins. Each runtime's factory call gets its own `pichamber` handle; its
|
|
212
|
+
* state listeners are dropped when that session shuts down.
|
|
213
|
+
*/
|
|
214
|
+
const pichamberUi = createPichamberUi();
|
|
215
|
+
const extensionFactories = () => [...loaded.values()].map((plugin) => ({
|
|
216
|
+
name: `pichamber:${plugin.id}`,
|
|
217
|
+
replaceable: plugin.replaceable,
|
|
218
|
+
factory: async (pi) => {
|
|
219
|
+
const runtimeListeners = new Set();
|
|
220
|
+
plugin.listeners.add(runtimeListeners);
|
|
221
|
+
pi.on?.('session_shutdown', () => {
|
|
222
|
+
plugin.listeners.delete(runtimeListeners);
|
|
223
|
+
});
|
|
224
|
+
const pichamber = Object.freeze({
|
|
225
|
+
id: plugin.id,
|
|
226
|
+
ui: pichamberUi,
|
|
227
|
+
state: (directory, sessionId) => resolveState(loaded.get(plugin.id) ?? plugin, directory, sessionId),
|
|
228
|
+
onStateChange: (listener) => {
|
|
229
|
+
if (typeof listener !== 'function') return () => {};
|
|
230
|
+
runtimeListeners.add(listener);
|
|
231
|
+
return () => runtimeListeners.delete(listener);
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
await plugin.factory(recordRegistrations(plugin.id, pi), pichamber);
|
|
235
|
+
},
|
|
236
|
+
}));
|
|
237
|
+
|
|
238
|
+
/** id -> `['tool:x', 'command:y', 'flag:z']` for plugins whose factory has run. */
|
|
239
|
+
const registeredNames = () => new Map([...registered.entries()].map(([id, names]) => [id, [...names]]));
|
|
240
|
+
|
|
241
|
+
/** Ids of the plugins currently configured and importable. */
|
|
242
|
+
const configuredIds = () => [...loaded.keys()];
|
|
243
|
+
|
|
244
|
+
return { configure, extensionFactories, registeredNames, configuredIds };
|
|
245
|
+
};
|