@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
@@ -1,6 +1,7 @@
1
- // Owns what `pi config`, `pi list`, and `pi remove` do for Pi extensions:
2
- // listing what is configured (path-free), turning resources on or off per
3
- // scope, and removing a configured package. `session-daemon.js` routes the
1
+ // Owns what `pi config`, `pi list`, `pi install npm:<name>`, `pi update`, and
2
+ // `pi remove` do for Pi extensions: listing what is configured (path-free),
3
+ // turning resources on or off per scope, and installing, updating, or
4
+ // removing a configured package. `session-daemon.js` routes the
4
5
  // private commands here and supplies the lock, queue, trust, and runtime
5
6
  // recreation.
6
7
  //
@@ -10,7 +11,7 @@
10
11
  // Recheck them against that file on every SDK upgrade.
11
12
 
12
13
  import { createHash } from 'node:crypto';
13
- import { realpathSync } from 'node:fs';
14
+ import { closeSync, fstatSync, openSync, readSync, realpathSync } from 'node:fs';
14
15
  import { homedir } from 'node:os';
15
16
  import { basename, dirname, isAbsolute, join, relative, resolve, win32 } from 'node:path';
16
17
  import { fileURLToPath } from 'node:url';
@@ -35,6 +36,19 @@ const GROUP_ORDER = { package: 0, auto: 1, settings: 2, builtin: 3 };
35
36
  const MAX_ERROR_MESSAGE_LENGTH = 300;
36
37
  const MAX_NAME_LENGTH = 256;
37
38
  const ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
39
+ // npm's rules for a new package name (validate-npm-package-name): lowercase,
40
+ // optional scope, URL-safe characters, no leading `.` or `_`.
41
+ const NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/;
42
+ const MAX_NPM_NAME_LENGTH = 214;
43
+ const MAX_VERSION_LENGTH = 64;
44
+ const VERSION_PATTERN = /^[0-9A-Za-z.+-]+$/;
45
+ // The exact versions semver's `valid()` takes, which is what Pi calls pinned
46
+ // (`isExactNpmVersion` in core/package-manager.js).
47
+ const EXACT_VERSION_PATTERN = /^=?v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
48
+ const MAX_PACKAGE_JSON_BYTES = 256 * 1024;
49
+
50
+ const isValidNpmPackageName = (name) => typeof name === 'string'
51
+ && name.length > 0 && name.length <= MAX_NPM_NAME_LENGTH && NPM_PACKAGE_NAME_PATTERN.test(name);
38
52
 
39
53
  class ExtensionConfigError extends Error {
40
54
  constructor(code, message) {
@@ -353,7 +367,46 @@ export const displayPackageSource = (source, baseDir) => {
353
367
  return sanitizeName(basename(resolved) || 'local');
354
368
  };
355
369
 
356
- const parseNpmName = (spec) => spec.match(/^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/)?.[1] ?? spec;
370
+ const NPM_SPEC_PATTERN = /^(@?[^@]+(?:\/[^@]+)?)(?:@(.+))?$/;
371
+ const parseNpmName = (spec) => spec.match(NPM_SPEC_PATTERN)?.[1] ?? spec;
372
+
373
+ // Pi never updates an npm source written with an exact version.
374
+ const isPinnedSource = (source) => {
375
+ if (packageKind(source) !== 'npm') return false;
376
+ const version = source.trim().slice('npm:'.length).trim().match(NPM_SPEC_PATTERN)?.[2];
377
+ return typeof version === 'string' && EXACT_VERSION_PATTERN.test(version.trim());
378
+ };
379
+
380
+ // name, version, and the PiChamber plugin marker from an installed package's
381
+ // own package.json. Any read or parse error leaves them out; the path is
382
+ // never returned.
383
+ const readInstalledPackageInfo = (installedPath) => {
384
+ if (typeof installedPath !== 'string' || installedPath.length === 0) return {};
385
+ let fd;
386
+ try {
387
+ fd = openSync(join(installedPath, 'package.json'), 'r');
388
+ const { size } = fstatSync(fd);
389
+ if (size > MAX_PACKAGE_JSON_BYTES) return {};
390
+ const buffer = Buffer.alloc(size);
391
+ const read = readSync(fd, buffer, 0, size, 0);
392
+ const manifest = JSON.parse(buffer.subarray(0, read).toString('utf8'));
393
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) return {};
394
+ const { name, version, pichamber } = manifest;
395
+ return {
396
+ ...(isValidNpmPackageName(name) ? { name } : {}),
397
+ ...(typeof version === 'string' && version.length <= MAX_VERSION_LENGTH && VERSION_PATTERN.test(version) ? { version } : {}),
398
+ ...(pichamber && typeof pichamber === 'object' && !Array.isArray(pichamber) && Number.isFinite(pichamber.apiVersion)
399
+ ? { pichamber: true }
400
+ : {}),
401
+ };
402
+ } catch {
403
+ return {};
404
+ } finally {
405
+ if (fd !== undefined) {
406
+ try { closeSync(fd); } catch { /* already closed */ }
407
+ }
408
+ }
409
+ };
357
410
 
358
411
  // Pi's package identity (npm by name, local by resolved path); git sources
359
412
  // keep their written form minus credentials.
@@ -517,6 +570,8 @@ export function createExtensionConfig({
517
570
  kind: packageKind(pkg.source),
518
571
  installed: typeof pkg.installedPath === 'string' && pkg.installedPath.length > 0,
519
572
  filtered: pkg.filtered === true,
573
+ ...(isPinnedSource(pkg.source) ? { pinned: true } : {}),
574
+ ...readInstalledPackageInfo(pkg.installedPath),
520
575
  });
521
576
  }
522
577
  packages.sort((a, b) => (a.scope === b.scope ? a.source.localeCompare(b.source) : a.scope === 'user' ? -1 : 1));
@@ -669,28 +724,159 @@ export function createExtensionConfig({
669
724
  if (setProjectResourceOverride(ctx, item, state)) await commit(settingsManager);
670
725
  };
671
726
 
672
- /**
673
- * Removes one configured package through Pi's `removeAndPersist`. Same
674
- * locking contract as `set`. PiChamber deletes no path itself.
675
- */
676
- const removePackage = async (target, payload) => {
677
- if (!payload || typeof payload !== 'object' || Array.isArray(payload)
678
- || typeof payload.id !== 'string' || !ID_PATTERN.test(payload.id)) {
679
- throw invalid();
680
- }
727
+ const managersFor = (target) => {
681
728
  const projectTrusted = Boolean(target.directory && target.trusted);
682
729
  const globalCwd = target.directory ?? target.cwd;
683
730
  const settingsManager = createSettingsManager({ cwd: globalCwd, agentDir, projectTrusted });
684
731
  const packageManager = createPackageManager({ cwd: globalCwd, agentDir, settingsManager, builtinExtensions: [...builtinExtensions] });
732
+ return { projectTrusted, globalCwd, settingsManager, packageManager };
733
+ };
734
+
735
+ const configuredEntries = (packageManager) => {
685
736
  const configured = packageManager.listConfiguredPackages();
686
- const match = (Array.isArray(configured) ? configured : []).find((pkg) => (
687
- pkg && typeof pkg.source === 'string' && (pkg.scope === 'user' || pkg.scope === 'project')
688
- && packageId(pkg.scope, packageIdentity(pkg.source, baseDirFor(pkg.scope, globalCwd))) === payload.id
737
+ return (Array.isArray(configured) ? configured : [])
738
+ .filter((pkg) => pkg && typeof pkg.source === 'string' && (pkg.scope === 'user' || pkg.scope === 'project'));
739
+ };
740
+
741
+ // The configured package a list id names. A project package needs a
742
+ // trusted directory.
743
+ const findConfiguredPackage = (target, id) => {
744
+ const managers = managersFor(target);
745
+ const match = configuredEntries(managers.packageManager).find((pkg) => (
746
+ packageId(pkg.scope, packageIdentity(pkg.source, baseDirFor(pkg.scope, managers.globalCwd))) === id
689
747
  ));
690
748
  if (!match) throw new ExtensionConfigError('RESOURCE_NOT_FOUND', 'The requested package was not found.');
691
- if (match.scope === 'project' && !projectTrusted) {
749
+ if (match.scope === 'project' && !managers.projectTrusted) {
692
750
  throw new ExtensionConfigError('PROJECT_UNTRUSTED', 'The project is not trusted.');
693
751
  }
752
+ return { ...managers, match };
753
+ };
754
+
755
+ const errorText = (error, globalCwd) => sanitizeErrorMessage(
756
+ error instanceof Error ? error.message : error,
757
+ [agentDir, globalCwd, homedir()],
758
+ );
759
+
760
+ const runDirectly = (operation) => operation();
761
+
762
+ const parseInstallRequest = (payload) => {
763
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw invalid();
764
+ // A bare npm name only: no version, and no git, URL, or local source.
765
+ if (!isValidNpmPackageName(payload.name)) throw invalid('Only an npm package name can be installed.');
766
+ if (payload.scope !== 'user' && payload.scope !== 'project') throw invalid();
767
+ return { name: payload.name, scope: payload.scope };
768
+ };
769
+
770
+ const assertInstallTarget = (target, scope) => {
771
+ if (scope !== 'project') return;
772
+ if (!target.directory) throw invalid('Project scope requires a directory.');
773
+ if (!target.trusted) throw new ExtensionConfigError('PROJECT_UNTRUSTED', 'The project is not trusted.');
774
+ };
775
+
776
+ const assertNotConfigured = (packageManager, scope, identity) => {
777
+ if (configuredEntries(packageManager).some((pkg) => pkg.scope === scope && packageKind(pkg.source) === 'npm'
778
+ && packageIdentity(pkg.source) === identity)) {
779
+ throw new ExtensionConfigError('PACKAGE_ALREADY_INSTALLED', 'The package is already installed in that scope.');
780
+ }
781
+ };
782
+
783
+ /**
784
+ * `pi install npm:<name>` in two steps so the npm download holds no lock:
785
+ * `serializeInstall` runs Pi's `install` (one npm run at a time), then
786
+ * `withWriteLock(write)` runs `write(freshTarget)` under the resource
787
+ * mutation queue and the shared Pi config lock to add the source to
788
+ * settings. Both hooks default to running directly. `resolveTarget`
789
+ * reads the target again when the queued npm step starts, so trust
790
+ * revoked while it waited stops it. Returns `{ installedId }`, the new
791
+ * package's list id.
792
+ */
793
+ const installPackage = async (target, payload, {
794
+ serializeInstall = runDirectly,
795
+ withWriteLock = (write) => write(target),
796
+ resolveTarget = async () => target,
797
+ } = {}) => {
798
+ const request = parseInstallRequest(payload);
799
+ const source = `npm:${request.name}`;
800
+ const identity = packageIdentity(source);
801
+ const local = request.scope === 'project';
802
+ assertInstallTarget(target, request.scope);
803
+ {
804
+ const { packageManager } = managersFor(target);
805
+ assertNotConfigured(packageManager, request.scope, identity);
806
+ }
807
+ await serializeInstall(async () => {
808
+ // Trust can change while this waits in the queue: check again first.
809
+ const current = await resolveTarget();
810
+ assertInstallTarget(current, request.scope);
811
+ const { packageManager, globalCwd } = managersFor(current);
812
+ try {
813
+ await packageManager.install(source, { local });
814
+ } catch (error) {
815
+ throw new ExtensionConfigError('PACKAGE_INSTALL_FAILED', errorText(error, globalCwd));
816
+ }
817
+ });
818
+ await withWriteLock(async (fresh) => {
819
+ // Trust and settings can change while npm runs: check again.
820
+ assertInstallTarget(fresh, request.scope);
821
+ const { settingsManager, packageManager } = managersFor(fresh);
822
+ assertNotConfigured(packageManager, request.scope, identity);
823
+ assertWritable(settingsManager);
824
+ // The package files are installed by now and stay if this write fails;
825
+ // Pi's own `installAndPersist` leaves them the same way. Report the
826
+ // failed write, never success.
827
+ try {
828
+ packageManager.addSourceToSettings(source, { local });
829
+ } catch {
830
+ throw new ExtensionConfigError('PI_SETTINGS_INVALID', 'Pi settings could not be written.');
831
+ }
832
+ await commit(settingsManager);
833
+ });
834
+ return { installedId: packageId(request.scope, identity) };
835
+ };
836
+
837
+ /**
838
+ * `pi update <source>` for one configured npm or git package, run through
839
+ * `serializeInstall` with no lock held. Pi updates every entry with the
840
+ * same identity in the settings it can read. `resolveTarget` reads the
841
+ * target again when the queued step starts, so the package is looked up
842
+ * with the trust and settings of that moment. The caller recreates
843
+ * runtimes afterwards.
844
+ */
845
+ const updatePackage = async (target, payload, { serializeInstall = runDirectly, resolveTarget = async () => target } = {}) => {
846
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)
847
+ || typeof payload.id !== 'string' || !ID_PATTERN.test(payload.id)) {
848
+ throw invalid();
849
+ }
850
+ const assertUpdatable = (source) => {
851
+ if (packageKind(source) === 'local') throw invalid('A local package has nothing to update.');
852
+ if (isPinnedSource(source)) throw new ExtensionConfigError('PACKAGE_PINNED', 'The package is pinned to a version.');
853
+ };
854
+ assertUpdatable(findConfiguredPackage(target, payload.id).match.source);
855
+ await serializeInstall(async () => {
856
+ // Trust and settings can change while this waits in the queue: look
857
+ // the package up again, which leaves out an untrusted project's.
858
+ const current = await resolveTarget();
859
+ const { match } = findConfiguredPackage(current, payload.id);
860
+ assertUpdatable(match.source);
861
+ const { packageManager, globalCwd } = managersFor(current);
862
+ try {
863
+ await packageManager.update(match.source);
864
+ } catch (error) {
865
+ throw new ExtensionConfigError('PACKAGE_UPDATE_FAILED', errorText(error, globalCwd));
866
+ }
867
+ });
868
+ };
869
+
870
+ /**
871
+ * Removes one configured package through Pi's `removeAndPersist`. Same
872
+ * locking contract as `set`. PiChamber deletes no path itself.
873
+ */
874
+ const removePackage = async (target, payload) => {
875
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)
876
+ || typeof payload.id !== 'string' || !ID_PATTERN.test(payload.id)) {
877
+ throw invalid();
878
+ }
879
+ const { projectTrusted, globalCwd, settingsManager, packageManager, match } = findConfiguredPackage(target, payload.id);
694
880
  assertWritable(settingsManager);
695
881
  // Pi matches the source as if it were typed after `pi remove`: a relative
696
882
  // local path is read against the working directory. Settings keep it
@@ -703,10 +889,7 @@ export function createExtensionConfig({
703
889
  try {
704
890
  removed = await packageManager.removeAndPersist(source, { local: match.scope === 'project' });
705
891
  } catch (error) {
706
- throw new ExtensionConfigError(
707
- 'PACKAGE_REMOVE_FAILED',
708
- sanitizeErrorMessage(error instanceof Error ? error.message : error, [agentDir, globalCwd, homedir()]),
709
- );
892
+ throw new ExtensionConfigError('PACKAGE_REMOVE_FAILED', errorText(error, globalCwd));
710
893
  }
711
894
  // The package files may already be gone here. A settings write that
712
895
  // fails now leaves an entry for a missing package: report it, never
@@ -715,5 +898,5 @@ export function createExtensionConfig({
715
898
  if (!removed) throw new ExtensionConfigError('PACKAGE_NOT_CONFIGURED', 'Pi settings had no entry for the package.');
716
899
  };
717
900
 
718
- return { list, set, removePackage };
901
+ return { list, set, installPackage, updatePackage, removePackage };
719
902
  }
@@ -616,3 +616,183 @@ describe('package removal with a stubbed package manager', () => {
616
616
  expect(partial.calls).toHaveLength(1);
617
617
  });
618
618
  });
619
+
620
+ describe('package install and update with a stubbed package manager', () => {
621
+ const stubbed = ({ configured = [], install = async () => {}, update = async () => {}, drainAfterFlush = [] } = {}) => {
622
+ const calls = [];
623
+ const state = { configured: [...configured] };
624
+ let flushed = false;
625
+ const settingsManager = {
626
+ flush: async () => { flushed = true; calls.push({ op: 'flush' }); },
627
+ drainErrors: () => (flushed ? drainAfterFlush : []),
628
+ getGlobalSettings: () => ({}),
629
+ getProjectSettings: () => ({}),
630
+ };
631
+ const packageManager = {
632
+ resolve: async () => ({ extensions: [], skills: [], prompts: [], themes: [], installFailures: [] }),
633
+ listConfiguredPackages: () => state.configured,
634
+ install: async (source, options) => { calls.push({ op: 'install', source, options }); return install(source, options); },
635
+ update: async (source) => { calls.push({ op: 'update', source }); return update(source); },
636
+ addSourceToSettings: (source, options) => {
637
+ calls.push({ op: 'add', source, options });
638
+ state.configured.push({ source, scope: options.local ? 'project' : 'user', filtered: false });
639
+ return true;
640
+ },
641
+ };
642
+ const service = createExtensionConfig({
643
+ agentDir: '/agent',
644
+ createSettingsManager: () => { flushed = false; return settingsManager; },
645
+ createPackageManager: () => packageManager,
646
+ builtinExtensions: [],
647
+ });
648
+ return { service, calls, state };
649
+ };
650
+ const user = { cwd: '/work', trusted: false };
651
+ const project = { cwd: '/work', directory: '/work', trusted: true };
652
+
653
+ it('installs npm:<name> then writes settings under the write hook, and answers with its list id', async () => {
654
+ const { service, calls } = stubbed();
655
+ const order = [];
656
+ const { installedId } = await service.installPackage(project, { name: '@acme/pi-btw', scope: 'project' }, {
657
+ serializeInstall: async (operation) => { order.push('queue'); await operation(); order.push('queued-done'); },
658
+ withWriteLock: async (write) => { order.push('lock'); await write(project); order.push('unlock'); },
659
+ });
660
+ expect(order).toEqual(['queue', 'queued-done', 'lock', 'unlock']);
661
+ expect(calls).toEqual([
662
+ { op: 'install', source: 'npm:@acme/pi-btw', options: { local: true } },
663
+ { op: 'add', source: 'npm:@acme/pi-btw', options: { local: true } },
664
+ { op: 'flush' },
665
+ ]);
666
+ const listed = (await service.list(project)).packages.find((pkg) => pkg.source === 'npm:@acme/pi-btw');
667
+ expect(listed).toMatchObject({ id: installedId, scope: 'project', kind: 'npm' });
668
+ });
669
+
670
+ it.each([
671
+ ['npm:pi-btw'], ['https://github.com/acme/tool'], ['git:github.com/acme/tool'], ['../x'], ['pi-btw@1.0.0'],
672
+ ['Pi-Btw'], ['.hidden'], ['_private'], ['a'.repeat(215)], [''], [7],
673
+ ])('refuses %s as a package name', async (name) => {
674
+ const { service, calls } = stubbed();
675
+ await expect(service.installPackage(user, { name, scope: 'user' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
676
+ expect(calls).toEqual([]);
677
+ });
678
+
679
+ it('refuses an untrusted or missing project, a bad scope, and an already configured package', async () => {
680
+ const { service, calls } = stubbed({ configured: [{ source: 'npm:pi-btw@0.8.1', scope: 'user' }] });
681
+ await expect(service.installPackage({ cwd: '/work', directory: '/work', trusted: false }, { name: 'x', scope: 'project' }))
682
+ .rejects.toMatchObject({ code: 'PROJECT_UNTRUSTED' });
683
+ await expect(service.installPackage(user, { name: 'x', scope: 'project' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
684
+ await expect(service.installPackage(user, { name: 'x', scope: 'global' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
685
+ await expect(service.installPackage(user, { name: 'pi-btw', scope: 'user' })).rejects.toMatchObject({ code: 'PACKAGE_ALREADY_INSTALLED' });
686
+ expect(calls).toEqual([]);
687
+ // The same name in the other scope is a separate package.
688
+ await service.installPackage(project, { name: 'pi-btw', scope: 'project' });
689
+ expect(calls.map((call) => call.op)).toEqual(['install', 'add', 'flush']);
690
+ });
691
+
692
+ it('checks again under the lock and writes nothing when another writer got there first', async () => {
693
+ const { service, calls, state } = stubbed();
694
+ await expect(service.installPackage(user, { name: 'pi-btw', scope: 'user' }, {
695
+ withWriteLock: async (write) => {
696
+ state.configured.push({ source: 'npm:pi-btw', scope: 'user' });
697
+ return write(user);
698
+ },
699
+ })).rejects.toMatchObject({ code: 'PACKAGE_ALREADY_INSTALLED' });
700
+ expect(calls.map((call) => call.op)).toEqual(['install']);
701
+ });
702
+
703
+ it('reports a failed npm run sanitized and a failed settings write after install', async () => {
704
+ const failing = stubbed({ install: async () => { throw new Error('npm install pi-btw --prefix /agent/npm failed: EACCES /agent/npm/x'); } });
705
+ const failure = await failing.service.installPackage(user, { name: 'pi-btw', scope: 'user' }).catch((error) => error);
706
+ expect(failure.code).toBe('PACKAGE_INSTALL_FAILED');
707
+ expect(failure.message).not.toContain('/agent');
708
+ expect(failing.calls.map((call) => call.op)).toEqual(['install']);
709
+
710
+ const partial = stubbed({ drainAfterFlush: [{ scope: 'global', error: new Error('EACCES') }] });
711
+ await expect(partial.service.installPackage(user, { name: 'pi-btw', scope: 'user' })).rejects.toMatchObject({ code: 'PI_SETTINGS_INVALID' });
712
+ expect(partial.calls.map((call) => call.op)).toEqual(['install', 'add', 'flush']);
713
+ });
714
+
715
+ const configured = [
716
+ { source: 'npm:pi-btw', scope: 'user', filtered: false },
717
+ { source: 'npm:pinned@1.2.3', scope: 'user', filtered: false },
718
+ { source: 'https://tok@github.com/acme/tool', scope: 'user', filtered: false },
719
+ { source: '../pkgs/local-one', scope: 'user', filtered: false },
720
+ { source: 'npm:proj-pkg', scope: 'project', filtered: false },
721
+ ];
722
+ const idOf = async (service, target, source) => (await service.list(target)).packages.find((pkg) => pkg.source === source).id;
723
+
724
+ it.each([
725
+ ['npm:pi-btw', 'npm:pi-btw'],
726
+ ['https://github.com/acme/tool', 'https://tok@github.com/acme/tool'],
727
+ ])('updates %s through the install queue', async (display, source) => {
728
+ const { service, calls } = stubbed({ configured });
729
+ const queued = [];
730
+ await service.updatePackage(user, { id: await idOf(service, user, display) }, {
731
+ serializeInstall: async (operation) => { queued.push(true); return operation(); },
732
+ });
733
+ expect(queued).toHaveLength(1);
734
+ expect(calls).toEqual([{ op: 'update', source }]);
735
+ });
736
+
737
+ it('refuses pinned, local, unknown, and untrusted project packages, and sanitizes failures', async () => {
738
+ const { service, calls } = stubbed({ configured });
739
+ const list = await service.list(user);
740
+ expect(list.packages.find((pkg) => pkg.source === 'npm:pinned@1.2.3').pinned).toBe(true);
741
+ expect(list.packages.find((pkg) => pkg.source === 'npm:pi-btw').pinned).toBeUndefined();
742
+ await expect(service.updatePackage(user, { id: await idOf(service, user, 'npm:pinned@1.2.3') })).rejects.toMatchObject({ code: 'PACKAGE_PINNED' });
743
+ await expect(service.updatePackage(user, { id: await idOf(service, user, 'local-one') })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
744
+ await expect(service.updatePackage(user, { id: 'B'.repeat(43) })).rejects.toMatchObject({ code: 'RESOURCE_NOT_FOUND' });
745
+ await expect(service.updatePackage(user, { id: 7 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
746
+ const projectId = await idOf(service, project, 'npm:proj-pkg');
747
+ await expect(service.updatePackage({ cwd: '/work', directory: '/work', trusted: false }, { id: projectId })).rejects.toMatchObject({ code: 'PROJECT_UNTRUSTED' });
748
+ expect(calls).toEqual([]);
749
+
750
+ const failing = stubbed({ configured, update: async () => { throw new Error('git pull failed in /agent/git/github.com/acme/tool'); } });
751
+ const failure = await failing.service.updatePackage(user, { id: await idOf(failing.service, user, 'npm:pi-btw') }).catch((error) => error);
752
+ expect(failure.code).toBe('PACKAGE_UPDATE_FAILED');
753
+ expect(failure.message).not.toContain('/agent');
754
+ });
755
+
756
+ it('reads trust again when a queued install or update starts, and stops when it was revoked', async () => {
757
+ const revoked = { cwd: '/work', directory: '/work', trusted: false };
758
+ const { service, calls } = stubbed({ configured });
759
+ await expect(service.installPackage(project, { name: 'pi-new', scope: 'project' }, {
760
+ resolveTarget: async () => revoked,
761
+ })).rejects.toMatchObject({ code: 'PROJECT_UNTRUSTED' });
762
+ const projectId = await idOf(service, project, 'npm:proj-pkg');
763
+ await expect(service.updatePackage(project, { id: projectId }, {
764
+ resolveTarget: async () => revoked,
765
+ })).rejects.toMatchObject({ code: 'PROJECT_UNTRUSTED' });
766
+ expect(calls).toEqual([]);
767
+ });
768
+
769
+ it('lists name, version, and the PiChamber marker from the installed package.json, ignoring a broken one', async () => {
770
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-extension-config-pkg-'));
771
+ try {
772
+ const good = join(root, 'good');
773
+ const broken = join(root, 'broken');
774
+ const odd = join(root, 'odd');
775
+ await Promise.all([mkdir(good), mkdir(broken), mkdir(odd)]);
776
+ await writeFile(join(good, 'package.json'), JSON.stringify({ name: '@acme/pi-btw', version: '0.8.1', pichamber: { apiVersion: 1 } }));
777
+ await writeFile(join(broken, 'package.json'), '{ not json');
778
+ await writeFile(join(odd, 'package.json'), JSON.stringify({ name: 'Bad Name', version: 'x'.repeat(65), pichamber: { apiVersion: '1' } }));
779
+ const { service } = stubbed({
780
+ configured: [
781
+ { source: 'npm:pi-btw', scope: 'user', installedPath: good },
782
+ { source: 'npm:broken', scope: 'user', installedPath: broken },
783
+ { source: 'npm:odd', scope: 'user', installedPath: odd },
784
+ { source: 'npm:missing', scope: 'user', installedPath: join(root, 'nope') },
785
+ ],
786
+ });
787
+ const { packages } = await service.list(user);
788
+ const bySource = Object.fromEntries(packages.map((pkg) => [pkg.source, pkg]));
789
+ expect(bySource['npm:pi-btw']).toMatchObject({ name: '@acme/pi-btw', version: '0.8.1', pichamber: true, installed: true });
790
+ for (const source of ['npm:broken', 'npm:odd', 'npm:missing']) {
791
+ expect(Object.keys(bySource[source]).sort()).toEqual(['filtered', 'id', 'installed', 'kind', 'scope', 'source']);
792
+ }
793
+ expect(JSON.stringify(packages)).not.toContain(root);
794
+ } finally {
795
+ await rm(root, { recursive: true, force: true });
796
+ }
797
+ });
798
+ });
@@ -0,0 +1,167 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { createConnection } from 'node:net';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { StringDecoder } from 'node:string_decoder';
8
+
9
+ import { hasTrustRequiringProjectResources } from '@earendil-works/pi-coding-agent';
10
+
11
+ import { createSessionDaemon } from './session-daemon.js';
12
+
13
+ // `sessions.readPersisted` projects a transcript straight from its JSONL
14
+ // file: no Pi runtime, extension, or tool starts, and nothing is written.
15
+ // The server uses it to show a sandboxed project's transcripts while its
16
+ // sandbox cannot run (#242, "Fail closed").
17
+
18
+ const credential = 'a-private-daemon-credential';
19
+
20
+ const endpointFor = (root) => (process.platform === 'win32'
21
+ ? `\\\\.\\pipe\\pichamber-test-${createHash('sha1').update(root).digest('hex').slice(0, 16)}`
22
+ : join(root, 'daemon.sock'));
23
+
24
+ const connect = (endpoint) => {
25
+ const socket = createConnection({ path: endpoint });
26
+ const decoder = new StringDecoder('utf8');
27
+ let buffer = '';
28
+ const messages = [];
29
+ const waiters = [];
30
+ socket.on('data', (chunk) => {
31
+ buffer += decoder.write(chunk);
32
+ let index;
33
+ while ((index = buffer.indexOf('\n')) !== -1) {
34
+ const line = buffer.slice(0, index);
35
+ buffer = buffer.slice(index + 1);
36
+ if (!line) continue;
37
+ const message = JSON.parse(line);
38
+ messages.push(message);
39
+ for (let at = waiters.length - 1; at >= 0; at -= 1) {
40
+ if (waiters[at].predicate(message)) waiters.splice(at, 1)[0].resolve(message);
41
+ }
42
+ }
43
+ });
44
+ const waitFor = (predicate) => {
45
+ const hit = messages.find(predicate);
46
+ if (hit) return Promise.resolve(hit);
47
+ return new Promise((resolve) => waiters.push({ predicate, resolve }));
48
+ };
49
+ return {
50
+ async authenticate() {
51
+ await new Promise((resolve, reject) => { socket.once('connect', resolve); socket.once('error', reject); });
52
+ socket.write(`${JSON.stringify({ kind: 'authenticate', credential })}\n`);
53
+ await waitFor((message) => message.kind === 'authenticated');
54
+ },
55
+ request(command, payload = {}) {
56
+ const requestId = `request-${messages.length}-${Math.random()}`;
57
+ socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId, command, payload })}\n`);
58
+ // A failed request answers with an `error` frame (no request id) and
59
+ // closes the connection.
60
+ return waitFor((message) => message.kind === 'error' || (message.kind === 'response' && message.requestId === requestId));
61
+ },
62
+ close: () => socket.destroy(),
63
+ };
64
+ };
65
+
66
+ const line = (value) => `${JSON.stringify(value)}\n`;
67
+ const at = (minute) => `2026-01-01T00:0${minute}:00.000Z`;
68
+
69
+ describe('sessions.readPersisted', () => {
70
+ let daemon;
71
+ let client;
72
+ const roots = [];
73
+
74
+ afterEach(async () => {
75
+ client?.close();
76
+ await daemon?.stop().catch(() => {});
77
+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
78
+ });
79
+
80
+ const start = async (daemonOptions = {}) => {
81
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-read-persisted-'));
82
+ roots.push(root);
83
+ const sessionFile = join(root, 'session.jsonl');
84
+ const content = line({ type: 'session', version: 3, id: 'read-only-session', cwd: root, timestamp: at(0) })
85
+ + line({ type: 'message', id: 'u1', parentId: null, timestamp: at(1), message: { role: 'user', content: 'first question', timestamp: Date.parse(at(1)) } })
86
+ + line({ type: 'message', id: 'a1', parentId: 'u1', timestamp: at(2), message: { role: 'assistant', content: [{ type: 'text', text: 'first answer' }], provider: 'test', model: 'model-a', timestamp: Date.parse(at(2)) } })
87
+ + line({ type: 'session_info', id: 'i1', parentId: 'a1', timestamp: at(3), name: 'Read me' })
88
+ + line({ type: 'message', id: 'u2', parentId: 'i1', timestamp: at(4), message: { role: 'user', content: 'second question', timestamp: Date.parse(at(4)) } });
89
+ await writeFile(sessionFile, content);
90
+ const createdRuntimes = [];
91
+ daemon = createSessionDaemon({
92
+ endpoint: endpointFor(root),
93
+ credential,
94
+ cwd: root,
95
+ agentDir: root,
96
+ listSessions: async () => [{ path: sessionFile, id: 'read-only-session', cwd: root }],
97
+ createRuntime: async (options) => {
98
+ createdRuntimes.push(options);
99
+ throw new Error('a read must not start a Pi runtime');
100
+ },
101
+ ...daemonOptions,
102
+ });
103
+ await daemon.start();
104
+ client = connect(endpointFor(root));
105
+ await client.authenticate();
106
+ return { root, sessionFile, content, createdRuntimes };
107
+ };
108
+
109
+ it('projects the transcript from JSONL without starting a runtime or writing the file', async () => {
110
+ const { root, sessionFile, content, createdRuntimes } = await start();
111
+
112
+ const response = await client.request('sessions.readPersisted', { sessionId: 'read-only-session', directory: root });
113
+
114
+ expect(response.kind).toBe('response');
115
+ const { result } = response;
116
+ expect(result.readOnly).toBe(true);
117
+ expect(result.session).toMatchObject({ id: 'read-only-session', directory: root, title: 'Read me', messageCount: 3 });
118
+ expect(result.messages.map((item) => item.message.id)).toEqual(['u1', 'a1', 'u2']);
119
+ expect(result.messages[1].parts).toEqual([expect.objectContaining({ type: 'text', text: 'first answer' })]);
120
+ // Read-only and idle: no live claims that belong to a running daemon.
121
+ expect(result).toMatchObject({ isStreaming: false, lifecycle: 'idle', lastSequence: -1 });
122
+ expect(result).not.toHaveProperty('streamEpoch');
123
+ expect(result).not.toHaveProperty('inputState');
124
+ expect(createdRuntimes).toEqual([]);
125
+ await expect(readFile(sessionFile, 'utf8')).resolves.toBe(content);
126
+ await expect(client.request('runtime.health')).resolves.toMatchObject({ result: { residentSessions: 0 } });
127
+ });
128
+
129
+ it('pages older messages with the same cursor as sessions.messages', async () => {
130
+ const { root } = await start();
131
+
132
+ const latest = await client.request('sessions.readPersisted', { sessionId: 'read-only-session', directory: root, limit: 1 });
133
+ expect(latest.result.messages.map((item) => item.message.id)).toEqual(['u2']);
134
+ expect(latest.result).toMatchObject({ hasMoreBefore: true, beforeCursor: expect.any(String) });
135
+
136
+ const older = await client.request('sessions.readPersisted', {
137
+ sessionId: 'read-only-session', directory: root, before: latest.result.beforeCursor, limit: 5,
138
+ });
139
+ expect(older.result.messages.map((item) => item.message.id)).toEqual(['u1', 'a1']);
140
+ expect(older.result.hasMoreBefore).toBe(false);
141
+ });
142
+
143
+ it('does not trust the folder it reads from', async () => {
144
+ const trustWrites = [];
145
+ const { root } = await start({
146
+ createTrustStore: () => ({ get: () => null, set: (directory, value) => { trustWrites.push([directory, value]); } }),
147
+ });
148
+ // A project extension is what makes Pi ask for trust.
149
+ await mkdir(join(root, '.pi', 'extensions'), { recursive: true });
150
+ await writeFile(join(root, '.pi', 'extensions', 'demo.ts'), 'export default () => {};\n');
151
+ expect(hasTrustRequiringProjectResources(root)).toBe(true);
152
+
153
+ const response = await client.request('sessions.readPersisted', { sessionId: 'read-only-session', directory: root });
154
+
155
+ expect(response.kind).toBe('response');
156
+ expect(trustWrites).toEqual([]);
157
+ });
158
+
159
+ it('answers INVALID_SESSION for an unknown session', async () => {
160
+ const { root } = await start();
161
+
162
+ const response = await client.request('sessions.readPersisted', { sessionId: 'missing-session', directory: root });
163
+
164
+ expect(response.kind).toBe('error');
165
+ expect(response.error.code).toBe('INVALID_SESSION');
166
+ });
167
+ });