@pi-chamber/web 1.0.5 → 1.0.6-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 (539) hide show
  1. package/dist/assets/{DiagramView-CrKjR8CR.js → DiagramView-BdDt1SI7.js} +1 -1
  2. package/dist/assets/DiffView-Dk3VIX9E.js +18 -0
  3. package/dist/assets/FileSaveConflictDialog-DpyPjMH1.js +3 -0
  4. package/dist/assets/{FilesView-BRR3N7UA.js → FilesView-CumrwioK.js} +3 -3
  5. package/dist/assets/{GitHubDetailScaffold-C1UHuETI.js → GitHubDetailScaffold-CW2ZqU0Y.js} +3 -3
  6. package/dist/assets/{GitHubLinkPicker-B0O3Vapu.js → GitHubLinkPicker-BjJNQ7Ap.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-DvQDU--z.js → GitHubListPrimitives-BcB-cCTs.js} +1 -1
  8. package/dist/assets/{GitView-wAscrRhO.js → GitView-BoCaX5AO.js} +4 -4
  9. package/dist/assets/{IssuesSurface-mh50UUQ8.js → IssuesSurface-CDZENHrE.js} +3 -3
  10. package/dist/assets/{JsonTreeView-BfErTllU.js → JsonTreeView-DpCgOUXg.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-SXAK4uOu.js → MarkdownRendererImpl-BkT5TUWF.js} +2 -2
  12. package/dist/assets/{PatchDiff-CHr79sJ6.js → PatchDiff-Dcr3EQgA.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-CGpKcLro.js → PierreDiffViewer-o_Edh6ny.js} +3 -3
  14. package/dist/assets/PullRequestsSurface-eSXl6sef.js +2 -0
  15. package/dist/assets/{SessionSwitcherContent-DEAw6v12.js → SessionSwitcherContent-Dm30bfpn.js} +1 -1
  16. package/dist/assets/SessionSwitcherDropdown-CFj9VWSa.js +2 -0
  17. package/dist/assets/SessionUnreadDot-CHlK2awX.js +1 -0
  18. package/dist/assets/SettingsView-CcHRUyev.js +6 -0
  19. package/dist/assets/{SettingsWindow-BiY5FmhZ.js → SettingsWindow-BMzUErrM.js} +1 -1
  20. package/dist/assets/{StickyHorizontalScrollbar-BMITjK4e.js → StickyHorizontalScrollbar-p7EbL2-E.js} +2 -2
  21. package/dist/assets/{ToolOutputDialog-B3RRLhR3.js → ToolOutputDialog-QC8IoeBH.js} +4 -4
  22. package/dist/assets/{ToolPartDiffPreview-D9m_vrht.js → ToolPartDiffPreview-BigGwtul.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-B8lhZGLu.js → VirtualizedFileDiff-DvLCd7Qq.js} +4 -4
  24. package/dist/assets/{Virtualizer-DP6HbEeC.js → Virtualizer-DNJrJKVb.js} +1 -1
  25. package/dist/assets/{appThemeRegistry-gegrE2dq.js → appThemeRegistry-Ca8eGRB9.js} +1 -1
  26. package/dist/assets/{collapsible-9MJx4VhA.js → collapsible-0yfy07W2.js} +1 -1
  27. package/dist/assets/{computeVirtualFileMetrics-Bjhk2CQS.js → computeVirtualFileMetrics-aX6tjjqv.js} +2 -2
  28. package/dist/assets/{contextFileOpenGuard-CsF5Boky.js → contextFileOpenGuard-CZKJuHxf.js} +1 -1
  29. package/dist/assets/{document-attachments-BslE4Ns7.js → document-attachments-CZl9rK1z.js} +5 -5
  30. package/dist/assets/{gitStatusPredicates-B3Zxud6E.js → gitStatusPredicates-3i8CcYWJ.js} +1 -1
  31. package/dist/assets/{githubLink-CbGYxsIq.js → githubLink-BvevcNay.js} +5 -5
  32. package/dist/assets/index-BMdbHCFt.js +1 -0
  33. package/dist/assets/{index-D4n3TVp2.js → index-C2ISrmRR.js} +10 -10
  34. package/dist/assets/index-DgwThEwf.css +1 -0
  35. package/dist/assets/{lua-BgMRiT3U.js → lua-VAEuO923.js} +1 -1
  36. package/dist/assets/main-BM-b2y8p.js +2 -0
  37. package/dist/assets/main-BXZ561E3.js +137 -0
  38. package/dist/assets/{markdown-shiki.worker-DnvH1S1x.js → markdown-shiki.worker-BVA5NZBT.js} +5 -5
  39. package/dist/assets/markdownCore-DbS8DkKw.js +2 -0
  40. package/dist/assets/miniChat-DO3DW6kJ.js +2 -0
  41. package/dist/assets/mobile-BgWLkut6.js +2 -0
  42. package/dist/assets/{nativeFileSave-BJsGPh58.js → nativeFileSave-Bhafll_7.js} +1 -1
  43. package/dist/assets/nsis-LY0VT_u5.js +1 -0
  44. package/dist/assets/permissionStore-zIpxq9Pq.js +1 -0
  45. package/dist/assets/pi-session-focus-preference-ChYVctYk.js +9 -0
  46. package/dist/assets/{registerCustomTheme-DmolaWWZ.js → registerCustomTheme-C-h6lsYW.js} +1 -1
  47. package/dist/assets/{renderDiffWithHighlighter-BhMEWmHn.js → renderDiffWithHighlighter-xlvSvnTf.js} +1 -1
  48. package/dist/assets/renderElectronMiniChatApp-CgVqxKDm.js +2 -0
  49. package/dist/assets/{renderFileWithHighlighter-DUGluXlw.js → renderFileWithHighlighter-CCoYfC-t.js} +1 -1
  50. package/dist/assets/renderMobileApp-CoY1tsk5.js +11 -0
  51. package/dist/assets/ruby-BK5aLJev.js +1 -0
  52. package/dist/assets/runtimeEndpointReset-fozcAShH.js +62 -0
  53. package/dist/assets/runtimeSurface-CJN1oo_1.js +1 -0
  54. package/dist/assets/themeResolver-DrfmQi8i.js +1 -0
  55. package/dist/assets/useAppFontEffects-D_gtiA95.js +215 -0
  56. package/dist/assets/useFilesViewSearch-BUxcZj60.js +7 -0
  57. package/dist/assets/{useGitHubRemoteSearch-DYoLQ4ro.js → useGitHubRemoteSearch-CevR5iLf.js} +1 -1
  58. package/dist/assets/{useSwitcherItems-BS6E199F.js → useSwitcherItems-kaRkXggX.js} +1 -1
  59. package/dist/assets/vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js +1 -0
  60. package/dist/assets/vendor-base-ui-C7vVMZTg.js +1 -0
  61. package/dist/assets/{vendor-beautiful-mermaid-DApbjBp2.js → vendor-beautiful-mermaid-b48gT2g0.js} +1 -1
  62. package/dist/assets/vendor-boot-CoTxysn6.js +65 -0
  63. package/dist/assets/{vendor-capacitor-app-BaupizkW.js → vendor-capacitor-app-NX6DULfp.js} +1 -1
  64. package/dist/assets/{vendor-capacitor-keyboard-9BVxykO7.js → vendor-capacitor-keyboard-DJD81I9f.js} +1 -1
  65. package/dist/assets/{vendor-capacitor-status-bar-BsrUwiaA.js → vendor-capacitor-status-bar-DV24OoQV.js} +1 -1
  66. package/dist/assets/vendor-codemirror-autocomplete-qsuH4Dh-.js +1 -0
  67. package/dist/assets/vendor-codemirror-lang-angular-ZHWyBf7j.js +1 -0
  68. package/dist/assets/vendor-codemirror-lang-cpp-pCTOmv-k.js +1 -0
  69. package/dist/assets/vendor-codemirror-lang-css-2bFuyM70.js +1 -0
  70. package/dist/assets/{vendor-codemirror-lang-go-Crwca_X7.js → vendor-codemirror-lang-go-DrG_c7D7.js} +2 -2
  71. package/dist/assets/vendor-codemirror-lang-html-BV8lrR8v.js +1 -0
  72. package/dist/assets/vendor-codemirror-lang-java-DrsvH6T2.js +1 -0
  73. package/dist/assets/vendor-codemirror-lang-javascript-Dkzl3s07.js +13 -0
  74. package/dist/assets/vendor-codemirror-lang-jinja-8Nn3bnoP.js +1 -0
  75. package/dist/assets/vendor-codemirror-lang-json-CsdmtHhi.js +1 -0
  76. package/dist/assets/vendor-codemirror-lang-less-DJuZ4cZe.js +1 -0
  77. package/dist/assets/vendor-codemirror-lang-liquid-D2RO-Pzr.js +1 -0
  78. package/dist/assets/vendor-codemirror-lang-markdown-C0Zu3b3n.js +1 -0
  79. package/dist/assets/vendor-codemirror-lang-php-CuDtt2Zj.js +1 -0
  80. package/dist/assets/vendor-codemirror-lang-python-Cv2exx_M.js +3 -0
  81. package/dist/assets/vendor-codemirror-lang-rust-C4TxJ6Rg.js +1 -0
  82. package/dist/assets/vendor-codemirror-lang-sass-BmtPz8kf.js +1 -0
  83. package/dist/assets/{vendor-codemirror-lang-sql-B0f-qCZo.js → vendor-codemirror-lang-sql-BF1ZaXqJ.js} +2 -2
  84. package/dist/assets/vendor-codemirror-lang-vue-DZgXrP2k.js +1 -0
  85. package/dist/assets/vendor-codemirror-lang-wast-DsnaGtL_.js +1 -0
  86. package/dist/assets/vendor-codemirror-lang-xml-D8DzzFat.js +1 -0
  87. package/dist/assets/vendor-codemirror-lang-yaml-D5hBv7m6.js +1 -0
  88. package/dist/assets/{vendor-codemirror-language-data-CqU7kHmg.js → vendor-codemirror-language-data-vn2RyN9T.js} +2 -2
  89. package/dist/assets/vendor-codemirror-search-BVCYIV0D.js +2 -0
  90. package/dist/assets/vendor-dompurify-BGCr_sdL.js +3 -0
  91. package/dist/assets/vendor-elkjs-D1S1RCAO.js +24 -0
  92. package/dist/assets/vendor-fuse.js-t_7AcMTv.js +1 -0
  93. package/dist/assets/{vendor-hast-util-to-html-BKBhbTDb.js → vendor-hast-util-to-html-O3stl53j.js} +1 -1
  94. package/dist/assets/{vendor-heic2any-pq-UTQQR.js → vendor-heic2any-sztndhZI.js} +1 -1
  95. package/dist/assets/vendor-lezer-cpp-vqXSn3lv.js +1 -0
  96. package/dist/assets/vendor-lezer-css-JnEzSyZR.js +1 -0
  97. package/dist/assets/{vendor-lezer-go-CHIhCNY6.js → vendor-lezer-go-dD2gQMIL.js} +1 -1
  98. package/dist/assets/{vendor-lezer-html-B3h0MOrG.js → vendor-lezer-html-Cr3U-1pu.js} +1 -1
  99. package/dist/assets/vendor-lezer-java-CRM0IMCo.js +1 -0
  100. package/dist/assets/vendor-lezer-javascript-B3s21DIS.js +1 -0
  101. package/dist/assets/{vendor-lezer-json-BP_UAzLL.js → vendor-lezer-json-DPFM6EBV.js} +1 -1
  102. package/dist/assets/vendor-lezer-lr-Bllrq8hY.js +1 -0
  103. package/dist/assets/vendor-lezer-markdown-6-3PLvXG.js +6 -0
  104. package/dist/assets/vendor-lezer-php-DOyzfHRl.js +1 -0
  105. package/dist/assets/{vendor-lezer-python-EJ4Im4y2.js → vendor-lezer-python-CdHdN5qt.js} +1 -1
  106. package/dist/assets/vendor-lezer-rust-CqnW8EMH.js +1 -0
  107. package/dist/assets/{vendor-lezer-sass-CMi6zfXI.js → vendor-lezer-sass-BbcF4y6A.js} +1 -1
  108. package/dist/assets/{vendor-lezer-xml-0MHMeZDp.js → vendor-lezer-xml-C31AyWoo.js} +1 -1
  109. package/dist/assets/{vendor-lezer-yaml-BE2EFjpA.js → vendor-lezer-yaml-Cv908yC2.js} +1 -1
  110. package/dist/assets/{vendor-lru_map-DOPmc7GU.js → vendor-lru_map-BbiDqlyL.js} +1 -1
  111. package/dist/assets/vendor-marked-Be78pDn1.js +59 -0
  112. package/dist/assets/{vendor-oniguruma-parser-C0D4_9rT.js → vendor-oniguruma-parser-BrbMHgHx.js} +1 -1
  113. package/dist/assets/vendor-oniguruma-to-es-DgwFOwdE.js +94 -0
  114. package/dist/assets/{vendor-pierre-theming-Dgp7B_O4.js → vendor-pierre-theming-BO6EPniU.js} +1 -1
  115. package/dist/assets/vendor-property-information-C40bX6nM.js +1 -0
  116. package/dist/assets/{vendor-qrcode-Dv4uniC1.js → vendor-qrcode-gzL9QFkg.js} +5 -5
  117. package/dist/assets/vendor-react-Bz1tRBxM.js +1 -0
  118. package/dist/assets/{vendor-react-drawio-Duu5LgQA.js → vendor-react-drawio-IYnLUY5N.js} +1 -1
  119. package/dist/assets/vendor-remend-DcBOpbSu.js +24 -0
  120. package/dist/assets/vendor-replit-codemirror-vim-Cwhyn_5f.js +6 -0
  121. package/dist/assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js +34 -0
  122. package/dist/assets/vendor-shiki-BEwTOAFg.js +1 -0
  123. package/dist/assets/{vendor-shikijs-core-CGM_jqPK.js → vendor-shikijs-core-Ck_OPM_T.js} +1 -1
  124. package/dist/assets/{vendor-shikijs-engine-javascript-Cme4830A.js → vendor-shikijs-engine-javascript-DL394yyj.js} +1 -1
  125. package/dist/assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js +3 -0
  126. package/dist/assets/vendor-tailwind-merge-BKkUfl9q.js +1 -0
  127. package/dist/assets/vendor-workbox-window-BBnX5xw4.js +2 -0
  128. package/dist/assets/vendor-zumer-snapdom-SJzqoCHV.js +8 -0
  129. package/dist/assets/vendor-zustand-CXhN0IMY.js +6 -0
  130. package/dist/assets/{web-components-DzQ9ybbb.js → web-components-6ORYp3Iv.js} +1 -1
  131. package/dist/assets/worker-CKCfxIfO.js +153 -0
  132. package/dist/assets/workerFactory-DlGfNFqf.js +1 -0
  133. package/dist/assets/zig-BB16gwVL.js +1 -0
  134. package/dist/index.html +8 -8
  135. package/dist/mini-chat.html +7 -7
  136. package/dist/mobile.html +7 -7
  137. package/package.json +54 -53
  138. package/server/index.js +18 -1
  139. package/server/lib/client-auth/live-revocation.test.js +4 -0
  140. package/server/lib/fs/DOCUMENTATION.md +10 -0
  141. package/server/lib/fs/project-icon.js +243 -0
  142. package/server/lib/fs/project-icon.test.js +114 -0
  143. package/server/lib/fs/routes.js +35 -0
  144. package/server/lib/fs/routes.test.js +74 -0
  145. package/server/lib/git/DOCUMENTATION.md +2 -1
  146. package/server/lib/git/routes.js +11 -3
  147. package/server/lib/git/routes.test.js +80 -0
  148. package/server/lib/git/service.js +38 -3
  149. package/server/lib/git/service.test.js +93 -0
  150. package/server/lib/open-url/DOCUMENTATION.md +35 -0
  151. package/server/lib/open-url/browser-env.js +199 -0
  152. package/server/lib/open-url/browser-env.test.js +147 -0
  153. package/server/lib/open-url/browser-handler.mjs +154 -0
  154. package/server/lib/open-url/browser-handler.test.js +69 -0
  155. package/server/lib/open-url/intake.js +187 -0
  156. package/server/lib/open-url/intake.test.js +75 -0
  157. package/server/lib/pi/extension-protocol.js +149 -0
  158. package/server/lib/pi/extension-protocol.test.js +20 -1
  159. package/server/lib/pi/routes.js +195 -1
  160. package/server/lib/pi/routes.test.js +129 -0
  161. package/server/lib/pi/session-daemon/DOCUMENTATION.md +38 -10
  162. package/server/lib/pi/session-daemon/builtin-extensions.js +14 -4
  163. package/server/lib/pi/session-daemon/daemon-process.js +13 -0
  164. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +6 -1
  165. package/server/lib/pi/session-daemon/extension-bridge.js +40 -6
  166. package/server/lib/pi/session-daemon/extension-custom-host.js +1259 -0
  167. package/server/lib/pi/session-daemon/extension-custom-host.test.js +759 -0
  168. package/server/lib/pi/session-daemon/extension-keybindings.js +21 -0
  169. package/server/lib/pi/session-daemon/extension-keybindings.test.js +37 -0
  170. package/server/lib/pi/session-daemon/extension-message-render.js +7 -4
  171. package/server/lib/pi/session-daemon/extension-message-render.test.js +14 -2
  172. package/server/lib/pi/session-daemon/extension-tool-render.js +7 -0
  173. package/server/lib/pi/session-daemon/extension-tool-render.test.js +26 -0
  174. package/server/lib/pi/session-daemon/open-request.js +60 -0
  175. package/server/lib/pi/session-daemon/open-request.test.js +54 -0
  176. package/server/lib/pi/session-daemon/prompt-preflight.test.js +134 -0
  177. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +21 -4
  178. package/server/lib/pi/session-daemon/session-daemon-bash.e2e.test.js +225 -0
  179. package/server/lib/pi/session-daemon/session-daemon-directory-catalog.e2e.test.js +156 -0
  180. package/server/lib/pi/session-daemon/session-daemon-directory-catalog.test.js +381 -0
  181. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +11 -2
  182. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +30 -4
  183. package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +20 -0
  184. package/server/lib/pi/session-daemon/session-daemon-mcp.e2e.test.js +16 -4
  185. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +7 -2
  186. package/server/lib/pi/session-daemon/session-daemon.js +448 -49
  187. package/server/lib/pi/session-daemon/session-daemon.test.js +91 -4
  188. package/server/lib/pi/session-daemon/session-engine-router.js +9 -3
  189. package/server/lib/pi/session-daemon/session-engine-router.test.js +12 -2
  190. package/server/lib/pi/session-daemon/session-engines.js +7 -2
  191. package/server/lib/pi/session-daemon/session-jsonl.js +170 -75
  192. package/server/lib/pi/session-daemon/session-jsonl.test.js +106 -2
  193. package/server/lib/pi/session-daemon/supervisor.js +4 -0
  194. package/server/lib/pi/session-daemon/user-bash.js +326 -0
  195. package/server/lib/pi/session-daemon/user-bash.test.js +371 -0
  196. package/server/lib/preview/proxy-runtime.js +140 -45
  197. package/server/lib/preview/proxy-runtime.test.js +174 -3
  198. package/server/lib/preview/proxy-runtime.websocket.test.js +89 -0
  199. package/server/lib/relay/tunnel-host.js +1 -0
  200. package/server/lib/security/request-security.js +37 -0
  201. package/server/lib/security/request-security.test.js +54 -0
  202. package/server/lib/security/server-network-host.js +107 -0
  203. package/server/lib/security/server-network-host.test.js +70 -0
  204. package/server/lib/server-browser/DOCUMENTATION.md +243 -0
  205. package/server/lib/server-browser/browser-tab.js +524 -0
  206. package/server/lib/server-browser/chrome-executable.js +138 -0
  207. package/server/lib/server-browser/chrome-launch.js +138 -0
  208. package/server/lib/server-browser/dev-servers.js +288 -0
  209. package/server/lib/server-browser/dev-servers.test.js +152 -0
  210. package/server/lib/server-browser/downloads.js +75 -0
  211. package/server/lib/server-browser/frame-policy.js +183 -0
  212. package/server/lib/server-browser/frame-policy.test.js +98 -0
  213. package/server/lib/server-browser/network-guard.js +235 -0
  214. package/server/lib/server-browser/page-scripts.js +209 -0
  215. package/server/lib/server-browser/runtime.integration.test.js +474 -0
  216. package/server/lib/server-browser/runtime.js +300 -0
  217. package/server/lib/server-browser/runtime.test.js +50 -0
  218. package/server/lib/server-browser/server-browser.js +431 -0
  219. package/server/lib/server-browser/server-browser.test.js +975 -0
  220. package/server/lib/server-browser/tab-input.js +241 -0
  221. package/server/lib/server-browser/tab-prompts.js +125 -0
  222. package/server/lib/server-browser/tab-stream.js +252 -0
  223. package/server/lib/server-browser/uploads.js +98 -0
  224. package/server/lib/stt/runtime.js +4 -1
  225. package/server/lib/stt/runtime.test.js +43 -0
  226. package/server/lib/terminal/runtime.js +4 -1
  227. package/server/lib/terminal/runtime.test.js +41 -0
  228. package/server/lib/ui-auth/DOCUMENTATION.md +29 -1
  229. package/server/lib/ui-auth/ui-auth.js +1 -0
  230. package/server/lib/ui-auth/ui-auth.test.js +9 -1
  231. package/server/lib/workspace/host.js +20 -3
  232. package/dist/assets/DiffView-CSonR3pr.js +0 -18
  233. package/dist/assets/FileSaveConflictDialog-Cun0LIbj.js +0 -3
  234. package/dist/assets/PullRequestsSurface-CfaOpeZn.js +0 -2
  235. package/dist/assets/SessionSwitcherDropdown-BSutduo7.js +0 -2
  236. package/dist/assets/SessionUnreadDot-Dav_rix1.js +0 -1
  237. package/dist/assets/SettingsView-CQJkOPJh.js +0 -6
  238. package/dist/assets/abap-BdImnpbu.js +0 -1
  239. package/dist/assets/actionscript-3-CoDkCxhg.js +0 -1
  240. package/dist/assets/ada-bCR0ucgS.js +0 -1
  241. package/dist/assets/angular-html-CU67Zn6k.js +0 -1
  242. package/dist/assets/angular-ts-BwZT4LLn.js +0 -1
  243. package/dist/assets/apache-Pmp26Uib.js +0 -1
  244. package/dist/assets/apex-D8_7TLub.js +0 -1
  245. package/dist/assets/apl-dKokRX4l.js +0 -1
  246. package/dist/assets/applescript-Co6uUVPk.js +0 -1
  247. package/dist/assets/ara-BRHolxvo.js +0 -1
  248. package/dist/assets/asciidoc-Ve4PFQV2.js +0 -1
  249. package/dist/assets/asm-D_Q5rh1f.js +0 -1
  250. package/dist/assets/astro-CbQHKStN.js +0 -1
  251. package/dist/assets/awk-DMzUqQB5.js +0 -1
  252. package/dist/assets/ballerina-BFfxhgS-.js +0 -1
  253. package/dist/assets/bat-BkioyH1T.js +0 -1
  254. package/dist/assets/beancount-k_qm7-4y.js +0 -1
  255. package/dist/assets/berry-uYugtg8r.js +0 -1
  256. package/dist/assets/bibtex-CHM0blh-.js +0 -1
  257. package/dist/assets/bicep-Bmn6On1c.js +0 -1
  258. package/dist/assets/bird2-DPOp833l.js +0 -1
  259. package/dist/assets/blade-D4QpJJKB.js +0 -1
  260. package/dist/assets/bsl-BO_Y6i37.js +0 -1
  261. package/dist/assets/c-BIGW1oBm.js +0 -1
  262. package/dist/assets/c3-eo99z4R2.js +0 -1
  263. package/dist/assets/cadence-Bv_4Rxtq.js +0 -1
  264. package/dist/assets/cairo-KRGpt6FW.js +0 -1
  265. package/dist/assets/clarity-D53aC0YG.js +0 -1
  266. package/dist/assets/clojure-P80f7IUj.js +0 -1
  267. package/dist/assets/cmake-D1j8_8rp.js +0 -1
  268. package/dist/assets/cobol-nwyudZeR.js +0 -1
  269. package/dist/assets/codeowners-Bp6g37R7.js +0 -1
  270. package/dist/assets/codeql-DsOJ9woJ.js +0 -1
  271. package/dist/assets/coffee-Ch7k5sss.js +0 -1
  272. package/dist/assets/common-lisp-Cg-RD9OK.js +0 -1
  273. package/dist/assets/coq-DkFqJrB1.js +0 -1
  274. package/dist/assets/cpp-CofmeUqb.js +0 -1
  275. package/dist/assets/crystal-tKQVLTB8.js +0 -1
  276. package/dist/assets/csharp-COcwbKMJ.js +0 -1
  277. package/dist/assets/css-DPfMkruS.js +0 -1
  278. package/dist/assets/csv-fuZLfV_i.js +0 -1
  279. package/dist/assets/cue-D82EKSYY.js +0 -1
  280. package/dist/assets/cypher-COkxafJQ.js +0 -1
  281. package/dist/assets/d-85-TOEBH.js +0 -1
  282. package/dist/assets/dart-CF10PKvl.js +0 -1
  283. package/dist/assets/dax-CEL-wOlO.js +0 -1
  284. package/dist/assets/desktop-BmXAJ9_W.js +0 -1
  285. package/dist/assets/diff-D97Zzqfu.js +0 -1
  286. package/dist/assets/docker-BcOcwvcX.js +0 -1
  287. package/dist/assets/dotenv-Da5cRb03.js +0 -1
  288. package/dist/assets/dream-maker-BtqSS_iP.js +0 -1
  289. package/dist/assets/edge-BkV0erSs.js +0 -1
  290. package/dist/assets/elixir-CDX3lj18.js +0 -1
  291. package/dist/assets/elm-DbKCFpqz.js +0 -1
  292. package/dist/assets/emacs-lisp-C9XAeP06.js +0 -1
  293. package/dist/assets/erb-B12qg9BL.js +0 -1
  294. package/dist/assets/erlang-DsQrWhSR.js +0 -1
  295. package/dist/assets/fennel-BYunw83y.js +0 -1
  296. package/dist/assets/fish-BvzEVeQv.js +0 -1
  297. package/dist/assets/fluent-C4IJs8-o.js +0 -1
  298. package/dist/assets/fortran-fixed-form-CkoXwp7k.js +0 -1
  299. package/dist/assets/fortran-free-form-BxgE0vQu.js +0 -1
  300. package/dist/assets/fsharp-CXgrBDvD.js +0 -1
  301. package/dist/assets/gdresource-BOOCDP_w.js +0 -1
  302. package/dist/assets/gdscript-C5YyOfLZ.js +0 -1
  303. package/dist/assets/gdshader-DkwncUOv.js +0 -1
  304. package/dist/assets/genie-D0YGMca9.js +0 -1
  305. package/dist/assets/gherkin-DyxjwDmM.js +0 -1
  306. package/dist/assets/git-commit-F4YmCXRG.js +0 -1
  307. package/dist/assets/git-rebase-r7XF79zn.js +0 -1
  308. package/dist/assets/gleam-BspZqrRM.js +0 -1
  309. package/dist/assets/glimmer-js-Rg0-pVw9.js +0 -1
  310. package/dist/assets/glimmer-ts-U6CK756n.js +0 -1
  311. package/dist/assets/glsl-DplSGwfg.js +0 -1
  312. package/dist/assets/gn-n2N0HUVH.js +0 -1
  313. package/dist/assets/gnuplot-DdkO51Og.js +0 -1
  314. package/dist/assets/go-CxLEBnE3.js +0 -1
  315. package/dist/assets/graphql-ChdNCCLP.js +0 -1
  316. package/dist/assets/groovy-gcz8RCvz.js +0 -1
  317. package/dist/assets/hack-CaT9iCJl.js +0 -1
  318. package/dist/assets/haml-B8DHNrY2.js +0 -1
  319. package/dist/assets/handlebars-BL8al0AC.js +0 -1
  320. package/dist/assets/haskell-Df6bDoY_.js +0 -1
  321. package/dist/assets/haxe-CzTSHFRz.js +0 -1
  322. package/dist/assets/hcl-BWvSN4gD.js +0 -1
  323. package/dist/assets/hjson-D5-asLiD.js +0 -1
  324. package/dist/assets/hlsl-D3lLCCz7.js +0 -1
  325. package/dist/assets/html-GMplVEZG.js +0 -1
  326. package/dist/assets/html-derivative-BFtXZ54Q.js +0 -1
  327. package/dist/assets/http-jrhK8wxY.js +0 -1
  328. package/dist/assets/hurl-irOxFIW8.js +0 -1
  329. package/dist/assets/hxml-Bvhsp5Yf.js +0 -1
  330. package/dist/assets/hy-DFXneXwc.js +0 -1
  331. package/dist/assets/imba-DGztddWO.js +0 -1
  332. package/dist/assets/index-B0h6_x5N.js +0 -1
  333. package/dist/assets/index-BwoW_-vk.css +0 -1
  334. package/dist/assets/ini-BEwlwnbL.js +0 -1
  335. package/dist/assets/java-CylS5w8V.js +0 -1
  336. package/dist/assets/javascript-wDzz0qaB.js +0 -1
  337. package/dist/assets/jinja-4LBKfQ-Z.js +0 -1
  338. package/dist/assets/jison-wvAkD_A8.js +0 -1
  339. package/dist/assets/json-Cp-IABpG.js +0 -1
  340. package/dist/assets/json5-C9tS-k6U.js +0 -1
  341. package/dist/assets/jsonc-Des-eS-w.js +0 -1
  342. package/dist/assets/jsonl-DcaNXYhu.js +0 -1
  343. package/dist/assets/jsonnet-DFQXde-d.js +0 -1
  344. package/dist/assets/jssm-C2t-YnRu.js +0 -1
  345. package/dist/assets/jsx-g9-lgVsj.js +0 -1
  346. package/dist/assets/julia-CxzCAyBv.js +0 -1
  347. package/dist/assets/just-Cw27pwNe.js +0 -1
  348. package/dist/assets/kdl-DV7GczEv.js +0 -1
  349. package/dist/assets/kotlin-BdnUsdx6.js +0 -1
  350. package/dist/assets/kusto-DZf3V79B.js +0 -1
  351. package/dist/assets/latex-CWtU0Tv5.js +0 -1
  352. package/dist/assets/lean-BZvkOJ9d.js +0 -1
  353. package/dist/assets/less-B1dDrJ26.js +0 -1
  354. package/dist/assets/liquid-DYVedYrR.js +0 -1
  355. package/dist/assets/llvm-DjAJT7YJ.js +0 -1
  356. package/dist/assets/log-2UxHyX5q.js +0 -1
  357. package/dist/assets/logo-BtOb2qkB.js +0 -1
  358. package/dist/assets/lua-BaeVxFsk.js +0 -1
  359. package/dist/assets/luau-C-HG3fhB.js +0 -1
  360. package/dist/assets/main-C6i4ph9N.js +0 -2
  361. package/dist/assets/main-r5elIPBi.js +0 -136
  362. package/dist/assets/make-CHLpvVh8.js +0 -1
  363. package/dist/assets/markdown-Cvjx9yec.js +0 -1
  364. package/dist/assets/markdownCore-C2YQ3Z0q.js +0 -2
  365. package/dist/assets/marko-CnJfTvn9.js +0 -1
  366. package/dist/assets/matlab-D7o27uSR.js +0 -1
  367. package/dist/assets/mdc-BMNejdWA.js +0 -1
  368. package/dist/assets/mdx-Cmh6b_Ma.js +0 -1
  369. package/dist/assets/mermaid-mWjccvbQ.js +0 -1
  370. package/dist/assets/miniChat-d_GCHoIf.js +0 -2
  371. package/dist/assets/mipsasm-CKIfxQSi.js +0 -1
  372. package/dist/assets/mobile-BJ3tgyKd.js +0 -2
  373. package/dist/assets/mojo-rZm6bMo-.js +0 -1
  374. package/dist/assets/moonbit-_H4v1dQx.js +0 -1
  375. package/dist/assets/move-IF9eRakj.js +0 -1
  376. package/dist/assets/narrat-DRg8JJMk.js +0 -1
  377. package/dist/assets/nextflow-Zz6hmt5N.js +0 -1
  378. package/dist/assets/nextflow-groovy-BeH2EWoN.js +0 -1
  379. package/dist/assets/nginx-BpAMiNFr.js +0 -1
  380. package/dist/assets/nim-CVrawwO9.js +0 -1
  381. package/dist/assets/nix-CwoSXNpI.js +0 -1
  382. package/dist/assets/nsis-LdVXkNf5.js +0 -1
  383. package/dist/assets/nushell-Cz2AlsmD.js +0 -1
  384. package/dist/assets/objective-c-DXmwc3jG.js +0 -1
  385. package/dist/assets/objective-cpp-CLxacb5B.js +0 -1
  386. package/dist/assets/ocaml-C0hk2d4L.js +0 -1
  387. package/dist/assets/odin-BBf5iR-q.js +0 -1
  388. package/dist/assets/openscad-C4EeE6gA.js +0 -1
  389. package/dist/assets/pascal-D93ZcfNL.js +0 -1
  390. package/dist/assets/perl-C0TMdlhV.js +0 -1
  391. package/dist/assets/permissionStore-B9Hkrqny.js +0 -1
  392. package/dist/assets/php-Dhbhpdrm.js +0 -1
  393. package/dist/assets/pi-session-focus-preference-BFnGFuvP.js +0 -9
  394. package/dist/assets/pkl-u5AG7uiY.js +0 -1
  395. package/dist/assets/plsql-ChMvpjG-.js +0 -1
  396. package/dist/assets/po-BTJTHyun.js +0 -1
  397. package/dist/assets/polar-C0HS_06l.js +0 -1
  398. package/dist/assets/postcss-CXtECtnM.js +0 -1
  399. package/dist/assets/powerquery-CEu0bR-o.js +0 -1
  400. package/dist/assets/powershell-Dpen1YoG.js +0 -1
  401. package/dist/assets/prisma-Dd19v3D-.js +0 -1
  402. package/dist/assets/prolog-CbFg5uaA.js +0 -1
  403. package/dist/assets/proto-C7zT0LnQ.js +0 -1
  404. package/dist/assets/pug-CGlum2m_.js +0 -1
  405. package/dist/assets/puppet-BMWR74SV.js +0 -1
  406. package/dist/assets/purescript-CklMAg4u.js +0 -1
  407. package/dist/assets/python-B6aJPvgy.js +0 -1
  408. package/dist/assets/qml-3beO22l8.js +0 -1
  409. package/dist/assets/qmldir-C8lEn-DE.js +0 -1
  410. package/dist/assets/qss-IeuSbFQv.js +0 -1
  411. package/dist/assets/r-Dspwwk_N.js +0 -1
  412. package/dist/assets/racket-BqYA7rlc.js +0 -1
  413. package/dist/assets/raku-DXvB9xmW.js +0 -1
  414. package/dist/assets/razor-Uh8Bk_45.js +0 -1
  415. package/dist/assets/reg-C-SQnVFl.js +0 -1
  416. package/dist/assets/regexp-CDVJQ6XC.js +0 -1
  417. package/dist/assets/rel-C3B-1QV4.js +0 -1
  418. package/dist/assets/renderElectronMiniChatApp-Bap5OwgB.js +0 -2
  419. package/dist/assets/renderMobileApp-DJbslvby.js +0 -11
  420. package/dist/assets/riscv-BM1_JUlF.js +0 -1
  421. package/dist/assets/ron-D8l8udqQ.js +0 -1
  422. package/dist/assets/rosmsg-BJDFO7_C.js +0 -1
  423. package/dist/assets/rst-BrH8l1NY.js +0 -1
  424. package/dist/assets/ruby-B2Rjki9n.js +0 -1
  425. package/dist/assets/ruby-Dw2BHqvy.js +0 -1
  426. package/dist/assets/runtimeEndpointReset-D22U_Vjs.js +0 -62
  427. package/dist/assets/runtimeSurface-k1Eit61v.js +0 -1
  428. package/dist/assets/rust-B1yitclQ.js +0 -1
  429. package/dist/assets/sas-cz2c8ADy.js +0 -1
  430. package/dist/assets/sass-Cj5Yp3dK.js +0 -1
  431. package/dist/assets/scala-C151Ov-r.js +0 -1
  432. package/dist/assets/scheme-C98Dy4si.js +0 -1
  433. package/dist/assets/scss-OYdSNvt2.js +0 -1
  434. package/dist/assets/sdbl-DVxCFoDh.js +0 -1
  435. package/dist/assets/shaderlab-Dg9Lc6iA.js +0 -1
  436. package/dist/assets/shellscript-Yzrsuije.js +0 -1
  437. package/dist/assets/shellsession-BADoaaVG.js +0 -1
  438. package/dist/assets/smalltalk-BERRCDM3.js +0 -1
  439. package/dist/assets/solidity-rGO070M0.js +0 -1
  440. package/dist/assets/soy-Brmx7dQM.js +0 -1
  441. package/dist/assets/sparql-rVzFXLq3.js +0 -1
  442. package/dist/assets/splunk-BtCnVYZw.js +0 -1
  443. package/dist/assets/sql-BLtJtn59.js +0 -1
  444. package/dist/assets/ssh-config-_ykCGR6B.js +0 -1
  445. package/dist/assets/stata-BH5u7GGu.js +0 -1
  446. package/dist/assets/stylus-BEDo0Tqx.js +0 -1
  447. package/dist/assets/surrealql-Bq5Q-fJD.js +0 -1
  448. package/dist/assets/svelte-C_ipcX3V.js +0 -1
  449. package/dist/assets/swift-D82vCrfD.js +0 -1
  450. package/dist/assets/system-verilog-CnnmHF94.js +0 -1
  451. package/dist/assets/systemd-4A_iFExJ.js +0 -1
  452. package/dist/assets/talonscript-CkByrt1z.js +0 -1
  453. package/dist/assets/tasl-QIJgUcNo.js +0 -1
  454. package/dist/assets/tcl-dwOrl1Do.js +0 -1
  455. package/dist/assets/templ-P3uqSqPl.js +0 -1
  456. package/dist/assets/terraform-BETggiCN.js +0 -1
  457. package/dist/assets/tex-idrVyKtj.js +0 -1
  458. package/dist/assets/themeResolver-yJ9XpNMI.js +0 -1
  459. package/dist/assets/toml-vGWfd6FD.js +0 -1
  460. package/dist/assets/ts-tags-zn1MmPIZ.js +0 -1
  461. package/dist/assets/tsv-B_m7g4N7.js +0 -1
  462. package/dist/assets/tsx-COt5Ahok.js +0 -1
  463. package/dist/assets/turtle-BsS91CYL.js +0 -1
  464. package/dist/assets/twig-DNn4PbVi.js +0 -1
  465. package/dist/assets/typescript-BPQ3VLAy.js +0 -1
  466. package/dist/assets/typespec-BGHnOYBU.js +0 -1
  467. package/dist/assets/typst-DHCkPAjA.js +0 -1
  468. package/dist/assets/useAppFontEffects-CqHhRKmN.js +0 -212
  469. package/dist/assets/useFilesViewSearch-CqoYEK0U.js +0 -7
  470. package/dist/assets/v-BcVCzyr7.js +0 -1
  471. package/dist/assets/vala-CsfeWuGM.js +0 -1
  472. package/dist/assets/vb-D17OF-Vu.js +0 -1
  473. package/dist/assets/vendor-aparajita-capacitor-secure-storage-BDrMx_CE.js +0 -1
  474. package/dist/assets/vendor-base-ui-CKRUCG-f.js +0 -1
  475. package/dist/assets/vendor-boot-EC6IyLt1.js +0 -69
  476. package/dist/assets/vendor-codemirror-autocomplete-CGpAsPWp.js +0 -1
  477. package/dist/assets/vendor-codemirror-lang-angular-CDJoHJSY.js +0 -1
  478. package/dist/assets/vendor-codemirror-lang-cpp-BmHofQls.js +0 -1
  479. package/dist/assets/vendor-codemirror-lang-css-RM2HqXZ0.js +0 -1
  480. package/dist/assets/vendor-codemirror-lang-html-CHSHUpwq.js +0 -1
  481. package/dist/assets/vendor-codemirror-lang-java-lhQXgWu0.js +0 -1
  482. package/dist/assets/vendor-codemirror-lang-javascript-Dw4kFO4e.js +0 -13
  483. package/dist/assets/vendor-codemirror-lang-jinja-_pAC3UTN.js +0 -1
  484. package/dist/assets/vendor-codemirror-lang-json-B-b1vAv-.js +0 -1
  485. package/dist/assets/vendor-codemirror-lang-less-xIgOi1ze.js +0 -1
  486. package/dist/assets/vendor-codemirror-lang-liquid-CP49m5dB.js +0 -1
  487. package/dist/assets/vendor-codemirror-lang-markdown-BTht2ATe.js +0 -1
  488. package/dist/assets/vendor-codemirror-lang-php-BguZDhaO.js +0 -1
  489. package/dist/assets/vendor-codemirror-lang-python-CH6_em9L.js +0 -3
  490. package/dist/assets/vendor-codemirror-lang-rust-EG_DtGyi.js +0 -1
  491. package/dist/assets/vendor-codemirror-lang-sass-BknY5Qpo.js +0 -1
  492. package/dist/assets/vendor-codemirror-lang-vue-CyGn9snv.js +0 -1
  493. package/dist/assets/vendor-codemirror-lang-wast-CsFfSyyB.js +0 -1
  494. package/dist/assets/vendor-codemirror-lang-xml-Cdan_Jp1.js +0 -1
  495. package/dist/assets/vendor-codemirror-lang-yaml-COI5hck8.js +0 -1
  496. package/dist/assets/vendor-codemirror-search-DUfSCF9S.js +0 -2
  497. package/dist/assets/vendor-dompurify-r8glNMJW.js +0 -2
  498. package/dist/assets/vendor-elkjs-D27273Ms.js +0 -24
  499. package/dist/assets/vendor-fuse.js-Dw8P0qyA.js +0 -1
  500. package/dist/assets/vendor-lezer-cpp-DMZOJzBa.js +0 -1
  501. package/dist/assets/vendor-lezer-css-DUkkbMp7.js +0 -1
  502. package/dist/assets/vendor-lezer-java-tMazV_6X.js +0 -1
  503. package/dist/assets/vendor-lezer-javascript-ctwLWf4v.js +0 -1
  504. package/dist/assets/vendor-lezer-lr-B8TQctNw.js +0 -1
  505. package/dist/assets/vendor-lezer-markdown-aGLZf_3h.js +0 -6
  506. package/dist/assets/vendor-lezer-php-D5zCNzlt.js +0 -1
  507. package/dist/assets/vendor-lezer-rust-DO5c7OtA.js +0 -1
  508. package/dist/assets/vendor-marked-CX41MkDF.js +0 -59
  509. package/dist/assets/vendor-oniguruma-to-es-DLBnFDCE.js +0 -94
  510. package/dist/assets/vendor-property-information-rJCbAzvX.js +0 -1
  511. package/dist/assets/vendor-react-DASdDPIk.js +0 -1
  512. package/dist/assets/vendor-remend-BWYYytN3.js +0 -22
  513. package/dist/assets/vendor-replit-codemirror-vim-AnOuN8yJ.js +0 -39
  514. package/dist/assets/vendor-shiki-Bbf2GEcE.js +0 -2
  515. package/dist/assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js +0 -3
  516. package/dist/assets/vendor-tailwind-merge-CPcsbTWB.js +0 -1
  517. package/dist/assets/vendor-workbox-window-BIl4cyR9.js +0 -2
  518. package/dist/assets/vendor-zumer-snapdom-Btyu_Xi2.js +0 -8
  519. package/dist/assets/vendor-zustand-CUi8eEds.js +0 -6
  520. package/dist/assets/verilog-BQ8w6xss.js +0 -1
  521. package/dist/assets/vhdl-CeAyd5Ju.js +0 -1
  522. package/dist/assets/viml-CJc9bBzg.js +0 -1
  523. package/dist/assets/vue-DN_0RTcg.js +0 -1
  524. package/dist/assets/vue-html-AaS7Mt5G.js +0 -1
  525. package/dist/assets/vue-vine-CQOfvN7w.js +0 -1
  526. package/dist/assets/vyper-CDx5xZoG.js +0 -1
  527. package/dist/assets/wasm-MzD3tlZU.js +0 -1
  528. package/dist/assets/wenyan-BV7otONQ.js +0 -1
  529. package/dist/assets/wgsl-Dx-B1_4e.js +0 -1
  530. package/dist/assets/wikitext-BhOHFoWU.js +0 -1
  531. package/dist/assets/wit-5i3qLPDT.js +0 -1
  532. package/dist/assets/wolfram-lXgVvXCa.js +0 -1
  533. package/dist/assets/worker-BBk7yuNN.js +0 -153
  534. package/dist/assets/workerFactory-tw7cIdmV.js +0 -1
  535. package/dist/assets/xml-sdJ4AIDG.js +0 -1
  536. package/dist/assets/xsl-CtQFsRM5.js +0 -1
  537. package/dist/assets/yaml-Buea-lGh.js +0 -1
  538. package/dist/assets/zenscript-DVFEvuxE.js +0 -1
  539. package/dist/assets/zig-VOosw3JB.js +0 -1
@@ -0,0 +1,1259 @@
1
+ // Hosts Pi `ctx.ui.custom()` components for PiChamber sessions.
2
+ //
3
+ // Components render on the daemon exactly as Pi would render them; browsers
4
+ // receive the rendered lines and send keys back. One module owns the whole
5
+ // surface lifetime: factory, focus, overlay layout, input, terminal size,
6
+ // frames, and every way a surface can end (docs/plans/pi-extension-custom.md).
7
+ //
8
+ // Pi has one terminal; PiChamber has two sizes. Inline surfaces replace the
9
+ // composer and render at the composer column width. Overlays lay out on the
10
+ // "screen", the whole chat pane, with Pi's own `resolveOverlayLayout`, so an
11
+ // edge-anchored overlay can use the empty space beside the chat column.
12
+ // `tui.terminal` reports the screen, as it does in Pi.
13
+ //
14
+ // Several devices can watch one session, each with its own size. One client
15
+ // drives the size: the last one that acted (typed, clicked, focused, closed,
16
+ // or claimed on open); before anyone acts, the first one that reports. Other
17
+ // clients' sizes are kept but ignored, so idle screens never make the layout
18
+ // flap between sizes.
19
+
20
+ import { createRequire } from 'node:module';
21
+ import { dirname, join } from 'node:path';
22
+ import { fileURLToPath, pathToFileURL } from 'node:url';
23
+ import { randomUUID } from 'node:crypto';
24
+
25
+ import { MAX_CUSTOM_FRAME_LINES, MAX_CUSTOM_INPUT_CHARS, MAX_CUSTOM_INPUT_ITEMS, MAX_CUSTOM_LINE_CHARS } from '../extension-protocol.js';
26
+
27
+ const MAX_SURFACES_PER_SESSION = 16;
28
+ const MAX_FRAME_LINES = MAX_CUSTOM_FRAME_LINES;
29
+ const MAX_LINE_CHARS = MAX_CUSTOM_LINE_CHARS;
30
+ const MAX_TITLE_CHARS = 128;
31
+ const MAX_BLOCKED_MESSAGE_CHARS = 256;
32
+ const MAX_CLIENTS_PER_SESSION = 16;
33
+ const MAX_INPUT_ITEMS = MAX_CUSTOM_INPUT_ITEMS;
34
+ const MAX_INPUT_CHARS = MAX_CUSTOM_INPUT_CHARS;
35
+ const FRAME_INTERVAL_MS = 33;
36
+ const SIZE_SETTLE_MS = 150;
37
+
38
+ const CUSTOM_VIEWPORT_LIMITS = Object.freeze({
39
+ columns: [20, 200],
40
+ screenColumns: [20, 400],
41
+ rows: [10, 80],
42
+ });
43
+ const DEFAULT_CUSTOM_VIEWPORT = Object.freeze({ columns: 100, screenColumns: 140, rows: 30 });
44
+
45
+ const clampInt = (value, [min, max]) => Math.max(min, Math.min(max, Math.floor(value)));
46
+
47
+ /** Clamped viewport, or `undefined` when the value is not a viewport. */
48
+ export const normalizeCustomViewport = (value) => {
49
+ if (!value || typeof value !== 'object') return undefined;
50
+ const { columns, rows } = value;
51
+ if (!Number.isFinite(columns) || !Number.isFinite(rows)) return undefined;
52
+ const screenColumns = Number.isFinite(value.screenColumns) ? value.screenColumns : columns;
53
+ return {
54
+ columns: clampInt(columns, CUSTOM_VIEWPORT_LIMITS.columns),
55
+ screenColumns: clampInt(screenColumns, CUSTOM_VIEWPORT_LIMITS.screenColumns),
56
+ rows: clampInt(rows, CUSTOM_VIEWPORT_LIMITS.rows),
57
+ };
58
+ };
59
+
60
+ // Pi's TUI classes are not all exported from the package index: the overlay
61
+ // layout lives on `TuiBase` and the app keybindings in the SDK's
62
+ // `core/keybindings.js`. Both are loaded from the installed SDK so they are
63
+ // the same module instances the SDK and extensions use.
64
+ let piTuiPromise;
65
+ const loadPiTui = () => {
66
+ piTuiPromise ??= (async () => {
67
+ const sdkEntry = fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent'));
68
+ const sdkDist = dirname(sdkEntry);
69
+ const requireFromSdk = createRequire(join(dirname(sdkDist), 'package.json'));
70
+ const tuiEntry = requireFromSdk.resolve('@earendil-works/pi-tui');
71
+ const [tuiIndex, tuiModule, keybindingsModule] = await Promise.all([
72
+ import(pathToFileURL(tuiEntry).href),
73
+ import(pathToFileURL(join(dirname(tuiEntry), 'tui.js')).href),
74
+ import(pathToFileURL(join(sdkDist, 'core', 'keybindings.js')).href),
75
+ ]);
76
+ return {
77
+ visibleWidth: tuiIndex.visibleWidth,
78
+ sliceByColumn: tuiIndex.sliceByColumn,
79
+ setKeybindings: tuiIndex.setKeybindings,
80
+ cursorMarker: tuiModule.CURSOR_MARKER,
81
+ fakeCursorStart: tuiModule.FAKE_CURSOR_START,
82
+ fakeCursorEnd: tuiModule.FAKE_CURSOR_END,
83
+ resolveOverlayLayout: (options, height, columns, rows) => tuiModule.TuiBase.prototype.resolveOverlayLayout
84
+ .call(tuiModule.TuiBase.prototype, options, height, columns, rows),
85
+ dispatchMouseEvent: tuiModule.dispatchMouseEvent,
86
+ retargetMouseEvent: tuiModule.retargetMouseEvent,
87
+ KeybindingsManager: keybindingsModule.KeybindingsManager,
88
+ };
89
+ })();
90
+ piTuiPromise.catch(() => {
91
+ piTuiPromise = undefined;
92
+ });
93
+ return piTuiPromise;
94
+ };
95
+
96
+ const OTHER_APC = /\x1b_[^\x07\x1b]*(?:\x07|\x1b\\)/g;
97
+ /** An escape sequence that is whole at the start of a string: CSI, OSC/APC/DCS with its terminator, or a two-byte escape. */
98
+ const WHOLE_ESCAPE = /^\x1b(?:\[[0-?]*[ -/]*[@-~]|[\]_P^X][^\x07\x1b]*(?:\x07|\x1b\\)|[ -OQ-WYZ\\`-~])/;
99
+
100
+ /**
101
+ * A line cut to the frame cap. The cut never leaves half an escape sequence
102
+ * behind, since the browser would show its tail as text.
103
+ */
104
+ const capLine = (text) => {
105
+ if (text.length <= MAX_LINE_CHARS) return text;
106
+ let cut = text.slice(0, MAX_LINE_CHARS);
107
+ const escape = cut.lastIndexOf('\x1b');
108
+ if (escape !== -1 && !WHOLE_ESCAPE.test(cut.slice(escape))) cut = cut.slice(0, escape);
109
+ // Nor half a surrogate pair.
110
+ const last = cut.charCodeAt(cut.length - 1);
111
+ return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;
112
+ };
113
+ // SGR mouse report, as a terminal sends it in mouse mode: ESC [ < button ;
114
+ // column ; row, then M (press or motion) or m (release); cells are 1-based.
115
+ const SGR_MOUSE = /^\x1b\[<(\d{1,3});(\d{1,4});(\d{1,4})([Mm])$/;
116
+ const MOUSE_BUTTONS = Object.freeze(['left', 'middle', 'right', 'none']);
117
+ // Pi's double-click window (pi-tui `DOUBLE_CLICK_INTERVAL_MS`).
118
+ const DOUBLE_CLICK_MS = 500;
119
+ // The same escapes the browser's `parseAnsiSegments` drops (CSI, OSC, APC,
120
+ // DCS/SOS/PM strings, and two-character escapes), so grapheme indices in
121
+ // `cells` match the text the browser draws.
122
+ const ANSI = /\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|_[^\x07\x1b]*(?:\x07|\x1b\\)|[PX^_][^\x1b]*\x1b\\|[@-Z\\-_])/g;
123
+ const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
124
+
125
+ // Browsers draw emoji and CJK at whatever width the font gives them; Pi
126
+ // counts them as two cells (or zero). The frame carries Pi's width for every
127
+ // grapheme that is not one cell wide, keyed by grapheme index, so the browser
128
+ // can draw fixed cell boxes and keep borders aligned.
129
+ const wideCellsFor = (line, visibleWidth) => {
130
+ const plain = line.replace(ANSI, '');
131
+ if (/^[\x20-\x7e]*$/.test(plain)) return undefined;
132
+ let cells;
133
+ let index = 0;
134
+ for (const { segment } of graphemes.segment(plain)) {
135
+ const width = visibleWidth(segment);
136
+ if (width !== 1) (cells ??= {})[index] = width;
137
+ index += 1;
138
+ }
139
+ return cells;
140
+ };
141
+
142
+ const sameLayout = (a, b) => (a === b) || (a && b && a.row === b.row && a.col === b.col && a.width === b.width && a.height === b.height);
143
+ const sameCursor = (a, b) => (a === b) || (a && b && a.row === b.row && a.col === b.col);
144
+ const sameCells = (a, b) => (a === b) || (a && b && JSON.stringify(a) === JSON.stringify(b));
145
+
146
+ /** Pi `blocked.kind` to the pending-input kind the sidebar and alerts use. */
147
+ const pendingKindFor = (blocked) => (blocked?.kind === 'permission' ? 'approval' : 'input');
148
+
149
+ const normalizeBlocked = (blocked) => {
150
+ if (!blocked || typeof blocked !== 'object') return undefined;
151
+ const kind = ['permission', 'question', 'auth'].includes(blocked.kind) ? blocked.kind : undefined;
152
+ if (!kind) return undefined;
153
+ const message = typeof blocked.message === 'string'
154
+ ? blocked.message.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, MAX_BLOCKED_MESSAGE_CHARS)
155
+ : '';
156
+ return { kind, message };
157
+ };
158
+
159
+ const terminalOnlyError = () => new Error('PiChamber sessions do not hand the terminal to extensions.');
160
+
161
+ /**
162
+ * Creates the per-daemon `custom()` host. Dependencies are injected so the
163
+ * session daemon keeps thin call sites and tests can drive it directly.
164
+ */
165
+ export const createExtensionCustomHost = ({
166
+ publish,
167
+ publishTransient = publish,
168
+ pendingInput,
169
+ directoryForSession,
170
+ redactLine = (line) => line,
171
+ theme,
172
+ agentDir,
173
+ describeOrigin = () => undefined,
174
+ /** The client that sent the session's latest prompt, which opened the surface. */
175
+ openerClientFor = () => undefined,
176
+ onSettled = () => {},
177
+ onError = () => {},
178
+ loadTui = loadPiTui,
179
+ setTimer = setTimeout,
180
+ clearTimer = clearTimeout,
181
+ } = {}) => {
182
+ /** sessionId -> session state */
183
+ const sessions = new Map();
184
+ let keybindings;
185
+ let tui;
186
+
187
+ const ensureTui = async () => {
188
+ if (tui) return tui;
189
+ const loaded = await loadTui();
190
+ if (!keybindings && loaded.KeybindingsManager) {
191
+ try {
192
+ keybindings = agentDir ? loaded.KeybindingsManager.create(agentDir) : new loaded.KeybindingsManager();
193
+ } catch {
194
+ keybindings = new loaded.KeybindingsManager();
195
+ }
196
+ // pi-tui components (SelectList, Input, Editor) read the process-wide
197
+ // keybindings, as they do under Pi's interactive mode.
198
+ try {
199
+ loaded.setKeybindings?.(keybindings);
200
+ } catch {
201
+ // A missing global setter only loses user remaps.
202
+ }
203
+ }
204
+ tui = loaded;
205
+ return tui;
206
+ };
207
+
208
+ const stateFor = (sessionId) => {
209
+ let state = sessions.get(sessionId);
210
+ if (!state) {
211
+ state = {
212
+ sessionId,
213
+ surfaces: [],
214
+ focus: null,
215
+ viewport: { ...DEFAULT_CUSTOM_VIEWPORT },
216
+ clients: new Map(),
217
+ driver: null,
218
+ opener: null,
219
+ sizeTimer: undefined,
220
+ renderTimer: undefined,
221
+ lastFlushAt: 0,
222
+ dirty: new Set(),
223
+ z: 0,
224
+ // The pointer gesture in progress (press target or capture), and the
225
+ // last click, for click counts.
226
+ mouse: null,
227
+ lastClick: null,
228
+ };
229
+ sessions.set(sessionId, state);
230
+ }
231
+ return state;
232
+ };
233
+
234
+ const dropStateIfEmpty = (state) => {
235
+ if (state.surfaces.length > 0) return;
236
+ if (state.renderTimer) clearTimer(state.renderTimer);
237
+ if (state.sizeTimer) clearTimer(state.sizeTimer);
238
+ // The driver and client sizes outlive surfaces only while something is
239
+ // open; the next surface starts from the last applied viewport.
240
+ state.renderTimer = undefined;
241
+ state.sizeTimer = undefined;
242
+ state.dirty.clear();
243
+ state.focus = null;
244
+ state.opener = null;
245
+ };
246
+
247
+ const findSurface = (state, surfaceId) => state?.surfaces.find((surface) => surface.id === surfaceId);
248
+
249
+ /**
250
+ * The overlay options, called fresh like Pi does. An options function
251
+ * that throws keeps the last options it returned: the extension's error
252
+ * must never escape into a render timer, where it would end the daemon.
253
+ */
254
+ const resolveOptions = (surface) => {
255
+ if (typeof surface.options !== 'function') {
256
+ return surface.options && typeof surface.options === 'object' ? surface.options : undefined;
257
+ }
258
+ try {
259
+ const value = surface.options();
260
+ surface.lastOptions = value && typeof value === 'object' ? value : undefined;
261
+ } catch (error) {
262
+ if (!surface.optionsFailed) onError(surface.sessionId, 'overlayOptions', error);
263
+ surface.optionsFailed = true;
264
+ }
265
+ return surface.lastOptions;
266
+ };
267
+
268
+ const isVisibleAt = (state, surface) => {
269
+ if (surface.hidden) return false;
270
+ if (!surface.overlay) return true;
271
+ const visible = resolveOptions(surface)?.visible;
272
+ if (typeof visible !== 'function') return true;
273
+ try {
274
+ return visible(state.viewport.screenColumns, state.viewport.rows) !== false;
275
+ } catch {
276
+ return true;
277
+ }
278
+ };
279
+
280
+ // ---------------------------------------------------------------- focus
281
+
282
+ const setComponentFocused = (component, focused) => {
283
+ if (!component || typeof component !== 'object' || !('focused' in component)) return;
284
+ try {
285
+ component.focused = focused;
286
+ } catch {
287
+ // A read-only focus flag only loses the cursor.
288
+ }
289
+ };
290
+
291
+ /** Topmost visible capturing overlay, else the top inline surface. */
292
+ const topFocusable = (state, except) => {
293
+ let best = null;
294
+ for (const surface of state.surfaces) {
295
+ if (surface === except || !surface.overlay || !surface.capturing || !isVisibleAt(state, surface)) continue;
296
+ if (!best || surface.z > best.z) best = surface;
297
+ }
298
+ if (best) return best;
299
+ for (let index = state.surfaces.length - 1; index >= 0; index -= 1) {
300
+ const surface = state.surfaces[index];
301
+ if (surface !== except && !surface.overlay) return surface;
302
+ }
303
+ return null;
304
+ };
305
+
306
+ const publishMeta = (state, surface) => {
307
+ publish('extension.custom', projectMeta(state, surface), state.sessionId, directoryForSession(state.sessionId));
308
+ };
309
+
310
+ const focusSurface = (state, surface, component = surface?.component) => {
311
+ const previous = state.focus;
312
+ if (previous?.surface === surface && previous?.component === component) return;
313
+ if (previous) setComponentFocused(previous.component, false);
314
+ state.focus = surface ? { surface, component } : null;
315
+ if (surface) setComponentFocused(component, true);
316
+ // Focus moves the cursor, so both surfaces render again.
317
+ if (previous?.surface && previous.surface !== surface && state.surfaces.includes(previous.surface)) {
318
+ publishMeta(state, previous.surface);
319
+ scheduleRender(state, previous.surface);
320
+ }
321
+ if (surface && previous?.surface !== surface) {
322
+ publishMeta(state, surface);
323
+ }
324
+ if (surface) scheduleRender(state, surface);
325
+ };
326
+
327
+ // ---------------------------------------------------------------- frames
328
+
329
+ const projectMeta = (state, surface) => ({
330
+ surfaceId: surface.id,
331
+ ...(surface.parentId ? { parentId: surface.parentId } : {}),
332
+ title: surface.title,
333
+ mode: surface.overlay ? 'overlay' : 'inline',
334
+ capturing: surface.capturing,
335
+ hidden: surface.hidden,
336
+ focused: state.focus?.surface === surface,
337
+ z: surface.z,
338
+ ...(surface.blocked ? { blocked: { ...surface.blocked } } : {}),
339
+ });
340
+
341
+ const renderSurface = (state, surface) => {
342
+ const { visibleWidth, sliceByColumn, cursorMarker, fakeCursorStart, fakeCursorEnd, resolveOverlayLayout } = tui;
343
+ const { columns, screenColumns, rows } = state.viewport;
344
+ const options = surface.overlay ? (resolveOptions(surface) ?? (Number.isFinite(surface.component?.width) ? { width: surface.component.width } : undefined)) : undefined;
345
+ const sizing = surface.overlay ? resolveOverlayLayout(options, 0, screenColumns, rows) : undefined;
346
+ const width = surface.overlay ? Math.max(1, sizing.width) : columns;
347
+ let raw;
348
+ try {
349
+ raw = surface.component.render(width);
350
+ } catch (error) {
351
+ onError(state.sessionId, 'render', error);
352
+ // A component that cannot render is closed, never left half-shown.
353
+ // Deferred so a failure during open still finds its owner.
354
+ queueMicrotask(() => {
355
+ if (!state.surfaces.includes(surface)) return;
356
+ if (surface.settle) surface.settle('cancelled');
357
+ else removeSurface(state, surface, 'cancelled');
358
+ });
359
+ return null;
360
+ }
361
+ let lines = Array.isArray(raw) ? raw : [];
362
+ if (sizing?.maxHeight !== undefined && lines.length > sizing.maxHeight) lines = lines.slice(0, sizing.maxHeight);
363
+ lines = lines.slice(0, MAX_FRAME_LINES);
364
+ let cursor = null;
365
+ const focusedHere = state.focus?.surface === surface;
366
+ lines = lines.map((line, row) => {
367
+ let text = capLine(String(line ?? ''));
368
+ const marker = text.indexOf(cursorMarker);
369
+ if (marker !== -1) {
370
+ if (focusedHere && !cursor) cursor = { row, col: visibleWidth(text.slice(0, marker)) };
371
+ text = text.split(cursorMarker).join('');
372
+ }
373
+ // Fake cursors (unfocused editors) become reverse video, as Pi draws
374
+ // them; every other private APC marker is dropped.
375
+ text = text.split(fakeCursorStart).join('\x1b[7m').split(fakeCursorEnd).join('\x1b[27m').replace(OTHER_APC, '');
376
+ // Pi cuts overlay lines to the declared width before compositing.
377
+ if (surface.overlay && visibleWidth(text) > width) text = sliceByColumn(text, 0, width, true);
378
+ return redactLine(text);
379
+ });
380
+ const cells = lines.map((line) => wideCellsFor(line, visibleWidth));
381
+ const layout = surface.overlay
382
+ ? (() => {
383
+ const placed = resolveOverlayLayout(options, lines.length, screenColumns, rows);
384
+ return { row: placed.row, col: placed.col, width, height: lines.length };
385
+ })()
386
+ : null;
387
+ return {
388
+ lines,
389
+ cells,
390
+ cursor,
391
+ layout,
392
+ visible: isVisibleAt(state, surface),
393
+ columns: width,
394
+ screenColumns,
395
+ rows,
396
+ };
397
+ };
398
+
399
+ /** Full frame payload for a surface's current frame. */
400
+ const fullFrame = (surface) => {
401
+ const frame = surface.frame;
402
+ const cells = {};
403
+ let hasCells = false;
404
+ frame.cells.forEach((value, index) => {
405
+ if (value) {
406
+ cells[index] = value;
407
+ hasCells = true;
408
+ }
409
+ });
410
+ return {
411
+ surfaceId: surface.id,
412
+ version: frame.version,
413
+ length: frame.lines.length,
414
+ lines: [...frame.lines],
415
+ ...(hasCells ? { cells } : {}),
416
+ cursor: frame.cursor,
417
+ layout: frame.layout,
418
+ visible: frame.visible,
419
+ columns: frame.columns,
420
+ screenColumns: frame.screenColumns,
421
+ rows: frame.rows,
422
+ };
423
+ };
424
+
425
+ const flushSurface = (state, surface, { forceFull = false } = {}) => {
426
+ const next = renderSurface(state, surface);
427
+ if (!next) return;
428
+ const previous = surface.frame;
429
+ const sameShape = previous
430
+ && previous.columns === next.columns
431
+ && previous.screenColumns === next.screenColumns
432
+ && previous.rows === next.rows;
433
+ const changes = [];
434
+ if (previous) {
435
+ for (let index = 0; index < next.lines.length; index += 1) {
436
+ if (previous.lines[index] !== next.lines[index] || !sameCells(previous.cells[index], next.cells[index])) {
437
+ changes.push(index);
438
+ }
439
+ }
440
+ }
441
+ const unchanged = previous
442
+ && sameShape
443
+ && changes.length === 0
444
+ && previous.lines.length === next.lines.length
445
+ && sameCursor(previous.cursor, next.cursor)
446
+ && sameLayout(previous.layout, next.layout)
447
+ && previous.visible === next.visible;
448
+ if (unchanged && !forceFull) return;
449
+ const version = (previous?.version ?? 0) + 1;
450
+ surface.frame = { ...next, version };
451
+ const directory = directoryForSession(state.sessionId);
452
+ if (!previous || forceFull || !sameShape || changes.length * 2 > next.lines.length) {
453
+ publishTransient('extension.custom.frame', fullFrame(surface), state.sessionId, directory);
454
+ return;
455
+ }
456
+ publishTransient('extension.custom.frame', {
457
+ surfaceId: surface.id,
458
+ version,
459
+ base: previous.version,
460
+ length: next.lines.length,
461
+ changes: changes.map((index) => ({
462
+ index,
463
+ line: next.lines[index],
464
+ ...(next.cells[index] ? { cells: next.cells[index] } : {}),
465
+ })),
466
+ cursor: next.cursor,
467
+ layout: next.layout,
468
+ visible: next.visible,
469
+ columns: next.columns,
470
+ screenColumns: next.screenColumns,
471
+ rows: next.rows,
472
+ }, state.sessionId, directory);
473
+ };
474
+
475
+ /** Closes a surface that failed, as one whose render throws. */
476
+ const failSurface = (state, surface, stage, error) => {
477
+ onError(state.sessionId, stage, error);
478
+ if (!state.surfaces.includes(surface)) return;
479
+ if (surface.settle) surface.settle('cancelled');
480
+ else removeSurface(state, surface, 'cancelled');
481
+ };
482
+
483
+ /** Renders and publishes one surface; a failure closes it, never throws. */
484
+ const safeFlushSurface = (state, surface, options) => {
485
+ try {
486
+ flushSurface(state, surface, options);
487
+ } catch (error) {
488
+ failSurface(state, surface, 'render', error);
489
+ }
490
+ };
491
+
492
+ const flush = (state) => {
493
+ state.renderTimer = undefined;
494
+ state.lastFlushAt = Date.now();
495
+ const dirty = [...state.dirty];
496
+ state.dirty.clear();
497
+ for (const surface of dirty) {
498
+ if (state.surfaces.includes(surface)) safeFlushSurface(state, surface);
499
+ }
500
+ };
501
+
502
+ function scheduleRender(state, surface) {
503
+ if (!state.surfaces.includes(surface)) return;
504
+ state.dirty.add(surface);
505
+ if (state.renderTimer) return;
506
+ // The first change after a quiet spell draws on the next tick, so a key
507
+ // shows at once; changes within 33 ms of the last draw wait out the rest
508
+ // of it, so an animating component still sends about 30 frames a second.
509
+ // Changes made in one turn (a batch of keys) still share one draw.
510
+ const sinceLast = Date.now() - (state.lastFlushAt ?? 0);
511
+ state.renderTimer = setTimer(() => flush(state), Math.max(0, FRAME_INTERVAL_MS - sinceLast));
512
+ }
513
+
514
+ const scheduleAll = (state) => {
515
+ for (const surface of state.surfaces) scheduleRender(state, surface);
516
+ };
517
+
518
+ // ---------------------------------------------------------------- surfaces
519
+
520
+ const removeSurface = (state, surface, reason) => {
521
+ const index = state.surfaces.indexOf(surface);
522
+ if (index === -1) return false;
523
+ // Nested overlays a component opened go with it.
524
+ for (const child of state.surfaces.filter((candidate) => candidate.parentId === surface.id)) {
525
+ removeSurface(state, child, reason);
526
+ }
527
+ state.surfaces.splice(state.surfaces.indexOf(surface), 1);
528
+ state.dirty.delete(surface);
529
+ if (surface.pendingRegistered) {
530
+ surface.pendingRegistered = false;
531
+ try {
532
+ pendingInput?.close(state.sessionId, surface.id);
533
+ } catch {
534
+ // Pending-input bookkeeping never blocks closing a surface.
535
+ }
536
+ }
537
+ publish('extension.custom.dismiss', { surfaceId: surface.id, reason }, state.sessionId, directoryForSession(state.sessionId));
538
+ if (state.focus?.surface === surface) {
539
+ setComponentFocused(state.focus.component, false);
540
+ state.focus = null;
541
+ const next = topFocusable(state);
542
+ if (next) focusSurface(state, next);
543
+ }
544
+ dropStateIfEmpty(state);
545
+ return true;
546
+ };
547
+
548
+ const disposeComponent = (component) => {
549
+ try {
550
+ component?.dispose?.();
551
+ } catch {
552
+ // Pi ignores dispose errors too.
553
+ }
554
+ };
555
+
556
+ /** True when `candidate` is `root` or an overlay nested under it. */
557
+ const isWithin = (state, candidate, root) => {
558
+ for (let current = candidate, depth = 0; current && depth <= state.surfaces.length; depth += 1) {
559
+ if (current === root) return true;
560
+ current = current.parentId ? state.surfaces.find((surface) => surface.id === current.parentId) : undefined;
561
+ }
562
+ return false;
563
+ };
564
+
565
+ /**
566
+ * Keys reach a capturing surface, or a non-capturing one while it or an
567
+ * overlay it opened holds focus: in Pi `nonCapturing` only keeps an
568
+ * overlay from taking focus when shown, and `handle.focus()` (or a click
569
+ * the component answers with `focus`) gives it the keys.
570
+ */
571
+ const takesKeys = (state, surface) => (
572
+ surface.capturing || (state.focus?.surface != null && isWithin(state, state.focus.surface, surface))
573
+ );
574
+
575
+ /**
576
+ * Overlays one `custom()` call opened through `tui.showOverlay`: children
577
+ * of its surface, or, while its factory still runs, the ones it showed so
578
+ * far. Never another call's overlays.
579
+ */
580
+ const ownedOverlays = (state, owner) => state.surfaces.filter((surface) => (
581
+ owner.surface ? surface.parentId === owner.surface.id : owner.early.includes(surface)
582
+ ));
583
+
584
+ /**
585
+ * A factory may show overlays from its constructor, before its own surface
586
+ * exists (Pi's overlay focus demo does). They belong to that surface: its
587
+ * Close and its end take them along, and keys sent to it reach them.
588
+ */
589
+ const adoptEarlyOverlays = (state, owner) => {
590
+ for (const surface of owner.early.splice(0)) {
591
+ if (!state.surfaces.includes(surface)) continue;
592
+ surface.parentId = owner.surface.id;
593
+ if (surface.pendingRegistered) {
594
+ surface.pendingRegistered = false;
595
+ try {
596
+ pendingInput?.close(state.sessionId, surface.id);
597
+ } catch {
598
+ // Pending-input bookkeeping never blocks showing a surface.
599
+ }
600
+ }
601
+ publishMeta(state, surface);
602
+ }
603
+ };
604
+
605
+ /** Removes overlays a factory showed when its own surface never opens. */
606
+ const dropEarlyOverlays = (state, owner, reason) => {
607
+ for (const surface of owner.early.splice(0)) removeSurface(state, surface, reason);
608
+ };
609
+
610
+ /** False once `clear()` dropped this state (the session closed or reloaded). */
611
+ const isLive = (state) => sessions.get(state.sessionId) === state;
612
+
613
+ const addSurface = (state, fields) => {
614
+ if (!isLive(state)) throw new Error('The session closed before the extension surface opened.');
615
+ state.z += 1;
616
+ const surface = {
617
+ sessionId: state.sessionId,
618
+ id: `custom-${randomUUID()}`,
619
+ parentId: fields.parentId ?? null,
620
+ component: fields.component,
621
+ overlay: fields.overlay,
622
+ options: fields.options,
623
+ title: fields.title,
624
+ blocked: fields.blocked,
625
+ capturing: true,
626
+ hidden: false,
627
+ z: state.z,
628
+ frame: null,
629
+ settle: fields.settle ?? null,
630
+ pendingRegistered: false,
631
+ };
632
+ // Through resolveOptions, so these options are the fallback if a later
633
+ // call throws.
634
+ surface.capturing = !(surface.overlay && resolveOptions(surface)?.nonCapturing === true);
635
+ state.surfaces.push(surface);
636
+ if (surface.capturing && !surface.parentId) {
637
+ try {
638
+ pendingInput?.open({
639
+ sessionId: state.sessionId,
640
+ directory: directoryForSession(state.sessionId),
641
+ requestId: surface.id,
642
+ kind: pendingKindFor(surface.blocked),
643
+ });
644
+ surface.pendingRegistered = true;
645
+ } catch {
646
+ // Pending-input bookkeeping never blocks showing a surface.
647
+ }
648
+ }
649
+ try {
650
+ // Focusing publishes the surface; otherwise publish it here.
651
+ if (surface.capturing && isVisibleAt(state, surface)) focusSurface(state, surface);
652
+ else publishMeta(state, surface);
653
+ flushSurface(state, surface);
654
+ } catch (error) {
655
+ // Never leave a surface half-open: it would hold its pending-input
656
+ // entry and block idle disposal with nothing able to close it.
657
+ removeSurface(state, surface, 'cancelled');
658
+ throw error;
659
+ }
660
+ return surface;
661
+ };
662
+
663
+ const makeHandle = (state, surface) => ({
664
+ hide: () => {
665
+ if (!state.surfaces.includes(surface)) return;
666
+ if (surface.settle) {
667
+ // Pi removes a hidden custom() overlay but leaves its promise to
668
+ // `done()`. Keep the record so `done()` still settles it, and let
669
+ // the user close it from the pending strip.
670
+ surface.hidden = true;
671
+ if (state.focus?.surface === surface) focusSurface(state, topFocusable(state, surface));
672
+ publishMeta(state, surface);
673
+ scheduleRender(state, surface);
674
+ return;
675
+ }
676
+ removeSurface(state, surface, 'done');
677
+ },
678
+ setHidden: (hidden) => {
679
+ const next = Boolean(hidden);
680
+ if (surface.hidden === next || !state.surfaces.includes(surface)) return;
681
+ surface.hidden = next;
682
+ if (next && state.focus?.surface === surface) focusSurface(state, topFocusable(state, surface));
683
+ if (!next && surface.capturing && isVisibleAt(state, surface)) {
684
+ state.z += 1;
685
+ surface.z = state.z;
686
+ focusSurface(state, surface);
687
+ }
688
+ publishMeta(state, surface);
689
+ scheduleRender(state, surface);
690
+ },
691
+ isHidden: () => surface.hidden,
692
+ focus: () => {
693
+ if (!state.surfaces.includes(surface) || !isVisibleAt(state, surface)) return;
694
+ state.z += 1;
695
+ surface.z = state.z;
696
+ focusSurface(state, surface);
697
+ publishMeta(state, surface);
698
+ },
699
+ unfocus: (options) => {
700
+ if (state.focus?.surface !== surface) return;
701
+ const target = options?.target;
702
+ const owner = target ? state.surfaces.find((candidate) => candidate.component === target) : undefined;
703
+ focusSurface(state, owner ?? topFocusable(state, surface));
704
+ },
705
+ isFocused: () => state.focus?.surface === surface,
706
+ getBounds: () => {
707
+ const layout = surface.frame?.layout;
708
+ return layout ? { ...layout } : undefined;
709
+ },
710
+ });
711
+
712
+ /** The TUI handed to factories. `owner` is filled once the surface exists. */
713
+ const createTui = (state, owner, title) => {
714
+ const terminal = {
715
+ get columns() {
716
+ return state.viewport.screenColumns;
717
+ },
718
+ get rows() {
719
+ return state.viewport.rows;
720
+ },
721
+ kittyProtocolActive: false,
722
+ write: () => {},
723
+ };
724
+ const stub = {
725
+ terminal,
726
+ mode: 'regular',
727
+ children: [],
728
+ fullRedraws: 0,
729
+ requestRender: () => {
730
+ if (owner.surface) scheduleRender(state, owner.surface);
731
+ for (const surface of ownedOverlays(state, owner)) scheduleRender(state, surface);
732
+ },
733
+ setFocus: (component) => {
734
+ if (!component) {
735
+ focusSurface(state, null);
736
+ return;
737
+ }
738
+ const target = state.surfaces.find((surface) => surface.component === component);
739
+ if (target) {
740
+ focusSurface(state, target);
741
+ return;
742
+ }
743
+ // A child component of this surface, such as an Input inside a
744
+ // Container: keys go to it directly, as in Pi.
745
+ if (owner.surface) focusSurface(state, owner.surface, component);
746
+ },
747
+ getFocusedComponent: () => state.focus?.component ?? null,
748
+ showOverlay: (component, options) => {
749
+ // After the session closed, or after this command ended (an
750
+ // extension may keep its tui and call this from a timer), a late
751
+ // overlay is never shown: its parent is gone. The handle stays
752
+ // callable as one for a removed overlay.
753
+ if (!isLive(state) || owner.settled) return makeHandle(state, { hidden: false, frame: null });
754
+ const surface = addSurface(state, {
755
+ component,
756
+ overlay: true,
757
+ options,
758
+ title,
759
+ parentId: owner.surface?.id ?? null,
760
+ });
761
+ // Shown by the factory before its own surface exists; adopted by
762
+ // that surface once it opens (see adoptEarlyOverlays).
763
+ if (!owner.surface) owner.early.push(surface);
764
+ return makeHandle(state, surface);
765
+ },
766
+ hideOverlay: () => {
767
+ const nested = ownedOverlays(state, owner).sort((a, b) => b.z - a.z)[0];
768
+ if (nested) removeSurface(state, nested, 'done');
769
+ },
770
+ hasOverlay: () => state.surfaces.some((surface) => surface.overlay && isVisibleAt(state, surface)),
771
+ addChild: () => {},
772
+ removeChild: () => {},
773
+ clear: () => {},
774
+ invalidate: () => {},
775
+ render: () => [],
776
+ getShowHardwareCursor: () => false,
777
+ setShowHardwareCursor: () => {},
778
+ getClearOnShrink: () => false,
779
+ setClearOnShrink: () => {},
780
+ addInputListener: () => () => {},
781
+ removeInputListener: () => {},
782
+ onTerminalColorSchemeChange: () => () => {},
783
+ setTerminalColorSchemeNotifications: () => {},
784
+ queryTerminalBackgroundColor: async () => undefined,
785
+ queryTerminalColorScheme: async () => undefined,
786
+ // D1: the terminal is never handed to an extension.
787
+ stop: () => {
788
+ throw terminalOnlyError();
789
+ },
790
+ start: () => {
791
+ throw terminalOnlyError();
792
+ },
793
+ };
794
+ return stub;
795
+ };
796
+
797
+ // ---------------------------------------------------------------- custom()
798
+
799
+ /** `ctx.ui.custom()` for one session. */
800
+ const open = async (sessionId, factory, options) => {
801
+ if (typeof factory !== 'function') return undefined;
802
+ await ensureTui();
803
+ const state = stateFor(sessionId);
804
+ const topLevel = state.surfaces.filter((surface) => surface.settle).length;
805
+ if (topLevel >= MAX_SURFACES_PER_SESSION) {
806
+ throw new Error('Too many extension surfaces are open in this session.');
807
+ }
808
+ const origin = describeOrigin(sessionId);
809
+ const title = typeof origin === 'string' && origin.trim().length > 0
810
+ ? origin.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, MAX_TITLE_CHARS)
811
+ : 'Extension';
812
+ const owner = { surface: null, early: [], settled: false };
813
+ return new Promise((resolve, reject) => {
814
+ let component;
815
+ const finish = (result, reason) => {
816
+ if (owner.settled) return;
817
+ owner.settled = true;
818
+ const surface = owner.surface;
819
+ if (surface) removeSurface(state, surface, reason);
820
+ else dropEarlyOverlays(state, owner, reason);
821
+ disposeComponent(component);
822
+ resolve(result);
823
+ onSettled(sessionId);
824
+ };
825
+ const done = (result) => finish(result, 'done');
826
+ const stub = createTui(state, owner, title);
827
+ Promise.resolve()
828
+ .then(() => factory(stub, theme, keybindings, done))
829
+ .then((created) => {
830
+ component = created;
831
+ // done() called during construction: Pi never shows the component.
832
+ if (owner.settled) {
833
+ disposeComponent(component);
834
+ return;
835
+ }
836
+ // The session closed or reloaded while an async factory ran: its
837
+ // state is gone, so the surface would be unreachable. Resolve as
838
+ // the session closing would have.
839
+ if (!component || typeof component.render !== 'function' || !isLive(state)) {
840
+ owner.settled = true;
841
+ if (isLive(state)) dropEarlyOverlays(state, owner, 'cancelled');
842
+ if (component && !isLive(state)) disposeComponent(component);
843
+ resolve(undefined);
844
+ onSettled(sessionId);
845
+ return;
846
+ }
847
+ const overlay = options?.overlay === true;
848
+ const overlayOptions = overlay ? options?.overlayOptions : undefined;
849
+ preferOpener(state);
850
+ owner.surface = addSurface(state, {
851
+ component,
852
+ overlay,
853
+ // Pi falls back to the component's own width without options.
854
+ options: overlayOptions ?? (overlay && Number.isFinite(component.width) ? { width: component.width } : undefined),
855
+ title,
856
+ blocked: normalizeBlocked(options?.blocked),
857
+ settle: (reason) => finish(undefined, reason),
858
+ });
859
+ adoptEarlyOverlays(state, owner);
860
+ if (overlay && typeof options?.onHandle === 'function') {
861
+ try {
862
+ options.onHandle(makeHandle(state, owner.surface));
863
+ } catch (error) {
864
+ onError(sessionId, 'onHandle', error);
865
+ }
866
+ }
867
+ })
868
+ .catch((error) => {
869
+ if (owner.settled) return;
870
+ owner.settled = true;
871
+ if (owner.surface) removeSurface(state, owner.surface, 'cancelled');
872
+ else dropEarlyOverlays(state, owner, 'cancelled');
873
+ onError(sessionId, 'factory', error);
874
+ reject(error);
875
+ onSettled(sessionId);
876
+ });
877
+ });
878
+ };
879
+
880
+ // ---------------------------------------------------------------- size
881
+
882
+ const applyViewport = (state) => {
883
+ if (state.sizeTimer) clearTimer(state.sizeTimer);
884
+ state.sizeTimer = setTimer(() => {
885
+ state.sizeTimer = undefined;
886
+ try {
887
+ resizeTo(state);
888
+ } catch (error) {
889
+ // Unreachable in practice (extension calls are guarded); a timer
890
+ // callback must still never throw into the daemon process.
891
+ onError(state.sessionId, 'resize', error);
892
+ }
893
+ }, SIZE_SETTLE_MS);
894
+ };
895
+
896
+ /** Applies the driver's viewport once it settled. */
897
+ const resizeTo = (state) => {
898
+ const next = state.driver ? state.clients.get(state.driver) : undefined;
899
+ if (!next) return;
900
+ const current = state.viewport;
901
+ if (next.columns === current.columns && next.screenColumns === current.screenColumns && next.rows === current.rows) return;
902
+ state.viewport = { ...next };
903
+ for (const surface of state.surfaces) {
904
+ try {
905
+ surface.component.invalidate?.();
906
+ } catch {
907
+ // A failing invalidate still renders at the new size.
908
+ }
909
+ }
910
+ // `visible()` can change with the size; focus follows what is shown.
911
+ if (state.focus?.surface && !isVisibleAt(state, state.focus.surface)) focusSurface(state, topFocusable(state));
912
+ else if (!state.focus) {
913
+ const next = topFocusable(state);
914
+ if (next) focusSurface(state, next);
915
+ }
916
+ scheduleAll(state);
917
+ };
918
+
919
+ const recordClient = (state, clientId, viewport, claim) => {
920
+ if (typeof clientId !== 'string' || clientId.length === 0 || clientId.length > 128) return;
921
+ const normalized = normalizeCustomViewport(viewport);
922
+ if (normalized) {
923
+ state.clients.delete(clientId);
924
+ state.clients.set(clientId, normalized);
925
+ while (state.clients.size > MAX_CLIENTS_PER_SESSION) {
926
+ const oldest = state.clients.keys().next().value;
927
+ state.clients.delete(oldest);
928
+ if (state.driver === oldest) state.driver = null;
929
+ }
930
+ }
931
+ // The client whose prompt opened the surface drives once it reports
932
+ // its size, unless another client acted first.
933
+ if (claim || !state.driver || state.opener === clientId) {
934
+ if (state.clients.has(clientId)) {
935
+ state.driver = clientId;
936
+ state.opener = null;
937
+ }
938
+ }
939
+ if (state.driver === clientId) applyViewport(state);
940
+ };
941
+
942
+ /**
943
+ * A new top-level surface is drawn at the size of the client that sent
944
+ * the prompt that opened it: the device that ran the command sees it at
945
+ * its own width. Its size applies now if known, else when it reports.
946
+ */
947
+ const preferOpener = (state) => {
948
+ const opener = openerClientFor(state.sessionId);
949
+ if (typeof opener !== 'string' || opener.length === 0 || opener.length > 128) return;
950
+ if (state.clients.has(opener)) {
951
+ state.opener = null;
952
+ if (state.driver !== opener) {
953
+ state.driver = opener;
954
+ applyViewport(state);
955
+ }
956
+ return;
957
+ }
958
+ state.opener = opener;
959
+ };
960
+
961
+ // ------------------------------------------------------------------ mouse
962
+
963
+ /**
964
+ * A pi-tui mouse event for a surface. Coordinates are cells local to the
965
+ * surface's frame, which is also its "screen": the browser reports them
966
+ * per surface. The width is the one the component last rendered at, which
967
+ * containers compare against their recorded child layout.
968
+ */
969
+ const mouseEvent = (surface, type, code, x, y, extra = {}) => ({
970
+ type,
971
+ button: type === 'wheel' ? 'none' : MOUSE_BUTTONS[code & 3],
972
+ x,
973
+ y,
974
+ screenX: x,
975
+ screenY: y,
976
+ width: Math.max(1, surface.frame?.columns ?? 1),
977
+ height: Math.max(1, surface.frame?.lines.length ?? 1),
978
+ shift: (code & 4) !== 0,
979
+ alt: (code & 8) !== 0,
980
+ ctrl: (code & 16) !== 0,
981
+ ...extra,
982
+ });
983
+
984
+ const clickCount = (state, component, x, y) => {
985
+ const now = Date.now();
986
+ const previous = state.lastClick;
987
+ const count = previous && now - previous.at <= DOUBLE_CLICK_MS && previous.component === component
988
+ && previous.x === x && previous.y === y
989
+ ? (previous.count % 3) + 1
990
+ : 1;
991
+ state.lastClick = { at: now, count, component, x, y };
992
+ return count;
993
+ };
994
+
995
+ /**
996
+ * Applies a component's answer as pi-tui does: `focus` gives it the keys
997
+ * (an overlay's own component, as Pi keeps overlays as focus owners),
998
+ * `capture` routes the rest of the gesture to it. Returns whether to
999
+ * render.
1000
+ */
1001
+ const applyMouseResult = (state, surface, event, result) => {
1002
+ let focusChanged = false;
1003
+ if (result.focus) {
1004
+ const component = surface.overlay ? surface.component : (result.focusTarget ?? result.target?.component ?? surface.component);
1005
+ focusChanged = state.focus?.surface !== surface || state.focus?.component !== component;
1006
+ focusSurface(state, surface, component);
1007
+ }
1008
+ if (result.capture && state.mouse?.surface === surface) state.mouse.capture = result.target;
1009
+ return result.render ?? (focusChanged || event.type === 'press' || event.type === 'click'
1010
+ || event.type === 'drag' || event.type === 'wheel');
1011
+ };
1012
+
1013
+ /**
1014
+ * One SGR mouse report for a surface, routed the way pi-tui's
1015
+ * alternate-screen TUI routes it: a press goes to the component under the
1016
+ * pointer, which keeps the rest of the gesture; a release on the press
1017
+ * cell adds a click with its count; wheel steps carry `wheelDelta`.
1018
+ */
1019
+ const mouseItem = (state, surface, match) => {
1020
+ const code = Number(match[1]);
1021
+ const x = Math.max(0, Number(match[2]) - 1);
1022
+ const y = Math.max(0, Number(match[3]) - 1);
1023
+ const release = match[4] === 'm';
1024
+ const dispatch = (event, target) => {
1025
+ try {
1026
+ return target
1027
+ ? tui.dispatchMouseEvent(target.component, tui.retargetMouseEvent(event, target))
1028
+ : tui.dispatchMouseEvent(surface.component, event);
1029
+ } catch (error) {
1030
+ onError(state.sessionId, 'mouse', error);
1031
+ return undefined;
1032
+ }
1033
+ };
1034
+ if (state.mouse && (state.mouse.surface !== surface || !state.surfaces.includes(state.mouse.surface))) state.mouse = null;
1035
+ let render = false;
1036
+ if (code & 64) {
1037
+ if (release) return;
1038
+ const event = mouseEvent(surface, 'wheel', code, x, y, { wheelDelta: code & 1 ? 1 : -1 });
1039
+ const result = dispatch(event);
1040
+ if (result) render = applyMouseResult(state, surface, event, result);
1041
+ } else {
1042
+ const motion = (code & 32) !== 0;
1043
+ const type = release ? 'release' : motion ? (MOUSE_BUTTONS[code & 3] === 'none' ? 'move' : 'drag') : 'press';
1044
+ const event = mouseEvent(surface, type, code, x, y);
1045
+ const gesture = state.mouse;
1046
+ const target = gesture ? (gesture.capture ?? gesture.pressTarget) : undefined;
1047
+ if (gesture && target) {
1048
+ if (x !== gesture.x || y !== gesture.y) {
1049
+ gesture.moved = true;
1050
+ state.lastClick = null;
1051
+ }
1052
+ const result = dispatch(event, target);
1053
+ if (result) render = applyMouseResult(state, surface, event, result);
1054
+ if (release) {
1055
+ if (!gesture.moved && state.surfaces.includes(surface)) {
1056
+ const click = mouseEvent(surface, 'click', code, x, y, { clickCount: clickCount(state, target.component, x, y) });
1057
+ const clickResult = dispatch(click, target);
1058
+ if (clickResult) render = applyMouseResult(state, surface, click, clickResult) || render;
1059
+ }
1060
+ state.mouse = null;
1061
+ }
1062
+ } else {
1063
+ const result = dispatch(event);
1064
+ if (result) {
1065
+ if (type === 'press') state.mouse = { surface, pressTarget: result.target, capture: undefined, x, y, moved: false };
1066
+ render = applyMouseResult(state, surface, event, result);
1067
+ }
1068
+ }
1069
+ }
1070
+ // PiChamber sends no extension shortcuts (Pi's way back into a side
1071
+ // panel such as pi-btw's), so a press on a non-capturing overlay that
1072
+ // takes keys gives it focus when its component did not take it.
1073
+ if (!release && !(code & 96) && surface.overlay && !surface.capturing && typeof surface.component?.handleInput === 'function'
1074
+ && state.surfaces.includes(surface) && isVisibleAt(state, surface) && !takesKeys(state, surface)) {
1075
+ state.z += 1;
1076
+ surface.z = state.z;
1077
+ focusSurface(state, surface);
1078
+ publishMeta(state, surface);
1079
+ render = true;
1080
+ }
1081
+ if (render && state.surfaces.includes(surface)) scheduleRender(state, surface);
1082
+ };
1083
+
1084
+ // ---------------------------------------------------------------- commands
1085
+
1086
+ /**
1087
+ * Keys and mouse reports from a client. Items are terminal byte sequences,
1088
+ * one key, one bracketed paste or one SGR mouse report each, already split
1089
+ * the way Pi's stdin buffer splits. Keys go to a capturing surface, which
1090
+ * takes focus first, as a click does in Pi; mouse reports go to any shown
1091
+ * surface and move focus only when the component asks for it.
1092
+ */
1093
+ const input = ({ sessionId, surfaceId, clientId, viewport, items } = {}) => {
1094
+ const state = sessions.get(sessionId);
1095
+ const surface = findSurface(state, surfaceId);
1096
+ if (!surface) return { accepted: false };
1097
+ recordClient(state, clientId, viewport, true);
1098
+ if (!Array.isArray(items) || items.length === 0) return { accepted: true };
1099
+ const hasMouse = items.some((item) => typeof item === 'string' && item.startsWith('\x1b[<'));
1100
+ // The surface is open but takes no input right now (hidden at the
1101
+ // driver's size, or non-capturing without focus and this is not the
1102
+ // mouse): drop it, as Pi's TUI would. It is still open, so this is not
1103
+ // the "not open" answer that makes a client drop the surface.
1104
+ if (!isVisibleAt(state, surface) || (!takesKeys(state, surface) && !hasMouse)) return { accepted: true, delivered: false };
1105
+ let total = 0;
1106
+ let focused = false;
1107
+ for (const item of items.slice(0, MAX_INPUT_ITEMS)) {
1108
+ if (typeof item !== 'string' || item.length === 0) continue;
1109
+ total += item.length;
1110
+ if (total > MAX_INPUT_CHARS) break;
1111
+ if (!state.surfaces.includes(surface)) break;
1112
+ if (item.startsWith('\x1b[<')) {
1113
+ // Pi's TUI never hands a mouse report to handleInput, even one it
1114
+ // cannot parse.
1115
+ const match = SGR_MOUSE.exec(item);
1116
+ if (match) mouseItem(state, surface, match);
1117
+ continue;
1118
+ }
1119
+ if (!takesKeys(state, surface)) continue;
1120
+ // Keys for a surface whose child component or nested overlay holds
1121
+ // focus go there; any other surface takes focus first.
1122
+ if (!focused) {
1123
+ focused = true;
1124
+ const focusedSurface = state.focus?.surface;
1125
+ if (focusedSurface !== surface && focusedSurface?.parentId !== surface.id) focusSurface(state, surface);
1126
+ }
1127
+ const target = state.focus?.component;
1128
+ const owner = state.focus?.surface;
1129
+ if (!target || !owner || !state.surfaces.includes(owner)) break;
1130
+ // Keys typed at this surface stay with it and the overlays it opened.
1131
+ // Once a key closed it (Enter on a confirm), the rest of the batch is
1132
+ // dropped rather than landing in whatever surface took focus next.
1133
+ if (!isWithin(state, owner, surface)) break;
1134
+ try {
1135
+ target.handleInput?.(item);
1136
+ } catch (error) {
1137
+ onError(sessionId, 'input', error);
1138
+ }
1139
+ // Pi's TUI renders after every key it hands to a component.
1140
+ if (state.surfaces.includes(owner)) scheduleRender(state, owner);
1141
+ }
1142
+ return { accepted: true };
1143
+ };
1144
+
1145
+ /** A client's viewport. `claim` makes it the driver (open or focus). */
1146
+ const reportViewport = ({ sessionId, clientId, viewport, claim } = {}) => {
1147
+ const state = sessions.get(sessionId);
1148
+ if (!state || state.surfaces.length === 0) return { accepted: false };
1149
+ recordClient(state, clientId, viewport, claim === true);
1150
+ return { accepted: true };
1151
+ };
1152
+
1153
+ /** The host Close button: resolve `undefined`, as Pi's Escape would not. */
1154
+ const close = ({ sessionId, surfaceId, clientId, viewport } = {}) => {
1155
+ const state = sessions.get(sessionId);
1156
+ const surface = findSurface(state, surfaceId);
1157
+ if (!surface) return { closed: false };
1158
+ recordClient(state, clientId, viewport, true);
1159
+ if (surface.settle) surface.settle('cancelled');
1160
+ else removeSurface(state, surface, 'cancelled');
1161
+ return { closed: true };
1162
+ };
1163
+
1164
+ /**
1165
+ * Brings a panel a command opened with `tui.showOverlay` to the front and
1166
+ * gives it the keys, as `handle.focus()` would: the browser's tab stack
1167
+ * calls this when the user picks a tab. Only nested overlays are offered
1168
+ * as tabs, so only they are accepted. The panel's family redraws, since
1169
+ * extensions read `isFocused()` while rendering.
1170
+ */
1171
+ const focus = ({ sessionId, surfaceId, clientId, viewport } = {}) => {
1172
+ const state = sessions.get(sessionId);
1173
+ const surface = findSurface(state, surfaceId);
1174
+ if (!surface || !surface.overlay || !surface.parentId || !isVisibleAt(state, surface)) return { focused: false };
1175
+ recordClient(state, clientId, viewport, true);
1176
+ state.z += 1;
1177
+ surface.z = state.z;
1178
+ focusSurface(state, surface);
1179
+ publishMeta(state, surface);
1180
+ // Bounded, and stops at a missing parent, so a broken chain cannot hang
1181
+ // the daemon.
1182
+ let root = surface;
1183
+ for (let depth = 0; root.parentId && depth <= state.surfaces.length; depth += 1) {
1184
+ const parent = state.surfaces.find((candidate) => candidate.id === root.parentId);
1185
+ if (!parent) break;
1186
+ root = parent;
1187
+ }
1188
+ for (const candidate of state.surfaces) {
1189
+ if (candidate === root || isWithin(state, candidate, root)) scheduleRender(state, candidate);
1190
+ }
1191
+ return { focused: true };
1192
+ };
1193
+
1194
+ /** Publishes full frames again, for a client that missed a patch. */
1195
+ const refresh = ({ sessionId, surfaceId } = {}) => {
1196
+ const state = sessions.get(sessionId);
1197
+ if (!state) return { refreshed: false };
1198
+ let refreshed = false;
1199
+ for (const surface of state.surfaces) {
1200
+ if (surfaceId && surface.id !== surfaceId) continue;
1201
+ if (!surface.frame) continue;
1202
+ publishTransient('extension.custom.frame', fullFrame(surface), sessionId, directoryForSession(sessionId));
1203
+ refreshed = true;
1204
+ }
1205
+ return { refreshed };
1206
+ };
1207
+
1208
+ /** Ends every surface of a session (or all sessions) with `reason`. */
1209
+ const clear = (sessionId, reason = 'session-closed') => {
1210
+ const targets = sessionId ? [sessions.get(sessionId)].filter(Boolean) : [...sessions.values()];
1211
+ for (const state of targets) {
1212
+ for (const surface of [...state.surfaces].reverse()) {
1213
+ if (!state.surfaces.includes(surface)) continue;
1214
+ if (surface.settle) surface.settle(reason);
1215
+ else removeSurface(state, surface, reason);
1216
+ }
1217
+ if (state.renderTimer) clearTimer(state.renderTimer);
1218
+ if (state.sizeTimer) clearTimer(state.sizeTimer);
1219
+ sessions.delete(state.sessionId);
1220
+ }
1221
+ };
1222
+
1223
+ /** Surface stack with full frames, for snapshots and `sessions.open`. */
1224
+ const snapshot = (sessionId) => {
1225
+ const state = sessions.get(sessionId);
1226
+ if (!state || state.surfaces.length === 0) return undefined;
1227
+ return state.surfaces.map((surface) => ({
1228
+ ...projectMeta(state, surface),
1229
+ ...(surface.frame ? { frame: fullFrame(surface) } : {}),
1230
+ }));
1231
+ };
1232
+
1233
+ /** Current full frames, written to a client that attached by replay. */
1234
+ const keyframes = (sessionId) => {
1235
+ const out = [];
1236
+ for (const state of sessions.values()) {
1237
+ if (sessionId && state.sessionId !== sessionId) continue;
1238
+ for (const surface of state.surfaces) {
1239
+ if (surface.frame) out.push({ sessionId: state.sessionId, payload: fullFrame(surface) });
1240
+ }
1241
+ }
1242
+ return out;
1243
+ };
1244
+
1245
+ const hasOpenSurfaces = (sessionId) => (sessions.get(sessionId)?.surfaces.length ?? 0) > 0;
1246
+
1247
+ return {
1248
+ open,
1249
+ input,
1250
+ reportViewport,
1251
+ close,
1252
+ focus,
1253
+ refresh,
1254
+ clear,
1255
+ snapshot,
1256
+ keyframes,
1257
+ hasOpenSurfaces,
1258
+ };
1259
+ };