@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
@@ -5,7 +5,7 @@ import { createReadStream, existsSync, readFileSync } from 'node:fs';
5
5
  import { homedir } from 'node:os';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { createInterface } from 'node:readline';
8
- import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
8
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
9
  import { hasTrustRequiringProjectResources } from '@earendil-works/pi-coding-agent';
10
10
  import { StringDecoder } from 'node:string_decoder';
11
11
  import {
@@ -13,6 +13,7 @@ import {
13
13
  createAgentSessionRuntime,
14
14
  createAgentSessionServices,
15
15
  getAgentDir,
16
+ parseSessionEntries,
16
17
  ProjectTrustStore,
17
18
  SessionManager,
18
19
  SettingsManager,
@@ -32,6 +33,7 @@ import {
32
33
  isDisplayedExtensionEntryType,
33
34
  isIddExtensionEntry,
34
35
  } from './extension-bridge.js';
36
+ import { commandName, createComposerControlsExtension, isComposerControlsExtensionPath } from './extension-controls.js';
35
37
  import { resolveExtensionName } from './extension-name.js';
36
38
  import { createExtensionTheme } from './extension-theme.js';
37
39
  import {
@@ -41,6 +43,9 @@ import {
41
43
  import { createExtensionMessageRenderer } from './extension-message-render.js';
42
44
  import { normalizeOpenRequestUrl, resolveOpenRequestSession } from './open-request.js';
43
45
  import { getBuiltinExtensionFactories } from './builtin-extensions.js';
46
+ import { createExtensionConfig } from './extension-config.js';
47
+ import { describeRuntimeReplacements } from './extension-replacements.js';
48
+ import { createPluginHost } from './plugin-host.js';
44
49
  import {
45
50
  SESSION_DAEMON_DEFAULT_MESSAGE_PAGE_LIMIT,
46
51
  SESSION_DAEMON_MAX_FRAME_BYTES as MAX_FRAME_BYTES,
@@ -71,6 +76,7 @@ import {
71
76
  validatePiSessionJsonlFile,
72
77
  } from './session-jsonl.js';
73
78
  import { resolvePiChamberDataDir } from '../../pichamber-data-dir.js';
79
+ import { createTrustAskReader } from '../sandbox/trust-ask.js';
74
80
  import {
75
81
  createSessionEngineRegistry,
76
82
  logSessionEngineError,
@@ -78,6 +84,9 @@ import {
78
84
  import { createSessionEngineRouter } from './session-engine-router.js';
79
85
  import { createPendingInputIndex } from './pending-input.js';
80
86
  import { createExtensionCustomHost } from './extension-custom-host.js';
87
+ import { resolveExtensionMode } from './extension-ui-mode.js';
88
+ import { createPichamberUi } from './pichamber-ui.js';
89
+ import { createExtensionPaletteResolver, isTerminalColors } from './extension-palette.js';
81
90
 
82
91
  const textFromContent = (content) => (
83
92
  Array.isArray(content)
@@ -87,18 +96,28 @@ const textFromContent = (content) => (
87
96
 
88
97
  // Marker so pi extensions can detect PiChamber without an extra dependency.
89
98
  // Extensions should use optional detection, e.g.:
90
- // const chamber = (globalThis as any).__PICHAMBER__;
99
+ // const marker = (globalThis as any).__PICHAMBER__;
91
100
  // or `process.env.PICHAMBER === "1"`. The object is frozen and versioned.
101
+ // `globalThis.pichamber` holds PiChamber's own dialog calls (`pichamber.ui`),
102
+ // kept off Pi's `ctx.ui` so a method Pi adds later cannot be shadowed.
92
103
  if (!globalThis.__PICHAMBER__) {
93
104
  try {
94
105
  globalThis.__PICHAMBER__ = Object.freeze({
95
106
  version: 1,
96
107
  protocol: 'pichamber-extension-ui',
97
- // Matches `ctx.mode` (extension-bridge.js).
98
- mode: 'tui',
108
+ // The `ctx.mode` new sessions get (extension-ui-mode.js). A session
109
+ // keeps the mode it started with; its `ctx.mode` is authoritative.
110
+ get mode() {
111
+ return resolveExtensionMode({ dataDir: resolvePiChamberDataDir() });
112
+ },
99
113
  });
100
114
  } catch {}
101
115
  }
116
+ if (!globalThis.pichamber) {
117
+ try {
118
+ globalThis.pichamber = Object.freeze({ version: 1, ui: createPichamberUi() });
119
+ } catch {}
120
+ }
102
121
  if (!process.env.PICHAMBER) {
103
122
  try { process.env.PICHAMBER = '1'; } catch {}
104
123
  }
@@ -146,11 +165,20 @@ export function isLocalSessionDaemonEndpoint(endpoint, platform = process.platfo
146
165
  // factory to daemon socket state.
147
166
  export async function createPiSessionRuntime({ cwd, agentDir = getAgentDir(), sessionFile }, hooks) {
148
167
  const createRuntime = async ({ cwd: runtimeCwd, agentDir: runtimeAgentDir, sessionManager, sessionStartEvent }) => {
168
+ // Lets the daemon know a session's id before Pi starts it, so what its
169
+ // extensions publish at `session_start` can already be attributed.
170
+ hooks?.beforeSession?.(sessionManager);
149
171
  const services = await createAgentSessionServices({
150
172
  cwd: runtimeCwd,
151
173
  agentDir: runtimeAgentDir,
152
174
  resourceLoaderOptions: {
153
- extensionFactories: getBuiltinExtensionFactories(),
175
+ // PiChamber plugins load after Pi's built-ins (plugin-host.js); the
176
+ // composer-controls listener loads last (extension-controls.js).
177
+ extensionFactories: [
178
+ ...getBuiltinExtensionFactories(),
179
+ ...(hooks?.pluginExtensionFactories?.() ?? []),
180
+ ...(hooks?.internalExtensionFactories?.() ?? []),
181
+ ],
154
182
  },
155
183
  });
156
184
 
@@ -185,6 +213,12 @@ export function createSessionDaemon({
185
213
  credential,
186
214
  cwd,
187
215
  agentDir = getAgentDir(),
216
+ // Session leases key on the real Pi agent folder. A sandbox daemon runs on
217
+ // a shadow agent folder, so it passes the real one here; leases then match
218
+ // the main daemon's for the same session.
219
+ leaseAgentDir = agentDir,
220
+ // A sandbox daemon's own lease folder (session-lease.js); unset otherwise.
221
+ leaseScope,
188
222
  createRuntime: injectCreateRuntime,
189
223
  createServices: injectCreateServices = createAgentSessionServices,
190
224
  healthMetadata = {},
@@ -198,6 +232,10 @@ export function createSessionDaemon({
198
232
  onShutdown,
199
233
  idleTimeoutMs = 5 * 60 * 1_000,
200
234
  sendOperationTtlMs = 10 * 60 * 1_000,
235
+ // The `ctx.mode` each new binding reports; the "Extension interface" setting.
236
+ resolveExtensionMode: resolveBindingExtensionMode = () => resolveExtensionMode({ dataDir: resolvePiChamberDataDir() }),
237
+ // Pi's colours for extension surfaces in a given terminal palette (extension-palette.js).
238
+ resolveExtensionPalette = createExtensionPaletteResolver(),
201
239
  sessionListCache = createPiSessionJsonlListCache(),
202
240
  listSessions = ({ cwd: sessionCwd, agentDir: sessionAgentDir = agentDir }) => listPiSessionJsonlDirectory({
203
241
  cwd: sessionCwd,
@@ -210,6 +248,12 @@ export function createSessionDaemon({
210
248
  { projectTrusted },
211
249
  ),
212
250
  createTrustStore = (settingsAgentDir = agentDir) => new ProjectTrustStore(settingsAgentDir),
251
+ // Folders whose trust a server reset to "ask" when their sandbox was
252
+ // turned off (../sandbox/trust-ask.js): never trusted automatically.
253
+ isTrustAskDirectory = createTrustAskReader({ dataDir: resolvePiChamberDataDir() }),
254
+ // Folders a sandbox daemon owns (../sandbox/sandboxed-folders.js). Only
255
+ // the main daemon is given the check: it never starts a runtime in one.
256
+ isSandboxedDirectory = () => false,
213
257
  modelConfigStore = createPiModelConfigStore({ file: join(agentDir, 'models.json') }),
214
258
  renamePersistedSession = ({ sessionFile, title, cwd: sessionCwd = cwd, agentDir: sessionAgentDir = agentDir }) => {
215
259
  const manager = SessionManager.open(sessionFile, getPiSessionDirectory({ cwd: sessionCwd, agentDir: sessionAgentDir }), sessionCwd);
@@ -227,6 +271,8 @@ export function createSessionDaemon({
227
271
  extensionToolRenderer: injectExtensionToolRenderer,
228
272
  engines = [],
229
273
  extensionMessageRenderer: injectExtensionMessageRenderer,
274
+ // Configured only by the server through `plugins.configure`.
275
+ pluginHost = createPluginHost(),
230
276
  } = {}) {
231
277
  if (!isLocalSessionDaemonEndpoint(endpoint, platform)) {
232
278
  throw new SessionDaemonProtocolError('INVALID_ENDPOINT', 'The session daemon endpoint must be local.');
@@ -270,27 +316,60 @@ export function createSessionDaemon({
270
316
  // Exclusive cross-daemon ownership of one resident session. The session
271
317
  // stays visible in listings; contention reports SESSION_IN_USE instead of
272
318
  // pretending the session is absent or idle.
273
- const acquireResidentLease = async ({ cwd: leaseCwd, sessionId }) => {
319
+ // Lease changes for one session run one at a time, so the retry of a
320
+ // failed release (`sessions.release`) cannot remove a lease that an
321
+ // activation of the same session took in the meantime.
322
+ const leaseChains = new Map();
323
+ const withSessionLease = (sessionId, work) => {
324
+ const run = (leaseChains.get(sessionId) ?? Promise.resolve()).then(work);
325
+ const tail = run.catch(() => {});
326
+ leaseChains.set(sessionId, tail);
327
+ void tail.then(() => {
328
+ if (leaseChains.get(sessionId) === tail) leaseChains.delete(sessionId);
329
+ });
330
+ return run;
331
+ };
332
+ const acquireResidentLease = ({ cwd: leaseCwd, sessionId }) => {
274
333
  const owner = leaseOwner();
275
- if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return;
334
+ if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return Promise.resolve();
335
+ return withSessionLease(sessionId, () => acquireLeaseNow({ owner, leaseCwd, sessionId }));
336
+ };
337
+ const acquireLeaseNow = async ({ owner, leaseCwd, sessionId }) => {
276
338
  let result;
277
339
  try {
278
- result = await acquireSessionLease({ agentDir, cwd: leaseCwd, sessionId, owner });
340
+ result = await acquireSessionLease({ agentDir: leaseAgentDir, cwd: leaseCwd, sessionId, owner, scope: leaseScope });
279
341
  } catch (error) {
280
342
  throw new SessionDaemonProtocolError('SESSION_LEASE_UNAVAILABLE', 'The session ownership check is temporarily unavailable.');
281
343
  }
282
344
  if (!result.acquired) {
283
345
  throw new SessionDaemonProtocolError('SESSION_IN_USE', 'Another PiChamber instance is currently using this session.');
284
346
  }
347
+ unreleasedLeases.delete(sessionId);
285
348
  };
286
- const releaseResidentLease = async ({ cwd: leaseCwd, sessionId }) => {
349
+ // Leases this daemon still holds for sessions it no longer runs, because
350
+ // releasing them failed. While this daemon lives, such a lease keeps every
351
+ // other daemon out of the session, so `sessions.release` retries it and
352
+ // reports the session as pending until it is gone.
353
+ const unreleasedLeases = new Map();
354
+ // `onlyUnreleased` is the retry: it does nothing (`skipped`) when the
355
+ // lease is no longer one left over from a failed release.
356
+ const releaseResidentLease = ({ cwd: leaseCwd, sessionId }, { onlyUnreleased = false } = {}) => {
287
357
  const owner = leaseOwner();
288
- if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return { released: false };
358
+ if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return Promise.resolve({ released: false });
359
+ return withSessionLease(sessionId, () => {
360
+ if (onlyUnreleased && !unreleasedLeases.has(sessionId)) return { released: false, skipped: true };
361
+ return releaseLeaseNow({ owner, leaseCwd, sessionId });
362
+ });
363
+ };
364
+ const releaseLeaseNow = async ({ owner, leaseCwd, sessionId }) => {
289
365
  try {
290
- return await releaseSessionLease({ agentDir, cwd: leaseCwd, sessionId, owner });
366
+ const result = await releaseSessionLease({ agentDir: leaseAgentDir, cwd: leaseCwd, sessionId, owner, scope: leaseScope });
367
+ unreleasedLeases.delete(sessionId);
368
+ return result;
291
369
  } catch {
292
370
  // Lease release is best-effort; a stale lease is reclaimable by the
293
371
  // next owner once this daemon pid is dead.
372
+ unreleasedLeases.set(sessionId, { cwd: leaseCwd, sessionId });
294
373
  return { released: false };
295
374
  }
296
375
  };
@@ -316,6 +395,19 @@ export function createSessionDaemon({
316
395
  let stopping = false;
317
396
  const knownDirectories = new Set([cwd]);
318
397
  let activeDirectory = cwd;
398
+ // The folder a request without one is answered for. While the active
399
+ // folder (or the startup folder) belongs to a sandbox daemon, this daemon
400
+ // answers from a folder outside every sandbox instead: starting a runtime
401
+ // in the project would load its extensions outside its sandbox.
402
+ const neutralDirectory = () => [cwd, agentDir].find((directory) => typeof directory === 'string'
403
+ && directory.length > 0 && !isSandboxedDirectory(directory)) ?? agentDir;
404
+ const outsideSandbox = (directory) => (isSandboxedDirectory(directory) ? neutralDirectory() : directory);
405
+ const defaultDirectory = () => outsideSandbox(activeDirectory || cwd);
406
+ const refuseSandboxedRuntime = (directory) => {
407
+ if (isSandboxedDirectory(directory)) {
408
+ throw new SessionDaemonProtocolError('DIRECTORY_SANDBOXED', 'The folder belongs to a sandboxed project.');
409
+ }
410
+ };
319
411
  const clients = new Set();
320
412
  // A reconnect replays only a contiguous retained suffix; otherwise it receives
321
413
  // a new authoritative snapshot before later events can arrive. The suffix is
@@ -453,6 +545,10 @@ export function createSessionDaemon({
453
545
  if (!hasPendingUserStarts(buckets)) pendingUserStartsBySession.delete(sessionId);
454
546
  };
455
547
  const shutdownRequestedBySession = new Set();
548
+ // Sessions in folders the server asked this daemon to release (#247):
549
+ // the session moves to another daemon, so it is disposed at its next idle
550
+ // edge instead of after the idle timeout.
551
+ const releaseRequestedBySession = new Set();
456
552
  const disposingSessionIds = new Set();
457
553
  const streamingRedactionBuffers = new Map();
458
554
  const loginAttempts = new Map();
@@ -464,7 +560,7 @@ export function createSessionDaemon({
464
560
 
465
561
  const skillReadClassifierFor = (activeRuntime, directory) => {
466
562
  if (!activeRuntime || typeof activeRuntime !== 'object') return undefined;
467
- const classifierCwd = activeRuntime.cwd || directory || activeDirectory || cwd;
563
+ const classifierCwd = activeRuntime.cwd || directory || defaultDirectory();
468
564
  const cached = skillReadClassifierByRuntime.get(activeRuntime);
469
565
  if (cached?.cwd === classifierCwd) return cached.classifier;
470
566
  const loader = activeRuntime.services?.resourceLoader;
@@ -487,12 +583,36 @@ export function createSessionDaemon({
487
583
  const getToolInput = (sessionId, toolCallId) => toolInputBySession.get(sessionId)?.get(toolCallId);
488
584
 
489
585
  const forgetToolInput = (sessionId, toolCallId) => {
586
+ forgetToolPartial(sessionId, toolCallId);
490
587
  const inputs = toolInputBySession.get(sessionId);
491
588
  if (!inputs) return;
492
589
  inputs.delete(toolCallId);
493
590
  if (inputs.size === 0) toolInputBySession.delete(sessionId);
494
591
  };
495
592
 
593
+ // The latest partial result of each running tool. A client that opens the
594
+ // session mid-call gets it on the running part, as live clients did from
595
+ // `session.tool.update`: a tool that reports once and then waits (a Visuals
596
+ // question showing its options) would otherwise stay blank there. Dropped
597
+ // when the tool ends, the run settles, or the session closes.
598
+ const toolPartialBySession = new Map();
599
+
600
+ const rememberToolPartial = (sessionId, toolCallId, projected) => {
601
+ if (projected.output === undefined && projected.metadata === undefined) return;
602
+ const partials = toolPartialBySession.get(sessionId) ?? new Map();
603
+ partials.set(toolCallId, projected);
604
+ toolPartialBySession.set(sessionId, partials);
605
+ };
606
+
607
+ const getToolPartial = (sessionId, toolCallId) => toolPartialBySession.get(sessionId)?.get(toolCallId);
608
+
609
+ const forgetToolPartial = (sessionId, toolCallId) => {
610
+ const partials = toolPartialBySession.get(sessionId);
611
+ if (!partials) return;
612
+ partials.delete(toolCallId);
613
+ if (partials.size === 0) toolPartialBySession.delete(sessionId);
614
+ };
615
+
496
616
  const mergeToolPresentationMetadata = (metadata, activeRuntime, directory, toolName, args) => {
497
617
  const skill = skillReadClassifierFor(activeRuntime, directory)?.(toolName, args);
498
618
  if (!skill) return metadata;
@@ -537,13 +657,13 @@ export function createSessionDaemon({
537
657
  // so skills (and other resources) never trigger the trust popup for known dirs.
538
658
  try {
539
659
  const trustStore = createTrustStore(agentDir);
540
- if (trustStore.get(validated) === null && hasTrustRequiringProjectResources(validated)) {
660
+ if (trustStore.get(validated) === null && !isTrustAskDirectory(validated) && hasTrustRequiringProjectResources(validated)) {
541
661
  trustStore.set(validated, true);
542
662
  }
543
663
  } catch {}
544
664
  return validated;
545
665
  }
546
- return activeDirectory || cwd;
666
+ return defaultDirectory();
547
667
  };
548
668
 
549
669
  // Listing or deleting a folder's sessions reads Pi's session store, not the
@@ -552,7 +672,7 @@ export function createSessionDaemon({
552
672
  // still be a directory, and opening or creating a session keeps the strict
553
673
  // check in `resolveDirectory`.
554
674
  const resolveSessionStoreDirectory = async (requested) => {
555
- if (typeof requested !== 'string' || requested.trim().length === 0) return activeDirectory || cwd;
675
+ if (typeof requested !== 'string' || requested.trim().length === 0) return defaultDirectory();
556
676
  const trimmed = requested.trim();
557
677
  const normalized = trimmed === '~' ? homedir() : trimmed;
558
678
  if (!isAbsolute(normalized)) {
@@ -591,26 +711,35 @@ export function createSessionDaemon({
591
711
  // no watchers, intervals, or listeners), so dropping the reference lets GC
592
712
  // reclaim it. Retaining them only grew the daemon and fanned provider
593
713
  // refreshes out to orphan ModelRuntimes whose catalogs are never read.
594
- const createFreshPromptServices = async (targetCwd = activeDirectory || cwd) => injectCreateServices({
595
- cwd: targetCwd,
714
+ const createFreshPromptServices = async (targetCwd = defaultDirectory()) => injectCreateServices({
715
+ cwd: outsideSandbox(targetCwd),
596
716
  agentDir,
597
717
  resourceLoaderOptions: {
598
- extensionFactories: getBuiltinExtensionFactories(),
718
+ extensionFactories: [...getBuiltinExtensionFactories(), ...pluginHost.extensionFactories(), ...internalExtensionFactories()],
599
719
  },
600
720
  });
601
721
 
602
722
  // The session that most recently produced an event: the carrier for an
603
723
  // Open request nobody can attribute (see open-request.js).
604
724
  let lastPublishedSession = null;
725
+ // Sessions started for a new-session draft before its first send (see
726
+ // `createSession` with `draft: true`). Listings and the pending-input list
727
+ // leave them out, and their events carry `draft: true`, so no client adds
728
+ // a sidebar row or transcript for them; only the drafting client uses
729
+ // them, for the draft's composer controls and model. Sending adopts the
730
+ // session (`draftSessionId`), which clears the mark.
731
+ const draftSessionIds = new Set();
605
732
  const publish = (event, payload, sessionId = runtime?.session?.sessionId, directory) => {
606
733
  if (typeof sessionId !== 'string' || sessionId.length === 0) return;
607
- const targetDirectory = directory || activeDirectory || cwd;
734
+ const targetDirectory = directory || defaultDirectory();
735
+ const draft = draftSessionIds.has(sessionId);
608
736
  const message = {
609
737
  protocolVersion: PROTOCOL_VERSION,
610
738
  kind: 'event',
611
739
  event,
612
740
  streamEpoch,
613
741
  sequence: ++sequence,
742
+ ...(draft ? { draft: true } : {}),
614
743
  payload: {
615
744
  sessionId,
616
745
  directory: targetDirectory,
@@ -618,7 +747,8 @@ export function createSessionDaemon({
618
747
  },
619
748
  };
620
749
  const line = `${JSON.stringify(message)}\n`;
621
- lastPublishedSession = { sessionId, directory: targetDirectory };
750
+ // A draft is no target for open requests: no client shows it.
751
+ if (!draft) lastPublishedSession = { sessionId, directory: targetDirectory };
622
752
  // Live delivery stays full-fidelity even when the event is too large to
623
753
  // retain: retention evicts whole oldest events and never truncates content.
624
754
  replayLog.append(message.sequence, sessionId, line);
@@ -638,7 +768,8 @@ export function createSessionDaemon({
638
768
  event,
639
769
  streamEpoch,
640
770
  sequence: ++sequence,
641
- payload: { sessionId, directory: directory || activeDirectory || cwd, ...payload },
771
+ ...(draftSessionIds.has(sessionId) ? { draft: true } : {}),
772
+ payload: { sessionId, directory: directory || defaultDirectory(), ...payload },
642
773
  };
643
774
  const line = `${JSON.stringify(message)}\n`;
644
775
  for (const client of clients) writeLine(client, line);
@@ -657,7 +788,11 @@ export function createSessionDaemon({
657
788
  const userBash = createUserBash({
658
789
  publish,
659
790
  redact: (value) => redactAttachmentPaths(value),
660
- onSettled: (sessionId) => safeTouchIdleDisposal(sessionId),
791
+ onSettled: (sessionId) => {
792
+ safeTouchIdleDisposal(sessionId);
793
+ // A settings change that waited for this command can apply now.
794
+ void flushPendingRuntimeRecreation().catch(() => {});
795
+ },
661
796
  });
662
797
  // What opened a `custom()` surface, for its header: the running top-level
663
798
  // tool, else the extension command being run. Pi's ctx.ui is shared per
@@ -668,6 +803,13 @@ export function createSessionDaemon({
668
803
  // same id it uses for custom() surfaces): surfaces that input opens are
669
804
  // drawn at that tab's size.
670
805
  const promptClientBySession = new Map();
806
+ const recordInputClient = (sessionId, clientId) => {
807
+ if (typeof clientId === 'string' && clientId.length > 0 && clientId.length <= 128) {
808
+ promptClientBySession.set(sessionId, clientId);
809
+ } else {
810
+ promptClientBySession.delete(sessionId);
811
+ }
812
+ };
671
813
  /**
672
814
  * The running extension command while it is the only thing running (no
673
815
  * agent turn): the session is busy, as in Pi's interactive mode, which
@@ -694,7 +836,7 @@ export function createSessionDaemon({
694
836
  pendingInput,
695
837
  agentDir,
696
838
  theme: extensionTheme,
697
- directoryForSession: (sessionId) => findRuntimeForSession(sessionId)?.cwd || activeDirectory || cwd,
839
+ directoryForSession: (sessionId) => findRuntimeForSession(sessionId)?.cwd || defaultDirectory(),
698
840
  redactLine: (line) => redactAttachmentPaths(line),
699
841
  describeOrigin: describeCustomOrigin,
700
842
  openerClientFor: (sessionId) => promptClientBySession.get(sessionId),
@@ -714,14 +856,22 @@ export function createSessionDaemon({
714
856
  redactAttachmentValues: (value) => redactAttachmentValues(value),
715
857
  findRuntimeBySessionId: (sessionId) => runtimeRegistry?.findBySessionId(sessionId)
716
858
  || (runtime?.session?.sessionId === sessionId ? runtime : undefined),
717
- getDefaultDirectory: () => activeDirectory || cwd,
859
+ getDefaultDirectory: () => defaultDirectory(),
718
860
  getSequence: () => sequence,
719
861
  protocolError: (code, message) => new SessionDaemonProtocolError(code, message),
720
862
  renderExtensionMessage: (session, message) => extensionMessageRenderer.renderMessage(session, message),
721
863
  requestSessionShutdown: (sessionId) => shutdownRequestedBySession.add(sessionId),
722
864
  pendingInput,
723
865
  customHost,
866
+ resolveExtensionMode: resolveBindingExtensionMode,
724
867
  });
868
+ // Factories PiChamber itself adds to every runtime, after plugins: the
869
+ // listener for composer controls extensions declare on `pi.events`.
870
+ const composerControlsExtension = createComposerControlsExtension(
871
+ (sessionId, data) => extensionBridge.setComposerControl(sessionId, data),
872
+ );
873
+ const internalExtensionFactories = () => [composerControlsExtension];
874
+
725
875
  // `custom()` commands from browsers. Unknown or closed surfaces answer
726
876
  // `accepted: false` instead of throwing, like stale dialog responses, so a
727
877
  // late key from another device never tears down the daemon socket.
@@ -767,7 +917,7 @@ export function createSessionDaemon({
767
917
  event: 'extension.custom.frame',
768
918
  streamEpoch,
769
919
  sequence: ++sequence,
770
- payload: { sessionId, directory: findRuntimeForSession(sessionId)?.cwd || activeDirectory || cwd, ...payload },
920
+ payload: { sessionId, directory: findRuntimeForSession(sessionId)?.cwd || defaultDirectory(), ...payload },
771
921
  });
772
922
  }
773
923
  };
@@ -796,8 +946,11 @@ export function createSessionDaemon({
796
946
  // host factories keep their single-argument contract and ignore the hooks.
797
947
  const baseCreateRuntime = injectCreateRuntime
798
948
  ?? ((runtimeOptions, runtimeHooks) => createPiSessionRuntime(runtimeOptions, runtimeHooks));
799
- const createRuntime = (runtimeOptions) => baseCreateRuntime(runtimeOptions, {
949
+ const createRuntime = (runtimeOptions, extraHooks) => baseCreateRuntime(runtimeOptions, {
800
950
  createExtensionBindings: buildExtensionBindings,
951
+ pluginExtensionFactories: pluginHost.extensionFactories,
952
+ internalExtensionFactories,
953
+ ...extraHooks,
801
954
  });
802
955
 
803
956
  const getSessionState = () => runtime
@@ -834,7 +987,7 @@ export function createSessionDaemon({
834
987
  dormantSession = {
835
988
  sessionId,
836
989
  sessionFile,
837
- cwd: runtime.cwd || activeDirectory || cwd,
990
+ cwd: runtime.cwd || defaultDirectory(),
838
991
  };
839
992
  };
840
993
 
@@ -859,7 +1012,7 @@ export function createSessionDaemon({
859
1012
  const activeSession = targetRuntime?.session || runtime?.session;
860
1013
  const retry = session.sessionId ? retryStateBySession.get(session.sessionId) : undefined;
861
1014
  const compaction = compactionStateFor(activeSession);
862
- const targetDirectory = targetRuntime?.cwd || activeDirectory || cwd;
1015
+ const targetDirectory = targetRuntime?.cwd || defaultDirectory();
863
1016
  const lastAssistant = activeSession ? projectLatestAssistantMessage(targetRuntime || runtime) : undefined;
864
1017
  const model = activeSession?.model;
865
1018
  const snapshotSequence = ++sequence;
@@ -898,6 +1051,9 @@ export function createSessionDaemon({
898
1051
  serverNow: Date.now(),
899
1052
  lastSequence: snapshotSequence,
900
1053
  ...(extensionSnapshot.statuses ? { extensionStatuses: extensionSnapshot.statuses } : {}),
1054
+ // Always sent: an empty list is authoritative (no controls), unlike a
1055
+ // missing field.
1056
+ extensionControls: extensionSnapshot.controls ?? [],
901
1057
  ...(extensionSnapshot.widgets ? { extensionWidgets: extensionSnapshot.widgets } : {}),
902
1058
  ...(extensionSnapshot.dialogs ? { extensionDialogs: extensionSnapshot.dialogs } : {}),
903
1059
  ...(extensionSnapshot.panels ? { extensionPanels: extensionSnapshot.panels } : {}),
@@ -963,7 +1119,36 @@ export function createSessionDaemon({
963
1119
  idleDisposeTimers.clear();
964
1120
  };
965
1121
 
1122
+ // A disposed session whose assigned JSONL is positively absent never
1123
+ // reached disk, so nothing can reopen it. Clears the same safe per-session
1124
+ // state as explicit deletion and tells clients it is gone. Callers decide
1125
+ // absence (ENOENT only) and hold a successful lease release first.
1126
+ const forgetEphemeralSession = ({ cwd: sessionCwd, sessionId }) => {
1127
+ if (dormantSession?.sessionId === sessionId) dormantSession = undefined;
1128
+ messageEntryAliases.clearSession({ cwd: sessionCwd, sessionId });
1129
+ retryStateBySession.delete(sessionId);
1130
+ compactionStateBySession.delete(sessionId);
1131
+ activeRunStartedAt.delete(sessionId);
1132
+ shutdownRequestedBySession.delete(sessionId);
1133
+ publish('session.deleted', {}, sessionId, sessionCwd);
1134
+ pendingInput.forgetSession(sessionId);
1135
+ };
1136
+
1137
+ const isSessionFileAbsent = async (sessionFile) => {
1138
+ if (typeof sessionFile !== 'string' || sessionFile.length === 0) return false;
1139
+ try {
1140
+ await stat(sessionFile);
1141
+ return false;
1142
+ } catch (error) {
1143
+ return error?.code === 'ENOENT';
1144
+ }
1145
+ };
1146
+
966
1147
  const disposeRuntime = async () => {
1148
+ // Record the session the active runtime holds now (navigate, fork, or a
1149
+ // first message may have changed it since activation) so the dormant
1150
+ // entry names the file a later `ensureRuntime` would reopen.
1151
+ rememberRuntimeSession();
967
1152
  clearAllIdleDisposals();
968
1153
  extensionToolRenderer.dispose();
969
1154
  activeSessionInputs.clear();
@@ -976,14 +1161,14 @@ export function createSessionDaemon({
976
1161
  try {
977
1162
  for (const tracked of runtimeRegistry?.listAll?.() ?? []) {
978
1163
  if (typeof tracked?.session?.sessionId === 'string') {
979
- leased.push({ cwd: tracked.cwd || activeDirectory || cwd, sessionId: tracked.session.sessionId });
1164
+ leased.push({ cwd: tracked.cwd || defaultDirectory(), sessionId: tracked.session.sessionId });
980
1165
  }
981
1166
  }
982
1167
  } catch {
983
1168
  // Registry enumeration must never block teardown.
984
1169
  }
985
1170
  if (runtime && typeof runtime.session?.sessionId === 'string') {
986
- leased.push({ cwd: runtime.cwd || activeDirectory || cwd, sessionId: runtime.session.sessionId });
1171
+ leased.push({ cwd: runtime.cwd || defaultDirectory(), sessionId: runtime.session.sessionId });
987
1172
  }
988
1173
  if (runtimeRegistry) {
989
1174
  const hadTrackedRuntime = runtimeRegistry.size > 0;
@@ -994,12 +1179,39 @@ export function createSessionDaemon({
994
1179
  await runtime?.dispose?.();
995
1180
  }
996
1181
  runtime = undefined;
1182
+ // Drafts die with their runtimes. Announce each while it is still marked,
1183
+ // so the event carries `draft: true` and only the drafting client hears
1184
+ // it, then drop the mark: no later id may be taken for a live draft.
997
1185
  for (const lease of leased) {
998
- await releaseResidentLease(lease);
999
- }
1186
+ if (!draftSessionIds.has(lease.sessionId)) continue;
1187
+ publish('session.deleted', {}, lease.sessionId, lease.cwd);
1188
+ draftSessionIds.delete(lease.sessionId);
1189
+ }
1190
+ // Pi defers the JSONL until the first user or assistant message, so the
1191
+ // remembered session may never have reached disk (a catalog read on a
1192
+ // fresh install, or a new session with nothing sent). Decide that while
1193
+ // the leases are still held, as idle disposal does. Reopening an absent
1194
+ // file fails as SESSION_JSONL_UNREADABLE on every later `ensureRuntime`,
1195
+ // so the dormant entry is dropped and the next start opens a fresh session.
1196
+ // Capture once: the dormant binding can change during the await, and the
1197
+ // session cleared or announced must be the one whose file was checked.
1198
+ const dormantCandidate = dormantSession;
1199
+ const ephemeralSession = dormantCandidate && await isSessionFileAbsent(dormantCandidate.sessionFile)
1200
+ ? dormantCandidate
1201
+ : undefined;
1202
+ let ephemeralReleased = false;
1203
+ for (const lease of leased) {
1204
+ const result = await releaseResidentLease(lease);
1205
+ if (ephemeralSession && lease.sessionId === ephemeralSession.sessionId && result?.released === true) ephemeralReleased = true;
1206
+ }
1207
+ if (!ephemeralSession) return;
1208
+ if (dormantSession === ephemeralSession) dormantSession = undefined;
1209
+ // Only an owned, released session is announced as gone; an implicit
1210
+ // catalog session held no lease and was never listed.
1211
+ if (ephemeralReleased) forgetEphemeralSession({ cwd: ephemeralSession.cwd, sessionId: ephemeralSession.sessionId });
1000
1212
  };
1001
1213
 
1002
- const startRuntime = async ({ cwd: runtimeCwd = activeDirectory || cwd, sessionFile, activate = true } = {}) => {
1214
+ const startRuntime = async ({ cwd: runtimeCwd = defaultDirectory(), sessionFile, activate = true } = {}) => {
1003
1215
  if (sessionFile) await validatePiSessionJsonlFile(sessionFile);
1004
1216
  const canonicalRuntimeCwd = sessionFile && dormantSession?.cwd
1005
1217
  ? dormantSession.cwd
@@ -1009,6 +1221,7 @@ export function createSessionDaemon({
1009
1221
  }
1010
1222
  let newRuntime;
1011
1223
  try {
1224
+ refuseSandboxedRuntime(canonicalRuntimeCwd);
1012
1225
  newRuntime = await createRuntime({ cwd: canonicalRuntimeCwd, agentDir, ...(sessionFile ? { sessionFile } : {}) });
1013
1226
  } catch (error) {
1014
1227
  if (sessionFile && dormantSession?.sessionId) {
@@ -1046,14 +1259,17 @@ export function createSessionDaemon({
1046
1259
  return newRuntime;
1047
1260
  };
1048
1261
 
1049
- const ensureRuntime = (targetCwd = activeDirectory || cwd) => {
1262
+ const ensureRuntime = (targetCwd = defaultDirectory()) => {
1050
1263
  const requestedCwd = resolve(targetCwd);
1051
1264
  // Runtime state is owned per working directory. A request that names a
1052
1265
  // directory is answered by a runtime resident in that directory, never by
1053
1266
  // the active runtime of a different project, whose loaded extensions,
1054
1267
  // skills, prompts, and models would then be reported for the wrong project.
1055
1268
  const resident = runtimeRegistry?.listByDirectory?.(requestedCwd) ?? [];
1056
- const candidate = resident.includes(runtime) ? runtime : resident[0];
1269
+ // A draft session never answers as a folder's general runtime: its
1270
+ // events are tagged `draft` and only the drafting client reads them.
1271
+ const general = resident.filter((entry) => !draftSessionIds.has(entry?.session?.sessionId));
1272
+ const candidate = general.includes(runtime) ? runtime : general[0];
1057
1273
  if (candidate) return Promise.resolve(candidate);
1058
1274
 
1059
1275
  // Concurrent starts are shared per directory, never across directories.
@@ -1072,7 +1288,7 @@ export function createSessionDaemon({
1072
1288
  // runtime, adopts what it starts. After idle disposal clears `runtime`,
1073
1289
  // `activeDirectory` still names the user's project, so reading another
1074
1290
  // project's catalog leaves that project and its dormant session intact.
1075
- activate: !runtime && requestedCwd === resolve(activeDirectory || cwd),
1291
+ activate: !runtime && requestedCwd === resolve(defaultDirectory()),
1076
1292
  }).finally(() => {
1077
1293
  if (runtimeStartPromises.get(requestedCwd) === pendingStart) {
1078
1294
  runtimeStartPromises.delete(requestedCwd);
@@ -1093,12 +1309,20 @@ export function createSessionDaemon({
1093
1309
  else activeSessionInputs.delete(targetRuntime);
1094
1310
  };
1095
1311
 
1312
+ // Recreating runtimes disposes every one of them, so it waits for work
1313
+ // that ends by itself: a turn, a compaction, an input being accepted, a
1314
+ // user shell command (`!cmd`, live from acceptance, before Pi reports
1315
+ // `isBashRunning`). A dialog or custom() surface left open does not hold
1316
+ // it back, since nothing says when that ends; recreation cancels it, as a
1317
+ // daemon restart does.
1096
1318
  const isRuntimeReloadSafe = (targetRuntime) => {
1097
1319
  const session = targetRuntime?.session;
1098
1320
  return Boolean(
1099
1321
  session?.sessionId
1100
1322
  && session.isStreaming !== true
1101
1323
  && session.isCompacting !== true
1324
+ && session.isBashRunning !== true
1325
+ && !userBash.isActive(session.sessionId)
1102
1326
  && !activeSessionInputs.has(targetRuntime)
1103
1327
  );
1104
1328
  };
@@ -1204,7 +1428,7 @@ export function createSessionDaemon({
1204
1428
  ? (runtimeRegistry?.listAll?.() ?? [])
1205
1429
  : (runtimeRegistry?.listByDirectory?.(targetDir) ?? [])
1206
1430
  );
1207
- if (runtime && (affectsGlobal || resolve(runtime.cwd || activeDirectory || cwd) === resolve(targetDir))) {
1431
+ if (runtime && (affectsGlobal || resolve(runtime.cwd || defaultDirectory()) === resolve(targetDir))) {
1208
1432
  candidates.add(runtime);
1209
1433
  }
1210
1434
  await Promise.all([...candidates].map(async (targetRuntime) => {
@@ -1221,6 +1445,10 @@ export function createSessionDaemon({
1221
1445
 
1222
1446
  const isIdleDisposalSafe = (sessionId, targetRuntime) => {
1223
1447
  if (!targetRuntime) return false;
1448
+ // A draft is always disposable: nobody else can see it, so a dialog,
1449
+ // custom() surface, or command left in it would keep it forever.
1450
+ // Disposal ends them (`disposeIdleSessionRuntime`).
1451
+ if (isValidIdleSessionId(sessionId) && draftSessionIds.has(sessionId)) return true;
1224
1452
  // A session blocked on a hosted input request (e.g. an extension dialog
1225
1453
  // opened while idle) must survive the idle timer so a user who walks
1226
1454
  // away finds it still pending later. Deletion and daemon stop still
@@ -1271,8 +1499,15 @@ export function createSessionDaemon({
1271
1499
  } catch {
1272
1500
  assignedSessionFile = undefined;
1273
1501
  }
1274
- const targetCwd = targetRuntime.cwd || activeDirectory || cwd;
1502
+ const targetCwd = targetRuntime.cwd || defaultDirectory();
1275
1503
  try {
1504
+ if (draftSessionIds.has(sessionId)) {
1505
+ // Forceful for a draft: answer its dialogs, close its surfaces,
1506
+ // stop anything running, and let a control's command settle.
1507
+ clearExtensionState(sessionId);
1508
+ try { await targetRuntime.session?.abort?.(); } catch { /* disposal follows */ }
1509
+ await waitForControlRuns(sessionId);
1510
+ }
1276
1511
  if (targetRuntime === runtime) rememberRuntimeSession();
1277
1512
  // Kept for safety: while a hosted input request is pending the idle
1278
1513
  // guard above refuses disposal, so this cancel path is normally
@@ -1283,6 +1518,7 @@ export function createSessionDaemon({
1283
1518
  extensionToolRenderer.clearSession(sessionId);
1284
1519
  runningToolsBySession.delete(sessionId);
1285
1520
  await runtimeRegistry.dispose(targetRuntime);
1521
+ releaseRequestedBySession.delete(sessionId);
1286
1522
  // Positively determine ephemerality while the resident lease is
1287
1523
  // still held, before any release. A stat success means persisted;
1288
1524
  // ENOENT means the assigned JSONL never reached disk; any other
@@ -1291,14 +1527,7 @@ export function createSessionDaemon({
1291
1527
  // here (after dispose, before release) keeps the check
1292
1528
  // authoritative: no cross-daemon owner can interleave a recreate
1293
1529
  // while this lease is held.
1294
- let ephemeral = false;
1295
- if (typeof assignedSessionFile === 'string' && assignedSessionFile.length > 0) {
1296
- try {
1297
- await stat(assignedSessionFile);
1298
- } catch (error) {
1299
- if (error?.code === 'ENOENT') ephemeral = true;
1300
- }
1301
- }
1530
+ const ephemeral = await isSessionFileAbsent(assignedSessionFile);
1302
1531
  const releaseResult = await releaseResidentLease({ cwd: targetCwd, sessionId });
1303
1532
  const released = releaseResult?.released === true;
1304
1533
  shutdownRequestedBySession.delete(sessionId);
@@ -1312,22 +1541,15 @@ export function createSessionDaemon({
1312
1541
  // deletion. A confirmed ephemeral expiration clears the same safe
1313
1542
  // per-session auxiliary state as explicit deletion where
1314
1543
  // applicable (aliases, retry/compaction/run-start/shutdown).
1315
- if (ephemeral && released) {
1316
- if (dormantSession?.sessionId === sessionId) dormantSession = undefined;
1317
- messageEntryAliases.clearSession({ cwd: targetCwd, sessionId });
1318
- retryStateBySession.delete(sessionId);
1319
- compactionStateBySession.delete(sessionId);
1320
- activeRunStartedAt.delete(sessionId);
1321
- shutdownRequestedBySession.delete(sessionId);
1322
- publish('session.deleted', {}, sessionId, targetCwd);
1323
- pendingInput.forgetSession(sessionId);
1324
- }
1544
+ if (ephemeral && released) forgetEphemeralSession({ cwd: targetCwd, sessionId });
1325
1545
  } catch {
1326
1546
  // A failed disposal retains ownership (registry entry, lease, and
1327
1547
  // global runtime are all still held) and never emits deletion.
1328
1548
  publish('session.error', { code: 'RUNTIME_DISPOSAL_FAILED' }, sessionId, targetRuntime.cwd);
1329
1549
  } finally {
1330
1550
  disposingSessionIds.delete(sessionId);
1551
+ // A draft that idled out is gone; its deletion went out marked.
1552
+ if (!runtimeRegistry?.findBySessionId(sessionId)) draftSessionIds.delete(sessionId);
1331
1553
  }
1332
1554
  })();
1333
1555
  disposingSessionPromises.set(sessionId, tracked);
@@ -1337,6 +1559,42 @@ export function createSessionDaemon({
1337
1559
  return tracked;
1338
1560
  };
1339
1561
 
1562
+ // Let go of every resident session in `directories` (and folders inside
1563
+ // them): idle ones are disposed now, busy ones (turn, compaction, shell
1564
+ // command, custom surface, pending dialog) at their next idle edge. The
1565
+ // server polls until nothing is pending, announcing each move.
1566
+ const releaseDirectories = async (payload) => {
1567
+ const directories = payload?.directories;
1568
+ if (!Array.isArray(directories) || directories.length === 0 || directories.length > 64
1569
+ || directories.some((directory) => typeof directory !== 'string' || !isAbsolute(directory))) {
1570
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The folders to release are invalid.');
1571
+ }
1572
+ const roots = directories.map((directory) => resolve(directory));
1573
+ const owns = (directory) => roots.some((root) => directory === root || directory.startsWith(root.endsWith(sep) ? root : `${root}${sep}`));
1574
+ const released = [];
1575
+ const pending = [];
1576
+ for (const target of runtimeRegistry?.listAll() ?? []) {
1577
+ const sessionId = target.session?.sessionId;
1578
+ const directory = typeof target.cwd === 'string' && target.cwd.length > 0 ? resolve(target.cwd) : null;
1579
+ if (!isValidIdleSessionId(sessionId) || !directory || !owns(directory)) continue;
1580
+ releaseRequestedBySession.add(sessionId);
1581
+ await disposeIdleSessionRuntime(sessionId);
1582
+ if (runtimeRegistry.findBySessionId(sessionId) === target || unreleasedLeases.has(sessionId)) pending.push({ sessionId, directory });
1583
+ else released.push({ sessionId, directory });
1584
+ }
1585
+ // Sessions disposed earlier whose lease could not be released then.
1586
+ for (const lease of [...unreleasedLeases.values()]) {
1587
+ const directory = typeof lease.cwd === 'string' && lease.cwd.length > 0 ? resolve(lease.cwd) : null;
1588
+ if (!directory || !owns(directory) || runtimeRegistry?.findBySessionId(lease.sessionId)) continue;
1589
+ if (released.some((item) => item.sessionId === lease.sessionId) || pending.some((item) => item.sessionId === lease.sessionId)) continue;
1590
+ // Skipped means the session is being opened here again: still this
1591
+ // daemon's, so not released.
1592
+ const { skipped } = await releaseResidentLease(lease, { onlyUnreleased: true });
1593
+ (skipped || unreleasedLeases.has(lease.sessionId) ? pending : released).push({ sessionId: lease.sessionId, directory });
1594
+ }
1595
+ return { released, pending, streamEpoch };
1596
+ };
1597
+
1340
1598
  const completeRequestedShutdown = (sessionId) => {
1341
1599
  if (!shutdownRequestedBySession.has(sessionId)) return false;
1342
1600
  void disposeIdleSessionRuntime(sessionId);
@@ -1349,7 +1607,7 @@ export function createSessionDaemon({
1349
1607
  const timer = setTimeout(() => {
1350
1608
  idleDisposeTimers.delete(sessionId);
1351
1609
  void disposeIdleSessionRuntime(sessionId);
1352
- }, idleTimeoutMs);
1610
+ }, releaseRequestedBySession.has(sessionId) ? 0 : idleTimeoutMs);
1353
1611
  idleDisposeTimers.set(sessionId, timer);
1354
1612
  };
1355
1613
 
@@ -1416,7 +1674,8 @@ export function createSessionDaemon({
1416
1674
  case 'sessions.bash':
1417
1675
  case 'sessions.abortBash':
1418
1676
  case 'sessions.delete':
1419
- case 'sessions.rename': {
1677
+ case 'sessions.rename':
1678
+ case 'extensions.control': {
1420
1679
  const candidate = message?.payload?.sessionId;
1421
1680
  return isValidIdleSessionId(candidate) ? candidate : undefined;
1422
1681
  }
@@ -1479,6 +1738,8 @@ export function createSessionDaemon({
1479
1738
  }
1480
1739
  const extra = [];
1481
1740
  for (const entry of activeEntries) {
1741
+ // A draft's session is listed once a send adopts it.
1742
+ if (draftSessionIds.has(entry?.session?.sessionId)) continue;
1482
1743
  if (entry?.session?.sessionId && !knownIds.has(entry.session.sessionId)) {
1483
1744
  const name = entry.session.sessionManager?.getSessionName?.() || entry.session.title || undefined;
1484
1745
  const messageCount = entry.session.messages?.length || 0;
@@ -1552,7 +1813,7 @@ export function createSessionDaemon({
1552
1813
  }
1553
1814
  const sessionId = payload.sessionId;
1554
1815
  const title = payload.title.trim();
1555
- const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
1816
+ const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (defaultDirectory());
1556
1817
  const activeRuntime = runtimeRegistry?.get({ cwd: targetDir, sessionId })
1557
1818
  || runtimeRegistry?.findBySessionId(sessionId)
1558
1819
  || (runtime?.session?.sessionId === sessionId ? runtime : undefined);
@@ -1579,11 +1840,13 @@ export function createSessionDaemon({
1579
1840
 
1580
1841
  // Deletion passes `allowRemovedDirectory`: a session whose folder has since
1581
1842
  // been removed is still found in the store. Opening keeps the strict check.
1582
- const findPersistedSession = async (sessionId, requestedDirectory, { allowRemovedDirectory = false } = {}) => {
1843
+ const findPersistedSession = async (sessionId, requestedDirectory, { allowRemovedDirectory = false, readOnly = false } = {}) => {
1583
1844
  if (typeof sessionId !== 'string' || sessionId.length === 0) {
1584
1845
  throw new SessionDaemonProtocolError('INVALID_SESSION', 'The Pi session does not exist.');
1585
1846
  }
1586
- const resolve = allowRemovedDirectory ? resolveSessionStoreDirectory : resolveDirectory;
1847
+ // A read-only lookup only checks the folder: `resolveDirectory` also
1848
+ // records it and may trust it, which a transcript read must not do.
1849
+ const resolve = allowRemovedDirectory ? resolveSessionStoreDirectory : (readOnly ? validateDirectoryPath : resolveDirectory);
1587
1850
  const candidateDirs = new Set();
1588
1851
  let requestedTargetDirectory;
1589
1852
  if (requestedDirectory) {
@@ -1696,6 +1959,9 @@ export function createSessionDaemon({
1696
1959
  try {
1697
1960
  const targetDir = await resolveDirectory(requestedDirectory);
1698
1961
  const existing = runtimeRegistry.get({ cwd: targetDir, sessionId });
1962
+ // A draft answers its own commands but never becomes the active
1963
+ // session: a restart must not try to reopen what was never written.
1964
+ if (existing && draftSessionIds.has(sessionId)) return existing;
1699
1965
  if (existing) {
1700
1966
  runtime = existing;
1701
1967
  activeDirectory = targetDir;
@@ -1704,6 +1970,7 @@ export function createSessionDaemon({
1704
1970
  } catch {}
1705
1971
  }
1706
1972
  const existingAnywhere = runtimeRegistry.findBySessionId(sessionId);
1973
+ if (existingAnywhere && draftSessionIds.has(sessionId)) return existingAnywhere;
1707
1974
  if (existingAnywhere) {
1708
1975
  runtime = existingAnywhere;
1709
1976
  if (existingAnywhere.cwd) activeDirectory = existingAnywhere.cwd;
@@ -1713,6 +1980,7 @@ export function createSessionDaemon({
1713
1980
  await acquireResidentLease({ cwd: directory, sessionId });
1714
1981
  let newRuntime;
1715
1982
  try {
1983
+ refuseSandboxedRuntime(directory);
1716
1984
  newRuntime = await createRuntime({ cwd: directory, agentDir, sessionFile: target.path });
1717
1985
  if (!newRuntime.cwd) newRuntime.cwd = directory;
1718
1986
  if (newRuntime.session?.sessionId !== sessionId && typeof newRuntime.switchSession === 'function') {
@@ -1820,7 +2088,7 @@ export function createSessionDaemon({
1820
2088
  return undefined;
1821
2089
  };
1822
2090
 
1823
- const projectMessageEntries = (activeRuntime, targetDir = activeDirectory || cwd) => {
2091
+ const projectMessageEntries = (activeRuntime, targetDir = defaultDirectory()) => {
1824
2092
  const session = activeRuntime?.session;
1825
2093
  // Use the active branch, not the full file. `getEntries()` returns every
1826
2094
  // entry ever written, so a bare `branch()`/`resetLeaf()` would appear to
@@ -1957,7 +2225,8 @@ export function createSessionDaemon({
1957
2225
  const startedAt = activeStartedAt ?? completedTiming?.startedAt;
1958
2226
  const running = streaming && !result;
1959
2227
  const interrupted = !running && !result;
1960
- const metadata = mergeToolPresentationMetadata(result?.metadata, activeRuntime, targetDir, part.name, part.arguments);
2228
+ const partial = running ? getToolPartial(session.sessionId, part.id) : undefined;
2229
+ const metadata = mergeToolPresentationMetadata(result?.metadata ?? partial?.metadata, activeRuntime, targetDir, part.name, part.arguments);
1961
2230
  let resolveRender;
1962
2231
  if (running) {
1963
2232
  const liveRender = extensionToolRenderer.getLiveRender?.(session.sessionId, part.id);
@@ -1983,7 +2252,7 @@ export function createSessionDaemon({
1983
2252
  name: part.name,
1984
2253
  input: redactAttachmentValues(part.arguments),
1985
2254
  state: result?.isError || interrupted ? 'error' : running ? 'running' : 'completed',
1986
- ...(result?.output ? { output: result.output } : {}),
2255
+ ...(result?.output ? { output: result.output } : partial?.output ? { output: partial.output } : {}),
1987
2256
  ...(result?.error
1988
2257
  ? { error: result.error }
1989
2258
  : interrupted
@@ -2112,7 +2381,7 @@ export function createSessionDaemon({
2112
2381
 
2113
2382
  const projectActiveSession = (
2114
2383
  activeRuntime = runtime,
2115
- targetDir = activeRuntime?.cwd || activeDirectory || cwd,
2384
+ targetDir = activeRuntime?.cwd || defaultDirectory(),
2116
2385
  pageOptions = {},
2117
2386
  ) => {
2118
2387
  const session = activeRuntime?.session;
@@ -2133,9 +2402,14 @@ export function createSessionDaemon({
2133
2402
  break;
2134
2403
  }
2135
2404
  }
2136
- const sessionModel = lastAssistant?.model
2137
- ?? (model?.provider && model?.id ? { providerId: model.provider, modelId: model.id } : undefined);
2138
- const sessionThinking = lastAssistant?.thinkingLevel || session.thinkingLevel;
2405
+ // The live session is what the next prompt runs on, so it wins. Pi already
2406
+ // restores a reopened session's model and thinking from its branch. The
2407
+ // last assistant turn only fills a gap: after a revert, a failed turn, or
2408
+ // a switch nobody has prompted on yet, it names a model the session is no
2409
+ // longer on, and a client that trusted it would skip the switch it needs.
2410
+ const sessionModel = (model?.provider && model?.id ? { providerId: model.provider, modelId: model.id } : undefined)
2411
+ ?? lastAssistant?.model;
2412
+ const sessionThinking = session.thinkingLevel || lastAssistant?.thinkingLevel;
2139
2413
  const isStreaming = session.isStreaming === true;
2140
2414
  const retry = retryStateBySession.get(session.sessionId);
2141
2415
  const compaction = compactionStateFor(session);
@@ -2159,6 +2433,9 @@ export function createSessionDaemon({
2159
2433
  ...(activeRunStartedAt.has(session.sessionId) ? { runStartedAt: activeRunStartedAt.get(session.sessionId) } : {}),
2160
2434
  serverNow: Date.now(),
2161
2435
  ...(extensionSnapshot.statuses ? { extensionStatuses: extensionSnapshot.statuses } : {}),
2436
+ // Always sent: an empty list is authoritative (no controls), unlike a
2437
+ // missing field.
2438
+ extensionControls: extensionSnapshot.controls ?? [],
2162
2439
  ...(extensionSnapshot.widgets ? { extensionWidgets: extensionSnapshot.widgets } : {}),
2163
2440
  ...(extensionSnapshot.dialogs ? { extensionDialogs: extensionSnapshot.dialogs } : {}),
2164
2441
  ...(extensionSnapshot.panels ? { extensionPanels: extensionSnapshot.panels } : {}),
@@ -2172,6 +2449,131 @@ export function createSessionDaemon({
2172
2449
  };
2173
2450
  };
2174
2451
 
2452
+ /**
2453
+ * A transcript read straight from its JSONL file (#242, fail closed). The
2454
+ * server asks for it when a sandboxed project's session cannot open in its
2455
+ * sandbox: no Pi runtime, extension, or tool starts, nothing is written
2456
+ * (an in-memory session manager over the parsed entries), and no lease is
2457
+ * taken. The detail is metadata only: `readOnly`, idle, `lastSequence` -1,
2458
+ * and no stream epoch, input state, extension state, or bash executions,
2459
+ * because none of that is this daemon's to claim.
2460
+ */
2461
+ const readPersistedSession = async (payload) => {
2462
+ const sessionId = payload?.sessionId;
2463
+ const { target, directory } = await findPersistedSession(sessionId, payload?.directory || payload?.cwd, { readOnly: true });
2464
+ const entries = parseSessionEntries(await readFile(target.path, 'utf8'));
2465
+ const header = entries[0];
2466
+ const createdAt = Date.parse(header?.timestamp);
2467
+ if (header?.type !== 'session' || header.id !== sessionId || !Number.isFinite(createdAt)) {
2468
+ throw new SessionDaemonProtocolError('INVALID_SESSION', 'The Pi session does not exist.');
2469
+ }
2470
+ const sessionManager = SessionManager.inMemory(directory, undefined, entries);
2471
+ const session = { sessionId, sessionManager, sessionName: sessionManager.getSessionName(), isStreaming: false };
2472
+ const allMessages = projectMessageEntries({ cwd: directory, session }, directory);
2473
+ const page = projectMessagePage(allMessages, { before: payload?.before, limit: payload?.limit });
2474
+ let lastAssistant;
2475
+ for (let index = allMessages.length - 1; index >= 0 && !lastAssistant; index -= 1) {
2476
+ if (allMessages[index]?.message?.role === 'assistant') lastAssistant = allMessages[index].message;
2477
+ }
2478
+ return {
2479
+ session: {
2480
+ id: sessionId, directory, createdAt, updatedAt: createdAt,
2481
+ ...(session.sessionName ? { title: session.sessionName } : {}),
2482
+ ...(lastAssistant?.model ? { model: lastAssistant.model } : {}),
2483
+ ...(lastAssistant?.thinkingLevel ? { thinking: lastAssistant.thinkingLevel } : {}),
2484
+ messageCount: allMessages.length,
2485
+ },
2486
+ messages: page.messages,
2487
+ hasMoreBefore: page.hasMoreBefore === true,
2488
+ ...(page.hasMoreBefore ? { beforeCursor: page.beforeCursor } : {}),
2489
+ lastSequence: -1,
2490
+ isStreaming: false,
2491
+ lifecycle: 'idle',
2492
+ readOnly: true,
2493
+ serverNow: Date.now(),
2494
+ };
2495
+ };
2496
+
2497
+ /**
2498
+ * Send from a draft: its session becomes the new session, with the title,
2499
+ * model, and thinking the send asked for, so what the draft's controls did
2500
+ * (a mode picked, a toggle flipped) carries over. Returns null when the
2501
+ * draft cannot be used (gone, being disposed, another folder, a fork); the
2502
+ * caller then creates a session as usual and a stale draft is dropped.
2503
+ */
2504
+ const adoptDraftSession = async (payload, targetCwd, parent) => {
2505
+ const sessionId = payload.draftSessionId;
2506
+ if (!draftSessionIds.has(sessionId)) return null;
2507
+ const draftRuntime = runtimeRegistry?.findBySessionId(sessionId);
2508
+ if (!draftRuntime || parent || draftRuntime.cwd !== targetCwd || disposingSessionIds.has(sessionId)) {
2509
+ void discardDraftSession(sessionId).catch(() => {});
2510
+ return null;
2511
+ }
2512
+ // The idle timer stops first: it must not fire during the awaits below.
2513
+ clearIdleDisposal(sessionId);
2514
+ // A control's command still running in the draft lands its effects
2515
+ // before the session is projected for the reply (bounded, in case it
2516
+ // waits on a dialog the user has not answered). The draft keeps its mark
2517
+ // meanwhile, so a turn that command starts is still stopped.
2518
+ await waitForControlRuns(sessionId);
2519
+ // Only one send adopts a draft; another (or a discard during the wait)
2520
+ // leaves this send to create as usual.
2521
+ if (!draftSessionIds.has(sessionId) || runtimeRegistry?.findBySessionId(sessionId) !== draftRuntime
2522
+ || disposingSessionIds.has(sessionId)) {
2523
+ return null;
2524
+ }
2525
+ draftSessionIds.delete(sessionId);
2526
+ try {
2527
+ const current = draftRuntime.session?.model;
2528
+ if (payload.model && !(current?.provider === payload.model.providerId && current?.id === payload.model.modelId)) {
2529
+ await setSessionModel(draftRuntime, payload.model);
2530
+ publishSessionModel(draftRuntime.session, sessionId, targetCwd);
2531
+ }
2532
+ if (payload.thinking !== undefined && draftRuntime.session?.thinkingLevel !== payload.thinking) {
2533
+ applyThinking(draftRuntime, payload.thinking, sessionId, targetCwd);
2534
+ }
2535
+ } catch (error) {
2536
+ // The draft stays a draft, back on its idle lifetime; the send
2537
+ // reports the failure.
2538
+ draftSessionIds.add(sessionId);
2539
+ safeTouchIdleDisposal(sessionId);
2540
+ throw error;
2541
+ }
2542
+ if (payload.title) draftRuntime.session.sessionManager?.appendSessionInfo?.(payload.title.trim());
2543
+ // From here it is an ordinary new session, whose first send arms the
2544
+ // idle lifetime again.
2545
+ runtime = draftRuntime;
2546
+ activeDirectory = targetCwd;
2547
+ rememberRuntimeSession();
2548
+ // Published before the reply is built, so the reply's sequence covers it.
2549
+ // A client never saw the draft's events (they were marked `draft`); if
2550
+ // this event reached it before the reply and the reply were older, it
2551
+ // would keep its own empty copy of the session's controls.
2552
+ const createdTitle = (typeof payload.title === 'string' ? payload.title.trim() : '')
2553
+ || draftRuntime.session?.sessionManager?.getSessionName?.();
2554
+ if (createdTitle) {
2555
+ publish('session.updated', { title: redactAttachmentPaths(createdTitle) }, sessionId, targetCwd);
2556
+ }
2557
+ return projectActiveSession(draftRuntime, targetCwd);
2558
+ };
2559
+
2560
+ /**
2561
+ * Stop a draft's session when the draft closes or moves to another folder.
2562
+ * Only a draft can be discarded this way, and always is: its dialogs are
2563
+ * cancelled, its surfaces closed, and anything running stopped first.
2564
+ */
2565
+ const discardDraftSession = async (sessionId) => {
2566
+ if (!draftSessionIds.has(sessionId)) return { discarded: false };
2567
+ if (!runtimeRegistry?.findBySessionId(sessionId)) {
2568
+ draftSessionIds.delete(sessionId);
2569
+ return { discarded: true };
2570
+ }
2571
+ await disposeIdleSessionRuntime(sessionId);
2572
+ const gone = !runtimeRegistry?.findBySessionId(sessionId);
2573
+ if (gone) draftSessionIds.delete(sessionId);
2574
+ return { discarded: gone };
2575
+ };
2576
+
2175
2577
  const createSession = async (payload) => {
2176
2578
  const explicitRetryLimit = payload && typeof payload === 'object' ? (payload.maxRetries ?? payload.retryLimit ?? payload.defaultRetryLimit) : undefined;
2177
2579
  if (explicitRetryLimit !== undefined && (!Number.isInteger(explicitRetryLimit) || explicitRetryLimit < 0 || explicitRetryLimit > 10)) {
@@ -2181,9 +2583,14 @@ export function createSessionDaemon({
2181
2583
  || (payload.cwd !== undefined && (typeof payload.cwd !== 'string' || payload.cwd.length === 0))
2182
2584
  || (payload.title !== undefined && (typeof payload.title !== 'string' || payload.title.trim().length === 0 || payload.title.length > 256))
2183
2585
  || (payload.thinking !== undefined && !isPiThinkingLevel(payload.thinking))
2184
- || (payload.model !== undefined && (!payload.model || typeof payload.model.providerId !== 'string' || typeof payload.model.modelId !== 'string'))) {
2586
+ || (payload.model !== undefined && (!payload.model || typeof payload.model.providerId !== 'string' || typeof payload.model.modelId !== 'string'))
2587
+ || (payload.draft !== undefined && typeof payload.draft !== 'boolean')
2588
+ || (payload.draftSessionId !== undefined && (typeof payload.draftSessionId !== 'string' || payload.draftSessionId.length === 0 || payload.draftSessionId.length > 128))
2589
+ // A draft has no title, parent, or draft of its own yet.
2590
+ || (payload.draft === true && (payload.title !== undefined || payload.parentId !== undefined || payload.draftSessionId !== undefined))) {
2185
2591
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The requested session creation options are invalid.');
2186
2592
  }
2593
+ const draft = payload.draft === true;
2187
2594
  try {
2188
2595
  await flushPendingRuntimeRecreation();
2189
2596
  } catch {
@@ -2194,16 +2601,36 @@ export function createSessionDaemon({
2194
2601
  const targetCwd = await resolveDirectory(payload.cwd);
2195
2602
  await validatePiSessionJsonlDirectory({ cwd: targetCwd, agentDir });
2196
2603
  const parent = payload.parentId === undefined ? undefined : (await findPersistedSession(payload.parentId, targetCwd)).target;
2604
+ if (payload.draftSessionId !== undefined) {
2605
+ const adopted = await adoptDraftSession(payload, targetCwd, parent);
2606
+ if (adopted) return adopted;
2607
+ }
2197
2608
  if (!runtimeRegistry) {
2198
2609
  runtimeRegistry = createSessionRuntimeRegistry({
2199
2610
  onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
2200
2611
  });
2201
2612
  }
2202
- const newRuntime = await createRuntime({
2203
- cwd: targetCwd,
2204
- agentDir,
2205
- ...(parent ? { sessionFile: parent.path } : {}),
2206
- });
2613
+ refuseSandboxedRuntime(targetCwd);
2614
+ // A draft's sessions are marked from the moment Pi assigns their ids:
2615
+ // the runtime's first session (replaced below) and the draft itself.
2616
+ const markedDraftIds = new Set();
2617
+ const markDraft = (manager) => {
2618
+ const id = manager?.getSessionId?.();
2619
+ if (typeof id !== 'string' || id.length === 0) return;
2620
+ markedDraftIds.add(id);
2621
+ draftSessionIds.add(id);
2622
+ };
2623
+ let newRuntime;
2624
+ try {
2625
+ newRuntime = await createRuntime({
2626
+ cwd: targetCwd,
2627
+ agentDir,
2628
+ ...(parent ? { sessionFile: parent.path } : {}),
2629
+ }, draft ? { beforeSession: markDraft } : undefined);
2630
+ } catch (error) {
2631
+ for (const id of markedDraftIds) draftSessionIds.delete(id);
2632
+ throw error;
2633
+ }
2207
2634
  if (!newRuntime.cwd) newRuntime.cwd = targetCwd;
2208
2635
  // Apply default retry limit for new sessions. Explicit per-run overrides win.
2209
2636
  // With no PiChamber override configured, Pi's own retry settings stay
@@ -2233,18 +2660,30 @@ export function createSessionDaemon({
2233
2660
  result = await newRuntime.newSession({
2234
2661
  ...(parent ? { parentSession: parent.path } : {}),
2235
2662
  ...(payload.title ? { setup: async (manager) => manager.appendSessionInfo(payload.title.trim()) } : {}),
2663
+ // An injected runtime factory may not call `beforeSession`.
2664
+ ...(draft ? { setup: async (manager) => markDraft(manager) } : {}),
2236
2665
  });
2237
2666
  } else if (payload.title && newRuntime.session?.sessionManager?.appendSessionInfo) {
2238
2667
  newRuntime.session.sessionManager.appendSessionInfo(payload.title.trim());
2239
2668
  }
2240
2669
  if (result?.cancelled) {
2670
+ // Dispose before unmarking, so what disposal publishes stays `draft`.
2241
2671
  try { await newRuntime.dispose?.(); } catch { /* the cancelled create owns nothing */ }
2672
+ for (const id of markedDraftIds) draftSessionIds.delete(id);
2242
2673
  throw new SessionDaemonProtocolError('SESSION_CREATE_CANCELLED', 'Pi cancelled session creation.');
2243
2674
  }
2675
+ if (draft) {
2676
+ const draftId = newRuntime.session?.sessionId;
2677
+ // The replaced first session is gone; only the draft keeps its mark.
2678
+ for (const id of markedDraftIds) if (id !== draftId) draftSessionIds.delete(id);
2679
+ if (draftId) draftSessionIds.add(draftId);
2680
+ }
2244
2681
  try {
2245
2682
  await acquireResidentLease({ cwd: targetCwd, sessionId: newRuntime.session.sessionId });
2246
2683
  } catch (error) {
2684
+ const failedDraftId = newRuntime.session?.sessionId;
2247
2685
  try { await newRuntime.dispose?.(); } catch { /* the failed create owns nothing */ }
2686
+ draftSessionIds.delete(failedDraftId);
2248
2687
  throw error;
2249
2688
  }
2250
2689
  try {
@@ -2258,9 +2697,13 @@ export function createSessionDaemon({
2258
2697
  } catch (error) {
2259
2698
  const failedSessionId = newRuntime.session?.sessionId;
2260
2699
  const failedCwd = targetCwd;
2700
+ // Unmarked only once disposal is done (or failed), so its events stay
2701
+ // `draft`.
2261
2702
  try {
2262
2703
  await newRuntime.dispose?.();
2704
+ draftSessionIds.delete(failedSessionId);
2263
2705
  } catch {
2706
+ draftSessionIds.delete(failedSessionId);
2264
2707
  // Dispose-first cleanup rejected: retain ownership for a later
2265
2708
  // delete/stop retry. Do not release the lease, install dormant
2266
2709
  // state, or register the runtime. The original model/thinking
@@ -2278,6 +2721,14 @@ export function createSessionDaemon({
2278
2721
  throw error;
2279
2722
  }
2280
2723
  runtimeRegistry.register(newRuntime, { cwd: targetCwd });
2724
+ if (draft) {
2725
+ // A draft is not the daemon's active session and is not remembered
2726
+ // for a restart: nothing has been sent in it. It gets the idle
2727
+ // lifetime of any view-only session, so an abandoned draft goes away.
2728
+ rebuildSessionExtensionState(newRuntime);
2729
+ touchIdleDisposal(newRuntime.session.sessionId);
2730
+ return projectActiveSession(newRuntime, targetCwd);
2731
+ }
2281
2732
  runtime = newRuntime;
2282
2733
  activeDirectory = targetCwd;
2283
2734
  rebuildSessionExtensionState(newRuntime);
@@ -2298,7 +2749,7 @@ export function createSessionDaemon({
2298
2749
  } catch {
2299
2750
  // A failed rebuild stays queued for a later edge; the ensure below retries startup.
2300
2751
  }
2301
- const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
2752
+ const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (defaultDirectory());
2302
2753
  const activeRuntime = await ensureRuntime(targetDir);
2303
2754
  const modelRuntime = activeRuntime.session?.modelRuntime;
2304
2755
  const models = modelRuntime?.getModels?.();
@@ -2326,6 +2777,58 @@ export function createSessionDaemon({
2326
2777
  return { providers: [...providers.values()] };
2327
2778
  };
2328
2779
 
2780
+ // Host names of signed-in providers' model endpoints: the default network
2781
+ // allowlist of a sandboxed project. Loopback hosts are left out; a local
2782
+ // model server is allowed per project by port.
2783
+ // The runtime that answers a provider question for the server's sandbox
2784
+ // manager. `exclude` names the folders of sandboxed projects: this daemon
2785
+ // must not start (or reopen a dormant session in) a runtime there, since
2786
+ // that would load the project's extensions outside its sandbox. A resident
2787
+ // runtime elsewhere is used as it is; otherwise one starts in the active
2788
+ // folder, or in the agent folder when the active folder is excluded.
2789
+ const providerRuntime = async (exclude) => {
2790
+ if (exclude !== undefined && (!Array.isArray(exclude) || exclude.length > 4096
2791
+ || exclude.some((directory) => typeof directory !== 'string' || !isAbsolute(directory)))) {
2792
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The folders to stay out of are invalid.');
2793
+ }
2794
+ const roots = (exclude ?? []).map((directory) => resolve(directory));
2795
+ if (roots.length === 0) return ensureRuntime(defaultDirectory());
2796
+ const excluded = (directory) => {
2797
+ const target = resolve(directory);
2798
+ return roots.some((root) => target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`));
2799
+ };
2800
+ const residents = [...(runtime ? [runtime] : []), ...(runtimeRegistry?.listAll?.() ?? [])];
2801
+ const resident = residents.find((candidate) => typeof candidate?.cwd === 'string' && candidate.cwd.length > 0 && !excluded(candidate.cwd));
2802
+ if (resident) return resident;
2803
+ const target = [defaultDirectory(), agentDir].find((directory) => typeof directory === 'string' && directory.length > 0 && !excluded(directory));
2804
+ if (!target) throw new SessionDaemonProtocolError('PROVIDER_UNAVAILABLE', 'No folder outside the sandboxed projects can answer for the providers.');
2805
+ return ensureRuntime(target);
2806
+ };
2807
+
2808
+ const listProviderHosts = async (payload) => {
2809
+ const activeRuntime = await providerRuntime(payload?.exclude);
2810
+ const modelRuntime = activeRuntime.session?.modelRuntime;
2811
+ const models = modelRuntime?.getModels?.();
2812
+ if (!Array.isArray(models)) throw new SessionDaemonProtocolError('PROVIDER_UNAVAILABLE', 'Pi did not provide a model catalog.');
2813
+ const hosts = new Set();
2814
+ for (const model of models) {
2815
+ if (!model || typeof model.provider !== 'string' || typeof model.baseUrl !== 'string') continue;
2816
+ if (modelRuntime.getProviderAuthStatus?.(model.provider)?.configured !== true) continue;
2817
+ let hostname;
2818
+ try {
2819
+ const url = new URL(model.baseUrl);
2820
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') continue;
2821
+ hostname = url.hostname.toLowerCase();
2822
+ } catch {
2823
+ continue;
2824
+ }
2825
+ if (!hostname || hostname === 'localhost' || hostname.endsWith('.localhost')
2826
+ || /^[\d.]+$/.test(hostname) || hostname.startsWith('[')) continue;
2827
+ hosts.add(hostname);
2828
+ }
2829
+ return { hosts: [...hosts].sort() };
2830
+ };
2831
+
2329
2832
  // In-flight refreshes are shared per resolved directory, never across
2330
2833
  // directories, so a concurrent refresh for another project cannot return
2331
2834
  // this project's catalog. Refreshes for different directories still run one
@@ -2339,7 +2842,7 @@ export function createSessionDaemon({
2339
2842
  } catch {
2340
2843
  // A failed rebuild stays queued for a later edge; the catalog refresh below retries startup.
2341
2844
  }
2342
- const targetDir = resolve(await resolveDirectory(requestedDirectory));
2845
+ const targetDir = outsideSandbox(resolve(await resolveDirectory(requestedDirectory)));
2343
2846
  const existing = refreshProvidersInflight.get(targetDir);
2344
2847
  if (existing) return existing;
2345
2848
  const task = refreshProvidersQueue.then(async () => {
@@ -2556,6 +3059,32 @@ export function createSessionDaemon({
2556
3059
  return { config, ...(deferred ? { deferred: true } : {}) };
2557
3060
  };
2558
3061
 
3062
+ // The main daemon owns OAuth token refresh: a sandbox daemon reads
3063
+ // auth.json through a read-only grant, so before one starts (and after a
3064
+ // sandboxed turn failed to refresh) the server asks here. Each signed-in
3065
+ // OAuth provider whose token expires within `minValidityMs` is refreshed
3066
+ // through Pi under its auth lock. Only failed provider ids are reported.
3067
+ const refreshOAuthTokens = async (payload) => {
3068
+ const minValidityMs = payload?.minValidityMs;
3069
+ if (!Number.isSafeInteger(minValidityMs) || minValidityMs < 0 || minValidityMs > 24 * 60 * 60_000) {
3070
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The OAuth refresh window is invalid.');
3071
+ }
3072
+ const activeRuntime = await providerRuntime(payload?.exclude);
3073
+ const modelRuntime = activeRuntime.session?.modelRuntime;
3074
+ const providers = typeof modelRuntime?.getProviders === 'function' ? modelRuntime.getProviders() : [];
3075
+ const ids = [...new Set(providers.map((provider) => provider?.id).filter((id) => typeof id === 'string' && id.length > 0))]
3076
+ .filter((id) => modelRuntime.isUsingOAuth?.(id) === true);
3077
+ const failed = [];
3078
+ for (const id of ids) {
3079
+ try {
3080
+ await modelRuntime.getAuth(id, { minOAuthValidityMs: minValidityMs });
3081
+ } catch {
3082
+ failed.push(id);
3083
+ }
3084
+ }
3085
+ return { checked: ids.length, failed };
3086
+ };
3087
+
2559
3088
  const providerStatus = async (providerId) => {
2560
3089
  if (typeof providerId !== 'string' || providerId.length === 0 || providerId.length > 256) {
2561
3090
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The requested provider is invalid.');
@@ -2715,12 +3244,12 @@ export function createSessionDaemon({
2715
3244
  };
2716
3245
 
2717
3246
  const readPiSettings = (requestedDirectory) => {
2718
- const targetDir = requestedDirectory || activeDirectory || cwd;
3247
+ const targetDir = requestedDirectory || defaultDirectory();
2719
3248
  const trustStore = createTrustStore(agentDir);
2720
3249
  let trust = trustStore.get(targetDir);
2721
3250
  // Auto-trust known PiChamber projects so the skills popup never appears.
2722
3251
  // `knownDirectories` tracks every dir the user explicitly added/selected.
2723
- if (trust === null && knownDirectories.has(targetDir) && hasTrustRequiringProjectResources(targetDir)) {
3252
+ if (trust === null && knownDirectories.has(targetDir) && !isTrustAskDirectory(targetDir) && hasTrustRequiringProjectResources(targetDir)) {
2724
3253
  try {
2725
3254
  trustStore.set(targetDir, true);
2726
3255
  trust = true;
@@ -2751,7 +3280,7 @@ export function createSessionDaemon({
2751
3280
  if (!payload || typeof payload !== 'object' || !['global', 'project'].includes(payload.scope)) {
2752
3281
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi settings request is invalid.');
2753
3282
  }
2754
- const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
3283
+ const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (defaultDirectory());
2755
3284
  const hasModel = Object.hasOwn(payload, 'defaultModel');
2756
3285
  const hasThinking = Object.hasOwn(payload, 'defaultThinking');
2757
3286
  const hasTrust = Object.hasOwn(payload, 'trust');
@@ -2811,6 +3340,94 @@ export function createSessionDaemon({
2811
3340
  };
2812
3341
  };
2813
3342
 
3343
+ // `pi config` / `pi list` / `pi install` / `pi update` / `pi remove` for
3344
+ // extensions (extension-config.js). Writes share the resource mutation queue and the shared Pi config lock,
3345
+ // read trust inside the lock, and recreate resident runtimes afterwards.
3346
+ const extensionConfigService = createExtensionConfig({ agentDir, createSettingsManager });
3347
+ const extensionConfigTarget = async (payload) => {
3348
+ const directory = typeof payload?.directory === 'string' && payload.directory.trim().length > 0
3349
+ ? await resolveDirectory(payload.directory)
3350
+ : undefined;
3351
+ // Pi's own rule (`resolveProjectTrusted`): a saved decision wins, and a
3352
+ // project with nothing that needs trust counts as trusted, as it does for
3353
+ // `pi config -l`. `resolveDirectory` has already saved trust for a folder
3354
+ // that has project resources, so only a denied project is left out.
3355
+ const decision = directory ? createTrustStore(agentDir).get(directory) : null;
3356
+ return {
3357
+ cwd: defaultDirectory(),
3358
+ directory,
3359
+ trusted: directory ? decision ?? !hasTrustRequiringProjectResources(directory) : false,
3360
+ };
3361
+ };
3362
+ // What a live runtime left out because another extension took its names.
3363
+ // Never starts a runtime: with none resident, or one that predates a queued
3364
+ // recreation, the answer is unknown and the field is left out.
3365
+ const liveExtensionReplacements = (target) => {
3366
+ if (pendingRuntimeRecreation) return undefined;
3367
+ const resident = (runtimeRegistry?.listByDirectory?.(resolve(target.directory ?? target.cwd)) ?? [])
3368
+ .filter((entry) => !draftSessionIds.has(entry?.session?.sessionId));
3369
+ const entry = resident.includes(runtime) ? runtime : resident[0];
3370
+ if (!entry) return undefined;
3371
+ return describeRuntimeReplacements({
3372
+ session: entry.session,
3373
+ configuredPluginIds: pluginHost.configuredIds(),
3374
+ registeredNames: pluginHost.registeredNames(),
3375
+ });
3376
+ };
3377
+ const listExtensionConfig = async (payload) => {
3378
+ const target = await extensionConfigTarget(payload);
3379
+ return extensionConfigService.list(target, liveExtensionReplacements(target));
3380
+ };
3381
+ // Recreates resident runtimes after a change and answers with the fresh
3382
+ // list. Runs inside the resource mutation queue.
3383
+ const answerExtensionConfigChange = async (target) => {
3384
+ const deferred = activeRuntimes().length > 0 ? await scheduleRuntimeRecreation() : false;
3385
+ const result = await extensionConfigService.list(target, liveExtensionReplacements(target));
3386
+ return deferred ? { ...result, deferred: true } : result;
3387
+ };
3388
+ const mutateExtensionConfig = (payload, write) => transactResourceMutation(async () => {
3389
+ const target = await withSharedPiConfigLock(async () => {
3390
+ const resolved = await extensionConfigTarget(payload);
3391
+ await write(resolved);
3392
+ return resolved;
3393
+ });
3394
+ return answerExtensionConfigChange(target);
3395
+ });
3396
+ // `pi install` / `pi update` run npm or git for minutes, so they never hold
3397
+ // the shared Pi config lock (other writers give up after 5 s) or the
3398
+ // resource mutation queue. They queue here instead: one package download
3399
+ // at a time per daemon. Only the settings write afterwards takes the lock.
3400
+ let packageInstallTail = Promise.resolve();
3401
+ const serializePackageInstall = (operation) => {
3402
+ const pending = packageInstallTail.then(operation);
3403
+ packageInstallTail = pending.catch(() => {});
3404
+ return pending;
3405
+ };
3406
+ const installExtensionPackage = async (payload) => {
3407
+ let target = await extensionConfigTarget(payload);
3408
+ let answer;
3409
+ const { installedId } = await extensionConfigService.installPackage(target, payload, {
3410
+ serializeInstall: serializePackageInstall,
3411
+ resolveTarget: () => extensionConfigTarget(payload),
3412
+ withWriteLock: (write) => transactResourceMutation(async () => {
3413
+ await withSharedPiConfigLock(async () => {
3414
+ target = await extensionConfigTarget(payload);
3415
+ await write(target);
3416
+ });
3417
+ answer = await answerExtensionConfigChange(target);
3418
+ }),
3419
+ });
3420
+ return { ...answer, installedId };
3421
+ };
3422
+ const updateExtensionPackage = async (payload) => {
3423
+ const target = await extensionConfigTarget(payload);
3424
+ await extensionConfigService.updatePackage(target, payload, {
3425
+ serializeInstall: serializePackageInstall,
3426
+ resolveTarget: () => extensionConfigTarget(payload),
3427
+ });
3428
+ return transactResourceMutation(async () => answerExtensionConfigChange(await extensionConfigTarget(payload)));
3429
+ };
3430
+
2814
3431
  const resourceId = (kind, filePath) => `${kind}:${createHash('sha256').update(filePath).digest('base64url')}`;
2815
3432
 
2816
3433
  const isPathInside = (parent, candidate) => {
@@ -2834,7 +3451,8 @@ export function createSessionDaemon({
2834
3451
  }));
2835
3452
 
2836
3453
  const resourceCatalog = async (requestedDirectory) => {
2837
- const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
3454
+ // A sandboxed project's own resources are read by its sandbox daemon.
3455
+ const targetDir = outsideSandbox(requestedDirectory ? await resolveDirectory(requestedDirectory) : defaultDirectory());
2838
3456
  // A settings page may be the first caller after a turn settles without a
2839
3457
  // lifecycle event reaching this daemon, so give queued configuration a
2840
3458
  // chance to activate before reading the catalog.
@@ -2969,7 +3587,7 @@ export function createSessionDaemon({
2969
3587
  if (!payload || typeof payload.resourceId !== 'string' || typeof payload.content !== 'string' || payload.content.length > 200_000) {
2970
3588
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi resource update is invalid.');
2971
3589
  }
2972
- const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
3590
+ const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (defaultDirectory());
2973
3591
  const catalog = await resourceCatalog(targetDir);
2974
3592
  const resource = [...catalog.prompts, ...catalog.agents].find((item) => item.id === payload.resourceId && item.editable === true);
2975
3593
  if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi resource is not editable.');
@@ -2996,7 +3614,7 @@ export function createSessionDaemon({
2996
3614
  if (payload.location === 'project' && !payload.directory) {
2997
3615
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'Project prompt templates require an explicit directory.');
2998
3616
  }
2999
- const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
3617
+ const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (defaultDirectory());
3000
3618
  const trust = createTrustStore(agentDir).get(targetDir);
3001
3619
  if (payload.location === 'project' && trust !== true) throw new SessionDaemonProtocolError('PROJECT_UNTRUSTED', 'The project is not trusted.');
3002
3620
  const filePath = join(payload.location === 'global' ? agentDir : join(targetDir, '.pi'), 'prompts', `${payload.name}.md`);
@@ -3012,7 +3630,7 @@ export function createSessionDaemon({
3012
3630
 
3013
3631
  const deletePrompt = (payload) => transactResourceMutation(async () => {
3014
3632
  if (!payload || typeof payload.resourceId !== 'string') throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template is invalid.');
3015
- const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
3633
+ const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (defaultDirectory());
3016
3634
  const catalog = await resourceCatalog(targetDir);
3017
3635
  const resource = catalog.prompts.find((item) => item.id === payload.resourceId && item.editable === true);
3018
3636
  if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi prompt template is not editable.');
@@ -3088,7 +3706,7 @@ export function createSessionDaemon({
3088
3706
  if (hasLocation && payload.location !== 'global' && payload.location !== 'project') {
3089
3707
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi prompt template location is invalid.');
3090
3708
  }
3091
- const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (activeDirectory || cwd);
3709
+ const targetDir = payload.directory ? await resolveDirectory(payload.directory) : (defaultDirectory());
3092
3710
  const catalog = await resourceCatalog(targetDir);
3093
3711
  const resource = catalog.prompts.find((item) => item.id === payload.resourceId && item.editable === true);
3094
3712
  if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi prompt template is not editable.');
@@ -3187,8 +3805,18 @@ export function createSessionDaemon({
3187
3805
  const next = model && (model.reasoning === true || model.thinkingLevelMap)
3188
3806
  ? clampThinkingLevel(getSupportedThinkingLevels(model), thinking)
3189
3807
  : thinking;
3808
+ const previous = runtime.session.thinkingLevel;
3190
3809
  runtime.session.setThinkingLevel(next);
3191
- publish('session.thinking', { thinking: next }, sessionId, directory);
3810
+ const effective = runtime.session.thinkingLevel ?? next;
3811
+ // Exactly one `session.thinking` per change. Pi emits
3812
+ // `thinking_level_changed` (published by `publishSessionEvent`) when the
3813
+ // level changes on a runtime the registry subscribes to; publish here
3814
+ // only when it will not: an unchanged level (the caller still gets its
3815
+ // echo) or a runtime not yet registered (a session being created).
3816
+ const changed = effective !== previous;
3817
+ const subscribed = runtimeRegistry?.findBySessionId?.(sessionId) === runtime;
3818
+ if (changed && subscribed) return;
3819
+ publish('session.thinking', { thinking: effective }, sessionId, directory);
3192
3820
  };
3193
3821
 
3194
3822
  const validateThinking = (thinking) => {
@@ -3510,12 +4138,18 @@ export function createSessionDaemon({
3510
4138
  // idle disposal, which reports the session as deleted when its assigned JSONL
3511
4139
  // is positively absent (see disposeIdleSessionRuntime).
3512
4140
 
3513
- const runSessionInput = async (payload, delivery) => {
4141
+ // `keepDraft`: a composer control runs a command without sending the
4142
+ // composer, so the extension's view of the draft stays as it is.
4143
+ // `requireExtensionCommand`: the text must be a command the session's
4144
+ // extensions register once the runtime is settled, or nothing runs. A
4145
+ // composer control sets it, so its `/command` never reaches the model as a
4146
+ // prompt when a queued recreation drops the extension behind it.
4147
+ const runSessionInput = async (payload, delivery, { keepDraft = false, requireExtensionCommand = false } = {}) => {
3514
4148
  if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
3515
4149
  || typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
3516
4150
  throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
3517
4151
  }
3518
- resetExtensionDraft(payload.sessionId);
4152
+ if (!keepDraft) resetExtensionDraft(payload.sessionId);
3519
4153
  if (payload.thinking !== undefined) validateThinking(payload.thinking);
3520
4154
  // Idle protection is owned by the request-dispatch guard: it holds the
3521
4155
  // session refcount across activation/acceptance, agent_start clears once
@@ -3581,6 +4215,9 @@ export function createSessionDaemon({
3581
4215
  && Array.isArray(registeredExtensionCommands)
3582
4216
  && registeredExtensionCommands.some((command) => command?.invocationName === slashInvocation),
3583
4217
  );
4218
+ if (requireExtensionCommand && !isExtensionCommand) {
4219
+ throw new SessionDaemonProtocolError('CONTROL_UNAVAILABLE', 'The command for this control is not available.');
4220
+ }
3584
4221
  // Like the Pi CLI, never persist an auto-title. Lists derive the display
3585
4222
  // title from the first user prompt; publish that derived title live (not
3586
4223
  // persisted) so connected surfaces converge without waiting for a list.
@@ -3626,11 +4263,7 @@ export function createSessionDaemon({
3626
4263
  // describeCustomOrigin). Cleared when the command settles.
3627
4264
  const commandMarker = isExtensionCommand ? { name: slashInvocation } : undefined;
3628
4265
  if (commandMarker) runningCommandBySession.set(payload.sessionId, commandMarker);
3629
- if (typeof payload.clientId === 'string' && payload.clientId.length > 0 && payload.clientId.length <= 128) {
3630
- promptClientBySession.set(payload.sessionId, payload.clientId);
3631
- } else {
3632
- promptClientBySession.delete(payload.sessionId);
3633
- }
4266
+ recordInputClient(payload.sessionId, payload.clientId);
3634
4267
  // True SDK acceptance: await the prompt preflight signal, not the full
3635
4268
  // agent turn. In SDK 1.0.0, preflightResult is called on acceptance with
3636
4269
  // a PromptDisposition ("started" | "queued" | "handled"). Rejections
@@ -3801,6 +4434,69 @@ export function createSessionDaemon({
3801
4434
  }
3802
4435
  };
3803
4436
 
4437
+ /**
4438
+ * A click on a composer control: run the extension command the control
4439
+ * names for the value the client asks for, as if it had been typed. Only a
4440
+ * command the session's extensions registered runs; anything else would
4441
+ * reach the model as a prompt. A stale click (the control is gone, or
4442
+ * already has that value) runs nothing and answers `ran: false`.
4443
+ */
4444
+ // Composer-control commands in flight per session, so adopting a draft
4445
+ // can wait for them (`adoptDraftSession`).
4446
+ const controlRunsBySession = new Map();
4447
+ const CONTROL_RUN_ADOPT_WAIT_MS = 5000;
4448
+ const waitForControlRuns = async (sessionId) => {
4449
+ const runs = controlRunsBySession.get(sessionId);
4450
+ if (!runs || runs.size === 0) return;
4451
+ let timer;
4452
+ await Promise.race([
4453
+ Promise.allSettled([...runs]),
4454
+ new Promise((resolveWait) => { timer = setTimeout(resolveWait, CONTROL_RUN_ADOPT_WAIT_MS); }),
4455
+ ]);
4456
+ clearTimeout(timer);
4457
+ };
4458
+
4459
+ const runComposerControl = async (payload) => {
4460
+ const sessionId = payload?.sessionId;
4461
+ const id = payload?.id;
4462
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256
4463
+ || typeof id !== 'string' || id.length === 0 || id.length > 64) {
4464
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The control request is invalid.');
4465
+ }
4466
+ const resolved = extensionBridge.resolveComposerControl(sessionId, id, payload.value);
4467
+ if (resolved.error === 'CONTROL_NOT_FOUND') return { ran: false };
4468
+ if (resolved.error) throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The control value is invalid.');
4469
+ if (resolved.command === null) return { ran: false };
4470
+ const target = runtimeRegistry?.findBySessionId(sessionId)
4471
+ || (runtime?.session?.sessionId === sessionId ? runtime : undefined);
4472
+ const registered = target?.session?.extensionRunner?.getRegisteredCommands?.();
4473
+ const name = commandName(resolved.command);
4474
+ if (!Array.isArray(registered) || !registered.some((command) => command?.invocationName === name)) {
4475
+ throw new SessionDaemonProtocolError('CONTROL_UNAVAILABLE', 'The command for this control is not available.');
4476
+ }
4477
+ const clientId = typeof payload.clientId === 'string' && payload.clientId.length > 0 && payload.clientId.length <= 128
4478
+ ? payload.clientId
4479
+ : undefined;
4480
+ // Pi runs extension commands at once, also during a turn; `steer` only
4481
+ // lets the daemon accept the input while the session streams.
4482
+ const run = runSessionInput({
4483
+ sessionId,
4484
+ text: `/${resolved.command}`,
4485
+ directory: target.cwd,
4486
+ ...(clientId ? { clientId } : {}),
4487
+ }, target.session.isStreaming ? 'steer' : undefined, { keepDraft: true, requireExtensionCommand: true });
4488
+ const runs = controlRunsBySession.get(sessionId) ?? new Set();
4489
+ controlRunsBySession.set(sessionId, runs);
4490
+ runs.add(run);
4491
+ try {
4492
+ await run;
4493
+ } finally {
4494
+ runs.delete(run);
4495
+ if (runs.size === 0 && controlRunsBySession.get(sessionId) === runs) controlRunsBySession.delete(sessionId);
4496
+ }
4497
+ return { ran: true };
4498
+ };
4499
+
3804
4500
  const treeForSession = async (sessionId, requestedDirectory) => {
3805
4501
  // Idle protection is owned by the request-dispatch guard; the release
3806
4502
  // re-arms even when projection below throws.
@@ -3832,7 +4528,7 @@ export function createSessionDaemon({
3832
4528
  throw new SessionDaemonProtocolError('RUNTIME_DISPOSAL_FAILED', 'The Pi session runtime could not be disposed.');
3833
4529
  }
3834
4530
  const active = runtimeRegistry?.findBySessionId(sessionId);
3835
- let targetDir = requestedDirectory ? await resolveSessionStoreDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
4531
+ let targetDir = requestedDirectory ? await resolveSessionStoreDirectory(requestedDirectory) : active?.cwd || defaultDirectory();
3836
4532
  const activeSessionFile = active?.session?.sessionManager?.getSessionFile?.();
3837
4533
  if (active) {
3838
4534
  if (active.session?.isStreaming) await active.session.abort();
@@ -3871,6 +4567,7 @@ export function createSessionDaemon({
3871
4567
  latestUserMessageIds.delete(sessionId);
3872
4568
  latestAssistantMessageIds.delete(sessionId);
3873
4569
  toolInputBySession.delete(sessionId);
4570
+ toolPartialBySession.delete(sessionId);
3874
4571
  clearToolTimingsForSession(sessionId);
3875
4572
  extensionToolRenderer.clearSession(sessionId);
3876
4573
  // Explicit typed deletion: every connected and replaying client drops
@@ -3886,7 +4583,7 @@ export function createSessionDaemon({
3886
4583
  }
3887
4584
  };
3888
4585
 
3889
- const publishSessionEvent = (sessionId, event, directory = activeDirectory || cwd) => {
4586
+ const publishSessionEvent = (sessionId, event, directory = defaultDirectory()) => {
3890
4587
  const owningRuntime = runtimeRegistry?.get({ cwd: directory, sessionId })
3891
4588
  || (runtime?.session?.sessionId === sessionId ? runtime : undefined);
3892
4589
  switch (event.type) {
@@ -4064,6 +4761,7 @@ export function createSessionDaemon({
4064
4761
  const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
4065
4762
  const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
4066
4763
  const projected = projectToolResult(event.partialResult, false);
4764
+ rememberToolPartial(sessionId, event.toolCallId, projected);
4067
4765
  const metadata = mergeToolPresentationMetadata(projected.metadata, activeRuntime, directory, event.toolName, toolArgs);
4068
4766
  const definition = extensionToolRenderer.resolve(activeRuntime?.session, event.toolName);
4069
4767
  let render;
@@ -4178,6 +4876,18 @@ export function createSessionDaemon({
4178
4876
  clearIdleDisposal(sessionId);
4179
4877
  retryStateBySession.delete(sessionId);
4180
4878
  if (!activeRunStartedAt.has(sessionId)) activeRunStartedAt.set(sessionId, Date.now());
4879
+ // A model turn in a draft (a control's command calling
4880
+ // `sendUserMessage`) ends the draft: Pi has written the session
4881
+ // file with the user message by now, and the turn is real work the
4882
+ // user must be able to see. The session becomes an ordinary one
4883
+ // here, at the first event Pi reports for the turn. The drafting
4884
+ // client hears one last marked event, this busy state without a
4885
+ // `command`, and lets go of the draft; everything after it is
4886
+ // unmarked, so every client lists the session as running.
4887
+ if (draftSessionIds.has(sessionId)) {
4888
+ publish('session.lifecycle', { state: 'busy', runStartedAt: activeRunStartedAt.get(sessionId), serverNow: Date.now() }, sessionId, directory);
4889
+ draftSessionIds.delete(sessionId);
4890
+ }
4181
4891
  publish('session.lifecycle', { state: 'busy', runStartedAt: activeRunStartedAt.get(sessionId), serverNow: Date.now() }, sessionId, directory);
4182
4892
  break;
4183
4893
  case 'agent_end': {
@@ -4210,6 +4920,7 @@ export function createSessionDaemon({
4210
4920
  latestUserMessageIds.delete(sessionId);
4211
4921
  latestAssistantMessageIds.delete(sessionId);
4212
4922
  toolInputBySession.delete(sessionId);
4923
+ toolPartialBySession.delete(sessionId);
4213
4924
  clearToolTimingsForSession(sessionId, { keepCompleted: true });
4214
4925
  extensionToolRenderer.clearSession(sessionId);
4215
4926
  // A missed tool_execution_end must not title later surfaces.
@@ -4360,20 +5071,25 @@ export function createSessionDaemon({
4360
5071
  sessionId: getSessionState().sessionId,
4361
5072
  lastSequence: sequence,
4362
5073
  streamEpoch,
5074
+ // Resident Pi runtimes, starting ones included. A server stops an
5075
+ // idle project daemon only when this is zero.
5076
+ residentSessions: (runtimeRegistry?.size ?? 0) + runtimeStartPromises.size,
4363
5077
  capabilities: [
4364
5078
  // Public stream-lifetime identification: every event, snapshot,
4365
5079
  // and health result carries `streamEpoch`, and session read
4366
5080
  // responses stamp it so clients can reject stale-epoch data.
4367
5081
  'events.streamEpoch',
4368
5082
  'runtime.claim', 'runtime.shutdown',
4369
- 'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
5083
+ 'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.readPersisted', 'sessions.rename', 'sessions.delete',
4370
5084
  'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
4371
5085
  'sessions.steer', 'sessions.followUp', 'sessions.sendReceipt', 'sessions.pendingInput', 'sessions.abort', 'sessions.setModel',
4372
- 'sessions.setThinking', 'sessions.compact', 'sessions.bash', 'sessions.abortBash', 'engines.list', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.models.add', 'providers.status', 'providers.login',
5086
+ 'sessions.setThinking', 'sessions.discardDraft', 'sessions.compact', 'sessions.bash', 'sessions.abortBash', 'sessions.release', 'engines.list', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.models.add', 'providers.status', 'providers.hosts', 'providers.oauth.refresh', 'providers.login',
4373
5087
  'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
4374
5088
  'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
4375
- 'extensions.list', 'extensions.respond', 'extensions.draft',
4376
- 'openUrl.publish', 'archive.publish',
5089
+ 'extensions.list', 'extensions.respond', 'extensions.control', 'extensions.draft', 'extensions.palette',
5090
+ 'extensions.config.list', 'extensions.config.set', 'extensions.packages.remove',
5091
+ 'extensions.packages.install', 'extensions.packages.update',
5092
+ 'openUrl.publish', 'archive.publish', 'plugins.configure',
4377
5093
  'extensions.custom.input', 'extensions.custom.viewport', 'extensions.custom.close', 'extensions.custom.focus', 'extensions.custom.refresh',
4378
5094
  ],
4379
5095
  ...(Number.isInteger(healthMetadata.daemonPid) ? { daemonPid: healthMetadata.daemonPid } : {}),
@@ -4503,6 +5219,16 @@ export function createSessionDaemon({
4503
5219
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
4504
5220
  return;
4505
5221
  }
5222
+ case 'providers.oauth.refresh': {
5223
+ const result = await refreshOAuthTokens(message.payload);
5224
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5225
+ return;
5226
+ }
5227
+ case 'providers.hosts': {
5228
+ const result = await listProviderHosts(message.payload);
5229
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5230
+ return;
5231
+ }
4506
5232
  case 'providers.status': {
4507
5233
  const result = await providerStatus(message.payload?.providerId);
4508
5234
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
@@ -4542,6 +5268,15 @@ export function createSessionDaemon({
4542
5268
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
4543
5269
  return;
4544
5270
  }
5271
+ case 'plugins.configure': {
5272
+ // Private, server-only. A changed enabled set recreates runtimes at
5273
+ // the next safe edge; a state-only change reaches live runtimes
5274
+ // through their `pichamber.onStateChange` listeners.
5275
+ const { enabledChanged, plugins } = await pluginHost.configure(message.payload);
5276
+ const deferred = enabledChanged ? await scheduleRuntimeRecreation() : false;
5277
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: { plugins, enabledChanged, deferred } });
5278
+ return;
5279
+ }
4545
5280
  case 'resources.list': {
4546
5281
  const result = publicResources(await resourceCatalog(message.payload?.directory));
4547
5282
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
@@ -4567,11 +5302,41 @@ export function createSessionDaemon({
4567
5302
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
4568
5303
  return;
4569
5304
  }
5305
+ case 'extensions.config.list': {
5306
+ const result = await listExtensionConfig(message.payload);
5307
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5308
+ return;
5309
+ }
5310
+ case 'extensions.config.set': {
5311
+ const result = await mutateExtensionConfig(message.payload, (target) => extensionConfigService.set(target, message.payload));
5312
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5313
+ return;
5314
+ }
5315
+ case 'extensions.packages.remove': {
5316
+ const result = await mutateExtensionConfig(message.payload, (target) => extensionConfigService.removePackage(target, message.payload));
5317
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5318
+ return;
5319
+ }
5320
+ case 'extensions.packages.install': {
5321
+ const result = await installExtensionPackage(message.payload);
5322
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5323
+ return;
5324
+ }
5325
+ case 'extensions.packages.update': {
5326
+ const result = await updateExtensionPackage(message.payload);
5327
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5328
+ return;
5329
+ }
4570
5330
  case 'extensions.respond': {
4571
5331
  const resolution = await resolveExtensionDialog(message.payload);
4572
5332
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: resolution });
4573
5333
  return;
4574
5334
  }
5335
+ case 'extensions.control': {
5336
+ const result = await runComposerControl(message.payload);
5337
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5338
+ return;
5339
+ }
4575
5340
  case 'extensions.custom.input':
4576
5341
  case 'extensions.custom.viewport':
4577
5342
  case 'extensions.custom.close':
@@ -4592,9 +5357,24 @@ export function createSessionDaemon({
4592
5357
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
4593
5358
  return;
4594
5359
  }
5360
+ case 'extensions.palette': {
5361
+ const terminal = message.payload?.terminal;
5362
+ if (!isTerminalColors(terminal)) {
5363
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The terminal colours are invalid.');
5364
+ }
5365
+ // Pi's theme setting is global; a project's own setting is not read.
5366
+ const settings = createSettingsManager({ cwd: defaultDirectory(), agentDir, projectTrusted: false });
5367
+ // Unreadable settings are a failure, not the system theme: the
5368
+ // browser keeps PiChamber's colours instead of caching a wrong answer.
5369
+ if (settings.drainErrors().length > 0) throw new SessionDaemonProtocolError('PI_SETTINGS_INVALID', 'Pi settings could not be read.');
5370
+ const themeSetting = settings.getThemeSetting();
5371
+ const result = await resolveExtensionPalette({ themeSetting, terminal });
5372
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5373
+ return;
5374
+ }
4595
5375
  case 'extensions.list': {
4596
5376
  const requestedExtensionsDir = message.payload?.directory || message.payload?.cwd;
4597
- const activeRuntime = await ensureRuntime(requestedExtensionsDir ? await resolveDirectory(requestedExtensionsDir) : undefined);
5377
+ const activeRuntime = await ensureRuntime(requestedExtensionsDir ? outsideSandbox(await resolveDirectory(requestedExtensionsDir)) : undefined);
4598
5378
  const extensionSession = activeRuntime.session;
4599
5379
  const extensionPaths = typeof extensionSession?.extensionRunner?.getExtensionPaths === 'function'
4600
5380
  ? extensionSession.extensionRunner.getExtensionPaths()
@@ -4610,6 +5390,8 @@ export function createSessionDaemon({
4610
5390
  directory: activeRuntime.cwd,
4611
5391
  extensions: (Array.isArray(extensionPaths) ? extensionPaths : [])
4612
5392
  .filter((extensionPath) => typeof extensionPath === 'string' && extensionPath.length > 0)
5393
+ // PiChamber's own listener is part of the app, not an extension.
5394
+ .filter((extensionPath) => !isComposerControlsExtensionPath(extensionPath))
4613
5395
  // Opaque id only: server filesystem paths must never reach the
4614
5396
  // browser (see DOCUMENTATION.md route invariants).
4615
5397
  .map((extensionPath) => ({
@@ -4661,15 +5443,20 @@ export function createSessionDaemon({
4661
5443
  const residentRuntimes = new Set();
4662
5444
  if (runtime?.session?.sessionId) residentRuntimes.add(runtime);
4663
5445
  for (const tracked of runtimeRegistry?.listAll?.() ?? []) residentRuntimes.add(tracked);
4664
- const residents = [...residentRuntimes].map((tracked) => ({
4665
- sessionId: tracked?.session?.sessionId,
4666
- directory: typeof tracked?.cwd === 'string' && tracked.cwd.length > 0 ? tracked.cwd : (activeDirectory || cwd),
4667
- busy: tracked?.session?.isStreaming === true
4668
- || tracked?.session?.isCompacting === true
4669
- || activeSessionInputs.has(tracked),
4670
- }));
5446
+ // Drafts are no target: no client shows them.
5447
+ const residents = [...residentRuntimes]
5448
+ .filter((tracked) => !draftSessionIds.has(tracked?.session?.sessionId))
5449
+ .map((tracked) => ({
5450
+ sessionId: tracked?.session?.sessionId,
5451
+ directory: typeof tracked?.cwd === 'string' && tracked.cwd.length > 0 ? tracked.cwd : (defaultDirectory()),
5452
+ busy: tracked?.session?.isStreaming === true
5453
+ || tracked?.session?.isCompacting === true
5454
+ || activeSessionInputs.has(tracked),
5455
+ }));
4671
5456
  const target = resolveOpenRequestSession({
4672
- requestedSessionId: typeof message.payload?.sessionId === 'string' ? message.payload.sessionId : undefined,
5457
+ requestedSessionId: typeof message.payload?.sessionId === 'string' && !draftSessionIds.has(message.payload.sessionId)
5458
+ ? message.payload.sessionId
5459
+ : undefined,
4673
5460
  residents,
4674
5461
  recent: lastPublishedSession,
4675
5462
  });
@@ -4691,6 +5478,15 @@ export function createSessionDaemon({
4691
5478
  });
4692
5479
  return;
4693
5480
  }
5481
+ case 'sessions.release': {
5482
+ writeFrame(socket, {
5483
+ protocolVersion: PROTOCOL_VERSION,
5484
+ kind: 'response',
5485
+ requestId: message.requestId,
5486
+ result: await releaseDirectories(message.payload),
5487
+ });
5488
+ return;
5489
+ }
4694
5490
  case 'sessions.pendingInput': {
4695
5491
  // Daemon-level pending-input state for every session with an open
4696
5492
  // request. No arguments, not session-scoped, never routed to
@@ -4699,7 +5495,7 @@ export function createSessionDaemon({
4699
5495
  protocolVersion: PROTOCOL_VERSION,
4700
5496
  kind: 'response',
4701
5497
  requestId: message.requestId,
4702
- result: { sessions: pendingInput.list(), sequence, streamEpoch },
5498
+ result: { sessions: pendingInput.list().filter((entry) => !draftSessionIds.has(entry?.sessionId)), sequence, streamEpoch },
4703
5499
  });
4704
5500
  return;
4705
5501
  }
@@ -4750,11 +5546,29 @@ export function createSessionDaemon({
4750
5546
  });
4751
5547
  return;
4752
5548
  }
5549
+ case 'sessions.readPersisted': {
5550
+ const detail = await readPersistedSession(message.payload);
5551
+ const frame = { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: detail };
5552
+ if (Buffer.byteLength(JSON.stringify(frame)) > MAX_FRAME_BYTES) {
5553
+ throw new SessionDaemonProtocolError('DAEMON_RESPONSE_TOO_LARGE', 'The daemon response exceeds the IPC frame limit.');
5554
+ }
5555
+ writeFrame(socket, frame);
5556
+ return;
5557
+ }
4753
5558
  case 'sessions.rename': {
4754
5559
  await renameSession(message.payload);
4755
5560
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: {} });
4756
5561
  return;
4757
5562
  }
5563
+ case 'sessions.discardDraft': {
5564
+ // Not in the session-access guard: holding access would make the
5565
+ // disposal it asks for unsafe.
5566
+ const sessionId = message.payload?.sessionId;
5567
+ if (!isValidIdleSessionId(sessionId)) throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The draft session is invalid.');
5568
+ const result = await discardDraftSession(sessionId);
5569
+ writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
5570
+ return;
5571
+ }
4758
5572
  case 'sessions.delete': {
4759
5573
  await deleteSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
4760
5574
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: {} });
@@ -4902,6 +5716,9 @@ export function createSessionDaemon({
4902
5716
  if (commandOnlyRun(message.payload.sessionId, activeRuntime.session)) {
4903
5717
  throw new SessionDaemonProtocolError('SESSION_BUSY', 'An extension command is still running.');
4904
5718
  }
5719
+ // A `!command` is input too: an extension's user_bash handler can
5720
+ // open custom() surfaces, drawn at the size of the tab that ran it.
5721
+ recordInputClient(message.payload.sessionId, message.payload.clientId);
4905
5722
  let started;
4906
5723
  try {
4907
5724
  started = userBash.start({
@@ -5143,8 +5960,10 @@ export function createSessionDaemon({
5143
5960
  compactionStateBySession.clear();
5144
5961
  activeRunStartedAt.clear();
5145
5962
  toolStartedAt.clear();
5963
+ toolPartialBySession.clear();
5146
5964
  completedToolTimings.clear();
5147
5965
  shutdownRequestedBySession.clear();
5966
+ releaseRequestedBySession.clear();
5148
5967
  sendGenerationBySession.clear();
5149
5968
  settledSendGenerationBySession.clear();
5150
5969
  runningToolsBySession.clear();