@pi-chamber/web 1.0.7 → 1.0.8-rc.2

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 (265) hide show
  1. package/dist/assets/AgentsSurface-CcWBqAWV.js +1 -0
  2. package/dist/assets/ChoicesArtifact-Kk-qvrSB.js +1 -0
  3. package/dist/assets/DiagramView-DZUBo1uP.js +1 -0
  4. package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-CiZy4jFA.js} +6 -6
  5. package/dist/assets/FileSaveConflictDialog-DZ9NDwOO.js +3 -0
  6. package/dist/assets/FilesView-DqiZ9kw9.js +6 -0
  7. package/dist/assets/GitHubDetailScaffold-DM2DH7o8.js +11 -0
  8. package/dist/assets/GitHubLinkPicker-ChB8NZ1h.js +1 -0
  9. package/dist/assets/GitHubListPrimitives-CibDiJGq.js +1 -0
  10. package/dist/assets/{GitView-DD33ngnM.js → GitView--EaZQrBr.js} +5 -5
  11. package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-CySTpaD1.js} +3 -3
  12. package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-_yMHKKQZ.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-D_-2fQw0.js} +3 -3
  14. package/dist/assets/PatchDiff-bHObDlhD.js +1 -0
  15. package/dist/assets/PierreDiffViewer-UY7Cse-s.js +147 -0
  16. package/dist/assets/PullRequestsSurface-iXy6chwc.js +2 -0
  17. package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-DJGCa_wN.js} +1 -1
  18. package/dist/assets/SessionSwitcherDropdown-CDOX-5Y2.js +2 -0
  19. package/dist/assets/SessionUnreadDot-Dwc3MdvA.js +1 -0
  20. package/dist/assets/SettingsView-DA-U9lsj.js +11 -0
  21. package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-CUg49Mfh.js} +1 -1
  22. package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
  23. package/dist/assets/SubagentsArtifact-DUZX9tDe.js +1 -0
  24. package/dist/assets/ToolOutputDialog-BuZZaRw4.js +8 -0
  25. package/dist/assets/ToolPartDiffPreview-CKncG6i2.js +1 -0
  26. package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-BGZiLPe_.js} +4 -4
  27. package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
  28. package/dist/assets/VisualFrame-DBZkHFnG.js +22 -0
  29. package/dist/assets/VisualsArtifact-Bq0vMO-i.js +1 -0
  30. package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-Bro9KrfM.js} +1 -1
  31. package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DJQqK49u.js} +2 -2
  32. package/dist/assets/contextFileOpenGuard-ByWK3Sru.js +1 -0
  33. package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CyJ3TOYD.js} +2 -2
  34. package/dist/assets/gitStatusPredicates-BsXrwngT.js +1 -0
  35. package/dist/assets/githubLink-g2bmC0qi.js +10 -0
  36. package/dist/assets/index-B_L9GVYw.css +1 -0
  37. package/dist/assets/{index-ComwtfT4.js → index-C9rUUQ_Y.js} +1 -1
  38. package/dist/assets/index-CKKWVoND.js +11 -0
  39. package/dist/assets/{main-DoiadX0a.js → main-DT-4_fhe.js} +2 -2
  40. package/dist/assets/main-DsLMU9CT.js +137 -0
  41. package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-QmM_aOnZ.js} +2 -2
  42. package/dist/assets/{miniChat-Ck6MEZ9Q.js → miniChat-BqGslD2z.js} +2 -2
  43. package/dist/assets/{mobile-BucKVm1P.js → mobile-C5JOcDIC.js} +2 -2
  44. package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-DSMsJqXM.js} +1 -1
  45. package/dist/assets/pi-session-focus-preference-Cc_S4zi1.js +9 -0
  46. package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-BXhnIAHg.js} +1 -1
  47. package/dist/assets/renderElectronMiniChatApp-CiSkecEE.js +2 -0
  48. package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-CK29YZtC.js} +1 -1
  49. package/dist/assets/renderMobileApp-C4JuoxsZ.js +11 -0
  50. package/dist/assets/runtimeEndpointReset-Dwj-jCDS.js +66 -0
  51. package/dist/assets/runtimeSurface-0K7vuUpd.js +1 -0
  52. package/dist/assets/selection-CnYkEsu_.js +1 -0
  53. package/dist/assets/useAppFontEffects-CV5UyTRw.js +226 -0
  54. package/dist/assets/useGitHubRemoteSearch-CgP-zEBj.js +1 -0
  55. package/dist/assets/useSwitcherItems-C8G5F0hs.js +1 -0
  56. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
  57. package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
  58. package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
  59. package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
  60. package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
  61. package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
  85. package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
  86. package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
  87. package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
  88. package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
  89. package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
  90. package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
  91. package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
  92. package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
  93. package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
  94. package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
  95. package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
  96. package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
  97. package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
  98. package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
  99. package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
  100. package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
  101. package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
  102. package/dist/assets/{web-components-CGDpzixf.js → web-components-BpncHjnV.js} +4 -4
  103. package/dist/index.html +4 -4
  104. package/dist/mini-chat.html +3 -3
  105. package/dist/mobile.html +3 -3
  106. package/package.json +2 -1
  107. package/plugins/featured.json +12 -0
  108. package/plugins/registry.json +7 -0
  109. package/plugins/subagents/LICENSE +25 -0
  110. package/plugins/subagents/agents/planner.md +36 -0
  111. package/plugins/subagents/agents/reviewer.md +34 -0
  112. package/plugins/subagents/agents/scout.md +49 -0
  113. package/plugins/subagents/agents/worker.md +23 -0
  114. package/plugins/subagents/extension.js +631 -0
  115. package/plugins/subagents/extension.test.js +295 -0
  116. package/plugins/subagents/package.json +41 -0
  117. package/plugins/visuals/choices.js +168 -0
  118. package/plugins/visuals/extension.js +90 -0
  119. package/plugins/visuals/files.js +74 -0
  120. package/plugins/visuals/package.json +32 -0
  121. package/server/index.js +103 -24
  122. package/server/lib/git/DOCUMENTATION.md +4 -0
  123. package/server/lib/git/service.js +70 -5
  124. package/server/lib/git/service.test.js +179 -0
  125. package/server/lib/github/DOCUMENTATION.md +6 -2
  126. package/server/lib/github/gh-cli.js +35 -9
  127. package/server/lib/github/gh-cli.test.js +122 -0
  128. package/server/lib/marketplace/DOCUMENTATION.md +95 -0
  129. package/server/lib/marketplace/featured.js +176 -0
  130. package/server/lib/marketplace/featured.test.js +207 -0
  131. package/server/lib/marketplace/npm-registry.js +255 -0
  132. package/server/lib/marketplace/npm-registry.test.js +227 -0
  133. package/server/lib/marketplace/routes.js +64 -0
  134. package/server/lib/marketplace/routes.test.js +119 -0
  135. package/server/lib/marketplace/service.js +225 -0
  136. package/server/lib/marketplace/service.test.js +174 -0
  137. package/server/lib/notifications/DOCUMENTATION.md +10 -4
  138. package/server/lib/notifications/pi-notification-watcher.js +95 -33
  139. package/server/lib/notifications/pi-notification-watcher.test.js +89 -0
  140. package/server/lib/open-url/DOCUMENTATION.md +2 -1
  141. package/server/lib/pi/extension-protocol.js +54 -0
  142. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
  143. package/server/lib/pi/merged-event-stream.js +316 -0
  144. package/server/lib/pi/merged-event-stream.test.js +95 -0
  145. package/server/lib/pi/routes-daemon-pool.test.js +348 -0
  146. package/server/lib/pi/routes-extension-events.test.js +115 -0
  147. package/server/lib/pi/routes-merged-events.test.js +327 -0
  148. package/server/lib/pi/routes-sandbox.test.js +1684 -0
  149. package/server/lib/pi/routes.js +790 -87
  150. package/server/lib/pi/routes.test.js +381 -1
  151. package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
  152. package/server/lib/pi/sandbox/launcher.js +122 -0
  153. package/server/lib/pi/sandbox/launcher.test.js +91 -0
  154. package/server/lib/pi/sandbox/nono-launcher.js +455 -0
  155. package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
  156. package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
  157. package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
  158. package/server/lib/pi/sandbox/nono-profile.json +22 -0
  159. package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
  160. package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
  161. package/server/lib/pi/sandbox/project-sandbox.js +207 -0
  162. package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
  163. package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
  164. package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
  165. package/server/lib/pi/sandbox/trust-ask.js +135 -0
  166. package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
  167. package/server/lib/pi/sandbox/worktree-ids.js +96 -0
  168. package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
  169. package/server/lib/pi/session-daemon/DOCUMENTATION.md +47 -10
  170. package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
  171. package/server/lib/pi/session-daemon/daemon-process.js +10 -1
  172. package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
  173. package/server/lib/pi/session-daemon/extension-config.js +902 -0
  174. package/server/lib/pi/session-daemon/extension-config.test.js +798 -0
  175. package/server/lib/pi/session-daemon/extension-controls.js +177 -0
  176. package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
  177. package/server/lib/pi/session-daemon/extension-name.js +6 -0
  178. package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
  179. package/server/lib/pi/session-daemon/extension-palette.js +146 -0
  180. package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
  181. package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
  182. package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
  183. package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
  184. package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
  185. package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
  186. package/server/lib/pi/session-daemon/plugin-host.js +245 -0
  187. package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
  188. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
  189. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
  190. package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
  191. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
  192. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
  193. package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
  194. package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
  195. package/server/lib/pi/session-daemon/session-daemon.js +927 -108
  196. package/server/lib/pi/session-daemon/session-daemon.test.js +391 -4
  197. package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
  198. package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
  199. package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
  200. package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
  201. package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
  202. package/server/lib/pi/session-daemon/session-lease.js +93 -15
  203. package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
  204. package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
  205. package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
  206. package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
  207. package/server/lib/pi/session-daemon/supervisor.js +408 -38
  208. package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
  209. package/server/lib/pi/settings-store.js +14 -0
  210. package/server/lib/pi/settings-store.test.js +11 -0
  211. package/server/lib/pi/ui-settings-store.js +88 -2
  212. package/server/lib/pi/ui-settings-store.test.js +118 -0
  213. package/server/lib/plugins/DOCUMENTATION.md +198 -0
  214. package/server/lib/plugins/daemon-sync.js +88 -0
  215. package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
  216. package/server/lib/plugins/daemon-sync.test.js +108 -0
  217. package/server/lib/plugins/impact.js +139 -0
  218. package/server/lib/plugins/impact.test.js +83 -0
  219. package/server/lib/plugins/manifest.js +220 -0
  220. package/server/lib/plugins/manifest.test.js +127 -0
  221. package/server/lib/plugins/registry.js +59 -0
  222. package/server/lib/plugins/routes.js +92 -0
  223. package/server/lib/plugins/routes.test.js +247 -0
  224. package/server/lib/plugins/service.js +183 -0
  225. package/server/lib/plugins/store.js +261 -0
  226. package/server/lib/plugins/store.test.js +188 -0
  227. package/server/lib/plugins/visuals-extension.test.js +237 -0
  228. package/server/lib/server/cross-process-lock.js +28 -3
  229. package/server/lib/server-browser/DOCUMENTATION.md +32 -7
  230. package/server/lib/server-browser/browser-tab.js +4 -1
  231. package/server/lib/server-browser/downloads.js +261 -34
  232. package/server/lib/server-browser/downloads.test.js +171 -0
  233. package/server/lib/server-browser/runtime.integration.test.js +47 -0
  234. package/server/lib/server-browser/runtime.js +16 -0
  235. package/server/lib/server-browser/server-browser.js +25 -6
  236. package/server/lib/tunnels/executable-search.js +5 -1
  237. package/server/lib/tunnels/executable-search.test.js +26 -0
  238. package/dist/assets/DiagramView-BB-aZobi.js +0 -1
  239. package/dist/assets/FileSaveConflictDialog-Bzz8FNMq.js +0 -3
  240. package/dist/assets/FilesView-DECxN8Z0.js +0 -6
  241. package/dist/assets/GitHubDetailScaffold-CWsWycRd.js +0 -11
  242. package/dist/assets/GitHubLinkPicker-BVYdg_e8.js +0 -1
  243. package/dist/assets/GitHubListPrimitives-Dlv3tC4d.js +0 -1
  244. package/dist/assets/PatchDiff-BklyOEHs.js +0 -1
  245. package/dist/assets/PierreDiffViewer-wc6cB6qw.js +0 -147
  246. package/dist/assets/PullRequestsSurface-BZvJkT1I.js +0 -2
  247. package/dist/assets/SessionSwitcherDropdown-DShvvGwC.js +0 -2
  248. package/dist/assets/SessionUnreadDot-CbqRq6h_.js +0 -1
  249. package/dist/assets/SettingsView-DcF-At5E.js +0 -6
  250. package/dist/assets/ToolOutputDialog-DdMIfrnK.js +0 -8
  251. package/dist/assets/ToolPartDiffPreview-C6Sm4eVf.js +0 -1
  252. package/dist/assets/contextFileOpenGuard-UU86YHgI.js +0 -1
  253. package/dist/assets/gitStatusPredicates-DQEO4Psc.js +0 -1
  254. package/dist/assets/githubLink-ByPAyFjh.js +0 -10
  255. package/dist/assets/index-BaLCg7tL.css +0 -1
  256. package/dist/assets/index-I2QYqABE.js +0 -11
  257. package/dist/assets/main-DyFfbllq.js +0 -137
  258. package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
  259. package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
  260. package/dist/assets/renderMobileApp-Bp74b_Lo.js +0 -11
  261. package/dist/assets/runtimeEndpointReset-7nWYnKd4.js +0 -62
  262. package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
  263. package/dist/assets/useAppFontEffects-ZTyNwFk6.js +0 -213
  264. package/dist/assets/useGitHubRemoteSearch-BF3ohpsh.js +0 -1
  265. package/dist/assets/useSwitcherItems-BJzwyDGX.js +0 -1
@@ -25,6 +25,9 @@ import {
25
25
  projectCustomFrame,
26
26
  projectCustomSurface,
27
27
  projectCustomSurfaces,
28
+ MAX_EXTENSION_CHOICE_ID_CHARS,
29
+ MAX_EXTENSION_CHOICE_NOTE_CHARS,
30
+ projectExtensionChooseFields,
28
31
  sanitizeExtensionFormFields,
29
32
  } from './extension-protocol.js';
30
33
  import { createPiUiSettingsStore } from './ui-settings-store.js';
@@ -32,6 +35,10 @@ import { createPiSnippetsStore } from './snippets-store.js';
32
35
  import { isValidSendOperationId, isValidStreamEpoch } from './session-daemon/send-operation-registry.js';
33
36
  import { ENGINE_HANDLER_COMMANDS, ENGINE_UNSUPPORTED_OPERATION, isValidEngineId } from './session-daemon/session-engines.js';
34
37
  import { normalizeOpenRequestUrl } from './session-daemon/open-request.js';
38
+ import { createPiDaemonPool, MAIN_DAEMON_KEY, publicDaemonStreamId } from './session-daemon/daemon-pool.js';
39
+ import { decodePiEventCursor, subscribeMergedPiEvents } from './merged-event-stream.js';
40
+ import { registerPiSandboxRoutes } from './sandbox/sandbox-routes.js';
41
+ import { MAX_CONTROLS_PER_SESSION, parseComposerControl } from './session-daemon/extension-controls.js';
35
42
  import {
36
43
  DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
37
44
  createPiEventStreamRegistry,
@@ -40,6 +47,7 @@ import {
40
47
 
41
48
  const UNAVAILABLE_CODES = new Set([
42
49
  'DAEMON_UNAVAILABLE',
50
+ 'SANDBOX_UNAVAILABLE',
43
51
  'DAEMON_AUTH_FAILED',
44
52
  'DAEMON_REQUEST_FAILED',
45
53
  'DAEMON_TIMEOUT',
@@ -69,16 +77,23 @@ const BAD_GATEWAY_CODES = new Set([
69
77
  'DAEMON_RESPONSE_TOO_LARGE',
70
78
  ]);
71
79
 
80
+ // npm or git failed for a package install or update.
81
+ const PACKAGE_UPSTREAM_FAILURE_CODES = new Set([
82
+ 'PACKAGE_INSTALL_FAILED',
83
+ 'PACKAGE_UPDATE_FAILED',
84
+ ]);
85
+
72
86
  const writeDaemonError = (res, error) => {
73
87
  const code = typeof error?.code === 'string' ? error.code : 'DAEMON_REQUEST_FAILED';
74
88
  const status = UNAVAILABLE_CODES.has(code)
75
89
  ? 503
76
- : BAD_GATEWAY_CODES.has(code)
90
+ : BAD_GATEWAY_CODES.has(code) || PACKAGE_UPSTREAM_FAILURE_CODES.has(code)
77
91
  ? 502
78
92
  : code === 'INVALID_SESSION'
79
93
  ? 404
80
94
  : code === 'SESSION_IN_USE' || code === 'OPERATION_PAYLOAD_MISMATCH' || code === 'STALE_STREAM_EPOCH'
81
- || code === ENGINE_UNSUPPORTED_OPERATION
95
+ || code === ENGINE_UNSUPPORTED_OPERATION || code === 'CONTROL_UNAVAILABLE'
96
+ || code === 'PACKAGE_ALREADY_INSTALLED' || code === 'PACKAGE_PINNED'
82
97
  ? 409
83
98
  : code === 'OPERATION_EXPIRED'
84
99
  ? 410
@@ -89,11 +104,18 @@ const writeDaemonError = (res, error) => {
89
104
  : code === 'ATTACHMENT_MISSING'
90
105
  ? 410
91
106
  : 400;
92
- res.status(status).json({ error: { code } });
107
+ // A sandbox failure carries the launcher's stable reason code (for
108
+ // example NO_LANDLOCK); never a path or raw launcher output.
109
+ // A session refused while it finishes a turn before changing daemons says
110
+ // so (`SESSION_SWITCHING`), since `SESSION_IN_USE` otherwise means another
111
+ // PiChamber instance holds it.
112
+ const reason = (code === 'SANDBOX_UNAVAILABLE' || code === 'SESSION_IN_USE') && typeof error?.reason === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(error.reason)
113
+ ? error.reason
114
+ : undefined;
115
+ res.status(status).json({ error: { code, ...(reason ? { reason } : {}) } });
93
116
  };
94
117
 
95
- const getDaemonRuntime = (getPiSessionDaemonRuntime) => {
96
- const runtime = getPiSessionDaemonRuntime();
118
+ const requireDaemon = (runtime) => {
97
119
  if (!runtime) {
98
120
  const error = new Error('The Pi session daemon is unavailable.');
99
121
  error.code = 'DAEMON_UNAVAILABLE';
@@ -157,6 +179,36 @@ const projectListLiveStatus = (value) => {
157
179
  };
158
180
  };
159
181
 
182
+ // Fill in live state the owning daemon lacks from daemons still draining
183
+ // sessions for the same folder, matched by session id. Membership and every
184
+ // other field stay the owner's.
185
+ // Live state (`live`, `inputState`) another daemon samples for rows the
186
+ // list's own daemon lacks, merged by session id. Its sequences belong to
187
+ // that daemon's stream, so a merged row says which: `stream` (`main` for
188
+ // the main daemon) and that daemon's `streamEpoch`. `others` is a list of
189
+ // `{ stream, streamEpoch, items }`.
190
+ const mergeOtherDaemonsLiveState = (items, others) => {
191
+ if (others.length === 0) return items;
192
+ const byId = new Map();
193
+ for (const other of others) {
194
+ for (const item of other.items) {
195
+ if (!item.live && !item.inputState) continue;
196
+ if (!byId.get(item.session.id)?.item.live) byId.set(item.session.id, { other, item });
197
+ }
198
+ }
199
+ return items.map((item) => {
200
+ const found = byId.get(item.session.id);
201
+ if (!found || item.live || item.inputState) return item;
202
+ return {
203
+ ...item,
204
+ ...(found.item.live ? { live: found.item.live } : {}),
205
+ ...(found.item.inputState ? { inputState: found.item.inputState } : {}),
206
+ stream: found.other.stream,
207
+ ...(found.other.streamEpoch ? { streamEpoch: found.other.streamEpoch } : {}),
208
+ };
209
+ });
210
+ };
211
+
160
212
  const projectSessionList = (sessions) => {
161
213
  if (!Array.isArray(sessions)) throw protocolMismatch();
162
214
  return sessions.map((item) => {
@@ -430,6 +482,13 @@ const projectSessionDetail = (value) => {
430
482
  lastSequence: value.lastSequence,
431
483
  isStreaming,
432
484
  lifecycle,
485
+ // Read from the transcript on disk while the session's sandbox cannot
486
+ // run: history only, no live state (see the project sandbox manager).
487
+ // `readOnlyReason` is why the sandbox cannot run (a stable code).
488
+ ...(value.readOnly === true ? {
489
+ readOnly: true,
490
+ ...(typeof value.readOnlyReason === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(value.readOnlyReason) ? { readOnlyReason: value.readOnlyReason } : {}),
491
+ } : {}),
433
492
  ...projectRunningCommand(lifecycle, value.command),
434
493
  ...(retry ? { retry } : {}),
435
494
  ...(compaction ? { compaction } : {}),
@@ -641,6 +700,40 @@ const projectExtensionAppPayload = (app) => ({
641
700
  const EXTENSION_COMMAND_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/;
642
701
  const OPAQUE_EXTENSION_ID_PATTERN = /^[a-f0-9]{16}$/;
643
702
 
703
+ const HEX_COLOR_PATTERN = /^#[0-9a-f]{6}$/i;
704
+ const PALETTE_TOKEN_PATTERN = /^[A-Za-z]{1,40}$/;
705
+
706
+ /** `{ background, foreground, palette[16] }` of `#rrggbb` colours, or null. */
707
+ const projectTerminalColors = (value) => {
708
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
709
+ const { background, foreground, palette } = value;
710
+ if (typeof background !== 'string' || !HEX_COLOR_PATTERN.test(background)) return null;
711
+ if (typeof foreground !== 'string' || !HEX_COLOR_PATTERN.test(foreground)) return null;
712
+ if (!Array.isArray(palette) || palette.length !== 16) return null;
713
+ if (!palette.every((color) => typeof color === 'string' && HEX_COLOR_PATTERN.test(color))) return null;
714
+ return { background, foreground, palette: [...palette] };
715
+ };
716
+
717
+ /** Pi's theme name, appearance, optional page background and token colours, or null. */
718
+ const projectExtensionPalette = (result) => {
719
+ if (!result || typeof result !== 'object') return null;
720
+ if (typeof result.theme !== 'string' || result.theme.length === 0 || result.theme.length > 128) return null;
721
+ if (result.appearance !== 'light' && result.appearance !== 'dark') return null;
722
+ if (result.background !== undefined && (typeof result.background !== 'string' || !HEX_COLOR_PATTERN.test(result.background))) return null;
723
+ if (!result.colors || typeof result.colors !== 'object' || Array.isArray(result.colors)) return null;
724
+ const colors = {};
725
+ for (const [token, color] of Object.entries(result.colors)) {
726
+ if (!PALETTE_TOKEN_PATTERN.test(token) || typeof color !== 'string' || !HEX_COLOR_PATTERN.test(color)) continue;
727
+ colors[token] = color;
728
+ }
729
+ return {
730
+ theme: result.theme,
731
+ appearance: result.appearance,
732
+ ...(result.background !== undefined ? { background: result.background } : {}),
733
+ colors,
734
+ };
735
+ };
736
+
644
737
  export const projectExtensionList = (result) => {
645
738
  if (!result || typeof result !== 'object' || typeof result.directory !== 'string'
646
739
  || !Array.isArray(result.extensions) || !Array.isArray(result.commands)) throw protocolMismatch();
@@ -666,6 +759,115 @@ export const projectExtensionList = (result) => {
666
759
  return { directory: result.directory, extensions, commands };
667
760
  };
668
761
 
762
+ // `pi config` / `pi list` for extensions (session-daemon/extension-config.js).
763
+ // Ids are opaque sha256 base64url; names and sources are display forms the
764
+ // daemon already made path-free, re-checked here so nothing path-like or
765
+ // unexpected crosses.
766
+ const EXTENSION_CONFIG_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
767
+ // The same rules as the daemon's `isValidNpmPackageName` (extension-config.js).
768
+ const NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/;
769
+ const isNpmPackageName = (value) => typeof value === 'string' && value.length > 0 && value.length <= 214
770
+ && NPM_PACKAGE_NAME_PATTERN.test(value);
771
+ const PACKAGE_VERSION_PATTERN = /^[0-9A-Za-z.+-]{1,64}$/;
772
+ // npm install / update can take minutes.
773
+ const PACKAGE_INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
774
+ const EXTENSION_CONFIG_OVERRIDE_STATES = new Set(['inherit', 'load', 'unload']);
775
+ const EXTENSION_CONFIG_GROUPS = new Set(['package', 'auto', 'settings', 'builtin']);
776
+ const EXTENSION_CONFIG_SCOPES = new Set(['user', 'project']);
777
+ const EXTENSION_CONFIG_PACKAGE_KINDS = new Set(['npm', 'git', 'local']);
778
+
779
+ const isDisplayText = (value, max = 256) => typeof value === 'string' && value.length > 0 && value.length <= max
780
+ && !value.includes('\\') && !value.startsWith('/') && !value.startsWith('~') && !/^[A-Za-z]:/.test(value);
781
+
782
+ // `replaced`: plugins and built-ins a live runtime left out because another
783
+ // extension took their tool, command, or flag. Present (even empty) only when
784
+ // the daemon answered from a live runtime. A bad entry is dropped; a bad
785
+ // optional part (`registers`, `by`) is left out of an otherwise good entry.
786
+ const EXTENSION_CONFIG_REPLACED_KINDS = new Set(['plugin', 'builtin']);
787
+ const EXTENSION_CONFIG_REGISTER_KINDS = new Set(['tool', 'command', 'flag']);
788
+ const PLUGIN_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
789
+
790
+ const projectReplacedExtensions = (replaced) => {
791
+ if (!Array.isArray(replaced)) return undefined;
792
+ return replaced.flatMap((entry) => {
793
+ if (!entry || typeof entry !== 'object' || !EXTENSION_CONFIG_REPLACED_KINDS.has(entry.kind) || typeof entry.id !== 'string'
794
+ || !(entry.kind === 'plugin' ? entry.id.length <= 40 && PLUGIN_ID_PATTERN.test(entry.id) : EXTENSION_CONFIG_ID_PATTERN.test(entry.id))) return [];
795
+ const registers = entry.registers;
796
+ const by = entry.by;
797
+ const validRegisters = registers && typeof registers === 'object' && EXTENSION_CONFIG_REGISTER_KINDS.has(registers.kind)
798
+ && isDisplayText(registers.name) && !registers.name.startsWith('--');
799
+ const validBy = by && typeof by === 'object' && isDisplayText(by.name);
800
+ return [{
801
+ kind: entry.kind,
802
+ id: entry.id,
803
+ ...(validRegisters ? { registers: { kind: registers.kind, name: registers.name } } : {}),
804
+ ...(validBy ? {
805
+ by: {
806
+ ...(typeof by.id === 'string' && EXTENSION_CONFIG_ID_PATTERN.test(by.id) ? { id: by.id } : {}),
807
+ name: by.name,
808
+ },
809
+ } : {}),
810
+ }];
811
+ });
812
+ };
813
+
814
+ const projectExtensionConfig = (result) => {
815
+ if (!result || typeof result !== 'object' || !result.project || typeof result.project !== 'object'
816
+ || !Array.isArray(result.packages) || !Array.isArray(result.extensions) || !Array.isArray(result.installFailures)
817
+ || (result.directory !== undefined && typeof result.directory !== 'string')) throw protocolMismatch();
818
+ const trusted = result.project.trusted === true;
819
+ const packages = result.packages.map((pkg) => {
820
+ if (!pkg || typeof pkg !== 'object' || typeof pkg.id !== 'string' || !EXTENSION_CONFIG_ID_PATTERN.test(pkg.id)
821
+ || !EXTENSION_CONFIG_SCOPES.has(pkg.scope) || !EXTENSION_CONFIG_PACKAGE_KINDS.has(pkg.kind)
822
+ || (pkg.kind === 'local' ? !isDisplayText(pkg.source) || pkg.source.includes('/') : !isDisplayText(pkg.source))) throw protocolMismatch();
823
+ // Read from the package's own package.json; a bad value is dropped.
824
+ return {
825
+ id: pkg.id,
826
+ source: pkg.source,
827
+ scope: pkg.scope,
828
+ kind: pkg.kind,
829
+ installed: pkg.installed === true,
830
+ filtered: pkg.filtered === true,
831
+ ...(isNpmPackageName(pkg.name) ? { name: pkg.name } : {}),
832
+ ...(typeof pkg.version === 'string' && PACKAGE_VERSION_PATTERN.test(pkg.version) ? { version: pkg.version } : {}),
833
+ ...(pkg.pichamber === true ? { pichamber: true } : {}),
834
+ ...(pkg.pinned === true && pkg.kind === 'npm' ? { pinned: true } : {}),
835
+ };
836
+ });
837
+ const packageIds = new Set(packages.map((pkg) => pkg.id));
838
+ const extensions = result.extensions.map((extension) => {
839
+ if (!extension || typeof extension !== 'object' || typeof extension.id !== 'string' || !EXTENSION_CONFIG_ID_PATTERN.test(extension.id)
840
+ || !isDisplayText(extension.name) || !EXTENSION_CONFIG_GROUPS.has(extension.group) || !EXTENSION_CONFIG_SCOPES.has(extension.scope)
841
+ || (extension.global !== undefined && typeof extension.global !== 'boolean')) throw protocolMismatch();
842
+ const project = extension.project;
843
+ if (project !== undefined && (!trusted || !project || typeof project !== 'object' || !EXTENSION_CONFIG_OVERRIDE_STATES.has(project.state)
844
+ || typeof project.inherited !== 'boolean' || typeof project.enabled !== 'boolean')) throw protocolMismatch();
845
+ return {
846
+ id: extension.id,
847
+ name: extension.name,
848
+ group: extension.group,
849
+ ...(extension.group === 'package' && packageIds.has(extension.packageId) ? { packageId: extension.packageId } : {}),
850
+ scope: extension.scope,
851
+ ...(typeof extension.global === 'boolean' ? { global: extension.global } : {}),
852
+ ...(project ? { project: { state: project.state, inherited: project.inherited, enabled: project.enabled } } : {}),
853
+ };
854
+ });
855
+ const installFailures = result.installFailures.flatMap((failure) => (
856
+ failure && typeof failure === 'object' && isDisplayText(failure.source) && typeof failure.message === 'string'
857
+ ? [{ source: failure.source, message: failure.message.slice(0, 300) }]
858
+ : []
859
+ ));
860
+ return {
861
+ ...(typeof result.directory === 'string' && result.directory.length > 0 ? { directory: result.directory } : {}),
862
+ project: { available: result.project.available === true, trusted },
863
+ packages,
864
+ extensions,
865
+ installFailures,
866
+ ...(Array.isArray(result.replaced) ? { replaced: projectReplacedExtensions(result.replaced) } : {}),
867
+ ...(result.deferred === true ? { deferred: true } : {}),
868
+ };
869
+ };
870
+
669
871
  // User shell commands (`!cmd`). Command text is user-authored; output is a
670
872
  // bounded tail. Field caps mirror the daemon's live/recorded limits.
671
873
  const BASH_COMMAND_MAX_CHARS = 100_000;
@@ -694,7 +896,16 @@ const projectBashExecutions = (value) => (Array.isArray(value)
694
896
  ? value.slice(0, 8).map(projectBashExecution).filter(Boolean)
695
897
  : undefined);
696
898
 
899
+ // Composer controls are checked again here with the daemon's own parser, so
900
+ // the browser only ever sees the validated shape.
901
+ const projectComposerControls = (value) => {
902
+ if (!Array.isArray(value)) return undefined;
903
+ // An empty list stays: it tells the browser the session has none.
904
+ return value.slice(0, MAX_CONTROLS_PER_SESSION).map(parseComposerControl).filter((control) => control && !control.remove);
905
+ };
906
+
697
907
  function projectExtensionSnapshotState(snapshot) {
908
+ const extensionControls = projectComposerControls(snapshot.extensionControls);
698
909
  const extensionStatuses = Array.isArray(snapshot.extensionStatuses)
699
910
  ? snapshot.extensionStatuses.filter((entry) => entry && typeof entry.key === 'string' && typeof entry.text === 'string' && entry.key.length > 0 && entry.key.length <= 128 && entry.text.length <= 1000).slice(0, 50).map((entry) => ({ key: entry.key.slice(0, 128), text: entry.text.slice(0, 1000) }))
700
911
  : undefined;
@@ -708,8 +919,9 @@ function projectExtensionSnapshotState(snapshot) {
708
919
  const extensionDialogs = Array.isArray(snapshot.extensionDialogs)
709
920
  ? snapshot.extensionDialogs.filter((entry) => entry && typeof entry.requestId === 'string' && typeof entry.method === 'string' && typeof entry.title === 'string').slice(0, 20).map((entry) => ({
710
921
  requestId: entry.requestId.slice(0, 512),
711
- method: ['select', 'confirm', 'input', 'editor', 'form'].includes(entry.method) ? entry.method : 'confirm',
922
+ method: ['select', 'confirm', 'input', 'editor', 'form', 'choose'].includes(entry.method) ? entry.method : 'confirm',
712
923
  title: entry.title.slice(0, 512),
924
+ ...(entry.method === 'choose' ? projectExtensionChooseFields(entry) : {}),
713
925
  ...(typeof entry.message === 'string' ? { message: entry.message.slice(0, 2000) } : {}),
714
926
  ...(Array.isArray(entry.options) ? { options: entry.options.filter((option) => typeof option === 'string').map((option) => option.slice(0, 256)).slice(0, 20) } : {}),
715
927
  ...(typeof entry.placeholder === 'string' ? { placeholder: entry.placeholder.slice(0, 512) } : {}),
@@ -735,6 +947,7 @@ function projectExtensionSnapshotState(snapshot) {
735
947
  : undefined;
736
948
  return {
737
949
  ...(extensionStatuses ? { extensionStatuses } : {}),
950
+ ...(extensionControls ? { extensionControls } : {}),
738
951
  ...(extensionWidgets ? { extensionWidgets } : {}),
739
952
  ...(extensionDialogs ? { extensionDialogs } : {}),
740
953
  ...(extensionPanels ? { extensionPanels } : {}),
@@ -758,7 +971,13 @@ export const projectEventFrame = (frame) => {
758
971
  const streamEpoch = typeof frame.streamEpoch === 'string' && frame.streamEpoch.length > 0 && frame.streamEpoch.length <= 128
759
972
  ? frame.streamEpoch
760
973
  : undefined;
761
- const common = { protocolVersion: 1, kind: 'event', name: frame.event, sequence: frame.sequence, sessionId, directory, ...(streamEpoch ? { streamEpoch } : {}) };
974
+ // `draft` marks a draft session's events (a runtime warmed for a
975
+ // new-session draft): clients keep them out of the session list.
976
+ const common = {
977
+ protocolVersion: 1, kind: 'event', name: frame.event, sequence: frame.sequence, sessionId, directory,
978
+ ...(streamEpoch ? { streamEpoch } : {}),
979
+ ...(frame.draft === true ? { draft: true } : {}),
980
+ };
762
981
  switch (frame.event) {
763
982
  case 'session.input': {
764
983
  const pending = projectPendingInputSummary(frame.payload.pending);
@@ -983,6 +1202,15 @@ export const projectEventFrame = (frame) => {
983
1202
  if (frame.payload.text !== undefined && typeof frame.payload.text !== 'string') return null;
984
1203
  return { ...common, payload: { key: frame.payload.key.slice(0, 128), ...(typeof frame.payload.text === 'string' ? { text: frame.payload.text.slice(0, 1000) } : {}) } };
985
1204
  }
1205
+ case 'extension.control': {
1206
+ if (frame.payload.removed === true) {
1207
+ if (typeof frame.payload.id !== 'string' || frame.payload.id.length === 0 || frame.payload.id.length > 64) return null;
1208
+ return { ...common, payload: { id: frame.payload.id, removed: true } };
1209
+ }
1210
+ const control = parseComposerControl(frame.payload.control);
1211
+ if (!control || control.remove) return null;
1212
+ return { ...common, payload: { control } };
1213
+ }
986
1214
  case 'extension.widget': {
987
1215
  if (typeof frame.payload.key !== 'string' || frame.payload.key.length === 0 || frame.payload.key.length > 128) return null;
988
1216
  if (frame.payload.lines !== undefined) {
@@ -1002,14 +1230,18 @@ export const projectEventFrame = (frame) => {
1002
1230
  }
1003
1231
  case 'extension.dialog': {
1004
1232
  if (typeof frame.payload.requestId !== 'string' || frame.payload.requestId.length === 0 || frame.payload.requestId.length > 512) return null;
1005
- if (!['select', 'confirm', 'input', 'editor', 'form'].includes(frame.payload.method)) return null;
1233
+ if (!['select', 'confirm', 'input', 'editor', 'form', 'choose'].includes(frame.payload.method)) return null;
1006
1234
  if (typeof frame.payload.title !== 'string' || frame.payload.title.length === 0 || frame.payload.title.length > 512) return null;
1235
+ const chooseFields = frame.payload.method === 'choose' ? projectExtensionChooseFields(frame.payload) : null;
1236
+ // A question nobody could answer is dropped, like any malformed event.
1237
+ if (chooseFields && chooseFields.choices.length === 0) return null;
1007
1238
  return {
1008
1239
  ...common,
1009
1240
  payload: {
1010
1241
  requestId: frame.payload.requestId.slice(0, 512),
1011
1242
  method: frame.payload.method,
1012
1243
  title: frame.payload.title.slice(0, 512),
1244
+ ...(chooseFields ?? {}),
1013
1245
  ...(typeof frame.payload.message === 'string' ? { message: frame.payload.message.slice(0, 2000) } : {}),
1014
1246
  ...(Array.isArray(frame.payload.options) ? { options: frame.payload.options.filter((option) => typeof option === 'string').map((option) => option.slice(0, 256)).slice(0, 20) } : {}),
1015
1247
  ...(typeof frame.payload.placeholder === 'string' ? { placeholder: frame.payload.placeholder.slice(0, 512) } : {}),
@@ -1092,20 +1324,78 @@ export const projectEventFrame = (frame) => {
1092
1324
  }
1093
1325
  };
1094
1326
 
1095
- const requestSessionOperation = async (req, res, getPiSessionDaemonRuntime, command, payload = {}) => {
1327
+ const sessionOperationDirectory = (req) => (typeof req.query?.directory === 'string' && req.query.directory.length > 0
1328
+ ? req.query.directory
1329
+ : (typeof req.body?.directory === 'string' && req.body.directory.length > 0
1330
+ ? req.body.directory
1331
+ : (typeof req.body?.cwd === 'string' && req.body.cwd.length > 0 ? req.body.cwd : undefined)));
1332
+
1333
+ // The folder a session operation was routed by: the request's own, or the
1334
+ // transcript's when `requestSessionOperation` looked it up. Stream stamps
1335
+ // use it so a response names the daemon that actually served it.
1336
+ const sessionRouteDirectory = (req, res) => res.locals?.piRouteDirectory ?? sessionOperationDirectory(req);
1337
+
1338
+ // Commands that let a session waiting to switch daemons finish its turn
1339
+ // (or be read) where it runs now. Anything else would start new work in the
1340
+ // old daemon, so it is refused until the session has moved.
1341
+ const DRAINING_SESSION_COMMANDS = new Set([
1342
+ 'sessions.open', 'sessions.messages', 'sessions.tree', 'sessions.abort', 'sessions.abortBash', 'sessions.steer',
1343
+ 'sessions.sendReceipt', 'extensions.draft', 'sessions.discardDraft',
1344
+ 'extensions.custom.input', 'extensions.custom.viewport', 'extensions.custom.close', 'extensions.custom.focus', 'extensions.custom.refresh',
1345
+ ]);
1346
+
1347
+ const sessionInUse = () => Object.assign(new Error('The session is finishing a turn before it switches.'), { code: 'SESSION_IN_USE', reason: 'SESSION_SWITCHING' });
1348
+
1349
+ // The daemon still running a session that waits to switch, or undefined.
1350
+ // Marks the response so its stream stamp names that daemon.
1351
+ const drainingSessionRuntime = (res, sandboxManager, sessionId, command) => {
1352
+ const draining = sandboxManager?.drainingSession?.(sessionId);
1353
+ if (!draining) return undefined;
1354
+ if (!DRAINING_SESSION_COMMANDS.has(command)) throw sessionInUse();
1355
+ if (res.locals) res.locals.piDrainingStream = { stream: draining.stream };
1356
+ return draining.runtime;
1357
+ };
1358
+
1359
+ // The folder that picks the daemon for a session operation. A daemon finds a
1360
+ // session by id wherever it lives, so the client's folder (its current one,
1361
+ // which a deep link can get wrong) or no folder at all could send a sandboxed
1362
+ // project's session to the main daemon and run its agent unsandboxed. While
1363
+ // any project is sandboxed, the session's transcript decides (the folder it
1364
+ // is stored under, then the folder in its header; see the manager's
1365
+ // `directoryForSession`); the client's folder applies only to a session not
1366
+ // yet written to disk. The daemon payload keeps the client's folder.
1367
+ const sessionDaemonDirectory = async (res, sandboxManager, sessionId, directory) => {
1368
+ if (!sandboxManager?.hasSandboxedProjects()) return directory;
1369
+ const transcriptDirectory = await sandboxManager.directoryForSession(sessionId);
1370
+ if (!transcriptDirectory) return sandboxManager.routeDirectory(directory);
1371
+ const routed = await sandboxManager.routeDirectory(transcriptDirectory);
1372
+ if (res.locals) res.locals.piRouteDirectory = routed;
1373
+ return routed;
1374
+ };
1375
+
1376
+ const requestSessionOperation = async (req, res, daemonPool, command, payload = {}, sandboxManager) => {
1096
1377
  const sessionId = sessionIdFrom(req);
1097
1378
  if (!sessionId) {
1098
1379
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1099
1380
  return undefined;
1100
1381
  }
1101
- const directory = typeof req.query?.directory === 'string' && req.query.directory.length > 0
1102
- ? req.query.directory
1103
- : (typeof req.body?.directory === 'string' && req.body.directory.length > 0
1104
- ? req.body.directory
1105
- : (typeof req.body?.cwd === 'string' && req.body.cwd.length > 0 ? req.body.cwd : undefined));
1382
+ const directory = sessionOperationDirectory(req);
1106
1383
  try {
1107
- return await getDaemonRuntime(getPiSessionDaemonRuntime).request(command, {
1108
- ...payload,
1384
+ const draining = drainingSessionRuntime(res, sandboxManager, sessionId, command);
1385
+ if (draining) {
1386
+ return await draining.request(command, { ...payload, sessionId, ...(directory ? { directory } : {}) });
1387
+ }
1388
+ const routeDirectory = await sessionDaemonDirectory(res, sandboxManager, sessionId, directory);
1389
+ const runtime = requireDaemon(daemonPool.forDirectory(routeDirectory));
1390
+ // The stream of the daemon this request goes to, taken now: the folder
1391
+ // may have another owner by the time the response is stamped.
1392
+ if (res.locals) res.locals.piServedStream = { stream: daemonPool.streamFor(routeDirectory) };
1393
+ // A send made with the old daemon's epoch right after the session moved.
1394
+ const sendPayload = typeof payload.streamEpoch === 'string' && sandboxManager?.sendEpochFor
1395
+ ? { ...payload, streamEpoch: await sandboxManager.sendEpochFor(sessionId, payload.streamEpoch, runtime) }
1396
+ : payload;
1397
+ return await runtime.request(command, {
1398
+ ...sendPayload,
1109
1399
  sessionId,
1110
1400
  ...(directory ? { directory } : {}),
1111
1401
  });
@@ -1122,6 +1412,16 @@ const requestSessionOperation = async (req, res, getPiSessionDaemonRuntime, comm
1122
1412
  */
1123
1413
  export const registerPiRuntimeRoutes = (app, {
1124
1414
  getPiSessionDaemonRuntime,
1415
+ // Which daemon serves a request (session-daemon/daemon-pool.js). Without
1416
+ // one, the single runtime from `getPiSessionDaemonRuntime` is the main
1417
+ // daemon and owns every directory.
1418
+ daemonPool = createPiDaemonPool({ getMainRuntime: getPiSessionDaemonRuntime }),
1419
+ // Sandboxed projects (sandbox/project-sandbox-manager.js). Without one no
1420
+ // project is sandboxed and no sandbox route exists.
1421
+ sandboxManager,
1422
+ // Folders whose trust must stay "ask" after a sandbox was turned off
1423
+ // (sandbox/trust-ask.js); an explicit trust decision clears one.
1424
+ trustAsk,
1125
1425
  archiveStore = createPiArchiveStore(),
1126
1426
  attachmentStore = createPiAttachmentStore(),
1127
1427
  settingsStore = createPiSettingsStore(),
@@ -1138,8 +1438,76 @@ export const registerPiRuntimeRoutes = (app, {
1138
1438
  smallModelGenerator = async (input) => (await import('./small-model-generation.js')).generateWithSmallModel(input),
1139
1439
  eventHeartbeatMs = 15_000,
1140
1440
  eventStreamMaxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
1441
+ eventStreamRetryBaseMs,
1442
+ // Called with the id after a session is deleted, for PiChamber state kept
1443
+ // per session elsewhere (plugin switches). Must not throw.
1444
+ onSessionDeleted = () => {},
1141
1445
  }) => {
1142
1446
  const eventStreamRegistry = createPiEventStreamRegistry();
1447
+ // Directory-less commands (providers, settings, projects, engines,
1448
+ // provider login, the extension palette) and resource writes always run on
1449
+ // the main daemon: they write Pi's own config and credentials, which a
1450
+ // project daemon may only read. Everything scoped to a directory runs on
1451
+ // the daemon that owns it.
1452
+ const mainDaemon = () => requireDaemon(daemonPool.main());
1453
+ // Sessions run by a sandbox daemon say so, and a session waiting to
1454
+ // switch modes after its turn says where to; other rows are unchanged.
1455
+ const withSandbox = (item) => {
1456
+ if (!sandboxManager || !item?.session) return item;
1457
+ const state = sandboxManager.sessionState(item.session.id, item.session.directory);
1458
+ if (!state.sandboxed && !state.pendingSwitch) return item;
1459
+ return {
1460
+ ...item,
1461
+ session: {
1462
+ ...item.session,
1463
+ ...(state.sandboxed ? { sandboxed: true } : {}),
1464
+ ...(state.pendingSwitch ? { pendingSwitch: state.pendingSwitch } : {}),
1465
+ },
1466
+ };
1467
+ };
1468
+ // PiChamber changed Pi's config files: running sandbox daemons are
1469
+ // replaced at their next idle edge. Never fails the write.
1470
+ const piConfigChanged = () => {
1471
+ sandboxManager?.configChanged().catch((error) => console.warn('[pi-sandbox] config change handling failed', error?.code ?? error));
1472
+ };
1473
+ // The pool owns sandboxed projects only after a reconcile has read the
1474
+ // settings. While the last one failed (unreadable settings at start, or a
1475
+ // failed apply after a save), try again before anything can route; if it
1476
+ // still fails, every Pi route is refused rather than run on the main
1477
+ // daemon. Settings and sandbox routes stay open so the cause can be fixed,
1478
+ // and so does the event stream, which starts nothing.
1479
+ if (sandboxManager) {
1480
+ const OPEN_WHILE_UNKNOWN = /^\/(?:ui-settings|sandbox(?:\/|$)|events(?:\/|$))/;
1481
+ app.use('/api/pi', async (req, res, next) => {
1482
+ if (!sandboxManager.needsReconcile()) return next();
1483
+ try {
1484
+ await sandboxManager.reconcile();
1485
+ return next();
1486
+ } catch (error) {
1487
+ if (OPEN_WHILE_UNKNOWN.test(req.path)) return next();
1488
+ console.warn('[pi-sandbox] sandbox settings are unreadable; refusing Pi requests', error?.code ?? '');
1489
+ return res.status(503).json({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'SANDBOX_SETTINGS_UNREADABLE' } });
1490
+ }
1491
+ });
1492
+ registerPiSandboxRoutes(app, { sandboxManager });
1493
+ }
1494
+ const daemonFor = (directory) => requireDaemon(daemonPool.forDirectory(directory));
1495
+ // The daemon for a folder a client named. While a project is sandboxed
1496
+ // the folder is first spelled the way the daemon reads it, so a padded or
1497
+ // symlinked path to a sandboxed project cannot reach the main daemon.
1498
+ const routeDirectoryFor = async (directory) => (sandboxManager ? sandboxManager.routeDirectory(directory) : directory);
1499
+ const daemonForClientDirectory = async (directory) => daemonFor(await routeDirectoryFor(directory));
1500
+ // A stamped response (`streamEpoch`, sequences) from a project daemon says
1501
+ // which daemon stream its sequences belong to; main responses are
1502
+ // unchanged.
1503
+ // A response served by a daemon draining the session (see
1504
+ // `drainingSessionRuntime`) names that daemon instead of the owner.
1505
+ const withStream = (body, directory, res) => {
1506
+ const draining = res?.locals?.piDrainingStream;
1507
+ const served = res?.locals?.piServedStream;
1508
+ const stream = draining ? draining.stream : served ? served.stream : daemonPool.streamFor(directory);
1509
+ return stream ? { ...body, stream } : body;
1510
+ };
1143
1511
  // Tell every device an archive mark changed (a `session.archive` event on
1144
1512
  // the session's stream) so other clients re-list that folder. The change is
1145
1513
  // already saved, so this never delays or fails the request: an older
@@ -1148,7 +1516,7 @@ export const registerPiRuntimeRoutes = (app, {
1148
1516
  const publishArchiveChange = (sessionId, archived, directory) => {
1149
1517
  void (async () => {
1150
1518
  try {
1151
- await getDaemonRuntime(getPiSessionDaemonRuntime).request('archive.publish', {
1519
+ await daemonFor(directory).request('archive.publish', {
1152
1520
  sessionId,
1153
1521
  archived,
1154
1522
  ...(typeof directory === 'string' && directory.length > 0 ? { directory } : {}),
@@ -1186,7 +1554,10 @@ export const registerPiRuntimeRoutes = (app, {
1186
1554
 
1187
1555
  app.put('/api/pi/ui-settings', async (req, res) => {
1188
1556
  try {
1189
- res.json(await uiSettingsStore.write(req.body));
1557
+ const saved = await uiSettingsStore.write(req.body);
1558
+ // A removed sandboxed project releases its daemon.
1559
+ await sandboxManager?.reconcile().catch((error) => console.warn('[pi-sandbox] reconcile failed', error?.code ?? error));
1560
+ res.json(saved);
1190
1561
  } catch {
1191
1562
  res.status(400).json({ error: 'Invalid UI settings' });
1192
1563
  }
@@ -1315,7 +1686,7 @@ export const registerPiRuntimeRoutes = (app, {
1315
1686
  });
1316
1687
 
1317
1688
  app.get('/api/pi/runtime', async (_req, res) => {
1318
- const runtime = getPiSessionDaemonRuntime();
1689
+ const runtime = daemonPool.main();
1319
1690
  if (!runtime) {
1320
1691
  res.status(503).json({
1321
1692
  protocolVersion: 1,
@@ -1348,7 +1719,7 @@ export const registerPiRuntimeRoutes = (app, {
1348
1719
 
1349
1720
  app.get('/api/pi/projects', async (_req, res) => {
1350
1721
  try {
1351
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('projects.list');
1722
+ const result = await mainDaemon().request('projects.list');
1352
1723
  if (!Array.isArray(result?.projects) || result.projects.some((project) => !project || typeof project.directory !== 'string' || typeof project.selected !== 'boolean')) throw protocolMismatch();
1353
1724
  res.json({ projects: result.projects.map((project) => ({ directory: project.directory, selected: project.selected })) });
1354
1725
  } catch (error) {
@@ -1363,7 +1734,7 @@ export const registerPiRuntimeRoutes = (app, {
1363
1734
  return;
1364
1735
  }
1365
1736
  try {
1366
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('projects.select', { directory });
1737
+ const result = await mainDaemon().request('projects.select', { directory });
1367
1738
  if (typeof result?.directory !== 'string') throw protocolMismatch();
1368
1739
  res.json({ directory: result.directory });
1369
1740
  } catch (error) {
@@ -1373,7 +1744,7 @@ export const registerPiRuntimeRoutes = (app, {
1373
1744
 
1374
1745
  app.get('/api/pi/providers', async (_req, res) => {
1375
1746
  try {
1376
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.list');
1747
+ const result = await mainDaemon().request('providers.list');
1377
1748
  res.json(projectProviders(result));
1378
1749
  } catch (error) {
1379
1750
  writeDaemonError(res, error);
@@ -1382,7 +1753,7 @@ export const registerPiRuntimeRoutes = (app, {
1382
1753
 
1383
1754
  app.get('/api/pi/engines', async (_req, res) => {
1384
1755
  try {
1385
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('engines.list');
1756
+ const result = await mainDaemon().request('engines.list');
1386
1757
  res.json(projectEngines(result));
1387
1758
  } catch (error) {
1388
1759
  writeDaemonError(res, error);
@@ -1392,7 +1763,7 @@ export const registerPiRuntimeRoutes = (app, {
1392
1763
  app.post('/api/pi/providers/refresh', async (req, res) => {
1393
1764
  const directory = typeof req.body?.directory === 'string' && req.body.directory.length > 0 ? req.body.directory : undefined;
1394
1765
  try {
1395
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.refresh', directory ? { directory } : undefined);
1766
+ const result = await mainDaemon().request('providers.refresh', directory ? { directory } : undefined);
1396
1767
  res.json(projectProviders(result));
1397
1768
  } catch (error) {
1398
1769
  writeDaemonError(res, error);
@@ -1406,7 +1777,7 @@ export const registerPiRuntimeRoutes = (app, {
1406
1777
  return;
1407
1778
  }
1408
1779
  try {
1409
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.config.get', { providerId });
1780
+ const result = await mainDaemon().request('providers.config.get', { providerId });
1410
1781
  res.json(projectProviderConfig(result));
1411
1782
  } catch (error) {
1412
1783
  writeDaemonError(res, error);
@@ -1421,7 +1792,8 @@ export const registerPiRuntimeRoutes = (app, {
1421
1792
  return;
1422
1793
  }
1423
1794
  try {
1424
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.models.set', { ...payload, providerId });
1795
+ const result = await mainDaemon().request('providers.models.set', { ...payload, providerId });
1796
+ piConfigChanged();
1425
1797
  res.json(projectProviderConfig(result));
1426
1798
  } catch (error) {
1427
1799
  writeDaemonError(res, error);
@@ -1448,7 +1820,7 @@ export const registerPiRuntimeRoutes = (app, {
1448
1820
  return;
1449
1821
  }
1450
1822
  try {
1451
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.models.add', {
1823
+ const result = await mainDaemon().request('providers.models.add', {
1452
1824
  providerId,
1453
1825
  model: {
1454
1826
  id,
@@ -1460,6 +1832,7 @@ export const registerPiRuntimeRoutes = (app, {
1460
1832
  ...(maxTokens !== undefined ? { maxTokens } : {}),
1461
1833
  },
1462
1834
  });
1835
+ piConfigChanged();
1463
1836
  res.status(201).json(projectProviderConfig(result));
1464
1837
  } catch (error) {
1465
1838
  writeDaemonError(res, error);
@@ -1473,7 +1846,7 @@ export const registerPiRuntimeRoutes = (app, {
1473
1846
  return;
1474
1847
  }
1475
1848
  try {
1476
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.status', { providerId });
1849
+ const result = await mainDaemon().request('providers.status', { providerId });
1477
1850
  res.json(projectProviderStatus(result));
1478
1851
  } catch (error) {
1479
1852
  writeDaemonError(res, error);
@@ -1490,10 +1863,12 @@ export const registerPiRuntimeRoutes = (app, {
1490
1863
  return;
1491
1864
  }
1492
1865
  try {
1493
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.login', {
1866
+ const result = await mainDaemon().request('providers.login', {
1494
1867
  providerId, type, ...(typeof apiKey === 'string' ? { apiKey } : {}),
1495
1868
  });
1496
- res.status(202).json(projectProviderLogin(result));
1869
+ const login = projectProviderLogin(result);
1870
+ if (login.state === 'complete') piConfigChanged();
1871
+ res.status(202).json(login);
1497
1872
  } catch (error) {
1498
1873
  writeDaemonError(res, error);
1499
1874
  }
@@ -1507,8 +1882,10 @@ export const registerPiRuntimeRoutes = (app, {
1507
1882
  return;
1508
1883
  }
1509
1884
  try {
1510
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.login.status', { providerId, loginId });
1511
- res.json(projectProviderLogin(result));
1885
+ const result = await mainDaemon().request('providers.login.status', { providerId, loginId });
1886
+ const login = projectProviderLogin(result);
1887
+ if (login.state === 'complete') piConfigChanged();
1888
+ res.json(login);
1512
1889
  } catch (error) {
1513
1890
  writeDaemonError(res, error);
1514
1891
  }
@@ -1523,8 +1900,10 @@ export const registerPiRuntimeRoutes = (app, {
1523
1900
  return;
1524
1901
  }
1525
1902
  try {
1526
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.login.respond', { providerId, loginId, value });
1527
- res.json(projectProviderLogin(result));
1903
+ const result = await mainDaemon().request('providers.login.respond', { providerId, loginId, value });
1904
+ const login = projectProviderLogin(result);
1905
+ if (login.state === 'complete') piConfigChanged();
1906
+ res.json(login);
1528
1907
  } catch (error) {
1529
1908
  writeDaemonError(res, error);
1530
1909
  }
@@ -1537,7 +1916,8 @@ export const registerPiRuntimeRoutes = (app, {
1537
1916
  return;
1538
1917
  }
1539
1918
  try {
1540
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('providers.logout', { providerId });
1919
+ const result = await mainDaemon().request('providers.logout', { providerId });
1920
+ piConfigChanged();
1541
1921
  res.json(projectProviderStatus(result));
1542
1922
  } catch (error) {
1543
1923
  writeDaemonError(res, error);
@@ -1576,7 +1956,7 @@ export const registerPiRuntimeRoutes = (app, {
1576
1956
 
1577
1957
  app.get('/api/pi/settings', async (_req, res) => {
1578
1958
  try {
1579
- const pi = projectPiSettings(await getDaemonRuntime(getPiSessionDaemonRuntime).request('settings.get'));
1959
+ const pi = projectPiSettings(await mainDaemon().request('settings.get'));
1580
1960
  const pichamber = await settingsStore.read();
1581
1961
  res.json({ ...pi, pichamber });
1582
1962
  } catch (error) {
@@ -1587,7 +1967,11 @@ export const registerPiRuntimeRoutes = (app, {
1587
1967
  app.put('/api/pi/settings/pi', async (req, res) => {
1588
1968
  const payload = req.body;
1589
1969
  try {
1590
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('settings.set', payload);
1970
+ const result = await mainDaemon().request('settings.set', payload);
1971
+ if (typeof payload?.trust === 'boolean' && typeof payload.directory === 'string') {
1972
+ await trustAsk?.remove(payload.directory).catch((error) => console.warn('[pi-sandbox] could not clear a trust reset', error?.code ?? error));
1973
+ }
1974
+ piConfigChanged();
1591
1975
  res.json(projectPiSettings(result));
1592
1976
  } catch (error) {
1593
1977
  writeDaemonError(res, error);
@@ -1608,7 +1992,7 @@ export const registerPiRuntimeRoutes = (app, {
1608
1992
  ? req.query.directory
1609
1993
  : undefined;
1610
1994
  try {
1611
- res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request(
1995
+ res.json(projectResources(await (await daemonForClientDirectory(directory)).request(
1612
1996
  'resources.list',
1613
1997
  directory ? { directory } : undefined,
1614
1998
  )));
@@ -1622,7 +2006,7 @@ export const registerPiRuntimeRoutes = (app, {
1622
2006
  ? req.query.directory
1623
2007
  : undefined;
1624
2008
  try {
1625
- const runtime = getDaemonRuntime(getPiSessionDaemonRuntime);
2009
+ const runtime = await daemonForClientDirectory(directory);
1626
2010
  const [resources, extensionList] = await Promise.all([
1627
2011
  runtime.request('resources.list', { ...(directory ? { directory } : {}) }),
1628
2012
  runtime.request('extensions.list', { ...(directory ? { directory } : {}) }),
@@ -1685,6 +2069,8 @@ export const registerPiRuntimeRoutes = (app, {
1685
2069
  ...(Number.isSafeInteger(snippet.updatedAt) ? { updatedAt: snippet.updatedAt } : {}),
1686
2070
  };
1687
2071
  }),
2072
+ // Where the server keeps every snippet, so a user can point an agent at it.
2073
+ ...(typeof snippetsStore.file === 'string' && snippetsStore.file.length > 0 ? { file: snippetsStore.file } : {}),
1688
2074
  };
1689
2075
  };
1690
2076
 
@@ -1803,6 +2189,14 @@ export const registerPiRuntimeRoutes = (app, {
1803
2189
  return queryDirectory ?? bodyDirectory;
1804
2190
  };
1805
2191
 
2192
+ // A project's own prompts and instruction files are changed by the daemon
2193
+ // that runs the project: for a sandboxed project that is its sandbox
2194
+ // daemon, since the main daemon never loads that project. Resources in
2195
+ // Pi's agent folder stay with the main daemon; a sandbox cannot write them.
2196
+ const resourceDaemon = async (directory, location) => (directory && location !== 'global'
2197
+ ? daemonForClientDirectory(directory)
2198
+ : mainDaemon());
2199
+
1806
2200
  app.put('/api/pi/resources/:resourceId', async (req, res) => {
1807
2201
  const resourceId = req.params.resourceId;
1808
2202
  const content = req.body?.content;
@@ -1812,7 +2206,7 @@ export const registerPiRuntimeRoutes = (app, {
1812
2206
  }
1813
2207
  const directory = resourceDirectoryFrom(req);
1814
2208
  try {
1815
- res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.update', { resourceId, content, ...(directory ? { directory } : {}) })));
2209
+ res.json(projectResources(await (await resourceDaemon(directory)).request('resources.update', { resourceId, content, ...(directory ? { directory } : {}) })));
1816
2210
  } catch (error) {
1817
2211
  writeDaemonError(res, error);
1818
2212
  }
@@ -1830,7 +2224,7 @@ export const registerPiRuntimeRoutes = (app, {
1830
2224
  }
1831
2225
  const directory = resourceDirectoryFrom(req);
1832
2226
  try {
1833
- res.status(201).json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.create', { name, description, content, location, ...(directory ? { directory } : {}) })));
2227
+ res.status(201).json(projectResources(await (await resourceDaemon(directory, location)).request('resources.prompts.create', { name, description, content, location, ...(directory ? { directory } : {}) })));
1834
2228
  } catch (error) {
1835
2229
  writeDaemonError(res, error);
1836
2230
  }
@@ -1860,7 +2254,7 @@ export const registerPiRuntimeRoutes = (app, {
1860
2254
  }
1861
2255
  const directory = resourceDirectoryFrom(req);
1862
2256
  try {
1863
- res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.update', {
2257
+ res.json(projectResources(await (await resourceDaemon(directory)).request('resources.prompts.update', {
1864
2258
  resourceId,
1865
2259
  ...(directory ? { directory } : {}),
1866
2260
  ...(name !== undefined ? { name } : {}),
@@ -1881,7 +2275,7 @@ export const registerPiRuntimeRoutes = (app, {
1881
2275
  }
1882
2276
  const directory = resourceDirectoryFrom(req);
1883
2277
  try {
1884
- res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.delete', { resourceId, ...(directory ? { directory } : {}) })));
2278
+ res.json(projectResources(await (await resourceDaemon(directory)).request('resources.prompts.delete', { resourceId, ...(directory ? { directory } : {}) })));
1885
2279
  } catch (error) {
1886
2280
  writeDaemonError(res, error);
1887
2281
  }
@@ -1921,8 +2315,20 @@ export const registerPiRuntimeRoutes = (app, {
1921
2315
  res.status(400).json({ error: { code: 'DAEMON_PROTOCOL_MISMATCH' } });
1922
2316
  return;
1923
2317
  }
2318
+ // Opaque resume position of every project daemon (merged-event-stream.js).
2319
+ // Only epoch-aware clients receive one, so it requires the same marker.
2320
+ const rawEventCursor = req.query.cursor;
2321
+ const eventCursor = rawEventCursor === undefined ? undefined : decodePiEventCursor(rawEventCursor);
2322
+ if (eventCursor === null) {
2323
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2324
+ return;
2325
+ }
2326
+ if (eventCursor !== undefined && !hasEpochCapability) {
2327
+ res.status(400).json({ error: { code: 'DAEMON_PROTOCOL_MISMATCH' } });
2328
+ return;
2329
+ }
1924
2330
  try {
1925
- const runtime = getDaemonRuntime(getPiSessionDaemonRuntime);
2331
+ const runtime = mainDaemon();
1926
2332
  if (typeof runtime.subscribe !== 'function') throw protocolMismatch();
1927
2333
  res.status(200).set({
1928
2334
  'Content-Type': 'text/event-stream',
@@ -1937,8 +2343,21 @@ export const registerPiRuntimeRoutes = (app, {
1937
2343
  openPiEventStream({
1938
2344
  req,
1939
2345
  res,
1940
- subscribe: (handlers) => runtime.subscribe({ sessionId, directory, fromSequence, streamEpoch, ...handlers }),
1941
- projectFrame: projectEventFrame,
2346
+ // Every live daemon's stream, merged. Frames arrive projected.
2347
+ subscribe: (handlers) => subscribeMergedPiEvents({
2348
+ pool: daemonPool,
2349
+ projectFrame: projectEventFrame,
2350
+ sessionId,
2351
+ directory,
2352
+ fromSequence,
2353
+ streamEpoch,
2354
+ cursor: eventCursor,
2355
+ ...(eventStreamRetryBaseMs !== undefined ? { retryBaseMs: eventStreamRetryBaseMs } : {}),
2356
+ // A sandbox daemon only reports on its own project's sessions.
2357
+ ...(sandboxManager?.sessionOnDaemon ? { ownsSession: sandboxManager.sessionOnDaemon } : {}),
2358
+ ...handlers,
2359
+ }),
2360
+ projectFrame: (event) => event,
1942
2361
  heartbeatMs: eventHeartbeatMs,
1943
2362
  maxBufferedBytes: eventStreamMaxBufferedBytes,
1944
2363
  registry: eventStreamRegistry,
@@ -1961,20 +2380,42 @@ export const registerPiRuntimeRoutes = (app, {
1961
2380
  }
1962
2381
 
1963
2382
  try {
1964
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('sessions.list', {
1965
- ...(typeof directory === 'string' ? { directory } : {}),
1966
- });
2383
+ const payload = typeof directory === 'string' ? { directory } : {};
2384
+ // The owner's rows are the list (JSONL is the authority). Other
2385
+ // daemons only fill in `live`/`inputState` the owner lacks: daemons
2386
+ // still draining this folder after a switch, or, for the all-sessions
2387
+ // list, every project daemon (the main daemon lists every folder but
2388
+ // only knows its own residents). A failed other daemon leaves those
2389
+ // rows unknown.
2390
+ // Stamped with the stream of the daemon asked, under the folder's
2391
+ // routed spelling, taken before the request.
2392
+ const listDirectory = await routeDirectoryFor(directory);
2393
+ const others = typeof directory === 'string'
2394
+ ? daemonPool.drainingFor(listDirectory)
2395
+ : daemonPool.live().filter((item) => item.key !== MAIN_DAEMON_KEY);
2396
+ const owner = daemonFor(listDirectory);
2397
+ res.locals.piServedStream = { stream: daemonPool.streamFor(listDirectory) };
2398
+ const [result, ...otherLists] = await Promise.all([
2399
+ owner.request('sessions.list', payload),
2400
+ ...others.map(({ key, runtime }) => runtime.request('sessions.list', payload)
2401
+ .then((value) => ({
2402
+ stream: publicDaemonStreamId(key),
2403
+ ...(isValidStreamEpoch(value?.streamEpoch) ? { streamEpoch: value.streamEpoch } : {}),
2404
+ items: projectSessionList(value?.sessions),
2405
+ }))
2406
+ .catch(() => ({ stream: publicDaemonStreamId(key), items: [] }))),
2407
+ ]);
1967
2408
  const archived = await archiveStore.read();
1968
2409
  const incompleteEngines = Array.isArray(result?.incompleteEngines)
1969
2410
  ? result.incompleteEngines.filter((engineId) => isValidEngineId(engineId))
1970
2411
  : [];
1971
- res.json({
2412
+ res.json(withStream({
1972
2413
  ...(typeof result?.streamEpoch === 'string' && result.streamEpoch ? { streamEpoch: result.streamEpoch } : {}),
1973
2414
  ...(incompleteEngines.length > 0 ? { incompleteEngines } : {}),
1974
- sessions: projectSessionList(result?.sessions).map((item) => archived[item.session.id]
2415
+ sessions: mergeOtherDaemonsLiveState(projectSessionList(result?.sessions), otherLists).map(withSandbox).map((item) => archived[item.session.id]
1975
2416
  ? { ...item, session: { ...item.session, archived: true, timeArchived: archived[item.session.id] } }
1976
2417
  : item),
1977
- });
2418
+ }, listDirectory, res));
1978
2419
  } catch (error) {
1979
2420
  writeDaemonError(res, error);
1980
2421
  }
@@ -1984,8 +2425,43 @@ export const registerPiRuntimeRoutes = (app, {
1984
2425
  // is not captured as a session id.
1985
2426
  app.get('/api/pi/sessions/pending-input', async (_req, res) => {
1986
2427
  try {
1987
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('sessions.pendingInput');
1988
- res.json(projectPendingInputList(result));
2428
+ // Fan out to every live daemon. One failed (or malformed) daemon
2429
+ // must not empty the others' lists; the response then says
2430
+ // `incomplete` so clients do not treat its absent rows as cleared.
2431
+ // Each daemon numbers its own stream: the top-level cursor is the
2432
+ // main daemon's (absent when it failed), and a project daemon's
2433
+ // entries carry `stream`, with its cursor under `streams[stream]`.
2434
+ const daemons = daemonPool.live();
2435
+ if (daemons.length === 0) requireDaemon(null);
2436
+ const settled = await Promise.allSettled(daemons.map(async ({ runtime }) => (
2437
+ projectPendingInputList(await runtime.request('sessions.pendingInput'))
2438
+ )));
2439
+ if (!settled.some((item) => item.status === 'fulfilled')) throw settled[0].reason;
2440
+ let mainList = null;
2441
+ const sessions = [];
2442
+ const streams = {};
2443
+ settled.forEach((item, index) => {
2444
+ if (item.status !== 'fulfilled') return;
2445
+ const { key } = daemons[index];
2446
+ if (key === MAIN_DAEMON_KEY) {
2447
+ mainList = item.value;
2448
+ sessions.push(...item.value.sessions);
2449
+ return;
2450
+ }
2451
+ const stream = publicDaemonStreamId(key);
2452
+ streams[stream] = {
2453
+ sequence: item.value.sequence,
2454
+ ...(item.value.streamEpoch ? { streamEpoch: item.value.streamEpoch } : {}),
2455
+ };
2456
+ for (const entry of item.value.sessions) sessions.push({ ...entry, stream });
2457
+ });
2458
+ res.json({
2459
+ sessions,
2460
+ ...(mainList ? { sequence: mainList.sequence } : {}),
2461
+ ...(mainList?.streamEpoch ? { streamEpoch: mainList.streamEpoch } : {}),
2462
+ ...(Object.keys(streams).length > 0 ? { streams } : {}),
2463
+ ...(settled.some((item) => item.status !== 'fulfilled') ? { incomplete: true } : {}),
2464
+ });
1989
2465
  } catch (error) {
1990
2466
  writeDaemonError(res, error);
1991
2467
  }
@@ -2003,7 +2479,7 @@ export const registerPiRuntimeRoutes = (app, {
2003
2479
  }
2004
2480
 
2005
2481
  try {
2006
- await getDaemonRuntime(getPiSessionDaemonRuntime).request('sessions.rename', {
2482
+ await daemonFor(await sessionDaemonDirectory(res, sandboxManager, sessionId, directory)).request('sessions.rename', {
2007
2483
  sessionId,
2008
2484
  title,
2009
2485
  ...(directory ? { directory } : {}),
@@ -2015,14 +2491,14 @@ export const registerPiRuntimeRoutes = (app, {
2015
2491
  });
2016
2492
 
2017
2493
  const sendSessionDetail = async (req, res) => {
2018
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.open');
2494
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.open', {}, sandboxManager);
2019
2495
  if (result === undefined) return;
2020
2496
  try {
2021
- const detail = projectSessionDetail(result);
2497
+ const detail = withSandbox(projectSessionDetail(result));
2022
2498
  const archived = await archiveStore.read();
2023
- res.json(archived[detail.session.id]
2499
+ res.json(withStream(archived[detail.session.id]
2024
2500
  ? { ...detail, session: { ...detail.session, archived: true, timeArchived: archived[detail.session.id] } }
2025
- : detail);
2501
+ : detail, sessionRouteDirectory(req, res), res));
2026
2502
  } catch (error) {
2027
2503
  writeDaemonError(res, error);
2028
2504
  }
@@ -2040,26 +2516,39 @@ export const registerPiRuntimeRoutes = (app, {
2040
2516
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2041
2517
  return;
2042
2518
  }
2043
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.messages', {
2519
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.messages', {
2044
2520
  ...(typeof before === 'string' ? { before } : {}),
2045
2521
  ...(limit !== undefined ? { limit } : {}),
2046
- });
2522
+ }, sandboxManager);
2047
2523
  if (result === undefined) return;
2048
2524
  try {
2049
- res.json(projectSessionDetail(result));
2525
+ res.json(withStream(projectSessionDetail(result), sessionRouteDirectory(req, res), res));
2050
2526
  } catch (error) {
2051
2527
  writeDaemonError(res, error);
2052
2528
  }
2053
2529
  });
2054
2530
 
2531
+ // Stop a draft session's runtime when its draft closes. Only a draft can be
2532
+ // discarded; any other session answers `{ discarded: false }` untouched.
2533
+ app.post('/api/pi/sessions/:sessionId/discard-draft', async (req, res) => {
2534
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.discardDraft', {}, sandboxManager);
2535
+ if (result === undefined) return;
2536
+ res.json({ discarded: result?.discarded === true });
2537
+ });
2538
+
2055
2539
  app.delete('/api/pi/sessions/:sessionId', async (req, res) => {
2056
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.delete');
2540
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.delete', {}, sandboxManager);
2057
2541
  if (result === undefined) return;
2058
2542
  try {
2059
2543
  await sessionShelfStore.remove(req.params.sessionId);
2060
2544
  } catch (error) {
2061
2545
  console.warn('[pi] could not remove a deleted session from the shelf', error?.code ?? error);
2062
2546
  }
2547
+ try {
2548
+ await onSessionDeleted(req.params.sessionId);
2549
+ } catch (error) {
2550
+ console.warn('[pi] could not drop a deleted session\'s plugin switches', error?.code ?? error);
2551
+ }
2063
2552
  res.status(204).end();
2064
2553
  });
2065
2554
 
@@ -2090,7 +2579,7 @@ export const registerPiRuntimeRoutes = (app, {
2090
2579
  try {
2091
2580
  // Same membership check as archive: shelf state is PiChamber metadata
2092
2581
  // for a session that exists, not a Pi session mutation.
2093
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request(
2582
+ const result = await (await daemonForClientDirectory(directory)).request(
2094
2583
  'sessions.list',
2095
2584
  directory ? { directory } : undefined,
2096
2585
  );
@@ -2125,7 +2614,7 @@ export const registerPiRuntimeRoutes = (app, {
2125
2614
  try {
2126
2615
  // Confirm membership without selecting/replacing the daemon's active
2127
2616
  // runtime: archive is PiChamber metadata, not a Pi session mutation.
2128
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request(
2617
+ const result = await (await daemonForClientDirectory(directory)).request(
2129
2618
  'sessions.list',
2130
2619
  directory ? { directory } : undefined,
2131
2620
  );
@@ -2152,7 +2641,7 @@ export const registerPiRuntimeRoutes = (app, {
2152
2641
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2153
2642
  return;
2154
2643
  }
2155
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'extensions.draft', { text, revision });
2644
+ const result = await requestSessionOperation(req, res, daemonPool, 'extensions.draft', { text, revision }, sandboxManager);
2156
2645
  if (result !== undefined) {
2157
2646
  res.status(204).end();
2158
2647
  }
@@ -2165,7 +2654,7 @@ export const registerPiRuntimeRoutes = (app, {
2165
2654
  return;
2166
2655
  }
2167
2656
  try {
2168
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('extensions.list', {
2657
+ const result = await (await daemonForClientDirectory(directory)).request('extensions.list', {
2169
2658
  ...(typeof directory === 'string' && directory.length > 0 ? { directory } : {}),
2170
2659
  });
2171
2660
  res.json(projectExtensionList(result));
@@ -2174,11 +2663,163 @@ export const registerPiRuntimeRoutes = (app, {
2174
2663
  }
2175
2664
  });
2176
2665
 
2666
+ // Extension config (`pi config`, `pi list`, `pi remove`). Toggles and
2667
+ // removal change what code runs on this server; the daemon re-resolves
2668
+ // every id and enforces trust (session-daemon/extension-config.js).
2669
+ // Like resources, a project's own view and choices go to the daemon that
2670
+ // runs the project, so a sandboxed project is read by its sandbox daemon
2671
+ // and the main daemon never resolves it. Global choices and package removal
2672
+ // write Pi's agent folder, which a sandbox cannot write, so they stay with
2673
+ // the main daemon.
2674
+ const extensionConfigDirectory = (value) => {
2675
+ if (value === undefined) return { ok: true };
2676
+ if (typeof value !== 'string' || value.length > 4096) return { ok: false };
2677
+ return { ok: true, ...(value.length > 0 ? { directory: value } : {}) };
2678
+ };
2679
+
2680
+ app.get('/api/pi/extensions/config', async (req, res) => {
2681
+ const target = extensionConfigDirectory(req.query?.directory);
2682
+ if (!target.ok) {
2683
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2684
+ return;
2685
+ }
2686
+ try {
2687
+ const daemon = target.directory ? await daemonForClientDirectory(target.directory) : mainDaemon();
2688
+ const result = await daemon.request('extensions.config.list', {
2689
+ ...(target.directory ? { directory: target.directory } : {}),
2690
+ });
2691
+ res.json(projectExtensionConfig(result));
2692
+ } catch (error) {
2693
+ writeDaemonError(res, error);
2694
+ }
2695
+ });
2696
+
2697
+ app.put('/api/pi/extensions/config/:id', async (req, res) => {
2698
+ const id = req.params.id;
2699
+ const body = req.body;
2700
+ let payload = null;
2701
+ if (typeof id === 'string' && EXTENSION_CONFIG_ID_PATTERN.test(id) && body && typeof body === 'object' && !Array.isArray(body)) {
2702
+ const keys = Object.keys(body);
2703
+ if (body.scope === 'global' && typeof body.enabled === 'boolean'
2704
+ && keys.every((key) => ['scope', 'enabled', 'directory'].includes(key))) {
2705
+ const target = extensionConfigDirectory(body.directory);
2706
+ if (target.ok) payload = { id, scope: 'global', enabled: body.enabled, ...(target.directory ? { directory: target.directory } : {}) };
2707
+ } else if (body.scope === 'project'
2708
+ && typeof body.directory === 'string' && body.directory.length > 0 && body.directory.length <= 4096) {
2709
+ // The override itself, or on/off for the daemon to turn into one.
2710
+ if (EXTENSION_CONFIG_OVERRIDE_STATES.has(body.state) && keys.every((key) => ['scope', 'state', 'directory'].includes(key))) {
2711
+ payload = { id, scope: 'project', state: body.state, directory: body.directory };
2712
+ } else if (typeof body.enabled === 'boolean' && keys.every((key) => ['scope', 'enabled', 'directory'].includes(key))) {
2713
+ payload = { id, scope: 'project', enabled: body.enabled, directory: body.directory };
2714
+ }
2715
+ }
2716
+ }
2717
+ if (!payload) {
2718
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2719
+ return;
2720
+ }
2721
+ try {
2722
+ const daemon = payload.scope === 'project' ? await daemonForClientDirectory(payload.directory) : mainDaemon();
2723
+ res.json(projectExtensionConfig(await daemon.request('extensions.config.set', payload)));
2724
+ } catch (error) {
2725
+ writeDaemonError(res, error);
2726
+ }
2727
+ });
2728
+
2729
+ // `pi install npm:<name>`: a bare npm name only, in user or project scope.
2730
+ app.post('/api/pi/extensions/packages', async (req, res) => {
2731
+ const body = req.body;
2732
+ let payload = null;
2733
+ if (body && typeof body === 'object' && !Array.isArray(body)
2734
+ && Object.keys(body).every((key) => ['name', 'scope', 'directory'].includes(key))
2735
+ && isNpmPackageName(body.name) && (body.scope === 'user' || body.scope === 'project')) {
2736
+ const target = extensionConfigDirectory(body.directory);
2737
+ if (target.ok && (body.scope === 'user' || target.directory)) {
2738
+ payload = { name: body.name, scope: body.scope, ...(target.directory ? { directory: target.directory } : {}) };
2739
+ }
2740
+ }
2741
+ if (!payload) {
2742
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2743
+ return;
2744
+ }
2745
+ try {
2746
+ const result = await mainDaemon()
2747
+ .request('extensions.packages.install', payload, { timeoutMs: PACKAGE_INSTALL_TIMEOUT_MS });
2748
+ res.json({
2749
+ ...projectExtensionConfig(result),
2750
+ ...(typeof result?.installedId === 'string' && EXTENSION_CONFIG_ID_PATTERN.test(result.installedId)
2751
+ ? { installedId: result.installedId }
2752
+ : {}),
2753
+ });
2754
+ } catch (error) {
2755
+ writeDaemonError(res, error);
2756
+ }
2757
+ });
2758
+
2759
+ // `pi update <source>` for one configured npm or git package.
2760
+ app.post('/api/pi/extensions/packages/:id/update', async (req, res) => {
2761
+ const id = req.params.id;
2762
+ const target = extensionConfigDirectory(req.query?.directory);
2763
+ if (typeof id !== 'string' || !EXTENSION_CONFIG_ID_PATTERN.test(id) || !target.ok) {
2764
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2765
+ return;
2766
+ }
2767
+ try {
2768
+ res.json(projectExtensionConfig(await mainDaemon().request('extensions.packages.update', {
2769
+ id,
2770
+ ...(target.directory ? { directory: target.directory } : {}),
2771
+ }, { timeoutMs: PACKAGE_INSTALL_TIMEOUT_MS })));
2772
+ } catch (error) {
2773
+ writeDaemonError(res, error);
2774
+ }
2775
+ });
2776
+
2777
+ app.delete('/api/pi/extensions/packages/:id', async (req, res) => {
2778
+ const id = req.params.id;
2779
+ const target = extensionConfigDirectory(req.query?.directory);
2780
+ if (typeof id !== 'string' || !EXTENSION_CONFIG_ID_PATTERN.test(id) || !target.ok) {
2781
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2782
+ return;
2783
+ }
2784
+ try {
2785
+ res.json(projectExtensionConfig(await mainDaemon().request('extensions.packages.remove', {
2786
+ id,
2787
+ ...(target.directory ? { directory: target.directory } : {}),
2788
+ })));
2789
+ } catch (error) {
2790
+ writeDaemonError(res, error);
2791
+ }
2792
+ });
2793
+
2794
+ // Pi's colours for extension surfaces drawn with the given terminal
2795
+ // colours (session-daemon/extension-palette.js).
2796
+ app.post('/api/pi/extensions/palette', async (req, res) => {
2797
+ const terminal = projectTerminalColors(req.body?.terminal);
2798
+ if (!terminal) {
2799
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2800
+ return;
2801
+ }
2802
+ try {
2803
+ const result = await mainDaemon().request('extensions.palette', { terminal });
2804
+ const palette = projectExtensionPalette(result);
2805
+ if (!palette) {
2806
+ res.status(502).json({ error: { code: 'MALFORMED_DAEMON_RESPONSE' } });
2807
+ return;
2808
+ }
2809
+ res.json(palette);
2810
+ } catch (error) {
2811
+ writeDaemonError(res, error);
2812
+ }
2813
+ });
2814
+
2177
2815
  app.post('/api/pi/extensions/respond', async (req, res) => {
2178
2816
  const body = req.body;
2179
2817
  if (!body || typeof body !== 'object' || Array.isArray(body)
2180
2818
  || typeof body.requestId !== 'string' || body.requestId.length === 0
2181
- || (body.directory !== undefined && typeof body.directory !== 'string')) {
2819
+ || (body.directory !== undefined && typeof body.directory !== 'string')
2820
+ // A `choose` answer: the choice id travels as `value`, with an optional note.
2821
+ || (body.note !== undefined && (typeof body.note !== 'string' || body.note.length > MAX_EXTENSION_CHOICE_NOTE_CHARS
2822
+ || typeof body.value !== 'string' || body.value.length > MAX_EXTENSION_CHOICE_ID_CHARS))) {
2182
2823
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2183
2824
  return;
2184
2825
  }
@@ -2198,14 +2839,28 @@ export const registerPiRuntimeRoutes = (app, {
2198
2839
  }
2199
2840
  }
2200
2841
  try {
2201
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('extensions.respond', {
2842
+ const respondPayload = {
2202
2843
  requestId: body.requestId,
2203
2844
  ...(typeof body.directory === 'string' && body.directory.length > 0 ? { directory: body.directory } : {}),
2204
2845
  ...(body.cancelled === true ? { cancelled: true } : {}),
2205
2846
  ...(body.confirmed === true ? { confirmed: true } : {}),
2206
2847
  ...(typeof body.value === 'string' ? { value: body.value } : {}),
2848
+ ...(typeof body.note === 'string' ? { note: body.note } : {}),
2207
2849
  ...(values ? { values } : {}),
2208
- });
2850
+ };
2851
+ // A dialog from a session still finishing its turn in a daemon that
2852
+ // drains this folder is answered there, and those daemons are asked
2853
+ // first: the folder's new owner may be a sandbox that is not running
2854
+ // (or cannot start), and it holds no dialog of that session. Request
2855
+ // ids are unique, so asking each in turn cannot answer the wrong
2856
+ // dialog.
2857
+ const respondDirectory = await routeDirectoryFor(body.directory);
2858
+ let result = null;
2859
+ for (const { runtime } of typeof respondDirectory === 'string' ? daemonPool.drainingFor(respondDirectory) : []) {
2860
+ result = await runtime.request('extensions.respond', respondPayload).catch(() => null);
2861
+ if (result?.resolved === true) break;
2862
+ }
2863
+ if (result?.resolved !== true) result = await daemonFor(respondDirectory).request('extensions.respond', respondPayload);
2209
2864
  if (!result || typeof result !== 'object' || result.resolved !== true) {
2210
2865
  res.status(404).json({ error: { code: 'EXTENSION_DIALOG_NOT_PENDING' } });
2211
2866
  return;
@@ -2216,6 +2871,40 @@ export const registerPiRuntimeRoutes = (app, {
2216
2871
  }
2217
2872
  });
2218
2873
 
2874
+ // A click on a composer control an extension declared. The daemon picks the
2875
+ // command from its own copy of the control; the browser only names the
2876
+ // control and the value it wants.
2877
+ app.post('/api/pi/extensions/control', async (req, res) => {
2878
+ const body = req.body;
2879
+ if (!body || typeof body !== 'object' || Array.isArray(body)
2880
+ || typeof body.sessionId !== 'string' || body.sessionId.length === 0 || body.sessionId.length > 256
2881
+ || typeof body.id !== 'string' || body.id.length === 0 || body.id.length > 64
2882
+ || (body.value !== undefined && typeof body.value !== 'boolean' && (typeof body.value !== 'string' || body.value.length > 64))
2883
+ || (body.clientId !== undefined && (typeof body.clientId !== 'string' || body.clientId.length > 128))
2884
+ || (body.directory !== undefined && (typeof body.directory !== 'string' || body.directory.length > 4096))) {
2885
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2886
+ return;
2887
+ }
2888
+ try {
2889
+ // Routed like any session operation: by the transcript's folder, or
2890
+ // for a draft (nothing on disk yet) by the folder the client names.
2891
+ // A control runs a command, so a session waiting to switch daemons
2892
+ // refuses it until it has moved.
2893
+ drainingSessionRuntime(res, sandboxManager, body.sessionId, 'extensions.control');
2894
+ const directory = typeof body.directory === 'string' && body.directory.length > 0 ? body.directory : undefined;
2895
+ const routeDirectory = await sessionDaemonDirectory(res, sandboxManager, body.sessionId, directory);
2896
+ const result = await daemonFor(routeDirectory).request('extensions.control', {
2897
+ sessionId: body.sessionId,
2898
+ id: body.id,
2899
+ ...(body.value !== undefined ? { value: body.value } : {}),
2900
+ ...(typeof body.clientId === 'string' && body.clientId.length > 0 ? { clientId: body.clientId } : {}),
2901
+ });
2902
+ res.json({ ran: result?.ran === true });
2903
+ } catch (error) {
2904
+ writeDaemonError(res, error);
2905
+ }
2906
+ });
2907
+
2219
2908
  // `ctx.ui.custom()` surfaces: keys, the sender's viewport, Close, picking a
2220
2909
  // panel in a tab stack, and a full-frame refresh after a missed patch. A surface that already closed
2221
2910
  // answers 404 so the browser drops it without retrying.
@@ -2255,13 +2944,13 @@ export const registerPiRuntimeRoutes = (app, {
2255
2944
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2256
2945
  return;
2257
2946
  }
2258
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, command, {
2947
+ const result = await requestSessionOperation(req, res, daemonPool, command, {
2259
2948
  ...(surfaceId ? { surfaceId } : {}),
2260
2949
  ...(clientId ? { clientId } : {}),
2261
2950
  ...(viewport ? { viewport } : {}),
2262
2951
  ...(items ? { items } : {}),
2263
2952
  ...(body.claim === true ? { claim: true } : {}),
2264
- });
2953
+ }, sandboxManager);
2265
2954
  if (result === undefined) return;
2266
2955
  const ok = result && typeof result === 'object'
2267
2956
  && (result.accepted === true || result.closed === true || result.focused === true || result.refreshed === true);
@@ -2273,23 +2962,23 @@ export const registerPiRuntimeRoutes = (app, {
2273
2962
  });
2274
2963
 
2275
2964
  app.get('/api/pi/sessions/:sessionId/tree', async (req, res) => {
2276
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.tree');
2965
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.tree', {}, sandboxManager);
2277
2966
  if (result !== undefined) res.json(projectSessionTree(result));
2278
2967
  });
2279
2968
 
2280
2969
  app.post('/api/pi/sessions/:sessionId/navigate', async (req, res) => {
2281
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.navigate', { messageId: req.body?.messageId });
2970
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.navigate', { messageId: req.body?.messageId }, sandboxManager);
2282
2971
  if (result === undefined) return;
2283
2972
  const detail = projectSessionDetail(result);
2284
2973
  const navigation = sanitizeNavigation(result.navigation);
2285
2974
  if (navigation) detail.navigation = navigation;
2286
- res.json(detail);
2975
+ res.json(withStream(detail, sessionRouteDirectory(req, res), res));
2287
2976
  });
2288
2977
 
2289
2978
  for (const [suffix, command] of [['fork', 'sessions.fork'], ['clone', 'sessions.clone']]) {
2290
2979
  app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
2291
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, command, req.body && typeof req.body === 'object' ? req.body : {});
2292
- if (result !== undefined) res.status(201).json(projectSessionDetail(result));
2980
+ const result = await requestSessionOperation(req, res, daemonPool, command, req.body && typeof req.body === 'object' ? req.body : {}, sandboxManager);
2981
+ if (result !== undefined) res.status(201).json(withStream(withSandbox(projectSessionDetail(result)), sessionRouteDirectory(req, res), res));
2293
2982
  });
2294
2983
  }
2295
2984
 
@@ -2320,7 +3009,7 @@ export const registerPiRuntimeRoutes = (app, {
2320
3009
  writeDaemonError(res, error);
2321
3010
  return;
2322
3011
  }
2323
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, command, payload);
3012
+ const result = await requestSessionOperation(req, res, daemonPool, command, payload, sandboxManager);
2324
3013
  if (result !== undefined) {
2325
3014
  if (!result || result.accepted !== true || typeof result.messageId !== 'string') {
2326
3015
  writeDaemonError(res, protocolMismatch());
@@ -2359,11 +3048,21 @@ export const registerPiRuntimeRoutes = (app, {
2359
3048
  return;
2360
3049
  }
2361
3050
  try {
2362
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('sessions.sendReceipt', {
3051
+ const directory = typeof req.query?.directory === 'string' && req.query.directory.length > 0
3052
+ ? req.query.directory
3053
+ : (typeof body.directory === 'string' && body.directory.length > 0 ? body.directory : undefined);
3054
+ // A session still finishing its turn in a draining daemon has its
3055
+ // receipts there; one that just moved may still name the old epoch.
3056
+ const runtime = drainingSessionRuntime(res, sandboxManager, sessionId, 'sessions.sendReceipt')
3057
+ ?? daemonFor(await sessionDaemonDirectory(res, sandboxManager, sessionId, directory));
3058
+ const receiptEpoch = streamEpoch !== undefined && !res.locals?.piDrainingStream && sandboxManager?.sendEpochFor
3059
+ ? await sandboxManager.sendEpochFor(sessionId, streamEpoch, runtime)
3060
+ : streamEpoch;
3061
+ const result = await runtime.request('sessions.sendReceipt', {
2363
3062
  kind,
2364
3063
  sessionId,
2365
3064
  operationId,
2366
- ...(streamEpoch !== undefined ? { streamEpoch } : {}),
3065
+ ...(receiptEpoch !== undefined ? { streamEpoch: receiptEpoch } : {}),
2367
3066
  });
2368
3067
  if (!result || typeof result !== 'object' || !['accepted', 'pending', 'expired', 'unknown'].includes(result.status)) {
2369
3068
  throw protocolMismatch();
@@ -2379,7 +3078,7 @@ export const registerPiRuntimeRoutes = (app, {
2379
3078
 
2380
3079
  for (const [suffix, command] of [['abort', 'sessions.abort'], ['model', 'sessions.setModel'], ['thinking', 'sessions.setThinking']]) {
2381
3080
  app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
2382
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, command, req.body && typeof req.body === 'object' ? req.body : {});
3081
+ const result = await requestSessionOperation(req, res, daemonPool, command, req.body && typeof req.body === 'object' ? req.body : {}, sandboxManager);
2383
3082
  if (result !== undefined) res.status(204).end();
2384
3083
  });
2385
3084
  }
@@ -2393,10 +3092,12 @@ export const registerPiRuntimeRoutes = (app, {
2393
3092
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2394
3093
  return;
2395
3094
  }
2396
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.bash', {
3095
+ const clientId = typeof body.clientId === 'string' && body.clientId.length > 0 && body.clientId.length <= 128 ? body.clientId : undefined;
3096
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.bash', {
2397
3097
  command: body.command,
2398
3098
  ...(body.excludeFromContext === true ? { excludeFromContext: true } : {}),
2399
- });
3099
+ ...(clientId ? { clientId } : {}),
3100
+ }, sandboxManager);
2400
3101
  if (result === undefined) return;
2401
3102
  if (!result || result.accepted !== true || typeof result.id !== 'string') {
2402
3103
  writeDaemonError(res, protocolMismatch());
@@ -2407,12 +3108,12 @@ export const registerPiRuntimeRoutes = (app, {
2407
3108
  });
2408
3109
 
2409
3110
  app.post('/api/pi/sessions/:sessionId/bash/abort', async (req, res) => {
2410
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.abortBash', {});
3111
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.abortBash', {}, sandboxManager);
2411
3112
  if (result !== undefined) res.status(204).end();
2412
3113
  });
2413
3114
 
2414
3115
  app.post('/api/pi/sessions/:sessionId/compact', async (req, res) => {
2415
- const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.compact', req.body && typeof req.body === 'object' ? req.body : {});
3116
+ const result = await requestSessionOperation(req, res, daemonPool, 'sessions.compact', req.body && typeof req.body === 'object' ? req.body : {}, sandboxManager);
2416
3117
  if (result === undefined) return;
2417
3118
  if (!result || result.accepted !== true) {
2418
3119
  writeDaemonError(res, protocolMismatch());
@@ -2474,12 +3175,14 @@ export const registerPiRuntimeRoutes = (app, {
2474
3175
  }
2475
3176
 
2476
3177
  try {
2477
- const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('sessions.create', { ...input, cwd });
3178
+ const routeCwd = await routeDirectoryFor(cwd);
3179
+ res.locals.piServedStream = { stream: daemonPool.streamFor(routeCwd) };
3180
+ const result = await daemonFor(routeCwd).request('sessions.create', { ...input, cwd });
2478
3181
  // A fresh session is not necessarily empty: extensions may append
2479
3182
  // entries or messages from `session_start`. Project it exactly like a
2480
3183
  // session read so those items, the stream epoch, and extension UI state
2481
3184
  // reach the client instead of failing creation.
2482
- res.status(201).json(projectSessionDetail(result));
3185
+ res.status(201).json(withStream(withSandbox(projectSessionDetail(result)), routeCwd, res));
2483
3186
  } catch (error) {
2484
3187
  writeDaemonError(res, error);
2485
3188
  }