@pi-chamber/web 1.0.8-rc.1 → 1.0.8-rc.3

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 (146) hide show
  1. package/dist/assets/{AgentsSurface-BmHImX8m.js → AgentsSurface-wsW9VCRp.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-C71fGOm2.js → ChoicesArtifact-EwCf4Yxu.js} +1 -1
  3. package/dist/assets/{DiagramView-BZQxoiZu.js → DiagramView-BX6N99cQ.js} +1 -1
  4. package/dist/assets/{DiffView-C70pbgk-.js → DiffView-CI0eSnPP.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-Cu8c3gBV.js → FileSaveConflictDialog-GLj2W7VE.js} +1 -1
  6. package/dist/assets/{FilesView-nFJYEdRw.js → FilesView-CI0tfZQL.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-Jvv_tgbl.js → GitHubDetailScaffold-B85tZ9m7.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-BXD2ODRi.js → GitHubLinkPicker-Y6AuNiGl.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-BWI706F0.js → GitHubListPrimitives-BJHBud6i.js} +1 -1
  10. package/dist/assets/{GitView-MIDG5RYW.js → GitView-DueE69kW.js} +5 -5
  11. package/dist/assets/{IssuesSurface-uNlozeu0.js → IssuesSurface-Cg-xkdIu.js} +3 -3
  12. package/dist/assets/{JsonTreeView-CSLsTriz.js → JsonTreeView-Cvg6lc40.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cs-7BfWi.js → MarkdownRendererImpl-DExPx-QM.js} +1 -1
  14. package/dist/assets/{PatchDiff-axbsnbTJ.js → PatchDiff-_c3HZ34I.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-lwn6w_5w.js → PierreDiffViewer-CZnaqO-_.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-o_AXDjbO.js → PullRequestsSurface-C9AYPiwo.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-C4CMlcbv.js → SessionSwitcherContent-DOpnN-8S.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-DCBVuCoo.js → SessionSwitcherDropdown-CmHMPZ69.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-DyeIrsro.js → SessionUnreadDot-CZCQ4t1J.js} +1 -1
  20. package/dist/assets/SettingsView-D5PO5M3z.js +11 -0
  21. package/dist/assets/{SettingsWindow-Cb4st5y5.js → SettingsWindow-DXV5UOE8.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-BzeMEoFP.js → SubagentsArtifact-CO1ZiI1x.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BP2mOWdV.js → ToolOutputDialog-GOwNLj-y.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-D49XBR9b.js → ToolPartDiffPreview-BoaiZji6.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-CLgDONEQ.js → VirtualizedFileDiff-Chq1X8nw.js} +1 -1
  26. package/dist/assets/VisualFrame-u7aRcX7O.js +22 -0
  27. package/dist/assets/VisualsArtifact-D9vPjihW.js +1 -0
  28. package/dist/assets/{collapsible-BeyKtQGB.js → collapsible-BjpDEohv.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DmO6H8u6.js → computeVirtualFileMetrics-DmPCxbok.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-DOK251YW.js → contextFileOpenGuard-CukNcUeY.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CnzR7kxA.js → fileTreeStatus-CDyfNPYO.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-4kPg2t6j.js → gitStatusPredicates-uI7Y7L5k.js} +1 -1
  33. package/dist/assets/{githubLink-QvaLfNNT.js → githubLink-B9Mxac4R.js} +1 -1
  34. package/dist/assets/{index-DMX9wT1Z.js → index-BWq2ibCw.js} +1 -1
  35. package/dist/assets/index-BxKPJ9uG.js +11 -0
  36. package/dist/assets/index-C5JgjS20.css +1 -0
  37. package/dist/assets/{main-BirYxac2.js → main-CWfC-9xT.js} +4 -4
  38. package/dist/assets/{main-BW9J3Y72.js → main-ckQ0ciIN.js} +2 -2
  39. package/dist/assets/{markdownCore-CxmcPur8.js → markdownCore-p2q2Kxwo.js} +1 -1
  40. package/dist/assets/{miniChat-BRB11eEs.js → miniChat-x2TrwRYA.js} +2 -2
  41. package/dist/assets/{mobile-DJZYYCuB.js → mobile-B0x2G8h1.js} +2 -2
  42. package/dist/assets/{nativeFileSave-B6QpoPRn.js → nativeFileSave-D542OJlG.js} +1 -1
  43. package/dist/assets/{pi-session-focus-preference-PWoh3LNA.js → pi-session-focus-preference-Q_RZUCnt.js} +1 -1
  44. package/dist/assets/{renderDiffWithHighlighter-C48T6YFJ.js → renderDiffWithHighlighter-CSFGSknx.js} +1 -1
  45. package/dist/assets/{renderElectronMiniChatApp-N-BQdJl0.js → renderElectronMiniChatApp-CFIdesZT.js} +2 -2
  46. package/dist/assets/{renderFileWithHighlighter-8Kt2MyTN.js → renderFileWithHighlighter-C5JE0mRX.js} +1 -1
  47. package/dist/assets/renderMobileApp-B1ybjcGM.js +11 -0
  48. package/dist/assets/runtimeEndpointReset-DyZSKCYM.js +66 -0
  49. package/dist/assets/{runtimeSurface-kIEoYsPP.js → runtimeSurface-BR_dhe7_.js} +1 -1
  50. package/dist/assets/{selection-BTEdLRVK.js → selection-CfOpW4rA.js} +1 -1
  51. package/dist/assets/useAppFontEffects-COMvkffC.js +226 -0
  52. package/dist/assets/{useGitHubRemoteSearch-DIBHNu8r.js → useGitHubRemoteSearch-M1AE2YuX.js} +1 -1
  53. package/dist/assets/{useSwitcherItems-DfLbfX37.js → useSwitcherItems-D0i2BYYP.js} +1 -1
  54. package/dist/assets/{web-components-C_DsTJis.js → web-components-wOQkOurQ.js} +1 -1
  55. package/dist/index.html +4 -4
  56. package/dist/mini-chat.html +3 -3
  57. package/dist/mobile.html +3 -3
  58. package/package.json +1 -1
  59. package/plugins/featured.json +12 -0
  60. package/plugins/subagents/package.json +1 -1
  61. package/plugins/visuals/extension.js +8 -5
  62. package/plugins/visuals/package.json +1 -1
  63. package/server/index.js +90 -27
  64. package/server/lib/git/DOCUMENTATION.md +4 -0
  65. package/server/lib/git/service.js +70 -5
  66. package/server/lib/git/service.test.js +179 -0
  67. package/server/lib/github/DOCUMENTATION.md +2 -0
  68. package/server/lib/marketplace/DOCUMENTATION.md +95 -0
  69. package/server/lib/marketplace/featured.js +176 -0
  70. package/server/lib/marketplace/featured.test.js +207 -0
  71. package/server/lib/marketplace/npm-registry.js +255 -0
  72. package/server/lib/marketplace/npm-registry.test.js +227 -0
  73. package/server/lib/marketplace/routes.js +64 -0
  74. package/server/lib/marketplace/routes.test.js +119 -0
  75. package/server/lib/marketplace/service.js +225 -0
  76. package/server/lib/marketplace/service.test.js +174 -0
  77. package/server/lib/notifications/DOCUMENTATION.md +10 -4
  78. package/server/lib/notifications/pi-notification-watcher.js +92 -33
  79. package/server/lib/notifications/pi-notification-watcher.test.js +79 -0
  80. package/server/lib/open-url/DOCUMENTATION.md +1 -0
  81. package/server/lib/pi/merged-event-stream.js +316 -0
  82. package/server/lib/pi/merged-event-stream.test.js +95 -0
  83. package/server/lib/pi/routes-daemon-pool.test.js +348 -0
  84. package/server/lib/pi/routes-merged-events.test.js +327 -0
  85. package/server/lib/pi/routes-sandbox.test.js +1684 -0
  86. package/server/lib/pi/routes.js +491 -90
  87. package/server/lib/pi/routes.test.js +87 -2
  88. package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
  89. package/server/lib/pi/sandbox/launcher.js +122 -0
  90. package/server/lib/pi/sandbox/launcher.test.js +91 -0
  91. package/server/lib/pi/sandbox/nono-launcher.js +455 -0
  92. package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
  93. package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
  94. package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
  95. package/server/lib/pi/sandbox/nono-profile.json +22 -0
  96. package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
  97. package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
  98. package/server/lib/pi/sandbox/project-sandbox.js +207 -0
  99. package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
  100. package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
  101. package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
  102. package/server/lib/pi/sandbox/trust-ask.js +135 -0
  103. package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
  104. package/server/lib/pi/sandbox/worktree-ids.js +96 -0
  105. package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
  106. package/server/lib/pi/session-daemon/DOCUMENTATION.md +26 -6
  107. package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
  108. package/server/lib/pi/session-daemon/daemon-process.js +10 -1
  109. package/server/lib/pi/session-daemon/extension-config.js +206 -23
  110. package/server/lib/pi/session-daemon/extension-config.test.js +180 -0
  111. package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
  112. package/server/lib/pi/session-daemon/session-daemon.js +368 -56
  113. package/server/lib/pi/session-daemon/session-daemon.test.js +227 -0
  114. package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
  115. package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
  116. package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
  117. package/server/lib/pi/session-daemon/session-lease.js +93 -15
  118. package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
  119. package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
  120. package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
  121. package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
  122. package/server/lib/pi/session-daemon/supervisor.js +386 -35
  123. package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
  124. package/server/lib/pi/ui-settings-store.js +90 -3
  125. package/server/lib/pi/ui-settings-store.test.js +118 -0
  126. package/server/lib/plugins/DOCUMENTATION.md +17 -5
  127. package/server/lib/plugins/daemon-sync.js +16 -6
  128. package/server/lib/plugins/daemon-sync.test.js +12 -0
  129. package/server/lib/plugins/impact.test.js +2 -1
  130. package/server/lib/plugins/manifest.js +25 -0
  131. package/server/lib/plugins/manifest.test.js +9 -0
  132. package/server/lib/plugins/routes.test.js +28 -0
  133. package/server/lib/plugins/service.js +24 -2
  134. package/server/lib/server/cross-process-lock.js +28 -3
  135. package/server/lib/wallpaper/DOCUMENTATION.md +25 -0
  136. package/server/lib/wallpaper/routes.js +63 -0
  137. package/server/lib/wallpaper/routes.test.js +109 -0
  138. package/server/lib/wallpaper/store.js +87 -0
  139. package/dist/assets/SettingsView-BHBpt2Um.js +0 -7
  140. package/dist/assets/VisualFrame-CJrAvWSo.js +0 -22
  141. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +0 -1
  142. package/dist/assets/index-B2v0_mez.js +0 -11
  143. package/dist/assets/index-D3F4JrPN.css +0 -1
  144. package/dist/assets/renderMobileApp-B7cT7m5b.js +0 -11
  145. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +0 -62
  146. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +0 -225
package/server/index.js CHANGED
@@ -17,15 +17,25 @@ import { createTailscaleService } from './lib/tailscale/service.js';
17
17
  import { createServerIdResolver } from './lib/relay/server-id.js';
18
18
  import { registerTailscaleRoutes } from './lib/tailscale/routes.js';
19
19
  import { registerPiRuntimeRoutes } from './lib/pi/routes.js';
20
+ import { createPiDaemonPool } from './lib/pi/session-daemon/daemon-pool.js';
20
21
  import { createPluginService } from './lib/plugins/service.js';
21
22
  import { createPluginDaemonSync } from './lib/plugins/daemon-sync.js';
22
23
  import { registerPluginRoutes } from './lib/plugins/routes.js';
24
+ import { createFeaturedSource, DEFAULT_FEATURED_URL } from './lib/marketplace/featured.js';
25
+ import { createNpmRegistry } from './lib/marketplace/npm-registry.js';
26
+ import { registerMarketplaceRoutes } from './lib/marketplace/routes.js';
27
+ import { registerWallpaperRoutes } from './lib/wallpaper/routes.js';
28
+ import { createWallpaperImageStore } from './lib/wallpaper/store.js';
29
+ import { createMarketplaceService } from './lib/marketplace/service.js';
23
30
  import { createDockerInitialLocalSettings, createPiUiSettingsStore } from './lib/pi/ui-settings-store.js';
24
31
  import { detectLinuxDistribution } from './lib/server/linux-distribution.js';
25
32
  import { createPiNotificationWatcher } from './lib/notifications/pi-notification-watcher.js';
26
33
  import { registerWorkspaceIntegrations } from './lib/workspace/host.js';
27
34
  import { createPiSessionDaemonSupervisor } from './lib/pi/session-daemon/supervisor.js';
28
35
  import { createOpenUrlIntake } from './lib/open-url/intake.js';
36
+ import { createNonoLauncher } from './lib/pi/sandbox/nono-launcher.js';
37
+ import { createProjectSandboxManager } from './lib/pi/sandbox/project-sandbox-manager.js';
38
+ import { createTrustAskStore } from './lib/pi/sandbox/trust-ask.js';
29
39
  import {
30
40
  getUnauthenticatedLanErrorMessage,
31
41
  isNetworkExposedBindHost,
@@ -134,6 +144,11 @@ export async function startWebUiServer(options = {}) {
134
144
  const apiOnly = options.apiOnly === true || isEnvFlagEnabled(process.env.PICHAMBER_API_ONLY);
135
145
  const app = express();
136
146
  const server = http.createServer(app);
147
+ // The port the server is listening on, or null before it binds.
148
+ const boundPort = () => {
149
+ const address = server.address();
150
+ return typeof address === 'object' && address ? address.port : null;
151
+ };
137
152
  const serverStartedAt = new Date().toISOString();
138
153
  const dataPath = (name) => path.join(PICHAMBER_DATA_DIR, name);
139
154
  const remoteClientAuthRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto: await import('node:crypto'), storePath: dataPath('remote-clients.json') });
@@ -160,10 +175,7 @@ export async function startWebUiServer(options = {}) {
160
175
  });
161
176
  const tunnelService = createTunnelService({
162
177
  dataDir: PICHAMBER_DATA_DIR,
163
- getPort: () => {
164
- const address = server.address();
165
- return typeof address === 'object' && address ? address.port : null;
166
- },
178
+ getPort: boundPort,
167
179
  tunnelAuthController,
168
180
  getServerLabel: () => os.hostname() || 'PiChamber',
169
181
  });
@@ -185,10 +197,7 @@ export async function startWebUiServer(options = {}) {
185
197
  const tailscaleService = createTailscaleService({
186
198
  dataDir: PICHAMBER_DATA_DIR,
187
199
  getServerId: serverIdResolver.getServerId,
188
- getPort: () => {
189
- const address = server.address();
190
- return typeof address === 'object' && address ? address.port : null;
191
- },
200
+ getPort: boundPort,
192
201
  isUiAuthEnabled: hasUiPasswordConfigured,
193
202
  isUnsafeUnauthenticatedLanAllowed: () => isUnsafeUnauthenticatedLanAllowed(process.env),
194
203
  });
@@ -198,10 +207,7 @@ export async function startWebUiServer(options = {}) {
198
207
  console.warn(`[tailscale] Failed to load persisted config: ${error?.message || error}`);
199
208
  }
200
209
  const pairingTransports = createPairingTransportResolvers({
201
- getPort: () => {
202
- const address = server.address();
203
- return typeof address === 'object' && address ? address.port : null;
204
- },
210
+ getPort: boundPort,
205
211
  bindHost: host,
206
212
  getTailscaleCandidate: () => tailscaleService.getPairingCandidate(),
207
213
  });
@@ -239,10 +245,7 @@ export async function startWebUiServer(options = {}) {
239
245
  serverStartedAt,
240
246
  gracefulShutdown,
241
247
  getHealthSnapshot: () => ({ pi: { state: 'ready' }, apiOnly }),
242
- getServerPort: () => {
243
- const address = server.address();
244
- return typeof address === 'object' && address ? address.port : null;
245
- },
248
+ getServerPort: boundPort,
246
249
  getTunnelUrl: () => null,
247
250
  getServerId: serverIdResolver.getServerId,
248
251
  tunnelAuthController,
@@ -265,21 +268,76 @@ export async function startWebUiServer(options = {}) {
265
268
  getServerLabel: () => os.hostname() || 'PiChamber',
266
269
  });
267
270
  // Plugins: the server owns manifests and state and pushes the enabled set
268
- // to the daemon (lib/plugins/DOCUMENTATION.md). A health probe runs the
269
- // supervisor's onDaemonReady hook, which pushes.
271
+ // to every daemon (lib/plugins/DOCUMENTATION.md). A health probe runs the
272
+ // supervisor's onDaemonReady hook, which pushes. A sandboxed project's
273
+ // daemon gets a config trimmed to its own folders.
270
274
  const pluginService = createPluginService();
271
275
  const pluginDaemonSync = createPluginDaemonSync({
272
- buildConfig: () => pluginService.daemonConfig(),
276
+ buildConfig: (scope) => pluginService.daemonConfig(scope),
273
277
  refresh: () => piSessionDaemonRuntime?.health(),
274
278
  });
275
- const piRuntimeRoutes = registerPiRuntimeRoutes(app, {
276
- getPiSessionDaemonRuntime: () => piSessionDaemonRuntime,
279
+ // The main daemon is today's supervisor; project daemons register here.
280
+ const piDaemonPool = createPiDaemonPool({ getMainRuntime: () => piSessionDaemonRuntime });
281
+ // Sandboxed projects get their own daemon, started through nono on first
282
+ // use. With no sandboxed project this registers nothing and probes nothing.
283
+ let piRuntimeRoutes = null;
284
+ // Folders whose Pi trust stays "ask" after their sandbox was turned off;
285
+ // the daemons read the same file (sandbox/trust-ask.js).
286
+ const piTrustAsk = createTrustAskStore({ dataDir: PICHAMBER_DATA_DIR });
287
+ const piSandboxManager = createProjectSandboxManager({
288
+ daemonPool: piDaemonPool,
289
+ trustAsk: piTrustAsk,
290
+ uiSettingsStore,
291
+ launcher: createNonoLauncher({
292
+ stageDir: path.join(PICHAMBER_DATA_DIR, 'pi', 'sandbox'),
293
+ customProfileFile: path.join(PICHAMBER_DATA_DIR, 'pi', 'sandbox', 'nono-profile.custom.json'),
294
+ }),
295
+ dataDir: PICHAMBER_DATA_DIR,
296
+ agentDir: async () => {
297
+ const configured = typeof process.env.PICHAMBER_PI_AGENT_DIR === 'string' ? process.env.PICHAMBER_PI_AGENT_DIR.trim() : '';
298
+ if (configured) return configured;
299
+ return (await import('@earendil-works/pi-coding-agent')).getAgentDir();
300
+ },
301
+ getServerPort: boundPort,
302
+ hasConnectedDevices: () => piRuntimeRoutes?.hasLiveEventStreams() ?? false,
303
+ // The same port and version as the main daemon, so sandbox profile keys
304
+ // extend the main daemon's.
305
+ supervisorOptions: ({ roots } = {}) => ({
306
+ port: boundPort() ?? port,
307
+ version: PICHAMBER_VERSION,
308
+ onDaemonReady: pluginDaemonSync.onDaemonReadyFor({ roots }),
309
+ }),
310
+ });
311
+ piRuntimeRoutes = registerPiRuntimeRoutes(app, {
312
+ daemonPool: piDaemonPool,
313
+ sandboxManager: piSandboxManager,
314
+ trustAsk: piTrustAsk,
277
315
  uiSettingsStore,
278
316
  onSessionDeleted: async (sessionId) => {
279
317
  if (await pluginService.forgetSession(sessionId)) pluginDaemonSync.changed();
280
318
  },
281
319
  });
282
320
  registerPluginRoutes(app, { service: pluginService, onChange: pluginDaemonSync.changed });
321
+ // The new-session wallpaper picture (lib/wallpaper/DOCUMENTATION.md).
322
+ registerWallpaperRoutes(app, { express, store: createWallpaperImageStore({ dataDir: PICHAMBER_DATA_DIR }) });
323
+ // Marketplace: npm search and the featured list (lib/marketplace/DOCUMENTATION.md).
324
+ // PICHAMBER_NPM_REGISTRY_URL / PICHAMBER_NPM_DOWNLOADS_URL point it at a
325
+ // mirror or a test fixture; PICHAMBER_FEATURED_URL=off stops refreshing the
326
+ // featured list from the repository.
327
+ const featuredUrlSetting = process.env.PICHAMBER_FEATURED_URL;
328
+ registerMarketplaceRoutes(app, {
329
+ service: createMarketplaceService({
330
+ registry: createNpmRegistry({
331
+ ...(process.env.PICHAMBER_NPM_REGISTRY_URL ? { registryUrl: process.env.PICHAMBER_NPM_REGISTRY_URL } : {}),
332
+ ...(process.env.PICHAMBER_NPM_DOWNLOADS_URL ? { downloadsUrl: process.env.PICHAMBER_NPM_DOWNLOADS_URL } : {}),
333
+ }),
334
+ featuredSource: createFeaturedSource({
335
+ cachePath: dataPath(path.join('pi', 'featured.json')),
336
+ remoteUrl: featuredUrlSetting === 'off' ? null : featuredUrlSetting || DEFAULT_FEATURED_URL,
337
+ }),
338
+ bundledPackageNames: () => pluginService.bundledPackageNames(),
339
+ }),
340
+ });
283
341
  // Cloudflare Tunnel external access (managed-remote and managed-local modes).
284
342
  const requireTunnelAuth = (req, res, next) => uiAuthController.requireAuth(req, res, next);
285
343
  app.get('/api/pichamber/tunnel/status', requireTunnelAuth, async (_req, res) => {
@@ -318,7 +376,7 @@ export async function startWebUiServer(options = {}) {
318
376
  void tailscaleService.reconcile().catch((error) => {
319
377
  console.warn(`[tailscale] Failed to apply mapping on startup: ${error?.message || error}`);
320
378
  });
321
- const resolvedPort = typeof server.address() === 'object' && server.address() ? server.address().port : null;
379
+ const resolvedPort = boundPort();
322
380
  piSessionDaemonRuntime = createPiSessionDaemonSupervisor({
323
381
  dataDir: PICHAMBER_DATA_DIR,
324
382
  port: typeof resolvedPort === 'number' ? resolvedPort : port,
@@ -339,7 +397,7 @@ export async function startWebUiServer(options = {}) {
339
397
  // supplies its native notification callback.
340
398
  if (typeof options.onDesktopNotification === 'function') {
341
399
  notificationWatcher = createPiNotificationWatcher({
342
- supervisor: piSessionDaemonRuntime,
400
+ daemonPool: piDaemonPool,
343
401
  uiSettingsStore,
344
402
  notify: options.onDesktopNotification,
345
403
  });
@@ -356,6 +414,13 @@ export async function startWebUiServer(options = {}) {
356
414
  } catch (error) {
357
415
  console.warn(`[open-url] Intake unavailable: ${error?.code ?? 'UNKNOWN'}`);
358
416
  }
417
+ // Register sandboxed projects before any request can route; a failure
418
+ // leaves those projects unregistered, so log it loudly.
419
+ try {
420
+ await piSandboxManager.reconcile();
421
+ } catch (error) {
422
+ console.warn(`[pi-sandbox] Could not load project sandbox settings: ${error?.code ?? error?.message ?? 'UNKNOWN'}`);
423
+ }
359
424
  void piSessionDaemonRuntime.start()
360
425
  .then(() => {
361
426
  // Configure plugins on the started daemon; later requests re-check.
@@ -370,10 +435,7 @@ export async function startWebUiServer(options = {}) {
370
435
  const controller = {
371
436
  expressApp: app,
372
437
  httpServer: server,
373
- getPort: () => {
374
- const address = server.address();
375
- return typeof address === 'object' && address ? address.port : null;
376
- },
438
+ getPort: boundPort,
377
439
  getTunnelUrl: () => null,
378
440
  getDaemonProfileKey: () => piSessionDaemonRuntime?.paths?.profileKey ?? null,
379
441
  getTailscaleStatus: () => tailscaleService.getStatus(),
@@ -390,6 +452,7 @@ export async function startWebUiServer(options = {}) {
390
452
  await Promise.allSettled([
391
453
  notificationWatcher?.stop(),
392
454
  openUrlIntake.stop(),
455
+ piSandboxManager.stop(),
393
456
  workspaceRuntime.shutdown(),
394
457
  piSessionDaemonRuntime ? piSessionDaemonRuntime.stop() : Promise.resolve(),
395
458
  tailscaleService.shutdown(),
@@ -24,6 +24,10 @@ This module provides Git repository operations for the web server runtime, inclu
24
24
  any git config previously written into repositories are left untouched on
25
25
  disk.
26
26
 
27
+ ## Sandbox
28
+
29
+ Only Pi session daemons (the agent) run in the sandbox. PiChamber's own Git panel, terminal, browser and GitHub features, and worktree hooks and start commands, run outside it with the user's access, so git config, hooks or filters an agent writes into the repo can run when the user or the Git panel runs git. This is a known, accepted trade-off. Git runs the same for every folder, sandboxed project or not. One exception is the worktree folder id: for a project the sandbox manager has remembered an id for (`../pi/sandbox/worktree-ids.js`), new worktrees are filed under that id, not the one in `.git/pichamber`, which the sandboxed agent can rewrite; an unreadable record fails the worktree operation. A project nothing is remembered for is kept out of folders remembered for other projects: when its id (a second clone of the same repository has the same one) is remembered for another root, its worktrees are filed under an id of its own (`ownWorktreeId`), so they never land in a folder a sandbox is granted.
30
+
27
31
  ## Public API
28
32
 
29
33
  The following functions are exported and used by the web server:
@@ -2,10 +2,12 @@ import simpleGit from 'simple-git';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import os from 'os';
5
+ import crypto from 'crypto';
5
6
  import { execFile } from 'child_process';
6
7
  import { promisify } from 'util';
7
8
  import { createRequire } from 'module';
8
9
  import { resolvePiChamberDataPath } from '../pichamber-data-dir.js';
10
+ import { createWorktreeIdStore, ownWorktreeId } from '../pi/sandbox/worktree-ids.js';
9
11
 
10
12
  const fsp = fs.promises;
11
13
  const require = createRequire(import.meta.url);
@@ -1506,12 +1508,75 @@ export async function continueIntegrate(stateInput = {}) {
1506
1508
  return { kind: 'success', moved: state.remainingCommits.length };
1507
1509
  }
1508
1510
 
1511
+ const PICHAMBER_ID_FILE_MAX_BYTES = 256;
1512
+
1513
+ // Sandboxed code can write `.git`, so the id file is never followed through a
1514
+ // symlink: it is read only as a small regular file, and replaced by renaming a
1515
+ // new file over it (rename swaps a symlink itself, it does not follow it).
1516
+ const readPiChamberIdFile = async (idFile) => {
1517
+ const info = await fsp.lstat(idFile).catch(() => null);
1518
+ if (!info?.isFile() || info.size > PICHAMBER_ID_FILE_MAX_BYTES) return '';
1519
+ const handle = await fsp.open(idFile, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)).catch(() => null);
1520
+ if (!handle) return '';
1521
+ try {
1522
+ const buffer = Buffer.alloc(PICHAMBER_ID_FILE_MAX_BYTES + 1);
1523
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
1524
+ return bytesRead > PICHAMBER_ID_FILE_MAX_BYTES ? '' : buffer.toString('utf8', 0, bytesRead).trim();
1525
+ } catch {
1526
+ return '';
1527
+ } finally {
1528
+ await handle.close().catch(() => undefined);
1529
+ }
1530
+ };
1531
+
1532
+ const writePiChamberIdFile = async (idFile, projectId) => {
1533
+ const info = await fsp.lstat(idFile).catch((error) => (error?.code === 'ENOENT' ? null : undefined));
1534
+ // A symlink is replaced itself by the rename below; anything else that is
1535
+ // not a regular file (a directory, a device) is left alone.
1536
+ if (info === undefined || (info && !info.isFile() && !info.isSymbolicLink())) return;
1537
+ const temp = `${idFile}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`;
1538
+ try {
1539
+ await fsp.writeFile(temp, projectId, { encoding: 'utf8', flag: 'wx', mode: 0o644 });
1540
+ await fsp.rename(temp, idFile);
1541
+ } catch {
1542
+ await fsp.rm(temp, { force: true }).catch(() => undefined);
1543
+ }
1544
+ };
1545
+
1546
+ // The id a sandboxed project was first seen with. Its sandbox owns and is
1547
+ // granted `worktree/<that id>` only, and the sandboxed agent can rewrite the
1548
+ // id file, so a remembered id stands whatever the file says: a worktree
1549
+ // created under another id would be outside the sandbox, or inside another
1550
+ // project's. An unreadable record throws rather than trust the file.
1551
+ const rememberedPiChamberProjectIds = async (primaryWorktree) => {
1552
+ const ids = await createWorktreeIdStore({ file: resolvePiChamberDataPath(['pi', 'sandbox', 'worktree-ids.json']) }).read();
1553
+ const root = path.resolve(primaryWorktree);
1554
+ const real = await fsp.realpath(root).catch(() => root);
1555
+ return {
1556
+ own: ids.get(root) ?? ids.get(real) ?? null,
1557
+ // Ids remembered for other projects: their sandboxes are granted those
1558
+ // folders, so this project's worktrees must not be filed there.
1559
+ others: new Set([...ids].filter(([other]) => other !== root && other !== real).map(([, id]) => id)),
1560
+ };
1561
+ };
1562
+
1563
+ // The worktree folder id of a project nothing is remembered for. A clone of
1564
+ // a repository whose folder a sandboxed project holds gets its own instead.
1565
+ const unsharedPiChamberProjectId = (primaryWorktree, id, others) => (
1566
+ others.has(id) ? ownWorktreeId(primaryWorktree) : id
1567
+ );
1568
+
1509
1569
  const ensurePiChamberProjectId = async (primaryWorktree) => {
1570
+ const { own: remembered, others } = await rememberedPiChamberProjectIds(primaryWorktree);
1571
+ if (remembered) return remembered;
1510
1572
  const gitDir = path.join(primaryWorktree, '.git');
1511
1573
  const idFile = path.join(gitDir, 'pichamber');
1512
- const existing = await fsp.readFile(idFile, 'utf8').then((value) => value.trim()).catch(() => '');
1513
- if (existing) {
1514
- return existing;
1574
+ const existing = await readPiChamberIdFile(idFile);
1575
+ // The id names a folder under the data directory, and an agent working in
1576
+ // the repository can write this file: only a commit hash is taken from it.
1577
+ // Anything else is replaced by the id derived below.
1578
+ if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(existing)) {
1579
+ return unsharedPiChamberProjectId(primaryWorktree, existing, others);
1515
1580
  }
1516
1581
 
1517
1582
  const rootsResult = await runGitCommandOrThrow(
@@ -1532,9 +1597,9 @@ const ensurePiChamberProjectId = async (primaryWorktree) => {
1532
1597
  }
1533
1598
 
1534
1599
  await fsp.mkdir(gitDir, { recursive: true }).catch(() => undefined);
1535
- await fsp.writeFile(idFile, projectId, 'utf8').catch(() => undefined);
1600
+ await writePiChamberIdFile(idFile, projectId);
1536
1601
 
1537
- return projectId;
1602
+ return unsharedPiChamberProjectId(primaryWorktree, projectId, others);
1538
1603
  };
1539
1604
 
1540
1605
  const resolveWorktreeProjectContext = async (directory) => {
@@ -622,6 +622,185 @@ describe('worktree root resolution', () => {
622
622
  // ---------------------------------------------------------------------------
623
623
 
624
624
  describe('createWorktree', () => {
625
+ it('takes only a commit hash from the repository id file, so worktrees stay under the data folder', async () => {
626
+ if (!canRunGit()) return;
627
+
628
+ const previousPiChamberDataDir = process.env.PICHAMBER_DATA_DIR;
629
+ const dataHome = createTempDir();
630
+ process.env.PICHAMBER_DATA_DIR = dataHome;
631
+ try {
632
+ const repo = createTempDir();
633
+ runGit(repo, ['init', '-b', 'main']);
634
+ runGit(repo, ['config', 'user.email', 'test@example.com']);
635
+ runGit(repo, ['config', 'user.name', 'Test User']);
636
+ fs.writeFileSync(path.join(repo, 'README.md'), '# Test\n');
637
+ runGit(repo, ['add', 'README.md']);
638
+ runGit(repo, ['commit', '-m', 'Initial commit']);
639
+ const rootCommit = runGit(repo, ['rev-list', '--max-parents=0', 'HEAD']).trim();
640
+ // Something working in the repository pointed the id out of the data folder.
641
+ const idFile = path.join(repo, '.git', 'pichamber');
642
+ fs.writeFileSync(idFile, '../../escape');
643
+
644
+ const created = await createWorktree(repo, {
645
+ mode: 'new',
646
+ branchName: 'feature/id-check',
647
+ worktreeName: 'id-check',
648
+ returnAfterDirectoryCreated: true,
649
+ });
650
+
651
+ const worktreeRoot = path.join(fs.realpathSync(dataHome), 'worktree', rootCommit);
652
+ expect(fs.realpathSync(created.path).startsWith(`${worktreeRoot}${path.sep}`)).toBe(true);
653
+ expect(fs.existsSync(path.join(dataHome, 'escape'))).toBe(false);
654
+ expect(fs.readFileSync(idFile, 'utf8')).toBe(rootCommit);
655
+ await expect.poll(
656
+ async () => (await getWorktreeBootstrapStatus(created.path)).phase,
657
+ { timeout: 5_000 },
658
+ ).toBe('setup-ready');
659
+ } finally {
660
+ if (previousPiChamberDataDir === undefined) {
661
+ delete process.env.PICHAMBER_DATA_DIR;
662
+ } else {
663
+ process.env.PICHAMBER_DATA_DIR = previousPiChamberDataDir;
664
+ }
665
+ }
666
+ });
667
+
668
+ it('keeps a project\'s worktrees out of a folder remembered for another (sandboxed) project', async () => {
669
+ if (!canRunGit()) return;
670
+
671
+ const previousPiChamberDataDir = process.env.PICHAMBER_DATA_DIR;
672
+ const dataHome = createTempDir();
673
+ process.env.PICHAMBER_DATA_DIR = dataHome;
674
+ try {
675
+ const repo = createTempDir();
676
+ runGit(repo, ['init', '-b', 'main']);
677
+ runGit(repo, ['config', 'user.email', 'test@example.com']);
678
+ runGit(repo, ['config', 'user.name', 'Test User']);
679
+ fs.writeFileSync(path.join(repo, 'README.md'), '# Test\n');
680
+ runGit(repo, ['add', 'README.md']);
681
+ runGit(repo, ['commit', '-m', 'Initial commit']);
682
+ // Another clone of this repository is sandboxed and holds the folder
683
+ // named by the repository's root commit.
684
+ const shared = runGit(repo, ['rev-list', '--max-parents=0', 'HEAD']).trim();
685
+ const record = path.join(dataHome, 'pi', 'sandbox', 'worktree-ids.json');
686
+ fs.mkdirSync(path.dirname(record), { recursive: true });
687
+ fs.writeFileSync(record, JSON.stringify({ version: 1, projects: { '/code/other-clone': shared } }));
688
+
689
+ const created = await createWorktree(repo, {
690
+ mode: 'new',
691
+ branchName: 'feature/own-folder',
692
+ worktreeName: 'own-folder',
693
+ returnAfterDirectoryCreated: true,
694
+ });
695
+ expect(fs.existsSync(path.join(dataHome, 'worktree', shared))).toBe(false);
696
+ expect(fs.realpathSync(created.path).startsWith(`${path.join(fs.realpathSync(dataHome), 'worktree')}${path.sep}`)).toBe(true);
697
+ await expect.poll(
698
+ async () => (await getWorktreeBootstrapStatus(created.path)).phase,
699
+ { timeout: 5_000 },
700
+ ).toBe('setup-ready');
701
+ } finally {
702
+ if (previousPiChamberDataDir === undefined) {
703
+ delete process.env.PICHAMBER_DATA_DIR;
704
+ } else {
705
+ process.env.PICHAMBER_DATA_DIR = previousPiChamberDataDir;
706
+ }
707
+ }
708
+ });
709
+
710
+ it('files worktrees under the id remembered for a sandboxed project, whatever its id file says', async () => {
711
+ if (!canRunGit()) return;
712
+
713
+ const previousPiChamberDataDir = process.env.PICHAMBER_DATA_DIR;
714
+ const dataHome = createTempDir();
715
+ process.env.PICHAMBER_DATA_DIR = dataHome;
716
+ try {
717
+ const repo = createTempDir();
718
+ runGit(repo, ['init', '-b', 'main']);
719
+ runGit(repo, ['config', 'user.email', 'test@example.com']);
720
+ runGit(repo, ['config', 'user.name', 'Test User']);
721
+ fs.writeFileSync(path.join(repo, 'README.md'), '# Test\n');
722
+ runGit(repo, ['add', 'README.md']);
723
+ runGit(repo, ['commit', '-m', 'Initial commit']);
724
+ const remembered = 'c'.repeat(40);
725
+ const record = path.join(dataHome, 'pi', 'sandbox', 'worktree-ids.json');
726
+ fs.mkdirSync(path.dirname(record), { recursive: true });
727
+ fs.writeFileSync(record, JSON.stringify({ version: 1, projects: { [path.resolve(repo)]: remembered } }));
728
+ // The sandboxed agent named another project's worktree folder.
729
+ const idFile = path.join(repo, '.git', 'pichamber');
730
+ fs.writeFileSync(idFile, 'd'.repeat(40));
731
+
732
+ const created = await createWorktree(repo, {
733
+ mode: 'new',
734
+ branchName: 'feature/remembered',
735
+ worktreeName: 'remembered',
736
+ returnAfterDirectoryCreated: true,
737
+ });
738
+ const worktreeRoot = path.join(fs.realpathSync(dataHome), 'worktree', remembered);
739
+ expect(fs.realpathSync(created.path).startsWith(`${worktreeRoot}${path.sep}`)).toBe(true);
740
+ expect(fs.existsSync(path.join(dataHome, 'worktree', 'd'.repeat(40)))).toBe(false);
741
+ await expect.poll(
742
+ async () => (await getWorktreeBootstrapStatus(created.path)).phase,
743
+ { timeout: 5_000 },
744
+ ).toBe('setup-ready');
745
+
746
+ // A record that cannot be read is not answered from the file.
747
+ fs.writeFileSync(record, '{');
748
+ await expect(createWorktree(repo, {
749
+ mode: 'new',
750
+ branchName: 'feature/unreadable',
751
+ worktreeName: 'unreadable',
752
+ returnAfterDirectoryCreated: true,
753
+ })).rejects.toThrow();
754
+ expect(fs.existsSync(path.join(dataHome, 'worktree', 'd'.repeat(40)))).toBe(false);
755
+ } finally {
756
+ if (previousPiChamberDataDir === undefined) {
757
+ delete process.env.PICHAMBER_DATA_DIR;
758
+ } else {
759
+ process.env.PICHAMBER_DATA_DIR = previousPiChamberDataDir;
760
+ }
761
+ }
762
+ });
763
+
764
+ it('does not follow a symlink planted at the repository id file', async () => {
765
+ if (!canRunGit()) return;
766
+
767
+ const previousPiChamberDataDir = process.env.PICHAMBER_DATA_DIR;
768
+ const dataHome = createTempDir();
769
+ process.env.PICHAMBER_DATA_DIR = dataHome;
770
+ try {
771
+ const repo = createTempDir();
772
+ runGit(repo, ['init', '-b', 'main']);
773
+ runGit(repo, ['config', 'user.email', 'test@example.com']);
774
+ runGit(repo, ['config', 'user.name', 'Test User']);
775
+ fs.writeFileSync(path.join(repo, 'README.md'), '# Test\n');
776
+ runGit(repo, ['add', 'README.md']);
777
+ runGit(repo, ['commit', '-m', 'Initial commit']);
778
+ const rootCommit = runGit(repo, ['rev-list', '--max-parents=0', 'HEAD']).trim();
779
+ const victim = path.join(createTempDir(), 'victim.txt');
780
+ fs.writeFileSync(victim, 'untouched');
781
+ const idFile = path.join(repo, '.git', 'pichamber');
782
+ fs.symlinkSync(victim, idFile);
783
+
784
+ await createWorktree(repo, {
785
+ mode: 'new',
786
+ branchName: 'feature/link-check',
787
+ worktreeName: 'link-check',
788
+ returnAfterDirectoryCreated: true,
789
+ });
790
+
791
+ expect(fs.readFileSync(victim, 'utf8')).toBe('untouched');
792
+ expect(fs.lstatSync(idFile).isSymbolicLink()).toBe(false);
793
+ expect(fs.readFileSync(idFile, 'utf8')).toBe(rootCommit);
794
+ expect(fs.readdirSync(path.join(repo, '.git')).filter((name) => name.endsWith('.tmp'))).toEqual([]);
795
+ } finally {
796
+ if (previousPiChamberDataDir === undefined) {
797
+ delete process.env.PICHAMBER_DATA_DIR;
798
+ } else {
799
+ process.env.PICHAMBER_DATA_DIR = previousPiChamberDataDir;
800
+ }
801
+ }
802
+ });
803
+
625
804
  it('returns ready/setup-ready when no bootstrap state is recorded', async () => {
626
805
  const directory = path.join(createTempDir(), 'missing-worktree');
627
806
 
@@ -7,6 +7,8 @@ server runtime. Every GitHub call runs here; the shared UI talks to
7
7
  `/api/github/*` through `RuntimeAPIs.github`, so web, desktop, hosted
8
8
  mobile, and Capacitor share one code path. Tokens never reach a client.
9
9
 
10
+ Sandboxing: Only Pi session daemons (the agent) run in the sandbox. PiChamber's own Git panel, terminal, browser and GitHub features, and worktree hooks and start commands, run outside it with the user's access, so git config, hooks or filters an agent writes into the repo can run when the user or the Git panel runs git. This is a known, accepted trade-off. The GitHub module's git calls run unsandboxed for every folder.
11
+
10
12
  ## Entrypoints and structure
11
13
 
12
14
  - `packages/web/server/lib/github/`: module directory.
@@ -0,0 +1,95 @@
1
+ # Marketplace (server)
2
+
3
+ ## Purpose
4
+
5
+ Lets Settings find and install Pi packages without a registry of our own.
6
+ Pi packages are npm packages with the `pi-package` keyword, the same list
7
+ pi.dev's package gallery shows. This module reads npm's public search and
8
+ package endpoints, adds a curated featured list from the PiChamber repo, and
9
+ answers the UI through `/api/pi/marketplace/*`. Installing is not here: it
10
+ is a Pi package-manager write owned by the session daemon
11
+ (`../pi/session-daemon/extension-config.js`, `POST /api/pi/extensions/packages`).
12
+
13
+ ## Entrypoints
14
+
15
+ - `npm-registry.js` is the only code that talks to npm.
16
+ `createNpmRegistry({ fetchImpl, registryUrl, downloadsUrl, timeoutMs })`
17
+ returns `searchRaw`, `latest(name)` and `weeklyDownloads(name)`. Responses
18
+ are size-capped (search 2 MB, manifest 512 KB) and time out after 8 s.
19
+ Failures are `MarketplaceError` with code `MARKETPLACE_UNAVAILABLE` or
20
+ `MARKETPLACE_PACKAGE_NOT_FOUND`. `summarizePackage` and `summarizeManifest`
21
+ reduce npm's answers to the fields the UI shows. Links pass `safeLink`
22
+ (http/https only). Requests carry the generic user agent `PiChamber` and
23
+ nothing about the user.
24
+ - `featured.js` owns the featured list. The built-in copy is
25
+ `packages/web/plugins/featured.json`; the remote copy is the same file on
26
+ the repo's `main` branch (`DEFAULT_FEATURED_URL`), refreshed at most every
27
+ 6 hours (10 minutes after a failure), capped at 64 KB, and cached at
28
+ `<dataDir>/pi/featured.json` as `{ fetchedAt, list }`. `get()` never waits
29
+ on the network: it answers with the newer of the cached and built-in lists
30
+ (by `updated`; on the same date the cached copy wins) and starts a refresh
31
+ in the background when one is due.
32
+ - `service.js` combines them with in-memory TTL caches (search 5 minutes,
33
+ package and downloads 10 minutes, 300 entries, shared in-flight requests,
34
+ failures not kept).
35
+ - `routes.js` registers the routes below. `server/index.js` builds the
36
+ registry, featured source and service.
37
+
38
+ ## List format
39
+
40
+ `featured.json`: `{ version: 1, updated: 'YYYY-MM-DD', featured: [{ name,
41
+ note? }], hidden: [name] }`. At most 24 featured entries with notes of at
42
+ most 120 characters, and 500 hidden names. Invalid names are dropped.
43
+ `hidden` is moderation: a hidden package is left out of search, featured and
44
+ package answers. Editing the file on `main` reaches every server within 6
45
+ hours; a release carries the file as the fallback.
46
+
47
+ ## Routes
48
+
49
+ - `GET /api/pi/marketplace/search?q=&from=&pichamber=1` →
50
+ `{ packages, total?, nextFrom }`. Pages of 20. `total` only without a
51
+ query (npm's count for the keyword).
52
+ - `GET /api/pi/marketplace/featured` → `{ packages, updated, source }`, in
53
+ the list's order. An entry npm cannot answer for comes back as
54
+ `{ name, note, unavailable: true }` rather than failing the list.
55
+ - `GET /api/pi/marketplace/package?name=` → the package summary plus
56
+ `license?`, `contains` (from its `pi` block), `pichamber` (its manifest
57
+ declares a `pichamber` block with a numeric `apiVersion`) and `isPiPackage`.
58
+ - `GET /api/pi/marketplace/versions?names=a,b` → `{ versions: { name:
59
+ version } }` for at most 50 names. Names npm cannot answer for are left out.
60
+ - Errors: 400 `INVALID_MARKETPLACE_REQUEST`, 404
61
+ `MARKETPLACE_PACKAGE_NOT_FOUND`, 502 `MARKETPLACE_UNAVAILABLE`. A failed
62
+ npm call is an error, never an empty list.
63
+
64
+ ## Invariants
65
+
66
+ - npm search text only ranks; it does not filter. A query for nonsense
67
+ returns popular packages that match nothing. The service keeps only hits
68
+ where a query word appears in the name, description or keywords, and stops
69
+ paging at the first page that has an unrelated hit, so the tail of
70
+ unrelated packages never shows.
71
+ - npm treats two keywords loosely, so the service asks for one
72
+ (`pichamber-plugin` with `pichamber=1`, otherwise `pi-package`) and checks
73
+ both itself.
74
+ - The `pichamber-plugin` keyword is a claim by the author: it marks a list
75
+ row. The package page reads the manifest and calls it a PiChamber plugin only
76
+ when the `pichamber` block is really there. A third-party package with
77
+ that block installs and runs as a plain Pi package; PiChamber does not load
78
+ its UI half.
79
+ - The bundled plugins (`pluginService.bundledPackageNames()`) and hidden
80
+ names never appear in an answer. The UI suggests the bundled plugin
81
+ instead when a search matches it.
82
+ - No README, images or other package content are fetched: only npm's
83
+ metadata, which is shown as text.
84
+
85
+ ## Configuration
86
+
87
+ - `PICHAMBER_NPM_REGISTRY_URL` and `PICHAMBER_NPM_DOWNLOADS_URL` point at
88
+ another registry (tests, mirrors).
89
+ - `PICHAMBER_FEATURED_URL` replaces the remote featured list; `off` turns the
90
+ refresh off so only the built-in copy is used.
91
+
92
+ ## Tests
93
+
94
+ `*.test.js` beside each file (vitest), with a fake `fetchImpl`; nothing
95
+ reaches the network.