@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,215 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-sztndhZI.js","assets/vendor-react-Bz1tRBxM.js","assets/document-attachments-CZl9rK1z.js","assets/vendor-fflate-C7GOKjkv.js","assets/vendor-capacitor-status-bar-DV24OoQV.js","assets/vendor-boot-CoTxysn6.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-capacitor-app-NX6DULfp.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-keyboard-DJD81I9f.js","assets/permissionStore-zIpxq9Pq.js","assets/vendor-zustand-CXhN0IMY.js","assets/MarkdownRendererImpl-BkT5TUWF.js","assets/vendor-morphdom-B7dS_VPB.js","assets/vendor-beautiful-mermaid-b48gT2g0.js","assets/vendor-elkjs-D1S1RCAO.js","assets/vendor-entities-C3BA0AJP.js","assets/index-C2ISrmRR.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-DgwThEwf.css","assets/markdownCore-DbS8DkKw.js","assets/vendor-marked-Be78pDn1.js","assets/vendor-dompurify-BGCr_sdL.js","assets/vendor-remend-DcBOpbSu.js","assets/registerCustomTheme-C-h6lsYW.js","assets/themeResolver-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/nativeFileSave-Bhafll_7.js","assets/runtimeSurface-CJN1oo_1.js","assets/vendor-codemirror-lang-javascript-Dkzl3s07.js","assets/vendor-lezer-javascript-B3s21DIS.js","assets/vendor-lezer-lr-Bllrq8hY.js","assets/vendor-codemirror-autocomplete-qsuH4Dh-.js","assets/vendor-codemirror-lang-json-CsdmtHhi.js","assets/vendor-lezer-json-DPFM6EBV.js","assets/vendor-codemirror-lang-css-2bFuyM70.js","assets/vendor-lezer-css-JnEzSyZR.js","assets/vendor-codemirror-lang-html-BV8lrR8v.js","assets/vendor-lezer-html-Cr3U-1pu.js","assets/vendor-codemirror-lang-markdown-C0Zu3b3n.js","assets/vendor-lezer-markdown-6-3PLvXG.js","assets/vendor-codemirror-lang-python-Cv2exx_M.js","assets/vendor-lezer-python-CdHdN5qt.js","assets/GitHubLinkPicker-BjJNQ7Ap.js","assets/GitHubListPrimitives-BcB-cCTs.js","assets/GitHubDetailScaffold-CW2ZqU0Y.js","assets/githubLink-BvevcNay.js","assets/ToolOutputDialog-QC8IoeBH.js","assets/JsonTreeView-DpCgOUXg.js","assets/web-components-6ORYp3Iv.js","assets/computeVirtualFileMetrics-aX6tjjqv.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/Virtualizer-DNJrJKVb.js","assets/renderFileWithHighlighter-CCoYfC-t.js","assets/PatchDiff-Dcr3EQgA.js","assets/VirtualizedFileDiff-DvLCd7Qq.js","assets/renderDiffWithHighlighter-xlvSvnTf.js","assets/vendor-diff-C3JhlQdm.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/ToolPartDiffPreview-BigGwtul.js"])))=>i.map(i=>d[i]);
2
+ import{au as Br,a as wt,a0 as dr,av as K9,aw as G9,ax as Fl,ay as kh,az as Bl,aA as o5,aB as i5,x as Ee,aC as lt,aD as a5,e as Gt,q as de,u as nt,z as Nt,aE as Jp,w as c5,U as Vr,j as Nd,aF as Z9,v as $r,b as Y,aG as Qp,aH as Ld,h as te,aI as Wo,J as l5,aJ as em,aK as ft,o as en,aL as Rd,aM as Mh,r as Nr,aN as Y9,aO as X9,aP as J9,S as Q9,aQ as eS,a9 as Ko,aR as Eg,aS as tS,aT as nS,aU as rS,A as sS,aV as oS,t as iS,aW as aS,aX as Fu,aY as jg,aZ as cS,f as R,ah as lS,a_ as Lr,ai as dS,ak as gn,ag as tm,a$ as Vl,b0 as uS,b1 as _g,al as Wn,b2 as fS,b3 as al,s as cl,b4 as Bu,b5 as Vu,b6 as Tg,b7 as hS,b8 as pS,aj as mS,b9 as gS,ba as yS,bb as vS,bc as xS,l as bS,bd as Ag,be as wS,bf as Ng,bg as SS,i as lr,bh as nm,d as CS,bi as kS,bj as MS,bk as IS,bl as $l,bm as ES,bn as Lg,bo as Rg,n as ps,bp as d5,P as u5,bq as Wi,br as jS,an as _t,$ as _S,bs as TS,W as AS,bt as NS,bu as Pg,bv as LS,bw as RS,bx as PS,by as f5,bz as DS,bA as h5,bB as OS,bC as HS,bD as FS,bE as BS,bF as $u,bG as zu,bH as gc,bI as VS,bJ as Ih,bK as yc,bL as fo,at as $S,ar as zS,bM as US,bN as Dg,M as qS,N as WS,O as KS,L as GS,bO as p5,V as ZS,Q as Is,bP as YS,bQ as XS,bR as JS,bS as Aa,bT as ll,T as QS,bU as Eh,a6 as jh,bV as eC,a7 as tC}from"./index-C2ISrmRR.js";import{j as c,aS as nC,aV as rC,aY as sC,aW as oC,aX as iC,aT as aC,aU as cC,bk as lC,bl as m5,bm as dC,bn as uC,b8 as g5,bo as y5,ba as v5,bb as fC,bc as hC,bp as pC,bq as mC,br as gC,bs as yC,bt as vC,bu as ai,bv as xC,bw as bC,bx as wC,by as SC,bz as CC,bA as kC,bB as MC,aP as pa,bC as IC,bD as EC,bE as jC,bF as _C,bG as TC,bH as AC,bI as NC,bJ as LC,Q as bn,bK as RC,bL as PC,bM as DC,bN as OC,bO as HC,bP as FC,bQ as BC,bR as VC,bS as $C,bT as zC,bU as UC,bV as qC,aZ as rm,a_ as ma,bf as x5,bg as b5,b0 as sm,b1 as om,bd as im,be as w5,bh as am,bi as cm,a$ as WC,bW as S5,bX as C5,bY as k5,bZ as M5,b_ as I5,b$ as Ls,c0 as KC,c1 as GC,c2 as ZC,b4 as YC,aj as XC,c3 as JC,c4 as QC,E as Pe,S as E5,O as j5,ap as e8,aq as t8,M as n8,af as r8,c5 as s8,c6 as o8,R as i8,U as Og,c7 as a8,c8,c9 as _5,ca as Hg,cb as l8,aQ as vc,b5 as T5,bj as d8,cc as u8}from"./vendor-boot-CoTxysn6.js";import{a as H,R as p}from"./vendor-react-Bz1tRBxM.js";import{c as Lt,d as mr,p as Pd}from"./vendor-zustand-CXhN0IMY.js";import{_ as mt}from"./vendor-vite-runtime-DD1OZmLC.js";import{i as un}from"./runtimeSurface-CJN1oo_1.js";import{saveOrShareFile as f8}from"./nativeFileSave-Bhafll_7.js";const kY=()=>{if(!Br())return!1;const e=K9();return e==="win32"||e==="linux"},MY=async()=>{if(!wt())return!1;try{return await dr("desktop_start_window_drag"),!0}catch{return!1}},h8=24;class ms{constructor(t,n,r){this.parent=t,this.overlay=n,this.depth=r}parent;overlay;depth;static empty(){return new ms(null,new Map,0)}static from(t){return new ms(null,new Map(t),0)}get(t){return this.overlay.has(t)?this.overlay.get(t):this.parent?.get(t)}has(t){return this.overlay.has(t)?!0:this.parent?.has(t)??!1}set(t,n){return this.overlay.set(t,n),this}fork(){return this.depth>=h8?this.compact().fork():new ms(this,new Map,this.depth+1)}compact(){if(!this.parent)return this;const t=new Map;return this.collect(t),new ms(null,t,0)}get size(){return this.parent?[...this.entries()].length:this.overlay.size}*entries(){const t=new Set;yield*this.walk(t)}*values(){for(const[,t]of this.entries())yield t}*keys(){for(const[t]of this.entries())yield t}[Symbol.iterator](){return this.entries()}*walk(t){for(const[n,r]of this.overlay)t.has(n)||(t.add(n),yield[n,r]);this.parent&&(yield*this.parent.walk(t))}collect(t){this.parent?.collect(t);for(const[n,r]of this.overlay)t.set(n,r)}}const zl=e=>e?ms.from(e):ms.empty(),Ul=()=>({bySession:new Map,lastSequence:new Map}),A5=()=>zl(),p8=10,m8=50;let g8=0;const N5=()=>`ext-${Date.now().toString(36)}-${g8+=1}`,L5=(e,t,n=p8)=>{const r=[...e,t];return r.length>n?r.slice(r.length-n):r},Un=(e,t,n)=>{t&&(e.lastMutatedMessageId=e.messages.get(t)?.id??t,e.lastMutationKind=n)},rs=e=>{e.parts=e.parts.fork()},y8=(e,t,n)=>{const r=e.bySession.get(t);if(r)return r;const s={sessionId:t,directory:n,lastSequence:-1,lifecycle:"idle",messages:new Map,partOrder:new Map,parts:A5(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};return e.bySession.set(t,s),s},Dd=(e,t)=>e.startsWith(`user-${t}-`),v8=250,Fg=new WeakMap,x8=(e,t)=>{if(e.size!==t.size)return!1;for(const n of e.list)if(t.get(n.id)!==n)return!1;return!0},Na=e=>{const t=Fg.get(e.messages);if(t&&x8(t,e.messages))return t.list;const n=new Set,r=[];for(const s of e.messages.values())n.has(s.id)||(n.add(s.id),r.push(s));for(let s=1;s<r.length;s+=1){const o=r[s-1],i=r[s];if(!(!o||!i||i.createdAt>=o.createdAt)){r.sort((a,l)=>a.createdAt-l.createdAt);break}}return Fg.set(e.messages,{size:e.messages.size,list:r}),r},R5=(e,t,n)=>{if(!t)return;let r,s=Number.POSITIVE_INFINITY;for(const o of Na(e)){if(o.role!=="user"||o.text!==t||Dd(o.id,e.sessionId))continue;const i=Math.abs(o.createdAt-n);i<=v8&&i<s&&(r=o,s=i)}return r},b8=(e,t,n)=>{if(n.role==="user"&&Dd(t,e.sessionId)){const r=R5(e,n.text,n.createdAt);if(r){e.messages.set(t,r);return}}e.messages.set(t,n)},Od=(e,t)=>{if(!t)return;const n=e.messages.get(t)?.id;if(n)return n;if(Dd(t,e.sessionId)){const r=Na(e);for(let s=r.length-1;s>=0;s-=1){const o=r[s];if(o?.role==="user")return o.id}}return t},w8=(e,t,n)=>{const r=e.messages.get(t.messageId);if(r)return r;if(t.role==="user"&&Dd(t.messageId,e.sessionId)){const i=R5(e,t.text??"",t.startedAt);if(i)return e.messages.set(t.messageId,i),i}const s=Od(e,t.parentId),o={id:t.messageId,sessionId:e.sessionId,directory:n,role:t.role,...s?{parentId:s}:{},createdAt:t.startedAt,text:t.role==="user"?t.text??"":"",thinking:"",streaming:t.role==="assistant",...t.model?{model:t.model}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}};if(e.messages.set(t.messageId,o),t.role==="user"&&t.files?.length){const i=[];for(const a of t.files){const l={id:a.id,index:a.index,type:"file",text:"",streaming:!1,file:{...a.mime?{mime:a.mime}:{},...a.filename?{filename:a.filename}:{},...a.url?{url:a.url}:{}}};e.parts.set(l.id,l),i.push(l.id)}e.partOrder.set(o.id,i)}return o},P5=(e,t,n,r)=>{const s=r??`${t.id}:${n}`,o=e.parts.get(s);if(o)return o;const i={id:s,index:(e.partOrder.get(t.id)??[]).length,type:n,text:"",streaming:!0};e.parts.set(s,i);const a=[...e.partOrder.get(t.id)??[]];return a.includes(i.id)||a.push(i.id),e.partOrder.set(t.id,a),i},S8=(e,t)=>{if(!e.messages.get(t))return{text:"",thinking:""};const r=e.partOrder.get(t)??[];let s="",o="";for(const i of r){const a=e.parts.get(i);a&&(a.type==="text"?s+=a.text:a.type==="thinking"&&(o+=a.text))}return{text:s,thinking:o}},Bg=(e,t,n,r)=>{const o=(e.partOrder.get(t)??[]).map(l=>e.parts.get(l)).filter(l=>l?.type===n);if(o.length===0){if(!r)return;const l=e.messages.get(t);if(!l)return;const d=P5(e,l,n);e.parts.set(d.id,{...d,text:r,streaming:!1});return}const[i,...a]=o;if(i){e.parts.set(i.id,{...i,text:r,streaming:!1});for(const l of a)e.parts.set(l.id,{...l,text:"",streaming:!1})}},lm=(e,t)=>{const n=e.messages.get(t);if(n&&n.role==="assistant")return n;const r=Na(e);for(let o=r.length-1;o>=0;o-=1){const i=r[o];if(i.role==="assistant"&&(i.streaming||i.durationMs===void 0))return e.messages.set(t,i),!e.partOrder.has(t)&&e.partOrder.has(i.id)&&e.partOrder.set(t,e.partOrder.get(i.id)),i}const s=r[r.length-1];if(s&&s.role==="assistant")return e.messages.set(t,s),!e.partOrder.has(t)&&e.partOrder.has(s.id)&&e.partOrder.set(t,e.partOrder.get(s.id)),s},C8=(e,t,n)=>{const r=new Set(e.partOrder.get(t)??[]);if(r.size!==0)for(const[s,o]of e.parts)!o.streaming||!n(o)||!r.has(o.id)&&!r.has(s)||e.parts.set(s,{...o,streaming:!1})},D5=(e,t)=>{C8(e,t,n=>n.type==="thinking")},k8=256,O5=(e,t)=>{if(!t)return e;if(!e)return t;if(t===e)return e;if(t.startsWith(e))return t;if(e.startsWith(t))return e;const n=Math.min(k8,e.length,t.length);for(let r=n;r>0;r-=1)if(e.endsWith(t.slice(0,r)))return e+t.slice(r);return e+t},Ro=(e,t,n=Date.now())=>{if(!(typeof e!="number"||!Number.isFinite(e)))return typeof t!="number"||!Number.isFinite(t)?e:e-(t-n)},M8=(e,t)=>{if(t.state==="busy"&&typeof t.command=="string"?e.runningCommand=t.command:delete e.runningCommand,t.state==="retry"){e.lifecycle="retry",e.retry={...t.attempt!==void 0?{attempt:t.attempt}:{},...t.next!==void 0?{next:t.next}:{},...t.message!==void 0?{message:t.message}:{}};return}if(t.state==="busy"&&e.retry){e.lifecycle="retry";return}if(e.lifecycle=t.state,e.retry=void 0,t.state!=="busy"){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[n,r]of e.messages)r.streaming&&e.messages.set(n,{...r,streaming:!1})}},I8=(e,t,n)=>{w8(e,n,t)},Vg=(e,t,n)=>{const r=lm(e,t.messageId);if(!r)return!1;r.streaming=!0,e.streamingMessages.add(r.id),e.streamingMessages.add(t.messageId),n==="text"&&D5(e,r.id);const s=t.partId??`${r.id}:${n}`;let o=e.parts.get(s);if(!o){const a=t.contentIndex;if(typeof a=="number"){const l=[`${r.id}:${n}:${a}`,`${r.id}:${a}`,`${r.id}:${n}`];for(const d of l){const f=e.parts.get(d);if(f&&f.type===n){o=f;break}}if(!o){const d=e.partOrder.get(r.id)??[];for(const f of d){const u=e.parts.get(f);if(u&&u.type===n&&u.index===a){o=u;break}}}}}if(o){if(o.type!==n)return!1;const a={...o,text:O5(o.text,t.delta),streaming:!0};return e.parts.set(o.id,a),s!==o.id&&e.parts.set(s,a),!0}const i=P5(e,r,n,s);return e.parts.set(i.id,{...i,text:t.delta,streaming:!0}),!0},E8=(e,t)=>{const n=lm(e,t.messageId);if(!n)return;const{text:r,thinking:s}=S8(e,n.id);n.text=typeof t.text=="string"?t.text:r,n.thinking=typeof t.thinking=="string"?t.thinking:s,Bg(e,n.id,"text",n.text),Bg(e,n.id,"thinking",n.thinking),t.continuing===!0&&!t.error?(n.streaming=!0,e.streamingMessages.add(n.id),e.streamingMessages.add(t.messageId)):n.streaming=!1,typeof t.durationMs=="number"?n.durationMs=t.durationMs:typeof n.createdAt=="number"&&n.createdAt>0&&(n.durationMs=Math.max(100,Date.now()-n.createdAt)),t.thinkingLevel&&(n.thinkingLevel=t.thinkingLevel),t.error&&(n.error=t.error),t.usage&&(n.usage=t.usage),t.continuing!==!0&&!t.error&&(e.streamingMessages.delete(n.id),e.streamingMessages.delete(t.messageId))},Uu=(e,t,n)=>{const r=e.toolsByCallId.get(n.toolCallId)??n.messageId,s=lm(e,r);if(!s)return!1;D5(e,s.id);const o=Date.now(),i=Ro(n.startedAt,n.serverNow,o),a=Ro(n.endedAt,n.serverNow,o);t!=="end"&&(s.streaming=!0,e.streamingMessages.add(s.id));const l=e.parts.get(n.partId)??Array.from(e.parts.values()).find(h=>h.type==="tool"&&h.tool?.toolCallId===n.toolCallId);if(t==="start"&&!l){const h={id:n.partId,index:(e.partOrder.get(s.id)??[]).length,type:"tool",text:"",streaming:!1,tool:{toolCallId:n.toolCallId,name:n.name,...n.input!==void 0?{input:n.input}:{},...n.render!==void 0?{render:n.render}:{},state:n.state,...i!==void 0?{startedAt:i}:{}}};e.parts.set(h.id,h);const m=[...e.partOrder.get(s.id)??[]];return m.push(h.id),e.partOrder.set(s.id,m),e.toolsByCallId.set(n.toolCallId,s.id),!0}if(!l||l.type!=="tool")return!1;const d={...l},f=l.tool,u=n.render!==void 0?{...f?.render??{},...n.render}:f?.render;return d.tool={toolCallId:n.toolCallId,name:n.name,...n.input!==void 0?{input:n.input}:f?.input!==void 0?{input:f.input}:{},...n.output!==void 0?{output:n.output}:f?.output!==void 0?{output:f.output}:{},...u!==void 0?{render:u}:{},...n.error!==void 0?{error:n.error}:f?.error!==void 0?{error:f.error}:{},...n.metadata!==void 0?{metadata:n.metadata}:f?.metadata!==void 0?{metadata:f.metadata}:{},...n.isError!==void 0?{isError:n.isError}:f?.isError!==void 0?{isError:f.isError}:{},state:n.state,...i!==void 0?{startedAt:i}:f?.startedAt!==void 0?{startedAt:f.startedAt}:{},...a!==void 0?{endedAt:a}:f?.endedAt!==void 0?{endedAt:f.endedAt}:{}},t==="end"&&(d.streaming=!1),e.parts.set(d.id,d),!0},j8=(e,t)=>{if(e.lifecycle="interrupted",e.retry=void 0,!!t){for(const n of e.streamingMessages){const r=e.messages.get(n);r&&(r.streaming=!1,r.error={code:"SESSION_INTERRUPTED"})}e.streamingMessages.clear()}},_8=(e,t,n)=>{e.lifecycle="error",e.retry=void 0;const r=Date.now();e.parts=e.parts.fork(),e.partOrder=new Map(e.partOrder);const s=[...e.streamingMessages].map(i=>e.messages.get(i)).filter((i,a,l)=>!!i&&l.indexOf(i)===a),o=s.reduce((i,a)=>!i||a.createdAt>=i.createdAt?a:i,void 0);for(const i of s){i.streaming=!1,i.error=i===o?{code:t,...n?{message:n}:{}}:void 0,i.durationMs===void 0&&i.createdAt>0&&(i.durationMs=Math.max(100,r-i.createdAt));for(const a of e.partOrder.get(i.id)??[]){const l=e.parts.get(a);if(!l)continue;const d=l.tool?.state==="running"||l.tool?.state==="pending";if(!l.streaming&&!d)continue;const f={...l,streaming:!1};d&&f.tool&&(f.tool={...f.tool,state:"error",...n?{error:n}:{},endedAt:f.tool.endedAt??r}),e.parts.set(a,f)}}e.streamingMessages.clear()},T8="pichamber.ui",A8="pichamber.",N8="pichamber-extension-ui",L8=1,R8=new Set(["info","success","warning","error","neutral"]),Kn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,tt=e=>typeof e=="string"?e:void 0,_h=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,H5=e=>{const t=tt(e);return t&&R8.has(t)?t:"neutral"},$g=e=>{if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=Kn(n);if(!r)continue;const s=tt(r.label);s!==void 0&&t.push({label:s,value:tt(r.value)??"",...r.tone!==void 0?{tone:H5(r.tone)}:{}})}return t},P8=128,ci=(e,t)=>e.length>t?e.slice(0,t):e,D8=e=>G9(e),zg=e=>{if(!Array.isArray(e))return;const t=[];for(const n of e.slice(0,8)){const r=Kn(n);if(!r)continue;const s=tt(r.label),o=tt(r.command);if(!s||!o||o.includes("/")||o.startsWith("."))continue;const i=Kn(r.promptForArgs),a=i?tt(i.label):void 0,l=i?tt(i.placeholder):void 0;t.push({label:ci(s,P8),command:o,...tt(r.args)!==void 0?{args:D8(tt(r.args))}:{},...r.variant==="outline"||r.variant==="ghost"?{variant:r.variant}:{},...tt(r.icon)!==void 0?{icon:ci(tt(r.icon)??"",64)}:{},...r.disabled===!0?{disabled:!0}:{},...r.loading===!0?{loading:!0}:{},...tt(r.confirm)!==void 0?{confirm:ci(tt(r.confirm)??"",500)}:{},...i?{promptForArgs:{...a!==void 0?{label:ci(a,256)}:{},...l!==void 0?{placeholder:ci(l,256)}:{}}}:{}})}return t.length>0?t:void 0},O8=(e,t)=>{switch(e){case"markdown":{const n=tt(t.body)??tt(t.text);return n!==void 0?{component:"markdown",body:n}:null}case"kv":{const n=$g(t.rows);return n&&n.length>0?{component:"kv",rows:n}:null}case"list":{const n=$g(t.items??t.rows);return n&&n.length>0?{component:"list",items:n}:null}case"table":{if(!Array.isArray(t.columns)||!Array.isArray(t.rows))return null;const n=t.columns.map(s=>tt(s)??"").filter(s=>s.length>0);if(n.length===0)return null;const r=[];for(const s of t.rows.slice(0,200))Array.isArray(s)&&r.push(s.map(o=>tt(o)??"").slice(0,n.length));return r.length>0?{component:"table",columns:n,rows:r}:null}case"progress":{const n=_h(t.value);if(n===void 0)return null;const r=_h(t.max)??100;return{component:"progress",value:n,max:r>0?r:100,...tt(t.label)!==void 0?{label:tt(t.label)}:{}}}case"badges":{if(!Array.isArray(t.items))return null;const n=t.items.map(r=>{const s=Kn(r);if(s){const i=tt(s.label);return i?{label:i,tone:H5(s.tone)}:null}const o=tt(r);return o?{label:o,tone:"neutral"}:null}).filter(r=>r!==null).slice(0,24);return n.length>0?{component:"badges",items:n}:null}case"code":{const n=tt(t.code);return n!==void 0?{component:"code",code:n,...tt(t.language)!==void 0?{language:tt(t.language)}:{}}:null}default:return null}},Ug=(e,t=2e3)=>e.length>t?`${e.slice(0,t)}…`:e,qg=e=>{if(!Array.isArray(e)||e.length===0)return;const t=[];for(const n of e){if(typeof n!="string")return;t.push(n)}return t},F5=e=>{const t=Kn(e);if(!t)return;const n=qg(t.message);if(!n)return;if(t.messageExpanded===void 0)return{message:n};const r=qg(t.messageExpanded);return r?{message:n,messageExpanded:r}:{message:n}},B5=e=>{const n=e.customType===T8||(e.customType?.startsWith(A8)??!1)?Kn(Kn(e.data)?.ui??null)??Kn(e.data)??Kn(e.details):null;if(n){const s=tt(n.protocol),o=_h(n.version);if(!(s&&s!==N8)){if(!(o!==void 0&&o!==L8)){const i=tt(n.component)??tt(n.type);if(i){const a=Kn(n.props)??{},l=O8(i,a),d=zg(n.actions);if(l||d){const f=tt(n.title);return{kind:"ui",descriptor:{...tt(n.id)!==void 0?{id:tt(n.id)?.slice(0,128)}:{},...f!==void 0?{title:f.slice(0,256)}:{},component:l??{component:"markdown",body:""},...d?{actions:d}:{}}}}}if(tt(n.title)||tt(n.text)||tt(n.body)){const a=tt(n.text)??tt(n.body)??"";if(a){const l=zg(n.actions);return{kind:"ui",descriptor:{...tt(n.id)!==void 0?{id:tt(n.id)?.slice(0,128)}:{},...tt(n.title)!==void 0?{title:tt(n.title)?.slice(0,256)}:{},component:{component:"markdown",body:a.slice(0,5e3)},...l?{actions:l}:{}}}}}}}}const r=[];if(typeof e.text=="string"&&e.text.trim().length>0&&r.push(e.text.trim()),e.data!==void 0)try{r.push(Ug(JSON.stringify(e.data,null,2)))}catch{r.push("[unserializable data]")}else if(e.details!==void 0)try{r.push(Ug(JSON.stringify(e.details,null,2)))}catch{r.push("[unserializable details]")}return{kind:"fallback",title:e.customType??"Extension",body:r.join(`
3
+
4
+ `)}},H8=(e,t,n,r)=>{if(!r.customType)return;const s={id:r.id,sessionId:n,directory:t,role:"extension",customType:r.customType,...r.data!==void 0?{data:r.data}:{},createdAt:r.createdAt,text:"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(s.id,s),Un(e,s.id,"structure")},F8=(e,t,n,r)=>{if(!r.customType)return;const s=F5(r.render),o={id:r.id,sessionId:n,directory:t,role:"extension",customType:r.customType,...r.details!==void 0?{details:r.details}:{},...s?{render:s}:{},createdAt:r.createdAt,text:r.text??"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(o.id,o),Un(e,o.id,"structure")},B8=(e,t)=>{e.extensionStatuses=new Map(e.extensionStatuses),typeof t.text=="string"&&t.text.length>0?e.extensionStatuses.set(t.key,t.text):e.extensionStatuses.delete(t.key)},V8=(e,t)=>{e.extensionWidgets=new Map(e.extensionWidgets),Array.isArray(t.lines)&&t.lines.length>0?e.extensionWidgets.set(t.key,{lines:t.lines,placement:t.placement==="belowEditor"?"belowEditor":"aboveEditor"}):e.extensionWidgets.delete(t.key)},$8=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)||(e.extensionDialogs=[...e.extensionDialogs,t])},z8=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)&&(e.extensionDialogs=e.extensionDialogs.filter(n=>n.requestId!==t.requestId))},U8=(e,t)=>{const n=typeof t.id=="string"&&t.id.length>0?t.id:N5();e.extensionNotices.some(r=>r.id===n)||(e.extensionNotices=L5(e.extensionNotices,{id:n,message:t.message,level:t.level,createdAt:typeof t.createdAt=="number"&&Number.isFinite(t.createdAt)?t.createdAt:Date.now()},m8))},q8=(e,t)=>{t.commands===!0&&(e.extensionCatalogRevision=(e.extensionCatalogRevision??0)+1)},W8=(e,t,n)=>{const r=t.mode==="paste"?"paste":"set",s={text:t.text,mode:r,sequence:n};if(r==="set")e.extensionEditorOps=[s];else{const i=[...e.extensionEditorOps??(e.extensionEditor?[e.extensionEditor]:[]),s];i.length>32&&i.splice(0,i.length-32),e.extensionEditorOps=i}e.extensionEditor=s},K8=(e,t)=>{e.extensionTitle=t.title},G8=(e,t)=>{e.extensionPanels=new Map(e.extensionPanels);const n=t.component!==void 0||t.title!==void 0||t.actions!==void 0;t.removed===!0||!n?e.extensionPanels.delete(t.id):e.extensionPanels.set(t.id,t)},Z8=(e,t)=>{e.extensionApps=new Map(e.extensionApps),t.removed===!0||typeof t.html!="string"||t.html.length===0?e.extensionApps.delete(t.appId):e.extensionApps.set(t.appId,t)},Y8=(e,t)=>{e.extensionErrors=L5(e.extensionErrors,{id:N5(),source:t.source,...t.event!==void 0?{event:t.event}:{},message:t.message,createdAt:Date.now()})},X8=(e,t)=>{const n=t.message||void 0,r=t.visible;n===void 0&&r===void 0?delete e.extensionWorking:e.extensionWorking={...n!==void 0?{message:n}:{},...r!==void 0?{visible:r}:{}}},J8=(e,t,n)=>{const r=e.bySession.get(t);if(!r||r.extensionDialogs.findIndex(i=>i.requestId===n)===-1)return e;const o={...r,extensionDialogs:r.extensionDialogs.filter(i=>i.requestId!==n)};return{bySession:new Map(e.bySession).set(t,o),lastSequence:new Map(e.lastSequence)}},V5=e=>({surfaceId:e.surfaceId,...e.parentId?{parentId:e.parentId}:{},title:e.title,mode:e.mode,capturing:e.capturing,hidden:e.hidden,focused:e.focused,z:e.z,...e.blocked?{blocked:{...e.blocked}}:{}}),$5=e=>({version:e.version,lines:e.lines,cells:e.lines.map((t,n)=>e.cells?.[n]),cursor:e.cursor,layout:e.layout,visible:e.visible,columns:e.columns,screenColumns:e.screenColumns,rows:e.rows}),z5=e=>Array.isArray(e.lines),U5=e=>{if(!Array.isArray(e)||e.length===0)return;const t=new Map;for(const n of e){if(typeof n?.surfaceId!="string"||n.surfaceId.length===0)continue;const r=n.frame&&n.frame.surfaceId===n.surfaceId&&z5(n.frame)?$5(n.frame):null;t.set(n.surfaceId,{...V5(n),frame:r})}return t.size>0?t:void 0},dl=(e,t)=>{const n=new Map(e.extensionSurfaces??[]);n.set(t.surfaceId,t),e.extensionSurfaces=n},Q8=(e,t)=>{const n=e.extensionSurfaces?.get(t.surfaceId);dl(e,{...V5(t),frame:n?.frame??null,...n?.stale?{stale:!0}:{}})},e6=(e,t)=>{const n=e.extensionSurfaces?.get(t.surfaceId);if(!n||n.frame&&t.version<=n.frame.version)return;if(z5(t)){dl(e,{...n,frame:$5(t),stale:!1});return}if(!n.frame||n.frame.version!==t.base){n.stale||dl(e,{...n,stale:!0});return}const r=n.frame.lines.slice(0,t.length),s=n.frame.cells.slice(0,t.length);for(;r.length<t.length;)r.push(""),s.push(void 0);for(const o of t.changes)r[o.index]=o.line,s[o.index]=o.cells;dl(e,{...n,frame:{version:t.version,lines:r,cells:s,cursor:t.cursor,layout:t.layout,visible:t.visible,columns:t.columns,screenColumns:t.screenColumns,rows:t.rows},stale:!1})},q5=(e,t)=>{if(!e.extensionSurfaces?.has(t.surfaceId))return;const n=new Map(e.extensionSurfaces);n.delete(t.surfaceId),n.size===0?delete e.extensionSurfaces:e.extensionSurfaces=n},t6=(e,t,n)=>{const r=e.bySession.get(t);if(!r?.extensionSurfaces?.has(n))return e;const s={...r};return q5(s,{surfaceId:n}),{bySession:new Map(e.bySession).set(t,s),lastSequence:new Map(e.lastSequence)}},n6=new Set(["running","completed","cancelled","failed"]),ql=e=>e.length>kh?e.slice(-kh):e,W5=e=>{const t=e;return!!t&&typeof t.id=="string"&&t.id.length>0&&typeof t.command=="string"&&n6.has(t.phase)&&typeof t.startedAt=="number"},r6=e=>{if(Array.isArray(e))return e.filter(W5).map(t=>typeof t.output=="string"&&t.output.length>kh?{...t,output:ql(t.output)}:t)},K5=(e,t)=>{const n=r6(t);if(n){if(n.length===0){e.bashExecutions?.length&&delete e.bashExecutions;return}e.bashExecutions=n}},s6=(e,t)=>{if(!W5(t))return;const n=e.bashExecutions??[],r=n.findIndex(l=>l.id===t.id),s=r>=0?n[r]:void 0,o=typeof t.output=="string"?ql(t.output):s?.output,i={...t,...o?{output:o}:{}};o||delete i.output;const a=[...n];r>=0?a[r]=i:a.push(i),e.bashExecutions=a},o6=(e,t)=>{const n=e.bashExecutions;if(!n)return;const r=n.findIndex(a=>a.id===t.id);if(r<0)return;const s=n[r],o=t.reset===!0?ql(t.output):ql(`${s.output??""}${t.delta}`);if(o===(s.output??""))return;const i=[...n];i[r]={...s,output:o},e.bashExecutions=i},i6=(e,t,n,r)=>{if(r.id&&e.bashExecutions?.some(i=>i.id===r.id)){const i=e.bashExecutions.filter(a=>a.id!==r.id);i.length>0?e.bashExecutions=i:delete e.bashExecutions}const{message:s}=r;if(!s||typeof s.id!="string"||s.customType!==Fl)return;const o={id:s.id,sessionId:n,directory:t,role:"extension",customType:Fl,details:s.details,createdAt:s.createdAt,text:"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(o.id,o),Un(e,o.id,"structure")},Er=["off","minimal","low","medium","high","xhigh","max"],a6={off:"Off",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},Ft=e=>e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",dn=e=>Ft(e)?e:null,c6=(e,t)=>{const n=e.filter(Ft),r=n.length>0?n:["off"];if(t&&r.includes(t))return t;const s=Er.indexOf(t);if(s===-1)return r[0];for(let o=s+1;o<Er.length;o+=1)if(r.includes(Er[o]))return Er[o];for(let o=s-1;o>=0;o-=1)if(r.includes(Er[o]))return Er[o];return r[0]},dm=e=>{if(Array.isArray(e?.thinkingLevels)&&e.thinkingLevels.length>0){const t=e.thinkingLevels,n=Er.filter(r=>t.includes(r));return n.length>0?n:["off"]}return e?.reasoning===!0||e?.supportsThinking===!0?Er.filter(t=>t!=="xhigh"&&t!=="max"):["off"]},Hd=e=>e.some(t=>t!=="off"&&Ft(t)),um=e=>{const t=dm(e);return Hd(t)?t:[]},zr=e=>e?Ft(e)?a6[e]:`${e.charAt(0).toUpperCase()}${e.slice(1)}`:"Default",l6=(e,t)=>t<=1||!Number.isFinite(e)?0:Math.min(t-1,Math.max(0,Math.round(e*(t-1)))),fm=(e,t,n)=>{const r=e.filter(Ft);if(!Hd(r))return;const s=[void 0,...r],o=Ft(t)&&r.includes(t)?t:void 0,i=s.indexOf(o);return s[(i+n+s.length)%s.length]},G5=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return`${t}/${n}`},Z5=(e,t)=>{if(!(!t||!e))return dn(e[t])??void 0},Wg=e=>{if(e.thinking)return e.thinking;const t=G5(e.model);return Z5(e.defaultThinkingByModel,t)??dn(e.defaultThinking)??void 0},xc=e=>{const t=dm(e);if(!Hd(t))return;const n=G5({providerId:e.providerId,modelId:e.modelId}),r=Z5(e.defaultThinkingByModel,n)??(Ft(e.previousThinking)?e.previousThinking:void 0)??dn(e.defaultThinking)??void 0;if(r)return c6(t,r)},Kg=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return{providerId:t,modelId:n}},d6=e=>{let t;if(e.messages)for(const s of e.messages){if(s.role!=="assistant")continue;const o=Kg(s.model),i=dn(s.thinkingLevel)??void 0;if(!o&&!i)continue;const a=typeof s.createdAt=="number"&&Number.isFinite(s.createdAt)?s.createdAt:0;(!t||a>=t.createdAt)&&(t={createdAt:a,...o?{model:o}:{},...i?{thinkingLevel:i}:{}})}const n=t?.model??Kg(e.model),r=t?.thinkingLevel??dn(e.thinking)??void 0;return{...n?{model:n}:{},...r?{thinking:r}:{}}},Gg=new WeakMap,u6=e=>{const t=Gg.get(e);if(t)return t;const n={id:e.id,type:e.type,text:e.text,streaming:e.streaming,...e.tool?{tool:e.tool}:{},...e.attachment?{attachment:e.attachment}:{},...e.file?{file:e.file}:{}};return Gg.set(e,n),n},f6=(e,t)=>{const n=new Set,r=new Set;for(let s=t.length-1;s>=0;s-=1){const o=t[s];if(!o||o.role!=="assistant")continue;const i=Od(e,o.parentId);if(!i)continue;const a=!!(o.text||o.thinking||(e.partOrder.get(o.id)?.length??0)>0);if(o.error&&!a&&n.has(i)){r.add(o.id);continue}o.error||n.add(i)}return r},h6=(e,t,n,r)=>n.id===t.id&&n.role===t.role&&n.parentId===Od(e,t.parentId)&&n.text===t.text&&n.thinking===t.thinking&&n.render===t.render&&n.streaming===t.streaming&&n.createdAt===t.createdAt&&n.durationMs===t.durationMs&&n.error===t.error&&n.model===t.model&&n.thinkingLevel===t.thinkingLevel&&n.usage===t.usage&&n.parts.length===r.length&&n.parts.every((s,o)=>s===r[o]),p6=(e,t,n)=>{const r=e.partOrder.get(t.id)??[],s=[];for(const i of r){const a=e.parts.get(i);a&&s.push(u6(a))}if(n&&h6(e,t,n,s))return n;const o=Od(e,t.parentId);return{id:t.id,role:t.role,...o?{parentId:o}:{},...t.customType!==void 0?{customType:t.customType}:{},...t.data!==void 0?{data:t.data}:{},...t.details!==void 0?{details:t.details}:{},...t.render!==void 0?{render:t.render}:{},text:t.text,thinking:t.thinking,streaming:t.streaming,createdAt:t.createdAt,...t.durationMs!==void 0?{durationMs:t.durationMs}:{},...t.error?{error:t.error}:{},...t.model?{model:t.model}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{},...t.usage?{usage:t.usage}:{},parts:s}},Y5=(e,t)=>{const n=Na(e),r=f6(e,n),s=t?new Map(t.projection.messages.map(i=>[i.id,i])):null,o=[];for(const i of n)r.has(i.id)||o.push(p6(e,i,s?.get(i.id)));return t&&t.projection.sessionId===e.sessionId&&t.projection.directory===e.directory&&t.projection.lifecycle===e.lifecycle&&t.projection.model===e.model&&t.projection.thinking===e.thinking&&t.projection.queue.steering===e.queue.steering&&t.projection.queue.followUp===e.queue.followUp&&t.projection.messages.length===o.length&&t.projection.messages.every((i,a)=>i===o[a])?t.projection:{sessionId:e.sessionId,directory:e.directory,lifecycle:e.lifecycle,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},queue:{...e.queue},messages:o}},X5=(e,t)=>{if(delete e.runningCommand,t?.lifecycle==="busy"&&t.command&&t.isStreaming!==!0){if(e.lifecycle="busy",e.retry=void 0,e.runningCommand=t.command,t.settleWhenIdle){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[a,l]of e.messages)l.streaming&&e.messages.set(a,{...l,streaming:!1})}return}const n=[],r=[];for(const[a,l]of e.parts){const d=l.tool?.state;if(l.type!=="tool"||d!=="running"&&d!=="pending")continue;r.push(a);const f=l.tool?.toolCallId?e.toolsByCallId.get(l.tool.toolCallId):void 0;f&&n.push(f)}if(!(t?.isStreaming===!0||t?.lifecycle==="busy"||t?.lifecycle==="retry"||t?.inferFromRunningTools===!0&&n.length>0)){if(e.retry=void 0,t?.settleWhenIdle){e.streamingMessages=new Set,e.messages=new Map(e.messages);for(const[a,l]of e.messages)l.streaming&&e.messages.set(a,{...l,streaming:!1})}return}e.lifecycle=t?.lifecycle==="retry"?"retry":"busy",e.retry=e.lifecycle==="retry"?t?.retry:void 0,e.streamingMessages=new Set(e.streamingMessages);for(const a of r){const l=e.parts.get(a);l&&e.parts.set(a,{...l,streaming:!0})}let o=n[n.length-1];if(!o){const a=Na(e);for(let l=a.length-1;l>=0;l-=1){const d=a[l];if(d?.role==="assistant"){o=d.id;break}}}if(!o)return;const i=e.messages.get(o);!i||i.role!=="assistant"||(e.messages.set(o,{...i,streaming:!0}),e.streamingMessages.add(o))},Wl=e=>{const t=Ul(),n=Date.now(),r=y8(t,e.session.id,e.session.directory);r.lastSequence=e.lastSequence,r.hasMoreBefore=e.hasMoreBefore===!0,r.beforeCursor=e.hasMoreBefore===!0&&typeof e.beforeCursor=="string"?e.beforeCursor:void 0,Array.isArray(e.extensionStatuses)&&(r.extensionStatuses=new Map(e.extensionStatuses.map(i=>[i.key,i.text]))),Array.isArray(e.extensionWidgets)&&(r.extensionWidgets=new Map(e.extensionWidgets.map(i=>[i.key,{lines:i.lines,placement:i.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(e.extensionDialogs)&&(r.extensionDialogs=e.extensionDialogs.filter(i=>typeof i.requestId=="string"&&typeof i.method=="string"&&typeof i.title=="string")),Array.isArray(e.extensionPanels)&&(r.extensionPanels=new Map(e.extensionPanels.filter(i=>typeof i?.id=="string"&&i.id.length>0).map(i=>[i.id,i]))),Array.isArray(e.extensionApps)&&(r.extensionApps=new Map(e.extensionApps.filter(i=>typeof i?.appId=="string"&&i.appId.length>0).map(i=>[i.appId,i]))),r.extensionTitle=e.extensionTitle,e.extensionWorking&&(r.extensionWorking={...e.extensionWorking}),e.extensionDraftTracked===!0&&(r.extensionDraftTracked=!0);const s=U5(e.extensionSurfaces);s&&(r.extensionSurfaces=s),K5(r,e.bashExecutions);for(const{message:i,parts:a}of e.messages??[]){const l=i.role==="extension",d=l?F5(i.render):void 0,f={id:i.id,sessionId:e.session.id,directory:e.session.directory,role:i.role,...l&&i.customType?{customType:i.customType}:{},...l&&i.data!==void 0?{data:i.data}:{},...l&&i.details!==void 0?{details:i.details}:{},...d?{render:d}:{},...i.parentId?{parentId:i.parentId}:{},createdAt:i.createdAt,text:i.text??"",thinking:i.role==="assistant"?i.thinking??"":"",streaming:!1,...i.role==="assistant"&&i.durationMs!==void 0?{durationMs:i.durationMs}:{},...i.role==="assistant"&&i.error?{error:i.error}:{},...i.role==="assistant"&&i.model?{model:i.model}:{},...i.role==="assistant"&&i.thinkingLevel?{thinkingLevel:i.thinkingLevel}:{},...i.role==="assistant"&&i.usage?{usage:i.usage}:{}};r.messages.set(i.id,f);const u=[];for(const h of a){const m=h.type==="tool"?Ro(h.startedAt,e.serverNow,n):void 0,g=h.type==="tool"?Ro(h.endedAt,e.serverNow,n):void 0,x={id:h.id,index:h.index,type:h.type,text:h.text??"",streaming:!1,...h.type==="tool"?{tool:{toolCallId:h.toolCallId??h.id,name:h.name??"unknown",...h.input!==void 0?{input:h.input}:{},...h.output!==void 0?{output:h.output}:{},...h.render!==void 0?{render:h.render}:{},...typeof h.error=="string"?{error:h.error}:{},...h.metadata!==void 0?{metadata:h.metadata}:{},...h.isError!==void 0?{isError:h.isError}:{},state:h.state??"completed",...m!==void 0?{startedAt:m}:{},...g!==void 0?{endedAt:g}:{}}}:{},...h.type==="attachment"&&h.attachment?{attachment:h.attachment}:{},...h.type==="file"?{file:{...typeof h.mime=="string"?{mime:h.mime}:{},...typeof h.filename=="string"?{filename:h.filename}:{},...typeof h.url=="string"?{url:h.url}:{}}}:{}};r.parts.set(h.id,x),u.push(h.id),h.type==="tool"&&h.toolCallId&&r.toolsByCallId.set(h.toolCallId,i.id)}r.partOrder.set(i.id,u)}const o=d6({model:e.session.model,thinking:e.session.thinking,messages:r.messages.values()});return o.model&&(r.model=o.model),o.thinking&&(r.thinking=o.thinking),r.compaction=e.compaction,X5(r,{...e.isStreaming!==void 0?{isStreaming:e.isStreaming}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.command?{command:e.command}:{},...e.retry?{retry:e.retry}:{},inferFromRunningTools:!0}),t.lastSequence.set(e.session.id,e.lastSequence),{state:t,session:r}},qu=(e,t)=>{const n=e.lastSequence.get(t.sessionId)??-1;if(t.sequence<=n)return{state:e,didApply:!1};if(t.name==="session.deleted"){const i=new Map(e.bySession);i.delete(t.sessionId);const a=new Map(e.lastSequence);return a.set(t.sessionId,t.sequence),{state:{bySession:i,lastSequence:a},didApply:!0,sessionId:t.sessionId}}if(t.name==="session.openUrl"){const i=new Map(e.lastSequence);return i.set(t.sessionId,t.sequence),{state:{bySession:e.bySession,lastSequence:i},didApply:!0,sessionId:t.sessionId}}const r=e.bySession.get(t.sessionId),s=r?{...r,lastSequence:t.sequence,...t.name==="session.lifecycle"?{lifecycle:t.payload.state}:{},...t.name==="session.queue"?{queue:{...t.payload}}:{},...t.name==="session.model"?{model:t.payload.model}:{},...t.name==="session.thinking"?{thinking:t.payload.thinking}:{}}:{sessionId:t.sessionId,directory:t.directory,lastSequence:t.sequence,lifecycle:"idle",messages:new Map,partOrder:new Map,parts:A5(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};switch(t.name){case"session.snapshot":if(t.payload?.snapshot){if(s.lifecycle=t.payload.snapshot.lifecycle??(t.payload.snapshot.isStreaming?"busy":"idle"),s.retry=s.lifecycle==="retry"?t.payload.snapshot.retry:void 0,s.compaction=t.payload.snapshot.compaction,t.payload.snapshot.model&&(s.model=t.payload.snapshot.model),t.payload.snapshot.thinking&&(s.thinking=t.payload.snapshot.thinking),t.payload.snapshot.queue&&(s.queue={...t.payload.snapshot.queue}),Array.isArray(t.payload.snapshot.extensionStatuses)&&(s.extensionStatuses=new Map(t.payload.snapshot.extensionStatuses.map(a=>[a.key,a.text]))),Array.isArray(t.payload.snapshot.extensionWidgets)&&(s.extensionWidgets=new Map(t.payload.snapshot.extensionWidgets.map(a=>[a.key,{lines:a.lines,placement:a.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(t.payload.snapshot.extensionDialogs)&&(s.extensionDialogs=t.payload.snapshot.extensionDialogs.filter(a=>typeof a.requestId=="string"&&typeof a.method=="string"&&typeof a.title=="string")),Array.isArray(t.payload.snapshot.extensionPanels)){const a=new Map;for(const l of t.payload.snapshot.extensionPanels)typeof l?.id=="string"&&l.id.length>0&&a.set(l.id,l);s.extensionPanels=a}if(Array.isArray(t.payload.snapshot.extensionApps)){const a=new Map;for(const l of t.payload.snapshot.extensionApps)typeof l?.appId=="string"&&l.appId.length>0&&a.set(l.appId,l);s.extensionApps=a}s.extensionTitle=t.payload.snapshot.extensionTitle,t.payload.snapshot.extensionWorking?s.extensionWorking={...t.payload.snapshot.extensionWorking}:delete s.extensionWorking,t.payload.snapshot.extensionDraftTracked===!0?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;const i=U5(t.payload.snapshot.extensionSurfaces);i?s.extensionSurfaces=i:delete s.extensionSurfaces,K5(s,t.payload.snapshot.bashExecutions),X5(s,{isStreaming:t.payload.snapshot.isStreaming,lifecycle:s.lifecycle,...t.payload.snapshot.command?{command:t.payload.snapshot.command}:{},...t.payload.snapshot.retry?{retry:t.payload.snapshot.retry}:{},settleWhenIdle:!0})}break;case"session.lifecycle":M8(s,t.payload);break;case"assistant.message.start":s.lifecycle=s.retry?"retry":"busy",delete s.runningCommand,s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages),t.payload.files?.length&&(rs(s),s.partOrder=new Map(s.partOrder)),I8(s,t.directory,t.payload),t.payload.role==="assistant"&&s.streamingMessages.add(t.payload.messageId),Un(s,t.payload.messageId,"structure");break;case"assistant.message.delta":rs(s),Vg(s,t.payload,"text")&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"assistant.message.end":s.messages=new Map(s.messages),rs(s),s.partOrder=new Map(s.partOrder),s.streamingMessages=new Set(s.streamingMessages),E8(s,t.payload),Un(s,t.payload.messageId,"structure");break;case"assistant.thinking.delta":rs(s),Vg(s,t.payload,"thinking")&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.tool.start":rs(s),s.partOrder=new Map(s.partOrder),s.toolsByCallId=new Map(s.toolsByCallId),Uu(s,"start",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.tool.update":rs(s),Uu(s,"update",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.tool.end":rs(s),Uu(s,"end",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Un(s,t.payload.messageId,"part");break;case"session.queue":s.queue={steering:t.payload.steering,followUp:t.payload.followUp};break;case"session.model":s.model=t.payload.model;break;case"session.thinking":s.thinking=t.payload.thinking;break;case"session.compaction":s.compaction={...t.payload};break;case"session.updated":break;case"session.input":break;case"session.bash":s6(s,t.payload.bash);break;case"session.bash.output":o6(s,t.payload);break;case"session.bash.recorded":i6(s,t.directory,t.sessionId,t.payload);break;case"session.tree.updated":s.sessionTreeRevision=(s.sessionTreeRevision??0)+1;break;case"session.error":s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages);for(const i of s.streamingMessages){const a=s.messages.get(i);a&&s.messages.set(i,{...a})}_8(s,t.payload.code,t.payload.message);break;case"session.interrupted":s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages);for(const i of s.streamingMessages){const a=s.messages.get(i);a&&s.messages.set(i,{...a})}j8(s,t.payload.streaming);break;case"extension.entry":H8(s,t.directory,t.sessionId,t.payload);break;case"extension.message":F8(s,t.directory,t.sessionId,t.payload);break;case"extension.notify":{const i=typeof t.payload.id=="string"&&t.payload.id.length>0?t.payload.id:void 0;if(i&&s.extensionNotices.some(a=>a.id===i)){const a=new Map(e.lastSequence);return a.set(t.sessionId,t.sequence),{state:{bySession:e.bySession,lastSequence:a},didApply:!0,sessionId:t.sessionId}}U8(s,t.payload);break}case"extension.catalog":q8(s,t.payload);break;case"extension.editor":W8(s,t.payload,t.sequence);break;case"extension.title":K8(s,t.payload);break;case"extension.status":B8(s,t.payload);break;case"extension.widget":V8(s,t.payload);break;case"extension.dialog":$8(s,t.payload);break;case"extension.dialog.dismiss":z8(s,t.payload);break;case"extension.ui":G8(s,t.payload);break;case"extension.app":Z8(s,t.payload);break;case"extension.working":X8(s,t.payload);break;case"extension.editor.track":t.payload.enabled?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;break;case"extension.custom":Q8(s,t.payload);break;case"extension.custom.frame":e6(s,t.payload);break;case"extension.custom.dismiss":q5(s,t.payload);break;case"extension.error":Y8(s,t.payload);break}const o={bySession:new Map(e.bySession),lastSequence:new Map(e.lastSequence)};return o.bySession.set(t.sessionId,s),o.lastSequence.set(t.sessionId,t.sequence),{state:o,didApply:!0,sessionId:t.sessionId}},m6={fetchHealth:o5,createStream:Bl},Wu=e=>e instanceof lt?{code:e.code,...e.message?{message:e.message}:{},...e.status!==void 0?{status:e.status}:{}}:e instanceof Error?{code:"DAEMON_REQUEST_FAILED",message:e.message}:{code:"DAEMON_REQUEST_FAILED"},g6=async(e,t=m6)=>{const n={phase:"idle",reducerState:{bySession:new Map,lastSequence:new Map},lastSequence:new Map,stream:null,errors:[],health:{state:"pending"}},r=async a=>e.retry?e.retry(a):a();n.phase="runtime-probe";const s=e.initialHealth??await r(()=>t.fetchHealth(e.signal,e.runtimeKey));if(s.state==="ready"){if(!(s.capabilities.includes(i5)&&typeof s.streamEpoch=="string"&&s.streamEpoch.length>0)){const l={code:"DAEMON_PROTOCOL_MISMATCH",message:"The Pi runtime does not advertise a restart-safe event stream (events.streamEpoch). Update the server."};return n.health={state:"unavailable",protocolVersion:s.protocolVersion,error:l},n.phase="failed",n.errors.push({phase:"runtime-probe",error:l}),n}n.health={state:"ready",protocolVersion:s.protocolVersion,capabilities:[...s.capabilities],streamEpoch:s.streamEpoch},n.streamEpoch=s.streamEpoch}else return n.health={state:"unavailable",protocolVersion:s.protocolVersion,error:{code:s.error?.code??"DAEMON_UNAVAILABLE",...s.error?.message?{message:s.error.message}:{}}},n.phase="failed",n.errors.push({phase:"runtime-probe",error:n.health.error}),n;n.phase="session-list";const o=a=>{for(const l of a)n.lastSequence.set(l.session.id,-1)};if(e.initialSessions)o(e.initialSessions);else try{const a=await r(()=>Ee.listSessions({...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new lt("DAEMON_PROTOCOL_MISMATCH","Session list omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new lt("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");o(a.sessions)}catch(a){if(n.errors.push({phase:"session-list",error:Wu(a)}),a instanceof lt&&a.code==="DAEMON_PROTOCOL_MISMATCH")return n.phase="failed",n}if(e.selectedSessionId){n.phase="session-hydrate";try{const a=e.initialDetail??await r(()=>Ee.getSession(e.selectedSessionId,{...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new lt("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new lt("DAEMON_REQUEST_FAILED","Session detail predates the current stream epoch");n.selectedSessionTiming={sessionId:a.session.id,isStreaming:a.isStreaming,lifecycle:a.lifecycle,...Number.isFinite(a.runStartedAt)?{runStartedAt:a.runStartedAt}:{},...Number.isFinite(a.serverNow)?{serverNow:a.serverNow}:{}};const{state:l}=Wl(a);n.reducerState=l,n.lastSequence.set(a.session.id,a.lastSequence)}catch(a){if(n.errors.push({phase:"session-hydrate",error:Wu(a)}),a instanceof lt&&a.code==="DAEMON_PROTOCOL_MISMATCH")return n.phase="failed",n}}n.phase="stream-attach";try{const a=e.selectedSessionId?n.lastSequence.get(e.selectedSessionId):e.fromSequence,l=t.createStream({onEvent:e.onEvent,onDisconnect:d=>e.onStreamDisconnect?.(d),onReconnect:()=>e.onStreamReconnect?.(),onTransportSwitch:()=>e.onTransportSwitch?.(),onEpochChange:d=>e.onEpochChange?.(d),onAuthRequired:()=>e.onAuthRequired?.()},{...typeof a=="number"&&a>=0?{fromSequence:a}:{},...n.streamEpoch?{streamEpoch:n.streamEpoch}:{},...e.runtimeKey?{runtimeKey:e.runtimeKey}:{},signal:e.signal});n.stream=l}catch(a){n.errors.push({phase:"stream-attach",error:Wu(a)})}const i=n.errors.some(a=>a.phase==="runtime-probe");return n.phase=i?"failed":"ready",n};let Zg=null;const J5=()=>(Zg??=a5(),Zg),y6=e=>({sessionId:e.sessionId,directory:e.directory,isStreaming:e.isStreaming,lastSequence:e.lastSequence,queue:e.queue??{steering:0,followUp:0},...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.compaction?{compaction:e.compaction}:{},...e.lastText?{lastText:e.lastText}:{},...e.lastThinking?{lastThinking:e.lastThinking}:{},...e.lastToolPart?{lastToolPart:e.lastToolPart}:{},lifecycle:e.lifecycle}),v6=()=>({bySession:new Map,lastSequence:new Map}),x6=(e,t)=>{const n=e.lastSequence.get(t.sessionId)??-1;if(t.lastSequence<=n)return{state:e,didUpdate:!1};const r={bySession:new Map(e.bySession),lastSequence:new Map(e.lastSequence)};return r.bySession.set(t.sessionId,y6(t)),r.lastSequence.set(t.sessionId,t.lastSequence),{state:r,didUpdate:!0}},b6={fetchHealth:o5,createStream:Bl},Yg=e=>e instanceof lt?{code:e.code,...e.message?{message:e.message}:{},...e.status!==void 0?{status:e.status}:{}}:e instanceof Error?{code:"DAEMON_REQUEST_FAILED",message:e.message}:{code:"DAEMON_REQUEST_FAILED"},w6=async(e,t=b6)=>{const n={phase:"idle",snapshotState:v6(),reducerState:{bySession:new Map,lastSequence:new Map},stream:null,lastSequence:e.lastKnownSequence??-1},r=async a=>e.retry?e.retry(a):a();n.phase="health-check";const s=await r(()=>t.fetchHealth(e.signal,e.runtimeKey,{fresh:!0}));if(s.state!=="ready")return n.phase="unavailable",n.error={code:s.error?.code??"DAEMON_UNAVAILABLE",...s.error?.message?{message:s.error.message}:{}},n;if(!s.capabilities.includes(i5)||typeof s.streamEpoch!="string"||s.streamEpoch.length===0)return n.phase="failed",n.error={code:"DAEMON_PROTOCOL_MISMATCH",message:"The Pi runtime does not advertise a restart-safe event stream (events.streamEpoch). Update the server."},n;n.epoch=s.streamEpoch;const o=typeof e.streamEpoch=="string"&&e.streamEpoch.length>0?e.streamEpoch:null,i=o!==null&&o!==n.epoch;i&&(n.epochChanged=!0),n.phase="snapshot-fetch";try{const a=await r(()=>Ee.getSession(e.sessionId,{directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new lt("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.epoch)throw new lt("DAEMON_REQUEST_FAILED","Session detail predates the current stream epoch");const l=Wl(a);n.reducerState=l.state,(a.lifecycle==="busy"||a.lifecycle==="retry")&&Number.isFinite(a.runStartedAt)&&(n.runStartedAt=a.runStartedAt,Number.isFinite(a.serverNow)&&(n.serverNow=a.serverNow));const d={protocolVersion:1,kind:"event",name:"session.snapshot",sequence:a.lastSequence,sessionId:a.session.id,directory:a.session.directory,payload:{snapshot:{sessionId:a.session.id,directory:a.session.directory,lastSequence:a.lastSequence,isStreaming:a.isStreaming===!0,queue:{steering:0,followUp:0},lifecycle:a.lifecycle??(a.isStreaming?"busy":"idle"),...a.command?{command:a.command}:{},...a.retry?{retry:a.retry}:{},...a.compaction?{compaction:a.compaction}:{},...Number.isFinite(a.runStartedAt)?{runStartedAt:a.runStartedAt}:{},...Number.isFinite(a.serverNow)?{serverNow:a.serverNow}:{},...a.session.model?{model:a.session.model}:{},...a.session.thinking?{thinking:a.session.thinking}:{}}}},f=x6(n.snapshotState,d.payload.snapshot);n.snapshotState=f.state;const u=e.lastKnownSequence??-1;n.lastSequence=i?a.lastSequence:o!==null&&u>=0?u:Math.max(u,a.lastSequence)}catch(a){const l=Yg(a);return l.code==="INVALID_SESSION",n.phase="failed",n.error=l,n}n.phase="stream-attach";try{n.stream=t.createStream({onEvent:e.onEvent,onDisconnect:a=>e.onStreamDisconnect?.(a),onReconnect:()=>e.onStreamReconnect?.(),onTransportSwitch:()=>e.onTransportSwitch?.(),onEpochChange:a=>e.onEpochChange?.(a),onAuthRequired:()=>e.onAuthRequired?.()},{fromSequence:n.lastSequence,streamEpoch:n.epoch,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{},signal:e.signal})}catch(a){return n.phase="failed",n.error=Yg(a),n}return n.phase="ready",n},S6=new Set(["assistant.message.delta","assistant.thinking.delta","session.tool.update"]),C6=e=>S6.has(e.name),Kl=e=>e.name==="assistant.message.delta"||e.name==="assistant.thinking.delta"?e:null,k6=(e,t)=>{const n=Kl(e),r=Kl(t);return!n||!r||n.name!==r.name||n.sessionId!==r.sessionId?!1:n.payload.messageId===r.payload.messageId&&n.payload.contentIndex===r.payload.contentIndex&&(n.payload.partId??"")===(r.payload.partId??"")},M6=(e,t)=>{const n=Kl(e),r=Kl(t);return!n||!r||n.name!==r.name?t:{...r,payload:{...r.payload,delta:O5(n.payload.delta,r.payload.delta)}}},I6=(e,t)=>e.name==="session.tool.update"&&t.name==="session.tool.update"&&e.sessionId===t.sessionId&&e.payload.toolCallId===t.payload.toolCallId&&e.payload.partId===t.payload.partId&&e.payload.messageId===t.payload.messageId,Ku=e=>{const t=[];for(const n of e){const r=t[t.length-1];r&&k6(r,n)?t[t.length-1]=M6(r,n):r&&I6(r,n)?t[t.length-1]=n:t.push(n)}return t};class E6{constructor(t){this.publish=t}publish;buffer=[];scheduled="none";generation=0;rafId=0;push(t){if(!C6(t)){const n=this.takeBuffer();this.publish(Ku([...n,t]));return}this.buffer.push(t),this.schedule()}flush(){const t=this.takeBuffer();t.length!==0&&this.publish(Ku(t))}dispose(){this.flush()}takeBuffer(){if(this.generation+=1,this.scheduled="none",this.rafId&&typeof globalThis.cancelAnimationFrame=="function"&&globalThis.cancelAnimationFrame(this.rafId),this.rafId=0,this.buffer.length===0)return[];const t=this.buffer;return this.buffer=[],t}schedule(){if(this.scheduled!=="none")return;const t=++this.generation,n=()=>{if(t!==this.generation)return;this.scheduled="none",this.rafId=0;const r=this.buffer;this.buffer=[],r.length!==0&&this.publish(Ku(r))};if(typeof globalThis.requestAnimationFrame=="function"){this.scheduled="frame",this.rafId=globalThis.requestAnimationFrame(n);return}this.scheduled="microtask",queueMicrotask(n)}}const j6=[{name:"undo",description:"Undo the last message"},{name:"redo",description:"Redo previously undone messages"},{name:"timeline",description:"Open the conversation timeline"},{name:"compact",description:"Compress session history using AI to reduce context size"}],Cr=()=>j6.map(e=>({id:`system:${e.name}`,name:e.name,invocationName:e.name,source:"system",description:e.description})),_6=e=>e.map(t=>{if(t.source==="skill"){const n=t.name.startsWith("skill:")?t.name:`skill:${t.name}`,r=n.slice(6);return{id:`skill:${t.scope??"runtime"}:${n}`,name:r,invocationName:n,source:"skill",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}}return t.source==="extension"?{id:`extension:${t.scope??"runtime"}:${t.name}`,name:t.name,invocationName:t.name,source:"extension",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}:{id:`prompt:${t.scope??"runtime"}:${t.name}`,name:t.name,invocationName:t.name,source:"prompt",...t.description?{description:t.description}:{},...t.scope?{scope:t.scope}:{}}}),T6=3e4,Xt=new Map;let Q5=0;const Th=new Set,eb=()=>{Q5+=1;for(const e of Th)e()},Gu=()=>Q5,A6=e=>(Th.add(e),()=>Th.delete(e)),N6=20,Fd=(e,t)=>`${e}
5
+ ${t?.trim()??""}`,Xg=(e,t)=>Xt.get(Fd(e,t))?.commands,L6=(e,t)=>{const n=Xt.get(Fd(e,t));return n?{...n}:void 0},R6=(e,t=Date.now())=>t-e.fetchedAt<T6,P6=(e,t,n,r)=>{const s=Fd(e,t);for(Xt.delete(s),Xt.set(s,{commands:n,fetchedAt:r?.fetchedAt??Date.now(),promptSignature:r?.promptSignature??"",skillSignature:r?.skillSignature??""});Xt.size>N6;){const o=Xt.keys().next().value;if(typeof o!="string")break;Xt.delete(o)}},D6=(e,t,n,r)=>{const s=Fd(e,t),o=Xt.get(s);return o?(Xt.delete(s),Xt.set(s,{...o,promptSignature:n,skillSignature:r}),!0):!1},ul=e=>{if(typeof e=="string"&&e.trim().length>0){const t=`
6
+ ${e.trim()}`;for(const n of[...Xt.keys()])n.endsWith(t)&&Xt.delete(n)}else Xt.clear();eb()},O6=()=>{Xt.clear(),eb()};function Ah(e,t=50){if(typeof e!="string"||e.trim().length===0)return"";const r=e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[attachment:[^\]]+\]/g," ").replace(/(^|\s)@[\w.-]+/g," ").replace(/<[^>]+>/g," ").replace(/\r\n/g,`
7
+ `).split(`
8
+ `).map(o=>o.trim()).find(o=>o.length>0);if(!r)return"";const s=r.replace(/\s+/g," ");return s.length<=t?s:`${s.slice(0,t).trimEnd()}…`}const Zu="pichamber.piSessionCatalog.v1",Gl=1,H6=250,tb=4,nb=512,Nh=2e3,Jg=512,F6=8192,B6=4096,V6=16384,li=(e,t,n=!1)=>typeof e=="string"&&e.length<=t&&(n||e.length>0),fl=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,Qg=e=>{if(!e||typeof e!="object")return null;const t=e;if(!fl(t.updatedAt)||!Array.isArray(t.directories)||t.directories.length>nb)return null;const n=new Map,r=new Map,s=new Map;let o=0;for(const i of t.directories){if(!i||typeof i!="object")return null;const a=i.directory,l=i.sessions;if(!li(a,F6)||!Array.isArray(l))return null;const d=de(a);if(!d||r.has(d)||(o+=l.length,o>Nh))return null;const f=[];for(const u of l){if(!u||typeof u!="object")return null;const h=u;if(!li(h.id,Jg)||h.parentId!==null&&!li(h.parentId,Jg)||!li(h.title,B6,!0)||typeof h.archived!="boolean"||!fl(h.createdAt)||!fl(h.updatedAt)||h.preview!==void 0&&!li(h.preview,V6,!0)||h.messageCount!==void 0&&(!Number.isSafeInteger(h.messageCount)||h.messageCount<0)||n.has(h.id))return null;const m=h.id;n.set(m,{id:m,directory:d,parentId:h.parentId,title:h.title,archived:h.archived,createdAt:h.createdAt,updatedAt:h.updatedAt,...h.preview!==void 0?{preview:h.preview}:{},...h.messageCount!==void 0?{messageCount:h.messageCount}:{},lifecycle:"idle",hydrated:!1}),f.push(m)}r.set(d,f),s.set(d,"idle")}return{byId:n,byDirectory:r,listStatusByDirectory:s}},e0=e=>{if(!e)return null;try{const t=JSON.parse(e);if(t.version!==Gl||!t.runtimes||typeof t.runtimes!="object"||Array.isArray(t.runtimes))return null;const n=Object.entries(t.runtimes);return n.length>tb?null:{version:Gl,runtimes:Object.fromEntries(n)}}catch{return null}},$6=(e,t)=>{const n=[];let r=0;const s=new Set([...e.byDirectory.keys(),...e.listStatusByDirectory.keys()]);for(const o of s){if(n.length>=nb||r>=Nh)break;const i=de(o);if(!i)continue;const a=[];for(const l of e.byDirectory.get(o)??[]){if(r>=Nh)break;const d=e.byId.get(l);!d||de(d.directory)!==i||(a.push({id:d.id,parentId:d.parentId,title:d.title,archived:d.archived,createdAt:d.createdAt,updatedAt:d.updatedAt,...d.preview!==void 0?{preview:d.preview}:{},...d.messageCount!==void 0?{messageCount:d.messageCount}:{}}),r+=1)}n.push({directory:i,sessions:a})}return{updatedAt:t,directories:n}},z6=(e=Gt(),t={})=>{const n=t.flushDelayMs??H6,r=new Map;let s=null,o=!1;const i=u=>{if(!u)return null;try{const h=e0(e.getItem(Zu));return!h||!Object.prototype.hasOwnProperty.call(h.runtimes,u)?null:Qg(h.runtimes[u])}catch{return null}},a=()=>{if(s!==null&&clearTimeout(s),s=null,r.size===0)return;let u={version:Gl,runtimes:{}};try{const x=e0(e.getItem(Zu));x&&(u=x)}catch{}const h=new Map(Object.entries(u.runtimes));let m=[...h.values()].reduce((x,b)=>fl(b?.updatedAt)?Math.max(x,b.updatedAt):x,0);for(const[x,b]of r)m=Math.max(Date.now(),m+1),h.set(x,$6(b,m));r.clear();const g=[...h.entries()].filter(([,x])=>Qg(x)!==null).sort(([,x],[,b])=>b.updatedAt-x.updatedAt).slice(0,tb);try{e.setItem(Zu,JSON.stringify({version:Gl,runtimes:Object.fromEntries(g)}))}catch{}},l=(u,h)=>{o||!u||(r.set(u,h),s===null&&(s=setTimeout(a,Math.max(0,n))))},d=()=>a(),f=()=>{document.visibilityState==="hidden"&&a()};return t.registerLifecycleListeners&&typeof window<"u"&&(window.addEventListener("pagehide",d,{capture:!0}),window.addEventListener("beforeunload",d,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",f),document.addEventListener("freeze",d))),{read:i,schedule:l,flush:a,dispose:()=>{o||(a(),o=!0,t.registerLifecycleListeners&&typeof window<"u"&&(window.removeEventListener("pagehide",d,{capture:!0}),window.removeEventListener("beforeunload",d,{capture:!0}),typeof document<"u"&&(document.removeEventListener("visibilitychange",f),document.removeEventListener("freeze",d))))}}},U6={read:()=>null,schedule:()=>{},flush:()=>{},dispose:()=>{}};let t0=null;const q6=()=>typeof window>"u"?U6:(t0??=z6(Gt(),{registerLifecycleListeners:!0}),t0),Yn=Gt(),Lh="projects",Rh="activeProjectId",W6=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim().replace(/\/+$/,""):""},hm=()=>{const e=Nd().trim().replace(/\/+$/,"");return e||""},Bd=()=>{const e=hm();return e?`${Lh}:${encodeURIComponent(e)}`:Lh},rb=()=>{const e=hm();return e?`${Rh}:${encodeURIComponent(e)}`:Rh},sb=()=>{const e=hm();if(!e)return!0;const t=W6();return!!(t&&e===t)},K6=(e,t)=>{const n=e.trim();return!n.startsWith("~")||!t?n:n==="~"?t:n.startsWith("~/")||n.startsWith("~\\")?`${t}${n.slice(1)}`:n},G6=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,ob=e=>{if(typeof e!="string")return;const t=e.trim();if(!t)return;const n=t.indexOf("/");if(!(n<=0||n>=t.length-1))return t},ib=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&G6.test(t)?t.toLowerCase():null},pm=e=>{const t=e.trim();if(!t)return"";const n=Yn.getItem("homeDirectory")||nt.getState().homeDirectory||"",s=K6(t,n).replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},Z6=e=>{const t=pm(e);if(!t||t==="/")return"Root";const n=t.split("/").filter(Boolean);return(n[n.length-1]||t).replace(/[-_]/g," ").replace(/\b\w/g,s=>s.toUpperCase())},Y6=e=>{if(!e||typeof e!="object")return;const t=e,n=typeof t.mime=="string"?t.mime.trim():"",r=typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)?Math.max(0,Math.round(t.updatedAt)):0,s=t.source==="custom"||t.source==="auto"?t.source:null;if(!(!n||!r||!s))return{mime:n,updatedAt:r,source:s}},X6=e=>{const t=typeof e.type=="string"?e.type.trim().toLowerCase():"";if(t==="image/png"||t==="image/jpeg"||t==="image/svg+xml")return t;const n=e.name.toLowerCase();return n.endsWith(".png")?"image/png":n.endsWith(".jpg")||n.endsWith(".jpeg")?"image/jpeg":n.endsWith(".svg")?"image/svg+xml":null},J6=async e=>await new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>{n(new Error("Failed to read icon file"))},r.onload=()=>{const s=typeof r.result=="string"?r.result:"";if(!s){n(new Error("Failed to read icon file"));return}t(s)},r.readAsDataURL(e)}),ab=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set,r=new Set;for(const s of e){if(!s||typeof s!="object")continue;const o=s,i=typeof o.path=="string"?o.path.trim():"";if(!i)continue;const a=pm(i);if(!a)continue;const l=Jp(a);if(!l||n.has(l)||r.has(a))continue;n.add(l),r.add(a);const d={id:l,path:a};if(typeof o.label=="string"&&o.label.trim().length>0&&(d.label=o.label.trim()),typeof o.icon=="string"&&o.icon.trim().length>0&&(d.icon=o.icon.trim()),o.iconImage===null)d.iconImage=null;else{const u=Y6(o.iconImage);u&&(d.iconImage=u)}typeof o.color=="string"&&o.color.trim().length>0&&(d.color=o.color.trim());const f=ob(o.defaultModel);if(f&&(d.defaultModel=f),o.iconBackground===null)d.iconBackground=null;else{const u=ib(o.iconBackground);u&&(d.iconBackground=u)}typeof o.addedAt=="number"&&Number.isFinite(o.addedAt)&&o.addedAt>=0&&(d.addedAt=o.addedAt),typeof o.lastOpenedAt=="number"&&Number.isFinite(o.lastOpenedAt)&&o.lastOpenedAt>=0&&(d.lastOpenedAt=o.lastOpenedAt),typeof o.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=o.sidebarCollapsed),t.push(d)}return t},Q6=()=>{try{const e=Yn.getItem(Bd())||(sb()?Yn.getItem(Lh):null);return e?ab(JSON.parse(e)):[]}catch{return[]}},ek=()=>{try{const e=Yn.getItem(Bd()+":manualOrder");if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}},n0=()=>{try{const e=Yn.getItem(rb())||(sb()?Yn.getItem(Rh):null);if(typeof e=="string"&&e.trim().length>0)return e.trim()}catch{return null}return null},cb=e=>{try{const t=rb();e?Yn.setItem(t,e):Yn.removeItem(t)}catch{}},lb=(e,t)=>{try{Yn.setItem(Bd(),JSON.stringify(e))}catch{}cb(t)},tk=e=>{cb(e),Vr({activeProjectId:e})},di=(e,t,n)=>{lb(e,t),n&&Ph(n),Vr({projects:e,activeProjectId:t??void 0})},Ph=e=>{try{Yn.setItem(Bd()+":manualOrder",JSON.stringify(e))}catch{}},Dh=Q6(),nk=Dh.some(e=>e.id===n0())?n0():Dh[0]?.id??null,at=Lt()(mr((e,t)=>({projects:Dh,activeProjectId:nk,manualProjectOrder:ek(),validateProjectPath:n=>{if(typeof n!="string"||n.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const r=pm(n);return r?{ok:!0,normalizedPath:r}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(n,r)=>{const{validateProjectPath:s}=t(),o=s(n);if(!o.ok||!o.normalizedPath)return null;const i=o.normalizedPath,a=t().projects.find(m=>m.path===i);if(a)return t().setActiveProject(a.id),a;const l=Date.now(),d=r?.label?.trim()||Z6(i),u={id:Jp(i),path:i,label:d,addedAt:l,lastOpenedAt:l},h=[...t().projects,u];return e({projects:h}),c5()&&console.info("[ProjectsStore] Added project",u),t().setActiveProject(u.id),u},removeProject:n=>{const r=t(),s=r.projects.filter(a=>a.id!==n);let o=r.activeProjectId;r.activeProjectId===n&&(o=s[0]?.id??null);const i=t().manualProjectOrder.filter(a=>a!==n);if(e({projects:s,activeProjectId:o,manualProjectOrder:i}),di(s,o,i),o){const a=s.find(l=>l.id===o);a&&nt.getState().setDirectory(a.path,{showOverlay:!1})}else nt.getState().goHome()},setActiveProject:n=>{const{projects:r,activeProjectId:s}=t();if(s===n)return;const o=r.find(l=>l.id===n);if(!o)return;const i=Date.now(),a=r.map(l=>l.id===n?{...l,lastOpenedAt:i}:l);e({projects:a,activeProjectId:n}),di(a,n,t().manualProjectOrder),nt.getState().setDirectory(o.path,{showOverlay:!1})},setActiveProjectIdOnly:n=>{const{projects:r,activeProjectId:s}=t();s===n||!r.some(o=>o.id===n)||(e({activeProjectId:n}),tk(n))},renameProject:(n,r)=>{const s=r.trim();if(!s)return;const{projects:o,activeProjectId:i}=t(),a=o.map(l=>l.id===n?{...l,label:s}:l);e({projects:a}),di(a,i,t().manualProjectOrder)},updateProjectMeta:(n,r)=>{const{projects:s,activeProjectId:o}=t(),i=s.map(a=>{if(a.id!==n)return a;const l={...a};if(r.label!==void 0){const d=r.label.trim();d&&(l.label=d)}if(r.icon!==void 0&&(l.icon=r.icon),r.color!==void 0&&(l.color=r.color),r.iconBackground!==void 0&&(l.iconBackground=ib(r.iconBackground)),r.defaultModel!==void 0){const d=ob(r.defaultModel);d?l.defaultModel=d:delete l.defaultModel}return l});e({projects:i}),di(i,o,t().manualProjectOrder)},uploadProjectIcon:async(n,r)=>{const s=X6(r);if(!s)return{ok:!1,error:"Only PNG, JPEG, and SVG are supported"};if(!Number.isFinite(r.size)||r.size<=0)return{ok:!1,error:"Icon file is empty"};if(r.size>5*1024*1024)return{ok:!1,error:"Icon exceeds size limit (5 MB)"};try{const i=(await J6(r)).replace(/^data:[^;]+;/i,`data:${s};`),a=await Nt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:i})});if(!a.ok)return{ok:!1,error:(await a.json().catch(()=>null))?.error||"Failed to upload project icon"};const l=await a.json().catch(()=>null);return l?.settings&&t().synchronizeFromSettings(l.settings),{ok:!0}}catch(o){return{ok:!1,error:(o instanceof Error?o.message:String(o))||"Failed to upload project icon"}}},removeProjectIcon:async n=>{try{const r=await Nt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"DELETE",headers:{Accept:"application/json"}});if(!r.ok)return{ok:!1,error:(await r.json().catch(()=>null))?.error||"Failed to remove project icon"};const s=await r.json().catch(()=>null);return s?.settings&&t().synchronizeFromSettings(s.settings),{ok:!0}}catch(r){return{ok:!1,error:(r instanceof Error?r.message:String(r))||"Failed to remove project icon"}}},discoverProjectIcon:async()=>({ok:!0,skipped:!0,reason:"unsupported"}),reorderProjects:(n,r)=>{const{projects:s,activeProjectId:o}=t();if(n<0||n>=s.length||r<0||r>=s.length||n===r)return;const i=[...s],[a]=i.splice(n,1);i.splice(r,0,a);const l=i.map(d=>d.id);e({projects:i,manualProjectOrder:l}),di(i,o,l)},resetForRuntimeSwitch:()=>{e({projects:[],activeProjectId:null,manualProjectOrder:[]})},synchronizeFromSettings:n=>{const r=ab(n.projects??[]),s=t(),o=n.activeProjectId===void 0?r.some(f=>f.id===s.activeProjectId)?s.activeProjectId:null:typeof n.activeProjectId=="string"&&n.activeProjectId.trim()?n.activeProjectId.trim():null,i=r.map(f=>f.id),a=JSON.stringify(s.projects)!==JSON.stringify(r),l=s.activeProjectId!==o,d=s.manualProjectOrder.length!==i.length||s.manualProjectOrder.some((f,u)=>f!==i[u]);if(!a&&!l){d&&(e({manualProjectOrder:i}),Ph(i));return}if(e({projects:r,activeProjectId:o,manualProjectOrder:i}),lb(r,o),Ph(i),o&&(l||n.activeProjectId!==void 0)){const f=r.find(u=>u.id===o);f&&nt.getState().setDirectory(f.path,{showOverlay:!1})}},getActiveProject:()=>{const{projects:n,activeProjectId:r}=t();return r?n.find(s=>s.id===r)??null:null}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{const t=e.detail;t&&typeof t=="object"&&at.getState().synchronizeFromSettings(t)});const gs=de,rk=(e,t)=>{const n=gs(t);if(!n)return null;let r=null;for(const s of e){const o=gs(s.path);o&&(n!==o&&!n.startsWith(`${o}/`)||(!r||o.length>(gs(r.path)?.length??0))&&(r=s))}return r},Zn=(e,t,n)=>{const s=gs((typeof t=="string"?t:n)??null);if(!s)return null;const o=rk(e,s);if(o)return o;if(!(t instanceof Map))return null;const i=new Map;for(const l of e){const d=gs(l.path);d&&i.set(d,l)}let a=null;for(const[l,d]of t){const f=gs(l),u=f?i.get(f):null;if(u)for(const h of d??[]){const m=gs(h?.path??null);m&&(s!==m&&!s.startsWith(`${m}/`)||(!a||m.length>a.worktreePath.length)&&(a={project:u,worktreePath:m}))}}return a?.project??null},r0=500,sk=()=>{if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("startupTrace")==="1"||window.localStorage?.getItem("PICHAMBER_STARTUP_TRACE")==="1"}catch{return!1}},it=(e,t)=>{if(!sk())return;const n=typeof performance<"u"?performance.now():Date.now();window.__PICHAMBER_STARTUP_TRACE_START__??=n,window.__PICHAMBER_STARTUP_TRACE__??=[],window.__PICHAMBER_STARTUP_TRACE__.push({t:Math.round(n-window.__PICHAMBER_STARTUP_TRACE_START__),name:e,...t?{data:t}:{}}),window.__PICHAMBER_STARTUP_TRACE__.length>r0&&window.__PICHAMBER_STARTUP_TRACE__.splice(0,window.__PICHAMBER_STARTUP_TRACE__.length-r0)},ok=()=>{const e=typeof window<"u"?window.__PICHAMBER_STARTUP_TRACE__??[]:[],t=e.findIndex(r=>r.name==="ModelControls:ready"),n=t>=0?Math.min(e.length,t+8):e.length;return e.slice(0,n).filter(r=>r.name.includes("checkConnection")||r.name.includes("checkHealth")||r.name.includes("initializeApp")||r.name.includes("initApp")||r.name.includes("loadProviders")||r.name.includes("config.defaults")||r.name.includes("modelsMetadata")||r.name.includes("ModelControls")||r.name.includes("activateDirectory"))};typeof window<"u"&&(window.__PICHAMBER_STARTUP_TRACE_SUMMARY__=ok);const Oh=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();it(`${e}:start`,n);try{const s=await t(),o=typeof performance<"u"?performance.now():Date.now();return it(`${e}:end`,{durationMs:Math.round(o-r)}),s}catch(s){const o=typeof performance<"u"?performance.now():Date.now();throw it(`${e}:error`,{durationMs:Math.round(o-r),error:s instanceof Error?s.message:String(s)}),s}},bc="https://models.dev/api.json",ga=e=>typeof e=="object"&&e!==null,Zl=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),ik=e=>{if(!ga(e))return!1;const t=e;if(!t.modalities)return!0;const{input:n,output:r}=t.modalities;return(!n||Zl(n))&&(!r||Zl(r))},ak=e=>{if(!ga(e))return!1;const t=e;return t.models===void 0||ga(t.models)},db=(e,t)=>{const n=e?.toLowerCase?.()??"";return!n||!t?"":`${n}/${t}`},s0=e=>{if(!e)return[];const t=[];return e.text&&t.push("text"),e.audio&&t.push("audio"),e.image&&t.push("image"),e.video&&t.push("video"),e.pdf&&t.push("pdf"),t},ck=(e,t)=>({id:t.id,providerId:e,name:t.name,tool_call:t.capabilities?.toolcall,reasoning:t.capabilities?.reasoning,temperature:t.capabilities?.temperature,attachment:t.capabilities?.attachment,modalities:t.capabilities?{input:s0(t.capabilities.input),output:s0(t.capabilities.output)}:void 0,cost:t.cost?{input:t.cost.input,output:t.cost.output,cache_read:t.cost.cache?.read,cache_write:t.cost.cache?.write}:void 0,limit:t.limit,release_date:t.release_date}),lk=e=>{const t=new Map;if(!ga(e))return t;for(const[n,r]of Object.entries(e)){if(!ak(r))continue;const s=typeof r.id=="string"&&r.id.length>0?r.id:n,o=r.models;if(!(!o||!ga(o)))for(const[i,a]of Object.entries(o)){if(!ik(a))continue;const l=i||a.id;if(!l)continue;const d=db(s,l);d&&t.set(d,{id:typeof a.id=="string"&&a.id.length>0?a.id:l,providerId:s,name:typeof a.name=="string"?a.name:void 0,tool_call:typeof a.tool_call=="boolean"?a.tool_call:void 0,reasoning:typeof a.reasoning=="boolean"?a.reasoning:void 0,temperature:typeof a.temperature=="boolean"?a.temperature:void 0,attachment:typeof a.attachment=="boolean"?a.attachment:void 0,structured_output:typeof a.structured_output=="boolean"?a.structured_output:void 0,modalities:a.modalities?{input:Zl(a.modalities.input)?a.modalities.input:void 0,output:Zl(a.modalities.output)?a.modalities.output:void 0}:void 0,cost:a.cost,limit:a.limit,knowledge:typeof a.knowledge=="string"?a.knowledge:void 0,release_date:typeof a.release_date=="string"?a.release_date:void 0,last_updated:typeof a.last_updated=="string"?a.last_updated:void 0})}}return t},dk=async()=>{if(typeof fetch!="function")return new Map;const e=typeof AbortController<"u"?new AbortController:void 0,t=e?setTimeout(()=>e.abort(),8e3):void 0;try{const n=await fetch(bc,{signal:e?.signal,headers:{Accept:"application/json"},cache:"no-store",mode:"cors"});if(!n.ok)throw new Error(`Metadata request to ${bc} returned status ${n.status}`);return lk(await n.json())}catch(n){return n?.name==="AbortError"?console.warn(`Model metadata request aborted (${bc})`):console.warn(`Failed to fetch model metadata from ${bc}:`,n),new Map}finally{t&&clearTimeout(t)}};let Ki=null;const uk=3e4;let Qs=null;const fk=1500;let wc=null;const hk=()=>{if(typeof window<"u"&&typeof window.requestIdleCallback=="function")return window.requestIdleCallback.bind(window);const e=globalThis.requestIdleCallback;return typeof e=="function"?e:null},Hh=(e,t)=>{e().size>0||Ki||Qs!==null&&Date.now()-Qs<uk||(it("modelsMetadata:queued"),Ki=Oh("modelsMetadata",dk).then(n=>(n.size>0?(Qs=null,it("modelsMetadata:set",{entries:n.size}),t(n)):Qs=Date.now(),n)).catch(()=>(Qs=Date.now(),new Map)).finally(()=>{Ki=null}))},pk=()=>{Ki=null,Qs=null},mk=(e,t)=>{if(e().size>0||Ki||wc)return;it("modelsMetadata:scheduledIdle");const n=()=>{wc=null,it("modelsMetadata:idleFired"),Hh(e,t)},r=hk();if(r){wc={kind:"idle",handle:r(n,{timeout:5e3})};return}wc={kind:"timeout",handle:setTimeout(n,fk)}},gk=(e,t,n,r)=>{const s=db(t,n);if(s)return e.get(s)??(r?ck(t,r):void 0)},ub=e=>{if(!e)return null;const t=e.indexOf("/");return t<=0||t>=e.length-1?null:{providerId:e.slice(0,t),modelId:e.slice(t+1)}},yk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!ub(n))continue;const s=dn(r);s&&(t[n]=s)}return t},vk=async()=>{try{const e=await Nt("/api/pi/settings",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return{ok:!1};const n=(await e.json())?.pichamber,r=n?.defaultModel;let s;if(r&&typeof r.providerId=="string"&&typeof r.modelId=="string"){const o=r.providerId.trim(),i=r.modelId.trim();o&&i&&(s=`${o}/${i}`)}return{ok:!0,defaultModel:s,defaultThinking:dn(n?.defaultThinking)??void 0,defaultThinkingByModel:yk(n?.defaultThinkingByModel)}}catch{return{ok:!1}}},Yu=e=>{const t=typeof e.defaultModel=="string"?e.defaultModel.trim():"",n=typeof e.defaultVariant=="string"?e.defaultVariant.trim():"",r=typeof e.zenModel=="string"?e.zenModel.trim():"",s=e.messageStreamTransport==="ws"||e.messageStreamTransport==="sse"||e.messageStreamTransport==="auto"?e.messageStreamTransport:void 0;return{defaultModel:t.length>0?t:void 0,defaultVariant:n.length>0?n:void 0,autoCreateWorktree:typeof e.autoCreateWorktree=="boolean"?e.autoCreateWorktree:void 0,zenModel:r.length>0?r:void 0,messageStreamTransport:s}},xk=async()=>{it("config.defaults:start");const e=typeof performance<"u"?performance.now():Date.now(),t=(n,r)=>{const s=typeof performance<"u"?performance.now():Date.now();return it("config.defaults:end",{source:n,durationMs:Math.round(s-e),hasDefaultModel:!!r.defaultModel}),r};try{const n=await vk(),r=(l,d)=>n.ok?t(l,{...d,defaultModel:n.defaultModel,defaultThinking:n.defaultThinking,defaultThinkingByModel:n.defaultThinkingByModel}):t(l,d),s=await Z9().catch(()=>null);if(s)return r("shared-settings",Yu(s));const o=$r()?.settings;if(o)try{const d=(await o.load())?.settings;if(d)return r("runtime-settings",Yu(d))}catch{}const i=await Nt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)return r("settings-route-not-ok",{});const a=await i.json();return r("settings-route",a&&typeof a=="object"&&!Array.isArray(a)?Yu(a):{})}catch(n){return it("config.defaults:error",{error:n instanceof Error?n.message:String(n)}),t("error",{})}},bk=3e4,Sc=new Map,o0=new WeakMap;let Cc=0;const wk=(e,t)=>JSON.stringify([e,de(t)??t]),Sk=(e,t)=>e.length===t.length&&e.every((n,r)=>{const s=t[r];return s&&n.path===s.path&&n.head===s.head&&n.branch===s.branch&&n.name===s.name&&n.isPrimary===s.isPrimary&&n.detached===s.detached&&n.locked===s.locked&&n.prunable===s.prunable}),i0=()=>({worktrees:[],status:"idle",error:null,fetchedAt:0}),Qt=Lt()((e,t)=>({runtimeKey:Y(),projects:new Map,refreshProject:async(n,r,s)=>{const o=de(n);if(!o)return null;const i=Y(),a=Cc,l=wk(i,o),d=Sc.get(l);if(d)return d;const f=t().projects.get(o)??i0();if(!s?.force&&f.status==="ready"&&f.error===null&&Date.now()-f.fetchedAt<bk)return f.worktrees;f.status==="idle"&&e(h=>{const m=new Map(h.projects);return m.set(o,{...f,status:"loading"}),{projects:m}});const u=(async()=>{try{const m=await r.checkIsGitRepository(o)?await(()=>{if(!r.listGitWorktrees)throw new Error("Git worktrees are unavailable for this runtime.");return r.listGitWorktrees(o)})():[];return a!==Cc||i!==Y()||t().runtimeKey!==i?null:(e(g=>{const x=g.projects.get(o)??i0(),b=Sk(x.worktrees,m);if(b&&x.status==="ready"&&x.error===null)return g;const S=new Map(g.projects);return S.set(o,{worktrees:b?x.worktrees:m,status:"ready",error:null,fetchedAt:Date.now()}),{projects:S}}),m)}catch(h){if(a!==Cc||i!==Y()||t().runtimeKey!==i)return null;const m=h instanceof Error?h.message:"Failed to discover Git worktrees.";return e(g=>{const x=g.projects.get(o)??f,b=new Map(g.projects);return b.set(o,{...x,status:"failed",error:m}),{projects:b}}),null}finally{Sc.delete(l)}})();return Sc.set(l,u),u},resetForRuntimeSwitch:n=>{Cc+=1,Sc.clear(),e({runtimeKey:n,projects:new Map})}})),Ck=(e,t)=>{const n=de(t??null);if(!n)return[];const r=e.projects.get(n)?.worktrees;if(!r)return[];const s=o0.get(r);if(s)return s;const o=r.filter(i=>!i.isPrimary&&!i.prunable);return o0.set(r,o),o},Ln=(e,t)=>{const n=new Map;for(const r of e){const s=de(r.path??null);s&&n.set(s,Ck(t,s))}return n},mm="__global__",ys=e=>{const t=typeof e=="string"?e.trim():"";return t.length>0?t:mm},cs=e=>e===mm?null:e,kk=()=>typeof window>"u"?mm:pl(nt.getState().currentDirectory),fb="oc.worktreeProjectMap.v2",Fh="oc.worktreeProjectMap",Mk=8,a0=new Map,hb=()=>{try{const e=typeof localStorage<"u"?localStorage.getItem(fb):null;if(!e)return{version:2,legacyClaimed:!1,runtimes:{}};const t=JSON.parse(e);return t.version!==2||!t.runtimes||typeof t.runtimes!="object"?{version:2,legacyClaimed:!1,runtimes:{}}:{version:2,legacyClaimed:t.legacyClaimed===!0,runtimes:t.runtimes}}catch{return{version:2,legacyClaimed:!1,runtimes:{}}}},pb=e=>{const t=Object.fromEntries(Object.entries(e.runtimes).sort(([,n],[,r])=>r.updatedAt-n.updatedAt).slice(0,Mk));localStorage.setItem(fb,JSON.stringify({...e,runtimes:t}))},mb=()=>{const e=Y()||"default",t=a0.get(e);if(t)return t;const n=hb();let r=n.runtimes[e]?.entries??null;if(!r&&!n.legacyClaimed)try{const o=typeof localStorage<"u"?localStorage.getItem(Fh):null;r=o?JSON.parse(o):{},n.legacyClaimed=!0,n.runtimes[e]={updatedAt:Date.now(),entries:r},pb(n),localStorage.removeItem(Fh)}catch{r={}}const s=r??{};return a0.set(e,s),s},Ik=(e,t)=>{if(!e||!t||e===t)return;const n=mb();if(n[e]!==t){n[e]=t;try{const r=Y()||"default",s=hb();s.legacyClaimed=!0,s.runtimes[r]={updatedAt:Date.now(),entries:n},pb(s),localStorage.removeItem(Fh)}catch{}}},Gi=e=>{const t=de(e);return t===null?null:t||"/"},Ek=()=>{try{return at.getState().projects.map(e=>Gi(e.path)).filter(e=>!!e)}catch{return[]}},jk=()=>{try{const{projects:e,activeProjectId:t}=at.getState(),n=t?e.find(r=>r.id===t):null;return Gi(n?.path??e[0]?.path??null)}catch{return null}},hl=e=>{const t=Gi(e),n=Ek();if(!t)return null;if(n.includes(t))return t;const r=Gi(mb()[t]);if(r)return r;try{const s=at.getState().projects,o=Zn(s,Ln(s,Qt.getState()),t),i=Gi(o?.path??null);if(i&&i!==t)return Ik(t,i),i}catch{return null}return null},pl=e=>ys(hl(e)),gb="__add_provider__",ss="zen",c0="big-pickle",yb=e=>ub(e),vb=(e,t)=>{const n=dn(t);return n&&um(e).includes(n)?n:void 0},l0=e=>e===gb?"":e??"",Yl=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},Xl=(e,t,n)=>{const r=e.find(s=>s.id===t);return r?r.models.some(s=>s.id===n):!1},_k=({providers:e,currentProviderId:t,currentModelId:n,currentVariant:r,settingsDefaultModel:s,settingsDefaultVariant:o})=>{const i=(d,f,u)=>{if(!u)return;const h=e.find(m=>m.id===d)?.models.find(m=>m.id===f);return vb(h,u)};if(t&&n&&Xl(e,t,n))return{providerId:t,modelId:n,variant:i(t,n,r)};if(s){const d=yb(s);if(d&&Xl(e,d.providerId,d.modelId))return{providerId:d.providerId,modelId:d.modelId,variant:i(d.providerId,d.modelId,o)}}const a=e.find(d=>d.authenticated&&d.models.length>0)||e.find(d=>d.models.length>0)||e[0],l=a?.models[0];return a&&l?{providerId:a.id,modelId:l.id}:null},Xu=({providers:e,settingsZenModel:t})=>{const n=Yl(t);if(!Array.isArray(e)||e.length===0)return n?{providerId:ss,modelId:n}:null;if(n&&Xl(e,ss,n))return{providerId:ss,modelId:n};if(Xl(e,ss,c0))return{providerId:ss,modelId:c0};const r=e.find(s=>s.id===ss);if(r?.models.length){const s=Math.floor(Math.random()*r.models.length),o=Yl(r.models[s]?.id);if(o)return{providerId:ss,modelId:o}}return null},Tk=4,Ak=800,Nk=3e4,Lk=1e3,Rk=e=>{const t={...e};delete t.agents,delete t.currentAgentName,delete t.agentModelSelections,delete t.runtimeDefaultAgent,delete t.runtimeDefaultModel,delete t.settingsDefaultFileViewerPreview,delete t.defaultFileViewerPreview,delete t.settingsGitmojiEnabled,delete t.gitmojiEnabled;const n=e.directoryScoped;if(n&&typeof n=="object"){const a={};for(const[l,d]of Object.entries(n)){if(!d||typeof d!="object"){a[l]=d;continue}const f={...d};delete f.agents,delete f.currentAgentName,delete f.agentModelSelections,delete f.runtimeDefaultAgent,delete f.runtimeDefaultModel,delete f.settingsDefaultFileViewerPreview,delete f.defaultFileViewerPreview,a[l]=f}t.directoryScoped=a}const r=t.directoryScoped,s=t.activeDirectoryKey;if(!r||!s)return t;const o=r[s];if(!o)return t;const i={...t};return(!i.providers||i.providers.length===0)&&o.providers?.length&&(i.providers=o.providers),(!i.defaultProviders||Object.keys(i.defaultProviders).length===0)&&o.defaultProviders&&Object.keys(o.defaultProviders).length>0&&(i.defaultProviders=o.defaultProviders),o.selectionSource&&(i.selectionSource=o.selectionSource),i},d0=new Map,Pk=(e,t)=>{const n=e.get(t);return typeof n=="number"&&Date.now()-n<Nk},Dk=e=>new Promise(t=>setTimeout(t,e)),xb=async()=>(await Ee.health({runtimeKey:Y()})).state==="ready",Ok=async(e=Ak)=>Promise.race([xb().catch(()=>!1),Dk(Math.max(1,e)).then(()=>!1)]),u0=new Set;function Hk(e){return u0.add(e),()=>{u0.delete(e)}}function Fk(e,t){return e.scopes.includes("all")||e.scopes.includes(t)}const Bk=async(e,t)=>{const n=e.getState(),r=Array.from(new Set([n.activeDirectoryKey,...Object.keys(n.directoryScoped)])).filter(a=>a.length>0);n.invalidateProviderCache();let s=0;const o=Math.min(Tk,r.length),i=Array.from({length:o},async()=>{for(;s<r.length;){const a=r[s];s+=1,await e.getState().loadProviders({directory:cs(a),source:t})}});await Promise.all(i)};let f0=null,h0=null;const Vk=e=>{typeof window<"u"&&(window.__zustand_config_store__=e),f0||(f0=Hk(async t=>{Fk(t,"providers")&&await Bk(e,"configChange:providers")})),typeof window<"u"&&!h0&&(h0=nt.subscribe((t,n)=>{const r=ys(t.currentDirectory),s=ys(n.currentDirectory);r!==s&&(it("directoryStore:changed",{previous:s,next:r}),e.getState().activateDirectory(t.currentDirectory))}))},$k=e=>{if(e.authenticated!==!0)return!1;const t=e.models;return Array.isArray(t)?t.length>0:t&&typeof t=="object"?Object.keys(t).length>0:!1},zk=e=>e.filter($k),Uk=async()=>{const e=await Ee.listProviders({runtimeKey:Y()}),n=zk(e.providers).map(s=>{const o=s.models.map(i=>({id:i.id,name:i.label??i.id,providerID:i.providerId,reasoning:i.supportsThinking===!0,...Number.isSafeInteger(i.contextWindow)?{limit:{context:i.contextWindow}}:{},...Array.isArray(i.thinkingLevels)&&i.thinkingLevels.length>0?{thinkingLevels:i.thinkingLevels}:{}}));return{id:s.id,name:s.label??s.id,authenticated:s.authenticated===!0,models:o}}),r=e.default?{[e.default.providerId]:e.default.modelId}:{};return{providers:n,defaults:r}},Ju=e=>new Promise(t=>setTimeout(t,e)),Qu=new Map;let kc=null;const We=Lt()(mr(Pd((e,t)=>({activeDirectoryKey:kk(),directoryScoped:{},providers:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,selectedProviderId:"",defaultProviders:{},selectionSource:"auto",isConnected:!1,hasEverConnected:!1,connectionPhase:"connecting",lastDisconnectReason:null,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultThinking:void 0,settingsDefaultThinkingByModel:{},settingsAutoCreateWorktree:!1,settingsZenModel:void 0,activateDirectory:async n=>{const r=hl(n),s=typeof n=="string"&&n.trim().length>0;if(!r&&s){it("activateDirectory:skippedUnknownDirectory",{directory:n});return}const o=ys(r);let i=!1;e(a=>{const l=a.directoryScoped[o];return l?(i=l.providers.length>0,{activeDirectoryKey:o,providers:l.providers,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,selectedProviderId:l.selectedProviderId,defaultProviders:l.defaultProviders,selectionSource:l.selectionSource??"auto"}):{activeDirectoryKey:o,providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{},selectionSource:"auto"}}),t().isConnected&&(i?Pk(d0,o)?it("activateDirectory:providersFresh",{directoryKey:o}):(it("activateDirectory:refreshProvidersBackground",{directoryKey:o}),t().loadProviders({directory:cs(o),source:"activateDirectory:refresh"})):await t().loadProviders({directory:cs(o),source:"activateDirectory"}))},invalidateProviderCache:n=>{const r=n===void 0?null:ys(n);e(s=>{const o={};let i=!1;const a={...s.directoryScoped},l=d=>d.providers.length===0&&Object.keys(d.defaultProviders).length===0?d:(i=!0,{...d,providers:[],defaultProviders:{}});if(r){const d=s.directoryScoped[r];d&&(a[r]=l(d))}else for(const[d,f]of Object.entries(s.directoryScoped))a[d]=l(f);return i&&(o.directoryScoped=a),(r===null||r===s.activeDirectoryKey)&&(s.providers.length>0&&(o.providers=[]),Object.keys(s.defaultProviders).length>0&&(o.defaultProviders={})),Object.keys(o).length>0?o:s})},loadProviders:async n=>{const r=n?.directory??cs(t().activeDirectoryKey),s=hl(r),o=typeof r=="string"&&r.trim().length>0;if(!s&&o){it("loadProviders:skippedUnknownDirectory",{requestedDirectory:r,source:n?.source??"unknown"});return}const i=s??null,a=ys(s),l=n?.source??"unknown";it("loadProviders:called",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i});const d=Qu.get(a);if(d)return it("loadProviders:deduped",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i}),d;const f=(async()=>{const u=typeof performance<"u"?performance.now():Date.now();it("loadProviders:start",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i});const h=t().directoryScoped[a],m=h?.providers??(t().activeDirectoryKey===a?t().providers:[]),g=h?.defaultProviders??(t().activeDirectoryKey===a?t().defaultProviders:{});let x=null;for(let b=0;b<3;b++)try{const S=await Oh("loadProviders:api",async()=>Uk(),{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,attempt:b+1}),y=S?.providers??[],v=S?.defaults??{};e(w=>{const M=w.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},j=w.activeDirectoryKey===a?w.currentProviderId:M.currentProviderId,T=w.activeDirectoryKey===a?w.currentModelId:M.currentModelId,A=w.activeDirectoryKey===a?w.currentVariant:M.currentVariant,_=_k({providers:y,currentProviderId:j,currentModelId:T,currentVariant:A,settingsDefaultModel:w.settingsDefaultModel,settingsDefaultVariant:w.settingsDefaultVariant}),k=w.activeDirectoryKey===a?w.selectedProviderId:M.selectedProviderId,E=k===gb||y.some(O=>O.id===k)?k:_?.providerId??y[0]?.id??"",I={...M,providers:y,defaultProviders:v,currentProviderId:_?.providerId??"",currentModelId:_?.modelId??"",currentVariant:_?.variant,selectedProviderId:E},N={directoryScoped:{...w.directoryScoped,[a]:I}};return w.activeDirectoryKey===a&&(N.providers=y,N.defaultProviders=v,N.currentProviderId=I.currentProviderId,N.currentModelId=I.currentModelId,N.currentVariant=I.currentVariant,N.selectedProviderId=E),N});const C=typeof performance<"u"?performance.now():Date.now();it("loadProviders:end",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,durationMs:Math.round(C-u),providers:y.length,models:y.reduce((w,M)=>w+M.models.length,0)}),d0.set(a,Date.now());return}catch(S){x=S,it("loadProviders:attemptError",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,attempt:b+1,error:S instanceof Error?S.message:String(S)});const y=200*(b+1);await new Promise(v=>setTimeout(v,y))}console.error("Failed to load providers:",x),it("loadProviders:error",{directoryKey:a,source:l,requestedDirectory:r,effectiveDirectory:i,error:x instanceof Error?x.message:String(x)}),e(b=>{const y={...b.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},providers:m,defaultProviders:g},v={directoryScoped:{...b.directoryScoped,[a]:y}};if(b.activeDirectoryKey===a&&(v.providers=m,v.defaultProviders=g,!b.currentProviderId&&!b.currentModelId&&b.settingsDefaultModel)){const C=yb(b.settingsDefaultModel);if(C){const w=m.find(M=>M.id===C.providerId);if(w?.models.some(M=>M.id===C.modelId)){const M=w.models.find(T=>T.id===C.modelId),j=vb(M,b.settingsDefaultVariant);v.currentProviderId=C.providerId,v.currentModelId=C.modelId,v.currentVariant=j,v.selectedProviderId=C.providerId,y.currentProviderId=C.providerId,y.currentModelId=C.modelId,y.currentVariant=j,y.selectedProviderId=C.providerId}}}return v})})().finally(()=>Qu.delete(a));return Qu.set(a,f),f},setProvider:n=>{const{providers:r}=t(),s=r.find(a=>a.id===n);if(!s)return;const i=s.models[0]?.id||"";e(a=>{const l=a.activeDirectoryKey,f={...a.directoryScoped[l]??{providers:a.providers,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,selectedProviderId:a.selectedProviderId,defaultProviders:a.defaultProviders},currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual"};return{currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual",directoryScoped:{...a.directoryScoped,[l]:f}}})},setModel:n=>{e(r=>{const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},currentModelId:n,selectionSource:"manual"};return{currentModelId:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},setCurrentVariant:n=>{e(r=>{if(r.currentVariant===n)return r;const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},currentVariant:n,selectionSource:"manual"};return{currentVariant:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},getCurrentModelVariants:()=>um(t().getCurrentModel()),cycleCurrentVariant:()=>{const n=fm(t().getCurrentModelVariants(),t().currentVariant,1);t().setCurrentVariant(n)},setSelectedProvider:n=>{e(r=>{const s=r.activeDirectoryKey,i={...r.directoryScoped[s]??{providers:r.providers,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,selectedProviderId:r.selectedProviderId,defaultProviders:r.defaultProviders},selectedProviderId:n,selectionSource:"manual"};return{selectedProviderId:n,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[s]:i}}})},invalidateModelMetadataCache:()=>{pk(),e({modelsMetadata:new Map})},ensureModelMetadata:()=>{Hh(()=>t().modelsMetadata,n=>e({modelsMetadata:n}))},setSettingsDefaultModel:n=>{e({settingsDefaultModel:n})},setSettingsDefaultVariant:n=>{e({settingsDefaultVariant:n})},setSettingsDefaultThinking:n=>{e({settingsDefaultThinking:n})},setSettingsDefaultThinkingByModel:n=>{e({settingsDefaultThinkingByModel:n})},setSettingsAutoCreateWorktree:n=>{e({settingsAutoCreateWorktree:n})},setSettingsZenModel:n=>{e({settingsZenModel:n})},getResolvedGitGenerationModel:()=>{const n=t();return Xu({providers:n.providers,settingsZenModel:n.settingsZenModel})},probeConnection:async n=>{if(await Ok(n?.timeoutMs))return e({isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),!0;const s=t();return s.isConnected?!0:(e({isConnected:!1,connectionPhase:s.hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_probe_unhealthy"}),!1)},checkConnection:async()=>{it("checkConnection:start");const n=5;let r=0,s=null;for(;r<n;)try{it("checkConnection:attempt",{attempt:r+1});const o=await Oh("checkConnection:health",()=>xb(),{attempt:r+1});if(!o&&r<n-1){const a=t().hasEverConnected;e({isConnected:!1,connectionPhase:a?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),r+=1,await Ju(400*r);continue}const i=t().hasEverConnected;return e(o?{isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}:{isConnected:!1,connectionPhase:i?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),it("checkConnection:end",{healthy:o,attempts:r+1}),o}catch(o){s=o,r+=1;const i=400*r;await Ju(i)}return s&&console.warn("[ConfigStore] Failed to reach Pi after retrying:",s),e({isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_check_failed"}),it("checkConnection:end",{healthy:!1,attempts:n}),!1},initializeApp:async()=>{if(kc)return it("initializeApp:deduped"),kc;const n=(async()=>{const r=typeof performance<"u"?performance.now():Date.now();it("initializeApp:start");try{const s=c5();s&&console.log("Starting app initialization...");const o=await t().checkConnection();if(s&&console.log("Connection check result:",o),!o){s&&console.log("Server not connected"),e({isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting"});return}s&&console.log("Initializing app..."),it("initApp:skipped",{reason:"checkConnection already verified health"});const i=nt.getState().currentDirectory??cs(t().activeDirectoryKey),a=Zn(at.getState().projects,null,i??null),l=hl(a?.path??i??null),d=l??jk();d||it("initializeApp:globalConfigScope"),d&&!l&&i!==d&&(it("initializeApp:normalizedUnknownDirectoryToProject",{initialDirectory:i,configDirectory:d}),nt.getState().setDirectory(d,{showOverlay:!1}));const f=ys(d);t().activeDirectoryKey!==f&&e({activeDirectoryKey:f}),s&&console.log("Loading providers..."),await t().loadProviders({directory:d,source:"initializeApp"});const u=await xk(),h=t().providers,m=Yl(t().settingsZenModel),g=Yl(u.zenModel),b=(Xu({providers:h,settingsZenModel:m})??Xu({providers:h,settingsZenModel:g}))?.modelId||g||m;e({settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultThinking:u.defaultThinking,settingsDefaultThinkingByModel:u.defaultThinkingByModel??{},settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsZenModel:b}),b&&b!==g&&Vr({zenModel:b,gitProviderId:"",gitModelId:""}).catch(()=>{}),e({isInitialized:!0,isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),mk(()=>t().modelsMetadata,y=>e({modelsMetadata:y})),t().prewarmProjectConfigs(d);const S=typeof performance<"u"?performance.now():Date.now();it("initializeApp:end",{durationMs:Math.round(S-r),providers:t().providers.length}),s&&console.log("App initialized successfully")}catch(s){console.error("Failed to initialize app:",s),e({isInitialized:!1,isConnected:!1,connectionPhase:t().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"init_error"}),it("initializeApp:error",{error:s instanceof Error?s.message:String(s)})}})().finally(()=>{kc=null});return kc=n,n},prewarmProjectConfigs:async n=>{if(!t().isConnected)return;const r=pl(n??cs(t().activeDirectoryKey)),s=at.getState().projects.map(a=>a.path).filter(a=>typeof a=="string"&&a.trim().length>0),o=new Set([r]),i=[];for(const a of s){const l=pl(a);if(o.has(l)||(o.add(l),t().directoryScoped[l]?.providers.length))continue;const f=cs(l);f&&i.push(f)}for(const a of i){if(await Ju(Lk),!t().isConnected)return;const l=pl(a),d=t().directoryScoped[l],f=[];d?.providers.length||f.push(t().loadProviders({directory:a,source:"projectConfigPrewarm"})),f.length>0&&await Promise.allSettled(f)}},getCurrentProvider:()=>{const{providers:n,currentProviderId:r}=t();return n.find(s=>s.id===r)},getCurrentModel:()=>{const n=t().getCurrentProvider(),{currentModelId:r}=t();if(n)return n.models.find(s=>s.id===r)},getModelMetadata:(n,r)=>{Hh(()=>t().modelsMetadata,a=>e({modelsMetadata:a}));const{modelsMetadata:s,providers:o}=t(),i=o.find(a=>a.id===n)?.models.find(a=>a.id===r);return gk(s,n,r,i)}}),{name:"config-store",storage:Qp(),merge:(e,t)=>Rk({...t,...e&&typeof e=="object"?e:{}}),partialize:e=>({activeDirectoryKey:e.activeDirectoryKey,directoryScoped:Object.fromEntries(Object.entries(e.directoryScoped).map(([t,n])=>[t,{...n,selectedProviderId:l0(n.selectedProviderId)}])),providers:e.providers,currentProviderId:e.currentProviderId,currentModelId:e.currentModelId,currentVariant:e.currentVariant,selectedProviderId:l0(e.selectedProviderId),defaultProviders:e.defaultProviders,settingsDefaultModel:e.settingsDefaultModel,settingsDefaultVariant:e.settingsDefaultVariant,settingsDefaultThinking:e.settingsDefaultThinking,settingsDefaultThinkingByModel:e.settingsDefaultThinkingByModel,settingsAutoCreateWorktree:e.settingsAutoCreateWorktree,settingsZenModel:e.settingsZenModel})})));Vk(We);const qk=5e3,yo=new Map,vo=new Map,Jl=e=>{const t=Y();yo.delete(t),vo.delete(t),(!t||t==="local")&&(yo.clear(),vo.clear())},bb=()=>{yo.clear(),vo.clear()},Dr=Lt()(mr(Pd((e,t)=>({selectedSkillName:null,skills:[],isLoading:!1,setSelectedSkill:n=>e({selectedSkillName:n}),loadSkills:async()=>{const n=Y(),r=Date.now(),s=yo.get(n)??0;if(s>0&&r-s<qk)return!0;const o=vo.get(n);if(o)return o;const i=(async()=>{e({isLoading:!0});try{const l=(await Ee.listResources({runtimeKey:n})).skills.map(d=>({id:d.id,name:d.name,path:d.id,scope:d.location==="project"?"project":"user",source:"agents",...d.description?{description:d.description}:{},location:d.location,...typeof d.content=="string"&&d.content.length>0?{content:d.content}:{},...d.editable===!0?{editable:!0}:{}}));return e(d=>({skills:l,isLoading:!1,...d.selectedSkillName&&!l.some(f=>f.name===d.selectedSkillName)?{selectedSkillName:null}:{}})),yo.set(n,Date.now()),!0}catch{return e({isLoading:!1}),!1}})();vo.set(n,i);try{return await i}finally{vo.delete(n)}},renameSkill:async()=>!1,updateSkillContent:async(n,r)=>{const s=t().skills.find(o=>o.name===n);if(!s)return!1;try{const i=(await Ee.updateResource({resourceId:s.id,content:r},{runtimeKey:Y()})).skills.map(a=>({id:a.id,name:a.name,path:a.id,scope:a.location==="project"?"project":"user",source:"agents",...a.description?{description:a.description}:{},location:a.location,...typeof a.content=="string"&&a.content.length>0?{content:a.content}:{},...a.editable===!0?{editable:!0}:{}}));return e({skills:i}),yo.set(Y(),Date.now()),!0}catch{return!1}},getSkillByName:n=>t().skills.find(r=>r.name===n),resetForRuntimeSwitch:()=>{bb(),e({skills:[],isLoading:!1,selectedSkillName:null})}}),{name:"skills-store",storage:Qp(),partialize:e=>({selectedSkillName:e.selectedSkillName})}),{name:"skills-store"})),IY=Object.freeze(Object.defineProperty({__proto__:null,invalidateSkillsLoadCache:Jl,resetSkillsForRuntimeSwitch:bb,useSkillsStore:Dr},Symbol.toStringTag,{value:"Module"})),Wk=200,wb=1440*60*1e3,Kk=3e4,Gk=15e3,Zk=9e4,Bh="oc.session-activity.v1",Yk=new Set,Xk=new Map,Rn=Lt(()=>({startedAt:new Map,settledMs:new Map})),Es=new Map;let gm=0,Ql=null;const Jk=()=>typeof performance<"u"&&Number.isFinite(performance.timeOrigin)?performance.timeOrigin:Date.now();let ym=Jk();const Sb=(e,t)=>e.start<=t&&t-e.start<=wb&&e.seen<=t&&ym-e.seen<=Kk,Qk=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const{start:t,seen:n}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)?null:{start:t,seen:n}},eM=()=>{const e=new Map;let t=null;try{t=Ld().getItem(Bh)}catch{return e}if(!t)return e;let n;try{n=JSON.parse(t)}catch{return e}if(!n||typeof n!="object"||Array.isArray(n))return e;const r=Date.now();for(const[s,o]of Object.entries(n)){const i=Qk(o);i&&Sb(i,r)&&e.set(s,i)}return e},Vd=()=>(Ql??=eM(),Ql),tM=e=>e-ym>Zk?(Ql?.clear(),Xk):Vd(),Ss=(e,t)=>{const n={};for(const[r,s]of Vd())Sb(s,t)&&(n[r]=s);for(const[r,s]of e)n[r]={start:s,seen:Es.get(r)??t};gm=t;try{const r=Ld();if(Object.keys(n).length===0){r.removeItem(Bh);return}r.setItem(Bh,JSON.stringify(n))}catch{}},ef=()=>{const{startedAt:e}=Rn.getState();if(e.size===0)return;const t=Date.now();for(const n of e.keys())Es.set(n,t);Ss(e,t)};let p0=!1;const Cb=()=>{if(!(p0||typeof window>"u")){p0=!0;try{window.addEventListener("pagehide",ef,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&ef()}),document.addEventListener("freeze",ef))}catch{}}},nM=e=>{for(;e.size>Wk;){const t=e.keys().next();if(t.done)return;e.delete(t.value)}},m0=(e,t)=>{const n=Date.now(),r=tM(n),s=Rn.getState(),o={started:null,settled:null};let i=!1,a=!1;const l=()=>o.started??=new Map(s.startedAt),d=()=>o.settled??=new Map(s.settledMs);for(const u of e)i=!0,Es.set(u,n),!(o.started??s.startedAt).has(u)&&(l().set(u,r.get(u)?.start??n),(o.settled??s.settledMs).has(u)&&d().delete(u));const f=(u,h)=>{l().delete(u),Es.delete(u),d().set(u,Math.max(0,n-h))};if(t!==null){Vd().delete(t)&&(a=!0);const u=s.startedAt.get(t);u!==void 0&&f(t,u)}if(o.settled&&nM(o.settled),(o.started||o.settled)&&Rn.setState({startedAt:o.started??s.startedAt,settledMs:o.settled??s.settledMs}),o.started){o.started.size>0&&Cb(),Ss(o.started,n);return}if(a){Ss(s.startedAt,n);return}i&&s.startedAt.size>0&&n-gm>=Gk&&Ss(s.startedAt,n)},g0=(e,t)=>{if(t==="active"){m0(new Set([e]),null);return}m0(Yk,e)},Mn=(e,t,n)=>{if(!Number.isFinite(t))return;const r=Date.now(),s=Ro(t,n,r);if(s===void 0||r-s>wb||s>r+6e4)return;const o=Rn.getState(),i=o.startedAt.get(e);if(i!==void 0&&s>=i)return;const a=new Map(o.startedAt);a.set(e,s);const l=new Map(o.settledMs);l.delete(e),Es.set(e,r),Rn.setState({startedAt:a,settledMs:l}),Cb(),Ss(a,r)},y0=e=>{const t=Vd().delete(e),n=Rn.getState(),r=n.startedAt.has(e),s=n.settledMs.has(e);if(Es.delete(e),!r&&!s){t&&Ss(n.startedAt,Date.now());return}let o=n.startedAt;if(r){const a=new Map(n.startedAt);a.delete(e),o=a}let i=n.settledMs;if(s){const a=new Map(n.settledMs);a.delete(e),i=a}Rn.setState({startedAt:o,settledMs:i}),(r||t)&&Ss(o,Date.now())},EY=(e={})=>{Ql=null,Es.clear(),gm=0,ym=e.pageLoadAt??Date.now(),Rn.setState({startedAt:new Map,settledMs:new Map})},kb=e=>Rn(H.useCallback(t=>t.startedAt.get(e),[e])),jY=e=>Rn(H.useCallback(t=>t.settledMs.get(e),[e])),_Y=(e,t)=>Rn(H.useCallback(n=>t?n.startedAt.has(e):n.settledMs.has(e),[t,e])),Vh="oc.sessions.pinned.v2",rM="oc.sessions.pinned",ml=Gt(),$h=(e,t,n)=>{const r=de(t);return!e||!r||!n?null:JSON.stringify([e,r,n])},Mb=e=>{try{const t=JSON.parse(e);if(!Array.isArray(t)||t.length!==3)return null;const[n,r,s]=t;if(typeof n!="string"||typeof r!="string"||typeof s!="string")return null;const o=de(r);return!n||!o||o!==r||!s?null:[n,o,s]}catch{return null}},zh=(e,t,n)=>{if(!t)return!1;const r=$h(Y(),t,n);return r?e.has(r):!1},sM=()=>{ml.removeItem(rM);const e=ml.getItem(Vh);if(e===null)return{ids:new Set,touchedAt:{}};try{const t=JSON.parse(e);if(t.version!==2||!t.sessions||typeof t.sessions!="object")return{ids:new Set,touchedAt:{}};const n=Object.entries(t.sessions).filter(([r,s])=>Mb(r)&&typeof s=="number"&&Number.isFinite(s)).sort((r,s)=>s[1]-r[1]);return{ids:new Set(n.map(([r])=>r)),touchedAt:Object.fromEntries(n)}}catch{return ml.removeItem(Vh),{ids:new Set,touchedAt:{}}}},v0=(e,t)=>{const n=[...e].filter(r=>Mb(r)!==null).map(r=>[r,t[r]??Date.now()]).sort((r,s)=>s[1]-r[1]);return{ids:new Set(n.map(([r])=>r)),touchedAt:Object.fromEntries(n)}},x0=({ids:e,touchedAt:t})=>{const n=Object.fromEntries([...e].map(r=>[r,t[r]??Date.now()]));ml.setItem(Vh,JSON.stringify({version:2,sessions:n}))},b0=sM(),oM=Lt((e,t)=>({ids:b0.ids,touchedAt:b0.touchedAt,setIds:n=>{const r=t().ids,s=typeof n=="function"?n(r):n;if(s===r)return;const o=v0(s,t().touchedAt);e(o),x0(o)},toggle:n=>{const r=$h(Y(),n.directory,n.sessionId);if(!r)return;const s=new Set(t().ids),o={...t().touchedAt};s.has(r)?(s.delete(r),delete o[r]):(s.add(r),o[r]=Date.now());const i=v0(s,o);e(i),x0(i)},clearPinnedSession:(n,r,s)=>{const o=$h(n,r,s);if(!o||!t().ids.has(o))return;const i=new Set(t().ids);i.delete(o),t().setIds(i)}})),TY=new Map,ed=new Map,Po=new Map;let gl=0;const ya=Lt(()=>({rankById:new Map})),w0=()=>(gl=Math.max(gl+1,Date.now()),gl),iM=(e,t=!1)=>{const n=[...e];n.length!==0&&ya.setState(r=>{const s=new Map(r.rankById),o=t?w0():null;for(const i of n)s.set(i,o??w0());return{rankById:s}})},aM=(e,t)=>{const n=ed.get(e);ed.set(e,t),t==="active"&&n!=="active"&&iM([e])},cM=e=>{ed.delete(e),Po.delete(e),ya.setState(t=>{if(!t.rankById.has(e))return t;const n=new Map(t.rankById);return n.delete(e),{rankById:n}})},AY=()=>{ed.clear(),Po.clear(),gl=0,ya.setState({rankById:new Map})},Uh=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ib=e=>Uh(e.time?.updated)||Uh(e.time?.created),lM=e=>Uh(e.time?.created),qh=e=>e.parentID??null,Wh=e=>{const t=e;return de(t.directory??null)??de(t.project?.worktree??null)},Ai=(e,t)=>{const n=Po.get(e.id),r=t?"created":"updated",s=n?.[r];if(s!==void 0)return s;const o=t?lM(e):Ib(e);return Po.set(e.id,{...n,[r]:o}),o},dM=e=>{const t=ya.getState().rankById;let n=!1;for(const r of e){const s=Ib(r);if(t.get(r.id)!==void 0)continue;const o=Po.get(r.id);o?.updated!==void 0&&o.updated>=s||(Po.set(r.id,{...o,updated:s}),n=!0)}n&&ya.setState(r=>({rankById:new Map(r.rankById)}))},S0=(e,t,n=!1)=>t.get(e.id)??Ai(e,n),Eb=(e,t,n,r,s)=>{if(n!==r)return n?-1:1;const o=Ai(e,n),i=Ai(t,r);if(qh(e)===qh(t)){const d=S0(t,s,r)-S0(e,s,n);if(d!==0)return d}const a=i-o;if(a!==0)return a;const l=Ai(t,!0)-Ai(e,!0);return l!==0?l:e.id.localeCompare(t.id)},NY=(e,t,n,r)=>Eb(e,t,zh(n,Wh(e),e.id),zh(n,Wh(t),t.id),r),uM=(e,t,n=r=>r)=>{const r=new Map,s=o=>{let i=r.get(o);return i===void 0&&(i=zh(e,Wh(o),o.id),r.set(o,i)),i};return(o,i)=>{const a=n(o),l=n(i);return Eb(a,l,s(a),s(l),t)}},LY=(e,t,n)=>{const r=new Set(e.map(f=>f.id)),s=[],o=new Map;for(const f of e){const u=qh(f);if(!u||!r.has(u)){s.push(f);continue}const h=o.get(u);h?h.push(f):o.set(u,[f])}const i=uM(t,n);s.sort(i);for(const f of o.values())f.sort(i);const a=[],l=new Set,d=f=>{if(!l.has(f.id)){l.add(f.id),a.push(f);for(const u of o.get(f.id)??[])d(u)}};for(const f of s)d(f);for(const f of e)d(f);return a},C0=500,fM=1e3*60*60*24*30;function hM(e){const t=Date.now()-fM,n=e.filter(r=>r.time>=t);return n.length<=C0?n:n.slice(n.length-C0)}function tf(e){const t={session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}};for(const n of e)n.viewed||(n.session&&(t.session.unseenCount[n.session]=(t.session.unseenCount[n.session]??0)+1,n.type==="error"&&(t.session.unseenHasError[n.session]=!0)),n.directory&&(t.project.unseenCount[n.directory]=(t.project.unseenCount[n.directory]??0)+1,n.type==="error"&&(t.project.unseenHasError[n.directory]=!0)));return t}const $d=Lt((e,t)=>({list:[],index:{session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}},append:n=>{const r=t().list,s=hM([...r,n]);e({list:s,index:tf(s)})},markSessionViewed:n=>{const r=t();if((r.index.session.unseenCount[n]??0)===0)return;const o=r.list.map(i=>i.session===n&&!i.viewed?{...i,viewed:!0}:i);e({list:o,index:tf(o)})},markProjectViewed:n=>{const r=t();if((r.index.project.unseenCount[n]??0)===0)return;const o=r.list.map(i=>i.directory===n&&!i.viewed?{...i,viewed:!0}:i);e({list:o,index:tf(o)})},sessionUnseenCount:n=>t().index.session.unseenCount[n]??0,sessionHasError:n=>t().index.session.unseenHasError[n]??!1,projectUnseenCount:n=>t().index.project.unseenCount[n]??0,projectHasError:n=>t().index.project.unseenHasError[n]??!1}));function zd(e){$d.getState().markSessionViewed(e)}function jb(e,t,n){const r=$d.getState();(r.index.session.unseenCount[e]??0)>0||r.append(n?.error?{type:"error",session:e,directory:t,error:n.error,time:Date.now(),viewed:!1}:{type:"turn-complete",session:e,directory:t,time:Date.now(),viewed:!1})}function _b(e){const t=te.getState();if(!t.nativeNotificationsEnabled||e.kind==="completion"&&!t.notifyOnCompletion||e.kind==="error"&&!t.notifyOnError)return;const n=$r()?.notifications;if(!n)return;const r=e.title?.trim()||"Open PiChamber to review the session.";n.notify({title:e.kind==="error"?"Work failed":"Work completed",body:r,tag:`pichamber:${e.kind}:${e.sessionId}:${e.sequence}`,kind:e.kind,sessionId:e.sessionId,directory:e.directory,requireHidden:t.notificationMode!=="always"})}function vm(e,t){return`pichamber:input:${e}:${t}`}function Tb(e){const t=te.getState();if(!t.nativeNotificationsEnabled||t.notifyOnInputNeeded===!1)return;const n=$r()?.notifications;if(!n)return;const r=e.title?.trim()||"Open PiChamber to answer.";n.notify({title:e.kind==="approval"?"Approval needed":"Input needed",body:r,tag:vm(e.sessionId,e.since),kind:"input",sessionId:e.sessionId,directory:e.directory,requireHidden:t.notificationMode!=="always"})}function pM(e){return $d(t=>t.index.session.unseenCount[e]??0)}const RY=Object.freeze(Object.defineProperty({__proto__:null,dispatchInputNeededNotification:Tb,dispatchSessionNotification:_b,inputNeededNotificationTag:vm,markSessionViewed:zd,notifySessionTurnComplete:jb,useNotificationStore:$d,useSessionUnseenCount:pM},Symbol.toStringTag,{value:"Module"})),mM="pichamber_sync_perf",xm=()=>({pipelineRawEvents:0,pipelineCoalescedEvents:0,pipelineDeliveredEvents:0,reducerEvents:0,reducerChangedEvents:0,directoryStorePublications:0,streamingFullReconciliations:0,streamingIncrementalReconciliations:0,streamingStatusEntriesVisited:0,streamingSessionCandidatesVisited:0,streamingMessagesVisited:0,streamingHeartbeatAttempts:0,streamingHeartbeatCommits:0,permissionChangeCallbacks:0,questionChangeCallbacks:0,sessionMessageChangeCallbacks:0,sessionRenderableNotificationSkips:0,userMessageHistoryNotificationSkips:0,sessionMessageRecordNotificationSkips:0,materializationEnqueues:0,materializationEmptyAssistantEnqueues:0,materializationMissingMessageEnqueues:0,materializationMissingPartEnqueues:0,materializationLifecycleEnqueues:0,materializationPreflightSkips:0,materializationRequests:0,statusAggregationSessionEntries:0,statusAggregationCandidates:0,persistenceSerializations:0,persistenceStorageWrites:0,persistenceUtf8Bytes:0}),gM=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(mM)==="1"}catch{return!1}},Ab=gM();let yl=Ab||Wo()?xm():null;const yM=()=>Wo()||Ab,bm=()=>yM()?(yl||(yl=xm()),yl):null;function Nb(){bm()&&(yl=xm())}function Lb(){const e=bm();return e?{...e}:null}function vM(e){const t=bm();t&&(t.persistenceSerializations+=1,t.persistenceUtf8Bytes+=new TextEncoder().encode(e).byteLength)}typeof window<"u"&&(window.__pichamberSyncPerformance={getSnapshot:Lb,reset:Nb});const Kh="pichamber.chatDrafts.v2",xM=50,Gh=Gt(),Zh=new Set;let Ni,or;const Go=(e,t,n)=>{const r=de(t);return!e||!r?null:{runtimeKey:e,directory:r,sessionId:n}},Jt=e=>JSON.stringify([e.runtimeKey,e.directory,e.sessionId]),Rb=()=>{const e=Gh.getItem(Kh);if(e===Ni&&or)return or;try{const t=JSON.parse(e??"");if(t.version!==2||!t.drafts||typeof t.drafts!="object"||Array.isArray(t.drafts))return Ni=e,or={version:2,drafts:{}},or;const n={};for(const[r,s]of Object.entries(t.drafts)){if(!s||typeof s!="object")continue;const o=s;typeof o.text!="string"||!Array.isArray(o.confirmedMentions)||typeof o.touchedAt!="number"||(n[r]={text:o.text,confirmedMentions:o.confirmedMentions.filter(i=>typeof i=="string"),touchedAt:o.touchedAt})}return Ni=e,or={version:2,drafts:n},or}catch{return Gh.removeItem(Kh),Ni=null,or={version:2,drafts:{}},or}},bM=e=>{const t=JSON.stringify(e);Ni=t,or=e,vM(t),Gh.setItem(Kh,t)},Ud=e=>{if(!e)return{text:"",confirmedMentions:new Set};const t=Rb().drafts[Jt(e)];return t?{text:t.text,confirmedMentions:new Set(t.confirmedMentions)}:{text:"",confirmedMentions:new Set}},js=(e,t,n)=>{if(!e)return;const r=Rb(),s=Jt(e),o=Array.from(new Set(n));if(!t&&o.length===0){if(!(s in r.drafts))return;delete r.drafts[s]}else r.drafts[s]={text:t,confirmedMentions:o,touchedAt:Date.now()};const i=Object.entries(r.drafts).sort((a,l)=>l[1].touchedAt-a[1].touchedAt).slice(0,xM);bM({version:2,drafts:Object.fromEntries(i)})},wM=(e,t=!1)=>{js(e,"",[]),t&&Zh.forEach(n=>n(e))},SM=e=>(Zh.add(e),()=>Zh.delete(e)),qd=e=>({...e,previewUrl:void 0,uploadState:e.uploadState?{...e.uploadState}:e.uploadState}),CM=["image/png","image/jpeg","image/gif","image/webp","image/heic","image/heif","application/pdf","application/zip","application/x-zip-compressed","application/gzip","application/x-tar","application/x-7z-compressed","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","text/*","application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml",".bat",".c",".cc",".cjs",".cmd",".conf",".cpp",".cs",".css",".csv",".cts",".dart",".diff",".docx",".drawio",".env",".erl",".ex",".exs",".fs",".fsx",".go",".gql",".graphql",".h",".har",".hh",".hcl",".heic",".heif",".hpp",".hrl",".htm",".html",".ini",".ipynb",".java",".jl",".js",".json",".jsonl",".jsx",".kt",".kts",".log",".lua",".md",".mdx",".mjs",".mts",".ndjson",".odp",".ods",".odt",".patch",".php",".proto",".pptx",".ps1",".py",".r",".rb",".rs",".sass",".scala",".scss",".sh",".sol",".sql",".svelte",".svg",".swift",".tf",".toml",".ts",".tsx",".txt",".vue",".xml",".xlsx",".yaml",".yml",".zig",".zip",".7z",".gz",".rar",".tar",".tgz",".zsh"],kM=CM.join(","),MM=e=>{const t=e.toLowerCase().split(";",1)[0]?.trim()??"";if(t.startsWith("image/"))return"image";if(t.startsWith("audio/"))return"audio";if(t.startsWith("video/"))return"video";if(t==="application/pdf")return"pdf";if(t.startsWith("text/"))return"text"},IM=(e,t)=>{const n=new Set(t.map(s=>s.toLowerCase())),r=[];for(const s of e){const o=MM(s.mimeType);o&&!n.has(o)&&r.push({attachment:s,modality:o})}return r},EM=new Map([["image/png","image/png"],["image/jpeg","image/jpeg"],["image/gif","image/gif"],["image/webp","image/webp"],["application/pdf","application/pdf"]]),jM=new Map([["gif","image/gif"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["pdf","application/pdf"],["png","image/png"],["webp","image/webp"]]),_M=new Set(["application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml","image/svg+xml"]),TM=4096,AM=new Set(["docx","pptx","xlsx","odt","odp","ods"]),vl="[REDACTED]",NM="[OMITTED BY PICHAMBER]",Yh=/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api[-_]?key|client[-_]?secret|password|secret|access[-_]?token|refresh[-_]?token|id[-_]?token|token)$/i,wm=e=>{const t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()},Pb=e=>e.type.split(";",1)[0]?.trim().toLowerCase()??"",LM=async e=>{const t=new Uint8Array(await e.slice(0,TM).arrayBuffer());if(t.some(r=>r===0))return;const n=t.filter(r=>r<9||r>13&&r<32).length;if(!(t.length>0&&n/t.length>.3))return"text/plain"},RM=e=>{const t=Pb(e),n=EM.get(t);if(n)return n;const r=wm(e.name),s=jM.get(r);return(!t||t==="application/octet-stream")&&s?s:t.startsWith("text/")||_M.has(t)||t.endsWith("+json")||t.endsWith("+xml")?"text/plain":LM(e).then(o=>o||t||"application/octet-stream")},Mc=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join(""):"",PM=(e,t)=>{if(!e||typeof e!="object")return;const n=e;if(!Array.isArray(n.cells))return;const r=typeof n.metadata?.kernelspec?.language=="string"?n.metadata.kernelspec.language:"",s=[`# Notebook: ${t}`];return n.cells.forEach((o,i)=>{if(!o||typeof o!="object")return;const a=o,l=Mc(a.source).trimEnd();if(a.cell_type==="markdown"){s.push(`## Markdown cell ${i+1}
9
+
10
+ ${l}`);return}if(a.cell_type!=="code"||(s.push(`## Code cell ${i+1}
11
+
12
+ \`\`\`${r}
13
+ ${l}
14
+ \`\`\``),!Array.isArray(a.outputs)))return;const d=[];for(const f of a.outputs){if(!f||typeof f!="object")continue;const u=f,h=Mc(u.text)||Mc(u.traceback);if(h){d.push(h.trimEnd());continue}if(u.data&&typeof u.data=="object"){const m=u.data,g=Mc(m["text/plain"]);g&&d.push(g.trimEnd());const x=Object.keys(m).filter(b=>b!=="text/plain");x.length>0&&d.push(`[Non-text output omitted: ${x.join(", ")}]`);continue}(typeof u.ename=="string"||typeof u.evalue=="string")&&d.push(`${String(u.ename??"Error")}: ${String(u.evalue??"")}`.trimEnd())}d.length>0&&s.push(`### Output
15
+
16
+ ${d.join(`
17
+
18
+ `)}`)}),`${s.join(`
19
+
20
+ `)}
21
+ `},DM=e=>{try{const t=new URL(e);for(const n of Array.from(t.searchParams.keys()))Yh.test(n)&&t.searchParams.set(n,vl);return t.toString()}catch{return e}},Xh=(e,t)=>{if(t&&Yh.test(t))return vl;if(t==="cookies"&&Array.isArray(e))return e.map(s=>!s||typeof s!="object"?s:{...s,value:vl});if(t==="text"||t==="encoding")return NM;if(typeof e=="string")return t==="url"?DM(e):e;if(Array.isArray(e))return e.map(s=>Xh(s));if(!e||typeof e!="object")return e;const n=e,r=typeof n.name=="string"&&Yh.test(n.name);return Object.fromEntries(Object.entries(n).map(([s,o])=>[s,r&&s==="value"?vl:Xh(o,s)]))},OM=async(e,t)=>{const n=await e.text();if(t==="har")try{const r=Xh(JSON.parse(n));return new File([`${JSON.stringify(r,null,2)}
22
+ `],e.name,{type:"text/plain"})}catch{return}if(t==="ipynb")try{const r=PM(JSON.parse(n),e.name);if(r)return new File([r],e.name,{type:"text/plain"})}catch{}return new File([n],e.name,{type:"text/plain"})},HM=async e=>{try{const t=(await mt(async()=>{const{default:o}=await import("./vendor-heic2any-sztndhZI.js").then(i=>i.h);return{default:o}},__vite__mapDeps([0,1]))).default,n=await t({blob:e,toType:"image/jpeg",quality:.9}),r=Array.isArray(n)?n[0]:n;if(!r)return;const s=e.name.replace(/\.(heic|heif)$/i,".jpg");return new File([r],s,{type:"image/jpeg"})}catch(t){console.warn("Failed to convert HEIC attachment to JPEG",t);return}},k0=e=>{const t=wm(e.name),n=Pb(e);if(n==="image/heic"||n==="image/heif"||t==="heic"||t==="heif")return HM(e).then(s=>s?{file:s,mimeType:"image/jpeg"}:void 0);if(t==="har"||t==="ipynb")return OM(e,t).then(s=>s?{file:s,mimeType:"text/plain"}:void 0);const r=RM(e);return typeof r=="string"?{file:e,mimeType:r}:r?.then(s=>s?{file:e,mimeType:s}:void 0)},FM=(e,t=[])=>{if(!AM.has(wm(e.name))){const n=k0(e);return n instanceof Promise?n.then(r=>r?[r]:void 0):n?[n]:void 0}return mt(()=>import("./document-attachments-CZl9rK1z.js"),__vite__mapDeps([2,3])).then(async({extractDocumentAttachments:n})=>{const r=await n(e,t);if(!r)return;const s=[{file:r.textFile,mimeType:"text/plain"}];for(const o of r.images){const i=await k0(o);if(!i||!i.mimeType.startsWith("image/"))return;s.push(i)}return s})},BM=3,VM=3,$M=100*1024*1024,Ws=20;let eo=0,nf=0;const Do=[],xo=new Map,fs=new Map,td=new Map,M0=(e,t)=>{if(e.length===0)return!1;const n=new Set(t.map(r=>r.filename.toLowerCase()));return e.some(r=>n.has(r.toLowerCase()))},Ic=(e="attachment")=>`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`,zM=(e,t)=>{if(!(!t.startsWith("image/")||typeof URL.createObjectURL!="function"))return URL.createObjectURL(e)},I0=new Set,Db=e=>{!e||I0.has(e)||(I0.add(e),typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e))},UM=e=>{for(const t of e)Db(t.previewUrl)},qM=(e,t)=>new Promise((n,r)=>{const s=new FileReader;s.onload=()=>{const o=typeof s.result=="string"?s.result:"",i=o.indexOf(",");n(i===-1?o:`data:${t};base64,${o.slice(i+1)}`)},s.onerror=()=>r(s.error??new Error("Failed to read file")),s.onabort=()=>r(new Error("File read aborted")),s.readAsDataURL(e)}),Ob=async e=>Promise.all(e.map(async t=>{if(t.source!=="local"||t.dataUrl.startsWith("data:"))return{...t,previewUrl:void 0};const n=t.file instanceof Blob?t.file:null;if(!n)throw new Error("Attachment data is unavailable");return{...t,dataUrl:await qM(n,t.mimeType),previewUrl:void 0}})),WM=e=>{if(!e.startsWith("data:"))return 0;const t=e.indexOf(",");if(t<0)return 0;const n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);if(!n.endsWith(";base64"))return 0;let s=0;return r.endsWith("==")?s=2:r.endsWith("=")&&(s=1),Math.max(0,Math.floor(r.length*3/4)-s)},KM=(e,t)=>{const n=e.indexOf(",");if(!e.startsWith("data:")||n<0)return null;const r=e.slice(5,n);if(!r.toLowerCase().endsWith(";base64"))return null;try{const s=atob(e.slice(n+1)),o=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)o[i]=s.charCodeAt(i);return new Blob([o],{type:r.slice(0,-7)||t})}catch{return null}},GM=e=>{const t=typeof e=="object"&&e&&"code"in e?String(e.code):"";return t==="ATTACHMENT_TOO_LARGE"?"File exceeds the 100 MB upload limit.":t==="ATTACHMENT_LIMIT_REACHED"?"Too many unused uploads. Remove a file and retry.":t==="DAEMON_UNAVAILABLE"?"The runtime changed or is unavailable. Retry the upload.":e instanceof DOMException&&e.name==="AbortError"?"Upload canceled.":"Upload failed. Retry or remove this file."},cn=(e,t)=>{let n=!1;return Ye.setState(r=>({attachedFiles:r.attachedFiles.map(s=>s.id!==e?s:(n=!0,t(s)))})),n},Hb=()=>{for(;nf<VM&&Do.length>0;){const e=Do.shift();if(!e)continue;const t=Ye.getState().attachedFiles.find(n=>n.id===e);!t||t.source!=="local"||t.uploadState?.status!=="preparing"||(nf+=1,ZM(e).finally(()=>{nf-=1,Hb()}))}},rf=e=>{Do.includes(e)||xo.has(e)||(Do.push(e),Hb())},ZM=async e=>{const t=Ye.getState().attachedFiles.find(a=>a.id===e);if(!t||t.source!=="local")return;const n=t.file instanceof Blob?t.file:KM(t.dataUrl,t.mimeType);if(!n||n.size===0){cn(e,a=>({...a,uploadState:{status:"failed",error:"The file data is no longer available."}}));return}const r=Y(),s=(fs.get(e)??0)+1;fs.set(e,s);const o=new AbortController;xo.set(e,o);let i=-1;cn(e,a=>({...a,uploadState:{status:"uploading",progress:n.size>0?0:null}}));try{const a=await Ee.uploadAttachment(n,{filename:t.filename,mime:t.mimeType,signal:o.signal,onProgress:({loaded:d,total:f})=>{const u=f>0?Math.min(99,Math.floor(d/f*100)):null;u!==i&&(i=u??i,!(fs.get(e)!==s||r!==Y())&&cn(e,h=>h.uploadState?.status==="uploading"?{...h,uploadState:{status:"uploading",progress:u}}:h))}},{runtimeKey:r});if(fs.get(e)!==s||r!==Y()){Ee.deleteAttachment(a.id,{runtimeKey:r}).catch(()=>{});return}cn(e,d=>({...d,uploadState:{status:"ready",attachmentId:a.id,expiresAt:a.expiresAt}}));const l=setTimeout(()=>{td.delete(e),cn(e,d=>d.uploadState?.status==="ready"&&d.uploadState.attachmentId===a.id?{...d,uploadState:{status:"failed",error:"Upload expired. Retry the upload."}}:d)},Math.max(0,a.expiresAt-Date.now()+1));td.set(e,l)}catch(a){if(fs.get(e)!==s)return;cn(e,l=>({...l,uploadState:{status:"failed",error:GM(a)}}))}finally{xo.get(e)===o&&xo.delete(e)}},Jh=e=>{fs.set(e.id,(fs.get(e.id)??0)+1),xo.get(e.id)?.abort(),xo.delete(e.id);const t=td.get(e.id);t&&clearTimeout(t),td.delete(e.id);const n=Do.indexOf(e.id);n>=0&&Do.splice(n,1)},YM=(e,t)=>{Jh(e),Db(e.previewUrl),t&&e.uploadState?.status==="ready"&&Ee.deleteAttachment(e.uploadState.attachmentId,{runtimeKey:Y()}).catch(()=>{})},rr=(e,t)=>{for(const n of e)YM(n,t)},XM=10,JM=50*1024*1024,QM=e=>{let t=0;for(const n of Object.values(e))for(const r of n)t+=Number.isFinite(r.size)?r.size:0;return t};let E0=0;const eI=(e,t,n)=>!e||e.draftKey!==t?!1:n===e.text,Ye=Lt()((e,t)=>({pendingInputText:null,pendingInputMode:"replace",pendingRevertText:null,pendingSyntheticParts:null,pendingStarterInsert:null,pendingWorktreeRestore:null,attachedFiles:[],stashedAttachmentsByDraft:{},activeAttachmentsDraftKey:null,sentDraftClear:null,setPendingInputText:(n,r="replace")=>e({pendingInputText:n,pendingInputMode:r}),consumePendingInputText:()=>{const{pendingInputText:n,pendingInputMode:r}=t();return n===null?null:(e({pendingInputText:null,pendingInputMode:"replace"}),{text:n,mode:r})},setPendingRevertText:n=>e({pendingRevertText:n}),consumePendingRevertText:()=>{const{pendingRevertText:n}=t();return n===null?null:(e({pendingRevertText:null}),n)},requestStarterInsert:n=>e({pendingStarterInsert:{name:n}}),requestStarterTextInsert:n=>e({pendingStarterInsert:{text:n}}),consumePendingStarterInsert:()=>{const{pendingStarterInsert:n}=t();return n===null?null:(e({pendingStarterInsert:null}),n)},setPendingSyntheticParts:n=>e({pendingSyntheticParts:n}),consumePendingSyntheticParts:()=>{const{pendingSyntheticParts:n}=t();return n!==null&&e({pendingSyntheticParts:null}),n},requestWorktreeRestore:n=>e({pendingWorktreeRestore:n}),consumePendingWorktreeRestore:()=>{const{pendingWorktreeRestore:n}=t();return n===null?null:(e({pendingWorktreeRestore:null}),n)},resetForRuntimeSwitch:()=>{t().pendingWorktreeRestore!==null&&e({pendingWorktreeRestore:null}),t().sentDraftClear!==null&&e({sentDraftClear:null})},publishSentDraftClear:(n,r)=>{n&&(E0+=1,e({sentDraftClear:{draftKey:n,text:r,nonce:E0}}))},consumeSentDraftClear:n=>{t().sentDraftClear?.nonce===n&&e({sentDraftClear:null})},addAttachedFile:async n=>{const r=eo,s=Ic("preparing"),o={id:s,file:n,dataUrl:"",mimeType:n.type||"application/octet-stream",filename:n.name,size:n.size,source:"local",uploadState:{status:"preparing"}};if(e(i=>({attachedFiles:[...i.attachedFiles,o]})),t().attachedFiles.length>Ws)return cn(s,i=>({...i,uploadState:{status:"failed",error:`You can attach up to ${Ws} files to one message.`}})),!1;for(let i=0;i<BM;i+=1){const a=t().attachedFiles.filter(h=>h.id!==s).map(h=>h.filename);let l;try{const h=FM(n,a);l=h instanceof Promise?await h:h}catch{l=null}if(r!==eo||!t().attachedFiles.some(h=>h.id===s))return!1;if(!l||l.length===0)return cn(s,h=>({...h,uploadState:{status:"failed",error:"This file could not be prepared."}})),!1;if(t().attachedFiles.length-1+l.length>Ws)return cn(s,h=>({...h,uploadState:{status:"failed",error:`You can attach up to ${Ws} files to one message.`}})),!1;if(l.some(h=>h.file.size>$M))return cn(s,h=>({...h,uploadState:{status:"failed",error:"File exceeds the 100 MB upload limit."}})),!1;const d=l.slice(1).map(h=>h.file.name);if(M0(d,t().attachedFiles.filter(h=>h.id!==s)))continue;const f=l.length>1?Ic("document"):void 0,u=l.map(h=>({id:Ic(),file:h.file,dataUrl:"",previewUrl:zM(h.file,h.mimeType),mimeType:h.mimeType,filename:h.file.name,size:h.file.size,source:"local",uploadState:{status:"preparing"},sourceDocumentId:f}));if(r!==eo)return rr(u,!1),!1;if(M0(d,t().attachedFiles.filter(h=>h.id!==s))){rr(u,!1);continue}e(h=>({attachedFiles:h.attachedFiles.flatMap(m=>m.id===s?u:[m])}));for(const h of u)rf(h.id);return!0}return cn(s,i=>({...i,uploadState:{status:"failed",error:"Generated filenames conflict with existing attachments."}})),!1},retryAttachmentUpload:n=>{const r=t().attachedFiles.find(s=>s.id===n);if(!(!r||r.source!=="local")){if(r.sourceDocumentId){for(const s of t().attachedFiles.filter(o=>o.sourceDocumentId===r.sourceDocumentId))(s.uploadState?.status==="failed"||s.uploadState?.status==="ready"&&s.uploadState.expiresAt<=Date.now())&&(cn(s.id,o=>({...o,uploadState:{status:"preparing"}})),rf(s.id));return}cn(n,s=>({...s,uploadState:{status:"preparing"}})),rf(n)}},removeAttachedFile:n=>{const r=t().attachedFiles.find(i=>i.id===n);if(!r)return;const s=r.sourceDocumentId?t().attachedFiles.filter(i=>i.sourceDocumentId===r.sourceDocumentId):[r];rr(s,!0);const o=new Set(s.map(i=>i.id));e(i=>({attachedFiles:i.attachedFiles.filter(a=>!o.has(a.id))}))},detachAttachedFiles:n=>{const r=new Set(n),s=t().attachedFiles.filter(a=>r.has(a.id));rr(s,!1);const o=t().stashedAttachmentsByDraft;let i=o;if(o){i={};for(const[a,l]of Object.entries(o)){const d=l.filter(f=>!r.has(f.id));UM(l.filter(f=>r.has(f.id))),d.length>0&&(i[a]=d)}}e(a=>({attachedFiles:a.attachedFiles.filter(l=>!r.has(l.id)),stashedAttachmentsByDraft:i}))},restoreAttachmentsForRetry:n=>{const r=t().attachedFiles.length;if(!n||n.length===0)return{ok:!0,restoredCount:0,totalCount:r};const s=new Set(t().attachedFiles.map(f=>f.id)),o=new Set,i=[];for(const f of n)s.has(f.id)||o.has(f.id)||(o.add(f.id),i.push(f));if(i.length===0)return{ok:!0,restoredCount:0,totalCount:r};if(r+i.length>Ws)return{ok:!1,reason:"attachment-limit",limit:Ws,currentCount:r,missingCount:i.length};const a=new Set(i.map(f=>f.id)),l=t().stashedAttachmentsByDraft??{},d={};for(const[f,u]of Object.entries(l)){const h=u.filter(m=>!a.has(m.id));h.length>0&&(d[f]=h)}return e(f=>({attachedFiles:[...f.attachedFiles,...i.map(qd)],stashedAttachmentsByDraft:d})),{ok:!0,restoredCount:i.length,totalCount:r+i.length}},activateAttachmentsDraft:n=>{const r=t().activeAttachmentsDraftKey;if(r===null){e({activeAttachmentsDraftKey:n});return}if(r===n)return;const s=t().stashedAttachmentsByDraft,o=t().attachedFiles,i=s[n]??[],a={};for(const[d,f]of Object.entries(s))d!==r&&d!==n&&(a[d]=f);o.length>0&&(a[r]=o);const l=Object.keys(a);for(;l.length>XM||QM(a)>JM;){const d=l.shift();if(!d)break;rr(a[d]??[],!0),delete a[d]}e({attachedFiles:i,stashedAttachmentsByDraft:a,activeAttachmentsDraftKey:n})},clearStashedAttachmentsForSession:n=>{const r=a=>{try{const l=JSON.parse(a);return Array.isArray(l)&&l[0]===n.runtimeKey&&l[1]===n.directory&&l[2]===n.sessionId}catch{return!1}},s=t(),o={};for(const[a,l]of Object.entries(s.stashedAttachmentsByDraft))r(a)?rr(l,!0):o[a]=l;const i=s.activeAttachmentsDraftKey!==null&&r(s.activeAttachmentsDraftKey);i&&rr(s.attachedFiles,!0),e({attachedFiles:i?[]:s.attachedFiles,stashedAttachmentsByDraft:o})},setAttachedFiles:n=>{eo+=1;const r=new Set(n.map(s=>s.id));rr(t().attachedFiles.filter(s=>!r.has(s.id)),!1),e({attachedFiles:n.map(s=>s.source==="local"&&s.uploadState===void 0?{...s,uploadState:{status:"failed",error:"Upload needs to be refreshed. Retry the upload."}}:s)})},clearAttachedFiles:()=>{eo+=1,rr(t().attachedFiles,!0),e({attachedFiles:[]})},addRestoredAttachment:({url:n,mimeType:r,filename:s})=>{const o=Ic("restored"),i=new File([],s,{type:r}),a={id:o,file:i,dataUrl:n,mimeType:r,filename:s,size:WM(n),source:"server",serverPath:n};e(l=>({attachedFiles:[...l.attachedFiles,a]}))}}));l5(()=>{eo+=1;const e=s=>s.map(o=>o.source==="local"?{...o,uploadState:{status:"failed",error:"The runtime changed. Retry the upload."}}:o),t=Ye.getState().attachedFiles;for(const s of t)Jh(s);const n=Ye.getState().stashedAttachmentsByDraft??{},r={};for(const[s,o]of Object.entries(n)){for(const i of o)Jh(i);r[s]=e(o)}Ye.setState({attachedFiles:e(t),stashedAttachmentsByDraft:r,pendingWorktreeRestore:null,sentDraftClear:null})});const bo="oc.sessions.folders",wo="oc.sessions.folderCollapse",nd="oc.sessions.folders.v2.index",Fb="/api/pi/session-folders",tI=250,zt=Gt(),sf=Ld();let vs=null,Zi=!1,xl=!1,Yi=!1,Xi,Ji,Qi=null,ea=null,Oo=null,Pn=Y(),Cs=0,rd=0;const sd=new Map,Ur=(e,t)=>`${e}.v2:${encodeURIComponent(t)}`,Sm=()=>{try{const e=JSON.parse(zt.getItem(nd)??"");return e.version===2&&Array.isArray(e.runtimes)?{version:2,legacyClaimed:!!e.legacyClaimed,runtimes:e.runtimes}:{version:2,legacyClaimed:!1,runtimes:[]}}catch{return{version:2,legacyClaimed:!1,runtimes:[]}}},va=(e,t=Date.now(),n=zt)=>{const r=Sm(),s=[{runtimeKey:e,updatedAt:t},...r.runtimes.filter(o=>o.runtimeKey!==e)];n.setItem(nd,JSON.stringify({version:2,legacyClaimed:r.legacyClaimed,runtimes:s}))},Bb=e=>{const t=Sm();if(t.legacyClaimed)return;const n=zt.getItem(bo),r=zt.getItem(wo);n&&zt.setItem(Ur(bo,e),n),r&&zt.setItem(Ur(wo,e),r);const s={...t,legacyClaimed:!0};zt.setItem(nd,JSON.stringify(s)),zt.getItem(nd)===JSON.stringify(s)&&(zt.removeItem(bo),zt.removeItem(wo)),va(e,0)},nI=(e,t)=>{if(typeof window>"u")return;vs&&clearTimeout(vs);const n=JSON.parse(JSON.stringify(e)),r=Array.from(t),s=Pn,o=Cs;vs=setTimeout(()=>{if(vs=null,s!==Y()||o!==Cs)return;const i=Math.max(Date.now(),(sd.get(s)??0)+1);sd.set(s,i),Nt(Fb,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:1,foldersMap:n,collapsedFolderIds:r,updatedAt:i})}).then(l=>{l.status===409&&(s!==Y()||o!==Cs||(Zi=!1,Yi=!0,Wd()))}).catch(()=>{})},tI)},j0=(e=Pn)=>{try{Bb(e);const t=zt.getItem(Ur(bo,e));if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};const r={};for(const[s,o]of Object.entries(n)){if(!Array.isArray(o))continue;const i=[];for(const a of o){if(!a||typeof a!="object")continue;const l=a,d=typeof l.id=="string"?l.id.trim():"",f=typeof l.name=="string"?l.name.trim():"",u=typeof l.createdAt=="number"?l.createdAt:0;if(!d||!f)continue;const h=Array.isArray(l.sessionIds)?l.sessionIds.filter(g=>typeof g=="string"&&g.trim().length>0):[],m=typeof l.parentId=="string"?l.parentId:null;i.push({id:d,name:f,sessionIds:h,createdAt:u,parentId:m})}i.length>0&&(r[s]=i)}return r}catch{return{}}},_0=(e=Pn)=>{try{Bb(e);const t=zt.getItem(Ur(wo,e));if(!t)return new Set;const n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(r=>typeof r=="string")):new Set}catch{return new Set}},Vb=e=>{Qi=e,Oo=Pn,clearTimeout(Xi),Xi=setTimeout(()=>{try{const t=Oo??Pn;zt.setItem(Ur(bo,t),JSON.stringify(e)),va(t),Qi=null}catch{}},300)},$b=e=>{ea=e,Oo=Pn,clearTimeout(Ji),Ji=setTimeout(()=>{try{const t=Oo??Pn;zt.setItem(Ur(wo,t),JSON.stringify(Array.from(e))),va(t),ea=null}catch{}},300)},zb=()=>{Xi&&clearTimeout(Xi),Ji&&clearTimeout(Ji),Xi=void 0,Ji=void 0;const e=Oo??Pn;let t=!1;if(Qi!==null){const n=Ur(bo,e),r=JSON.stringify(Qi);zt.setItem(n,r),sf.setItem(n,r),Qi=null,t=!0}if(ea!==null){const n=Ur(wo,e),r=JSON.stringify(Array.from(ea));zt.setItem(n,r),sf.setItem(n,r),ea=null,t=!0}if(t){const n=Date.now();va(e,n),va(e,n,sf)}Oo=null};if(typeof window<"u"){const e=()=>{try{zb()}catch{}};window.addEventListener("pagehide",e,{capture:!0}),window.addEventListener("beforeunload",e,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()}),document.addEventListener("freeze",e))}const sr=(e,t)=>{rd+=1,Vb(e),$b(t),nI(e,t)},rI=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`folder_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,ui=(e,t,n)=>{const r=new Set(t.map(o=>o.id));let s=null;for(const o of e)!r.has(o.id)&&n.has(o.id)&&(s||(s=new Set(n)),s.delete(o.id));return s},Cm=Lt()(mr((e,t)=>({foldersMap:j0(),collapsedFolderIds:_0(),resetForRuntimeSwitch:n=>{try{zb()}catch{}Pn=n,Cs+=1,rd=0,Zi=!1,xl=!1,Yi=!1,vs&&clearTimeout(vs),vs=null,e({foldersMap:j0(n),collapsedFolderIds:_0(n)}),queueMicrotask(()=>{Wd()})},getFoldersForScope:n=>n?t().foldersMap[n]??[]:[],createFolder:(n,r,s)=>{const o=r.trim()||"New folder",i={id:rI(),name:o,sessionIds:[],createdAt:Date.now(),parentId:s??null},a=t().foldersMap,l=a[n]??[],d={...a,[n]:[...l,i]};return e({foldersMap:d}),sr(d,t().collapsedFolderIds),i},renameFolder:(n,r,s)=>{const o=s.trim();if(!o||!n)return;const i=t().foldersMap,a=i[n];if(!a)return;const l=a.map(f=>f.id===r?{...f,name:o}:f),d={...i,[n]:l};e({foldersMap:d}),sr(d,t().collapsedFolderIds)},deleteFolder:(n,r)=>{if(!n)return;const s=t().foldersMap,o=s[n];if(!o)return;const i=new Set([r]);let a=!0;for(;a;){a=!1;for(const h of o)h.parentId&&i.has(h.parentId)&&!i.has(h.id)&&(i.add(h.id),a=!0)}const l=o.filter(h=>!i.has(h.id)),d={...s,[n]:l},f=t().collapsedFolderIds,u=ui(o,l,f);e(u?{foldersMap:d,collapsedFolderIds:u}:{foldersMap:d}),sr(d,u??f)},addSessionToFolder:(n,r,s)=>{if(!n||!r||!s)return;const o=t().foldersMap,i=o[n];if(!i)return;const a=i.find(h=>h.id===r);if(!a)return;const l=i.reduce((h,m)=>h+(m.sessionIds.includes(s)?1:0),0);if(a.sessionIds.includes(s)&&l===1)return;const d=i.map(h=>{const m=h.sessionIds.filter(g=>g!==s);return h.id===r?{...h,sessionIds:[...m,s]}:m.length!==h.sessionIds.length?{...h,sessionIds:m}:h}),f={...o,[n]:d},u=ui(i,d,t().collapsedFolderIds);e(u?{foldersMap:f,collapsedFolderIds:u}:{foldersMap:f}),sr(f,u??t().collapsedFolderIds)},addSessionsToFolder:(n,r,s)=>{if(!n||!r||s.length===0)return;const o=t().foldersMap,i=o[n];if(!i)return;const a=new Set(s.filter(m=>typeof m=="string"&&m.length>0));if(a.size===0)return;const l=i.find(m=>m.id===r);if(!l)return;let d=!1;for(const m of i){for(const g of a)if(m.sessionIds.includes(g)&&(m.id!==r||!l.sessionIds.includes(g))){d=!0;break}if(d)break}if(!d){for(const m of a)if(!l.sessionIds.includes(m)){d=!0;break}}if(!d)return;const f=i.map(m=>{const g=m.sessionIds.filter(x=>!a.has(x));return m.id===r?{...m,sessionIds:[...g,...a]}:g.length!==m.sessionIds.length?{...m,sessionIds:g}:m}),u={...o,[n]:f},h=ui(i,f,t().collapsedFolderIds);e(h?{foldersMap:u,collapsedFolderIds:h}:{foldersMap:u}),sr(u,h??t().collapsedFolderIds)},removeSessionsFromFolders:(n,r)=>{if(!n||r.length===0)return;const s=t().foldersMap,o=s[n];if(!o)return;const i=new Set(r.filter(u=>typeof u=="string"&&u.length>0));if(i.size===0)return;let a=!1;const l=o.map(u=>{const h=u.sessionIds.filter(m=>!i.has(m));return h.length!==u.sessionIds.length?(a=!0,{...u,sessionIds:h}):u});if(!a)return;const d={...s,[n]:l},f=ui(o,l,t().collapsedFolderIds);e(f?{foldersMap:d,collapsedFolderIds:f}:{foldersMap:d}),sr(d,f??t().collapsedFolderIds)},removeSessionFromFolder:(n,r)=>{if(!n||!r)return;const s=t().foldersMap,o=s[n];if(!o)return;let i=!1;const a=o.map(f=>{const u=f.sessionIds.filter(h=>h!==r);return u.length!==f.sessionIds.length?(i=!0,{...f,sessionIds:u}):f});if(!i)return;const l={...s,[n]:a},d=ui(o,a,t().collapsedFolderIds);e(d?{foldersMap:l,collapsedFolderIds:d}:{foldersMap:l}),sr(l,d??t().collapsedFolderIds)},removeSessionEverywhere:(n,r)=>{if(!n||n!==Pn||n!==Y()||!r)return;const s=t().foldersMap;let o=null;for(const[i,a]of Object.entries(s)){let l=!1;const d=a.map(f=>{const u=f.sessionIds.filter(h=>h!==r);return u.length===f.sessionIds.length?f:(l=!0,{...f,sessionIds:u})});l&&(o??={...s},o[i]=d)}o&&(e({foldersMap:o}),sr(o,t().collapsedFolderIds))},toggleFolderCollapse:n=>{const r=t().collapsedFolderIds,s=new Set(r);s.has(n)?s.delete(n):s.add(n),e({collapsedFolderIds:s}),sr(t().foldersMap,s)},getSessionFolderId:(n,r)=>{if(!n||!r)return null;const s=t().foldersMap[n];if(!s)return null;for(const o of s)if(o.sessionIds.includes(r))return o.id;return null}}),{name:"session-folders-store"})),Wd=async()=>{if(typeof window>"u"||xl||Zi&&!Yi)return;Yi=!1,xl=!0;const e=Pn,t=Cs,n=rd;let r=!1;try{const s=await Nt(Fb).catch(()=>null);if(!s||!s.ok)return;const o=await s.json().catch(()=>null);if(!o)return;if(o.exists===!1){r=!0;return}const i=o.foldersMap&&typeof o.foldersMap=="object"?o.foldersMap:{},a=Array.isArray(o.collapsedFolderIds)?new Set(o.collapsedFolderIds.filter(u=>typeof u=="string")):new Set;if(t!==Cs||e!==Y())return;const l=Sm().runtimes.find(u=>u.runtimeKey===e)?.updatedAt??0,d=typeof o.updatedAt=="number"&&Number.isFinite(o.updatedAt)?o.updatedAt:0;d>0&&sd.set(e,Math.max(sd.get(e)??0,d)),(o.exists===!0||d>0)&&rd===n&&d>=l&&(Cm.setState({foldersMap:i,collapsedFolderIds:a}),Vb(i),$b(a)),r=!0}catch{}finally{t===Cs&&e===Y()&&(xl=!1,r&&(Zi=!0),Yi&&(Zi=!1,queueMicrotask(()=>{Wd()})))}},sI=()=>{typeof window>"u"||Wd()};sI();const oI=e=>{if(e.runtimeKey!==Y()||!e.directory||e.directory==="global"||!e.sessionId)return;const t=em(e.sessionId,e.directory,e.runtimeKey);t&&ft.getState().clearQueue(t),Cm.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),oM.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Go(e.runtimeKey,e.directory,e.sessionId);n&&wM(n,!0),Ye.getState().clearStashedAttachmentsForSession(e)},xa=e=>{if(!e||e.streamingMessages.size===0)return null;let t=null;for(const n of e.streamingMessages){const r=e.messages.get(n);r?.role==="assistant"&&(t=r.id)}return t},iI=(e,t)=>e.sessionId===t.sessionId&&e.directory===t.directory&&e.messages===t.messages&&e.parts===t.parts&&e.partOrder===t.partOrder&&e.streamingMessages===t.streamingMessages&&e.lifecycle===t.lifecycle&&e.model===t.model&&e.thinking===t.thinking&&e.queue===t.queue,aI=e=>{let t=null;for(const n of e.messages.values())n.role==="user"&&(t=n.id);return t},Ub=e=>{const t=e?.awaitingPromptEcho?.baselineUserMessageId;return!e||e.awaitingPromptEcho===void 0?!1:aI(e)===t},cI=(e,t)=>{if(e===t||e.messages===t.messages&&e.parts===t.parts&&e.partOrder===t.partOrder)return!0;if(e.messages.size!==t.messages.size||t.lastMutationKind==="structure")return!1;if(t.lastMutationKind==="part"&&t.lastMutatedMessageId)return t.messages.get(t.lastMutatedMessageId)?.role!=="user";const n=xa(t);return n?Qh(e,t,n):!1},Qh=(e,t,n)=>e===t?!0:e.messages.size!==t.messages.size||e.messages!==t.messages||t.lastMutationKind==="structure"?!1:t.lastMutationKind==="part"&&t.lastMutatedMessageId===n?!0:t.lastMutationKind==="part"&&t.lastMutatedMessageId&&t.lastMutatedMessageId!==n?!1:dI(e,t,n),lI=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},dI=(e,t,n)=>{for(const[r,s]of t.messages){const o=e.messages.get(r);if(!o||o.id!==s.id)return!1;if(r===n)continue;if(o!==s)return!1;const i=e.partOrder.get(r)??[],a=t.partOrder.get(r)??[];if(!lI(i,a))return!1;for(const l of a)if(e.parts.get(l)!==t.parts.get(l))return!1}for(const r of e.messages.keys())if(!t.messages.has(r))return!1;return!0},uI="selection-store",fI=3,T0="context-store",A0=1,So=500,ba=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_s=e=>typeof e=="string",km=e=>typeof e=="object"&&e!==null&&typeof e.providerId=="string"&&typeof e.modelId=="string",N0=(e,t)=>`${e}/${t}`,L0=(e,t,n)=>JSON.stringify([e,t,n]),hI=(e,t)=>JSON.stringify([e,t]),Tn=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===3&&t.every(_s))return t}catch{}return null},of=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===2&&t.every(_s))return t}catch{}return null},to=new Set,no=new Set,Ir=new Set;let ep=!1;const pI=()=>{to.clear(),no.clear(),Ir.clear(),ep=!1},Kd=e=>{if(!Array.isArray(e))return[];const t=new Set,n=[];for(const r of e)typeof r!="string"||t.has(r)||(t.add(r),n.push(r));return n},mI=e=>{const t=Kd(e.sessionRecency),n=new Set(t),r=s=>{n.has(s)||(n.add(s),t.push(s))};for(const s of e.sessionModelSelections.keys())r(s);for(const s of e.sessionAgentSelections.keys())r(s);for(const s of e.sessionAgentModelSelections.keys())r(s);for(const s of e.sessionAgentModelVariantSelections.keys())r(s);for(const s of e.clearedVariantKeys){const o=typeof s=="string"?Tn(s):null;o&&r(o[0])}return t},Ec=(e,t)=>{let n=null;for(const r of t)(n??e).has(r)&&(n||(n=new Map(e)),n.delete(r));return n??e},jc=(e,t)=>{if(!e.has(t))return e;const n=new Map(e);return n.delete(t),n},os=(e,t=[])=>{const n=mI(e);for(const o of t){const i=n.indexOf(o);i!==-1&&n.splice(i,1),n.push(o)}if(n.length<=So){const o=e.sessionRecency;return o.length===n.length&&o.every((a,l)=>a===n[l])?e:{...e,sessionRecency:n}}const r=new Set(n.slice(0,n.length-So));let s=e.clearedVariantKeys;return s.some(o=>{const i=typeof o=="string"?Tn(o):null;return i!==null&&r.has(i[0])})&&(s=s.filter(o=>{const i=typeof o=="string"?Tn(o):null;return i===null||!r.has(i[0])})),{sessionModelSelections:Ec(e.sessionModelSelections,r),sessionAgentSelections:Ec(e.sessionAgentSelections,r),sessionAgentModelSelections:Ec(e.sessionAgentModelSelections,r),sessionAgentModelVariantSelections:Ec(e.sessionAgentModelVariantSelections,r),clearedVariantKeys:s,sessionRecency:n.slice(n.length-So)}},R0=(e,t)=>e.sessionModelSelections.has(t)||e.sessionAgentSelections.has(t)||e.sessionAgentModelSelections.has(t)||e.sessionAgentModelVariantSelections.has(t)||e.sessionRecency.includes(t)?!0:e.clearedVariantKeys.some(n=>Tn(n)?.[0]===t),gI=e=>{const t=Kd(e.sessionRecency),n=new Set(t),r=o=>{typeof o=="string"&&!n.has(o)&&(n.add(o),t.push(o))},s=o=>{if(Array.isArray(o))for(const i of o)Array.isArray(i)&&i.length>0&&r(i[0])};if(s(e.sessionModelSelections),s(e.sessionAgentSelections),s(e.sessionAgentModelSelections),s(e.sessionAgentModelVariantSelections),Array.isArray(e.clearedVariantKeys)){for(const o of e.clearedVariantKeys)if(typeof o=="string"){const i=Tn(o);i&&r(i[0])}}return t},_c=(e,t)=>Array.isArray(e)?e.filter(n=>{const r=Array.isArray(n)&&n.length>0&&typeof n[0]=="string"?n[0]:null;return r===null||t.has(r)}):e,yI=(e,t)=>Array.isArray(e)?e.filter(n=>{if(typeof n!="string")return!0;const r=Tn(n);return r===null||t.has(r[0])}):e,vI=e=>{if(!ba(e))return e;try{const t=gI(e),n=Kd(e.sessionRecency),r=n.length===t.length&&n.every((o,i)=>o===t[i])&&Array.isArray(e.sessionRecency)&&e.sessionRecency.length===n.length;if(t.length<=So)return r?e:{...e,sessionRecency:t};const s=new Set(t.slice(t.length-So));return{...e,sessionModelSelections:_c(e.sessionModelSelections,s),sessionAgentSelections:_c(e.sessionAgentSelections,s),sessionAgentModelSelections:_c(e.sessionAgentModelSelections,s),sessionAgentModelVariantSelections:_c(e.sessionAgentModelVariantSelections,s),clearedVariantKeys:yI(e.clearedVariantKeys,s),sessionRecency:t.slice(t.length-So)}}catch{return e}},P0=(e,t,n)=>{e.delete(t),e.set(t,n)},ks=(e,t)=>{const n=new Map;if(e===void 0)return{value:n,failed:!1};if(!Array.isArray(e))return{value:n,failed:!0};let r=!1;for(const s of e){if(!Array.isArray(s)||s.length!==2){r=!0;continue}const[o,i]=s;if(typeof o!="string"||!t(i)){r=!0;continue}n.set(o,i)}return{value:n,failed:r}},qb=e=>{const t=new Map;if(e===void 0)return{value:t,failed:!1};if(!Array.isArray(e))return{value:t,failed:!0};let n=!1;for(const r of e){if(!Array.isArray(r)||r.length!==2){n=!0;continue}const[s,o]=r;if(typeof s!="string"||!Array.isArray(o)){n=!0;continue}const i=ks(o,km);i.failed&&(n=!0),(i.value.size>0||o.length===0)&&t.set(s,i.value)}return{value:t,failed:n}},Wb=e=>{const t=new Map;if(e===void 0)return{value:t,failed:!1};if(!Array.isArray(e))return{value:t,failed:!0};let n=!1;for(const r of e){if(!Array.isArray(r)||r.length!==2){n=!0;continue}const[s,o]=r;if(typeof s!="string"||!Array.isArray(o)){n=!0;continue}const i=new Map;for(const a of o){if(!Array.isArray(a)||a.length!==2){n=!0;continue}const[l,d]=a;if(typeof l!="string"||!Array.isArray(d)){n=!0;continue}const f=ks(d,_s);f.failed&&(n=!0),f.value.size>0&&i.set(l,f.value)}i.size>0&&t.set(s,i)}return{value:t,failed:n}},xs=()=>({models:new Map,agents:new Map,agentModels:new Map,variants:new Map,currentAgentContext:new Map}),D0=e=>{if(e===null)return{status:"missing",failed:!1,data:xs()};let t;try{t=JSON.parse(e)}catch{return{status:"failed",failed:!0,data:xs()}}if(!ba(t))return{status:"failed",failed:!0,data:xs()};const n="state"in t?t.state:t;if(!ba(n))return{status:"failed",failed:!0,data:xs()};const r=ks(n.sessionModelSelections??void 0,km),s=ks(n.sessionAgentSelections??void 0,_s),o=qb(n.sessionAgentModelSelections??void 0),i=Wb(n.sessionAgentModelVariantSelections??void 0),a=ks(n.currentAgentContext??void 0,_s),l=r.failed||s.failed||o.failed||i.failed||a.failed;return{status:l?"failed":"ok",failed:l,data:{models:r.value,agents:s.value,agentModels:o.value,variants:i.value,currentAgentContext:a.value}}},xI=()=>{try{if(typeof window<"u"&&window.localStorage)return D0(window.localStorage.getItem(T0))}catch{return{status:"failed",failed:!0,data:xs()}}try{return D0(Ld().getItem(T0))}catch{return{status:"failed",failed:!0,data:xs()}}},bI=(e,t,n,r)=>{const s=e.get(t),o=s?.get(n);return o?.has(r)?(o.delete(r),o.size===0&&s?.delete(n),s&&s.size===0&&e.delete(t),!0):!1},At=Lt()(Pd((e,t)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,lastUsedProvider:null,hasHydrated:typeof window>"u",contextStoreMigrationVersion:void 0,clearedVariantKeys:[],sessionRecency:[],saveSessionModelSelection:(n,r,s)=>{to.add(n),ep=!0,e(o=>{const i=new Map(o.sessionModelSelections);return i.delete(n),i.set(n,{providerId:r,modelId:s}),{...os({...o,sessionModelSelections:i},[n]),lastUsedProvider:{providerID:r,modelID:s}}})},getSessionModelSelection:n=>t().sessionModelSelections.get(n)??null,saveSessionAgentSelection:(n,r)=>{t().sessionAgentSelections.get(n)!==r&&(to.add(n),e(s=>{if(s.sessionAgentSelections.get(n)===r)return s;const o=new Map(s.sessionAgentSelections);return o.delete(n),o.set(n,r),os({...s,sessionAgentSelections:o},[n])}))},getSessionAgentSelection:n=>t().sessionAgentSelections.get(n)??null,saveAgentModelForSession:(n,r,s,o)=>{const i=t().sessionAgentModelSelections.get(n)?.get(r);i?.providerId===s&&i?.modelId===o||(no.add(hI(n,r)),e(a=>{const l=a.sessionAgentModelSelections.get(n)?.get(r);if(l?.providerId===s&&l?.modelId===o)return a;const d=new Map(a.sessionAgentModelSelections),f=new Map(d.get(n)??new Map);return d.delete(n),f.set(r,{providerId:s,modelId:o}),d.set(n,f),os({...a,sessionAgentModelSelections:d},[n])}))},getAgentModelForSession:(n,r)=>t().sessionAgentModelSelections.get(n)?.get(r)??null,saveAgentModelVariantForSession:(n,r,s,o,i)=>{const a=N0(s,o),l=L0(n,r,a);if(i===void 0){if(t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0){t().hasHydrated||(Ir.add(l),e(f=>f.clearedVariantKeys.includes(l)?f:os({...f,clearedVariantKeys:[...f.clearedVariantKeys,l]},[n])));return}Ir.add(l),e(f=>{if(f.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0)return f;const u=new Map(f.sessionAgentModelVariantSelections),h=new Map(u.get(n)??new Map),m=new Map(h.get(r)??new Map);m.delete(a),m.size===0?h.delete(r):h.set(r,m),h.size===0?u.delete(n):(u.delete(n),u.set(n,h));const g=f.clearedVariantKeys.includes(l)?f.clearedVariantKeys:[...f.clearedVariantKeys,l];return os({...f,sessionAgentModelVariantSelections:u,clearedVariantKeys:g},[n])});return}t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)!==i&&(Ir.add(l),e(d=>{if(d.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===i)return d;const f=new Map(d.sessionAgentModelVariantSelections),u=new Map(f.get(n)??new Map),h=new Map(u.get(r)??new Map);return f.delete(n),h.set(a,i),u.set(r,h),f.set(n,u),os({...d,sessionAgentModelVariantSelections:f},[n])}))},getAgentModelVariantForSession:(n,r,s,o)=>{const i=N0(s,o);return t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(i)},forgetSession:n=>{if(!(!n||!R0(t(),n))){to.delete(n);for(const r of Array.from(no))of(r)?.[0]===n&&no.delete(r);for(const r of Array.from(Ir))Tn(r)?.[0]===n&&Ir.delete(r);e(r=>{if(!R0(r,n))return r;let s=r.clearedVariantKeys;s.some(i=>Tn(i)?.[0]===n)&&(s=s.filter(i=>Tn(i)?.[0]!==n));let o=r.sessionRecency;return o.includes(n)&&(o=o.filter(i=>i!==n)),{sessionModelSelections:jc(r.sessionModelSelections,n),sessionAgentSelections:jc(r.sessionAgentSelections,n),sessionAgentModelSelections:jc(r.sessionAgentModelSelections,n),sessionAgentModelVariantSelections:jc(r.sessionAgentModelVariantSelections,n),clearedVariantKeys:s,sessionRecency:o}})}}}),{name:uI,version:fI,storage:Qp(),partialize:e=>({sessionModelSelections:Array.from(e.sessionModelSelections.entries()),sessionAgentSelections:Array.from(e.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(e.sessionAgentModelSelections.entries()).map(([t,n])=>[t,Array.from(n.entries())]),sessionAgentModelVariantSelections:Array.from(e.sessionAgentModelVariantSelections.entries()).map(([t,n])=>[t,Array.from(n.entries()).map(([r,s])=>[r,Array.from(s.entries())])]),lastUsedProvider:e.lastUsedProvider,contextStoreMigrationVersion:e.contextStoreMigrationVersion,clearedVariantKeys:e.clearedVariantKeys,sessionRecency:e.sessionRecency}),merge:(e,t)=>{let n=!1,r;e===void 0?r=void 0:ba(e)?r=e:(n=!0,r=void 0);const s=ks(r?.sessionModelSelections??void 0,km),o=ks(r?.sessionAgentSelections??void 0,_s),i=qb(r?.sessionAgentModelSelections??void 0),a=Wb(r?.sessionAgentModelVariantSelections??void 0);r!==void 0&&(n=n||s.failed||o.failed||i.failed||a.failed);let l=t.lastUsedProvider;if(r?.lastUsedProvider!==void 0){const w=r.lastUsedProvider;w===null||ba(w)&&typeof w.providerID=="string"&&typeof w.modelID=="string"?l=w:n=!0}let d=[];if(r?.clearedVariantKeys!==void 0){const w=r.clearedVariantKeys;Array.isArray(w)&&w.every(_s)?d=[...w]:n=!0}const f=r?.contextStoreMigrationVersion===A0,u=f?{status:"missing",failed:!1,data:xs()}:xI(),h=u.failed,m=new Map(s.value),g=new Map(o.value),x=new Map(Array.from(i.value.entries()).map(([w,M])=>[w,new Map(M)])),b=new Map(Array.from(a.value.entries()).map(([w,M])=>[w,new Map(Array.from(M.entries()).map(([j,T])=>[j,new Map(T)]))])),S=new Set([...d,...t.clearedVariantKeys]);if(u.status==="ok"||u.status==="failed"){const w=u.data;for(const[M,j]of w.models)m.has(M)||m.set(M,j);for(const[M,j]of w.agents)g.has(M)||g.set(M,j);for(const[M,j]of w.currentAgentContext)g.has(M)||g.set(M,j);for(const[M,j]of w.agentModels){let T=x.get(M);T||(T=new Map,x.set(M,T));for(const[A,_]of j)T.has(A)||T.set(A,_)}for(const[M,j]of w.variants)for(const[T,A]of j)for(const[_,k]of A){if(S.has(L0(M,T,_)))continue;let E=b.get(M);E||(E=new Map,b.set(M,E));let I=E.get(T);I||(I=new Map,E.set(T,I)),I.has(_)||I.set(_,k)}}for(const w of to){const M=t.sessionModelSelections.get(w);M&&P0(m,w,M);const j=t.sessionAgentSelections.get(w);j!==void 0&&P0(g,w,j)}for(const w of no){const M=of(w);if(!M)continue;const[j,T]=M,A=t.sessionAgentModelSelections.get(j)?.get(T);if(!A)continue;let _=x.get(j);_||(_=new Map,x.set(j,_)),_.set(T,A),x.delete(j),x.set(j,_)}for(const w of Ir){const M=Tn(w);if(!M)continue;const[j,T,A]=M,_=t.sessionAgentModelVariantSelections.get(j)?.get(T)?.get(A);if(_!==void 0){let k=b.get(j);k||(k=new Map,b.set(j,k));let E=k.get(T);E||(E=new Map,k.set(T,E)),E.set(A,_)}else bI(b,j,T,A)}ep&&t.lastUsedProvider!==null&&(l=t.lastUsedProvider);const y=new Set;for(const w of to)y.add(w);for(const w of no){const M=of(w);M&&y.add(M[0])}for(const w of Ir){const M=Tn(w);M&&y.add(M[0])}const v=os({sessionModelSelections:m,sessionAgentSelections:g,sessionAgentModelSelections:x,sessionAgentModelVariantSelections:b,clearedVariantKeys:Array.from(S),sessionRecency:Kd(r?.sessionRecency)},Array.from(y)),C=f||!n&&!h;return pI(),{...t,sessionModelSelections:v.sessionModelSelections,sessionAgentSelections:v.sessionAgentSelections,sessionAgentModelSelections:v.sessionAgentModelSelections,sessionAgentModelVariantSelections:v.sessionAgentModelVariantSelections,lastUsedProvider:l,hasHydrated:!0,clearedVariantKeys:C?[]:v.clearedVariantKeys,sessionRecency:v.sessionRecency,contextStoreMigrationVersion:C?A0:t.contextStoreMigrationVersion}},migrate:e=>vI(e)}));if(typeof window<"u"){const e=At.persist,t=()=>{At.getState().hasHydrated||At.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const Mm=(e,t)=>`${e}::${t}`,Zo=Lt(e=>({byKey:new Map,setEntry:t=>e(n=>{const r=new Map(n.byKey);return r.set(Mm(t.runtimeKey,t.sessionId),t),{byKey:r}}),clearForSession:t=>e(n=>{const r=new Map(n.byKey);let s=!1;for(const o of r.keys())o.endsWith(`::${t}`)&&(r.delete(o),s=!0);return s?{byKey:r}:n}),clearAll:()=>e({byKey:new Map}),clearForRuntime:t=>e(n=>{const r=`${t}::`,s=new Map(n.byKey);let o=!1;for(const i of s.keys())i.startsWith(r)&&(s.delete(i),o=!0);return o?{byKey:s}:n})}));typeof window<"u"&&en(e=>{e.runtimeKey!==e.previousRuntimeKey&&e.previousRuntimeKey&&Zo.getState().clearForRuntime(e.previousRuntimeKey)});const wI=(e,t,n)=>{const r=Y();Zo.getState().setEntry({sessionId:e,runtimeKey:r,targetEntryId:t.targetEntryId,previousLeafId:t.previousLeafId,newLeafId:t.newLeafId,...t.editorText!==void 0?{editorText:t.editorText}:{},abandoned:n,createdAt:Date.now()})},af=e=>{Zo.getState().clearForSession(e)},cf=()=>{Zo.getState().clearAll()},Im=e=>{const t=Y();return Zo.getState().byKey.get(Mm(t,e))},SI=e=>Zo(t=>{if(e)return t.byKey.get(Mm(Y(),e))}),Em=e=>{const t=["~"],n=r=>{const s=de(r);s&&!t.includes(s)&&t.push(s)};n(e);try{n(Gt().getItem("homeDirectory"))}catch{}try{typeof window<"u"&&n(window.__PICHAMBER_HOME__)}catch{}return t},CI=(e,t)=>{const n=de(e);return!!(n&&Em(t).includes(n))},tp=()=>({byId:new Map,byDirectory:new Map,listStatusByDirectory:new Map}),bs=(e,t,n,r,s)=>{if(e.byId.has(t))return e;const o=qr(n),i=s??Date.now(),a={id:t,directory:o,parentId:null,title:"",archived:!1,createdAt:i,updatedAt:i,lifecycle:r,hydrated:!1},l=new Map(e.byId);l.set(t,a);const d=e.byDirectory.get(o),f=new Map(e.byDirectory);return d&&d.includes(t)?f.set(o,d):d?f.set(o,[t,...d]):f.set(o,[t]),{...e,byId:l,byDirectory:f}},qr=e=>de(e)??e,wa=(e,t)=>e===void 0||t===void 0||e===null||t===null?e===t:e.count===t.count&&e.kind===t.kind&&e.since===t.since,Kb=(e,t)=>e.id===t.id&&e.directory===t.directory&&e.parentId===t.parentId&&e.title===t.title&&e.archived===t.archived&&e.createdAt===t.createdAt&&e.updatedAt===t.updatedAt&&e.preview===t.preview&&e.messageCount===t.messageCount&&e.lifecycle===t.lifecycle&&e.retry===t.retry&&e.hydrated===t.hydrated&&wa(e.pendingInput,t.pendingInput),kI=(e,t,n,r)=>{const s=t.get(n)??[];for(const o of s){if(r.includes(o))continue;const i=e.get(o);i&&i.directory!==n||e.delete(o)}t.set(n,[...r])},MI=(e,t)=>e===t||!!e&&!!t&&e.attempt===t.attempt&&e.next===t.next&&e.message===t.message,II=(e,t,n,r,s)=>{const o=qr(t),i=[];let a=null,l=null;for(const m of n){const g=m?.session;if(!g?.id||!g.directory)continue;const x=qr(g.directory);if(x!==o)continue;const b=typeof g.timeArchived=="number"?g.timeArchived>0:!!g.archived,S=e.byId.get(g.id),y=typeof m.updatedAt=="number"&&Number.isFinite(m.updatedAt)?m.updatedAt:typeof g.updatedAt=="number"&&Number.isFinite(g.updatedAt)?g.updatedAt:r,v=m.live&&s?.acceptLiveObservation?.(g.id,m.live.sequence)?m.live:void 0,C=v?v.lifecycle:S?.lifecycle??"idle",w=v?.lifecycle==="retry"?v.retry??{}:void 0,M=v?MI(S?.retry,w)?S?.retry:w:S?.retry,j=m.inputState&&s?.acceptPendingInputObservation?.(g.id,m.inputState.sequence)?m.inputState.pending:void 0,T=j==null||Rd(j)?j:void 0,A=T!==void 0?T:S?.pendingInput,_={id:g.id,directory:x,parentId:g.parentId??null,title:g.title??"",archived:b,createdAt:g.createdAt,updatedAt:S?S.updatedAt:y,...typeof m.preview=="string"?{preview:m.preview}:{},...typeof g.messageCount=="number"?{messageCount:g.messageCount}:S?.messageCount!==void 0?{messageCount:S.messageCount}:{},lifecycle:C,...M?{retry:M}:{},...A!==void 0?{pendingInput:A}:{},hydrated:S?.hydrated??!1};if(S&&Kb(S,_)){i.push(g.id);continue}a||(a=new Map(e.byId),l=new Map(e.byDirectory)),a.set(g.id,_),i.push(g.id)}const f=e.byDirectory.get(o)??[],u=f.length!==i.length||f.some((m,g)=>m!==i[g]);if(!a&&!u){if(e.listStatusByDirectory.get(o)!=="ready"){const m=new Map(e.listStatusByDirectory);return m.set(o,"ready"),{...e,listStatusByDirectory:m}}return e}a||(a=new Map(e.byId)),l||(l=new Map(e.byDirectory)),kI(a,l,o,i);let h=null;return e.listStatusByDirectory.get(o)!=="ready"&&(h=new Map(e.listStatusByDirectory),h.set(o,"ready")),{byId:a,byDirectory:l,listStatusByDirectory:h??e.listStatusByDirectory}},EI=(e,t)=>{const n=qr(t),r=e.listStatusByDirectory.get(n);if(r==="loading"||r==="ready")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"loading"),{...e,listStatusByDirectory:s}},jI=(e,t)=>{const n=qr(t);if(e.listStatusByDirectory.get(n)==="failed")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"failed"),{...e,listStatusByDirectory:s}},Ks=(e,t,n,r)=>{const s=e.byId.get(t);if(!s)return e;const o=n==="retry"?r:void 0;if(s.lifecycle===n&&s.retry===o)return e;const i=new Map(e.byId);return i.set(t,{...s,lifecycle:n,retry:o}),{...e,byId:i}},lf=(e,t,n)=>{const r=e.byId.get(t);if(!r||r.hydrated===n)return e;const s=new Map(e.byId);return s.set(t,{...r,hydrated:n}),{...e,byId:s}},Tc=(e,t,n,r)=>{const s=e.byId.get(t);if(!s||s.title===n&&s.updatedAt===r)return e;const o=new Map(e.byId);return o.set(t,{...s,title:n,updatedAt:r}),{...e,byId:o}},O0=(e,t,n,r)=>{const s=e.byId.get(t);if(!s){if(!r)return e;const i=bs(e,t,r.directory,r.lifecycle,n),a=i.byId.get(t);if(!a||a.updatedAt===n)return i;const l=new Map(i.byId);return l.set(t,{...a,updatedAt:n}),{...i,byId:l}}if(s.updatedAt>=n&&s.lifecycle===(r?.lifecycle??s.lifecycle))return e;const o=new Map(e.byId);return o.set(t,{...s,updatedAt:Math.max(s.updatedAt,n),...r?.lifecycle?{lifecycle:r.lifecycle}:{}}),{...e,byId:o}},_I=(e,t,n,r)=>{const s=e.byId.get(t);if(!s||s.archived===n&&s.updatedAt===r)return e;const o=new Map(e.byId);return o.set(t,{...s,archived:n,updatedAt:r}),{...e,byId:o}},ta=(e,t,n,r,s,o)=>{if(r!==null&&!Rd(r))return e;const i=e.byId.get(t);if(i){if(wa(i.pendingInput,r))return e;const f=new Map(e.byId);return f.set(t,{...i,pendingInput:r}),{...e,byId:f}}if(r===null)return e;const a=bs(e,t,n,"idle"),l=a.byId.get(t);if(!l||wa(l.pendingInput,r))return a;const d=new Map(a.byId);return d.set(t,{...l,pendingInput:r}),{...a,byId:d}},TI=(e,t,n)=>{const r=n?.streamEpoch??null;if(r!==null&&(typeof t.streamEpoch!="string"||t.streamEpoch!==r))return e;const s=t.sequence;if(!Number.isSafeInteger(s)||s<0)return e;const o=n?.acceptPendingInputObservation??(()=>!0),i=new Set;let a=e;for(const l of t.sessions)!l||typeof l.sessionId!="string"||l.sessionId.length===0||typeof l.directory!="string"||l.directory.length===0||i.has(l.sessionId)||(i.add(l.sessionId),Rd(l.pending)&&o(l.sessionId,s)&&(a=ta(a,l.sessionId,l.directory,l.pending)));for(const[l,d]of a.byId)i.has(l)||d.pendingInput!=null&&o(l,s)&&(a=ta(a,l,d.directory,null));return a},AI=e=>{let t=null;for(const[n,r]of e.byId)r.pendingInput!==void 0&&(t||(t=new Map(e.byId)),t.set(n,{...r,pendingInput:void 0}));return t?{...e,byId:t}:e},NI=[],jm=e=>{const t=[];for(const n of e.byId.values())n.pendingInput!=null&&t.push({sessionId:n.id,directory:n.directory,pending:n.pendingInput});return t.length===0?NI:(t.sort((n,r)=>n.pending.since-r.pending.since||(n.sessionId<r.sessionId?-1:n.sessionId>r.sessionId?1:0)),t)},LI=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.sessionId!==s.sessionId||r.directory!==s.directory||!wa(r.pending,s.pending))return!1}return!0},H0=(e,t)=>{const n=e.byId.get(t.id);if(n&&Kb(n,t))return e;const r=new Map(e.byId);r.set(t.id,t);const s=e.byDirectory.get(t.directory);if(s){const i=s.filter(l=>l!==t.id),a=new Map(e.byDirectory);return a.set(t.directory,[t.id,...i]),{...e,byId:r,byDirectory:a}}const o=new Map(e.byDirectory);return o.set(t.directory,[t.id]),{...e,byId:r,byDirectory:o}},RI=(e,t)=>{const n=e.byId.get(t);if(!n)return e;const r=new Map(e.byId);r.delete(t);const s=e.byDirectory.get(n.directory);let o=null;if(s){const i=s.filter(a=>a!==t);o=new Map(e.byDirectory),i.length===0?o.delete(n.directory):o.set(n.directory,i)}return{byId:r,byDirectory:o??e.byDirectory,listStatusByDirectory:e.listStatusByDirectory}},F0=new WeakMap,Or=e=>{const t=F0.get(e);if(t)return t;const n={id:e.id,directory:e.directory,parentID:e.parentId,title:e.title,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:{},time:{created:e.createdAt,updated:e.updatedAt,...e.archived?{archived:e.updatedAt}:{}}};return F0.set(e,n),n},B0=[],Gb=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},Sa=(e,t)=>{const n=t?.archived??!1,r=t?.directory;let s;if(typeof r=="string"&&r.length>0){const i=qr(r),a=e.byDirectory.get(i)??[],l=Em();if(!l.includes(i))s=a;else{const d=[],f=new Set(a);for(const u of l){if(u===i)continue;const h=e.byDirectory.get(u);if(h)for(const m of h)f.has(m)||(f.add(m),d.push(m))}s=d.length>0?[...a,...d]:a}}else{if(r===null||r==="")return B0;s=[...e.byId.keys()]}const o=[];for(const i of s){const a=e.byId.get(i);a&&!!a.archived===n&&o.push(Or(a))}return o.length===0?B0:o},PI=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n);return t},PY=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n.id);return t.sort(),t.join("|")},df=(e,t,n,r,s,o,i)=>{const a=qr(n),l=[],d=[],f=new Set;for(const O of r){const L=O?.session;!L?.id||!L.directory||qr(L.directory)===a&&(f.has(L.id)||(f.add(L.id),l.push(L.id),d.push(O)))}const u=new Set(l),h=e.byDirectory.get(a)??[],m=t.byDirectory.get(a)??[],g=new Set(h),x=new Set;for(const O of g)t.byId.has(O)||x.add(O);const b=new Map,S=new Map,y=new Map,v=new Map,C=new Set,w=new Set;for(const O of h)w.add(O);for(const O of m)w.add(O);for(const O of l)w.add(O);for(const O of w){const L=t.byId.get(O);if(!L)continue;const D=e.byId.get(O);if(D===L)continue;if(L.directory!==a){D&&(D.directory===a||g.has(O)||u.has(O))&&C.add(O);continue}if(!D){if(u.has(O))continue;b.set(O,L);continue}const W=L.title!==D.title,z=L.archived!==D.archived;if(u.has(O)){(W||z)&&v.set(O,{rec:L,titleChanged:W,archivedChanged:z});continue}W||z?S.set(O,L):y.set(O,L)}const M=d.filter(O=>{const L=O.session.id;return!(x.has(L)||o?.has(L)||C.has(L))}),j=II(t,a,M,s,i);let T=null;for(const[O,L]of v){const D=j.byId.get(O);if(!D){S.set(O,L.rec);continue}const W=L.titleChanged?L.rec.title:D.title,z=L.archivedChanged?L.rec.archived:D.archived;(D.title!==W||D.archived!==z)&&(T||(T=new Map(j.byId)),T.set(O,{...D,title:W,archived:z}))}if(b.size===0&&S.size===0&&y.size===0&&!T)return j;const A=T??j.byId,_=j.byDirectory.get(a)??[],k=new Set(_),E=new Map([...b,...S,...y]),I=[];for(const O of m)E.has(O)&&!k.has(O)&&I.push(O);let N=null;if(I.length>0){N=new Map(j.byDirectory),N.set(a,[...I,..._]),T||(T=new Map(A));for(const O of I){const L=E.get(O);L&&T.set(O,L)}}return!T&&!N?j:{byId:T??j.byId,byDirectory:N??j.byDirectory,listStatusByDirectory:j.listStatusByDirectory}},DI=2,OI=(e,t)=>Mh([...e],DI,async n=>t(n)),V0="*",Ct="catalog",Ac="dialogs",Pt="chrome",uf=16,$0=2,HI=5,FI=300,BI=new Set(["DAEMON_UNAVAILABLE","DAEMON_TIMEOUT","DAEMON_START_TIMEOUT","DAEMON_SPAWN_FAILED","DAEMON_REQUEST_FAILED"]),Nc=e=>e==="busy"||e==="retry"?e:e==="error"?"error":"idle",Zb=e=>{if(e.name==="session.lifecycle"){const t=e.payload&&typeof e.payload=="object"?e.payload.state:void 0;return t==="busy"||t==="retry"||t==="error"?t:t==="idle"?"idle":void 0}if(e.name==="assistant.message.start")return"busy";if(e.name==="session.error")return"error"},In=e=>e instanceof lt?e:new lt("DAEMON_REQUEST_FAILED",e instanceof Error?e.message:void 0),fi=e=>e instanceof lt&&e.code==="INVALID_SESSION",ff=e=>e instanceof lt&&e.code==="SESSION_IN_USE",VI=e=>e instanceof lt&&e.code==="SESSION_RUNTIME_CONFLICT",z0=async()=>{await new Promise(e=>setTimeout(e,FI))},Lc=(e=tp())=>({directory:null,sessions:[],selectedSessionId:null,reducer:Ul(),connection:"loading",error:null,showArchived:!1,hydratedSessionIds:new Set,sessionLoadErrorById:new Map,focusPending:!1,sessionsListStatus:"idle",catalog:e,syncReadiness:"ready",syncRecovery:{directories:[],residents:[]}}),$I=(e,t,n)=>{const r=n?.now??Date.now(),s=t.byId.get(e.id),o=de(e.directory)??e.directory,i=typeof e.timeArchived=="number"?e.timeArchived>0:!!e.archived;return{id:e.id,directory:o,parentId:e.parentId??null,title:e.title??"",archived:i,createdAt:e.createdAt,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:r,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:s?.messageCount!==void 0?{messageCount:s.messageCount}:{},lifecycle:s?.lifecycle??"idle",hydrated:s?.hydrated??!1,...s?.pendingInput!==void 0?{pendingInput:s.pendingInput}:{}}},U0=(e,t,n,r)=>{if(typeof r!="number"||!Number.isSafeInteger(r)||r<0)return e;const s=e.byId.get(t);if(s){if(s.messageCount===r)return e;const l=new Map(e.byId);return l.set(t,{...s,messageCount:r}),{...e,byId:l}}const o=bs(e,t,n,"idle"),i=o.byId.get(t);if(!i||i.messageCount===r)return o;const a=new Map(o.byId);return a.set(t,{...i,messageCount:r}),{...o,byId:a}},zI=(e,t,n={})=>{if(!t||t.sessionId!==e.sessionId)return e;const r=e.lifecycle!=="busy"&&e.lifecycle!=="retry"&&e.streamingMessages.size===0&&e.lastSequence>=t.lastSequence&&n.localSendPending!==!0,o=(t.lifecycle==="busy"||t.lifecycle==="retry")&&!r||t.lastSequence>e.lastSequence,i=t.lastSequence>e.lastSequence,a=e.hasMoreBefore===!0&&t.messages.size>0,l={extensionNotices:t.extensionNotices,extensionErrors:t.extensionErrors,extensionCatalogRevision:t.extensionCatalogRevision,sessionTreeRevision:t.sessionTreeRevision,extensionEditor:t.extensionEditor,extensionEditorOps:t.extensionEditorOps,...t.awaitingPromptEcho!==void 0?{awaitingPromptEcho:t.awaitingPromptEcho}:{}};if(t.messages.size===0&&!o)return{...e,...l};const d={...e,...a&&t.hasMoreBefore!==void 0?{hasMoreBefore:t.hasMoreBefore,beforeCursor:t.beforeCursor}:{},lifecycle:o?t.lifecycle:e.lifecycle,lastSequence:Math.max(e.lastSequence,t.lastSequence),messages:new Map(e.messages),partOrder:new Map(e.partOrder),parts:zl(e.parts),toolsByCallId:new Map(e.toolsByCallId),streamingMessages:new Set(o?t.streamingMessages:e.streamingMessages),queue:t.queue.steering>0||t.queue.followUp>0?t.queue:e.queue,...t.model&&(o||!e.model)?{model:t.model}:{},...t.thinking&&(o||!e.thinking)?{thinking:t.thinking}:{},...i?{extensionStatuses:t.extensionStatuses,extensionWidgets:t.extensionWidgets,extensionDialogs:t.extensionDialogs,extensionPanels:t.extensionPanels,extensionApps:t.extensionApps,extensionTitle:t.extensionTitle,...t.extensionWorking?{extensionWorking:t.extensionWorking}:{},...t.extensionDraftTracked?{extensionDraftTracked:!0}:{},extensionSurfaces:t.extensionSurfaces,bashExecutions:t.bashExecutions}:{},...l},f=o?t.runningCommand:e.runningCommand;if(f?d.runningCommand=f:delete d.runningCommand,o||a){for(const[u,h]of t.messages)(o||!d.messages.has(u))&&b8(d,u,h);for(const[u,h]of t.partOrder)if(!(!o&&d.partOrder.has(u))){d.partOrder.set(u,h);for(const m of h){const g=t.parts.get(m);g&&d.parts.set(m,g)}}for(const[u,h]of t.toolsByCallId)(o||!d.toolsByCallId.has(u))&&d.toolsByCallId.set(u,h)}return d};let q0=null;const UI=new Set(["session.snapshot","session.interrupted","session.deleted"]),W0=e=>Zb(e)!==void 0||UI.has(e.name),hi=e=>e.inputState?{pending:e.inputState.pending,sequence:e.lastSequence}:void 0,Ue=()=>(q0??=new _m,q0),DY=e=>Ue().subscribeOpenRequests(e),qI=e=>Ue().subscribePendingInputTransitions(e);class _m{state;listenersByTopic=new Map;stream=null;streamGeneration=0;streamReadyRevision=0;runtimeGeneration=0;focusGeneration=0;recovering=!1;pendingFocus=null;pendingPreferredSessionId=null;selectionRevision=0;userSelection=null;newerSelection(t,n){const r=this.userSelection;return r&&r.revision>t&&(!r.directory||de(r.directory)===de(n))?r.id:null}hydratedSessionIds=new Set;activityPhaseById=new Map;pendingPromptById=new Set;promptGenerationById=new Map;acceptedPromptGenerationById=new Map;acceptedPromptReconcileInFlight=new Map;lastAccessById=new Map;lastAccessClock=0;lastSelectedByDirectory=new Map;directoryRefreshGenerationByDirectory=new Map;pendingCatalogPassByKey=new Map;deletedSessionIds=new Set;static MAX_DELETED_SESSION_TOMBSTONES=4096;isDeleted=t=>this.deletedSessionIds.has(t);deletedSessionCountForTests=()=>this.deletedSessionIds.size;providerRefreshRevisionByDirectory=new Map;providerRefreshTaskByDirectory=new Map;evictionScheduled=!1;restoringTranscriptById=new Set;hydrateInflightById=new Map;transcriptPrefetch=null;historyInflightById=new Map;navigationGenerationById=new Map;navigationCounter=0;streamEpoch=null;lifecycleSequenceById=new Map;pendingInputSequenceById=new Map;pendingInputUnsupported=!1;pendingInputFetchInFlight=null;pendingInputRefetchRequested=!1;pendingMetadataBackfillAttempted=new Set;retiredStreamEpochs=new Set;recoveryDirectories=new Set;recoveryResidents=new Set;recoveryRunning=!1;recoveryRevision=0;recoveryAttempt=0;recoveryTimer=null;adoptStreamEpoch(t){return typeof t!="string"||t.length===0||this.streamEpoch===t?!1:(this.streamEpoch!==null&&this.retiredStreamEpochs.add(this.streamEpoch),this.streamEpoch=t,!0)}isResponseEpochCurrent(t){const n=typeof t?.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:void 0;return n?this.retiredStreamEpochs.has(n)?!1:this.streamEpoch===null?(this.streamEpoch=n,!0):n===this.streamEpoch:this.streamEpoch===null}createListLiveGate(t,{streamAttaching:n=!1}={}){const r=typeof t.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:null;if(!r||r!==this.streamEpoch)return{options:void 0,commit:()=>{}};if(!this.stream&&!n)return{options:void 0,commit:()=>{}};const s=new Set,o=new Set;return{options:{acceptLiveObservation:(l,d)=>{if(!Number.isSafeInteger(d)||d<0)return!1;const f=Math.max(this.lifecycleSequenceById.get(l)??-1,this.hydratedSessionIds.has(l)?this.state.reducer.lastSequence.get(l)??-1:-1);if(d<f)return!1;if(this.pendingPromptById.has(l)){const u=this.promptGenerationById.get(l);return u!==void 0&&this.acceptedPromptGenerationById.get(l)===u&&o.add(l),!1}return s.add(l),!0}},commit:l=>{if(r===this.streamEpoch){for(const d of l)d.live?.lifecycle==="idle"&&o.has(d.session.id)&&this.reconcileAcceptedPromptFromList(d.session.id);if(s.size!==0)for(const d of l){const f=d.live;if(!f||!s.has(d.session.id))continue;const u=d.session.id;(this.lifecycleSequenceById.get(u)??-1)<f.sequence&&this.lifecycleSequenceById.set(u,f.sequence),!(f.lifecycle==="idle"||typeof f.runStartedAt!="number")&&this.state.catalog.byId.get(u)?.lifecycle===f.lifecycle&&Mn(u,f.runStartedAt,f.serverNow)}}}}}createListPendingInputGate(t,{streamAttaching:n=!1}={}){const r=typeof t.streamEpoch=="string"&&t.streamEpoch.length>0?t.streamEpoch:null;if(!r||r!==this.streamEpoch)return{options:void 0,commit:()=>{}};if(!this.stream&&!n)return{options:void 0,commit:()=>{}};const s=new Map;return{options:{acceptPendingInputObservation:(a,l)=>{if(!Number.isSafeInteger(l)||l<0||l<(this.pendingInputSequenceById.get(a)??-1))return!1;const d=s.get(a);return(d===void 0||l>d)&&s.set(a,l),!0}},commit:a=>{if(r!==this.streamEpoch||s.size===0)return;const l=new Map;for(const d of a)d.inputState&&s.has(d.session.id)&&l.set(d.session.id,d.inputState.sequence);for(const[d,f]of s){const u=l.get(d)??f;(this.pendingInputSequenceById.get(d)??-1)<u&&this.pendingInputSequenceById.set(d,u)}}}}createDirectoryListGates(t,{streamAttaching:n=!1}={}){const r=this.createListLiveGate(t,{streamAttaching:n}),s=this.createListPendingInputGate(t,{streamAttaching:n});return{options:r.options||s.options?{...r.options,...s.options}:void 0,commit:a=>{r.commit(a),s.commit(a)}}}applyVerifiedEpochChange(t){const n=this.streamEpoch!==null&&this.streamEpoch!==t;if(!this.adoptStreamEpoch(t)||!n)return null;const r=this.resetForEpochChange();return this.state={...this.state,reducer:Ul(),hydratedSessionIds:new Set(this.hydratedSessionIds)},this.queueSyncRecovery({directories:"all-known",residents:r}),r}handleVerifiedEpochChange(t){const n=this.applyVerifiedEpochChange(t);n&&this.emit([Pt,Ct,...[...n].map(r=>`session:${r}`)])}resetForEpochChange(){const t=new Set(this.hydratedSessionIds),n=[];for(const s of this.state.catalog.byId.values())s.pendingInput!=null&&n.push({type:"cleared",sessionId:s.id,directory:s.directory,pending:null});for(const[s,o]of this.openedPendingInputById)this.state.catalog.byId.has(s)||n.push({type:"cleared",sessionId:s,directory:o,pending:null});this.lifecycleSequenceById.clear(),this.pendingInputSequenceById.clear(),this.pendingInputUnsupported=!1,this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested=!1,this.pendingMetadataBackfillAttempted.clear(),this.hydratedSessionIds.clear(),this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch();for(const[s,o]of this.navigationGenerationById)this.navigationGenerationById.set(s,o+1);this.settleCarriedOverActivity();const r=AI(this.state.catalog);return r!==this.state.catalog&&(this.state={...this.state,catalog:r}),this.emitPendingInputTransitions(n),t}settleCarriedOverActivity(){let t=this.state.catalog;for(const n of t.byId.values())n.lifecycle!=="busy"&&n.lifecycle!=="retry"||this.pendingPromptById.has(n.id)||(t=Ks(t,n.id,"idle"),y0(n.id));t!==this.state.catalog&&(this.state={...this.state,catalog:t})}queueSyncRecovery(t){this.refreshPendingInputList();let n=!1,r=!1;if(t.directories==="all-known")for(const s of this.state.catalog.listStatusByDirectory.keys())s&&(n=!0,this.recoveryDirectories.has(s)||(this.recoveryDirectories.add(s),r=!0));else if(t.directories)for(const s of t.directories){const o=de(s);o&&(n=!0,this.recoveryDirectories.has(o)||(this.recoveryDirectories.add(o),r=!0))}if(t.residents)for(const s of t.residents)s&&(n=!0,this.recoveryResidents.has(s)||(this.recoveryResidents.add(s),r=!0));n&&(this.recoveryRevision+=1,this.recoveryAttempt=0,this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,r&&this.publishSyncRecoveryState(),this.runSyncRecovery())}publishSyncRecoveryState(){const t=[...this.recoveryDirectories],n=[...this.recoveryResidents],r=t.length===0&&n.length===0?"ready":"recovering",s=this.state.syncRecovery;r===this.state.syncReadiness&&s.directories.length===t.length&&s.residents.length===n.length&&t.every((i,a)=>s.directories[a]===i)&&n.every((i,a)=>s.residents[a]===i)||(this.state={...this.state,syncReadiness:r,syncRecovery:{directories:t,residents:n}},this.emitChrome())}clearSyncRecovery(){this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=null,this.recoveryDirectories.clear(),this.recoveryResidents.clear(),this.recoveryRunning=!1,this.recoveryRevision+=1,this.recoveryAttempt=0,this.publishSyncRecoveryState()}async runSyncRecovery(){if(this.recoveryRunning)return;if(this.recoveryDirectories.size===0&&this.recoveryResidents.size===0){this.publishSyncRecoveryState();return}this.recoveryRunning=!0;const t=this.runtimeGeneration,n=Y(),r=this.streamEpoch,s=this.recoveryRevision,o=()=>t===this.runtimeGeneration&&n===Y()&&r===this.streamEpoch&&s===this.recoveryRevision;try{const i=this.state.selectedSessionId,a=[...this.recoveryResidents].sort((f,u)=>f===i?-1:u===i?1:0);if(await Mh(a,$0,async f=>{if(!o()||!this.recoveryResidents.has(f))return;if(this.isDeleted(f)){this.recoveryResidents.delete(f);return}const u=this.resolveSessionDirectory(f)??this.state.directory??void 0;if(u){try{const h=await Ee.getSession(f,{directory:u,runtimeKey:n});if(!o()||h.session.id!==f)return;if(this.isDeleted(f)){this.recoveryResidents.delete(f);return}if(!this.isResponseEpochCurrent(h)||!o())return;const m=this.state.reducer.bySession.get(f);(!m||m.lastSequence<=h.lastSequence)&&((h.lifecycle==="busy"||h.lifecycle==="retry")&&typeof h.runStartedAt=="number"&&Mn(h.session.id,h.runStartedAt,h.serverNow),this.commitSessionDetail(h)),this.recoveryResidents.delete(f)}catch(h){o()&&fi(h)&&(this.commitDeletion(f,u),this.recoveryResidents.delete(f))}this.publishSyncRecoveryState()}}),!o())return;const l=this.state.directory?de(this.state.directory):null,d=[...this.recoveryDirectories].sort((f,u)=>f===l?-1:u===l?1:0);await Mh(d,$0,async f=>{if(o()&&this.recoveryDirectories.has(f)){try{(await this.refreshDirectoryCatalog(f)).ok&&o()&&this.recoveryDirectories.delete(f)}catch{}this.publishSyncRecoveryState()}})}finally{this.recoveryRunning=!1,t===this.runtimeGeneration&&n===Y()&&(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(s!==this.recoveryRevision||r!==this.streamEpoch)&&this.runSyncRecovery()}if(!(t!==this.runtimeGeneration||n!==Y())&&(this.publishSyncRecoveryState(),this.recoveryDirectories.size>0||this.recoveryResidents.size>0)){if(s!==this.recoveryRevision||r!==this.streamEpoch){this.runSyncRecovery();return}if(this.recoveryAttempt+=1,this.recoveryAttempt<=HI){const i=Math.min(16e3,1e3*2**(this.recoveryAttempt-1));this.recoveryTimer&&clearTimeout(this.recoveryTimer),this.recoveryTimer=setTimeout(()=>{this.recoveryTimer=null,this.runSyncRecovery()},i)}}}commitMissedDeletion=(t,n)=>this.commitDeletion(t,n);commitDeletion(t,n){if(!t)return!1;const r=this.deletedSessionIds.has(t);this.deletedSessionIds.add(t);let s;this.deletedSessionIds.size>_m.MAX_DELETED_SESSION_TOMBSTONES&&(s=this.deletedSessionIds.values().next().value,s&&this.deletedSessionIds.delete(s));const o=n??this.state.catalog.byId.get(t)?.directory??this.state.sessions.find(C=>C.session.id===t)?.session.directory??this.state.reducer.bySession.get(t)?.directory;if(o&&o!=="global")try{oI({runtimeKey:Y(),directory:o,sessionId:t})}catch{}try{At.getState().forgetSession(t)}catch{}y0(t),cM(t),af(t),this.navigationGenerationById.delete(t),this.pendingInputSequenceById.delete(t),this.historyInflightById.delete(t),this.hydrateInflightById.delete(t),this.restoringTranscriptById.delete(t);const i=this.state.reducer.bySession.has(t)||this.hydratedSessionIds.has(t)||this.state.catalog.byId.has(t)||this.state.sessions.some(C=>C.session.id===t),a=this.state.catalog.byId.get(t)?.pendingInput??null,l=this.state.catalog.byId.get(t)?.directory??n??"",d=this.state.sessions.filter(C=>C.session.id!==t),f=this.state.selectedSessionId===t?d.find(C=>!C.session.archived)?.session.id??null:this.state.selectedSessionId,u=new Map(this.state.reducer.bySession);u.delete(t);const h=new Map(this.state.reducer.lastSequence);s&&h.delete(s);const m=this.state.reducer.lastSequence.get(t);m!==void 0?h.set(t,m):h.delete(t),this.hydratedSessionIds.delete(t),this.activityPhaseById.delete(t),this.pendingPromptById.delete(t),this.promptGenerationById.delete(t),this.acceptedPromptGenerationById.delete(t),this.lastAccessById.delete(t);const g=RI(this.state.catalog,t),x=g!==this.state.catalog,b=f!==this.state.selectedSessionId;let S=this.state.sessionLoadErrorById;if(S.has(t)){const C=new Map(S);C.delete(t),S=C}const y=S!==this.state.sessionLoadErrorById;if(!i&&r&&!x&&!b&&!y)return!1;this.state={...this.state,sessions:d,selectedSessionId:f,hydratedSessionIds:new Set(this.hydratedSessionIds),reducer:{bySession:u,lastSequence:h},catalog:g,sessionLoadErrorById:S};const v=[`session:${t}`,Pt];return x&&v.push(Ct),this.emit(v),a!=null&&this.emitPendingInputTransitions([{type:"cleared",sessionId:t,directory:l,pending:null}]),!0}handleInvalidSession(t,n,r,s=[]){if(!t||r!==this.runtimeGeneration)return;const o=this.state.selectedSessionId===t;if(this.commitDeletion(t,n),s.length>0&&this.commitEvents(s),r!==this.runtimeGeneration||!o)return;const i=this.state.selectedSessionId,a=i&&!this.hydratedSessionIds.has(i);!!a!==this.state.focusPending&&(this.state={...this.state,focusPending:!!a},this.emitChrome()),i&&!this.hydratedSessionIds.has(i)&&this.hydrate(i,this.runtimeGeneration)}filterDeletedListItems(t){return this.deletedSessionIds.size===0?t:t.filter(n=>!this.deletedSessionIds.has(n.session.id))}cadence=new E6(t=>this.commitEvents(t));catalogCache;unsubscribeRuntime;constructor(t=q6()){this.catalogCache=t,this.state=Lc(this.readCachedCatalog(Y())),this.unsubscribeRuntime=en(n=>{if(n.runtimeKey===n.previousRuntimeKey){this.reconnectAfterTransportSwitch();return}this.resetForRuntime()})}getRuntimeGeneration=()=>this.runtimeGeneration;getFocusGeneration=()=>this.focusGeneration;hasClusterAttached=()=>this.stream!==null||this.state.connection==="ready";getState=()=>this.state;subscribe=(t,n=V0)=>{let r=this.listenersByTopic.get(n);return r||(r=new Set,this.listenersByTopic.set(n,r)),r.add(t),()=>{const s=this.listenersByTopic.get(n);s&&s.delete(t)}};pendingInputTransitionListeners=new Set;extensionSurfaceDismissListeners=new Set;subscribeExtensionSurfaceDismissals=t=>(this.extensionSurfaceDismissListeners.add(t),()=>{this.extensionSurfaceDismissListeners.delete(t)});openedPendingInputById=new Map;subscribePendingInputTransitions=t=>(this.pendingInputTransitionListeners.add(t),()=>{this.pendingInputTransitionListeners.delete(t)});openRequestListeners=new Set;subscribeOpenRequests=t=>(this.openRequestListeners.add(t),()=>{this.openRequestListeners.delete(t)});emitOpenRequest(t){for(const n of[...this.openRequestListeners])try{n(t)}catch(r){console.error("[pi-session-store] open-request listener failed",r)}}emitPendingInputTransitions(t){for(const n of t)n.type==="opened"?this.openedPendingInputById.set(n.sessionId,n.directory):this.openedPendingInputById.delete(n.sessionId);if(!(t.length===0||this.pendingInputTransitionListeners.size===0))for(const n of[...this.pendingInputTransitionListeners])for(const r of t)try{n(r)}catch(s){console.error("[pi-session-store] pending-input listener failed",s)}}resetLiveRuntimeState(){this.providerRefreshRevisionByDirectory.clear(),this.deletedSessionIds.clear(),this.runtimeGeneration+=1,this.focusGeneration+=1,this.pendingFocus=null,this.pendingPreferredSessionId=null,this.userSelection=null,this.hydratedSessionIds.clear(),this.activityPhaseById.clear(),this.pendingPromptById.clear(),this.promptGenerationById.clear(),this.acceptedPromptGenerationById.clear(),this.lastAccessById.clear(),this.lastAccessClock=0,this.lastSelectedByDirectory.clear(),this.directoryRefreshGenerationByDirectory.clear(),this.streamEpoch=null,this.retiredStreamEpochs.clear(),this.lifecycleSequenceById.clear(),this.pendingInputSequenceById.clear(),this.openedPendingInputById.clear(),this.pendingInputUnsupported=!1,this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested=!1,this.pendingMetadataBackfillAttempted.clear(),this.clearSyncRecovery(),this.evictionScheduled=!1,this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch(),this.cadence.dispose(),this.stream?.dispose(),this.stream=null,this.streamGeneration+=1,this.streamReadyRevision+=1}raiseOrderingBaselinesForDirectory(t){const n=de(t);if(!n)return;const r=this.state.catalog.byDirectory.get(n);if(!r||r.length===0)return;const s=[];for(const o of r){const i=this.state.catalog.byId.get(o);!i||i.archived||s.push(Or(i))}s.length>0&&dM(s)}recordClusterConnectionChange(t,n){this.state.connection!==t&&Nr("pi-connection",{code:t,detail:(t==="error"||t==="unavailable")&&n?n.code:void 0})}dispose=()=>{this.catalogCache.flush(),this.resetLiveRuntimeState(),this.unsubscribeRuntime(),cf(),this.navigationGenerationById.clear(),this.navigationCounter=0;const t=Lc();this.recordClusterConnectionChange(t.connection),this.state=t,this.emitBroadcast(),this.listenersByTopic.clear()};setShowArchived=t=>{t!==this.state.showArchived&&(this.state={...this.state,showArchived:t},this.emitChrome())};clearError=()=>{this.state.error&&(this.state={...this.state,error:null},this.emitChrome())};reportError=t=>{const n=In(t);this.recordClusterConnectionChange("error",n),this.state={...this.state,error:n,connection:"error"},this.emitChrome(),this.ensureConnectionRecovery(n)};ensureConnectionRecovery(t){if(this.stream||!BI.has(t.code))return;const n=this.runtimeGeneration,r=Y(),s=this.streamGeneration+1;this.streamGeneration=s;const o=this.streamCursor();let i=null;i=Bl({onEvent:()=>{},onAuthRequired:()=>this.handleStreamAuthRequired(),onReconnect:()=>{if(n!==this.runtimeGeneration||r!==Y()||s!==this.streamGeneration||this.stream!==i)return;i?.dispose(),this.stream=null,this.streamGeneration+=1,this.streamReadyRevision+=1;const{directory:a,selectedSessionId:l}=this.state;this.start({...a?{directory:a}:{},...l?{sessionId:l}:{}})}},{...o!==void 0?{fromSequence:o}:{},runtimeKey:r}),this.stream=i}handleStreamAuthRequired(){this.reportError(new lt("DAEMON_AUTH_FAILED","The Pi runtime rejected the client authorization.")),Y9()}failSessionLoad(t,n){const r=new Map(this.state.sessionLoadErrorById);r.set(t,n);const s=this.state.selectedSessionId===t;this.state={...this.state,sessionLoadErrorById:r,focusPending:s?!1:this.state.focusPending},this.emitChrome()}clearSessionLoadError(t){if(!this.state.sessionLoadErrorById.has(t))return;const n=new Map(this.state.sessionLoadErrorById);n.delete(t),this.state={...this.state,sessionLoadErrorById:n},this.emitChrome()}clear=()=>{this.resetLiveRuntimeState(),this.recordClusterConnectionChange("ready"),this.state={...Lc(),connection:"ready"},cf(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()};acceptPendingInputSequence(t,n){return!Number.isSafeInteger(n)||n<0||n<(this.pendingInputSequenceById.get(t)??-1)?!1:(this.pendingInputSequenceById.set(t,n),!0)}applyPendingInputList(t){if(!this.isResponseEpochCurrent(t))return;const n=TI(this.state.catalog,t,{acceptPendingInputObservation:(r,s)=>this.acceptPendingInputSequence(r,s),streamEpoch:this.streamEpoch});n!==this.state.catalog&&(this.state={...this.state,catalog:n},this.emit([Ct])),this.requestNeedingSessionMetadataBackfill(t.sessions.map(r=>r.sessionId))}requestNeedingSessionMetadataBackfill(t){for(const n of t){if(!n||this.pendingMetadataBackfillAttempted.has(n))continue;const r=this.state.catalog.byId.get(n);!r||r.pendingInput==null||r.title.trim()||typeof r.messageCount!="number"&&(this.hydratedSessionIds.has(n)||this.hydrateInflightById.has(n)||this.isDeleted(n)||(this.pendingMetadataBackfillAttempted.add(n),this.ensureHydrated(n).then(()=>{this.hydratedSessionIds.has(n)||this.pendingMetadataBackfillAttempted.delete(n)},()=>{this.pendingMetadataBackfillAttempted.delete(n)})))}}refreshPendingInputList(){if(this.pendingInputUnsupported)return;if(this.pendingInputFetchInFlight){this.pendingInputRefetchRequested=!0;return}if(this.streamEpoch===null)return;const t=this.runtimeGeneration,n=Y(),r=Ee.listPendingInput({runtimeKey:n}).then(s=>{t!==this.runtimeGeneration||n!==Y()||this.applyPendingInputList(s)},s=>{t!==this.runtimeGeneration||n!==Y()||s instanceof lt&&s.status===404&&(this.pendingInputUnsupported=!0)}).finally(()=>{this.pendingInputFetchInFlight===r&&(this.pendingInputFetchInFlight=null,this.pendingInputRefetchRequested&&(this.pendingInputRefetchRequested=!1,this.refreshPendingInputList()))});this.pendingInputFetchInFlight=r}adoptDetailPendingInput(t,n,r,s,o){return!s||!this.acceptPendingInputSequence(n,o)?t:ta(t,n,r,s.pending)}async refreshDirectoryCatalog(t){const n=de(t);if(!n)return{ok:!1,error:In(new lt("INVALID_ARGUMENT","directory is required"))};const r=Y(),s=(this.directoryRefreshGenerationByDirectory.get(n)??0)+1;this.directoryRefreshGenerationByDirectory.set(n,s);const o=this.runtimeGeneration,i=this.state.catalog,a=EI(this.state.catalog,n);a!==this.state.catalog&&(this.state={...this.state,catalog:a},this.emit([Ct]));try{const l=await Ee.listSessions({directory:n,runtimeKey:r});if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==Y())return{ok:!0};if(!this.isResponseEpochCurrent(l))throw new lt("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const d=this.filterDeletedListItems(l.sessions),f=this.createDirectoryListGates(l),u=df(i,this.state.catalog,n,d,Date.now(),this.deletedSessionIds,f.options);return u!==this.state.catalog?(this.state={...this.state,catalog:u},f.commit(d),this.emit([Ct]),this.raiseOrderingBaselinesForDirectory(n)):f.commit(d),{ok:!0}}catch(l){if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==Y())return{ok:!0};const d=In(l),f=jI(this.state.catalog,n),u=de(this.state.directory)===n,h=[];return f!==this.state.catalog&&(this.state={...this.state,catalog:f},h.push(Ct)),u&&(this.state={...this.state,error:d},h.push(Pt)),h.length>0&&this.emit(h),{ok:!1,error:d}}}async refreshAllDirectoryCatalogs(t){const n=[...new Set(t)].map(d=>de(d)).filter(d=>!!d);if(n.length===0)return;const r=this.runtimeGeneration,s=[],o=[],i=new Map,a=new Map;for(const d of n){const f=`${r}\0${d}`,u=this.pendingCatalogPassByKey.get(f);if(u){s.push(u);continue}o.push(d);const h=new Promise(m=>i.set(d,m));a.set(d,h),this.pendingCatalogPassByKey.set(f,h)}const l=OI(o,async d=>{const f=`${r}\0${d}`;try{return await this.refreshDirectoryCatalog(d)}finally{this.pendingCatalogPassByKey.get(f)===a.get(d)&&this.pendingCatalogPassByKey.delete(f),i.get(d)?.()}});try{await Promise.all([l,...s])}finally{for(const d of o){const f=`${r}\0${d}`;this.pendingCatalogPassByKey.get(f)===a.get(d)&&this.pendingCatalogPassByKey.delete(f),i.get(d)?.()}}}async start(t={}){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){await this.focusProject(t.directory??null,t.sessionId??null);return}try{const n=typeof t.directory=="string"&&t.directory.trim()?t.directory:null,r=!!(t.sessionId&&t.sessionDirectoryKnown===!1);if(n&&!r){await this.open(n,t.sessionId);return}if(t.sessionId&&(!t.sessionDirectoryKnown||r))try{const a=await Ee.getSession(t.sessionId,{...r?{}:{directory:n??void 0},runtimeKey:Y()});if(a?.session?.directory){await this.open(a.session.directory,t.sessionId);return}}catch{}const s=r?void 0:t.sessionId;if(n){await this.open(n,s);return}const o=await Ee.listProjects({runtimeKey:Y()}),i=o.projects.find(a=>a.selected)?.directory??o.projects[0]?.directory;if(!i){await this.connectWithoutProject();return}await this.open(i,s)}catch(n){this.reportError(n)}}async connectWithoutProject(){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){await this.focusProject(null,null);return}const t=++this.runtimeGeneration;this.focusGeneration=t,this.pendingFocus=null,this.pendingPreferredSessionId=null,this.clearTranscriptPrefetch(),this.recordClusterConnectionChange("loading"),this.state={...this.state,directory:null,sessions:[],selectedSessionId:null,connection:"loading",sessionsListStatus:"idle",focusPending:!1,error:null},this.emitChrome();try{const n=await Ee.health({runtimeKey:Y()});if(t!==this.runtimeGeneration)return;if(n.state!=="ready")throw new lt(n.error?.code??"DAEMON_UNAVAILABLE",n.error?.message);const r=n.streamEpoch;typeof r=="string"&&r.length>0&&this.streamEpoch!==null&&r!==this.streamEpoch?this.applyVerifiedEpochChange(r):this.adoptStreamEpoch(r),this.recordClusterConnectionChange("ready"),this.state={...this.state,directory:null,sessions:[],selectedSessionId:null,connection:"ready",sessionsListStatus:"idle",focusPending:!1,error:null},this.attachClusterStream(t,Y()),this.emit([Pt,Ct]),this.refreshPendingInputList()}catch(n){t===this.runtimeGeneration&&this.reportError(n)}}attachClusterStream(t,n){if(this.stream||t!==this.runtimeGeneration)return;const r=this.streamGeneration+1;this.streamGeneration=r;const s=()=>t===this.runtimeGeneration&&n===Y()&&r===this.streamGeneration,o=this.streamEpoch?this.streamCursor():void 0;this.stream=Bl({onEvent:i=>{s()&&this.apply(i)},onReconnect:()=>this.markStreamReconnected(t,n,r),onEpochChange:i=>{s()&&this.handleVerifiedEpochChange(i)},onAuthRequired:()=>{s()&&this.handleStreamAuthRequired()}},{...this.streamEpoch?{streamEpoch:this.streamEpoch}:{},...o!==void 0?{fromSequence:o}:{},runtimeKey:n})}async focusProject(t,n){const r=typeof t=="string"&&t.trim()?t.trim():null,s=de(r)===de(this.state.directory),o=n??null;if(s){if(!o||o===this.state.selectedSessionId)return;await this.select(o);return}if(!r){this.state={...this.state,directory:null,sessions:[],sessionsListStatus:"idle",focusPending:!1,error:null},this.emitChrome();return}const i=++this.focusGeneration,a=this.selectionRevision;this.pendingFocus={directory:r,expected:i,preferredSessionId:o},this.pendingPreferredSessionId=o,this.clearTranscriptPrefetch();const l=!!o&&this.hydratedSessionIds.has(o);this.state={...this.state,directory:r,sessions:[],selectedSessionId:l?o:o??null,sessionsListStatus:"loading",focusPending:!l,error:null},this.emitChrome(),l&&this.touchLastAccess(o),await this.resolveFocus(i,r,a)}async resolveFocus(t,n,r){const s=Y(),o=this.runtimeGeneration,i=this.state.catalog;let a=this.pendingPreferredSessionId,l=n;try{try{const v=await Ee.selectProject(n,{runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;l=v.directory,de(l)!==de(this.state.directory)&&(this.state={...this.state,directory:l},this.emitChrome())}catch(v){if(!this.shouldRetryFocusError(v))throw v;if(await z0(),t!==this.focusGeneration||o!==this.runtimeGeneration)return;l=(await Ee.selectProject(n,{runtimeKey:s})).directory,de(l)!==de(this.state.directory)&&(this.state={...this.state,directory:l},this.emitChrome())}const d=await this.fetchFocusListWithRetry(l,t,o,s);if(d.kind==="stale")return;if(d.kind==="failed"){this.failFocus(t,d.error);return}const f={sessions:this.filterDeletedListItems(d.payload.sessions)};if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;a=this.newerSelection(r,l)??a;let u=a?f.sessions.find(v=>v.session.id===a):void 0;if(a&&!u&&!this.isDeleted(a))try{const v=await Ee.getSession(a,{directory:l,runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;if(v?.session?.id)if(v.session.directory&&de(v.session.directory)!==de(l)&&t===this.focusGeneration){if(!this.newerSelection(r,l)){await this.focusProject(v.session.directory,a);return}}else f.sessions.unshift({session:v.session,updatedAt:v.session.updatedAt}),u={session:v.session,updatedAt:v.session.updatedAt}}catch(v){if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;fi(v)&&this.commitDeletion(a,l)}if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;const h=this.newerSelection(r,l),m=a&&!this.isDeleted(a),g=(h&&!this.isDeleted(h)?h:null)??u?.session.id??(m?a:f.sessions.find(v=>!v.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const x=this.createDirectoryListGates(d.payload),b=df(i,this.state.catalog,l,f.sessions,Date.now(),this.deletedSessionIds,x.options),S=b!==this.state.catalog;this.state={...this.state,sessions:f.sessions,selectedSessionId:g,sessionsListStatus:"ready",focusPending:!!g&&!this.hydratedSessionIds.has(g),error:null,catalog:b},x.commit(f.sessions);const y=[Pt];S&&y.push(Ct),this.emit(y),S&&this.raiseOrderingBaselinesForDirectory(l),g&&this.touchLastAccess(g),g&&!this.hydratedSessionIds.has(g)?(await this.hydrate(g,this.runtimeGeneration),t===this.focusGeneration&&this.state.focusPending&&this.state.selectedSessionId===g&&this.hydratedSessionIds.has(g)&&(this.state={...this.state,focusPending:!1},this.emitChrome())):g&&this.hydratedSessionIds.has(g)&&this.state.focusPending&&(this.state={...this.state,focusPending:!1},this.emitChrome())}catch(d){t===this.focusGeneration&&o===this.runtimeGeneration&&this.failFocus(t,In(d))}finally{t===this.focusGeneration&&this.pendingFocus?.expected===t&&(this.pendingFocus=null)}}failFocus(t,n){t===this.focusGeneration&&(this.state={...this.state,sessions:[],sessionsListStatus:"failed",focusPending:!1,error:n},this.emitChrome())}shouldRetryFocusError(t){if(t instanceof lt){if(t.code==="DAEMON_UNAVAILABLE")return!0;const n=t.status;return typeof n=="number"&&n>=500&&n<600||n===408||n===429}return!0}async fetchFocusListWithRetry(t,n,r,s){try{const o=await Ee.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(o))throw new lt("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");return{kind:"ok",payload:o}}catch(o){if(!this.shouldRetryFocusError(o))return{kind:"failed",error:In(o)};if(await z0(),n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};try{const i=await Ee.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(i))throw new lt("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");return{kind:"ok",payload:i}}catch(i){return{kind:"failed",error:In(i)}}}}startTranscriptPrefetch(t,n,r,s){if(!t||this.isDeleted(t))return;const o=Ee.getSession(t,{directory:n,runtimeKey:r});o.catch(()=>{}),this.transcriptPrefetch={sessionId:t,directory:n,runtimeKey:r,generation:s,promise:o}}clearTranscriptPrefetch(){this.transcriptPrefetch=null}takeTranscriptPrefetch(t,n,r,s){const o=this.transcriptPrefetch;return this.transcriptPrefetch=null,!o||o.generation!==s||o.sessionId!==t||o.directory!==n||o.runtimeKey!==r||this.isDeleted(t)?null:o.promise}async consumeTranscriptPrefetch(t,n,r,s){const o=this.takeTranscriptPrefetch(t,n,r,s);if(o)try{const i=await o;return s!==this.runtimeGeneration?void 0:i}catch{return}}async open(t,n){if(this.hasClusterAttached()&&this.state.connection!=="error"&&this.state.connection!=="unavailable"){if(de(t)===de(this.state.directory)){n&&n!==this.state.selectedSessionId&&await this.select(n);return}await this.focusProject(t,n??null);return}if(t===this.state.directory&&this.state.connection==="loading"){n&&n!==this.state.selectedSessionId&&(this.pendingPreferredSessionId=n,this.state={...this.state,selectedSessionId:n,error:null},this.emitChrome());return}if(t===this.state.directory&&this.state.connection==="ready"){n&&n!==this.state.selectedSessionId&&await this.select(n);return}this.providerRefreshRevisionByDirectory.clear();const r=++this.runtimeGeneration;this.focusGeneration=r,this.pendingFocus=null;const s=!n&&this.userSelection&&(!this.userSelection.directory||de(this.userSelection.directory)===de(t))?this.userSelection.id:null;this.pendingPreferredSessionId=n??s;const o=this.selectionRevision;this.hydratedSessionIds.clear(),this.activityPhaseById.clear(),this.pendingPromptById.clear(),this.promptGenerationById.clear(),this.acceptedPromptGenerationById.clear(),this.lastAccessById.clear(),this.lastAccessClock=0,this.lastSelectedByDirectory.clear(),this.directoryRefreshGenerationByDirectory.clear(),this.evictionScheduled=!1,this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch(),this.cadence.dispose(),this.stream?.dispose(),this.stream=null,this.recordClusterConnectionChange("loading"),this.state={...this.state,directory:t,selectedSessionId:this.pendingPreferredSessionId,connection:"loading",hydratedSessionIds:new Set,reducer:{bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)}},this.stripAwaitingPromptEchoMarkers(),this.emitChrome();const i=Y(),a=this.state.catalog;this.pendingPreferredSessionId&&this.startTranscriptPrefetch(this.pendingPreferredSessionId,t,i,r);try{const l=await Ee.selectProject(t,{runtimeKey:i});if(r!==this.runtimeGeneration)return;const d={directory:l.directory,runtimeKey:i};l.directory!==t&&(this.state={...this.state,directory:l.directory},this.emitChrome());const f=await Ee.health(d);if(r!==this.runtimeGeneration)return;if(f.state!=="ready")throw new lt(f.error?.code??"DAEMON_UNAVAILABLE",f.error?.message);const u=f.streamEpoch;typeof u=="string"&&u.length>0&&this.streamEpoch!==null&&u!==this.streamEpoch?(this.applyVerifiedEpochChange(u),this.emit([Pt,Ct])):this.adoptStreamEpoch(u);const h={state:"ready",protocolVersion:f.protocolVersion,capabilities:[...f.capabilities],...typeof f.streamEpoch=="string"?{streamEpoch:f.streamEpoch}:{}},m=await Ee.listSessions(d);if(r!==this.runtimeGeneration)return;if(!this.isResponseEpochCurrent(m))throw new lt("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const g=this.filterDeletedListItems(m.sessions),x=this.newerSelection(o,l.directory)??this.pendingPreferredSessionId??n;let b=x?g.find(A=>A.session.id===x):void 0,S=null;if(x&&!b&&!this.isDeleted(x))try{const A=await(this.takeTranscriptPrefetch(x,t,i,r)??Ee.getSession(x,{directory:t,runtimeKey:i}));if(r!==this.runtimeGeneration)return;if(A?.session?.directory&&A.session.directory!==t){if(r!==this.runtimeGeneration)return;if(!this.newerSelection(o,l.directory)){await this.open(A.session.directory,x);return}}else A?.session?.id&&(g.unshift({session:A.session,updatedAt:A.session.updatedAt}),b={session:A.session,updatedAt:A.session.updatedAt},S=A)}catch(A){if(r!==this.runtimeGeneration)return;fi(A)&&this.commitDeletion(x,t)}const y=this.newerSelection(o,l.directory),v=x&&!this.isDeleted(x),C=(y&&!this.isDeleted(y)?y:null)??b?.session.id??(v?x:g.find(A=>!A.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const w=this.createDirectoryListGates(m,{streamAttaching:!0}),M=df(a,this.state.catalog,l.directory,g,Date.now(),this.deletedSessionIds,w.options),j=M!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,sessions:g,selectedSessionId:C,connection:"ready",catalog:M},w.commit(g);const T=[Pt];if(j&&T.push(Ct),this.emit(T),j&&this.raiseOrderingBaselinesForDirectory(l.directory),this.refreshPendingInputList(),C){let A;C===x?A=S??await this.consumeTranscriptPrefetch(C,t,i,r):this.clearTranscriptPrefetch(),await this.hydrate(C,r,void 0,{initialHealth:h,initialSessions:g,...A?{initialDetail:A}:{}})}}catch(l){r===this.runtimeGeneration&&this.reportError(l)}}async select(t,n){if(!t)return;const r=n??this.state.reducer.bySession.get(t)?.directory??this.state.sessions.find(o=>o.session.id===t)?.session.directory;if(this.userSelection={id:t,directory:r??this.state.directory,revision:++this.selectionRevision},r&&de(r)!==de(this.state.directory)){if(this.stream!==null){await this.focusProject(r,t);return}await this.open(r,t);return}if(this.state.connection==="loading"){if(this.state.selectedSessionId===t)return;this.pendingPreferredSessionId=t,this.state={...this.state,selectedSessionId:t,error:null},this.emitChrome();return}if(!this.state.directory){await this.focusProject(null,t);return}if(t===this.state.selectedSessionId){this.touchLastAccess(t);const o=this.state.reducer.bySession.get(t);(!this.hydratedSessionIds.has(t)||!o)&&await this.hydrate(t,this.runtimeGeneration),this.scheduleIdleEviction();return}this.state.directory&&this.lastSelectedByDirectory.set(de(this.state.directory)??this.state.directory,t),this.cadence.flush(),this.state={...this.state,selectedSessionId:t,error:null,focusPending:!1},this.emitChrome(),this.touchLastAccess(t);const s=this.state.reducer.bySession.get(t);if(this.stream&&this.hydratedSessionIds.has(t)&&s){this.scheduleIdleEviction();return}await this.hydrate(t,this.runtimeGeneration)}lastSelectedSessionForDirectory(t){return t?this.lastSelectedByDirectory.get(de(t)??t)??null:null}async ensureHydrated(t){if(!t)return;const n=this.state.reducer.bySession.get(t);if(this.hydratedSessionIds.has(t)&&n){this.touchLastAccess(t);return}await this.hydrate(t,this.runtimeGeneration)}async create(t,n){const r=n?.directory||this.directory(),s=this.runtimeGeneration;let o=n?.model,i=n?.thinking;if(!o||!i&&!We.getState().isInitialized){const u=await Ee.getSettings({directory:r,runtimeKey:Y()});o??=u.pichamber.defaultModel,i=Wg({thinking:i,model:o,defaultThinkingByModel:u.pichamber.defaultThinkingByModel,defaultThinking:u.pichamber.defaultThinking})}else if(!i){const u=We.getState();i=Wg({model:o,defaultThinkingByModel:u.settingsDefaultThinkingByModel,defaultThinking:u.settingsDefaultThinking})}const a=await Ee.createSession({cwd:r,...t?{title:t}:{},...o?{model:o}:{},...i?{thinking:i}:{}},{directory:r,runtimeKey:Y()});if(s!==this.runtimeGeneration)return a.session.id;this.state={...this.state,sessions:[{session:a.session,updatedAt:a.session.updatedAt},...this.state.sessions],selectedSessionId:n?.select===!1?this.state.selectedSessionId:a.session.id};const l=H0(this.state.catalog,this.recordFromPiSession(a.session)),d=l!==this.state.catalog;this.state={...this.state,catalog:l};const f=[Pt];return d&&f.push(Ct),this.emit(f),await this.hydrate(a.session.id,s,a),a.session.id}async rename(t,n){const r=this.runtimeGeneration,s=Y();if(await Ee.renameSession({sessionId:t,title:n},this.scope()),r!==this.runtimeGeneration||s!==Y())return;const o=Date.now(),i=Tc(this.state.catalog,t,n,o),a=i!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(d=>d.session.id===t?{...d,session:{...d.session,title:n}}:d),catalog:i};const l=[Pt];a&&l.push(Ct),this.emit(l)}resolveSessionDirectory(t,n){return n??this.state.catalog.byId.get(t)?.directory??this.state.sessions.find(r=>r.session.id===t)?.session.directory}async archive(t,n,r){const s=this.runtimeGeneration,o=Y(),i=this.resolveSessionDirectory(t,r);if(await Ee.archiveSession({sessionId:t,archived:n},this.scope(i)),s!==this.runtimeGeneration||o!==Y())return;const a=Date.now(),l=_I(this.state.catalog,t,n,a),d=l!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(u=>u.session.id===t?{...u,session:{...u.session,archived:n}}:u),catalog:l};const f=[Pt];d&&f.push(Ct),this.emit(f)}async remove(t,n){const r=this.runtimeGeneration,s=Y(),o=this.resolveSessionDirectory(t,n);if(await Ee.deleteSession({sessionId:t,ignoreMissing:!0},o?this.scope(o):this.scope()),r!==this.runtimeGeneration||s!==Y())return;const i=this.state.selectedSessionId;this.commitDeletion(t,o);const a=this.state.selectedSessionId;a&&a!==i&&await this.hydrate(a,r)}async fork(t,n){const r=this.state.sessions.find(l=>l.session.id===t)?.session.title??this.state.catalog.byId.get(t)?.title??"",s=this.runtimeGeneration,o=Y(),i=await Ee.forkSession({sessionId:t,...n?{messageId:n}:{}},this.scope());if(s!==this.runtimeGeneration||o!==Y())return;this.upsertAndHydrate(i);const a=i.session.title?.trim()||r.trim()||"Untitled";if(!a.includes("(Fork)")){const l=`${a} (Fork)`;this.rename(i.session.id,l).catch(()=>{})}}async clone(t){const n=this.runtimeGeneration,r=Y(),s=await Ee.cloneSession({sessionId:t},this.scope());n!==this.runtimeGeneration||r!==Y()||this.upsertAndHydrate(s)}async navigate(t,n){const r=this.state.reducer.bySession.get(t),s=r?[...r.messages.values()]:[],o=new Map;for(const l of s){const d=typeof l.text=="string"?l.text.trim():"";d&&o.set(l.id,d)}const i=this.runtimeGeneration,a=(this.navigationGenerationById.get(t)??0)+1;this.navigationGenerationById.set(t,a),this.navigationCounter=Math.max(this.navigationCounter,a),this.hydrateInflightById.delete(t),this.historyInflightById.delete(t);try{const l=await Ee.navigateSession(t,n,this.scope());if((this.navigationGenerationById.get(t)??0)!==a||i!==this.runtimeGeneration||!this.isResponseEpochCurrent(l))return l;const d=this.sessionFromDetail(l);this.commitNavigationSession(d,hi(l),l.session);const f=l.navigation;if(f&&typeof f.targetEntryId=="string"&&l.hasMoreBefore!==!0){const u=new Set(l.messages.map(b=>b.message.id)),h=s.filter(b=>!u.has(b.id)).map(b=>{const S=(o.get(b.id)??"").replace(/\s+/g," ").slice(0,120)||"[No text]",y=b.role==="assistant"?"assistant":"user";return{id:b.id,role:y,preview:S}}),m=Im(t),g=new Set(h.map(b=>b.id)),x=[...h];for(const b of m?.abandoned??[])!u.has(b.id)&&!g.has(b.id)&&(x.push(b),g.add(b.id));x.length===0?af(t):wI(t,m?{...f,previousLeafId:m.previousLeafId}:f,x)}return l}catch(l){throw this.navigationGenerationById.get(t)===a&&(a<=1?this.navigationGenerationById.delete(t):this.navigationGenerationById.set(t,a-1)),l}}async prompt(t,n,r,s,o){const i=this.runtimeGeneration,a=o?.runtimeKey??Y(),l={directory:this.resolveSessionDirectory(t,o?.directory),runtimeKey:a,...o?.streamEpoch?{streamEpoch:o.streamEpoch}:{}};if(a!==Y())throw new Error("Runtime changed before sending message.");let d=this.state.reducer.bySession.get(t);const f=o?.knownEmptyTranscript===!0&&this.hydratedSessionIds.has(t)&&d!==void 0&&d.messages.size===0;if((!d||d.messages.size===0)&&!f){if(await this.hydrate(t,i),i!==this.runtimeGeneration||a!==Y())throw new Error("Runtime changed before sending message.");d=this.state.reducer.bySession.get(t)}const u=o?.operationId??a5(),h={sessionId:t,text:n,operationId:u,messageId:`msg_${u}`,clientId:J5(),...s?.length?{attachments:s}:{}},m=d?{...d,lifecycle:"busy"}:{sessionId:t,directory:this.state.directory??this.state.sessions.find(C=>C.session.id===t)?.session.directory??"",lastSequence:this.state.reducer.lastSequence.get(t)??-1,lifecycle:"busy",messages:new Map,partOrder:new Map,parts:zl(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};if(r==="prompt"){let C=null;if(d)for(const w of d.messages.values())w.role==="user"&&(C=w.id);m.awaitingPromptEcho={baselineUserMessageId:C}}else m.awaitingPromptEcho=void 0;const g=new Map(this.state.reducer.bySession);g.set(t,m),this.state={...this.state,reducer:{...this.state.reducer,bySession:g}};const x=(this.promptGenerationById.get(t)??0)+1;this.promptGenerationById.set(t,x),this.pendingPromptById.add(t),this.promoteSession(t,"active",{reorder:!0}),this.touchSessionList(t);const b=Date.now(),S=O0(Ks(this.state.catalog,t,"busy"),t,b,{directory:m.directory||this.state.directory||"",lifecycle:"busy"}),y=S!==this.state.catalog;this.state={...this.state,catalog:S};const v=[`session:${t}`,Pt];y&&v.push(Ct),this.emit(v);try{let C;return r==="steer"?C=await Ee.sendSteer(h,l):r==="followUp"?C=await Ee.sendFollowUp(h,l):C=await Ee.sendPrompt(h,l),this.promptGenerationById.get(t)===x&&this.acceptedPromptGenerationById.set(t,x),af(t),r==="prompt"&&n.trimStart().startsWith("/")&&this.reconcileAcceptedSlashPrompt(t,x,i),C}catch(C){if(X9("prompt-send",C),i!==this.runtimeGeneration||a!==Y())throw C;if(ff(C)&&this.failSessionLoad(t,C),this.promptGenerationById.get(t)===x){this.pendingPromptById.delete(t);const w=this.state.reducer.bySession.get(t);if(w?.lifecycle==="busy"&&w.streamingMessages.size===0){const M=new Map(this.state.reducer.bySession);M.set(t,{...w,lifecycle:"error",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:M}},this.promoteSession(t,"settled"),this.emit([`session:${t}`,Pt])}}throw C}}async reconcilePendingPromptSnapshot(t,n,r){const o=this.state.reducer.bySession.get(t)?.directory||this.resolveSessionDirectory(t)||this.state.directory;if(!o)return!1;try{const i=await Ee.getSession(t,{directory:o,runtimeKey:Y()});if(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n||i.session.id!==t||!this.isResponseEpochCurrent(i)||(this.state.reducer.lastSequence.get(t)??this.state.reducer.bySession.get(t)?.lastSequence??-1)>i.lastSequence)return!1;(i.lifecycle==="busy"||i.lifecycle==="retry")&&typeof i.runStartedAt=="number"&&Mn(i.session.id,i.runStartedAt,i.serverNow);const l=i.lifecycle!=="busy"&&i.lifecycle!=="retry"&&i.isStreaming!==!0;if(l){this.pendingPromptById.delete(t);const d=this.state.reducer.bySession.get(t);if(d?.lifecycle==="busy"||d?.lifecycle==="retry"){const f=new Map(this.state.reducer.bySession);f.set(t,{...d,lifecycle:"idle",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:f}}}}return this.commitSessionDetail(i),l}catch{return!1}}reconcileAcceptedPromptFromList(t){const n=this.promptGenerationById.get(t);if(n!==void 0){if(this.acceptedPromptReconcileInFlight.has(t)){this.acceptedPromptReconcileInFlight.set(t,!0);return}this.acceptedPromptReconcileInFlight.set(t,!1),this.reconcilePendingPromptSnapshot(t,n,this.runtimeGeneration).catch(()=>!1).finally(()=>{const r=this.acceptedPromptReconcileInFlight.get(t)===!0;this.acceptedPromptReconcileInFlight.delete(t);const s=this.promptGenerationById.get(t);r&&this.pendingPromptById.has(t)&&s!==void 0&&this.acceptedPromptGenerationById.get(t)===s&&this.reconcileAcceptedPromptFromList(t)})}}async reconcileAcceptedSlashPrompt(t,n,r){await new Promise(s=>setTimeout(s,750)),!(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n||!this.pendingPromptById.has(t))&&await this.reconcilePendingPromptSnapshot(t,n,r)&&(await new Promise(s=>setTimeout(s,2e3)),!(r!==this.runtimeGeneration||this.promptGenerationById.get(t)!==n)&&await this.reconcilePendingPromptSnapshot(t,n,r))}abort=t=>Ee.abortSession({sessionId:t},this.scope());compact=(t,n)=>Ee.compactSession({sessionId:t,...n?{customInstructions:n}:{}},this.scope());runBash=(t,n,r)=>Ee.runBash({sessionId:t,command:n,...r?.excludeFromContext?{excludeFromContext:!0}:{}},this.scope());abortBash=t=>Ee.abortBash({sessionId:t},this.scope());setModel=(t,n,r)=>Ee.setSessionModel({sessionId:t,model:{providerId:n,modelId:r}},this.scope());setThinking=(t,n)=>Ee.setSessionThinking({sessionId:t,thinking:n},this.scope());tree=t=>Ee.getSessionTree(t,this.scope());providers=()=>Ee.listProviders({runtimeKey:Y()});upload=t=>Ee.createAttachment(t,this.scope());uploadFile=(t,n)=>Ee.uploadAttachment(t,n,this.scope());deleteUpload=t=>Ee.deleteAttachment(t,this.scope());selected(){const t=this.state.selectedSessionId,n=t?this.state.reducer.bySession.get(t):void 0;return n?Y5(n):null}consumeExtensionEditor(t,n){const r=this.state.reducer.bySession.get(t);if(!r)return;const o=(r.extensionEditorOps??(r.extensionEditor?[r.extensionEditor]:[])).filter(l=>l.sequence>n),i=o.length>0?o[o.length-1]:void 0;if(r.extensionEditor===void 0&&r.extensionEditorOps===void 0&&o.length===0)return;const a=new Map(this.state.reducer.bySession);a.set(t,{...r,extensionEditorOps:o.length>0?o:void 0,extensionEditor:i}),this.state={...this.state,reducer:{...this.state.reducer,bySession:a}},this.emit([`session:${t}`])}dismissExtensionDialog(t,n){const r=J8(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`,Ac]))}dropExtensionSurface(t,n){const r=t6(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`]))}sessionFromDetail(t){return Wl(t).session}async loadOlderMessages(t){const n=this.historyInflightById.get(t);if(n)return n;const r=this.state.reducer.bySession.get(t);if(!r?.hasMoreBefore||!r.beforeCursor||this.isDeleted(t))return!1;const s=this.runtimeGeneration,o=this.navigationGenerationById.get(t)??0,i=r.beforeCursor,a=Y(),l=Ee.getSessionMessages(t,{before:i},{directory:r.directory,runtimeKey:a}).then(d=>{if(s!==this.runtimeGeneration||a!==Y()||(this.navigationGenerationById.get(t)??0)!==o)return!1;const f=this.state.reducer.bySession.get(t);if(!f||f.beforeCursor!==i||d.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(d))return!1;const u=Wl(d).session,h=new Map(u.messages);for(const[y,v]of f.messages)h.set(y,v);const m=new Map(u.partOrder);for(const[y,v]of f.partOrder)m.set(y,v);const g=zl(u.parts);for(const[y,v]of f.parts)g.set(y,v);const x=new Map(u.toolsByCallId);for(const[y,v]of f.toolsByCallId)x.set(y,v);const b={...f,messages:h,partOrder:m,parts:g,toolsByCallId:x,hasMoreBefore:u.hasMoreBefore===!0,beforeCursor:u.beforeCursor,lastSequence:f.lastSequence},S={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};return S.bySession.set(t,b),this.state={...this.state,reducer:S},this.touchLastAccess(t),this.emit([`session:${t}`]),b.hasMoreBefore===!0}).finally(()=>{this.historyInflightById.get(t)===l&&this.historyInflightById.delete(t)});return this.historyInflightById.set(t,l),l}recordFromPiSession(t,n){return $I(t,this.state.catalog,n)}mergeHydratedSession(t,n){return zI(t,n,{localSendPending:this.pendingPromptById.has(t.sessionId)})}touchLastAccess(t){t&&(this.lastAccessClock+=1,this.lastAccessById.set(t,this.lastAccessClock))}commitNavigationSession(t,n,r){this.cadence.flush();const s=this.state.reducer.bySession.get(t.sessionId),o=s?{...t,lastSequence:Math.max(t.lastSequence,s.lastSequence),...s.model&&!t.model?{model:s.model}:{},...s.thinking&&!t.thinking?{thinking:s.thinking}:{},queue:s.queue.steering>0||s.queue.followUp>0?s.queue:t.queue}:t,i={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};i.bySession.set(o.sessionId,o),i.lastSequence.set(o.sessionId,o.lastSequence),this.hydratedSessionIds.add(o.sessionId),this.touchLastAccess(o.sessionId);const l=this.state.selectedSessionId===o.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let d=this.state.sessionLoadErrorById;if(d.has(o.sessionId)){const g=new Map(d);g.delete(o.sessionId),d=g}const f=Nc(o.lifecycle);let u=this.state.catalog;u.byId.has(o.sessionId)||(u=bs(u,o.sessionId,o.directory,f)),u=lf(u,o.sessionId,!0),u=Ks(u,o.sessionId,f,o.retry),n&&(u=this.adoptDetailPendingInput(u,o.sessionId,o.directory,{pending:n.pending},n.sequence)),r&&(u=U0(u,o.sessionId,o.directory,r.messageCount));const h=u!==this.state.catalog;this.state={...this.state,reducer:i,error:null,focusPending:l,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:d,catalog:u};const m=[`session:${o.sessionId}`,Pt];h&&m.push(Ct),this.emit(m),this.scheduleIdleEviction()}commitSessionDetail(t,n=[]){this.commitHydratedSession(this.sessionFromDetail(t),n,hi(t),t.session)}commitHydratedSession(t,n=[],r,s){if(this.isDeleted(t.sessionId))return;this.cadence.flush();const o=this.state.reducer.bySession.get(t.sessionId),i=this.mergeHydratedSession(t,o);(i.lifecycle==="busy"||i.lifecycle==="retry")&&g0(i.sessionId,"active");let a={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};a.bySession.set(i.sessionId,i),a.lastSequence.set(i.sessionId,i.lastSequence);for(const S of n){const y=qu(a,S);a=y.state,y.didApply&&this.observeActivity(S)}this.hydratedSessionIds.add(i.sessionId),this.touchLastAccess(i.sessionId);const d=this.state.selectedSessionId===i.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let f=this.state.sessionLoadErrorById;if(f.has(i.sessionId)){const S=new Map(f);S.delete(i.sessionId),f=S}let u=this.applyCatalogFromEvents(n,a);r&&(u=this.adoptDetailPendingInput(u,i.sessionId,i.directory,{pending:r.pending},r.sequence));const h=a.bySession.get(i.sessionId),m=h?.lifecycle,g=m?Nc(m):void 0;u.byId.has(i.sessionId)||(u=bs(u,i.sessionId,i.directory,g??"idle")),u=lf(u,i.sessionId,!0),g!==void 0&&(u=Ks(u,i.sessionId,g,h?.retry)),s&&(u=U0(u,i.sessionId,i.directory,s.messageCount));const x=u!==this.state.catalog;this.state={...this.state,reducer:a,error:null,focusPending:d,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:f,catalog:u};const b=[`session:${i.sessionId}`,Pt,Ac];x&&b.push(Ct),this.emit(b),this.scheduleIdleEviction()}async hydrate(t,n,r,s){if(n!==this.runtimeGeneration||this.isDeleted(t))return;const o=this.hydrateInflightById.get(t);if(o)return o;const i=this.hydrateUnshared(t,n,r,s).finally(()=>{this.hydrateInflightById.get(t)===i&&this.hydrateInflightById.delete(t)});return this.hydrateInflightById.set(t,i),i}async hydrateUnshared(t,n,r,s){if(n!==this.runtimeGeneration||this.isDeleted(t))return;const o=this.resolveSessionDirectory(t)||this.directory(),i=Y(),l=!!(this.state.reducer.bySession.get(t)&&this.hydratedSessionIds.has(t)),d=this.navigationGenerationById.get(t)??0;if(!s?.force&&this.stream&&l&&!r){this.state.connection==="error"||this.state.connection==="unavailable"?this.reconnect(t,n,i):this.state.connection==="ready"&&this.state.error&&(this.state={...this.state,error:null},this.emitChrome());return}this.clearSessionLoadError(t);const f=this.stream;try{if(this.stream){const w=r??await Ee.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration||w.session.id!==t||!this.isResponseEpochCurrent(w)||this.isDeleted(t)||(this.navigationGenerationById.get(t)??0)!==d)return;(w.lifecycle==="busy"||w.lifecycle==="retry")&&typeof w.runStartedAt=="number"&&Mn(w.session.id,w.runStartedAt,w.serverNow),this.commitSessionDetail(w);return}const u=[];let h=!1;const m=this.streamGeneration+1;this.streamGeneration=m;const g=()=>n===this.runtimeGeneration&&i===Y()&&m===this.streamGeneration,x=w=>{g()&&(h?this.apply(w):u.push(w))},b=await g6({directory:o,selectedSessionId:t,runtimeKey:i,...s?.initialHealth?{initialHealth:s.initialHealth}:{},...s?.initialSessions?{initialSessions:s.initialSessions}:{},...s?.initialDetail?{initialDetail:s.initialDetail}:{},onEvent:x,onStreamDisconnect:()=>{g()&&this.reconnect(this.state.selectedSessionId??t,n,i)},onStreamReconnect:()=>this.markStreamReconnected(n,i,m),onEpochChange:w=>{g()&&this.handleVerifiedEpochChange(w)},onAuthRequired:()=>{g()&&this.handleStreamAuthRequired()}});if(!g()){b.stream?.dispose();return}if(b.phase==="failed")throw b.stream?.dispose(),b.errors.at(-1)?.error??new lt("DAEMON_PROTOCOL_MISMATCH","The Pi runtime returned an incompatible bootstrap response.");const S=b.selectedSessionTiming;S&&S.sessionId===t&&(S.lifecycle==="busy"||S.lifecycle==="retry")&&typeof S.runStartedAt=="number"&&Mn(S.sessionId,S.runStartedAt,S.serverNow);let y=r?this.sessionFromDetail(r):b.reducerState.bySession.get(t),v=r?hi(r):s?.initialDetail?hi(s.initialDetail):void 0,C=r?.session??s?.initialDetail?.session;if(r&&(r.lifecycle==="busy"||r.lifecycle==="retry")&&typeof r.runStartedAt=="number"&&Mn(r.session.id,r.runStartedAt,r.serverNow),!y)try{const w=r??await Ee.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration){b.stream?.dispose();return}if(this.isDeleted(t)){b.stream?.dispose();return}if(!this.isResponseEpochCurrent(w)){b.stream?.dispose();return}(w.lifecycle==="busy"||w.lifecycle==="retry")&&typeof w.runStartedAt=="number"&&Mn(w.session.id,w.runStartedAt,w.serverNow),v=hi(w),y=this.sessionFromDetail(w),C=w.session}catch(w){if(this.stream=b.stream,h=!0,n===this.runtimeGeneration&&fi(w)){this.handleInvalidSession(t,o,n,u);return}if(n===this.runtimeGeneration&&ff(w)){u.length>0&&this.commitEvents(u),this.failSessionLoad(t,In(w));return}throw b.stream?.dispose(),this.stream=null,w}if(y.sessionId!==t){b.stream?.dispose();return}if(this.isDeleted(t)){b.stream?.dispose();return}if((this.navigationGenerationById.get(t)??0)!==d){b.stream?.dispose();return}this.stream=b.stream,this.commitHydratedSession(y,u,v,C),h=!0}catch(u){if(n!==this.runtimeGeneration)return;if(fi(u)){this.handleInvalidSession(t,o,n);return}if(ff(u)){this.failSessionLoad(t,In(u));return}if(VI(u)){try{const h=await Ee.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration||h.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(h)||(this.navigationGenerationById.get(t)??0)!==d)return;(h.lifecycle==="busy"||h.lifecycle==="retry")&&typeof h.runStartedAt=="number"&&Mn(h.session.id,h.runStartedAt,h.serverNow),this.commitSessionDetail(h)}catch(h){if(n!==this.runtimeGeneration)return;this.failSessionLoad(t,In(h))}return}if(f&&this.stream===f&&In(u).code!=="DAEMON_AUTH_FAILED"){this.failSessionLoad(t,In(u));return}this.reportError(u)}}markStreamReconnected(t,n,r){if(!(t!==this.runtimeGeneration||n!==Y()||r!==this.streamGeneration)){if(this.streamReadyRevision+=1,this.state.connection==="ready"&&!this.state.error){(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(this.recoveryAttempt=0,this.runSyncRecovery());return}this.recordClusterConnectionChange("ready"),this.state={...this.state,connection:"ready",error:null},this.emitChrome()}}async reconnect(t,n,r){if(this.recovering||n!==this.runtimeGeneration)return;this.recovering=!0,this.cadence.flush();const s=this.stream,o=this.streamReadyRevision,i=this.streamGeneration+1,a=this.streamCursor(),l=()=>n===this.runtimeGeneration&&r===Y()&&(this.streamGeneration===i||this.streamGeneration===i-1&&o===this.streamReadyRevision);let d=!1;try{let f=!1;const u=await w6({directory:this.directory(),sessionId:t,runtimeKey:r,lastKnownSequence:a,streamEpoch:this.streamEpoch??void 0,onEvent:h=>{l()&&(!f&&h.name==="session.snapshot"&&h.payload?.snapshot?.resync===!0&&(f=!0,this.queueSyncRecovery({directories:"all-known",residents:this.hydratedSessionIds})),this.apply(h))},onStreamDisconnect:()=>{l()&&this.reconnect(this.state.selectedSessionId??t,n,r)},onStreamReconnect:()=>this.markStreamReconnected(n,r,i),onAuthRequired:()=>{l()&&(d=!0,this.handleStreamAuthRequired())},onEpochChange:h=>{l()&&this.handleVerifiedEpochChange(h)}});if(n!==this.runtimeGeneration||r!==Y()){u.stream?.dispose();return}if(o!==this.streamReadyRevision){u.stream?.dispose();return}if(u.phase==="ready"){typeof u.runStartedAt=="number"&&Mn(t,u.runStartedAt,u.serverNow);let h=!1;typeof u.epoch=="string"&&u.epoch.length>0&&this.streamEpoch!==u.epoch&&(h=this.applyVerifiedEpochChange(u.epoch)!==null),s?.dispose(),this.streamGeneration=i,this.stream=u.stream;const m={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)},g=[],x=[];for(const[v,C]of u.reducerState.bySession.entries()){const w=m.bySession.get(v),M=this.mergeHydratedSession(C,w);m.bySession.set(v,M),m.lastSequence.set(v,M.lastSequence),this.touchLastAccess(v),g.push(v),(w?.lifecycle==="busy"||w?.lifecycle==="retry")&&M.lifecycle!=="busy"&&M.lifecycle!=="retry"&&x.push(v)}for(const v of u.reducerState.bySession.keys())this.hydratedSessionIds.add(v);let b=this.state.catalog;for(const v of g){const C=m.bySession.get(v);C&&(b=Ks(b,v,Nc(C.lifecycle),C.retry))}const S=b!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,reducer:m,connection:"ready",error:null,hydratedSessionIds:new Set(this.hydratedSessionIds),...S?{catalog:b}:{}};const y=[Pt,Ac];for(const v of g)y.push(`session:${v}`);(S||h)&&y.push(Ct),this.emit(y),this.refreshPendingInputList();for(const v of x)this.promoteSession(v,"settled");for(const v of g){if(!this.pendingPromptById.has(v))continue;const C=this.promptGenerationById.get(v);if(C===void 0||this.acceptedPromptGenerationById.get(v)!==C)continue;const w=u.reducerState.bySession.get(v)?.lifecycle;w==="busy"||w==="retry"||this.reconcileAcceptedPromptFromList(v)}this.scheduleIdleEviction(),h&&this.publishSyncRecoveryState()}else d||this.reportError(new lt(u.error?.code??"DAEMON_UNAVAILABLE",u.error?.message))}finally{this.recovering=!1}}apply(t){this.cadence.push(t)}observeActivity(t){if(t.name==="session.lifecycle"){const n=t.payload.state==="busy"||t.payload.state==="retry";n&&typeof t.payload.runStartedAt=="number"&&Mn(t.sessionId,t.payload.runStartedAt,t.payload.serverNow),this.promoteSession(t.sessionId,n?"active":"settled",{notification:!n&&(t.payload.state==="idle"||t.payload.state==="error")?{kind:t.payload.state==="error"?"error":"completion",sequence:t.sequence,directory:t.directory}:void 0})}else if(t.name==="session.snapshot"){const n=t.payload.snapshot,r=n.lifecycle==="busy"||n.lifecycle==="retry"||n.isStreaming===!0;r&&typeof n.runStartedAt=="number"&&Mn(t.sessionId,n.runStartedAt,n.serverNow),this.promoteSession(t.sessionId,r?"active":"settled")}else t.name==="assistant.message.start"?this.promoteSession(t.sessionId,"active"):t.name==="session.interrupted"?this.promoteSession(t.sessionId,"settled"):t.name==="session.openUrl"?this.emitOpenRequest(t):t.name==="session.error"&&this.promoteSession(t.sessionId,"settled",{notification:{kind:"error",sequence:t.sequence,directory:t.directory,error:{code:t.payload.code,message:t.payload.message}}})}stripAwaitingPromptEchoMarkers(){let t=null;for(const[n,r]of this.state.reducer.bySession)r.awaitingPromptEcho!==void 0&&(t||(t=new Map(this.state.reducer.bySession)),t.set(n,{...r,awaitingPromptEcho:void 0}));t&&(this.state={...this.state,reducer:{...this.state.reducer,bySession:t}})}notePromptProgress(t){if(t.name==="assistant.message.start"||t.name==="session.lifecycle"&&(t.payload.state==="busy"||t.payload.state==="retry")){this.pendingPromptById.delete(t.sessionId);return}(t.name==="session.error"||t.name==="session.interrupted"||t.name==="session.lifecycle"&&t.payload.state!=="busy"&&t.payload.state!=="retry")&&this.pendingPromptById.delete(t.sessionId)}retainPendingPrompt(t,n){if(!this.pendingPromptById.has(n))return t;const r=t.bySession.get(n);if(!r||r.lifecycle==="busy"||r.lifecycle==="retry")return t;const s=new Map(t.bySession);return s.set(n,{...r,lifecycle:"busy"}),{...t,bySession:s}}promoteSession(t,n,r){const s=this.activityPhaseById.get(t);this.activityPhaseById.set(t,n),g0(t,n),r?.reorder&&aM(t,n);const o=r?.notification;if(!(n==="settled"&&s==="active"&&(r?.notifyIfSettled||o!==void 0)))return;const a=o?.directory??this.state.catalog.byId.get(t)?.directory??this.state.directory??void 0;this.state.selectedSessionId!==t&&jb(t,a,o?.kind==="error"?{error:o.error??{}}:void 0),o&&_b({sessionId:t,directory:a,sequence:o.sequence,kind:o.kind,title:this.state.catalog.byId.get(t)?.title})}touchSessionList(t){const n=this.state.sessions.findIndex(i=>i.session.id===t);if(n<0)return;const r=Date.now(),s=this.state.sessions[n];if(!s)return;const o=this.state.sessions.slice();o.splice(n,1),o.unshift({...s,updatedAt:r,session:{...s.session,updatedAt:r}}),this.state={...this.state,sessions:o}}requestProviderCatalogRefresh(t,n=!0){if(n){const i=(this.providerRefreshRevisionByDirectory.get(t)??0)+1;this.providerRefreshRevisionByDirectory.set(t,i)}if(this.providerRefreshTaskByDirectory.has(t))return;const r=this.runtimeGeneration;let s=0;const o=(async()=>{for(;r===this.runtimeGeneration;){const i=this.providerRefreshRevisionByDirectory.get(t)??0;if(i<=s)return;try{await We.getState().loadProviders({directory:t,source:"extension.catalog"})}finally{s=i}}})().catch(()=>{}).finally(()=>{if(this.providerRefreshTaskByDirectory.get(t)!==o)return;this.providerRefreshTaskByDirectory.delete(t);const i=this.providerRefreshRevisionByDirectory.get(t)??0;(r!==this.runtimeGeneration&&i>0||i>s)&&this.requestProviderCatalogRefresh(t,!1)});this.providerRefreshTaskByDirectory.set(t,o)}restoreTranscript(t){if(!t||this.restoringTranscriptById.has(t))return;this.restoringTranscriptById.add(t);const n=this.runtimeGeneration;this.hydrate(t,n,void 0,{force:!0}).finally(()=>{this.restoringTranscriptById.delete(t)})}commitEvents(t){if(t.length===0)return;let n=this.state.reducer,r=!1,s=!1;const o=new Set,i=new Set,a=new Map,l=[],d=[],f=new Map,u=new Map;for(const y of t){if(y.name!=="session.deleted")continue;const v=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0,C=u.get(v)??new Set;C.add(y.sessionId),u.set(v,C)}let h=null;for(const y of t){const v=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0;if(!v&&this.streamEpoch!==null||v&&this.retiredStreamEpochs.has(v))continue;if(v&&this.streamEpoch!==null&&v!==this.streamEpoch){if(y.name!=="session.snapshot")continue;this.adoptStreamEpoch(v);const _=this.resetForEpochChange();if(n=Ul(),o.clear(),h)for(const k of _)h.add(k);else h=_;i.clear(),a.clear(),f.clear(),l.length=0,r=!1,s=!1}if(v&&this.adoptStreamEpoch(v),this.deletedSessionIds.has(y.sessionId))continue;if(y.name==="session.deleted"){const _=qu(n,y);if(n=_.state,!_.didApply)continue;r=!0,i.add(y.sessionId),l.push(y),f.set(y.sessionId,y.directory),o.delete(y.sessionId),this.restoringTranscriptById.delete(y.sessionId);continue}if(u.get(v)?.has(y.sessionId))continue;const C=!n.bySession.has(y.sessionId),w=(n.lastSequence.get(y.sessionId)??-1)>=0,M=y.name==="extension.custom.dismiss"?n.bySession.get(y.sessionId)?.extensionSurfaces?.get(y.payload.surfaceId):void 0,j=qu(n,y);if(n=j.state,!j.didApply)continue;if(l.push(y),M&&y.name==="extension.custom.dismiss"&&d.push({sessionId:y.sessionId,reason:y.payload.reason,surface:M}),C&&w&&o.add(y.sessionId),y.name==="session.snapshot"&&o.add(y.sessionId),r=!0,i.add(y.sessionId),y.name==="extension.catalog"){const _=a.get(y.directory)??{providers:!1,resources:!1,commands:!1};a.set(y.directory,{providers:_.providers||y.payload.providers===!0,resources:_.resources||y.payload.resources===!0,commands:_.commands||y.payload.commands===!0})}this.notePromptProgress(y);const T=y.name==="session.error"||y.name==="session.interrupted"||y.name==="session.lifecycle"&&y.payload.state!=="busy"&&y.payload.state!=="retry",A=y.name==="assistant.message.start"&&y.payload.role==="user"||y.name==="session.snapshot";if(T||A){const _=n.bySession.get(y.sessionId);if(_?.awaitingPromptEcho!==void 0&&(T||!Ub(_))){const k=new Map(n.bySession);k.set(y.sessionId,{..._,awaitingPromptEcho:void 0}),n={...n,bySession:k}}}if(this.pendingPromptById.has(y.sessionId)&&y.name==="session.snapshot"&&!y.payload.snapshot.isStreaming){n=this.retainPendingPrompt(n,y.sessionId),this.promoteSession(y.sessionId,"active");continue}this.observeActivity(y),this.lastAccessClock+=1,this.lastAccessById.set(y.sessionId,this.lastAccessClock),s=!0}if(!r){h&&(this.state={...this.state,reducer:n,hydratedSessionIds:new Set(this.hydratedSessionIds)},this.emit([Pt,Ct,...[...h].map(y=>`session:${y}`)]),this.queueSyncRecovery({directories:"all-known",residents:h}));return}this.state={...this.state,reducer:n,...h?{hydratedSessionIds:new Set(this.hydratedSessionIds)}:{}};for(const[y,v]of f)this.commitDeletion(y,v);for(const y of l)W0(y)&&Number.isSafeInteger(y.sequence)&&(this.lifecycleSequenceById.get(y.sessionId)??-1)<y.sequence&&this.lifecycleSequenceById.set(y.sessionId,y.sequence);const m=this.applyCatalogFromEvents(l,n),g=m!==this.state.catalog,x=[];if(g){const y=this.state.catalog,v=new Map;for(const C of l){if(C.name!=="session.input")continue;const w=v.get(C.sessionId);w?w.push(C):v.set(C.sessionId,[C])}for(const[C,w]of v){const M=m.byId.get(C);if(!M)continue;const j=y.byId.get(C)?.pendingInput,T=M.pendingInput;let A=j;const _=[];for(const k of w){if(k.name!=="session.input")continue;const E=k.payload.pending,I=E===null?null:Rd(E)?E:void 0;if(I===void 0)continue;const N=k.payload.serverNow,O=typeof N=="number"&&Number.isFinite(N)&&N>0?N:void 0,L=A!=null,D=I!=null;!L&&D&&I?_.push({type:"opened",sessionId:C,directory:M.directory??k.directory,pending:I,...O!==void 0?{serverNow:O}:{}}):L&&!D&&_.push({type:"cleared",sessionId:C,directory:M.directory??k.directory,pending:null}),A=I}if(wa(A,T))for(const k of _)x.push(k);else{const k=j!=null,E=T!=null;!k&&E&&T?x.push({type:"opened",sessionId:C,directory:M.directory,pending:T}):k&&!E&&x.push({type:"cleared",sessionId:C,directory:M.directory,pending:null})}}this.state={...this.state,catalog:m}}const b=new Map;for(const y of l)y.name==="session.input"&&b.set(y.sessionId,y);for(const[y,v]of b){if(v.payload.pending!==null||m.byId.has(y)||this.pendingInputSequenceById.get(y)!==v.sequence)continue;const C=this.openedPendingInputById.get(y);C!==void 0&&x.push({type:"cleared",sessionId:y,directory:C,pending:null})}const S=[];(g||h)&&S.push(Ct),l.some(y=>y.name==="extension.dialog"||y.name==="extension.dialog.dismiss"||y.name==="session.snapshot")&&S.push(Ac);for(const y of i)S.push(`session:${y}`);S.length>0&&this.emit(S),this.emitPendingInputTransitions(x);for(const y of d)for(const v of[...this.extensionSurfaceDismissListeners])try{v(y)}catch(C){console.error("[pi-session-store] surface dismiss listener failed",C)}l.some(y=>y.name==="session.input")&&this.requestNeedingSessionMetadataBackfill(l.filter(y=>y.name==="session.input").map(y=>y.sessionId)),s&&this.scheduleIdleEviction();for(const y of o)this.restoreTranscript(y);h&&this.queueSyncRecovery({directories:"all-known",residents:h});for(const[y,v]of a)v.providers&&this.requestProviderCatalogRefresh(y),v.commands&&ul(y),v.resources&&(Jl(),de(y)===de(this.state.directory??"")&&Dr.getState().loadSkills())}applyCatalogFromEvents(t,n){let r=this.state.catalog;for(const s of t){if(this.deletedSessionIds.has(s.sessionId))continue;const o=n.bySession.get(s.sessionId),i=o?.lifecycle,a=Zb(s);if(a!==void 0&&!r.byId.has(s.sessionId)&&(r=bs(r,s.sessionId,s.directory,a)),i!==void 0&&(this.hydratedSessionIds.has(s.sessionId)||W0(s))&&(r=Ks(r,s.sessionId,Nc(i),o?.retry)),s.name==="session.input"&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=ta(r,s.sessionId,s.directory,s.payload.pending,s.sequence)),s.name==="session.snapshot"){const l=s.payload.snapshot.inputState;l&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=ta(r,s.sessionId,s.directory,l.pending,s.sequence))}if(s.name==="session.updated"){const l=typeof s.payload.title=="string"?s.payload.title.trim():"";if(l){r.byId.has(s.sessionId)||(r=bs(r,s.sessionId,s.directory,a??"idle"));const d=r.byId.get(s.sessionId);r=Tc(r,s.sessionId,l,d?.updatedAt??Date.now())}else{const d=r.byId.get(s.sessionId);if(d){const f=Ah(d.preview??"");r=Tc(r,s.sessionId,f,d.updatedAt)}}}if(s.name==="assistant.message.start"&&s.payload.role==="user"){r=O0(r,s.sessionId,Date.now(),{directory:s.directory,lifecycle:"busy"});const l=r.byId.get(s.sessionId),d=Ah(s.payload.text??"");d&&l&&l.title.trim().length===0&&(r=Tc(r,s.sessionId,d,l.updatedAt))}}return r}scheduleIdleEviction(){this.evictionScheduled||this.state.reducer.bySession.size<=uf||(this.evictionScheduled=!0,queueMicrotask(()=>{this.evictionScheduled=!1,this.evictIdleTranscripts()}))}evictIdleTranscripts(){const t=this.state.reducer.bySession;if(t.size<=uf)return;const n=new Set;this.state.selectedSessionId&&n.add(this.state.selectedSessionId);for(const[h,m]of t)(m.lifecycle==="busy"||m.lifecycle==="retry")&&n.add(h),m.extensionDialogs.length>0&&n.add(h),m.extensionSurfaces&&m.extensionSurfaces.size>0&&n.add(h),this.state.catalog.byId.get(h)?.pendingInput!=null&&n.add(h);for(const h of this.pendingPromptById)n.add(h);const r=[];for(const h of t.keys()){if(n.has(h))continue;const m=this.lastAccessById.get(h)??0;r.push([h,m])}r.sort((h,m)=>h[1]-m[1]);let s=null,o=null,i=null,a=null;const l=[];let d=0;for(const[h]of r){if(t.size-d<=uf)break;s||(s=new Map(t)),o||(o=new Set(this.hydratedSessionIds)),i||(i=new Map(this.lastAccessById)),s.delete(h),o.delete(h),i.delete(h),this.activityPhaseById.delete(h),a=a??this.state.catalog,a=lf(a,h,!1),d+=1,l.push(h)}if(!s||!o||!i)return;this.lastAccessById=i;const f=!!a&&a!==this.state.catalog;this.state={...this.state,reducer:{bySession:s,lastSequence:new Map(this.state.reducer.lastSequence)},hydratedSessionIds:o,...a?{catalog:a}:{}};const u=[Pt];for(const h of l)u.push(`session:${h}`);f&&u.push(Ct),this.emit(u)}async upsertAndHydrate(t){const n=this.runtimeGeneration,r=H0(this.state.catalog,this.recordFromPiSession(t.session)),s=r!==this.state.catalog;this.state={...this.state,sessions:[{session:t.session,updatedAt:t.session.updatedAt},...this.state.sessions.filter(i=>i.session.id!==t.session.id)],selectedSessionId:t.session.id,catalog:r};const o=[Pt];s&&o.push(Ct),this.emit(o),await this.hydrate(t.session.id,n,t)}directory(){if(!this.state.directory)throw new lt("DAEMON_UNAVAILABLE");return this.state.directory}streamCursor(){let t=-1;for(const n of this.state.reducer.lastSequence.values())n>t&&(t=n);return t>=0?t:void 0}scope(t){return{directory:t||this.directory(),runtimeKey:Y()}}reconnectAfterTransportSwitch(){const t=this.state.selectedSessionId;!this.stream||!t||!this.state.directory||this.reconnect(t,this.runtimeGeneration,Y())}resetForRuntime(){this.catalogCache.flush(),this.resetLiveRuntimeState(),this.state=Lc(this.readCachedCatalog(Y())),cf(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()}emit(t){if(t.length===0)return;t.includes(Ct)&&this.catalogCache.schedule(Y(),this.state.catalog);const n=new Set;for(const s of t){const o=this.listenersByTopic.get(s);if(o)for(const i of o)n.has(i)||(n.add(i),i())}const r=this.listenersByTopic.get(V0);if(r)for(const s of r)n.has(s)||(n.add(s),s())}readCachedCatalog(t){try{return this.catalogCache.read(t)??tp()}catch{return tp()}}emitBroadcast(){const t=new Set;for(const n of this.listenersByTopic.values())for(const r of n)t.has(r)||(t.add(r),r())}emitChrome(){this.emit([Pt])}}const Co=new Map,K0=e=>{Co.set(e,(Co.get(e)??0)+1)},WI=e=>(Co.get(e)??0)>0,KI=e=>{const t=Co.get(e)??0;return t<=0?!1:(t===1?Co.delete(e):Co.set(e,t-1),!0)};function Yb(){return Sa(Ue().getState().catalog,{archived:!1})}function Tm(){const e=Ue().getState().catalog;return[...Sa(e,{archived:!1}),...Sa(e,{archived:!0})]}function GI(e){const t=Ue().getState();return t.catalog.byId.get(e)?.directory??t.sessions.find(n=>n.session.id===e)?.session.directory??t.directory}function ZI(){return PI(Ue().getState().catalog).map(e=>({id:e.id,title:e.title.trim()||null,directory:e.directory}))}function OY(e,t){return[]}function HY(e,t){return[]}const Am=2048,G0=new WeakMap,YI=e=>e==="running"||e==="pending",Xb=e=>{if(e==null)return 0;if(typeof e=="string")return e.length;if(typeof e=="number"||typeof e=="boolean")return String(e).length;try{return JSON.stringify(e)?.length??0}catch{return Am+1}},XI=e=>{if(!e)return e;const t=e.patch??e.diff??e.filediff?.patch??e.filediff?.diff;if(Xb(t)<=Am)return e;const n={...e};if(delete n.patch,delete n.diff,n.filediff&&typeof n.filediff=="object"){const r={...n.filediff};delete r.patch,delete r.diff,n.filediff=r}return n.deferredBody=!0,n},Nm=(e,t)=>{if(e.type==="thinking")return{id:e.id,type:"reasoning",text:e.text,streaming:e.streaming};if(e.type==="attachment")return{id:e.id,type:"file",filename:e.attachment?.name,mime:e.attachment?.mime,size:e.attachment?.size};if(e.type==="file")return{id:e.id,type:"file",filename:e.file?.filename,mime:e.file?.mime,url:e.file?.url};if(e.type==="tool"){const n=YI(e.tool?.state),r=t?.full===!0||n,s=!r&&Xb(e.tool?.output)>Am,o=r?e.tool?.metadata:XI(e.tool?.metadata),i=!!(!r&&(s||o?.deferredBody)),a=e.tool?.render;let l;return a&&(i&&a.resultExpanded!==void 0?l={...a.call!==void 0?{call:a.call}:{},...a.result!==void 0?{result:a.result}:{}}:l=a),{id:e.id,type:"tool",tool:e.tool?.name,callID:e.tool?.toolCallId,state:{status:e.tool?.state==="running"||e.tool?.state==="pending"?"running":e.tool?.state==="error"?"error":e.tool?.state==="cancelled"?"cancelled":"completed",input:e.tool?.input,...s?{}:{output:e.tool?.output},...l!==void 0?{render:l}:{},error:e.tool?.error,time:{start:e.tool?.startedAt,end:e.tool?.endedAt},metadata:o,...i?{deferredBody:!0}:{}}}}return{id:e.id,type:"text",text:e.text}},JI=e=>({id:e.id,directory:e.directory,parentID:e.parentId??null,title:e.title,...typeof e.messageCount=="number"?{messageCount:e.messageCount}:{},time:{created:e.createdAt,updated:e.updatedAt,...e.archived?{archived:e.timeArchived??e.updatedAt}:{}}}),QI=(e,t)=>{const n=[];if(e.parts.length>0){const i=e.parts.some(l=>l.type==="thinking"),a=e.parts.some(l=>l.type==="text");!i&&e.thinking&&n.push({id:`${e.id}:thinking`,type:"reasoning",text:e.thinking,streaming:!1}),n.push(...e.parts.map(l=>Nm(l))),!a&&e.text&&n.push({id:`${e.id}:text`,type:"text",text:e.text})}else e.thinking&&n.push({id:`${e.id}:thinking`,type:"reasoning",text:e.thinking,streaming:!1}),e.text&&n.push({id:`${e.id}:text`,type:"text",text:e.text});const s=e.role==="assistant"&&!e.streaming?e.error?"error":"stop":void 0;return{info:{id:e.id,sessionID:t,role:e.role,...e.role==="extension"?{customType:e.customType,data:e.data,details:e.details,...e.render?{render:e.render}:{},...e.text?{text:e.text}:{}}:{},...e.parentId?{parentID:e.parentId}:{},time:{created:e.createdAt,...e.streaming?{}:typeof e.durationMs=="number"&&e.durationMs>0?{completed:e.createdAt+e.durationMs}:{completed:e.createdAt}},...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.error?{error:{name:e.error.code,message:e.error.message}}:{},...e.model?{model:{providerID:e.model.providerId,modelID:e.model.modelId},providerID:e.model.providerId,modelID:e.model.modelId}:{},...e.thinkingLevel?{variant:e.thinkingLevel}:{},...e.role==="assistant"&&e.usage?{usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,totalTokens:e.usage.totalTokens,cost:e.usage.cost},cost:e.usage.cost.total}:{},...s?{finish:s}:{}},parts:n}},eE=e=>e?e.messages.map(t=>{const n=G0.get(t);if(n&&n.info.sessionID===e.sessionId)return n;const r=QI(t,e.sessionId);return G0.set(t,r),r}):[],tE=["chat","git","diff","terminal","files","diagram"],nE=["settings","skills","providers","git-identities"],Rr={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Jb(e){const t=rE();return{sessionId:sE(t),tab:oE(t),settingsPath:iE(t),diffFile:aE(t)}}function rE(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function sE(e){const t=e.get(Rr.SESSION)??e.get("s");if(t&&t.trim().length>0)return t.trim();if(typeof window<"u"){const n=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i);if(n?.[1])return decodeURIComponent(n[1].trim())}return null}function oE(e){const t=e.get(Rr.TAB);if(!t)return null;const n=t.toLowerCase().trim();return tE.includes(n)?n:null}function iE(e){const t=e.get(Rr.SETTINGS);if(!t)return null;const n=t.toLowerCase().trim();return n.length===0?null:n==="pichamber"||n==="general"||n==="preferences"?"home":(nE.includes(n),n)}function aE(e){const t=e.get(Rr.FILE);if(!t||t.trim().length===0)return null;try{return decodeURIComponent(t.trim())}catch{return t.trim()}}function FY(){if(typeof window>"u")return!1;try{const e=new URLSearchParams(window.location.search);return/^\/(?:session|s)\/[^/?#]+/i.test(window.location.pathname)||e.has(Rr.SESSION)||e.has("s")||e.has(Rr.TAB)||e.has(Rr.SETTINGS)||e.has(Rr.FILE)}catch{return!1}}const Lm=(e,t)=>e?.open===!0&&t===null,BY=e=>e.currentSessionId??(Lm(e.draft,e.currentSessionId)?null:e.piSelectedSessionId),cE=()=>{let e=!1,t,n;return(r,s,o=Object.is)=>{if(e&&Object.is(t,r))return n;const i=s(r);return e&&(typeof o=="function"?o:Object.is)(n,i)?(t=r,n):(e=!0,t=r,n=i,i)}},Qb="oc.lastSession.v1",lE=8,hf=()=>({version:1,runtimes:{}}),Rm=e=>{try{const t=e.getItem(Qb);if(!t)return hf();const n=JSON.parse(t);if(n.version!==1||!n.runtimes||typeof n.runtimes!="object")return hf();const r={};for(const[s,o]of Object.entries(n.runtimes))!s||!o||typeof o.sessionId!="string"||o.sessionId.length===0||(r[s]={sessionId:o.sessionId,directory:typeof o.directory=="string"&&o.directory.length>0?o.directory:null,updatedAt:typeof o.updatedAt=="number"?o.updatedAt:0});return{version:1,runtimes:r}}catch{return hf()}},ew=(e,t)=>{const n=Object.entries(t.runtimes).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,lE);try{e.setItem(Qb,JSON.stringify({...t,runtimes:Object.fromEntries(n)}))}catch{}};function dE(e,t,n=Gt()){if(!t.sessionId)return;const r=Rm(n),s=Object.values(r.runtimes).reduce((o,i)=>Math.max(o,i.updatedAt),0);r.runtimes[e]={...t,updatedAt:Math.max(Date.now(),s+1)},ew(n,r)}function np(e,t=Gt()){if(!e)return null;const n=Rm(t).runtimes[e];return n?{sessionId:n.sessionId,directory:n.directory}:null}function uE(e,t=Gt()){if(!e)return;const n=Rm(t);n.runtimes[e]&&(delete n.runtimes[e],ew(t,n))}const fE=120,hE=600,tw=typeof window<"u"&&typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"?window.__PICHAMBER_HARDWARE_KEYBOARD__:null;let od=tw===!0,Gd=tw!==null,na=null,pf=!1;const rp=new Set;od&&typeof document<"u"&&document.documentElement.classList.add("oc-hardware-keyboard");const Zd=()=>{na!==null&&(window.clearTimeout(na),na=null)},Yd=e=>{if(od!==e){od=e,typeof document<"u"&&document.documentElement.classList.toggle("oc-hardware-keyboard",e);for(const t of rp)t()}},pE=()=>{if(typeof window>"u")return()=>{};const e=n=>{Gd=!0,Zd(),Yd(n)};if(typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"&&e(window.__PICHAMBER_HARDWARE_KEYBOARD__),pf)return()=>{};pf=!0;const t=n=>{const r=n.detail;e(r?.attached===!0)};return window.addEventListener("oc:hardware-keyboard",t),()=>{window.removeEventListener("oc:hardware-keyboard",t),pf=!1}},Z0=e=>{Gd||!Number.isFinite(e)||(Zd(),Yd(e>0&&e<fE))},mE=()=>{Gd||typeof window>"u"||typeof document>"u"||document.documentElement.classList.contains("oc-keyboard-open")||(Zd(),na=window.setTimeout(()=>{na=null,Yd(!0)},hE))},gE=()=>{Zd(),!Gd&&Yd(!1)},yE=()=>od,vE=e=>(rp.add(e),()=>{rp.delete(e)});function xE(){return p.useSyncExternalStore(vE,yE,()=>!1)}const Ho=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0?!0:window.location.protocol==="capacitor:",VY=()=>{p.useEffect(()=>{if(!Ho())return;let e=!1;const t=[],n=document.documentElement;n.classList.add("oc-capacitor-app"),window.Capacitor?.getPlatform?.()==="android"&&n.classList.add("oc-platform-android"),nw(),t.push(pE());const s=o=>{n.style.setProperty("--oc-keyboard-inset",`${Math.max(0,Math.round(o))}px`)};return mt(()=>import("./vendor-capacitor-status-bar-DV24OoQV.js"),__vite__mapDeps([4,5,1,6])).then(async({StatusBar:o,Style:i})=>{if(e)return;const a=window.Capacitor?.getPlatform?.(),l=async()=>{if(a==="android"){const h=document.documentElement.classList.contains("dark"),m=(h?localStorage.getItem("splashBgDark"):localStorage.getItem("splashBgLight"))||(h?"#171515":"#fffdf4");await o.setOverlaysWebView({overlay:!1}).catch(()=>{}),await o.setBackgroundColor({color:m}).catch(()=>{}),await o.setStyle({style:h?i.Dark:i.Light}).catch(()=>{}),await o.show().catch(()=>{});return}await o.setStyle({style:i.Default}).catch(()=>{}),await o.setOverlaysWebView({overlay:!0}).catch(()=>{}),await o.show().catch(()=>{})};await l();const d=window.setTimeout(()=>{l()},400);t.push(()=>window.clearTimeout(d));const{App:f}=await mt(async()=>{const{App:h}=await import("./vendor-capacitor-app-NX6DULfp.js");return{App:h}},__vite__mapDeps([7,8,5,1,6])),u=await f.addListener("appStateChange",({isActive:h})=>{h&&l()});if(e){u.remove();return}t.push(()=>{u.remove()})}).catch(()=>{}),mt(()=>import("./vendor-capacitor-keyboard-DJD81I9f.js"),__vite__mapDeps([9,5,1,6])).then(async({Keyboard:o})=>{if(e)return;if(window.Capacitor?.getPlatform?.()==="android"){const _=await o.addListener("keyboardWillShow",O=>{Z0(O.keyboardHeight),n.classList.add("oc-keyboard-open"),window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),k=await o.addListener("keyboardDidShow",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),E=await o.addListener("keyboardWillHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-intent",{detail:{open:!1}})),n.classList.remove("oc-keyboard-open")}),I=await o.addListener("keyboardDidHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!1}}))}),N=()=>{_.remove(),k.remove(),E.remove(),I.remove()};if(e){N();return}t.push(N);return}await o.setAccessoryBarVisible({isVisible:!1}).catch(()=>{});const a=250,l=200,d="cubic-bezier(0.38, 0.7, 0.125, 1)";let f=null,u=null,h=0,m=!1,g=0,x=!1;const b=(_,k)=>{n.style.setProperty(_,`${Math.max(0,Math.round(k))}px`)},S=()=>{f!==null&&(window.clearTimeout(f),f=null)},y=(_,k)=>{window.dispatchEvent(new CustomEvent(_,{detail:k}))},v=()=>{const _=[],k=document.querySelector(".oc-mobile-composer");k&&_.push({el:k,factor:1});const E=document.querySelector(".oc-draft-center");return E&&_.push({el:E,factor:.5}),_},C=()=>{for(const{el:_}of v())_.style.transition="",_.style.transform=""},w=await o.addListener("keyboardWillShow",_=>{if(S(),Z0(_.keyboardHeight),x=!0,h=_.keyboardHeight,!m){const E=document.querySelector(".oc-mobile-app-shell");g=E&&parseFloat(getComputedStyle(E).paddingBottom)||0}const k=Math.max(0,h-g);n.classList.remove("oc-kb-hide"),u!==null&&(window.clearTimeout(u),u=null),n.classList.add("oc-keyboard-open","oc-kb-animating","oc-kb-caret-hold"),s(h);for(const{el:E,factor:I}of v())E.style.transition=`transform ${a}ms ${d}`,E.style.transform=`translateY(${-k*I}px)`;b("--oc-kb-scroll-inset",k),y("oc:keyboard-settled",{open:!0}),y("oc:keyboard-anim",{phase:"show",slide:k,durationMs:a,easing:d}),f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",h),m=!0,C(),y("oc:keyboard-settled",{open:!0}),u=window.setTimeout(()=>{u=null,n.classList.remove("oc-kb-caret-hold")},250)},a+20)}),M=()=>{if(!x)return;x=!1,S(),y("oc:keyboard-intent",{open:!1}),u!==null&&(window.clearTimeout(u),u=null),n.classList.remove("oc-kb-caret-hold");const _=Math.max(0,h-g);if(n.classList.remove("oc-keyboard-open"),s(0),b("--oc-kb-scroll-inset",0),m){n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",0),m=!1;for(const{el:k,factor:E}of v())k.style.transition="none",k.style.transform=`translateY(${-_*E}px)`;document.querySelector(".oc-mobile-app-shell")?.offsetHeight}y("oc:keyboard-anim",{phase:"hide",slide:_,durationMs:l,easing:d}),n.classList.add("oc-kb-animating","oc-kb-hide");for(const{el:k}of v())k.style.transition=`transform ${l}ms ${d}`,k.style.transform="translateY(0px)";f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating","oc-kb-hide"),C(),y("oc:keyboard-settled",{open:!1})},l+20)},j=await o.addListener("keyboardWillHide",M),T=_=>_ instanceof HTMLElement&&(_.tagName==="TEXTAREA"||_.tagName==="INPUT"||_.isContentEditable),A=_=>{x&&T(_.target)&&(T(_.relatedTarget)||window.setTimeout(()=>{x&&(T(document.activeElement)||M())},0))};if(document.addEventListener("focusout",A,!0),e){S(),document.removeEventListener("focusout",A,!0),w.remove(),j.remove();return}t.push(S,()=>{u!==null&&(window.clearTimeout(u),u=null)},()=>document.removeEventListener("focusout",A,!0),()=>{w.remove()},()=>{j.remove()})}).catch(()=>{}),()=>{e=!0,t.forEach(o=>o()),gE(),n.classList.remove("oc-capacitor-app","oc-keyboard-open","oc-kb-animating","oc-kb-hide","oc-kb-caret-hold","oc-platform-android"),n.style.removeProperty("--oc-keyboard-inset"),n.style.removeProperty("--oc-kb-shift"),n.style.removeProperty("--oc-kb-layout"),n.style.removeProperty("--oc-kb-scroll-inset")}},[])},$Y=e=>{const t=p.useRef(!1);p.useEffect(()=>{if(!Ho())return;let n=!1;const r=[],s=()=>{t.current&&(t.current=!1,e())},o=()=>{if(document.visibilityState==="hidden"){t.current=!0,Nr("app-lifecycle",{code:"hidden"});return}Nr("app-lifecycle",{code:"visible"}),s()};return document.addEventListener("visibilitychange",o),r.push(()=>document.removeEventListener("visibilitychange",o)),mt(()=>import("./vendor-capacitor-app-NX6DULfp.js"),__vite__mapDeps([7,8,5,1,6])).then(async({App:i})=>{if(n)return;const a=await i.addListener("appStateChange",({isActive:d})=>{if(document.documentElement.classList.toggle("oc-native-app-active",d),Nr("app-lifecycle",{code:d?"resume":"pause"}),!d){t.current=!0;return}s()}),l=await i.addListener("resume",()=>{Nr("app-lifecycle",{code:"resume"}),s()});if(n){a.remove(),l.remove();return}r.push(()=>{a.remove()},()=>{l.remove()})}).catch(()=>{}),()=>{n=!0,r.forEach(i=>i())}},[e])},ra=[];let mf=null;const bE=()=>{for(let e=ra.length-1;e>=0;e--)try{if(ra[e]())return!0}catch{}return!1},nw=()=>Ho()?(mf||(mf=mt(async()=>{const{App:e}=await import("./vendor-capacitor-app-NX6DULfp.js");return{App:e}},__vite__mapDeps([7,8,5,1,6])).then(({App:e})=>e.addListener("backButton",()=>{bE()||e.minimizeApp().catch(()=>{})})).catch(()=>null)),mf.then(()=>{})):Promise.resolve(),zY=e=>{const t=p.useRef(e);t.current=e,p.useEffect(()=>{if(!Ho())return;nw();const n=()=>t.current();return ra.push(n),()=>{const r=ra.lastIndexOf(n);r!==-1&&ra.splice(r,1)}},[])},rw=p.createContext(null),La=()=>p.useContext(rw)??Ue(),UY=({children:e,directory:t})=>{const n=p.useMemo(()=>Ue(),[]),r=at(o=>o.projects.find(i=>i.id===o.activeProjectId)?.path??null),s=t?.trim()||r;return H.useEffect(()=>{const o=Jb(),i=pe.getState(),a=Lm(i.newSessionDraft,i.currentSessionId);if(o.sessionId&&!a){const d=n.getState();if(d.selectedSessionId===o.sessionId&&d.connection==="ready")return;n.start({directory:s??void 0,sessionId:o.sessionId});return}if(!s){if(!a&&!Ho()){const d=np(Y());if(d?.sessionId){n.start({sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.connectWithoutProject();return}const l=a?null:n.lastSelectedSessionForDirectory(s);if(l){n.start({directory:s,sessionId:l,sessionDirectoryKnown:!0});return}if(!a&&!Ho()){const d=np(Y());if(d?.sessionId){n.start({directory:s,sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.start({directory:s})},[n,s]),c.jsx(rw.Provider,{value:n,children:e})},wE=e=>e;function ze(e,t,n="*",r=""){const s=La(),o=H.useRef(e);o.current=e;const i=H.useRef(t);i.current=t;const a=H.useRef(null),l=`${n}\0${r}`;a.current?.key!==l&&(a.current={key:l,select:cE()});const d=H.useCallback(()=>{const u=o.current??wE,h=typeof i.current=="function"?i.current:Object.is;return a.current.select(s.getState(),u,h)},[s]),f=H.useMemo(()=>u=>s.subscribe(u,n),[s,n]);return H.useSyncExternalStore(f,d,d)}const sw={type:"idle"},SE={type:"busy"},CE={type:"retry"},Y0=new WeakMap,kE=[],ME=[],X0={loading:!1,complete:!0,status:"ready",cursor:void 0,error:null,errorCode:null},J0=[],Q0=new WeakMap,Yo="catalog",An="chrome",Kt=e=>`session:${e}`,IE=(e,t)=>{if(e==="busy")return SE;if(e!=="retry")return sw;if(!t)return CE;const n=Y0.get(t);if(n)return n;const r={type:"retry",...t};return Y0.set(t,r),r};function EE(e){const t=e?.archived??!1,n=e?.directory;return ze(r=>Sa(r.catalog,{archived:t,directory:n}),Gb,Yo)}function qY(e,t){return Xd(e)}function WY(e){const t=ze(n=>n.catalog.byId,void 0,Yo);if(e)return t.get(e)?.pendingInput}function ow(){return ze(e=>jm(e.catalog),LI,Yo)}function gf(e,t){Ue().select(t,e||void 0)}function Pm(e,t){const n=Qd(e);return H.useMemo(()=>n.map(r=>r.info),[n])}function jE(e,t,n){const r=ze(a=>e?a.reducer.bySession.get(e)??null:null,void 0,e?Kt(e):"*"),s=ze(a=>e?null:a.reducer.bySession,void 0,e?Kt(e):"*"),o=H.useMemo(()=>{if(e||!t||n!==void 0||!s)return null;for(const a of s.values())if(a.messages.has(t))return a;return null},[s,t,e,n]),i=r??o;return H.useMemo(()=>{if(!t||!i)return J0;const a=i.messages.get(t);if(!a)return J0;const l=i.partOrder.get(t)??[];if(l.length>0){const f=[];for(const u of l){const h=i.parts.get(u);if(!h)continue;const m=Q0.get(h);if(m){f.push(m);continue}const g=Nm({id:h.id,type:h.type,text:h.text,streaming:h.streaming,...h.tool?{tool:h.tool}:{},...h.attachment?{attachment:h.attachment}:{}},{full:!0});Q0.set(h,g),f.push(g)}return f}const d=[];return a.thinking&&d.push({id:`${a.id}:thinking`,type:"reasoning",text:a.thinking,streaming:!1}),a.text&&d.push({id:`${a.id}:text`,type:"text",text:a.text}),d},[t,i])}function Xd(e,t){const n=ze(s=>s.catalog.byId,void 0,Yo);if(!e)return sw;const r=n.get(e);return IE(r?.lifecycle,r?.retry)}function iw(){return ze(e=>e.connection,void 0,An)}function _E(e){return ze(t=>e?t.reducer.bySession.get(e)?.compaction??null:null,void 0,e?Kt(e):"*")}function Jd(e){return ze(t=>e?t.reducer.bySession.get(e)?.runningCommand??null:null,void 0,e?Kt(e):"*")}const e2=[];function aw(e){return ze(t=>e?t.reducer.bySession.get(e)?.extensionNotices??e2:e2,(t,n)=>t.length===n.length&&t.every((r,s)=>r.id===n[s]?.id),e?Kt(e):"*")}const t2=[];function TE(e){return ze(t=>e?t.reducer.bySession.get(e)?.bashExecutions??t2:t2,void 0,e?Kt(e):"*")}function AE(e){return ze(t=>!!(e&&t.reducer.bySession.get(e)?.bashExecutions?.length),void 0,e?Kt(e):"*")}function cw(){const e=ze(t=>t.directory,void 0,An);return EE({archived:!1,directory:e||null})}function KY(e,t){const n=ze(s=>s.catalog.byId,void 0,Yo),r=e?n.get(e)??null:null;return r?Or(r):void 0}function NE(e){const t=ze(s=>s.catalog.byId,void 0,Yo),n=ze(s=>s.directory,void 0,An);return(e?t.get(e)?.directory:void 0)??n??void 0}function LE(){return ze(e=>e.directory??"",void 0,An)}function RE(e,t){const n=ze(a=>a.hydratedSessionIds,void 0,An),r=ze(a=>a.selectedSessionId,void 0,An),s=ze(a=>a.connection,void 0,An),o=ze(a=>a.error,void 0,An),i=ze(a=>a.sessionLoadErrorById,void 0,An);return H.useMemo(()=>{if(!e||n.has(e))return X0;const l=i.get(e)??(s==="error"&&o?o:null);if(l)return{loading:!1,complete:!1,status:"error",cursor:void 0,error:l.message??"Session load failed",errorCode:l.code};const d=r===e||s==="loading";return{loading:d,complete:!1,status:d?"loading":"ready",cursor:void 0,error:null,errorCode:null}},[s,o,n,r,e,i])}function lw(e,t){const n=ze(r=>r.hydratedSessionIds,void 0,An);return!e||n.has(e)}function PE(e){const t=ze(n=>e?n.reducer.bySession.get(e)??null:null,(n,r)=>Object.is(n,r)?!0:!n||!r?!1:cI(n,r),e?Kt(e):"*");return H.useMemo(()=>{if(!t)return kE;const n=[],r=new Set,s=[];for(const o of t.messages.values())o.role!=="user"||r.has(o.id)||(r.add(o.id),s.push(o));s.sort((o,i)=>o.createdAt-i.createdAt);for(const o of s){const i=t.partOrder.get(o.id)??[],a=i.length>0?i.map(l=>t.parts.get(l)).filter(l=>l?.type==="text").map(l=>l?.text??"").join(""):o.text??"";a&&n.push(a)}return n},[t])}function DE(e){return ze(t=>xa(e?t.reducer.bySession.get(e)??null:null),Object.is,e?Kt(e):"*")}function OE(e){return ze(t=>Ub(e?t.reducer.bySession.get(e)??null:null),Object.is,e?Kt(e):"*")}function Qd(e,t,n){const r=n?.suspendPartUpdates!==!1,s=null,o=ze(a=>e?a.reducer.bySession.get(e)??null:null,(a,l)=>{if(Object.is(a,l)||a&&l&&iI(a,l))return!0;if(!a||!l)return!1;const d=xa(l);return d?Qh(a,l,d):!1},e?Kt(e):"*"),i=H.useRef(null);return H.useMemo(()=>{if(!o)return i.current=null,ME;const a=i.current,l=xa(o);if(l&&a&&a.sessionId===e&&Qh(a.session,o,l))return i.current={sessionId:e,session:o,projection:a.projection,records:a.records},a.records;const d=Y5(o,a&&a.sessionId===e?{session:a.session,projection:a.projection}:null),f=eE(d),u=a?.records,h=u&&u.length===f.length&&u.every((m,g)=>m===f[g])?u:f;return i.current={sessionId:e,session:o,projection:d,records:h},h},[s,o,e,r])}function HE(e,t,n){const r=La(),s=n&&e?Kt(e):An,o=H.useMemo(()=>l=>r.subscribe(l,s),[r,s]),i=H.useCallback(()=>!n||!e||!t?null:r.getState().reducer.bySession.get(e)?.parts.get(t)??null,[n,t,e,r]),a=H.useSyncExternalStore(o,i,i);return H.useMemo(()=>!n||!a?null:Nm({id:a.id,type:a.type,text:a.text,streaming:a.streaming,...a.tool?{tool:a.tool}:{},...a.attachment?{attachment:a.attachment}:{}},{full:!0}),[n,a])}function FE(e,t){return ze(n=>e?n.reducer.bySession.get(e)?.messages.size??0:0,void 0,e?Kt(e):"*")}function BE(e){const t=La(),n=ze(o=>!!(e&&o.reducer.bySession.get(e)?.hasMoreBefore),void 0,e?Kt(e):"*"),r=ze(o=>e?o.reducer.bySession.get(e)?.beforeCursor:void 0,void 0,e?Kt(e):"*"),s=H.useCallback(()=>e?t.loadOlderMessages(e):Promise.resolve(!1),[e,t]);return{hasMoreBefore:n,beforeCursor:r,loadOlder:s}}function VE(e,t,n=!0){const r=La();!n||!e||r.ensureHydrated(e)}const Ot=()=>Ue();async function $E(e,t,n,r){const s=await Ot().create(e,{...t?{directory:t}:{},...r?.model?{model:r.model}:{},...r?.thinking?{thinking:r.thinking}:{},...r?.select===!1?{select:!1}:{}}),o=Ot().getState().sessions.find(i=>i.session.id===s||i.session.id===Ot().getState().selectedSessionId);return o?JI(o.session):null}async function zE(e,t){return await Ot().remove(e),!0}async function UE(e,t){const n=[],r=[];for(const s of e)try{await Ot().remove(s),n.push(s)}catch{r.push(s)}return{deletedIds:n,failedIds:r}}async function qE(e){return await Ot().archive(e,!0),!0}async function WE(e,t){for(const n of e)await Ot().archive(n,!0);return{archivedIds:e,failedIds:[]}}async function KE(e){return await Ot().archive(e,!1),!0}async function GE(e,t){for(const n of e)await Ot().archive(n,!1);return{restoredIds:e,failedIds:[]}}async function ZE(e,t){await Ot().rename(e,t)}async function YE(e){return null}async function XE(e){return null}async function JE(e,t){const r=(await Ot().navigate(e,t))?.navigation?.editorText;if(typeof r=="string"&&r.length>0)try{Ye.getState().setPendingRevertText(r)}catch{}}async function QE(e,t){if(!Im(e))throw new Error("No reverted conversation is available to restore.");await Ot().navigate(e,t)}async function ej(e){const t=Im(e)?.previousLeafId;if(!t)throw new Error("No reverted conversation is available to restore.");await Ot().navigate(e,t)}async function tj(e,t){await Ot().fork(e,t)}async function nj(){const e=Ot().getState();if(e.connection!=="ready")throw e.error??new Error("Pi runtime is unavailable")}async function rj(e,t){await Ot().compact(e,t)}async function dw(e){await Ot().abortBash(e)}function Dm(e){e&&Ot().abort(e)}const sj=e=>{if(typeof e!="string")return"attachment";const n=e.replace(/[\\/]/g,"_").replace(/\.\.+/g,"_").replace(/[\x00-\x1f\x7f]/g,"").replace(/^\.+/,"").trim();return n.length===0?"attachment":n.length>200?n.slice(0,200):n};function n2(e){const t=Ue().getState(),n=t.reducer.bySession.get(e),r=t.sessions.find(s=>s.session.id===e)?.session;return{model:n?.model??r?.model,thinking:n?.thinking??r?.thinking}}async function sp(e){const t=e.delivery==="steer"||e.delivery==="followUp"?e.delivery:"prompt",n=e.runtimeKey??Y(),r=()=>{if(n!==Y())throw new Error("Runtime changed before sending message.")};r();const s=Ue();let o=!1;if(e.sessionId&&e.providerID&&e.modelID){const l=n2(e.sessionId).model;(!l||l.providerId!==e.providerID||l.modelId!==e.modelID)&&(await s.setModel(e.sessionId,e.providerID,e.modelID),r(),o=!0)}if(e.sessionId&&Ft(e.variant)){const l=n2(e.sessionId).thinking;(o||l!==e.variant)&&(await s.setThinking(e.sessionId,e.variant),r())}const i=[...e.files??[],...(e.additionalParts??[]).flatMap(l=>l.files??[])].filter(l=>l.uploadState!==void 0||l.url.startsWith("data:")),a=[];try{const l=await Promise.all(i.map(async f=>{const u=f.uploadState;if(u?.status==="preparing"||u?.status==="uploading")throw new Error("Attachments are still uploading.");if(u?.status==="failed")throw new Error("Retry or remove failed attachments.");if(u?.status==="ready"&&u.expiresAt>Date.now())return{id:u.attachmentId};if(typeof f.url=="string"&&f.url.startsWith("data:")){const m=await(await fetch(f.url)).blob();r();const g=await s.uploadFile(m,{filename:sj(f.filename),mime:f.mime});return a.push(g.id),{id:g.id}}throw new Error("Attachment data is unavailable. Remove the attachment and add it again.")}));r();const d=l.length>0?l:void 0;await s.prompt(e.sessionId,e.content,t,d,{...e.knownEmptyTranscript?{knownEmptyTranscript:!0}:{},...e.operationId?{operationId:e.operationId}:{},...e.streamEpoch?{streamEpoch:e.streamEpoch}:{},...e.directory?{directory:e.directory}:{},runtimeKey:n})}catch(l){throw typeof l=="object"&&l!==null&&l.name==="PiSendUnconfirmedError"||await Promise.all((n===Y()?a:[]).map(d=>s.deleteUpload(d).catch(()=>{}))),l}}function oj(e){const t=de(e.session?.directory??e.currentDirectory??null);return{directory:t,source:t?"session":void 0}}function GY(e){return""}const bl={id:null,open:!1,directoryOverride:null,branchIntent:null,worktreeIntent:null,parentID:null},uw=(e,t,n)=>!!(e.open&&e.id&&e.id===n&&t===null),fw=e=>de(e.directory??null),hw=Gt(),pw="oc.chatInput.lastDraftTarget",ij=()=>{try{const e=hw.getItem(pw);if(!e)return null;const t=JSON.parse(e);return{projectId:typeof t?.projectId=="string"?t.projectId:null,directory:de(typeof t?.directory=="string"?t.directory:null)}}catch{return null}},op=e=>{try{hw.setItem(pw,JSON.stringify(e))}catch{}},aj=e=>{const t=Tm().find(s=>s.id===e),n=t?fw(t):null;if(n)return de(n);const r=GI(e);return r?de(r):null},id=new Map,yf=new Map,ir=e=>(e??Y()).trim()||"default",ip=e=>({...e}),Gs=(e,t)=>{const n=id.get(e);id.set(e,{sessionId:n?.sessionId??null,directory:n?.directory??null,draft:n?.draft?ip(n.draft):{...bl},...t})},cj=e=>{const t=ir(),n=id.get(t),r=np(t);return{runtime:n?.sessionId===e?de(n.directory):null,persisted:r?.sessionId===e?de(r.directory):null}};let eu=null;const r2=()=>eu,lj=e=>{eu=e},s2=()=>{eu=null},dj=(e,t)=>({session:Tm().find(n=>n.id===e)??null,currentDirectory:e===eu?null:de(t)}),o2=(e,t=null)=>e?oj(dj(e,t))?.directory??null:null,ap=async e=>{await We.getState().activateDirectory(de(e))},sa=(e,t)=>!e||!t?!1:e.runtimeKey===t.runtimeKey&&de(e.directory)===de(t.directory)&&e.branch===t.branch;async function uj(e,t){const n=t.getState(),r=e.draftSnapshot??n.newSessionDraft;if(!r?.open)return null;if(r.branchIntent){const g=de(r.branchIntent.directory),x=de(r.directoryOverride);if(r.branchIntent.runtimeKey!==Y()||g!==x)throw new Error("The selected branch no longer matches this draft target.");if(!sa(r.branchIntent,e.branchCheckoutReceipt))throw new Error("Confirm the selected branch before creating this session.")}if(r.worktreeIntent){const g=e.worktreeCreationReceipt;if(!g||g.runtimeKey!==r.worktreeIntent.runtimeKey||de(g.projectRoot)!==de(r.worktreeIntent.projectRoot)||de(g.sourceDirectory)!==de(r.worktreeIntent.sourceDirectory)||g.startRef!==r.worktreeIntent.startRef||!de(g.path))throw new Error("Create the selected worktree before creating this session.")}const s=r.permissionAutoAcceptEnabled===!0,o=typeof e.agent=="string"&&e.agent.trim().length>0?e.agent.trim():void 0,i=e.worktreeCreationReceipt?.path??r.directoryOverride??null,a=r.selectedProjectId??null,l=r.title||(e.initialPrompt&&!e.initialPrompt.trimStart().startsWith("/")?Ah(e.initialPrompt):void 0),d=await n.createSession(l,i,r.parentID??null,{model:e.providerID&&e.modelID?{providerId:e.providerID,modelId:e.modelID}:void 0,thinking:Ft(e.variant)?e.variant:void 0,select:!1},{draftSnapshot:r,closeDraft:!1});if(!d?.id)throw new Error("Failed to create session");const f=de(d.directory??i??null),u=t.getState().newSessionDraft===r&&t.getState().currentSessionId===null;u&&op({projectId:a,directory:f});const h=r.syntheticParts;u&&ap(f).catch(g=>{console.warn("Failed to activate directory after creating session:",g)});const m=o;return At.getState().saveSessionModelSelection(d.id,e.providerID,e.modelID),m&&(At.getState().saveSessionAgentSelection(d.id,m),At.getState().saveAgentModelForSession(d.id,m,e.providerID,e.modelID),At.getState().saveAgentModelVariantForSession(d.id,m,e.providerID,e.modelID,e.variant)),u&&n.setCurrentSession(d.id,f),s&&mt(async()=>{const{usePermissionStore:g}=await import("./permissionStore-zIpxq9Pq.js");return{usePermissionStore:g}},__vite__mapDeps([10,11,1])).then(({usePermissionStore:g})=>g.getState().setSessionAutoAccept(d.id,!0)).catch(g=>{console.warn("Failed to apply draft permission auto-accept to new session:",g)}),{sessionId:d.id,directory:f,agent:m,syntheticParts:h}}let i2=0;const fj=()=>(i2+=1,`draft-${Date.now()}-${i2}`);async function cp(e){return uj(e,pe)}const pe=Lt()((e,t)=>({currentSessionId:null,currentSessionDirectory:null,newSessionDraft:{...bl},abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,webUICreatedSessions:new Set,sessionAbortFlags:new Map,sendingNewSessionDraftId:null,pendingChangesBarDismissed:new Map,setCurrentSession:(n,r)=>{n&&t().closeNewSessionDraft();const s=ir();yf.set(s,n);const o=nt.getState(),i=o2(n),a=Ue().getState().directory??o.currentDirectory??null,l=(r?de(r):null)??i,d=l??a,f=l===null,u=at.getState(),h=d?Zn(u.projects,Ln(u.projects,Qt.getState()),d):null;e({currentSessionId:n,currentSessionDirectory:n?d??null:null}),lj(f&&n?n:null);const m=f?null:d??null;Gs(s,{sessionId:n,directory:m}),n&&dE(s,{sessionId:n,directory:m}),n&&Ue().select(n,f?void 0:d);try{d&&o.currentDirectory!==d&&o.setDirectory(d,{showOverlay:!1}),h&&u.activeProjectId!==h.id&&u.setActiveProjectIdOnly(h.id)}catch(g){console.warn("Failed to set Pi directory for session switch:",g)}n&&(zd(n),gf(d??"",n))},prepareForRuntimeSwitch:n=>{const r=ir(n),s=nt.getState().currentDirectory||null,o=t().currentSessionId;yf.set(r,t().currentSessionId),Gs(r,{sessionId:o,directory:s,draft:ip(t().newSessionDraft)})},restoreForRuntimeSwitch:n=>{const r=ir(n),s=id.get(r),o=s?.sessionId??yf.get(r)??null,i=s?.draft?ip(s.draft):{...bl},a=s?.directory??null;a&&nt.getState().setDirectory(a,{showOverlay:!1}),e({currentSessionId:o,currentSessionDirectory:o?a:null,newSessionDraft:o?{...bl}:i,abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,sendingNewSessionDraftId:null,sessionAbortFlags:new Map,pendingChangesBarDismissed:new Map}),o?gf(a??Ue().getState().directory??"",o):gf("","")},openNewSessionDraft:n=>{n?.automatic||uE(ir());const r=at.getState(),s=r.projects,o=Ln(s,Qt.getState()),i=r.getActiveProject(),a=de(nt.getState().currentDirectory??null),l=ij(),d="__home__",f=n?.selectedProjectId===d,u=n?.directoryOverride!==void 0?de(n.directoryOverride):null,h=n?.selectedProjectId?f?{id:d,path:u??""}:s.find(T=>T.id===n.selectedProjectId)??null:null,m=Zn(s,o,u),g=i||(r.activeProjectId?s.find(T=>T.id===r.activeProjectId)??null:s[0]??null),x=l?.projectId===d,b=l?.projectId?x?{id:d,path:l.directory??""}:s.find(T=>T.id===l.projectId)??null:null,S=Zn(s,o,l?.directory??null),y=Zn(s,o,a),v=f||h?h:u!==null?m:a?y:x?b:S??b??g,C=u!==null?u:f?u??de(nt.getState().homeDirectory||Gt().getItem("homeDirectory")||"~")??u:h?de(h.path??null):a||(l?.directory?l.directory:de(v?.path??null)),w=f?d:v?.id??null;op({projectId:w,directory:C});const M={id:fj(),open:!0,selectedProjectId:w,directoryOverride:C,branchIntent:n?.branchIntent&&n.branchIntent.runtimeKey===Y()&&de(n.branchIntent.directory)===C?n.branchIntent:null,worktreeIntent:n?.worktreeIntent&&n.worktreeIntent.runtimeKey===Y()&&de(n.worktreeIntent.sourceDirectory)===C?n.worktreeIntent:null,permissionAutoAcceptEnabled:n?.permissionAutoAcceptEnabled===!0,preserveDirectoryOverride:n?.preserveDirectoryOverride===!0,parentID:n?.parentID??null,title:n?.title,initialPrompt:n?.initialPrompt,syntheticParts:n?.syntheticParts,targetFolderId:n?.targetFolderId};e({newSessionDraft:{...M},currentSessionId:null,currentSessionDirectory:null,error:null}),Gs(ir(),{sessionId:null,directory:C,draft:M}),n?.initialPrompt&&Ye.getState().setPendingInputText(n.initialPrompt);const j=de(v?.path??null)??C;ap(j),C&&C!==nt.getState().currentDirectory&&nt.getState().setDirectory(C)},closeNewSessionDraft:()=>{const n=t().newSessionDraft;if(!n.open&&n.selectedProjectId==null&&n.directoryOverride==null&&n.branchIntent==null&&n.worktreeIntent==null&&!n.preserveDirectoryOverride&&n.parentID==null&&n.title===void 0&&n.initialPrompt===void 0&&n.syntheticParts===void 0&&n.targetFolderId===void 0&&n.permissionAutoAcceptEnabled===void 0)return;const r={id:null,open:!1,selectedProjectId:null,directoryOverride:null,branchIntent:null,worktreeIntent:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0};e({newSessionDraft:r}),Gs(ir(),{draft:r})},setNewSessionDraftTarget:n=>{let r=null,s=null;e(o=>{r=de(n.directoryOverride??o.newSessionDraft.directoryOverride),s=n.projectId??n.selectedProjectId??o.newSessionDraft.selectedProjectId??null;const i=Object.prototype.hasOwnProperty.call(n,"branchIntent"),a=Object.prototype.hasOwnProperty.call(n,"worktreeIntent"),l=de(o.newSessionDraft.directoryOverride),d=r!==l,f=s!==(o.newSessionDraft.selectedProjectId??null),u=n.branchIntent,h=u&&u.runtimeKey===Y()&&de(u.directory)===r?u:null,m=n.worktreeIntent,g=m&&m.runtimeKey===Y()&&de(m.sourceDirectory)===r?m:null;return{newSessionDraft:{...o.newSessionDraft,selectedProjectId:s,directoryOverride:n.directoryOverride??o.newSessionDraft.directoryOverride,branchIntent:i?h:d||f?null:o.newSessionDraft.branchIntent,worktreeIntent:a?g:d||f?null:o.newSessionDraft.worktreeIntent}}}),op({projectId:s,directory:r}),ap(r),r&&r!==nt.getState().currentDirectory&&nt.getState().setDirectory(r)},setDraftPreserveDirectoryOverride:n=>e(r=>r.newSessionDraft?.open?{newSessionDraft:{...r.newSessionDraft,preserveDirectoryOverride:n}}:r),setDraftPermissionAutoAcceptEnabled:n=>e(r=>r.newSessionDraft?.open?{newSessionDraft:{...r.newSessionDraft,permissionAutoAcceptEnabled:n}}:r),acknowledgeSessionAbort:n=>e(r=>{const s=new Map(r.sessionAbortFlags),o=s.get(n);return o&&s.set(n,{...o,acknowledged:!0}),{sessionAbortFlags:s}}),clearAbortPrompt:()=>e({abortPromptSessionId:null,abortPromptExpiresAt:null}),armAbortPrompt:(n=5e3)=>{const{currentSessionId:r}=t();if(!r)return null;const s=Date.now()+n;return e({abortPromptSessionId:r,abortPromptExpiresAt:s}),s},clearError:()=>e({error:null}),setSendingNewSessionDraftId:n=>{t().sendingNewSessionDraftId!==n&&e({sendingNewSessionDraftId:n})},markSessionAsPiChamberCreated:n=>e(r=>{const s=new Set(r.webUICreatedSessions);return s.add(n),{webUICreatedSessions:s}}),isPiChamberCreatedSession:n=>t().webUICreatedSessions.has(n),dismissPendingChangesBar:(n,r)=>{const s=new Map(t().pendingChangesBarDismissed);r===null?s.delete(n):s.set(n,r),e({pendingChangesBarDismissed:s})},sendMessage:async(n,r,s,o,i,a,l,d,f,u)=>{const h=u?.target;if(h&&h.runtimeKey!==Y())throw new Error("Message was not sent because the runtime changed.");const m=h?.sessionId??u?.sessionId??(u?.draftSnapshot?null:t().currentSessionId);if(m){const w=new Map(t().pendingChangesBarDismissed);w.delete(m),e({pendingChangesBarDismissed:w})}const g=t().newSessionDraft,x=typeof o=="string"&&o.trim().length>0?o.trim():void 0;if(f==="shell"){let w=h?.sessionId??u?.sessionId??null;if(!w&&(u?.draftSnapshot?.open||g?.open)){const M=await cp({providerID:r,modelID:s,agent:x,variant:d,branchCheckoutReceipt:u?.branchCheckoutReceipt,worktreeCreationReceipt:u?.worktreeCreationReceipt,draftSnapshot:u?.draftSnapshot});if(!M)throw new Error("Failed to create session");w=M.sessionId}if(w??=t().currentSessionId,!w)throw new Error("Select a session to run a shell command.");await Ue().runBash(w,n,{excludeFromContext:u?.shellExcludeFromContext===!0});return}if(!h&&!u?.sessionId&&(u?.draftSnapshot?.open||g?.open)){const w=await cp({providerID:r,modelID:s,agent:x,variant:d,initialPrompt:n,branchCheckoutReceipt:u?.branchCheckoutReceipt,worktreeCreationReceipt:u?.worktreeCreationReceipt,draftSnapshot:u?.draftSnapshot,initialInputKind:u?.initialInputKind});if(!w)throw new Error("Failed to create session");const M=w.syntheticParts?.length?[...l||[],...w.syntheticParts]:l;K0(w.sessionId);const j=i?.map(T=>({type:"file",mime:T.mimeType,url:T.dataUrl,filename:T.filename,uploadState:T.uploadState}));await sp({sessionId:w.sessionId,directory:w.directory,content:n,providerID:r,modelID:s,agent:w.agent,agentMentionName:a,variant:d,inputMode:f,files:j,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,knownEmptyTranscript:!0,additionalParts:M?.map(T=>({text:T.text,synthetic:T.synthetic,files:T.attachments?.map(A=>({type:"file",mime:A.mimeType,url:A.dataUrl,filename:A.filename,uploadState:A.uploadState}))}))});return}const b=h?.sessionId??u?.sessionId??t().currentSessionId,S=b?At.getState().getSessionAgentSelection(b):null,y=x||S||void 0;b&&At.getState().saveSessionModelSelection(b,r,s),b&&y&&(At.getState().saveSessionAgentSelection(b,y),At.getState().saveAgentModelForSession(b,y,r,s),At.getState().saveAgentModelVariantForSession(b,y,r,s,d));const v=b?de(h?.directory??u?.directory??t().getDirectoryForSession(b)):null;b&&K0(b);const C=i?.map(w=>({type:"file",mime:w.mimeType,url:w.dataUrl,filename:w.filename,uploadState:w.uploadState}));await sp({runtimeKey:h?.runtimeKey,sessionId:b||"",directory:v,content:n,providerID:r,modelID:s,agent:y,agentMentionName:a,variant:d,inputMode:f,files:C,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,additionalParts:l?.map(w=>({text:w.text,synthetic:w.synthetic,files:w.attachments?.map(M=>({type:"file",mime:M.mimeType,url:M.dataUrl,filename:M.filename,uploadState:M.uploadState}))}))})},createSession:async(n,r,s,o,i)=>{const a=i?.draftSnapshot??t().newSessionDraft,l=a.targetFolderId;try{const d=r??Ue().getState().directory,f=await $E(n,d,s??null,o);if(!f)return null;if(i?.closeDraft!==!1&&t().newSessionDraft===a&&t().closeNewSessionDraft(),l){const u=r||f.directory;u&&Cm.getState().addSessionToFolder(u,l,f.id)}return f}catch(d){return console.error("[session-ui-store] createSession failed",d),null}},deleteSession:async(n,r)=>{const s=await zE(n);return s&&t().currentSessionId===n&&t().openNewSessionDraft(),s},deleteSessions:async(n,r)=>{const s=await UE(n),o=t().currentSessionId;return o&&s.deletedIds.includes(o)&&t().openNewSessionDraft(),s},archiveSession:n=>qE(n),archiveSessions:(n,r)=>WE(n),unarchiveSession:n=>KE(n),unarchiveSessions:(n,r)=>GE(n),updateSessionTitle:async(n,r)=>{await ZE(n,r)},shareSession:async n=>YE(),unshareSession:async n=>XE(),revertToMessage:async(n,r)=>{await JE(n,r)},restoreToMessage:async(n,r)=>{await QE(n,r)},handleSlashUndo:async n=>{const r=Ue().getState().reducer.bySession.get(n),o=(r?[...r.messages.values()]:[]).filter(l=>l.role==="user");if(o.length===0)return;const i=o[o.length-1];if(!i)return;String(i.text??"").slice(0,50)+((i.text?.length??0)>50?"...":""),await t().revertToMessage(n,i.id);const{toast:a}=await mt(async()=>{const{toast:l}=await import("./vendor-boot-CoTxysn6.js").then(d=>d.cp);return{toast:l}},__vite__mapDeps([5,1,6]));a.success("Reverted — conversation rewound. Files on disk were not changed.")},handleSlashRedo:async n=>{await ej(n);const{toast:r}=await mt(async()=>{const{toast:s}=await import("./vendor-boot-CoTxysn6.js").then(o=>o.cp);return{toast:s}},__vite__mapDeps([5,1,6]));r.success("Restored all messages")},forkFromMessage:async(n,r)=>{await tj(n,r)},getSessionsByDirectory:n=>{const r=de(n);return r?Tm().filter(o=>fw(o)===r):[]},getDirectoryForSession:n=>{const r=n===t().currentSessionId?t().currentSessionDirectory:null,s=o2(n,r);if(s)return s;try{return Ue().getState().catalog.byId.get(n)?.directory??null}catch{return null}},adoptAuthoritativeSessionDirectory:n=>{const r=n??t().currentSessionId;if(!r||r!==r2()||r!==t().currentSessionId)return;const s=aj(r);s&&(s2(),s!==t().currentSessionDirectory&&e({currentSessionDirectory:s}),Gs(ir(),{sessionId:r,directory:s}))},setSessionDirectory:(n,r)=>{const s=de(r);n===r2()&&s2(),n===t().currentSessionId&&(e({currentSessionDirectory:s}),Gs(ir(),{sessionId:n,directory:s}))}})),ZY=Object.freeze(Object.defineProperty({__proto__:null,draftBranchCheckoutReceiptMatches:sa,getRememberedSessionDirectory:cj,materializeOpenDraftSession:cp,routeMessage:sp,useSessionUIStore:pe},Symbol.toStringTag,{value:"Module"}));async function gr(e){let t=null;if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0,method:"clipboard"}}catch(n){t=n instanceof Error?n.message:String(n)}if(typeof document<"u"&&document.body){const n=document.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.top="-1000px",n.style.left="-1000px",document.body.appendChild(n),n.select(),n.setSelectionRange(0,n.value.length);const r=document.execCommand("copy");if(document.body.removeChild(n),r)return{ok:!0,method:"execCommand"}}return{ok:!1,error:t??"Clipboard access denied in current context"}}async function hj(e,t){if(typeof navigator<"u"&&navigator.clipboard?.write&&typeof ClipboardItem<"u")try{const n={"text/plain":new Blob([e],{type:"text/plain"}),"text/html":new Blob([t],{type:"text/html"})};return typeof ClipboardItem.supports=="function"&&ClipboardItem.supports("text/markdown")&&(n["text/markdown"]=new Blob([e],{type:"text/markdown"})),await navigator.clipboard.write([new ClipboardItem(n)]),{ok:!0,method:"clipboard"}}catch{}return gr(e)}const Om=H.createContext(void 0);function Jn(){const e=H.useContext(Om);if(!e)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return e}function mw(){return H.useContext(Om)}const gw=async(e,t)=>{if(!J9())throw new Error("Desktop runtime is not available");return dr(e,t)},pj=async e=>{if(wt())try{await gw("desktop_set_window_title",{title:e})}catch{}},mj=async(e,t)=>{if(wt())try{await gw("desktop_set_window_theme",{themeMode:e,themeVariant:t})}catch{}},vf=e=>{if(!e||typeof e!="string")return null;const t=e.trim();if(!t.startsWith("#"))return null;let n=t.slice(1);if((n.length===3||n.length===4)&&(n=n.split("").map(a=>a+a).join("")),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;const r=Number.parseInt(n,16);if(Number.isNaN(r))return null;const s=r>>16&255,o=r>>8&255,i=r&255;return`${s} ${o} ${i}`};class gj{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(t){const n=[];return n.push(...this.generateTailwindVariables(t)),n.push(...this.generatePrimaryColors(t.colors.primary)),n.push(...this.generateSurfaceColors(t.colors.surface)),n.push(...this.generateInteractiveColors(t.colors.interactive)),n.push(...this.generateStatusColors(t.colors.status)),n.push(...this.generatePullRequestColors(t)),n.push(...this.generateSyntaxColors(t.colors.syntax)),n.push(...this.generateComponentColors(t.colors,t)),n.push(...this.generateTypographyVariables()),t.config&&n.push(...this.generateConfigVariables(t.config)),n.join(`
23
+ `)}generateTailwindVariables(t){const n=[];n.push(` --background: ${t.colors.surface.background} !important;`),n.push(` --foreground: ${t.colors.surface.foreground} !important;`),n.push(` --muted: ${t.colors.surface.muted} !important;`),n.push(` --muted-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --card: ${t.colors.surface.elevated} !important;`),n.push(` --card-foreground: ${t.colors.surface.elevatedForeground} !important;`),n.push(` --popover: ${t.colors.surface.elevated} !important;`),n.push(` --popover-foreground: ${t.colors.surface.elevatedForeground} !important;`),n.push(` --border: ${t.colors.interactive.border} !important;`),n.push(` --input: ${t.colors.interactive.border} !important;`),n.push(` --primary: ${t.colors.primary.base} !important;`),n.push(` --primary-foreground: ${t.colors.primary.foreground} !important;`),n.push(` --secondary: ${t.colors.surface.muted} !important;`),n.push(` --secondary-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --accent: ${t.colors.surface.subtle} !important;`),n.push(` --accent-foreground: ${t.colors.surface.foreground} !important;`),n.push(` --destructive: ${t.colors.status.error} !important;`),n.push(` --destructive-foreground: ${t.colors.status.errorForeground} !important;`),n.push(` --ring: ${t.colors.interactive.focusRing} !important;`);const r=vf(t.colors.surface.muted),s=vf(t.colors.surface.subtle),o=vf(t.colors.interactive.border);n.push(` --sidebar-base: ${t.colors.surface.muted} !important;`),r&&n.push(` --sidebar-base-rgb: ${r} !important;`),n.push(" --sidebar: var(--sidebar-base) !important;"),n.push(` --sidebar-foreground: ${t.colors.surface.mutedForeground} !important;`),n.push(` --sidebar-primary: ${t.colors.primary.base} !important;`),n.push(` --sidebar-primary-foreground: ${t.colors.primary.foreground} !important;`),n.push(` --sidebar-accent-base: ${t.colors.surface.subtle} !important;`),s&&n.push(` --sidebar-accent-base-rgb: ${s} !important;`),n.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),n.push(` --sidebar-accent-foreground: ${t.colors.surface.foreground} !important;`),n.push(` --sidebar-border: ${t.colors.interactive.border} !important;`),o&&n.push(` --sidebar-border-rgb: ${o} !important;`),n.push(` --sidebar-ring: ${t.colors.interactive.focusRing} !important;`);const i=t.metadata.variant==="dark",a=i?.15:.5,l=i?.1:.3;if(r)n.push(` --sidebar-overlay-strong: rgb(${r} / ${a}) !important;`),n.push(` --sidebar-overlay-soft: rgb(${r} / ${l}) !important;`);else{const d=t.colors.surface.muted;n.push(` --sidebar-overlay-strong: ${this.opacity(d,a)} !important;`),n.push(` --sidebar-overlay-soft: ${this.opacity(d,l)} !important;`)}return t.colors.charts?.series&&Array.isArray(t.colors.charts.series)&&t.colors.charts.series.forEach((d,f)=>{n.push(` --chart-${f+1}: ${d};`)}),t.colors.loading?(n.push(` --loading-spinner: ${t.colors.loading.spinner||t.colors.primary.base};`),n.push(` --loading-spinner-track: ${t.colors.loading.spinnerTrack||t.colors.surface.muted};`)):(n.push(` --loading-spinner: ${t.colors.primary.base};`),n.push(` --loading-spinner-track: ${t.colors.surface.muted};`)),n}apply(t){const n=this.generate(t),r=document.createElement("style");r.id="pichamber-theme-variables";let s="";t.metadata.variant==="dark"?(s=`:root {
24
+ ${n}
25
+ }
26
+
27
+ .dark {
28
+ ${n}
29
+ }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(s=`:root {
30
+ ${n}
31
+ }
32
+
33
+ :root:not(.dark) {
34
+ ${n}
35
+ }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),r.textContent=s;const o=document.getElementById("pichamber-theme-variables");o&&o.remove(),document.head.appendChild(r),document.documentElement.setAttribute("data-theme",t.metadata.variant)}generatePrimaryColors(t){const n=[];return n.push(` --primary-base: ${t.base};`),n.push(` --primary-hover: ${t.hover||this.darken(t.base,10)};`),n.push(` --primary-active: ${t.active||this.darken(t.base,20)};`),n.push(` --primary-foreground: ${t.foreground||"#ffffff"};`),n.push(` --primary-muted: ${t.muted||this.opacity(t.base,.5)};`),n.push(` --primary-emphasis: ${t.emphasis||this.lighten(t.base,10)};`),n}generateSurfaceColors(t){const n=[];return n.push(` --surface-background: ${t.background};`),n.push(` --surface-foreground: ${t.foreground};`),n.push(` --surface-muted: ${t.muted};`),n.push(` --surface-muted-foreground: ${t.mutedForeground};`),n.push(` --surface-elevated: ${t.elevated};`),n.push(` --surface-elevated-foreground: ${t.elevatedForeground};`),n.push(` --surface-overlay: ${t.overlay};`),n.push(` --surface-subtle: ${t.subtle};`),n}generateInteractiveColors(t){const n=[];return n.push(` --interactive-border: ${t.border};`),n.push(` --interactive-border-hover: ${t.borderHover};`),n.push(` --interactive-border-focus: ${t.borderFocus};`),n.push(` --interactive-selection: ${t.selection};`),n.push(` --interactive-selection-foreground: ${t.selectionForeground};`),n.push(` --interactive-focus: ${t.focus};`),n.push(` --interactive-focus-ring: ${t.focusRing};`),n.push(` --interactive-cursor: ${t.cursor};`),n.push(` --interactive-hover: ${t.hover};`),n.push(` --interactive-active: ${t.active};`),n}generateStatusColors(t){const n=[];return n.push(` --status-error: ${t.error};`),n.push(` --status-error-foreground: ${t.errorForeground};`),n.push(` --status-error-background: ${t.errorBackground};`),n.push(` --status-error-border: ${t.errorBorder};`),n.push(` --status-warning: ${t.warning};`),n.push(` --status-warning-foreground: ${t.warningForeground};`),n.push(` --status-warning-background: ${t.warningBackground};`),n.push(` --status-warning-border: ${t.warningBorder};`),n.push(` --status-success: ${t.success};`),n.push(` --status-success-foreground: ${t.successForeground};`),n.push(` --status-success-background: ${t.successBackground};`),n.push(` --status-success-border: ${t.successBorder};`),n.push(` --status-info: ${t.info};`),n.push(` --status-info-foreground: ${t.infoForeground};`),n.push(` --status-info-background: ${t.infoBackground};`),n.push(` --status-info-border: ${t.infoBorder};`),n}generatePullRequestColors(t){const n=[],r=t.colors.pr;return n.push(` --pr-open: ${r?.open||t.colors.status.success};`),n.push(` --pr-draft: ${r?.draft||t.colors.surface.mutedForeground};`),n.push(` --pr-blocked: ${r?.blocked||t.colors.status.warning};`),n.push(` --pr-merged: ${r?.merged||(t.metadata.variant==="dark"?"#8957e5":"#8250df")};`),n.push(` --pr-closed: ${r?.closed||t.colors.status.error};`),n}generateSyntaxColors(t){const n=[];n.push(` --syntax-background: ${t.base.background};`),n.push(` --syntax-foreground: ${t.base.foreground};`),n.push(` --syntax-comment: ${t.base.comment};`),n.push(` --syntax-keyword: ${t.base.keyword};`),n.push(` --syntax-string: ${t.base.string};`),n.push(` --syntax-number: ${t.base.number};`),n.push(` --syntax-function: ${t.base.function};`),n.push(` --syntax-variable: ${t.base.variable};`),n.push(` --syntax-type: ${t.base.type};`),n.push(` --syntax-operator: ${t.base.operator};`);const r=this.generateSyntaxTokens(t);for(const[s,o]of Object.entries(r))n.push(` --syntax-${this.kebabCase(s)}: ${o};`);return n}generateSyntaxTokens(t){const n=t.base,r=t.tokens||{};return{commentDoc:r.commentDoc||this.lighten(n.comment,10),stringEscape:r.stringEscape||this.darken(n.string,20),stringInterpolation:r.stringInterpolation||n.variable,stringRegex:r.stringRegex||this.adjustHue(n.string,15),keywordControl:r.keywordControl||n.keyword,keywordOperator:r.keywordOperator||n.operator,keywordImport:r.keywordImport||this.lighten(n.keyword,10),keywordReturn:r.keywordReturn||this.emphasize(n.keyword),functionCall:r.functionCall||this.lighten(n.function,5),functionBuiltin:r.functionBuiltin||this.darken(n.function,10),method:r.method||n.function,methodCall:r.methodCall||this.lighten(n.function,5),variableBuiltin:r.variableBuiltin||this.emphasize(n.variable),variableProperty:r.variableProperty||this.lighten(n.variable,10),variableReadonly:r.variableReadonly||n.number,parameter:r.parameter||n.variable,typePrimitive:r.typePrimitive||this.darken(n.type,10),typeInterface:r.typeInterface||n.type,className:r.className||this.emphasize(n.type),enum:r.enum||n.type,boolean:r.boolean||n.number,null:r.null||this.opacity(n.number,.7),constant:r.constant||n.number,punctuation:r.punctuation||this.opacity(n.foreground,.7),delimiter:r.delimiter||this.opacity(n.foreground,.8),bracket:r.bracket||n.foreground,tag:r.tag||n.keyword,tagAttribute:r.tagAttribute||n.variable,tagAttributeValue:r.tagAttributeValue||n.string,tagBracket:r.tagBracket||this.opacity(n.foreground,.8),decorator:r.decorator||n.function,annotation:r.annotation||n.function,namespace:r.namespace||this.opacity(n.type,.8),module:r.module||this.opacity(n.type,.8),...r}}generateComponentColors(t,n){const r=[];return t.markdown?r.push(...this.generateMarkdownColors(t.markdown,n)):r.push(...this.generateDefaultMarkdownColors(n)),t.chat?r.push(...this.generateChatColors(t.chat,n)):r.push(...this.generateDefaultChatColors(n)),t.tools?r.push(...this.generateToolColors(t.tools,n)):r.push(...this.generateDefaultToolColors(n)),r}generateMarkdownColors(t,n){const r=[],s=n.colors.primary.base,o=n.colors.chat?.background||n.colors.surface.background;return r.push(` --markdown-heading1: ${t.heading1||s};`),r.push(` --markdown-heading2: ${t.heading2||this.opacity(s,.9)};`),r.push(` --markdown-heading3: ${t.heading3||this.opacity(s,.8)};`),r.push(` --markdown-heading4: ${t.heading4||n.colors.surface.foreground};`),r.push(` --markdown-link: ${t.link||s};`),r.push(` --markdown-link-hover: ${t.linkHover||n.colors.primary.hover||this.darken(s,10)};`),r.push(` --markdown-inline-code: ${t.inlineCode||n.colors.syntax.base.string};`),r.push(` --markdown-inline-code-bg: ${t.inlineCodeBackground||o};`),r.push(` --markdown-blockquote: ${t.blockquote||n.colors.surface.mutedForeground};`),r.push(` --markdown-blockquote-border: ${t.blockquoteBorder||n.colors.interactive.border};`),r.push(` --markdown-list-marker: ${t.listMarker||this.opacity(s,.6)};`),r.push(` --markdown-bold: ${t.bold||n.colors.surface.foreground};`),r.push(` --markdown-italic: ${t.italic||this.opacity(n.colors.surface.foreground,.9)};`),r.push(` --markdown-strikethrough: ${t.strikethrough||n.colors.surface.mutedForeground};`),r.push(` --markdown-hr: ${t.hr||n.colors.interactive.border};`),r}generateDefaultMarkdownColors(t){const n=[],r=t.colors.primary.base,s=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r};`),n.push(` --markdown-heading2: ${this.opacity(r,.9)};`),n.push(` --markdown-heading3: ${this.opacity(r,.8)};`),n.push(` --markdown-heading4: ${t.colors.surface.foreground};`),n.push(` --markdown-link: ${r};`),n.push(` --markdown-link-hover: ${t.colors.primary.hover||this.darken(r,10)};`),n.push(` --markdown-inline-code: ${t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${s};`),n.push(` --markdown-blockquote: ${t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${this.opacity(r,.6)};`),n.push(` --markdown-bold: ${t.colors.surface.foreground};`),n.push(` --markdown-italic: ${this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${t.colors.interactive.border};`),n}generateChatColors(t,n){const r=[],s=t.background||n.colors.surface.background;return r.push(` --chat-background: ${s};`),r.push(` --chat-user-message: ${t.userMessage||n.colors.surface.foreground};`),r.push(` --chat-user-message-bg: ${t.userMessageBackground||n.colors.surface.elevated};`),r.push(` --chat-assistant-message: ${t.assistantMessage||n.colors.surface.foreground};`),r.push(` --chat-assistant-message-bg: ${t.assistantMessageBackground||n.colors.surface.muted};`),r.push(` --chat-timestamp: ${t.timestamp||n.colors.surface.mutedForeground};`),r.push(` --chat-divider: ${t.divider||n.colors.interactive.border};`),r.push(` --chat-typing: ${t.typing||n.colors.surface.mutedForeground};`),r}generateDefaultChatColors(t){const n=[];return n.push(` --chat-background: ${t.colors.surface.background};`),n.push(` --chat-user-message: ${t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${t.colors.surface.muted};`),n.push(` --chat-timestamp: ${t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${t.colors.interactive.border};`),n.push(` --chat-typing: ${t.colors.surface.mutedForeground};`),n}generateToolColors(t,n){const r=[];return r.push(` --tools-background: ${t?.background||this.opacity(n.colors.surface.muted,.2)};`),r.push(` --tools-border: ${t?.border||this.opacity(n.colors.interactive.border,.3)};`),r.push(` --tools-header-hover: ${t?.headerHover||this.opacity(n.colors.surface.muted,.3)};`),r.push(` --tools-icon: ${t?.icon||n.colors.surface.mutedForeground};`),r.push(` --tools-title: ${t?.title||n.colors.surface.foreground};`),r.push(` --tools-description: ${t?.description||this.opacity(n.colors.surface.mutedForeground,.6)};`),t?.edit?(r.push(` --tools-edit-added: ${t.edit.added||n.colors.status.success};`),r.push(` --tools-edit-added-bg: ${t.edit.addedBackground||n.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${t.edit.removed||n.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${t.edit.removedBackground||n.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${t.edit.modified||n.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${t.edit.modifiedBackground||n.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${t.edit.lineNumber||this.opacity(n.colors.surface.mutedForeground,.6)};`)):(r.push(` --tools-edit-added: ${n.colors.status.success};`),r.push(` --tools-edit-added-bg: ${n.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${n.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${n.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${n.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${n.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${this.opacity(n.colors.surface.mutedForeground,.6)};`)),r}generateDefaultToolColors(t){const n=[];return n.push(` --tools-background: ${this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${t.colors.surface.foreground};`),n.push(` --tools-description: ${this.opacity(t.colors.surface.mutedForeground,.6)};`),n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.successBackground),.15)};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.errorBackground),.15)};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(t.colors.status.infoBackground),.15)};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`),n}generateConfigVariables(t){const n=[];return t&&(t.fonts&&(t.fonts.sans&&(n.push(` --font-sans: ${t.fonts.sans};`),n.push(` --font-family-sans: ${t.fonts.sans};`)),t.fonts.mono&&(n.push(` --font-mono: ${t.fonts.mono};`),n.push(` --font-family-mono: ${t.fonts.mono};`)),t.fonts.heading&&n.push(` --font-heading: ${t.fonts.heading};`)),t.transitions&&(t.transitions.fast&&n.push(` --transition-fast: ${t.transitions.fast};`),t.transitions.normal&&n.push(` --transition-normal: ${t.transitions.normal};`),t.transitions.slow&&n.push(` --transition-slow: ${t.transitions.slow};`))),n}generateTypographyVariables(){const t=[],n=Q9;return t.push(" /* Semantic Typography Variables */"),t.push(" --ui-regular-font-weight: 400;"),t.push(" /* Markdown content - all markdown elements use same size */"),t.push(` --text-markdown: ${n.markdown};`),t.push(" /* Code content - all code elements use same size */"),t.push(` --text-code: ${n.code};`),t.push(" /* UI headers - dialog titles, panel headers */"),t.push(` --text-ui-header: ${n.uiHeader};`),t.push(" /* UI labels - buttons, menus, navigation */"),t.push(` --text-ui-label: ${n.uiLabel};`),t.push(" /* Metadata - timestamps, status, helper text */"),t.push(` --text-meta: ${n.meta};`),t.push(" /* Micro text - badges, shortcuts, indicators */"),t.push(` --text-micro: ${n.micro};`),t.push(" /* Settings page titles - larger than section headers */"),t.push(` --text-settings-page-title: ${n.settingsPageTitle};`),t.push(" /* Heading line height and letter spacing */"),t.push(" --h1-line-height: 1.25rem;"),t.push(" --h2-line-height: 1.25rem;"),t.push(" --h3-line-height: 1.5rem;"),t.push(" --h4-line-height: 1.5rem;"),t.push(" --h5-line-height: 1.5rem;"),t.push(" --h6-line-height: 1.5rem;"),t.push(" --h1-letter-spacing: -0.025em;"),t.push(" --h2-letter-spacing: -0.02em;"),t.push(" --h3-letter-spacing: -0.015em;"),t.push(" --h4-letter-spacing: -0.01em;"),t.push(" --h5-letter-spacing: 0;"),t.push(" --h6-letter-spacing: 0.01em;"),t.push(" /* UI element line height and letter spacing */"),t.push(" --ui-button-line-height: 1.375rem;"),t.push(" --ui-button-letter-spacing: 0.02em;"),t.push(" --ui-button-font-weight: 500;"),t.push(" --ui-label-line-height: 1rem;"),t.push(" --ui-label-letter-spacing: 0.03em;"),t.push(" --ui-label-font-weight: 500;"),t.push(" --ui-caption-line-height: 1rem;"),t.push(" --ui-caption-letter-spacing: 0.025em;"),t.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Markdown line height and letter spacing */"),t.push(" --markdown-body-line-height: 1.5rem;"),t.push(" --markdown-body-letter-spacing: 0;"),t.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-h1-line-height: 1.25rem;"),t.push(" --markdown-h1-letter-spacing: -0.025em;"),t.push(" --markdown-h2-line-height: 1.25rem;"),t.push(" --markdown-h2-letter-spacing: -0.02em;"),t.push(" --markdown-h3-line-height: 1.5rem;"),t.push(" --markdown-h3-letter-spacing: -0.015em;"),t.push(" --markdown-h4-line-height: 1.5rem;"),t.push(" --markdown-h4-letter-spacing: -0.01em;"),t.push(" --markdown-h5-line-height: 1.5rem;"),t.push(" --markdown-h5-letter-spacing: 0;"),t.push(" --markdown-h6-line-height: 1.5rem;"),t.push(" --markdown-h6-letter-spacing: 0.01em;"),t.push(" --markdown-list-line-height: 1.375rem;"),t.push(" --markdown-code-block-line-height: 1rem;"),t.push(" --ui-button-small-line-height: 1.25rem;"),t.push(" --ui-button-small-letter-spacing: 0.02em;"),t.push(" --ui-button-small-font-weight: 500;"),t.push(" --markdown-body-small-line-height: 1.375rem;"),t.push(" --markdown-body-small-letter-spacing: 0;"),t.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-button-large-line-height: 1.5rem;"),t.push(" --ui-button-large-letter-spacing: 0.02em;"),t.push(" --ui-button-large-font-weight: 500;"),t.push(" --markdown-body-large-line-height: 1.625rem;"),t.push(" --markdown-body-large-letter-spacing: 0;"),t.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Code line height and letter spacing */"),t.push(" --code-inline-line-height: 1rem;"),t.push(" --code-inline-letter-spacing: 0;"),t.push(" --code-inline-font-weight: 400;"),t.push(" --code-block-line-height: round(1.4rem, 1px);"),t.push(" --code-block-letter-spacing: 0;"),t.push(" --code-block-font-weight: 400;"),t.push(" --code-line-numbers-line-height: 1.25rem;"),t.push(" --code-line-numbers-letter-spacing: 0;"),t.push(" --code-line-numbers-font-weight: 400;"),t.push(" /* Additional UI element line height and letter spacing */"),t.push(" --ui-badge-line-height: 1rem;"),t.push(" --ui-badge-letter-spacing: 0.025em;"),t.push(" --ui-badge-font-weight: 500;"),t.push(" --ui-tooltip-line-height: 1rem;"),t.push(" --ui-tooltip-letter-spacing: 0.025em;"),t.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-input-line-height: 1.375rem;"),t.push(" --ui-input-letter-spacing: 0.02em;"),t.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --ui-helper-text-line-height: 1rem;"),t.push(" --ui-helper-text-letter-spacing: 0.025em;"),t.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" /* Additional markdown line height and letter spacing */"),t.push(" --markdown-blockquote-line-height: 1.5rem;"),t.push(" --markdown-blockquote-letter-spacing: 0;"),t.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-list-letter-spacing: 0;"),t.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-link-line-height: 1.5rem;"),t.push(" --markdown-link-letter-spacing: 0;"),t.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),t.push(" --markdown-code-line-height: round(1.35em, 1px);"),t.push(" --markdown-code-letter-spacing: 0;"),t.push(" --markdown-code-font-weight: 400;"),t.push(" --markdown-code-block-letter-spacing: 0;"),t.push(" --markdown-code-block-font-weight: 400;"),t}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(t,n){return t.startsWith("#")?`${t}${Math.round(n*255).toString(16).padStart(2,"0")}`:t.startsWith("rgb")?t.replace("rgb","rgba").replace(")",`, ${n})`):t}removeTransparency(t){return t.startsWith("#")?t.length===9?t.slice(0,7):t.length===5?t.slice(0,4):t:t.startsWith("rgba")?t.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):t}addTransparency(t,n){if(t.startsWith("#")){const r=t.slice(1);if(r.length===3){const s=parseInt(r[0]+r[0],16),o=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16);return`rgba(${s}, ${o}, ${i}, ${n})`}else if(r.length===6){const s=parseInt(r.slice(0,2),16),o=parseInt(r.slice(2,4),16),i=parseInt(r.slice(4,6),16);return`rgba(${s}, ${o}, ${i}, ${n})`}}return t.startsWith("rgb")?t.replace("rgb","rgba").replace(")",`, ${n})`):t}darken(t,n){if(t.startsWith("#")){const r=parseInt(t.slice(1),16),s=Math.round(2.55*n),o=(r>>16)-s,i=(r>>8&255)-s,a=(r&255)-s;return"#"+(16777216+(o<255?o<0?0:o:255)*65536+(i<255?i<0?0:i:255)*256+(a<255?a<0?0:a:255)).toString(16).slice(1)}return t}lighten(t,n){if(t.startsWith("#")){const r=parseInt(t.slice(1),16),s=Math.round(2.55*n),o=(r>>16)+s,i=(r>>8&255)+s,a=(r&255)+s;return"#"+(16777216+(o<255?o<0?0:o:255)*65536+(i<255?i<0?0:i:255)*256+(a<255?a<0?0:a:255)).toString(16).slice(1)}return t}adjustHue(t,n){return this.lighten(t,n/10)}emphasize(t){return this.lighten(t,15)}kebabCase(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const a2=(e,t)=>t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e),yj=e=>typeof e=="string"&&e.trim().length>0,c2=e=>{if(!e||typeof e!="object")return!1;const t=[["metadata","id"],["metadata","name"],["metadata","variant"],["colors","primary","base"],["colors","primary","foreground"],["colors","surface","background"],["colors","surface","foreground"],["colors","surface","muted"],["colors","surface","mutedForeground"],["colors","surface","elevated"],["colors","surface","elevatedForeground"],["colors","surface","subtle"],["colors","interactive","border"],["colors","interactive","selection"],["colors","interactive","selectionForeground"],["colors","interactive","focusRing"],["colors","interactive","hover"],["colors","status","error"],["colors","status","errorForeground"],["colors","status","errorBackground"],["colors","status","errorBorder"],["colors","status","warning"],["colors","status","warningForeground"],["colors","status","warningBackground"],["colors","status","warningBorder"],["colors","status","success"],["colors","status","successForeground"],["colors","status","successBackground"],["colors","status","successBorder"],["colors","status","info"],["colors","status","infoForeground"],["colors","status","infoBackground"],["colors","status","infoBorder"],["colors","syntax","base","background"],["colors","syntax","base","foreground"],["colors","syntax","base","keyword"],["colors","syntax","base","string"],["colors","syntax","base","number"],["colors","syntax","base","function"],["colors","syntax","base","variable"],["colors","syntax","base","type"],["colors","syntax","base","comment"],["colors","syntax","base","operator"],["colors","syntax","highlights","diffAdded"],["colors","syntax","highlights","diffRemoved"],["colors","syntax","highlights","lineNumber"]];for(const r of t)if(!yj(a2(e,r)))return!1;const n=a2(e,["metadata","variant"]);return n==="light"||n==="dark"},vj=nS,xj=tS,bj=e=>sS(e==="dark"),wj=typeof window<"u"?p.useLayoutEffect:p.useEffect,Sj=()=>{if(typeof document>"u")return;const e=document.documentElement;e.classList.add("oc-theme-switching");const t=window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{e.classList.remove("oc-theme-switching")})});return()=>{window.cancelAnimationFrame(t),e.classList.remove("oc-theme-switching")}},Cj=e=>{let t=vj,n=xj,r="system";if(typeof window<"u"){const s=localStorage.getItem("themeMode"),o=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),a=localStorage.getItem("useSystemTheme"),l=localStorage.getItem("selectedThemeId"),d=localStorage.getItem("selectedThemeVariant");if(s==="light"||s==="dark"||s==="system")r=s;else if(a!==null){if(a==="true")r="system";else if(l){const u=Eg(l);u&&(r=u.metadata.variant==="dark"?"dark":"light",u.metadata.variant==="dark"?n=u.metadata.id:t=u.metadata.id)}}else(d==="light"||d==="dark")&&(r=d);typeof o=="string"&&o.trim().length>0&&(t=o.trim()),typeof i=="string"&&i.trim().length>0&&(n=i.trim())}if(e){const s=Eg(e);s&&(s.metadata.variant==="light"?t=s.metadata.id:n=s.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function YY({children:e,defaultThemeId:t}){const n=H.useMemo(()=>new gj,[]),[r,s]=H.useState(()=>Cj(t)),[o,i]=H.useState(()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches),[a,l]=H.useState([]),[d,f]=H.useState([]),[u,h]=H.useState(!1),m=H.useMemo(()=>wt(),[]),g=H.useRef(0),x=H.useMemo(()=>{const E=[],I=new Set,N=O=>{const L=O.metadata.id;I.has(L)||(I.add(L),E.push(O))};return a.forEach(N),d.forEach(N),eS.forEach(N),E},[a,d]);H.useEffect(()=>{const E=I=>{const N=I.detail;if(!c2(N))return;const O=rS(N);f(L=>{const D=L.findIndex(z=>z.metadata.id===O.metadata.id);if(D<0)return[...L,O];const W=[...L];return W[D]=O,W})};return window.addEventListener("pichamber:theme-hmr",E),()=>window.removeEventListener("pichamber:theme-hmr",E)},[]);const b=H.useCallback(E=>x.find(I=>I.metadata.id===E),[x]),S=H.useCallback((E,I)=>{const N=b(E);return N&&N.metadata.variant===I?N:x.find(L=>L.metadata.variant===I)??bj(I)},[x,b]),y=H.useMemo(()=>r.themeMode==="light"?S(r.lightThemeId,"light"):r.themeMode==="dark"||o?S(r.darkThemeId,"dark"):S(r.lightThemeId,"light"),[S,r,o]),v=H.useCallback(async()=>{if(typeof window>"u")return;const E=Y(),I=++g.current;h(!0);try{const N=await Nt("/api/pi/themes",{method:"GET",credentials:Ko()?"omit":"include",headers:{Accept:"application/json"}});if(N.status===401||!N.ok)return;const O=await N.json();if(I!==g.current||E!==Y())return;const D=(Array.isArray(O?.themes)?O.themes:[]).filter(c2);l(D)}catch{}finally{I===g.current&&E===Y()&&h(!1)}},[]);H.useEffect(()=>{v()},[v]),H.useEffect(()=>en(E=>{E.runtimeKey!==E.previousRuntimeKey&&(g.current+=1,l([]),h(!1),v())}),[v]);const C=H.useCallback(E=>{if(typeof document>"u")return;const I=E.colors.surface.background;document.body.style.backgroundColor=I;let N=document.querySelector('meta[name="theme-color"]');N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),document.head.appendChild(N)),N.setAttribute("content",I);const O=E.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let L=document.querySelector(`meta[name="theme-color"][media="${O}"]`);L||(L=document.createElement("meta"),L.setAttribute("name","theme-color"),L.setAttribute("media",O),document.head.appendChild(L)),L.setAttribute("content",I)},[]),w=H.useRef(!1);wj(()=>{if(typeof window>"u")return;const E=w.current?Sj():void 0;w.current=!0,n.apply(y),C(y);const I=document.documentElement;return I.classList.remove("light","dark"),I.classList.add(y.metadata.variant),E},[n,y,C]),H.useEffect(()=>{if(r.themeMode!=="system"||typeof window>"u")return;const E=window.matchMedia("(prefers-color-scheme: dark)"),I=N=>{i(N.matches)};return i(E.matches),E.addEventListener("change",I),()=>E.removeEventListener("change",I)},[r.themeMode]),H.useEffect(()=>{if(typeof window>"u")return;localStorage.setItem("themeMode",r.themeMode),localStorage.setItem("lightThemeId",r.lightThemeId),localStorage.setItem("darkThemeId",r.darkThemeId),localStorage.setItem("useSystemTheme",String(r.themeMode==="system")),localStorage.setItem("selectedThemeId",y.metadata.id),localStorage.setItem("selectedThemeVariant",y.metadata.variant==="light"?"light":"dark");const E=S(r.lightThemeId,"light"),I=S(r.darkThemeId,"dark");localStorage.setItem("splashBgLight",E.colors.surface.background),localStorage.setItem("splashFgLight",E.colors.surface.foreground),localStorage.setItem("splashBgDark",I.colors.surface.background),localStorage.setItem("splashFgDark",I.colors.surface.foreground)},[r,y,S]),H.useEffect(()=>{if(typeof window>"u")return;const E=I=>{I.storageArea===window.localStorage&&(I.key!=="themeMode"&&I.key!=="lightThemeId"&&I.key!=="darkThemeId"||s(N=>{const O=localStorage.getItem("themeMode"),L=O==="light"||O==="dark"||O==="system"?O:N.themeMode,D=localStorage.getItem("lightThemeId"),W=typeof D=="string"&&D.trim().length>0?D.trim():N.lightThemeId,z=localStorage.getItem("darkThemeId"),J=typeof z=="string"&&z.trim().length>0?z.trim():N.darkThemeId;return L===N.themeMode&&W===N.lightThemeId&&J===N.darkThemeId?N:{themeMode:L,lightThemeId:W,darkThemeId:J}}))};return window.addEventListener("storage",E),()=>window.removeEventListener("storage",E)},[]),H.useEffect(()=>{const E=S(r.lightThemeId,"light"),I=S(r.darkThemeId,"dark");Vr({themeId:y.metadata.id,themeVariant:y.metadata.variant==="light"?"light":"dark",useSystemTheme:r.themeMode==="system",lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,splashBgLight:E.colors.surface.background,splashFgLight:E.colors.surface.foreground,splashBgDark:I.colors.surface.background,splashFgDark:I.colors.surface.foreground})},[y.metadata.id,y.metadata.variant,S,r.themeMode,r.lightThemeId,r.darkThemeId]),H.useEffect(()=>{m&&(async()=>await mj(r.themeMode,y.metadata.variant))()},[y.metadata.variant,m,r.themeMode]),H.useEffect(()=>{if(typeof window>"u")return;const E=I=>{const N=I.detail;N&&s(O=>{let L=O.themeMode;N.useSystemTheme===!0?L="system":N.useSystemTheme===!1&&(N.themeVariant==="dark"||N.themeVariant==="light")&&(L=N.themeVariant);let D=O.lightThemeId;typeof N.lightThemeId=="string"&&N.lightThemeId.length>0&&(D=N.lightThemeId.trim());let W=O.darkThemeId;return typeof N.darkThemeId=="string"&&N.darkThemeId.length>0&&(W=N.darkThemeId.trim()),L===O.themeMode&&D===O.lightThemeId&&W===O.darkThemeId?O:{themeMode:L,lightThemeId:D,darkThemeId:W}})};return window.addEventListener("pichamber:settings-synced",E),()=>window.removeEventListener("pichamber:settings-synced",E)},[]);const M=H.useCallback(E=>{const I=x.find(N=>N.metadata.id===E);I&&s(N=>I.metadata.variant==="dark"?N.darkThemeId===I.metadata.id&&N.themeMode==="dark"?N:{...N,darkThemeId:I.metadata.id,themeMode:"dark"}:N.lightThemeId===I.metadata.id&&N.themeMode==="light"?N:{...N,lightThemeId:I.metadata.id,themeMode:"light"})},[x]),j=H.useCallback(E=>{r.themeMode!==E&&(s(I=>({...I,themeMode:E})),Vr({themeVariant:E==="system"?y.metadata.variant:E,useSystemTheme:E==="system"}))},[y.metadata.variant,r.themeMode]),T=H.useCallback(E=>{if(E){s(N=>N.themeMode==="system"?N:{...N,themeMode:"system"});return}const I=y.metadata.variant==="dark"?"dark":"light";s(N=>N.themeMode===I?N:{...N,themeMode:I})},[y.metadata.variant]),A=H.useCallback(E=>{const I=x.find(N=>N.metadata.id===E&&N.metadata.variant==="light");I&&s(N=>N.lightThemeId===I.metadata.id?N:{...N,lightThemeId:I.metadata.id})},[x]),_=H.useCallback(E=>{const I=x.find(N=>N.metadata.id===E&&N.metadata.variant==="dark");I&&s(N=>N.darkThemeId===I.metadata.id?N:{...N,darkThemeId:I.metadata.id})},[x]),k={currentTheme:y,availableThemes:x,setTheme:M,customThemesLoading:u,reloadCustomThemes:v,isSystemPreference:r.themeMode==="system",setSystemPreference:T,themeMode:r.themeMode,setThemeMode:j,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:A,setDarkThemePreference:_};return c.jsx(Om.Provider,{value:k,children:e})}let Rc=null;const XY=()=>{if(typeof window>"u"||Rc)return()=>{};let e={showDeletionDialog:te.getState().showDeletionDialog,nativeNotificationsEnabled:te.getState().nativeNotificationsEnabled,notificationMode:te.getState().notificationMode,notifyOnCompletion:te.getState().notifyOnCompletion,notifyOnError:te.getState().notifyOnError,notifyOnInputNeeded:te.getState().notifyOnInputNeeded,summarizeLastMessage:te.getState().summarizeLastMessage,summaryThreshold:te.getState().summaryThreshold,summaryLength:te.getState().summaryLength,maxLastMessageLength:te.getState().maxLastMessageLength,autoDeleteEnabled:te.getState().autoDeleteEnabled,autoSaveEnabled:te.getState().autoSaveEnabled,autoDeleteAfterDays:te.getState().autoDeleteAfterDays,sessionRetentionAction:te.getState().sessionRetentionAction,fontSize:te.getState().fontSize,terminalFontSize:te.getState().terminalFontSize,terminalShell:te.getState().terminalShell,terminalLoginShells:te.getState().terminalLoginShells,editorFontSize:te.getState().editorFontSize,uiFont:te.getState().uiFont,monoFont:te.getState().monoFont,padding:te.getState().padding,cornerRadius:te.getState().cornerRadius,inputBarOffset:te.getState().inputBarOffset,mobileKeyboardMode:te.getState().mobileKeyboardMode,diffLayoutPreference:te.getState().diffLayoutPreference,gitChangesViewMode:te.getState().gitChangesViewMode};const t=te.subscribe(s=>{const o={showDeletionDialog:s.showDeletionDialog,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode,notifyOnCompletion:s.notifyOnCompletion,notifyOnError:s.notifyOnError,notifyOnInputNeeded:s.notifyOnInputNeeded,summarizeLastMessage:s.summarizeLastMessage,summaryThreshold:s.summaryThreshold,summaryLength:s.summaryLength,maxLastMessageLength:s.maxLastMessageLength,autoDeleteEnabled:s.autoDeleteEnabled,autoSaveEnabled:s.autoSaveEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,sessionRetentionAction:s.sessionRetentionAction,fontSize:s.fontSize,terminalFontSize:s.terminalFontSize,terminalShell:s.terminalShell,terminalLoginShells:s.terminalLoginShells,editorFontSize:s.editorFontSize,uiFont:s.uiFont,monoFont:s.monoFont,padding:s.padding,cornerRadius:s.cornerRadius,inputBarOffset:s.inputBarOffset,mobileKeyboardMode:s.mobileKeyboardMode,diffLayoutPreference:s.diffLayoutPreference,gitChangesViewMode:s.gitChangesViewMode},i={};o.showDeletionDialog!==e.showDeletionDialog&&(i.showDeletionDialog=o.showDeletionDialog),o.nativeNotificationsEnabled!==e.nativeNotificationsEnabled&&(i.nativeNotificationsEnabled=o.nativeNotificationsEnabled),o.notificationMode!==e.notificationMode&&(i.notificationMode=o.notificationMode),o.notifyOnCompletion!==e.notifyOnCompletion&&(i.notifyOnCompletion=o.notifyOnCompletion),o.notifyOnError!==e.notifyOnError&&(i.notifyOnError=o.notifyOnError),o.notifyOnInputNeeded!==e.notifyOnInputNeeded&&(i.notifyOnInputNeeded=o.notifyOnInputNeeded),o.summarizeLastMessage!==e.summarizeLastMessage&&(i.summarizeLastMessage=o.summarizeLastMessage),o.summaryThreshold!==e.summaryThreshold&&(i.summaryThreshold=o.summaryThreshold),o.summaryLength!==e.summaryLength&&(i.summaryLength=o.summaryLength),o.maxLastMessageLength!==e.maxLastMessageLength&&(i.maxLastMessageLength=o.maxLastMessageLength),o.autoDeleteEnabled!==e.autoDeleteEnabled&&(i.autoDeleteEnabled=o.autoDeleteEnabled),o.autoSaveEnabled!==e.autoSaveEnabled&&(i.autoSaveEnabled=o.autoSaveEnabled),o.autoDeleteAfterDays!==e.autoDeleteAfterDays&&(i.autoDeleteAfterDays=o.autoDeleteAfterDays),o.sessionRetentionAction!==e.sessionRetentionAction&&(i.sessionRetentionAction=o.sessionRetentionAction),o.fontSize!==e.fontSize&&(i.fontSize=o.fontSize),o.terminalFontSize!==e.terminalFontSize&&(i.terminalFontSize=o.terminalFontSize),o.terminalShell!==e.terminalShell&&(i.terminalShell=o.terminalShell),o.terminalLoginShells!==e.terminalLoginShells&&(i.terminalLoginShells=o.terminalLoginShells),o.editorFontSize!==e.editorFontSize&&(i.editorFontSize=o.editorFontSize),o.uiFont!==e.uiFont&&(i.uiFont=o.uiFont),o.monoFont!==e.monoFont&&(i.monoFont=o.monoFont),o.padding!==e.padding&&(i.padding=o.padding),o.cornerRadius!==e.cornerRadius&&(i.cornerRadius=o.cornerRadius),o.inputBarOffset!==e.inputBarOffset&&(i.inputBarOffset=o.inputBarOffset),o.mobileKeyboardMode!==e.mobileKeyboardMode&&(i.mobileKeyboardMode=o.mobileKeyboardMode),o.diffLayoutPreference!==e.diffLayoutPreference&&(i.diffLayoutPreference=o.diffLayoutPreference),o.gitChangesViewMode!==e.gitChangesViewMode&&(i.gitChangesViewMode=o.gitChangesViewMode),e=o,Object.keys(i).length>0&&Vr(i)});let n=!1;const r=()=>{n||(n=!0,t(),Rc===r&&(Rc=null))};return Rc=r,r},ro={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},yw={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1,hasTouchOnlyPointer:!1},kj=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("surface")==="desktop",Mj=e=>{if(typeof navigator>"u")return{isExplicitTablet:!1};const t=navigator.userAgent||"",n=navigator.platform||"",r=/iPad/i.test(t)||(/Macintosh|MacIntel/i.test(t)||/MacIntel/i.test(n))&&e>1,s=/Android/i.test(t)&&!/Mobile/i.test(t),o=/Tablet/i.test(t);return{isExplicitTablet:r||s||o}},Ij=(e,t,n)=>{if(typeof window>"u")return;const r=document.documentElement;r.classList.remove("device-mobile","device-tablet","device-desktop"),r.classList.add(t==="mobile"?"device-mobile":t==="tablet"?"device-tablet":"device-desktop"),e?(r.classList.add("desktop-runtime"),r.classList.remove("mobile-pointer")):(r.classList.remove("desktop-runtime"),n?r.classList.add("mobile-pointer"):r.classList.remove("mobile-pointer"))};function tu(){const e=window.innerWidth,t=typeof window.matchMedia=="function",n=t?window.matchMedia("(pointer: coarse)"):null,r=t?window.matchMedia("(hover: none)"):null,s=n?.matches??!1,o=r?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,a=wt()||kj(),{isExplicitTablet:l}=Mj(i),d=s||o||i>0,f=s||o,u=e>ro.md&&e<=ro.lg,h=e<=ro.md;let m=d&&h,g=d&&!m&&(u||l),x=!d||!g&&e>ro.lg,b="desktop";a?(m=!1,g=!1,x=!0,b="desktop"):un()?(m=!0,g=!1,x=!1,b="mobile"):m?b="mobile":g?b="tablet":(x=!0,b="desktop"),Ij(a,b,d);let S="xs";for(const[y,v]of Object.entries(ro))e>=v&&(S=y);return{isMobile:m,isTablet:g,isDesktop:x,deviceType:b,screenWidth:e,breakpoint:S,hasTouchInput:d,hasTouchOnlyPointer:f}}const Ej=(e,t)=>e.isMobile===t.isMobile&&e.isTablet===t.isTablet&&e.isDesktop===t.isDesktop&&e.deviceType===t.deviceType&&e.screenWidth===t.screenWidth&&e.breakpoint===t.breakpoint&&e.hasTouchInput===t.hasTouchInput&&e.hasTouchOnlyPointer===t.hasTouchOnlyPointer,wl=new Set;let Hr=null,ko,pi=null;const jj=()=>typeof window>"u"?yw:(Hr||(Hr=tu()),Hr),_j=()=>{for(const e of wl)e()},Tj=()=>{ko=void 0;const e=tu();Hr&&Ej(Hr,e)||(Hr=e,_j())},Pc=()=>{typeof window>"u"||ko!==void 0||(ko=window.requestAnimationFrame(Tj))},ad=(e,t)=>e?typeof e.addEventListener=="function"?(e.addEventListener("change",t),()=>e.removeEventListener("change",t)):typeof e.addListener=="function"?(e.addListener(t),()=>e.removeListener(t)):()=>{}:()=>{},Aj=()=>{if(typeof window>"u")return()=>{};Hr=tu(),window.addEventListener("resize",Pc);const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null,t=typeof window.matchMedia=="function"?window.matchMedia("(hover: none)"):null,n=ad(e,Pc),r=ad(t,Pc);return()=>{window.removeEventListener("resize",Pc),n(),r(),ko!==void 0&&(window.cancelAnimationFrame(ko),ko=void 0)}},Nj=e=>typeof window>"u"?()=>{}:(wl.add(e),pi||(pi=Aj()),()=>{wl.delete(e),wl.size===0&&pi&&(pi(),pi=null,Hr=null)}),Lj=()=>typeof window>"u"?!1:!!(navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)")?.matches||window.matchMedia?.("(display-mode: fullscreen)")?.matches),l2=()=>{if(typeof window>"u"||wt())return!1;const e=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return Lj()&&e>0&&window.innerWidth>ro.md};function JY(){const[e,t]=p.useState(()=>l2());return p.useEffect(()=>{if(typeof window>"u")return;const n=()=>t(l2()),r=window.matchMedia?.("(display-mode: standalone)"),s=window.matchMedia?.("(display-mode: fullscreen)");n(),window.addEventListener("resize",n),window.addEventListener("focus",n);const o=a=>{a&&(typeof a.addEventListener=="function"?a.addEventListener("change",n):typeof a.addListener=="function"&&a.addListener(n))},i=a=>{a&&(typeof a.removeEventListener=="function"?a.removeEventListener("change",n):typeof a.removeListener=="function"&&a.removeListener(n))};return o(r),o(s),()=>{window.removeEventListener("resize",n),window.removeEventListener("focus",n),i(r),i(s)}},[]),e}const Rj=()=>typeof window>"u"?"portrait":window.matchMedia?.("(orientation: landscape)")?.matches?"landscape":"portrait";function QY(){const[e,t]=p.useState(Rj);return p.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(orientation: landscape)"),r=()=>t(n.matches?"landscape":"portrait");return r(),ad(n,r)},[]),e}const Pj=600,Dj=1e3,Hm=()=>{if(typeof window>"u")return{enabled:!1,roomyForPanels:!1};const e=window.innerWidth,t=window.innerHeight,n=oS()||Math.min(e,t)>=Pj;return{enabled:n,roomyForPanels:n&&e>t&&e>=Dj}},Oj=(e,t)=>e.enabled===t.enabled&&e.roomyForPanels===t.roomyForPanels,vw={enabled:!1,roomyForPanels:!1},Sl=new Set;let Fr=null,Mo,mi=null;const Hj=()=>typeof window>"u"?vw:(Fr||(Fr=Hm()),Fr),Fj=()=>{for(const e of Sl)e()},Bj=()=>{Mo=void 0;const e=Hm();Fr&&Oj(Fr,e)||(Fr=e,Fj())},xf=()=>{typeof window>"u"||Mo!==void 0||(Mo=window.requestAnimationFrame(Bj))},Vj=()=>{if(typeof window>"u")return()=>{};Fr=Hm(),window.addEventListener("resize",xf);const e=typeof window.matchMedia=="function"?window.matchMedia("(orientation: landscape)"):null,t=ad(e,xf);return()=>{window.removeEventListener("resize",xf),t(),Mo!==void 0&&(window.cancelAnimationFrame(Mo),Mo=void 0)}},$j=e=>typeof window>"u"?()=>{}:(Sl.add(e),mi||(mi=Vj()),()=>{Sl.delete(e),Sl.size===0&&mi&&(mi(),mi=null,Fr=null)});function nu(){return p.useSyncExternalStore($j,Hj,()=>vw)}function On(){return p.useSyncExternalStore(Nj,jj,()=>yw)}const Fm=e=>{const t=e;return de(t.directory??null)??de(t.project?.worktree??null)};let Dc=null;const eX=()=>{if(typeof window>"u"||typeof document>"u"||Dc)return()=>{};const e=()=>{document.visibilityState!=="hidden"&&iS()};document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),window.addEventListener("online",e);let t=!1;const n=()=>{t||(t=!0,document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),window.removeEventListener("online",e),Dc===n&&(Dc=null))};return Dc=n,n},zj=(e,t)=>{const n={};return Fu(e.favoriteModels,t.favoriteModels)||(n.favoriteModels=e.favoriteModels),Fu(e.hiddenModels,t.hiddenModels)||(n.hiddenModels=e.hiddenModels),jg(e.collapsedModelProviders,t.collapsedModelProviders)||(n.collapsedModelProviders=e.collapsedModelProviders),Fu(e.recentModels,t.recentModels)||(n.recentModels=e.recentModels),jg(e.recentAgents,t.recentAgents)||(n.recentAgents=e.recentAgents),cS(e.recentEfforts,t.recentEfforts)||(n.recentEfforts=e.recentEfforts),n},tX=()=>{if(typeof window>"u")return()=>{};const e=te.subscribe((t,n)=>{const r=zj(t,n);Object.keys(r).length!==0&&Vr(r).catch(()=>{})});return()=>{e(),aS()}};let bf=null;const Bm=()=>(bf??=mt(()=>import("./MarkdownRendererImpl-BkT5TUWF.js"),__vite__mapDeps([12,5,1,6,13,14,15,16,17,11,8,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43])).catch(e=>{throw bf=null,e}),bf),nX=()=>{Bm().catch(()=>{})},xw={add:'<path d="M11 11V5H13V11H19V13H13V19H11V13H5V11H11Z" fill="currentColor"/>',"add-circle":'<path d="M11 11V7H13V11H17V13H13V17H11V13H7V11H11ZM12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20Z" fill="currentColor"/>',"ai-agent":'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 14.7096 20.9205 17.1697 19.1709 18.9697C17.3551 20.8376 14.8124 22 12 22C9.18756 22 6.64488 20.8376 4.8291 18.9697C3.07949 17.1697 2 14.7096 2 12C2 6.47715 6.47715 2 12 2ZM12 16C10.0022 16 8.20124 16.8375 6.9248 18.1816C8.30642 19.3175 10.0724 20 12 20C13.9274 20 15.6927 19.3173 17.0742 18.1816C15.7978 16.8377 13.9975 16 12 16ZM12 4C7.58172 4 4 7.58172 4 12C4 13.7701 4.57462 15.4044 5.54785 16.7295C7.1822 15.0483 9.46797 14 12 14C14.5318 14 16.8169 15.0485 18.4512 16.7295C19.4246 15.4043 20 13.7703 20 12C20 7.58172 16.4183 4 12 4ZM11.5293 5.31934C11.7058 4.89329 12.2943 4.89329 12.4707 5.31934L12.7236 5.93066C13.1556 6.97343 13.9615 7.80622 14.9746 8.25684L15.6924 8.5752C16.1029 8.75796 16.1028 9.35627 15.6924 9.53906L14.9326 9.87695C13.9448 10.3163 13.1534 11.1193 12.7139 12.1279L12.4668 12.6934C12.2864 13.1074 11.7137 13.1074 11.5332 12.6934L11.2871 12.1279C10.8476 11.1193 10.0552 10.3163 9.06738 9.87695L8.30762 9.53906C7.89719 9.35628 7.89717 8.75795 8.30762 8.5752L9.02539 8.25684C10.0385 7.80623 10.8445 6.97345 11.2764 5.93066L11.5293 5.31934Z" fill="currentColor"/>',"ai-generate-2":'<path d="M20.4668 8.69379L20.7134 8.12811C21.1529 7.11947 21.9445 6.31641 22.9323 5.87708L23.6919 5.53922C24.1027 5.35653 24.1027 4.75881 23.6919 4.57612L22.9748 4.25714C21.9616 3.80651 21.1558 2.97373 20.7238 1.93083L20.4706 1.31953C20.2942 0.893489 19.7058 0.893489 19.5293 1.31953L19.2761 1.93083C18.8442 2.97373 18.0384 3.80651 17.0252 4.25714L16.308 4.57612C15.8973 4.75881 15.8973 5.35653 16.308 5.53922L17.0677 5.87708C18.0555 6.31641 18.8471 7.11947 19.2866 8.12811L19.5331 8.69379C19.7136 9.10792 20.2864 9.10792 20.4668 8.69379ZM5.79993 16H7.95399L8.55399 14.5H11.4459L12.0459 16H14.1999L10.9999 8H8.99993L5.79993 16ZM9.99993 10.8852L10.6459 12.5H9.35399L9.99993 10.8852ZM15 16V8H17V16H15ZM3 3C2.44772 3 2 3.44772 2 4V20C2 20.5523 2.44772 21 3 21H21C21.5523 21 22 20.5523 22 20V11H20V19H4V5H14V3H3Z" fill="currentColor"/>',alert:'<path d="M12.8659 3.00017L22.3922 19.5002C22.6684 19.9785 22.5045 20.5901 22.0262 20.8662C21.8742 20.954 21.7017 21.0002 21.5262 21.0002H2.47363C1.92135 21.0002 1.47363 20.5525 1.47363 20.0002C1.47363 19.8246 1.51984 19.6522 1.60761 19.5002L11.1339 3.00017C11.41 2.52187 12.0216 2.358 12.4999 2.63414C12.6519 2.72191 12.7782 2.84815 12.8659 3.00017ZM4.20568 19.0002H19.7941L11.9999 5.50017L4.20568 19.0002ZM10.9999 16.0002H12.9999V18.0002H10.9999V16.0002ZM10.9999 9.00017H12.9999V14.0002H10.9999V9.00017Z" fill="currentColor"/>',"align-justify":'<path d="M3 4H21V6H3V4ZM3 19H21V21H3V19ZM3 14H21V16H3V14ZM3 9H21V11H3V9Z" fill="currentColor"/>',apple:'<path d="M15.778 8.20793C15.3053 8.1711 14.7974 8.28434 14.0197 8.58067C14.085 8.55577 13.2775 8.87173 13.0511 8.95077C12.5494 9.12593 12.1364 9.22198 11.6734 9.22198C11.2151 9.22198 10.7925 9.13042 10.3078 8.96683C10.1524 8.91441 9.99616 8.8564 9.80283 8.7809C9.71993 8.74852 9.41997 8.62947 9.3544 8.60379C8.70626 8.34996 8.34154 8.25434 8.03885 8.26181C6.88626 8.2765 5.79557 8.9421 5.16246 10.0442C3.87037 12.2875 4.58583 16.3428 6.47459 19.075C7.4802 20.5189 8.03062 21.035 8.25199 21.0279C8.4743 21.0183 8.63777 20.9713 9.03567 20.8026C9.11485 20.7689 9.11485 20.7689 9.202 20.7317C10.2077 20.3032 10.9118 20.114 11.9734 20.114C12.9944 20.114 13.6763 20.2997 14.6416 20.7159C14.7302 20.7542 14.7302 20.7542 14.8097 20.7884C15.2074 20.9588 15.3509 20.9962 15.6016 20.9902C15.9591 20.9846 16.4003 20.5726 17.3791 19.1362C17.6471 18.7447 17.884 18.3333 18.0895 17.9168C17.9573 17.8077 17.826 17.6917 17.6975 17.5693C16.4086 16.3408 15.6114 14.6845 15.5895 12.6391C15.5756 11.0186 16.1057 9.61487 16.999 8.45797C16.6293 8.3142 16.2216 8.23805 15.778 8.20793ZM15.9334 6.21398C16.6414 6.26198 18.6694 6.47798 19.9894 8.40998C19.8814 8.46998 17.5654 9.81397 17.5894 12.622C17.6254 15.982 20.5294 17.098 20.5654 17.11C20.5414 17.194 20.0974 18.706 19.0294 20.266C18.1054 21.622 17.1454 22.966 15.6334 22.99C14.1454 23.026 13.6654 22.114 11.9734 22.114C10.2694 22.114 9.74138 22.966 8.33738 23.026C6.87338 23.074 5.76938 21.562 4.83338 20.218C2.92538 17.458 1.47338 12.442 3.42938 9.04597C4.40138 7.35397 6.12938 6.28598 8.01338 6.26198C9.44138 6.22598 10.7974 7.22198 11.6734 7.22198C12.5374 7.22198 14.0854 6.06998 15.9334 6.21398ZM14.7934 4.38998C14.0134 5.32598 12.7414 6.05798 11.5054 5.96198C11.3374 4.68998 11.9614 3.35798 12.6814 2.52998C13.4854 1.59398 14.8294 0.897976 15.9454 0.849976C16.0894 2.14598 15.5734 3.45398 14.7934 4.38998Z" fill="currentColor"/>',"arch-linux":'<path fill="currentColor" d="M12 2.2c-1.06 2.6-1.7 4.3-2.88 6.82.72.76 1.6 1.65 3.04 2.66-1.55-.64-2.61-1.29-3.4-1.96-1.5 3.13-3.83 7.57-6.76 12.08 2.3-1.33 4.09-2.15 5.76-2.47-.08-.35-.13-.73-.12-1.13l.01-.08c.06-2.25 1.23-3.98 2.61-3.87 1.38.1 2.45 2 2.39 4.25-.01.39-.06.76-.14 1.1 1.66.33 3.44 1.15 5.72 2.47-1.16-1.8-2.22-3.62-3.16-5.35-.74-.57-1.51-1.3-2.95-2.04.99.26 1.7.57 2.25.92C13.03 13.04 12.2 11.05 12 10.4c-.2.65-1.03 2.64-2.37 5.2.55-.35 1.26-.66 2.25-.92-1.44.74-2.21 1.47-2.95 2.04A78.9 78.9 0 0 1 5.77 22.07c2.28-1.32 4.06-2.14 5.72-2.47-.08-.34-.13-.71-.14-1.1-.06-2.25 1.01-4.15 2.39-4.25 1.38-.11 2.55 1.62 2.61 3.87l.01.08c.01.4-.04.78-.12 1.13 1.67.32 3.46 1.14 5.76 2.47-2.93-4.51-5.26-8.95-6.76-12.08-.79.67-1.85 1.32-3.4 1.96 1.44-1.01 2.32-1.9 3.04-2.66C13.7 6.5 13.06 4.8 12 2.2Z"/>',archive:'<path d="M3 10H2V4.00293C2 3.44903 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.43788 22 4.00293V10H21V20.0015C21 20.553 20.5551 21 20.0066 21H3.9934C3.44476 21 3 20.5525 3 20.0015V10ZM19 10H5V19H19V10ZM4 5V8H20V5H4ZM9 12H15V14H9V12Z" fill="currentColor"/>',"archive-stack":'<path d="M4 5H20V3H4V5ZM20 9H4V7H20V9ZM3 11H10V13H14V11H21V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V11ZM16 13V15H8V13H5V19H19V13H16Z" fill="currentColor"/>',"arrow-down":'<path d="M13.0001 16.1716L18.3641 10.8076L19.7783 12.2218L12.0001 20L4.22192 12.2218L5.63614 10.8076L11.0001 16.1716V4H13.0001V16.1716Z" fill="currentColor"/>',"arrow-down-s":'<path d="M11.9999 13.1714L16.9497 8.22168L18.3639 9.63589L11.9999 15.9999L5.63599 9.63589L7.0502 8.22168L11.9999 13.1714Z" fill="currentColor"/>',"arrow-go-back":'<path d="M5.82843 6.99955L8.36396 9.53509L6.94975 10.9493L2 5.99955L6.94975 1.0498L8.36396 2.46402L5.82843 4.99955H13C17.4183 4.99955 21 8.58127 21 12.9996C21 17.4178 17.4183 20.9996 13 20.9996H4V18.9996H13C16.3137 18.9996 19 16.3133 19 12.9996C19 9.68584 16.3137 6.99955 13 6.99955H5.82843Z" fill="currentColor"/>',"arrow-go-forward":'<path d="M18.1716 6.99955H11C7.68629 6.99955 5 9.68584 5 12.9996C5 16.3133 7.68629 18.9996 11 18.9996H20V20.9996H11C6.58172 20.9996 3 17.4178 3 12.9996C3 8.58127 6.58172 4.99955 11 4.99955H18.1716L15.636 2.46402L17.0503 1.0498L22 5.99955L17.0503 10.9493L15.636 9.53509L18.1716 6.99955Z" fill="currentColor"/>',"arrow-left":'<path d="M7.82843 10.9999H20V12.9999H7.82843L13.1924 18.3638L11.7782 19.778L4 11.9999L11.7782 4.22168L13.1924 5.63589L7.82843 10.9999Z" fill="currentColor"/>',"arrow-left-right":'<path d="M16.0503 12.0498L21 16.9996L16.0503 21.9493L14.636 20.5351L17.172 17.9988L4 17.9996V15.9996L17.172 15.9988L14.636 13.464L16.0503 12.0498ZM7.94975 2.0498L9.36396 3.46402L6.828 5.9988L20 5.99955V7.99955L6.828 7.9988L9.36396 10.5351L7.94975 11.9493L3 6.99955L7.94975 2.0498Z" fill="currentColor"/>',"arrow-left-s":'<path d="M10.8284 12.0007L15.7782 16.9504L14.364 18.3646L8 12.0007L14.364 5.63672L15.7782 7.05093L10.8284 12.0007Z" fill="currentColor"/>',"arrow-right":'<path d="M16.1716 10.9999L10.8076 5.63589L12.2218 4.22168L20 11.9999L12.2218 19.778L10.8076 18.3638L16.1716 12.9999H4V10.9999H16.1716Z" fill="currentColor"/>',"arrow-right-s":'<path d="M13.1717 12.0007L8.22192 7.05093L9.63614 5.63672L16.0001 12.0007L9.63614 18.3646L8.22192 16.9504L13.1717 12.0007Z" fill="currentColor"/>',"arrow-up":'<path d="M13.0001 7.82843V20H11.0001V7.82843L5.63614 13.1924L4.22192 11.7782L12.0001 4L19.7783 11.7782L18.3641 13.1924L13.0001 7.82843Z" fill="currentColor"/>',"arrow-up-double":'<path d="M12 4.83582L5.79291 11.0429L7.20712 12.4571L12 7.66424L16.7929 12.4571L18.2071 11.0429L12 4.83582ZM12 10.4857L5.79291 16.6928L7.20712 18.107L12 13.3141L16.7929 18.107L18.2071 16.6928L12 10.4857Z" fill="currentColor"/>',"arrow-up-s":'<path d="M11.9999 10.8284L7.0502 15.7782L5.63599 14.364L11.9999 8L18.3639 14.364L16.9497 15.7782L11.9999 10.8284Z" fill="currentColor"/>',"attachment-2":'<path d="M14.8287 7.75737L9.1718 13.4142C8.78127 13.8047 8.78127 14.4379 9.1718 14.8284C9.56232 15.219 10.1955 15.219 10.586 14.8284L16.2429 9.17158C17.4144 8.00001 17.4144 6.10052 16.2429 4.92894C15.0713 3.75737 13.1718 3.75737 12.0002 4.92894L6.34337 10.5858C4.39075 12.5384 4.39075 15.7042 6.34337 17.6569C8.29599 19.6095 11.4618 19.6095 13.4144 17.6569L19.0713 12L20.4855 13.4142L14.8287 19.0711C12.095 21.8047 7.66283 21.8047 4.92916 19.0711C2.19549 16.3374 2.19549 11.9053 4.92916 9.17158L10.586 3.51473C12.5386 1.56211 15.7045 1.56211 17.6571 3.51473C19.6097 5.46735 19.6097 8.63317 17.6571 10.5858L12.0002 16.2427C10.8287 17.4142 8.92916 17.4142 7.75759 16.2427C6.58601 15.0711 6.58601 13.1716 7.75759 12L13.4144 6.34316L14.8287 7.75737Z" fill="currentColor"/>',book:'<path d="M3 18.5V5C3 3.34315 4.34315 2 6 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22H6.5C4.567 22 3 20.433 3 18.5ZM19 20V17H6.5C5.67157 17 5 17.6716 5 18.5C5 19.3284 5.67157 20 6.5 20H19ZM5 15.3368C5.45463 15.1208 5.9632 15 6.5 15H19V4H6C5.44772 4 5 4.44772 5 5V15.3368Z" fill="currentColor"/>',"book-open":'<path d="M13 21V23H11V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H9C10.1947 3 11.2671 3.52375 12 4.35418C12.7329 3.52375 13.8053 3 15 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H13ZM20 19V5H15C13.8954 5 13 5.89543 13 7V19H20ZM11 19V7C11 5.89543 10.1046 5 9 5H4V19H11Z" fill="currentColor"/>',brain:'<path d="M9 4C10.1046 4 11 4.89543 11 6V12.8271C10.1058 12.1373 8.96602 11.7305 7.6644 11.5136L7.3356 13.4864C8.71622 13.7165 9.59743 14.1528 10.1402 14.7408C10.67 15.3147 11 16.167 11 17.5C11 18.8807 9.88071 20 8.5 20C7.11929 20 6 18.8807 6 17.5V17.1493C6.43007 17.2926 6.87634 17.4099 7.3356 17.4864L7.6644 15.5136C6.92149 15.3898 6.1752 15.1144 5.42909 14.7599C4.58157 14.3573 4 13.499 4 12.5C4 11.6653 4.20761 11.0085 4.55874 10.5257C4.90441 10.0504 5.4419 9.6703 6.24254 9.47014L7 9.28078V6C7 4.89543 7.89543 4 9 4ZM12 3.35418C11.2671 2.52376 10.1947 2 9 2C6.79086 2 5 3.79086 5 6V7.77422C4.14895 8.11644 3.45143 8.64785 2.94126 9.34933C2.29239 10.2415 2 11.3347 2 12.5C2 14.0652 2.79565 15.4367 4 16.2422V17.5C4 19.9853 6.01472 22 8.5 22C9.91363 22 11.175 21.3482 12 20.3287C12.825 21.3482 14.0864 22 15.5 22C17.9853 22 20 19.9853 20 17.5V16.2422C21.2044 15.4367 22 14.0652 22 12.5C22 11.3347 21.7076 10.2415 21.0587 9.34933C20.5486 8.64785 19.8511 8.11644 19 7.77422V6C19 3.79086 17.2091 2 15 2C13.8053 2 12.7329 2.52376 12 3.35418ZM18 17.1493V17.5C18 18.8807 16.8807 20 15.5 20C14.1193 20 13 18.8807 13 17.5C13 16.167 13.33 15.3147 13.8598 14.7408C14.4026 14.1528 15.2838 13.7165 16.6644 13.4864L16.3356 11.5136C15.034 11.7305 13.8942 12.1373 13 12.8271V6C13 4.89543 13.8954 4 15 4C16.1046 4 17 4.89543 17 6V9.28078L17.7575 9.47014C18.5581 9.6703 19.0956 10.0504 19.4413 10.5257C19.7924 11.0085 20 11.6653 20 12.5C20 13.499 19.4184 14.3573 18.5709 14.7599C17.8248 15.1144 17.0785 15.3898 16.3356 15.5136L16.6644 17.4864C17.1237 17.4099 17.5699 17.2926 18 17.1493Z" fill="currentColor"/>',"brain-ai-3":'<path d="M19.5 4.7832V7.6709L22 9.11426V14.8867L19.499 16.3311L19.5 19.2178L14.5 22.1045L12 20.6611L9.5 22.1045L4.5 19.2178V16.3311L2 14.8877L2.00098 9.11328L4.5 7.66992V4.78418L9.5 1.89746L11.999 3.34082L14.501 1.89648L19.5 4.7832ZM13 5.07227V7H11V5.07324L9.5 4.20703L6.49902 5.93848V8.8252L4 10.2676V13.7334L6.5 15.1768V18.0635L9.5 19.7959L11 18.9287V17H13V18.9297L14.5 19.7959L17.5 18.0625V15.1768L20 13.7324V10.2695L17.499 8.8252L17.5 5.9375L14.501 4.20605L13 5.07227ZM14.2646 13.1602C14.3529 12.9473 14.6472 12.9473 14.7354 13.1602L14.8623 13.4648C15.0783 13.986 15.4807 14.4027 15.9873 14.6279L16.3457 14.7871C16.5511 14.8784 16.5511 15.1773 16.3457 15.2686L15.9658 15.4375C15.4721 15.6571 15.0761 16.0586 14.8564 16.5625L14.7334 16.8447C14.6432 17.0517 14.3569 17.0517 14.2666 16.8447L14.1436 16.5625C13.9239 16.0586 13.5279 15.6571 13.0342 15.4375L12.6543 15.2686C12.4489 15.1773 12.4489 14.8784 12.6543 14.7871L13.0127 14.6279C13.5193 14.4027 13.9217 13.986 14.1377 13.4648L14.2646 13.1602ZM9.58789 7.7793C9.74239 7.40671 10.2577 7.4067 10.4121 7.7793L10.6338 8.31445C11.0118 9.22695 11.7161 9.95624 12.6025 10.3506L13.2305 10.6289C13.5899 10.7887 13.5897 11.3117 13.2305 11.4717L12.5654 11.7676C11.7013 12.152 11.0086 12.8548 10.624 13.7373L10.4082 14.2324C10.2504 14.5948 9.74973 14.5948 9.5918 14.2324L9.37598 13.7373C8.99143 12.8548 8.29875 12.152 7.43457 11.7676L6.76953 11.4717C6.41033 11.3117 6.41022 10.7887 6.76953 10.6289L7.39746 10.3506C8.2839 9.95624 8.98832 9.22697 9.36621 8.31445L9.58789 7.7793Z" fill="currentColor"/>',brush:'<path d="M15.4565 9.67503L15.3144 9.53297C14.6661 8.90796 13.8549 8.43369 12.9235 8.18412C10.0168 7.40527 7.22541 9.05273 6.43185 12.0143C6.38901 12.1742 6.36574 12.3537 6.3285 12.8051C6.17423 14.6752 5.73449 16.0697 4.5286 17.4842C6.78847 18.3727 9.46572 18.9986 11.5016 18.9986C13.9702 18.9986 16.1644 17.3394 16.8126 14.9202C17.3306 12.9869 16.7513 11.0181 15.4565 9.67503ZM13.2886 6.21301L18.2278 2.37142C18.6259 2.0618 19.1922 2.09706 19.5488 2.45367L22.543 5.44787C22.8997 5.80448 22.9349 6.37082 22.6253 6.76891L18.7847 11.7068C19.0778 12.8951 19.0836 14.1721 18.7444 15.4379C17.8463 18.7897 14.8142 20.9986 11.5016 20.9986C8 20.9986 3.5 19.4967 1 17.9967C4.97978 14.9967 4.04722 13.1865 4.5 11.4967C5.55843 7.54658 9.34224 5.23935 13.2886 6.21301ZM16.7015 8.09161C16.7673 8.15506 16.8319 8.21964 16.8952 8.28533L18.0297 9.41984L20.5046 6.23786L18.7589 4.4921L15.5769 6.96698L16.7015 8.09161Z" fill="currentColor"/>',bug:'<path d="M13 19.9C15.2822 19.4367 17 17.419 17 15V12C17 11.299 16.8564 10.6219 16.5846 10H7.41538C7.14358 10.6219 7 11.299 7 12V15C7 17.419 8.71776 19.4367 11 19.9V14H13V19.9ZM5.5358 17.6907C5.19061 16.8623 5 15.9534 5 15H2V13H5V12C5 11.3573 5.08661 10.7348 5.2488 10.1436L3.0359 8.86602L4.0359 7.13397L6.05636 8.30049C6.11995 8.19854 6.18609 8.09835 6.25469 8H17.7453C17.8139 8.09835 17.88 8.19854 17.9436 8.30049L19.9641 7.13397L20.9641 8.86602L18.7512 10.1436C18.9134 10.7348 19 11.3573 19 12V13H22V15H19C19 15.9534 18.8094 16.8623 18.4642 17.6907L20.9641 19.134L19.9641 20.866L17.4383 19.4077C16.1549 20.9893 14.1955 22 12 22C9.80453 22 7.84512 20.9893 6.56171 19.4077L4.0359 20.866L3.0359 19.134L5.5358 17.6907ZM8 6C8 3.79086 9.79086 2 12 2C14.2091 2 16 3.79086 16 6H8Z" fill="currentColor"/>',"centos-fill":'<path d="M12 13.0607L16.47 17.531L12 22L7.53 17.53L12 13.0607ZM3.99968 16.1207L7.87868 19.9997L4 20L3.99968 16.1207ZM19.9997 16.1207L20 20L16.1207 19.9997L19.9997 16.1207ZM17.53 7.53L22 12L17.531 16.47L13.0607 12L17.53 7.53ZM6.47 7.53L10.9393 12L6.469 16.469L2 12L6.47 7.53ZM12 2L16.469 6.469L12 10.9393L7.53 6.47L12 2ZM7.87868 3.99968L3.99968 7.87868L4 4L7.87868 3.99968ZM20 4L19.9997 7.87868L16.1207 3.99968L20 4Z" fill="currentColor"/>',"chat-1":'<path d="M10 3H14C18.4183 3 22 6.58172 22 11C22 15.4183 18.4183 19 14 19V22.5C9 20.5 2 17.5 2 11C2 6.58172 5.58172 3 10 3ZM12 17H14C17.3137 17 20 14.3137 20 11C20 7.68629 17.3137 5 14 5H10C6.68629 5 4 7.68629 4 11C4 14.61 6.46208 16.9656 12 19.4798V17Z" fill="currentColor"/>',"chat-3":'<path d="M7.29117 20.8242L2 22L3.17581 16.7088C2.42544 15.3056 2 13.7025 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.6944 21.5746 7.29117 20.8242ZM7.58075 18.711L8.23428 19.0605C9.38248 19.6745 10.6655 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 13.3345 4.32549 14.6175 4.93949 15.7657L5.28896 16.4192L4.63416 19.3658L7.58075 18.711Z" fill="currentColor"/>',"chat-4":'<path d="M5.76282 17H20V5H4V18.3851L5.76282 17ZM6.45455 19L2 22.5V4C2 3.44772 2.44772 3 3 3H21C21.5523 3 22 3.44772 22 4V18C22 18.5523 21.5523 19 21 19H6.45455Z" fill="currentColor"/>',"chat-ai-3":'<path d="M12 1.99996C12.8632 1.99996 13.701 2.10973 14.5 2.31539L14 4.25192C13.3608 4.0874 12.6906 3.99997 12 3.99997C7.58174 3.99997 4.00002 7.58172 4 12C4 13.3344 4.3255 14.6174 4.93945 15.7656L5.28906 16.4189L4.63379 19.3662L7.58105 18.7109L8.23438 19.0605C9.38255 19.6745 10.6656 20 12 20C16.4183 20 20 16.4183 20 12C20 11.6771 19.9805 11.3587 19.9434 11.0459L21.9297 10.8095C21.976 11.1999 22 11.5972 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.69425 21.5746 7.29102 20.8242L2 22L3.17578 16.709C2.42541 15.3057 2 13.7025 2 12C2.00002 6.47714 6.47717 1.99996 12 1.99996ZM19.5293 1.3193C19.7058 0.893513 20.2942 0.8935 20.4707 1.3193L20.7236 1.93063C21.1555 2.97343 21.9615 3.80614 22.9746 4.2568L23.6914 4.57614C24.1022 4.75882 24.1022 5.35635 23.6914 5.53903L22.9326 5.87692C21.945 6.3162 21.1534 7.11943 20.7139 8.1279L20.4668 8.69333C20.2863 9.10747 19.7136 9.10747 19.5332 8.69333L19.2861 8.1279C18.8466 7.11942 18.0551 6.3162 17.0674 5.87692L16.3076 5.53903C15.8974 5.35618 15.8974 4.75895 16.3076 4.57614L17.0254 4.2568C18.0384 3.80614 18.8445 2.97343 19.2764 1.93063L19.5293 1.3193Z" fill="currentColor"/>',"chat-history":'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.298 22 8.69525 21.5748 7.29229 20.8248L2 22L3.17629 16.7097C2.42562 15.3063 2 13.7028 2 12C2 6.47715 6.47715 2 12 2ZM12 4C7.58172 4 4 7.58172 4 12C4 13.3347 4.32563 14.6181 4.93987 15.7664L5.28952 16.4201L4.63445 19.3663L7.58189 18.7118L8.23518 19.061C9.38315 19.6747 10.6659 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4ZM13 7V12H17V14H11V7H13Z" fill="currentColor"/>',"chat-new":'<path d="M14 3V5H4V18.3851L5.76282 17H20V10H22V18C22 18.5523 21.5523 19 21 19H6.45455L2 22.5V4C2 3.44772 2.44772 3 3 3H14ZM19 3V0H21V3H24V5H21V8H19V5H16V3H19Z" fill="currentColor"/>',check:'<path d="M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z" fill="currentColor"/>',checkbox:'<path d="M4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM5 5V19H19V5H5ZM11.0026 16L6.75999 11.7574L8.17421 10.3431L11.0026 13.1716L16.6595 7.51472L18.0737 8.92893L11.0026 16Z" fill="currentColor"/>',"checkbox-blank":'<path d="M4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM5 5V19H19V5H5Z" fill="currentColor"/>',"checkbox-blank-circle-fill":'<path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" fill="currentColor"/>',"checkbox-circle":'<path d="M4 12C4 7.58172 7.58172 4 12 4C16.4183 4 20 7.58172 20 12C20 16.4183 16.4183 20 12 20C7.58172 20 4 16.4183 4 12ZM12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2ZM17.4571 9.45711L16.0429 8.04289L11 13.0858L8.20711 10.2929L6.79289 11.7071L11 15.9142L17.4571 9.45711Z" fill="currentColor"/>',"checkbox-multiple":'<path d="M6.99979 7V3C6.99979 2.44772 7.4475 2 7.99979 2H20.9998C21.5521 2 21.9998 2.44772 21.9998 3V16C21.9998 16.5523 21.5521 17 20.9998 17H17V20.9925C17 21.5489 16.551 22 15.9925 22H3.00728C2.45086 22 2 21.5511 2 20.9925L2.00276 8.00748C2.00288 7.45107 2.4518 7 3.01025 7H6.99979ZM8.99979 7H15.9927C16.549 7 17 7.44892 17 8.00748V15H19.9998V4H8.99979V7ZM15 9H4.00255L4.00021 20H15V9ZM8.50242 18L4.96689 14.4645L6.3811 13.0503L8.50242 15.1716L12.7451 10.9289L14.1593 12.3431L8.50242 18Z" fill="currentColor"/>',clipboard:'<path d="M7 4V2H17V4H20.0066C20.5552 4 21 4.44495 21 4.9934V21.0066C21 21.5552 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5551 3 21.0066V4.9934C3 4.44476 3.44495 4 3.9934 4H7ZM7 6H5V20H19V6H17V8H7V6ZM9 4V6H15V4H9Z" fill="currentColor"/>',close:'<path d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z" fill="currentColor"/>',"close-circle":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 10.5858L14.8284 7.75736L16.2426 9.17157L13.4142 12L16.2426 14.8284L14.8284 16.2426L12 13.4142L9.17157 16.2426L7.75736 14.8284L10.5858 12L7.75736 9.17157L9.17157 7.75736L12 10.5858Z" fill="currentColor"/>',cloud:'<path d="M12 2C15.866 2 19 5.13401 19 9C19 9.11351 18.9973 9.22639 18.992 9.33857C21.3265 10.16 23 12.3846 23 15C23 18.3137 20.3137 21 17 21H7C3.68629 21 1 18.3137 1 15C1 12.3846 2.67346 10.16 5.00804 9.33857C5.0027 9.22639 5 9.11351 5 9C5 5.13401 8.13401 2 12 2ZM12 4C9.23858 4 7 6.23858 7 9C7 9.08147 7.00193 9.16263 7.00578 9.24344L7.07662 10.7309L5.67183 11.2252C4.0844 11.7837 3 13.2889 3 15C3 17.2091 4.79086 19 7 19H17C19.2091 19 21 17.2091 21 15C21 12.79 19.21 11 17 11C15.233 11 13.7337 12.1457 13.2042 13.7347L11.3064 13.1021C12.1005 10.7185 14.35 9 17 9C17 6.23858 14.7614 4 12 4Z" fill="currentColor"/>',"cloud-off":'<path d="M3.51472 2.10051L22.6066 21.1924L21.1924 22.6066L19.1782 20.5924C18.503 20.8556 17.7684 21 17 21H7C3.68629 21 1 18.3137 1 15C1 12.3846 2.67346 10.16 5.00804 9.33857C5.0027 9.22639 5 9.11351 5 9C5 8.22228 5.12683 7.47418 5.36094 6.77527L2.10051 3.51472L3.51472 2.10051ZM7 9C7 9.08147 7.00193 9.16263 7.00578 9.24344L7.07662 10.7309L5.67183 11.2252C4.0844 11.7837 3 13.2889 3 15C3 17.2091 4.79086 19 7 19H17C17.1858 19 17.3687 18.9873 17.5478 18.9628L7.03043 8.44519C7.01032 8.62736 7 8.81247 7 9ZM12 2C15.866 2 19 5.13401 19 9C19 9.11351 18.9973 9.22639 18.992 9.33857C21.3265 10.16 23 12.3846 23 15C23 16.0883 22.7103 17.1089 22.2037 17.9889L20.7111 16.4955C20.8974 16.0335 21 15.5287 21 15C21 12.79 19.21 11 17 11C16.4711 11 15.9661 11.1027 15.5039 11.2892L14.0111 9.7964C14.8912 9.28978 15.9118 9 17 9C17 6.23858 14.7614 4 12 4C10.9295 4 9.93766 4.33639 9.12428 4.90922L7.69418 3.48056C8.88169 2.55284 10.3763 2 12 2Z" fill="currentColor"/>',code:'<path d="M23 12L15.9289 19.0711L14.5147 17.6569L20.1716 12L14.5147 6.34317L15.9289 4.92896L23 12ZM3.82843 12L9.48528 17.6569L8.07107 19.0711L1 12L8.07107 4.92896L9.48528 6.34317L3.82843 12Z" fill="currentColor"/>',"code-box":'<path d="M3 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3ZM4 5V19H20V5H4ZM20 12L16.4645 15.5355L15.0503 14.1213L17.1716 12L15.0503 9.87868L16.4645 8.46447L20 12ZM6.82843 12L8.94975 14.1213L7.53553 15.5355L4 12L7.53553 8.46447L8.94975 9.87868L6.82843 12ZM11.2443 17H9.11597L12.7557 7H14.884L11.2443 17Z" fill="currentColor"/>',"code-sslash":'<path d="M24 12L18.3431 17.6569L16.9289 16.2426L21.1716 12L16.9289 7.75736L18.3431 6.34315L24 12ZM2.82843 12L7.07107 16.2426L5.65685 17.6569L0 12L5.65685 6.34315L7.07107 7.75736L2.82843 12ZM9.78845 21H7.66009L14.2116 3H16.3399L9.78845 21Z" fill="currentColor"/>',"collapse-vertical":'<path d="M11.9995 13.4995 16.9492 18.4493 15.535 19.8635 12.9995 17.3279 12.9995 22.9995H10.9995L10.9995 17.3279 8.46643 19.861 7.05222 18.4468 11.9995 13.4995ZM10.9995.999512 10.9995 6.67035 8.46448 4.13535 7.05026 5.54956 12 10.4995 16.9497 5.54977 15.5355 4.13555 12.9995 6.67157V.999512L10.9995.999512Z" fill="currentColor"/>',command:'<path d="M10 8H14V6.5C14 4.567 15.567 3 17.5 3C19.433 3 21 4.567 21 6.5C21 8.433 19.433 10 17.5 10H16V14H17.5C19.433 14 21 15.567 21 17.5C21 19.433 19.433 21 17.5 21C15.567 21 14 19.433 14 17.5V16H10V17.5C10 19.433 8.433 21 6.5 21C4.567 21 3 19.433 3 17.5C3 15.567 4.567 14 6.5 14H8V10H6.5C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5V8ZM8 8V6.5C8 5.67157 7.32843 5 6.5 5C5.67157 5 5 5.67157 5 6.5C5 7.32843 5.67157 8 6.5 8H8ZM8 16H6.5C5.67157 16 5 16.6716 5 17.5C5 18.3284 5.67157 19 6.5 19C7.32843 19 8 18.3284 8 17.5V16ZM16 8H17.5C18.3284 8 19 7.32843 19 6.5C19 5.67157 18.3284 5 17.5 5C16.6716 5 16 5.67157 16 6.5V8ZM16 16V17.5C16 18.3284 16.6716 19 17.5 19C18.3284 19 19 18.3284 19 17.5C19 16.6716 18.3284 16 17.5 16H16ZM10 10V14H14V10H10Z" fill="currentColor"/>',"compass-3":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM16.5 7.5L14 14L7.5 16.5L10 10L16.5 7.5ZM12 13C12.5523 13 13 12.5523 13 12C13 11.4477 12.5523 11 12 11C11.4477 11 11 11.4477 11 12C11 12.5523 11.4477 13 12 13Z" fill="currentColor"/>',"corner-down-left":'<path d="M19.0001 13.9999L19.0002 5L17.0002 4.99997L17.0001 11.9999L6.8283 12L10.778 8.05024L9.36382 6.63603L2.99986 13L9.36382 19.364L10.778 17.9497L6.82826 14L19.0001 13.9999Z" fill="currentColor"/>',cursor:'<path d="M15.3873 13.4975L17.9403 20.5117L13.2418 22.2218L10.6889 15.2076L6.79004 17.6529L8.4086 1.63318L19.9457 12.8646L15.3873 13.4975ZM15.3768 19.3163L12.6618 11.8568L15.6212 11.4459L9.98201 5.9561L9.19088 13.7863L11.7221 12.1988L14.4371 19.6583L15.3768 19.3163Z" fill="currentColor"/>',debian:'<path fill="currentColor" d="M13.7 3.1c-2.8-.8-6.2.2-7.7 2.4 1.9-1.5 4.6-2 6.7-1.2 2.9 1.1 4.3 4.1 3.2 6.8-.9 2.2-3.1 3.6-5.3 3.4-1.8-.1-3.3-1.2-3.8-2.7-.5-1.4 0-2.9 1.2-3.7 1-.7 2.4-.7 3.3.1.7.6.9 1.6.5 2.4-.3.6-.9 1-1.5.9-.5 0-.9-.4-1-.8-.1-.4.1-.8.4-1 .3-.2.6-.1.8.1-.1-.5-.7-.8-1.2-.6-.7.2-1.1.9-1 1.6.1 1 1 1.7 2 1.8 1.2.1 2.4-.6 2.9-1.7.7-1.5.2-3.3-1.1-4.3-1.6-1.3-4-1.3-5.7-.1-2.1 1.5-2.9 4.2-2 6.6 1 2.7 3.6 4.5 6.6 4.7 3.8.2 7.4-2.1 8.8-5.6 1.7-4.2-.6-7.8-4.1-9.1Z"/>',"delete-bin":'<path d="M17 6H22V8H20V21C20 21.5523 19.5523 22 19 22H5C4.44772 22 4 21.5523 4 21V8H2V6H7V3C7 2.44772 7.44772 2 8 2H16C16.5523 2 17 2.44772 17 3V6ZM18 8H6V20H18V8ZM9 11H11V17H9V11ZM13 11H15V17H13V11ZM9 4V6H15V4H9Z" fill="currentColor"/>',docker:'<path fill="currentColor" d="M13.98 11.08h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9H8.92v1.9Zm-2.53 0h2.12v-1.9H6.39v1.9Zm5.06-2.3h2.12v-1.9h-2.12v1.9Zm-2.53 0h2.12v-1.9H8.92v1.9Zm-2.53 0h2.12v-1.9H6.39v1.9Zm2.53-2.3h2.12v-1.9H8.92v1.9ZM3.86 11.08h2.12v-1.9H3.86v1.9Zm17.9-.13c-.46-.3-1.52-.42-2.31-.27-.1-.78-.54-1.46-1.34-2.08l-.46-.3-.31.45c-.62.93-.79 2.46-.12 3.47-.3.16-.89.38-1.68.36H2.11c-.27 1.57.18 3.63 1.36 5.05 1.15 1.38 2.88 2.08 5.15 2.08 4.92 0 8.57-2.27 10.28-6.39.67.01 2.11 0 2.85-1.42.05-.09.23-.46.3-.61l-.29-.34Z"/>',"donut-chart":'<path d="M10.9999 2.04938L11 4.06188C7.05371 4.55396 4 7.92036 4 12C4 16.4183 7.58172 20 12 20C13.8487 20 15.5509 19.3729 16.9055 18.3199L18.3289 19.7428C16.605 21.1536 14.4014 22 12 22C6.47715 22 2 17.5228 2 12C2 6.81468 5.94662 2.55115 10.9999 2.04938ZM21.9506 13.0001C21.7509 15.0111 20.9555 16.8468 19.7433 18.3283L18.3199 16.9055C19.1801 15.799 19.756 14.4606 19.9381 12.9999L21.9506 13.0001ZM13.0011 2.04948C17.725 2.51902 21.4815 6.27589 21.9506 10.9999L19.9381 11C19.4869 7.38162 16.6192 4.51364 13.001 4.062L13.0011 2.04948Z" fill="currentColor"/>',"donut-chart-fill":'<path d="M10.9999 2.04938L11 5.07088C7.6077 5.55612 5 8.47352 5 12C5 15.866 8.13401 19 12 19C13.5723 19 15.0236 18.4816 16.1922 17.6064L18.3289 19.7428C16.605 21.1536 14.4014 22 12 22C6.47715 22 2 17.5228 2 12C2 6.81468 5.94662 2.55115 10.9999 2.04938ZM21.9506 13.0001C21.7509 15.0111 20.9555 16.8468 19.7433 18.3283L17.6064 16.1922C18.2926 15.2759 18.7595 14.1859 18.9291 13L21.9506 13.0001ZM13.0011 2.04948C17.725 2.51902 21.4815 6.27589 21.9506 10.9999L18.9291 10.9998C18.4905 7.93452 16.0661 5.50992 13.001 5.07103L13.0011 2.04948Z" fill="currentColor"/>',download:'<path d="M3 19H21V21H3V19ZM13 13.1716L19.0711 7.1005L20.4853 8.51472L12 17L3.51472 8.51472L4.92893 7.1005L11 13.1716V2H13V13.1716Z" fill="currentColor"/>',"download-cloud":'<path d="M1 14.5C1 12.1716 2.22429 10.1291 4.06426 8.9812C4.56469 5.044 7.92686 2 12 2C16.0731 2 19.4353 5.044 19.9357 8.9812C21.7757 10.1291 23 12.1716 23 14.5C23 17.9216 20.3562 20.7257 17 20.9811L7 21C3.64378 20.7257 1 17.9216 1 14.5ZM16.8483 18.9868C19.1817 18.8093 21 16.8561 21 14.5C21 12.927 20.1884 11.4962 18.8771 10.6781L18.0714 10.1754L17.9517 9.23338C17.5735 6.25803 15.0288 4 12 4C8.97116 4 6.42647 6.25803 6.0483 9.23338L5.92856 10.1754L5.12288 10.6781C3.81156 11.4962 3 12.927 3 14.5C3 16.8561 4.81833 18.8093 7.1517 18.9868L7.325 19H16.675L16.8483 18.9868ZM13 12H16L12 17L8 12H11V8H13V12Z" fill="currentColor"/>',draggable:'<path d="M8.5 7C9.32843 7 10 6.32843 10 5.5C10 4.67157 9.32843 4 8.5 4C7.67157 4 7 4.67157 7 5.5C7 6.32843 7.67157 7 8.5 7ZM8.5 13.5C9.32843 13.5 10 12.8284 10 12C10 11.1716 9.32843 10.5 8.5 10.5C7.67157 10.5 7 11.1716 7 12C7 12.8284 7.67157 13.5 8.5 13.5ZM10 18.5C10 19.3284 9.32843 20 8.5 20C7.67157 20 7 19.3284 7 18.5C7 17.6716 7.67157 17 8.5 17C9.32843 17 10 17.6716 10 18.5ZM15.5 7C16.3284 7 17 6.32843 17 5.5C17 4.67157 16.3284 4 15.5 4C14.6716 4 14 4.67157 14 5.5C14 6.32843 14.6716 7 15.5 7ZM17 12C17 12.8284 16.3284 13.5 15.5 13.5C14.6716 13.5 14 12.8284 14 12C14 11.1716 14.6716 10.5 15.5 10.5C16.3284 10.5 17 11.1716 17 12ZM15.5 20C16.3284 20 17 19.3284 17 18.5C17 17.6716 16.3284 17 15.5 17C14.6716 17 14 17.6716 14 18.5C14 19.3284 14.6716 20 15.5 20Z" fill="currentColor"/>',edit:'<path d="M6.41421 15.89L16.5563 5.74785L15.1421 4.33363L5 14.4758V15.89H6.41421ZM7.24264 17.89H3V13.6473L14.435 2.21231C14.8256 1.82179 15.4587 1.82179 15.8492 2.21231L18.6777 5.04074C19.0682 5.43126 19.0682 6.06443 18.6777 6.45495L7.24264 17.89ZM3 19.89H21V21.89H3V19.89Z" fill="currentColor"/>',equalizer:'<path d="M6.17071 18C6.58254 16.8348 7.69378 16 9 16C10.3062 16 11.4175 16.8348 11.8293 18H22V20H11.8293C11.4175 21.1652 10.3062 22 9 22C7.69378 22 6.58254 21.1652 6.17071 20H2V18H6.17071ZM12.1707 11C12.5825 9.83481 13.6938 9 15 9C16.3062 9 17.4175 9.83481 17.8293 11H22V13H17.8293C17.4175 14.1652 16.3062 15 15 15C13.6938 15 12.5825 14.1652 12.1707 13H2V11H12.1707ZM6.17071 4C6.58254 2.83481 7.69378 2 9 2C10.3062 2 11.4175 2.83481 11.8293 4H22V6H11.8293C11.4175 7.16519 10.3062 8 9 8C7.69378 8 6.58254 7.16519 6.17071 6H2V4H6.17071ZM9 6C9.55228 6 10 5.55228 10 5C10 4.44772 9.55228 4 9 4C8.44772 4 8 4.44772 8 5C8 5.55228 8.44772 6 9 6ZM15 13C15.5523 13 16 12.5523 16 12C16 11.4477 15.5523 11 15 11C14.4477 11 14 11.4477 14 12C14 12.5523 14.4477 13 15 13ZM9 20C9.55228 20 10 19.5523 10 19C10 18.4477 9.55228 18 9 18C8.44772 18 8 18.4477 8 19C8 19.5523 8.44772 20 9 20Z" fill="currentColor"/>',"error-warning":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 15H13V17H11V15ZM11 7H13V13H11V7Z" fill="currentColor"/>',"expand-up-down":'<path d="M18.2072 9.0428 12.0001 2.83569 5.793 9.0428 7.20721 10.457 12.0001 5.66412 16.793 10.457 18.2072 9.0428ZM5.79285 14.9572 12 21.1643 18.2071 14.9572 16.7928 13.543 12 18.3359 7.20706 13.543 5.79285 14.9572Z" fill="currentColor"/>',"external-link":'<path d="M10 6V8H5V19H16V14H18V20C18 20.5523 17.5523 21 17 21H4C3.44772 21 3 20.5523 3 20V7C3 6.44772 3.44772 6 4 6H10ZM21 3V11H19L18.9999 6.413L11.2071 14.2071L9.79289 12.7929L17.5849 5H13V3H21Z" fill="currentColor"/>',eye:'<path d="M12.0003 3C17.3924 3 21.8784 6.87976 22.8189 12C21.8784 17.1202 17.3924 21 12.0003 21C6.60812 21 2.12215 17.1202 1.18164 12C2.12215 6.87976 6.60812 3 12.0003 3ZM12.0003 19C16.2359 19 19.8603 16.052 20.7777 12C19.8603 7.94803 16.2359 5 12.0003 5C7.7646 5 4.14022 7.94803 3.22278 12C4.14022 16.052 7.7646 19 12.0003 19ZM12.0003 16.5C9.51498 16.5 7.50026 14.4853 7.50026 12C7.50026 9.51472 9.51498 7.5 12.0003 7.5C14.4855 7.5 16.5003 9.51472 16.5003 12C16.5003 14.4853 14.4855 16.5 12.0003 16.5ZM12.0003 14.5C13.381 14.5 14.5003 13.3807 14.5003 12C14.5003 10.6193 13.381 9.5 12.0003 9.5C10.6196 9.5 9.50026 10.6193 9.50026 12C9.50026 13.3807 10.6196 14.5 12.0003 14.5Z" fill="currentColor"/>',"eye-off":'<path d="M17.8827 19.2968C16.1814 20.3755 14.1638 21.0002 12.0003 21.0002C6.60812 21.0002 2.12215 17.1204 1.18164 12.0002C1.61832 9.62282 2.81932 7.5129 4.52047 5.93457L1.39366 2.80777L2.80788 1.39355L22.6069 21.1925L21.1927 22.6068L17.8827 19.2968ZM5.9356 7.3497C4.60673 8.56015 3.6378 10.1672 3.22278 12.0002C4.14022 16.0521 7.7646 19.0002 12.0003 19.0002C13.5997 19.0002 15.112 18.5798 16.4243 17.8384L14.396 15.8101C13.7023 16.2472 12.8808 16.5002 12.0003 16.5002C9.51498 16.5002 7.50026 14.4854 7.50026 12.0002C7.50026 11.1196 7.75317 10.2981 8.19031 9.60442L5.9356 7.3497ZM12.9139 14.328L9.67246 11.0866C9.5613 11.3696 9.50026 11.6777 9.50026 12.0002C9.50026 13.3809 10.6196 14.5002 12.0003 14.5002C12.3227 14.5002 12.6309 14.4391 12.9139 14.328ZM20.8068 16.5925L19.376 15.1617C20.0319 14.2268 20.5154 13.1586 20.7777 12.0002C19.8603 7.94818 16.2359 5.00016 12.0003 5.00016C11.1544 5.00016 10.3329 5.11773 9.55249 5.33818L7.97446 3.76015C9.22127 3.26959 10.5793 3.00016 12.0003 3.00016C17.3924 3.00016 21.8784 6.87992 22.8189 12.0002C22.5067 13.6998 21.8038 15.2628 20.8068 16.5925ZM11.7229 7.50857C11.8146 7.50299 11.9071 7.50016 12.0003 7.50016C14.4855 7.50016 16.5003 9.51488 16.5003 12.0002C16.5003 12.0933 16.4974 12.1858 16.4919 12.2775L11.7229 7.50857Z" fill="currentColor"/>',fedora:'<path fill="currentColor" d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2Zm2.9 5.2h-1.35c-.83 0-1.5.67-1.5 1.5v1.35h2.35v2h-2.35v4.15a2.8 2.8 0 0 1-2.8 2.8 2.8 2.8 0 0 1-2.8-2.8c0-1.55 1.25-2.8 2.8-2.8h.8v2h-.8a.8.8 0 1 0 .8.8V8.7a3.5 3.5 0 0 1 3.5-3.5h1.35v2Z"/>',file:'<path d="M9 2.00318V2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8L9 2.00318ZM5.82918 8H9V4.83086L5.82918 8ZM11 4V9C11 9.55228 10.5523 10 10 10H5V20H19V4H11Z" fill="currentColor"/>',"file-add":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11 11V8H13V11H16V13H13V16H11V13H8V11H11Z" fill="currentColor"/>',"file-check":'<path d="M12 20V22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9998 7V14H19V8H15V4H5V20H12ZM14.4646 19.4647L18.0001 23.0002L22.9498 18.0505L21.5356 16.6362L18.0001 20.1718L15.8788 18.0505L14.4646 19.4647Z" fill="currentColor"/>',"file-check-fill":'<path d="M20.9998 7L16 2H3.9985C3.44749 2 3 2.44405 3 2.9918V21.0082C3 21.5447 3.44476 22 3.9934 22H12.3414C12.1203 21.3744 12 20.7013 12 20C12 16.6863 14.6863 14 18 14C19.0928 14 20.1174 14.2922 20.9999 14.8026L20.9998 7ZM14.4646 19.4647L18.0001 23.0002L22.9498 18.0505L21.5356 16.6362L18.0001 20.1718L15.8788 18.0505L14.4646 19.4647Z" fill="currentColor"/>',"file-code":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM17.6569 12L14.1213 15.5355L12.7071 14.1213L14.8284 12L12.7071 9.87868L14.1213 8.46447L17.6569 12ZM6.34315 12L9.87868 8.46447L11.2929 9.87868L9.17157 12L11.2929 14.1213L9.87868 15.5355L6.34315 12Z" fill="currentColor"/>',"file-copy":'<path d="M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6Z" fill="currentColor"/>',"file-copy-2":'<path d="M6.9998 6V3C6.9998 2.44772 7.44752 2 7.9998 2H19.9998C20.5521 2 20.9998 2.44772 20.9998 3V17C20.9998 17.5523 20.5521 18 19.9998 18H16.9998V20.9991C16.9998 21.5519 16.5499 22 15.993 22H4.00666C3.45059 22 3 21.5554 3 20.9991L3.0026 7.00087C3.0027 6.44811 3.45264 6 4.00942 6H6.9998ZM5.00242 8L5.00019 20H14.9998V8H5.00242ZM8.9998 6H16.9998V16H18.9998V4H8.9998V6ZM7 11H13V13H7V11ZM7 15H13V17H7V15Z" fill="currentColor"/>',"file-download":'<path d="M13 12H16L12 16L8 12H11V8H13V12ZM15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-edit":'<path d="M21 6.75736L19 8.75736V4H10V9H5V20H19V17.2426L21 15.2426V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V6.75736ZM21.7782 8.80761L23.1924 10.2218L15.4142 18L13.9979 17.9979L14 16.5858L21.7782 8.80761Z" fill="currentColor"/>',"file-image":'<path d="M15 8V4H5V20H19V8H15ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11 9.5C11 10.3284 10.3284 11 9.5 11C8.67157 11 8 10.3284 8 9.5C8 8.67157 8.67157 8 9.5 8C10.3284 8 11 8.67157 11 9.5ZM17.5 17L13.5 10L8 17H17.5Z" fill="currentColor"/>',"file-list-2":'<path d="M20 22H4C3.44772 22 3 21.5523 3 21V3C3 2.44772 3.44772 2 4 2H20C20.5523 2 21 2.44772 21 3V21C21 21.5523 20.5523 22 20 22ZM19 20V4H5V20H19ZM8 7H16V9H8V7ZM8 11H16V13H8V11ZM8 15H13V17H8V15Z" fill="currentColor"/>',"file-music":'<path d="M16 8V10H13V14.5C13 15.8807 11.8807 17 10.5 17C9.11929 17 8 15.8807 8 14.5C8 13.1193 9.11929 12 10.5 12C10.6712 12 10.8384 12.0172 11 12.05V8H15V4H5V20H19V8H16ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-pdf":'<path d="M12 16H8V8H12C14.2091 8 16 9.79086 16 12C16 14.2091 14.2091 16 12 16ZM10 10V14H12C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10H10ZM15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918Z" fill="currentColor"/>',"file-search":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM13.529 14.4464C11.9951 15.3524 9.98633 15.1464 8.66839 13.8284C7.1063 12.2663 7.1063 9.73367 8.66839 8.17157C10.2305 6.60948 12.7631 6.60948 14.3252 8.17157C15.6432 9.48951 15.8492 11.4983 14.9432 13.0322L17.1537 15.2426L15.7395 16.6569L13.529 14.4464ZM12.911 12.4142C13.6921 11.6332 13.6921 10.3668 12.911 9.58579C12.13 8.80474 10.8637 8.80474 10.0826 9.58579C9.30156 10.3668 9.30156 11.6332 10.0826 12.4142C10.8637 13.1953 12.13 13.1953 12.911 12.4142Z" fill="currentColor"/>',"file-text":'<path d="M21 8V20.9932C21 21.5501 20.5552 22 20.0066 22H3.9934C3.44495 22 3 21.556 3 21.0082V2.9918C3 2.45531 3.4487 2 4.00221 2H14.9968L21 8ZM19 9H14V4H5V20H19V9ZM8 7H11V9H8V7ZM8 11H16V13H8V11ZM8 15H16V17H8V15Z" fill="currentColor"/>',"file-transfer":'<path d="M15 4H5V20H19V8H15V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H16L20.9997 7L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM12 11V8L16 12L12 16V13H8V11H12Z" fill="currentColor"/>',"file-video":'<path d="M15 4V8H19V20H5V4H15ZM3.9985 2C3.44749 2 3 2.44405 3 2.9918V21.0082C3 21.5447 3.44476 22 3.9934 22H20.0066C20.5551 22 21 21.5489 21 20.9925L20.9997 7L16 2H3.9985ZM15.0008 11.667L10.1219 8.41435C10.0562 8.37054 9.979 8.34717 9.9 8.34717C9.6791 8.34717 9.5 8.52625 9.5 8.74717V15.2524C9.5 15.3314 9.5234 15.4086 9.5672 15.4743C9.6897 15.6581 9.9381 15.7078 10.1219 15.5852L15.0008 12.3326C15.0447 12.3033 15.0824 12.2656 15.1117 12.2217C15.2343 12.0379 15.1846 11.7895 15.0008 11.667Z" fill="currentColor"/>',flask:'<path d="M15.9994 2V4H14.9994V7.24291C14.9994 8.40051 15.2506 9.54432 15.7357 10.5954L20.017 19.8714C20.3641 20.6236 20.0358 21.5148 19.2836 21.8619C19.0865 21.9529 18.8721 22 18.655 22H5.34375C4.51532 22 3.84375 21.3284 3.84375 20.5C3.84375 20.2829 3.89085 20.0685 3.98181 19.8714L8.26306 10.5954C8.74816 9.54432 8.99939 8.40051 8.99939 7.24291V4H7.99939V2H15.9994ZM13.3873 10.0012H10.6115C10.5072 10.3644 10.3823 10.7221 10.2371 11.0724L10.079 11.4335L6.12439 20H17.8734L13.9198 11.4335C13.7054 10.9691 13.5276 10.4902 13.3873 10.0012ZM10.9994 7.24291C10.9994 7.49626 10.9898 7.7491 10.9706 8.00087H13.0282C13.0189 7.87982 13.0119 7.75852 13.0072 7.63704L12.9994 7.24291V4H10.9994V7.24291Z" fill="currentColor"/>',folder:'<path d="M4 5V19H20V7H11.5858L9.58579 5H4ZM12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5Z" fill="currentColor"/>',"folder-3":'<path d="M12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5ZM4 7V19H20V7H4Z" fill="currentColor"/>',"folder-3-fill":'<path d="M22 8V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7H21C21.5523 7 22 7.44772 22 8ZM12.4142 5H2V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5Z" fill="currentColor"/>',"folder-6":'<path d="M2 4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21L3 21C2.45 21 2 20.55 2 20V4ZM10.5858 6L9.58579 5H4V7H9.58579L10.5858 6ZM4 9V19L20 19V7H12.4142L10.4142 9H4Z" fill="currentColor"/>',"folder-add":'<path d="M12.4142 5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5ZM4 5V19H20V7H11.5858L9.58579 5H4ZM11 12V9H13V12H16V14H13V17H11V14H8V12H11Z" fill="currentColor"/>',"folder-open":'<path d="M3 21C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H20C20.5523 5 21 5.44772 21 6V9H19V7H11.5858L9.58579 5H4V16.998L5.5 11H22.5L20.1894 20.2425C20.0781 20.6877 19.6781 21 19.2192 21H3ZM19.9384 13H7.06155L5.56155 19H18.4384L19.9384 13Z" fill="currentColor"/>',"folder-open-fill":'<path d="M3 21C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H20C20.5523 5 21 5.44772 21 6V9H4V18.996L6 11H22.5L20.1894 20.2425C20.0781 20.6877 19.6781 21 19.2192 21H3Z" fill="currentColor"/>',"folder-received":'<path d="M22 13H20V7H11.5858L9.58579 5H4V19H13V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H10.4142L12.4142 5H21C21.5523 5 22 5.44772 22 6V13ZM20 17H23V19H20V22.5L15 18L20 13.5V17Z" fill="currentColor"/>',folders:'<path d="M6 7V4C6 3.44772 6.44772 3 7 3H13.4142L15.4142 5H21C21.5523 5 22 5.44772 22 6V16C22 16.5523 21.5523 17 21 17H18V20C18 20.5523 17.5523 21 17 21H3C2.44772 21 2 20.5523 2 20V8C2 7.44772 2.44772 7 3 7H6ZM6 9H4V19H16V17H6V9ZM8 5V15H20V7H14.5858L12.5858 5H8Z" fill="currentColor"/>',fullscreen:'<path d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z" fill="currentColor"/>',"fullscreen-exit":'<path d="M18 7H22V9H16V3H18V7ZM8 9H2V7H6V3H8V9ZM18 17V21H16V15H22V17H18ZM8 15V21H6V17H2V15H8Z" fill="currentColor"/>',"git-branch":'<path d="M7.10508 15.2101C8.21506 15.6501 9 16.7334 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.30622 8.16519 8.41746 7 8.82929V11.9996C7.83566 11.3719 8.87439 11 10 11H14C15.3835 11 16.5482 10.0635 16.8949 8.78991C15.7849 8.34988 15 7.26661 15 6C15 4.34315 16.3431 3 18 3C19.6569 3 21 4.34315 21 6C21 7.3332 20.1303 8.46329 18.9274 8.85392C18.5222 11.2085 16.4703 13 14 13H10C8.61653 13 7.45179 13.9365 7.10508 15.2101ZM6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17ZM6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5ZM18 5C17.4477 5 17 5.44772 17 6C17 6.55228 17.4477 7 18 7C18.5523 7 19 6.55228 19 6C19 5.44772 18.5523 5 18 5Z" fill="currentColor"/>',"git-commit":'<path d="M15.874 13C15.4299 14.7252 13.8638 16 12 16C10.1362 16 8.57006 14.7252 8.12602 13H3V11H8.12602C8.57006 9.27477 10.1362 8 12 8C13.8638 8 15.4299 9.27477 15.874 11H21V13H15.874ZM12 14C13.1046 14 14 13.1046 14 12C14 10.8954 13.1046 10 12 10C10.8954 10 10 10.8954 10 12C10 13.1046 10.8954 14 12 14Z" fill="currentColor"/>',"git-merge":'<path d="M7.10508 8.78991C7.45179 10.0635 8.61653 11 10 11H14C16.4703 11 18.5222 12.7915 18.9274 15.1461C20.1303 15.5367 21 16.6668 21 18C21 19.6569 19.6569 21 18 21C16.3431 21 15 19.6569 15 18C15 16.7334 15.7849 15.6501 16.8949 15.2101C16.5482 13.9365 15.3835 13 14 13H10C8.87439 13 7.83566 12.6281 7 12.0004V15.1707C8.16519 15.5825 9 16.6938 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.26661 8.21506 8.34988 7.10508 8.78991ZM6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7ZM6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19ZM18 19C18.5523 19 19 18.5523 19 18C19 17.4477 18.5523 17 18 17C17.4477 17 17 17.4477 17 18C17 18.5523 17.4477 19 18 19Z" fill="currentColor"/>',"git-pull-request":'<path d="M15 5H17C18.1046 5 19 5.89543 19 7V15.1707C20.1652 15.5825 21 16.6938 21 18C21 19.6569 19.6569 21 18 21C16.3431 21 15 19.6569 15 18C15 16.6938 15.8348 15.5825 17 15.1707V7H15V10L10.5 6L15 2V5ZM5 8.82929C3.83481 8.41746 3 7.30622 3 6C3 4.34315 4.34315 3 6 3C7.65685 3 9 4.34315 9 6C9 7.30622 8.16519 8.41746 7 8.82929V15.1707C8.16519 15.5825 9 16.6938 9 18C9 19.6569 7.65685 21 6 21C4.34315 21 3 19.6569 3 18C3 16.6938 3.83481 15.5825 5 15.1707V8.82929ZM6 7C6.55228 7 7 6.55228 7 6C7 5.44772 6.55228 5 6 5C5.44772 5 5 5.44772 5 6C5 6.55228 5.44772 7 6 7ZM6 19C6.55228 19 7 18.5523 7 18C7 17.4477 6.55228 17 6 17C5.44772 17 5 17.4477 5 18C5 18.5523 5.44772 19 6 19ZM18 19C18.5523 19 19 18.5523 19 18C19 17.4477 18.5523 17 18 17C17.4477 17 17 17.4477 17 18C17 18.5523 17.4477 19 18 19Z" fill="currentColor"/>',"git-repository":'<path d="M13 21V23.5L10 21.5L7 23.5V21H6.5C4.567 21 3 19.433 3 17.5V5C3 3.34315 4.34315 2 6 2H20C20.5523 2 21 2.44772 21 3V20C21 20.5523 20.5523 21 20 21H13ZM13 19H19V16H6.5C5.67157 16 5 16.6716 5 17.5C5 18.3284 5.67157 19 6.5 19H7V17H13V19ZM19 14V4H6V14.0354C6.1633 14.0121 6.33024 14 6.5 14H19ZM7 5H9V7H7V5ZM7 8H9V10H7V8ZM7 11H9V13H7V11Z" fill="currentColor"/>',github:'<path d="M5.88401 18.6533C5.58404 18.4526 5.32587 18.1975 5.0239 17.8369C4.91473 17.7065 4.47283 17.1524 4.55811 17.2583C4.09533 16.6833 3.80296 16.417 3.50156 16.3089C2.9817 16.1225 2.7114 15.5499 2.89784 15.0301C3.08428 14.5102 3.65685 14.2399 4.17672 14.4263C4.92936 14.6963 5.43847 15.1611 6.12425 16.0143C6.03025 15.8974 6.46364 16.441 6.55731 16.5529C6.74784 16.7804 6.88732 16.9182 6.99629 16.9911C7.20118 17.1283 7.58451 17.1874 8.14709 17.1311C8.17065 16.7489 8.24136 16.3783 8.34919 16.0358C5.38097 15.3104 3.70116 13.3952 3.70116 9.63971C3.70116 8.40085 4.0704 7.28393 4.75917 6.3478C4.5415 5.45392 4.57433 4.37284 5.06092 3.15636C5.1725 2.87739 5.40361 2.66338 5.69031 2.57352C5.77242 2.54973 5.81791 2.53915 5.89878 2.52673C6.70167 2.40343 7.83573 2.69705 9.31449 3.62336C10.181 3.41879 11.0885 3.315 12.0012 3.315C12.9129 3.315 13.8196 3.4186 14.6854 3.62277C16.1619 2.69 17.2986 2.39649 18.1072 2.52651C18.1919 2.54013 18.2645 2.55783 18.3249 2.57766C18.6059 2.66991 18.8316 2.88179 18.9414 3.15636C19.4279 4.37256 19.4608 5.45344 19.2433 6.3472C19.9342 7.28337 20.3012 8.39208 20.3012 9.63971C20.3012 13.3968 18.627 15.3048 15.6588 16.032C15.7837 16.447 15.8496 16.9105 15.8496 17.4121C15.8496 18.0765 15.8471 18.711 15.8424 19.4225C15.8412 19.6127 15.8397 19.8159 15.8375 20.1281C16.2129 20.2109 16.5229 20.5077 16.6031 20.9089C16.7114 21.4504 16.3602 21.9773 15.8186 22.0856C14.6794 22.3134 13.8353 21.5538 13.8353 20.5611C13.8353 20.4708 13.836 20.3417 13.8375 20.1145C13.8398 19.8015 13.8412 19.599 13.8425 19.4094C13.8471 18.7019 13.8496 18.0716 13.8496 17.4121C13.8496 16.7148 13.6664 16.2602 13.4237 16.051C12.7627 15.4812 13.0977 14.3973 13.965 14.2999C16.9314 13.9666 18.3012 12.8177 18.3012 9.63971C18.3012 8.68508 17.9893 7.89571 17.3881 7.23559C17.1301 6.95233 17.0567 6.54659 17.199 6.19087C17.3647 5.77663 17.4354 5.23384 17.2941 4.57702L17.2847 4.57968C16.7928 4.71886 16.1744 5.0198 15.4261 5.5285C15.182 5.69438 14.8772 5.74401 14.5932 5.66413C13.7729 5.43343 12.8913 5.315 12.0012 5.315C11.111 5.315 10.2294 5.43343 9.40916 5.66413C9.12662 5.74359 8.82344 5.69492 8.57997 5.53101C7.8274 5.02439 7.2056 4.72379 6.71079 4.58376C6.56735 5.23696 6.63814 5.77782 6.80336 6.19087C6.94565 6.54659 6.87219 6.95233 6.61423 7.23559C6.01715 7.8912 5.70116 8.69376 5.70116 9.63971C5.70116 12.8116 7.07225 13.9683 10.023 14.2999C10.8883 14.3971 11.2246 15.4769 10.5675 16.0482C10.3751 16.2156 10.1384 16.7802 10.1384 17.4121V20.5611C10.1384 21.5474 9.30356 22.2869 8.17878 22.09C7.63476 21.9948 7.27093 21.4766 7.36613 20.9326C7.43827 20.5204 7.75331 20.2116 8.13841 20.1276V19.1381C7.22829 19.1994 6.47656 19.0498 5.88401 18.6533Z" fill="currentColor"/>',"github-fill":'<path d="M12.001 2C6.47598 2 2.00098 6.475 2.00098 12C2.00098 16.425 4.86348 20.1625 8.83848 21.4875C9.33848 21.575 9.52598 21.275 9.52598 21.0125C9.52598 20.775 9.51348 19.9875 9.51348 19.15C7.00098 19.6125 6.35098 18.5375 6.15098 17.975C6.03848 17.6875 5.55098 16.8 5.12598 16.5625C4.77598 16.375 4.27598 15.9125 5.11348 15.9C5.90098 15.8875 6.46348 16.625 6.65098 16.925C7.55098 18.4375 8.98848 18.0125 9.56348 17.75C9.65098 17.1 9.91348 16.6625 10.201 16.4125C7.97598 16.1625 5.65098 15.3 5.65098 11.475C5.65098 10.3875 6.03848 9.4875 6.67598 8.7875C6.57598 8.5375 6.22598 7.5125 6.77598 6.1375C6.77598 6.1375 7.61348 5.875 9.52598 7.1625C10.326 6.9375 11.176 6.825 12.026 6.825C12.876 6.825 13.726 6.9375 14.526 7.1625C16.4385 5.8625 17.276 6.1375 17.276 6.1375C17.826 7.5125 17.476 8.5375 17.376 8.7875C18.0135 9.4875 18.401 10.375 18.401 11.475C18.401 15.3125 16.0635 16.1625 13.8385 16.4125C14.201 16.725 14.5135 17.325 14.5135 18.2625C14.5135 19.6 14.501 20.675 14.501 21.0125C14.501 21.275 14.6885 21.5875 15.1885 21.4875C19.259 20.1133 21.9999 16.2963 22.001 12C22.001 6.475 17.526 2 12.001 2Z" fill="currentColor"/>',global:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM9.71002 19.6674C8.74743 17.6259 8.15732 15.3742 8.02731 13H4.06189C4.458 16.1765 6.71639 18.7747 9.71002 19.6674ZM10.0307 13C10.1811 15.4388 10.8778 17.7297 12 19.752C13.1222 17.7297 13.8189 15.4388 13.9693 13H10.0307ZM19.9381 13H15.9727C15.8427 15.3742 15.2526 17.6259 14.29 19.6674C17.2836 18.7747 19.542 16.1765 19.9381 13ZM4.06189 11H8.02731C8.15732 8.62577 8.74743 6.37407 9.71002 4.33256C6.71639 5.22533 4.458 7.8235 4.06189 11ZM10.0307 11H13.9693C13.8189 8.56122 13.1222 6.27025 12 4.24799C10.8778 6.27025 10.1811 8.56122 10.0307 11ZM14.29 4.33256C15.2526 6.37407 15.8427 8.62577 15.9727 11H19.9381C19.542 7.8235 17.2836 5.22533 14.29 4.33256Z" fill="currentColor"/>',hammer:'<path d="M20 2C20.5523 2 21 2.44772 21 3V8C21 8.55228 20.5523 9 20 9H15V22C15 22.5523 14.5523 23 14 23H10C9.44772 23 9 22.5523 9 22V9H3.5C2.94772 9 2.5 8.55228 2.5 8V5.61803C2.5 5.23926 2.714 4.893 3.05279 4.72361L8.5 2H20ZM15 4H8.97214L4.5 6.23607V7H11V21H13V7H15V4ZM19 4H17V7H19V4Z" fill="currentColor"/>',history:'<path d="M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12H4C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C9.25022 4 6.82447 5.38734 5.38451 7.50024L8 7.5V9.5H2V3.5H4L3.99989 5.99918C5.82434 3.57075 8.72873 2 12 2ZM13 7L12.9998 11.585L16.2426 14.8284L14.8284 16.2426L10.9998 12.413L11 7H13Z" fill="currentColor"/>',home:'<path d="M21 20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V9.48907C3 9.18048 3.14247 8.88917 3.38606 8.69972L11.3861 2.47749C11.7472 2.19663 12.2528 2.19663 12.6139 2.47749L20.6139 8.69972C20.8575 8.88917 21 9.18048 21 9.48907V20ZM19 19V9.97815L12 4.53371L5 9.97815V19H19Z" fill="currentColor"/>',hourglass:'<path d="M6 4H4V2H20V4H18V6C18 7.61543 17.1838 8.91468 16.1561 9.97667C15.4532 10.703 14.598 11.372 13.7309 12C14.598 12.628 15.4532 13.297 16.1561 14.0233C17.1838 15.0853 18 16.3846 18 18V20H20V22H4V20H6V18C6 16.3846 6.81616 15.0853 7.8439 14.0233C8.54682 13.297 9.40202 12.628 10.2691 12C9.40202 11.372 8.54682 10.703 7.8439 9.97667C6.81616 8.91468 6 7.61543 6 6V4ZM8 4V6C8 6.88457 8.43384 7.71032 9.2811 8.58583C10.008 9.33699 10.9548 10.0398 12 10.7781C13.0452 10.0398 13.992 9.33699 14.7189 8.58583C15.5662 7.71032 16 6.88457 16 6V4H8ZM12 13.2219C10.9548 13.9602 10.008 14.663 9.2811 15.4142C8.43384 16.2897 8 17.1154 8 18V20H16V18C16 17.1154 15.5662 16.2897 14.7189 15.4142C13.992 14.663 13.0452 13.9602 12 13.2219Z" fill="currentColor"/>',"image-download":'<path d="M21 15V19H24L20 23L16 19H19V15H21ZM21.0078 3C21.5555 3 21.9999 3.44482 22 3.99316V13H20V5H4V18.999L14 9L17 12V14.8291L14 11.8281L6.82715 19H14V21H2.99219C2.44451 21 2.00013 20.5552 2 20.0068V3.99316C2.00013 3.44463 2.45577 3 2.99219 3H21.0078ZM8 7C9.10457 7 10 7.89543 10 9C10 10.1046 9.10457 11 8 11C6.89543 11 6 10.1046 6 9C6 7.89543 6.89543 7 8 7Z" fill="currentColor"/>',"inbox-archive":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM20 9H4V19H20V9ZM13 10V14H16L12 18L8 14H11V10H13ZM18.7639 5H5.23656L4.23744 7H19.7639L18.7639 5Z" fill="currentColor"/>',"inbox-unarchive":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM20 9H4V19H20V9ZM12 10L16 14H13V18H11V14H8L12 10ZM18.764 5H5.236L4.237 7H19.764L18.764 5Z" fill="currentColor"/>',"inbox-unarchive-fill":'<path d="M20 3L22 7V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V7.00353L4 3H20ZM12 10L8 14H11V18H13V14H16L12 10ZM18.764 5H5.236L4.237 7H19.764L18.764 5Z" fill="currentColor"/>',information:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 7H13V9H11V7ZM11 11H13V17H11V11Z" fill="currentColor"/>',"layout-column":'<path d="M11 5H5V19H11V5ZM13 5V19H19V5H13ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3Z" fill="currentColor"/>',"layout-left":'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM7 5H4V19H7V5ZM20 5H9V19H20V5Z" fill="currentColor"/>',"layout-right":'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM15 5H4V19H15V5ZM20 5H17V19H20V5Z" fill="currentColor"/>',"list-check-2":'<path d="M11 4H21V6H11V4ZM11 8H17V10H11V8ZM11 14H21V16H11V14ZM11 18H17V20H11V18ZM3 4H9V10H3V4ZM5 6V8H7V6H5ZM3 14H9V20H3V14ZM5 16V18H7V16H5Z" fill="currentColor"/>',"list-check-3":'<path d="M8.00008 6V9H5.00008V6H8.00008ZM3.00008 4V11H10.0001V4H3.00008ZM13.0001 4H21.0001V6H13.0001V4ZM13.0001 11H21.0001V13H13.0001V11ZM13.0001 18H21.0001V20H13.0001V18ZM10.7072 16.2071L9.29297 14.7929L6.00008 18.0858L4.20718 16.2929L2.79297 17.7071L6.00008 20.9142L10.7072 16.2071Z" fill="currentColor"/>',"list-unordered":'<path d="M8 4H21V6H8V4ZM4.5 6.5C3.67157 6.5 3 5.82843 3 5C3 4.17157 3.67157 3.5 4.5 3.5C5.32843 3.5 6 4.17157 6 5C6 5.82843 5.32843 6.5 4.5 6.5ZM4.5 13.5C3.67157 13.5 3 12.8284 3 12C3 11.1716 3.67157 10.5 4.5 10.5C5.32843 10.5 6 11.1716 6 12C6 12.8284 5.32843 13.5 4.5 13.5ZM4.5 20.4C3.67157 20.4 3 19.7284 3 18.9C3 18.0716 3.67157 17.4 4.5 17.4C5.32843 17.4 6 18.0716 6 18.9C6 19.7284 5.32843 20.4 4.5 20.4ZM8 11H21V13H8V11ZM8 18H21V20H8V18Z" fill="currentColor"/>',loader:'<path d="M11.9995 2C12.5518 2 12.9995 2.44772 12.9995 3V6C12.9995 6.55228 12.5518 7 11.9995 7C11.4472 7 10.9995 6.55228 10.9995 6V3C10.9995 2.44772 11.4472 2 11.9995 2ZM11.9995 17C12.5518 17 12.9995 17.4477 12.9995 18V21C12.9995 21.5523 12.5518 22 11.9995 22C11.4472 22 10.9995 21.5523 10.9995 21V18C10.9995 17.4477 11.4472 17 11.9995 17ZM20.6597 7C20.9359 7.47829 20.772 8.08988 20.2937 8.36602L17.6956 9.86602C17.2173 10.1422 16.6057 9.97829 16.3296 9.5C16.0535 9.02171 16.2173 8.41012 16.6956 8.13398L19.2937 6.63397C19.772 6.35783 20.3836 6.52171 20.6597 7ZM7.66935 14.5C7.94549 14.9783 7.78161 15.5899 7.30332 15.866L4.70525 17.366C4.22695 17.6422 3.61536 17.4783 3.33922 17C3.06308 16.5217 3.22695 15.9101 3.70525 15.634L6.30332 14.134C6.78161 13.8578 7.3932 14.0217 7.66935 14.5ZM20.6597 17C20.3836 17.4783 19.772 17.6422 19.2937 17.366L16.6956 15.866C16.2173 15.5899 16.0535 14.9783 16.3296 14.5C16.6057 14.0217 17.2173 13.8578 17.6956 14.134L20.2937 15.634C20.772 15.9101 20.9359 16.5217 20.6597 17ZM7.66935 9.5C7.3932 9.97829 6.78161 10.1422 6.30332 9.86602L3.70525 8.36602C3.22695 8.08988 3.06308 7.47829 3.33922 7C3.61536 6.52171 4.22695 6.35783 4.70525 6.63397L7.30332 8.13398C7.78161 8.41012 7.94549 9.02171 7.66935 9.5Z" fill="currentColor"/>',"loader-4":'<path d="M18.364 5.63604L16.9497 7.05025C15.683 5.7835 13.933 5 12 5C8.13401 5 5 8.13401 5 12C5 15.866 8.13401 19 12 19C15.866 19 19 15.866 19 12H21C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C14.4853 3 16.7353 4.00736 18.364 5.63604Z" fill="currentColor"/>',lock:'<path d="M19 10H20C20.5523 10 21 10.4477 21 11V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V11C3 10.4477 3.44772 10 4 10H5V9C5 5.13401 8.13401 2 12 2C15.866 2 19 5.13401 19 9V10ZM5 12V20H19V12H5ZM11 14H13V18H11V14ZM17 10V9C17 6.23858 14.7614 4 12 4C9.23858 4 7 6.23858 7 9V10H17Z" fill="currentColor"/>',"lock-unlock":'<path d="M7 10H20C20.5523 10 21 10.4477 21 11V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V11C3 10.4477 3.44772 10 4 10H5V9C5 5.13401 8.13401 2 12 2C14.7405 2 17.1131 3.5748 18.2624 5.86882L16.4731 6.76344C15.6522 5.12486 13.9575 4 12 4C9.23858 4 7 6.23858 7 9V10ZM5 12V20H19V12H5ZM10 15H14V17H10V15Z" fill="currentColor"/>',"menu-2":'<path d="M3 4H21V6H3V4ZM3 11H15V13H3V11ZM3 18H21V20H3V18Z" fill="currentColor"/>',"menu-fold-2":'<path d="M4.40347 3.90332L2.98926 5.31753L6.17124 8.49951L2.98926 11.6815L4.40347 13.0957L8.99967 8.49951L4.40347 3.90332ZM20.9997 19.9995V17.9995H2.99967V19.9995H20.9997ZM20.9997 12.9995V10.9995H11.9997V12.9995H20.9997ZM20.9997 5.99951V3.99951H11.9997V5.99951H20.9997Z" fill="currentColor"/>',"menu-search":'<path d="M15.5 5C13.567 5 12 6.567 12 8.5C12 10.433 13.567 12 15.5 12C17.433 12 19 10.433 19 8.5C19 6.567 17.433 5 15.5 5ZM10 8.5C10 5.46243 12.4624 3 15.5 3C18.5376 3 21 5.46243 21 8.5C21 9.6575 20.6424 10.7315 20.0317 11.6175L22.7071 14.2929L21.2929 15.7071L18.6175 13.0317C17.7315 13.6424 16.6575 14 15.5 14C12.4624 14 10 11.5376 10 8.5ZM3 4H8V6H3V4ZM3 11H8V13H3V11ZM21 18V20H3V18H21Z" fill="currentColor"/>',mic:'<path d="M11.9998 3C10.3429 3 8.99976 4.34315 8.99976 6V10C8.99976 11.6569 10.3429 13 11.9998 13C13.6566 13 14.9998 11.6569 14.9998 10V6C14.9998 4.34315 13.6566 3 11.9998 3ZM11.9998 1C14.7612 1 16.9998 3.23858 16.9998 6V10C16.9998 12.7614 14.7612 15 11.9998 15C9.23833 15 6.99976 12.7614 6.99976 10V6C6.99976 3.23858 9.23833 1 11.9998 1ZM3.05469 11H5.07065C5.55588 14.3923 8.47329 17 11.9998 17C15.5262 17 18.4436 14.3923 18.9289 11H20.9448C20.4837 15.1716 17.1714 18.4839 12.9998 18.9451V23H10.9998V18.9451C6.82814 18.4839 3.51584 15.1716 3.05469 11Z" fill="currentColor"/>',more:'<path d="M4.5 10.5C3.675 10.5 3 11.175 3 12C3 12.825 3.675 13.5 4.5 13.5C5.325 13.5 6 12.825 6 12C6 11.175 5.325 10.5 4.5 10.5ZM19.5 10.5C18.675 10.5 18 11.175 18 12C18 12.825 18.675 13.5 19.5 13.5C20.325 13.5 21 12.825 21 12C21 11.175 20.325 10.5 19.5 10.5ZM12 10.5C11.175 10.5 10.5 11.175 10.5 12C10.5 12.825 11.175 13.5 12 13.5C12.825 13.5 13.5 12.825 13.5 12C13.5 11.175 12.825 10.5 12 10.5Z" fill="currentColor"/>',"more-2":'<path d="M12 3C11.175 3 10.5 3.675 10.5 4.5C10.5 5.325 11.175 6 12 6C12.825 6 13.5 5.325 13.5 4.5C13.5 3.675 12.825 3 12 3ZM12 18C11.175 18 10.5 18.675 10.5 19.5C10.5 20.325 11.175 21 12 21C12.825 21 13.5 20.325 13.5 19.5C13.5 18.675 12.825 18 12 18ZM12 10.5C11.175 10.5 10.5 11.175 10.5 12C10.5 12.825 11.175 13.5 12 13.5C12.825 13.5 13.5 12.825 13.5 12C13.5 11.175 12.825 10.5 12 10.5Z" fill="currentColor"/>',"more-2-fill":'<path d="M12 3C10.9 3 10 3.9 10 5C10 6.1 10.9 7 12 7C13.1 7 14 6.1 14 5C14 3.9 13.1 3 12 3ZM12 17C10.9 17 10 17.9 10 19C10 20.1 10.9 21 12 21C13.1 21 14 20.1 14 19C14 17.9 13.1 17 12 17ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z" fill="currentColor"/>',"more-fill":'<path d="M5 10C3.9 10 3 10.9 3 12C3 13.1 3.9 14 5 14C6.1 14 7 13.1 7 12C7 10.9 6.1 10 5 10ZM19 10C17.9 10 17 10.9 17 12C17 13.1 17.9 14 19 14C20.1 14 21 13.1 21 12C21 10.9 20.1 10 19 10ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z" fill="currentColor"/>',nixos:'<path fill="currentColor" d="m7.1 4.2 2.05 3.55-1.18 2.04L4.75 4.2H7.1Zm4.9-2.1 2.05 3.55h2.36L14.36 2.1H12Zm4.9 2.1-4.73 8.2h2.36l4.73-8.2H16.9Zm2.84 4.9h-4.1l-1.18 2.04h6.46l-1.18-2.04Zm-2.84 10.7-2.05-3.55 1.18-2.04 3.22 5.59H16.9ZM12 21.9l-2.05-3.55H7.59l2.05 3.55H12Zm-4.9-2.1 4.73-8.2H9.47l-4.73 8.2H7.1ZM4.26 14.9h4.1l1.18-2.04H3.08l1.18 2.04Z"/>',"node-tree":'<path d="M10 2C10.5523 2 11 2.44772 11 3V7C11 7.55228 10.5523 8 10 8H8V10H13V9C13 8.44772 13.4477 8 14 8H20C20.5523 8 21 8.44772 21 9V13C21 13.5523 20.5523 14 20 14H14C13.4477 14 13 13.5523 13 13V12H8V18H13V17C13 16.4477 13.4477 16 14 16H20C20.5523 16 21 16.4477 21 17V21C21 21.5523 20.5523 22 20 22H14C13.4477 22 13 21.5523 13 21V20H7C6.44772 20 6 19.5523 6 19V8H4C3.44772 8 3 7.55228 3 7V3C3 2.44772 3.44772 2 4 2H10ZM19 18H15V20H19V18ZM19 10H15V12H19V10ZM9 4H5V6H9V4Z" fill="currentColor"/>',"notification-3":'<path d="M20 17H22V19H2V17H4V10C4 5.58172 7.58172 2 12 2C16.4183 2 20 5.58172 20 10V17ZM18 17V10C18 6.68629 15.3137 4 12 4C8.68629 4 6 6.68629 6 10V17H18ZM9 21H15V23H9V21Z" fill="currentColor"/>',palette:'<path d="M12 2C17.5222 2 22 5.97778 22 10.8889C22 13.9556 19.5111 16.4444 16.4444 16.4444H14.4778C13.5556 16.4444 12.8111 17.1889 12.8111 18.1111C12.8111 18.5333 12.9778 18.9222 13.2333 19.2111C13.5 19.5111 13.6667 19.9 13.6667 20.3333C13.6667 21.2556 12.9 22 12 22C6.47778 22 2 17.5222 2 12C2 6.47778 6.47778 2 12 2ZM10.8111 18.1111C10.8111 16.0843 12.451 14.4444 14.4778 14.4444H16.4444C18.4065 14.4444 20 12.851 20 10.8889C20 7.1392 16.4677 4 12 4C7.58235 4 4 7.58235 4 12C4 16.19 7.2226 19.6285 11.324 19.9718C10.9948 19.4168 10.8111 18.7761 10.8111 18.1111ZM7.5 12C6.67157 12 6 11.3284 6 10.5C6 9.67157 6.67157 9 7.5 9C8.32843 9 9 9.67157 9 10.5C9 11.3284 8.32843 12 7.5 12ZM16.5 12C15.6716 12 15 11.3284 15 10.5C15 9.67157 15.6716 9 16.5 9C17.3284 9 18 9.67157 18 10.5C18 11.3284 17.3284 12 16.5 12ZM12 9C11.1716 9 10.5 8.32843 10.5 7.5C10.5 6.67157 11.1716 6 12 6C12.8284 6 13.5 6.67157 13.5 7.5C13.5 8.32843 12.8284 9 12 9Z" fill="currentColor"/>',pencil:'<path d="M15.7279 9.57627L14.3137 8.16206L5 17.4758V18.89H6.41421L15.7279 9.57627ZM17.1421 8.16206L18.5563 6.74785L17.1421 5.33363L15.7279 6.74785L17.1421 8.16206ZM7.24264 20.89H3V16.6473L16.435 3.21231C16.8256 2.82179 17.4587 2.82179 17.8492 3.21231L20.6777 6.04074C21.0682 6.43126 21.0682 7.06443 20.6777 7.45495L7.24264 20.89Z" fill="currentColor"/>',"pencil-ai":'<path d="M16.4356 3.21188C16.8261 2.82185 17.4592 2.82157 17.8496 3.21188L20.6777 6.04099C21.0681 6.43152 21.0682 7.06457 20.6777 7.45505L7.2422 20.8896H3.00001V16.6475L16.4356 3.21188ZM5.00001 17.4756V18.8896H6.41407L15.7276 9.57615L14.3135 8.16208L5.00001 17.4756ZM4.5293 1.3193C4.70583 0.893505 5.29418 0.893508 5.47071 1.3193L5.72364 1.93063C6.15555 2.97342 6.96155 3.80613 7.97462 4.2568L8.69239 4.57614C9.10267 4.75896 9.10262 5.35616 8.69239 5.53903L7.93263 5.87692C6.94497 6.3162 6.15339 7.11943 5.71387 8.1279L5.4668 8.69334C5.28636 9.10747 4.71366 9.10747 4.53321 8.69334L4.28614 8.1279C3.84661 7.11943 3.05506 6.3162 2.06739 5.87692L1.30762 5.53903C0.897483 5.35617 0.897435 4.75896 1.30762 4.57614L2.0254 4.2568C3.03845 3.80614 3.84446 2.97344 4.27637 1.93063L4.5293 1.3193ZM15.7276 6.74802L17.1426 8.16208L18.5567 6.74802L17.1426 5.33395L15.7276 6.74802Z" fill="currentColor"/>',pichamber:'<g transform="translate(12 12) scale(0.22) translate(-50 -50)"><path d="M50 3 91 27 50 51 9 27Z" fill="currentColor" fill-opacity="0.08"/><path d="M9 27 50 51V97L9 73Z" fill="currentColor" fill-opacity="0.15"/><path d="M50 51 91 27V73L50 97Z" fill="currentColor" fill-opacity="0.24"/><path d="M50 3 91 27V73L50 97 9 73V27Z" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/></g>',"picture-in-picture-2":'<path d="M21 3C21.5523 3 22 3.44772 22 4V11H20V5H4V19H10V21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM21 13C21.5523 13 22 13.4477 22 14V20C22 20.5523 21.5523 21 21 21H13C12.4477 21 12 20.5523 12 20V14C12 13.4477 12.4477 13 13 13H21ZM20 15H14V19H20V15ZM6.70711 6.29289L8.95689 8.54289L11 6.5V12H5.5L7.54289 9.95689L5.29289 7.70711L6.70711 6.29289Z" fill="currentColor"/>',"pie-chart":'<path d="M9 2.4578V4.58152C6.06817 5.76829 4 8.64262 4 12C4 16.4183 7.58172 20 12 20C15.3574 20 18.2317 17.9318 19.4185 15H21.5422C20.2679 19.0571 16.4776 22 12 22C6.47715 22 2 17.5228 2 12C2 7.52236 4.94289 3.73207 9 2.4578ZM12 2C17.5228 2 22 6.47715 22 12C22 12.3375 21.9833 12.6711 21.9506 13H11V2.04938C11.3289 2.01672 11.6625 2 12 2ZM13 4.06189V11H19.9381C19.4869 7.38128 16.6187 4.51314 13 4.06189Z" fill="currentColor"/>',play:'<path d="M16.3944 12.0001L10 7.7371V16.263L16.3944 12.0001ZM19.376 12.4161L8.77735 19.4818C8.54759 19.635 8.23715 19.5729 8.08397 19.3432C8.02922 19.261 8 19.1645 8 19.0658V4.93433C8 4.65818 8.22386 4.43433 8.5 4.43433C8.59871 4.43433 8.69522 4.46355 8.77735 4.5183L19.376 11.584C19.6057 11.7372 19.6678 12.0477 19.5146 12.2774C19.478 12.3323 19.4309 12.3795 19.376 12.4161Z" fill="currentColor"/>',"play-list-add":'<path d="M2 18H12V20H2V18ZM2 11H22V13H2V11ZM2 4H22V6H2V4ZM18 18V15H20V18H23V20H20V23H18V20H15V18H18Z" fill="currentColor"/>',"plug-2":'<path d="M13 18V20H19V22H13C11.8954 22 11 21.1046 11 20V18H8C5.79086 18 4 16.2091 4 14V7C4 6.44772 4.44772 6 5 6H7V2H9V6H15V2H17V6H19C19.5523 6 20 6.44772 20 7V14C20 16.2091 18.2091 18 16 18H13ZM8 16H16C17.1046 16 18 15.1046 18 14V11H6V14C6 15.1046 6.89543 16 8 16ZM18 8H6V9H18V8ZM12 14.5C11.4477 14.5 11 14.0523 11 13.5C11 12.9477 11.4477 12.5 12 12.5C12.5523 12.5 13 12.9477 13 13.5C13 14.0523 12.5523 14.5 12 14.5ZM11 2H13V5H11V2Z" fill="currentColor"/>',pushpin:'<path d="M13.8273 1.69L22.3126 10.1753L20.8984 11.5895L20.1913 10.8824L15.9486 15.125L15.2415 18.6606L13.8273 20.0748L9.58466 15.8321L4.63492 20.7819L3.2207 19.3677L8.17045 14.4179L3.92781 10.1753L5.34202 8.76107L8.87756 8.05396L13.1202 3.81132L12.4131 3.10422L13.8273 1.69ZM14.5344 5.22554L9.86358 9.89637L7.0417 10.4607L13.5418 16.9609L14.1062 14.139L18.7771 9.46818L14.5344 5.22554Z" fill="currentColor"/>',"pushpin-2":'<path d="M18 3V5H17V11L19 14V16H13V23H11V16H5V14L7 11V5H6V3H18ZM9 5V11.6056L7.4037 14H16.5963L15 11.6056V5H9Z" fill="currentColor"/>',"pushpin-2-fill":'<path d="M18 3V5H17V11L19 14V16H13V23H11V16H5V14L7 11V5H6V3H18Z" fill="currentColor"/>',puzzle:'<path d="M7 5C7 2.79086 8.79086 1 11 1C13.2091 1 15 2.79086 15 5H18C18.5523 5 19 5.44772 19 6V9C21.2091 9 23 10.7909 23 13C23 15.2091 21.2091 17 19 17V20C19 20.5523 18.5523 21 18 21H4C3.44772 21 3 20.5523 3 20V6C3 5.44772 3.44772 5 4 5H7ZM11 3C9.89543 3 9 3.89543 9 5C9 5.23554 9.0403 5.45952 9.11355 5.66675C9.22172 5.97282 9.17461 6.31235 8.98718 6.57739C8.79974 6.84243 8.49532 7 8.17071 7H5V19H17V15.8293C17 15.5047 17.1576 15.2003 17.4226 15.0128C17.6877 14.8254 18.0272 14.7783 18.3332 14.8865C18.5405 14.9597 18.7645 15 19 15C20.1046 15 21 14.1046 21 13C21 11.8954 20.1046 11 19 11C18.7645 11 18.5405 11.0403 18.3332 11.1135C18.0272 11.2217 17.6877 11.1746 17.4226 10.9872C17.1576 10.7997 17 10.4953 17 10.1707V7H13.8293C13.5047 7 13.2003 6.84243 13.0128 6.57739C12.8254 6.31235 12.7783 5.97282 12.8865 5.66675C12.9597 5.45952 13 5.23555 13 5C13 3.89543 12.1046 3 11 3Z" fill="currentColor"/>',question:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM11 15H13V17H11V15ZM13 13.3551V14H11V12.5C11 11.9477 11.4477 11.5 12 11.5C12.8284 11.5 13.5 10.8284 13.5 10C13.5 9.17157 12.8284 8.5 12 8.5C11.2723 8.5 10.6656 9.01823 10.5288 9.70577L8.56731 9.31346C8.88637 7.70919 10.302 6.5 12 6.5C13.933 6.5 15.5 8.067 15.5 10C15.5 11.5855 14.4457 12.9248 13 13.3551Z" fill="currentColor"/>',"record-circle":'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12C15 13.6569 13.6569 15 12 15Z" fill="currentColor"/>',refresh:'<path d="M5.46257 4.43262C7.21556 2.91688 9.5007 2 12 2C17.5228 2 22 6.47715 22 12C22 14.1361 21.3302 16.1158 20.1892 17.7406L17 12H20C20 7.58172 16.4183 4 12 4C9.84982 4 7.89777 4.84827 6.46023 6.22842L5.46257 4.43262ZM18.5374 19.5674C16.7844 21.0831 14.4993 22 12 22C6.47715 22 2 17.5228 2 12C2 9.86386 2.66979 7.88416 3.8108 6.25944L7 12H4C4 16.4183 7.58172 20 12 20C14.1502 20 16.1022 19.1517 17.5398 17.7716L18.5374 19.5674Z" fill="currentColor"/>',restart:'<path d="M18.5374 19.5674C16.7844 21.0831 14.4993 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 14.1361 21.3302 16.1158 20.1892 17.7406L17 12H20C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20C14.1502 20 16.1022 19.1517 17.5398 17.7716L18.5374 19.5674Z" fill="currentColor"/>',"robot-2":'<path d="M13.5 2C13.5 2.44425 13.3069 2.84339 13 3.11805V5H18C19.6569 5 21 6.34315 21 8V18C21 19.6569 19.6569 21 18 21H6C4.34315 21 3 19.6569 3 18V8C3 6.34315 4.34315 5 6 5H11V3.11805C10.6931 2.84339 10.5 2.44425 10.5 2C10.5 1.17157 11.1716 0.5 12 0.5C12.8284 0.5 13.5 1.17157 13.5 2ZM6 7C5.44772 7 5 7.44772 5 8V18C5 18.5523 5.44772 19 6 19H18C18.5523 19 19 18.5523 19 18V8C19 7.44772 18.5523 7 18 7H13H11H6ZM2 10H0V16H2V10ZM22 10H24V16H22V10ZM9 14.5C9.82843 14.5 10.5 13.8284 10.5 13C10.5 12.1716 9.82843 11.5 9 11.5C8.17157 11.5 7.5 12.1716 7.5 13C7.5 13.8284 8.17157 14.5 9 14.5ZM15 14.5C15.8284 14.5 16.5 13.8284 16.5 13C16.5 12.1716 15.8284 11.5 15 11.5C14.1716 11.5 13.5 12.1716 13.5 13C13.5 13.8284 14.1716 14.5 15 14.5Z" fill="currentColor"/>',rocket:'<path d="M4.99958 12.9999C4.99958 7.91198 7.90222 3.5636 11.9996 1.81799C16.0969 3.5636 18.9996 7.91198 18.9996 12.9999C18.9996 13.8229 18.9236 14.6264 18.779 15.4027L20.7194 17.2353C20.8845 17.3913 20.9238 17.6389 20.815 17.8383L18.3196 22.4133C18.1873 22.6557 17.8836 22.7451 17.6412 22.6128C17.5993 22.59 17.5608 22.5612 17.5271 22.5274L15.2925 20.2928C15.1049 20.1053 14.8506 19.9999 14.5854 19.9999H9.41379C9.14857 19.9999 8.89422 20.1053 8.70668 20.2928L6.47209 22.5274C6.27683 22.7227 5.96025 22.7227 5.76498 22.5274C5.73122 22.4937 5.70246 22.4552 5.67959 22.4133L3.18412 17.8383C3.07537 17.6389 3.11464 17.3913 3.27975 17.2353L5.22014 15.4027C5.07551 14.6264 4.99958 13.8229 4.99958 12.9999ZM6.47542 19.6957L7.29247 18.8786C7.85508 18.316 8.61814 17.9999 9.41379 17.9999H14.5854C15.381 17.9999 16.1441 18.316 16.7067 18.8786L17.5237 19.6957L18.5056 17.8955L17.4058 16.8568C16.9117 16.3901 16.6884 15.7045 16.8128 15.0364C16.9366 14.3722 16.9996 13.6911 16.9996 12.9999C16.9996 9.13037 15.0045 5.69965 11.9996 4.04033C8.99462 5.69965 6.99958 9.13037 6.99958 12.9999C6.99958 13.6911 7.06255 14.3722 7.18631 15.0364C7.31078 15.7045 7.08746 16.3901 6.59338 16.8568L5.49353 17.8955L6.47542 19.6957ZM11.9996 12.9999C10.895 12.9999 9.99958 12.1045 9.99958 10.9999C9.99958 9.89537 10.895 8.99994 11.9996 8.99994C13.1041 8.99994 13.9996 9.89537 13.9996 10.9999C13.9996 12.1045 13.1041 12.9999 11.9996 12.9999Z" fill="currentColor"/>',"save-3":'<path d="M18 19H19V6.82843L17.1716 5H16V9H7V5H5V19H6V12H18V19ZM4 3H18L20.7071 5.70711C20.8946 5.89464 21 6.149 21 6.41421V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM8 14V19H16V14H8Z" fill="currentColor"/>',"scan-2":'<path d="M5.67127 4.25705L13.4142 12L12 13.4142L8.55382 9.96803C8.20193 10.5635 8 11.2582 8 12C8 14.2091 9.79086 16 12 16C14.2091 16 16 14.2091 16 12C16 9.87494 14.3429 8.13693 12.2503 8.00771L10.4459 6.20323C10.9416 6.07067 11.4625 6 12 6C15.3137 6 18 8.68629 18 12C18 15.3137 15.3137 18 12 18C8.68629 18 6 15.3137 6 12C6 10.7042 6.41079 9.50428 7.10925 8.52347L5.68014 7.09436C4.62708 8.44904 4 10.1513 4 12C4 16.4183 7.58172 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C10.8915 4 9.83557 4.22547 8.8757 4.63306L7.37443 3.13179C8.75768 2.40883 10.3311 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 8.87842 3.43029 6.09091 5.67127 4.25705Z" fill="currentColor"/>',search:'<path d="M18.031 16.6168L22.3137 20.8995L20.8995 22.3137L16.6168 18.031C15.0769 19.263 13.124 20 11 20C6.032 20 2 15.968 2 11C2 6.032 6.032 2 11 2C15.968 2 20 6.032 20 11C20 13.124 19.263 15.0769 18.031 16.6168ZM16.0247 15.8748C17.2475 14.6146 18 12.8956 18 11C18 7.1325 14.8675 4 11 4C7.1325 4 4 7.1325 4 11C4 14.8675 7.1325 18 11 18C12.8956 18 14.6146 17.2475 15.8748 16.0247L16.0247 15.8748Z" fill="currentColor"/>',"send-plane":'<path d="M21.7267 2.95694L16.2734 22.0432C16.1225 22.5716 15.7979 22.5956 15.5563 22.1126L11 13L1.9229 9.36919C1.41322 9.16532 1.41953 8.86022 1.95695 8.68108L21.0432 2.31901C21.5716 2.14285 21.8747 2.43866 21.7267 2.95694ZM19.0353 5.09647L6.81221 9.17085L12.4488 11.4255L15.4895 17.5068L19.0353 5.09647Z" fill="currentColor"/>',"send-plane-2":'<path d="M3.5 1.34558C3.58425 1.34558 3.66714 1.36687 3.74096 1.40747L22.2034 11.5618C22.4454 11.6949 22.5337 11.9989 22.4006 12.2409C22.3549 12.324 22.2865 12.3924 22.2034 12.4381L3.74096 22.5924C3.499 22.7255 3.19497 22.6372 3.06189 22.3953C3.02129 22.3214 3 22.2386 3 22.1543V1.84558C3 1.56944 3.22386 1.34558 3.5 1.34558ZM5 4.38249V10.9999H10V12.9999H5V19.6174L18.8499 11.9999L5 4.38249Z" fill="currentColor"/>',server:'<path d="M5 11H19V5H5V11ZM21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20C20.5523 3 21 3.44772 21 4ZM19 13H5V19H19V13ZM7 15H10V17H7V15ZM7 7H10V9H7V7Z" fill="currentColor"/>',"settings-3":'<path d="M3.33946 17.0002C2.90721 16.2515 2.58277 15.4702 2.36133 14.6741C3.3338 14.1779 3.99972 13.1668 3.99972 12.0002C3.99972 10.8345 3.3348 9.824 2.36353 9.32741C2.81025 7.71651 3.65857 6.21627 4.86474 4.99001C5.7807 5.58416 6.98935 5.65534 7.99972 5.072C9.01009 4.48866 9.55277 3.40635 9.4962 2.31604C11.1613 1.8846 12.8847 1.90004 14.5031 2.31862C14.4475 3.40806 14.9901 4.48912 15.9997 5.072C17.0101 5.65532 18.2187 5.58416 19.1346 4.99007C19.7133 5.57986 20.2277 6.25151 20.66 7.00021C21.0922 7.7489 21.4167 8.53025 21.6381 9.32628C20.6656 9.82247 19.9997 10.8336 19.9997 12.0002C19.9997 13.166 20.6646 14.1764 21.6359 14.673C21.1892 16.2839 20.3409 17.7841 19.1347 19.0104C18.2187 18.4163 17.0101 18.3451 15.9997 18.9284C14.9893 19.5117 14.4467 20.5941 14.5032 21.6844C12.8382 22.1158 11.1148 22.1004 9.49633 21.6818C9.55191 20.5923 9.00929 19.5113 7.99972 18.9284C6.98938 18.3451 5.78079 18.4162 4.86484 19.0103C4.28617 18.4205 3.77172 17.7489 3.33946 17.0002ZM8.99972 17.1964C10.0911 17.8265 10.8749 18.8227 11.2503 19.9659C11.7486 20.0133 12.2502 20.014 12.7486 19.9675C13.1238 18.8237 13.9078 17.8268 14.9997 17.1964C16.0916 16.5659 17.347 16.3855 18.5252 16.6324C18.8146 16.224 19.0648 15.7892 19.2729 15.334C18.4706 14.4373 17.9997 13.2604 17.9997 12.0002C17.9997 10.74 18.4706 9.5632 19.2729 8.6665C19.1688 8.4405 19.0538 8.21822 18.9279 8.00021C18.802 7.78219 18.667 7.57148 18.5233 7.36842C17.3457 7.61476 16.0911 7.43414 14.9997 6.80405C13.9083 6.17395 13.1246 5.17768 12.7491 4.03455C12.2509 3.98714 11.7492 3.98646 11.2509 4.03292C10.8756 5.17671 10.0916 6.17364 8.99972 6.80405C7.9078 7.43447 6.65245 7.61494 5.47428 7.36803C5.18485 7.77641 4.93463 8.21117 4.72656 8.66637C5.52881 9.56311 5.99972 10.74 5.99972 12.0002C5.99972 13.2604 5.52883 14.4372 4.72656 15.3339C4.83067 15.5599 4.94564 15.7822 5.07152 16.0002C5.19739 16.2182 5.3324 16.4289 5.47612 16.632C6.65377 16.3857 7.90838 16.5663 8.99972 17.1964ZM11.9997 15.0002C10.3429 15.0002 8.99972 13.6571 8.99972 12.0002C8.99972 10.3434 10.3429 9.00021 11.9997 9.00021C13.6566 9.00021 14.9997 10.3434 14.9997 12.0002C14.9997 13.6571 13.6566 15.0002 11.9997 15.0002ZM11.9997 13.0002C12.552 13.0002 12.9997 12.5525 12.9997 12.0002C12.9997 11.4479 12.552 11.0002 11.9997 11.0002C11.4474 11.0002 10.9997 11.4479 10.9997 12.0002C10.9997 12.5525 11.4474 13.0002 11.9997 13.0002Z" fill="currentColor"/>',"shield-keyhole":'<path d="M12 1L20.2169 2.82598C20.6745 2.92766 21 3.33347 21 3.80217V13.7889C21 15.795 19.9974 17.6684 18.3282 18.7812L12 23L5.6718 18.7812C4.00261 17.6684 3 15.795 3 13.7889V3.80217C3 3.33347 3.32553 2.92766 3.78307 2.82598L12 1ZM12 3.04879L5 4.60434V13.7889C5 15.1263 5.6684 16.3752 6.7812 17.1171L12 20.5963L17.2188 17.1171C18.3316 16.3752 19 15.1263 19 13.7889V4.60434L12 3.04879ZM12 7C13.1046 7 14 7.89543 14 9C14 9.73984 13.5983 10.3858 13.0011 10.7318L13 15H11L10.9999 10.7324C10.4022 10.3866 10 9.74025 10 9C10 7.89543 10.8954 7 12 7Z" fill="currentColor"/>',"split-cells-horizontal":'<path d="M20 3C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20ZM11 5H5V19H11V15H13V19H19V5H13V9H11V5ZM15 9L18 12L15 15V13H9V15L6 12L9 9V11H15V9Z" fill="currentColor"/>',stack:'<path d="M20.0833 15.1999L21.2854 15.9212C21.5221 16.0633 21.5989 16.3704 21.4569 16.6072C21.4146 16.6776 21.3557 16.7365 21.2854 16.7787L12.5144 22.0412C12.1977 22.2313 11.8021 22.2313 11.4854 22.0412L2.71451 16.7787C2.47772 16.6366 2.40093 16.3295 2.54301 16.0927C2.58523 16.0223 2.64413 15.9634 2.71451 15.9212L3.9166 15.1999L11.9999 20.0499L20.0833 15.1999ZM20.0833 10.4999L21.2854 11.2212C21.5221 11.3633 21.5989 11.6704 21.4569 11.9072C21.4146 11.9776 21.3557 12.0365 21.2854 12.0787L11.9999 17.6499L2.71451 12.0787C2.47772 11.9366 2.40093 11.6295 2.54301 11.3927C2.58523 11.3223 2.64413 11.2634 2.71451 11.2212L3.9166 10.4999L11.9999 15.3499L20.0833 10.4999ZM12.5144 1.30864L21.2854 6.5712C21.5221 6.71327 21.5989 7.0204 21.4569 7.25719C21.4146 7.32757 21.3557 7.38647 21.2854 7.42869L11.9999 12.9999L2.71451 7.42869C2.47772 7.28662 2.40093 6.97949 2.54301 6.7427C2.58523 6.67232 2.64413 6.61343 2.71451 6.5712L11.4854 1.30864C11.8021 1.11864 12.1977 1.11864 12.5144 1.30864ZM11.9999 3.33233L5.88723 6.99995L11.9999 10.6676L18.1126 6.99995L11.9999 3.33233Z" fill="currentColor"/>',star:'<path d="M12.0006 18.26L4.94715 22.2082L6.52248 14.2799L0.587891 8.7918L8.61493 7.84006L12.0006 0.5L15.3862 7.84006L23.4132 8.7918L17.4787 14.2799L19.054 22.2082L12.0006 18.26ZM12.0006 15.968L16.2473 18.3451L15.2988 13.5717L18.8719 10.2674L14.039 9.69434L12.0006 5.27502L9.96214 9.69434L5.12921 10.2674L8.70231 13.5717L7.75383 18.3451L12.0006 15.968Z" fill="currentColor"/>',"star-fill":'<path d="M12.0006 18.26L4.94715 22.2082L6.52248 14.2799L0.587891 8.7918L8.61493 7.84006L12.0006 0.5L15.3862 7.84006L23.4132 8.7918L17.4787 14.2799L19.054 22.2082L12.0006 18.26Z" fill="currentColor"/>',"sticky-note":'<path d="M21 15L15 20.996L4.00221 21C3.4487 21 3 20.5551 3 20.0066V3.9934C3 3.44476 3.44495 3 3.9934 3H20.0066C20.5552 3 21 3.45576 21 4.00247V15ZM19 5H5V19H13V14C13 13.4872 13.386 13.0645 13.8834 13.0067L14 13L19 12.999V5ZM18.171 14.999L15 15V18.169L18.171 14.999Z" fill="currentColor"/>',stop:'<path d="M7 7V17H17V7H7ZM6 5H18C18.5523 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5Z" fill="currentColor"/>',subtract:'<path d="M5 11V13H19V11H5Z" fill="currentColor"/>',survey:'<path d="M17 2V4H20.0066C20.5552 4 21 4.44495 21 4.9934V21.0066C21 21.5552 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5551 3 21.0066V4.9934C3 4.44476 3.44495 4 3.9934 4H7V2H17ZM7 6H5V20H19V6H17V8H7V6ZM9 16V18H7V16H9ZM9 13V15H7V13H9ZM9 10V12H7V10H9ZM15 4H9V6H15V4Z" fill="currentColor"/>',task:'<path d="M19 4H5V20H19V4ZM3 2.9918C3 2.44405 3.44749 2 3.9985 2H19.9997C20.5519 2 20.9996 2.44772 20.9997 3L21 20.9925C21 21.5489 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5447 3 21.0082V2.9918ZM11.2929 13.1213L15.5355 8.87868L16.9497 10.2929L11.2929 15.9497L7.40381 12.0607L8.81802 10.6464L11.2929 13.1213Z" fill="currentColor"/>',terminal:'<path d="M10.9999 12L3.92886 19.0711L2.51465 17.6569L8.1715 12L2.51465 6.34317L3.92886 4.92896L10.9999 12ZM10.9999 19H20.9999V21H10.9999V19Z" fill="currentColor"/>',"terminal-box":'<path d="M3 3H21C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3ZM4 5V19H20V5H4ZM12 15H18V17H12V15ZM8.66685 12L5.83842 9.17157L7.25264 7.75736L11.4953 12L7.25264 16.2426L5.83842 14.8284L8.66685 12Z" fill="currentColor"/>',text:'<path d="M13 6V21H11V6H5V4H19V6H13Z" fill="currentColor"/>',"text-wrap":'<path d="M15 18H16.5C17.8807 18 19 16.8807 19 15.5C19 14.1193 17.8807 13 16.5 13H3V11H16.5C18.9853 11 21 13.0147 21 15.5C21 17.9853 18.9853 20 16.5 20H15V22L11 19L15 16V18ZM3 4H21V6H3V4ZM9 18V20H3V18H9Z" fill="currentColor"/>',time:'<path d="M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM13 12H17V14H11V7H13V12Z" fill="currentColor"/>',tools:'<path d="M5.32943 3.27158C6.56252 2.8332 7.9923 3.10749 8.97927 4.09446C10.1002 5.21537 10.3019 6.90741 9.5843 8.23385L20.293 18.9437L18.8788 20.3579L8.16982 9.64875C6.84325 10.3669 5.15069 10.1654 4.02952 9.04421C3.04227 8.05696 2.7681 6.62665 3.20701 5.39332L5.44373 7.63C6.02952 8.21578 6.97927 8.21578 7.56505 7.63C8.15084 7.04421 8.15084 6.09446 7.56505 5.50868L5.32943 3.27158ZM15.6968 5.15512L18.8788 3.38736L20.293 4.80157L18.5252 7.98355L16.7574 8.3371L14.6361 10.4584L13.2219 9.04421L15.3432 6.92289L15.6968 5.15512ZM8.97927 13.2868L10.3935 14.7011L5.09018 20.0044C4.69966 20.3949 4.06649 20.3949 3.67597 20.0044C3.31334 19.6417 3.28744 19.0699 3.59826 18.6774L3.67597 18.5902L8.97927 13.2868Z" fill="currentColor"/>',"ubuntu-fill":'<path d="M22.001 12C22.001 17.5224 17.524 22 12.001 22C6.47798 22 2.00098 17.5224 2.00098 12C2.00098 6.4771 6.47833 2 12.001 2C17.524 2 22.001 6.4771 22.001 12ZM5.20128 10.6642C4.46363 10.6642 3.86613 11.2623 3.86613 12C3.86613 12.7372 4.46363 13.3349 5.20128 13.3349C5.93848 13.3349 6.53628 12.7372 6.53628 12C6.53628 11.2622 5.93848 10.6642 5.20128 10.6642ZM14.7337 16.7325C14.0954 17.1015 13.8763 17.9175 14.2454 18.5558C14.6137 19.1942 15.4296 19.4137 16.0682 19.0448C16.7067 18.6759 16.9257 17.8595 16.5571 17.2208C16.1884 16.5832 15.3721 16.3644 14.7337 16.7325V16.7325ZM8.10133 12C8.10133 10.6808 8.75663 9.5152 9.75958 8.80915L8.78348 7.174C7.61518 7.955 6.74598 9.1485 6.38498 10.545C6.80648 10.8895 7.07613 11.4131 7.07613 12C7.07613 12.586 6.80643 13.1097 6.38493 13.4543C6.74583 14.8516 7.61503 16.0448 8.78343 16.826L9.75953 15.1903C8.75653 14.4848 8.10128 13.32 8.10128 12L8.10133 12ZM12.001 8.09975C14.0385 8.09975 15.7098 9.66175 15.8853 11.654L17.788 11.6261C17.6942 10.1551 17.0518 8.83495 16.0645 7.86435C15.5568 8.05565 14.9705 8.02685 14.4637 7.7342C13.9559 7.4412 13.6376 6.9472 13.5506 6.4104C13.0571 6.27455 12.538 6.2005 12.001 6.2005C11.0782 6.2005 10.2053 6.41685 9.43058 6.80035L10.3582 8.46275C10.8577 8.23045 11.4141 8.09975 12.001 8.09975ZM12.001 15.8995C11.4141 15.8995 10.8576 15.7691 10.3585 15.537L9.43063 17.1991C10.2055 17.5831 11.0782 17.8004 12.001 17.8004C12.538 17.8004 13.0575 17.7255 13.5506 17.5888C13.6376 17.0526 13.9561 16.5586 14.4638 16.2652C14.971 15.9726 15.5569 15.9435 16.0646 16.1349C17.0519 15.1642 17.6942 13.8441 17.7881 12.3732L15.8846 12.3456C15.7099 14.338 14.0386 15.8996 12.0011 15.8996L12.001 15.8995ZM14.7334 7.26675C15.372 7.6349 16.1883 7.4169 16.5566 6.77845C16.9257 6.1396 16.7071 5.32395 16.0683 4.95505C15.4296 4.58605 14.6138 4.8048 14.2447 5.44345C13.8763 6.08195 14.0954 6.89795 14.7334 7.2667V7.26675Z" fill="currentColor"/>',unpin:'<path d="M20.9701 17.1716 19.5559 18.5858 16.0214 15.0513 15.9476 15.1251 15.2405 18.6606 13.8263 20.0748 9.58369 15.8322 4.63394 20.7819 3.21973 19.3677 8.16947 14.418 3.92683 10.1753 5.34105 8.7611 8.87658 8.05399 8.95029 7.98028 5.41373 4.44371 6.82794 3.0295 20.9701 17.1716ZM10.3645 9.39449 9.86261 9.8964 7.04072 10.4608 13.5409 16.9609 14.1052 14.139 14.6071 13.6371 10.3645 9.39449ZM18.7761 9.46821 17.4356 10.8087 18.8498 12.2229 20.1903 10.8824 20.8974 11.5895 22.3116 10.1753 13.8263 1.69003 12.4121 3.10425 13.1192 3.81135 11.7787 5.15185 13.1929 6.56607 14.5334 5.22557 18.7761 9.46821Z" fill="currentColor"/>',user:'<path d="M4 22C4 17.5817 7.58172 14 12 14C16.4183 14 20 17.5817 20 22H18C18 18.6863 15.3137 16 12 16C8.68629 16 6 18.6863 6 22H4ZM12 13C8.685 13 6 10.315 6 7C6 3.685 8.685 1 12 1C15.315 1 18 3.685 18 7C18 10.315 15.315 13 12 13ZM12 11C14.21 11 16 9.21 16 7C16 4.79 14.21 3 12 3C9.79 3 8 4.79 8 7C8 9.21 9.79 11 12 11Z" fill="currentColor"/>',voiceprint:'<path d="M5 7H7V17H5V7ZM1 10H3V14H1V10ZM9 2H11V20H9V2ZM13 4H15V22H13V4ZM17 7H19V17H17V7ZM21 10H23V14H21V10Z" fill="currentColor"/>',window:'<path d="M21 3C21.5523 3 22 3.44772 22 4V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V4C2 3.44772 2.44772 3 3 3H21ZM20 11H4V19H20V11ZM20 5H4V9H20V5ZM11 6V8H9V6H11ZM7 6V8H5V6H7Z" fill="currentColor"/>',windows:'<path d="M21.001 2.5V21.5L3.00098 19.5V4.5L21.001 2.5ZM19.001 12.999L12.001 13V18.487L19.001 19.2655V12.999ZM5.00098 17.7099L10.001 18.265V13L5.00098 12.999V17.7099ZM19.001 10.999V4.73453L12.001 5.512V11L19.001 10.999ZM10.001 5.734L5.00098 6.29009V10.999L10.001 11V5.734Z" fill="currentColor"/>'},d2="pichamber-icon-sprite";let wf=!1;function Uj(){if(wf||typeof document>"u")return;const e=document.body;if(!e)return;if(document.getElementById(d2)){wf=!0;return}const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.id=d2,n.setAttribute("aria-hidden","true"),n.style.display="none",n.innerHTML=Object.entries(xw).map(([r,s])=>`<symbol id="oc-${r}" viewBox="0 0 24 24">${s}</symbol>`).join(""),e.insertBefore(n,e.firstChild),wf=!0}const $=p.memo(({name:e,className:t,...n})=>(typeof document<"u"&&Uj(),c.jsx("svg",{className:R("remixicon",t),viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",...n,children:c.jsx("use",{href:`#oc-${e}`})})));$.displayName="Icon";let Oc=0;function qj(e,t){return e&&H.isValidElement(t)?{render:t}:{children:t}}function ru({...e}){return c.jsx(nC,{...e})}function Wj({asChild:e,children:t,...n}){const r=qj(e,t);return c.jsx(lC,{"data-slot":"dialog-trigger",...n,...r})}function Kj({...e}){return c.jsx(aC,{...e})}const bw=H.forwardRef(({className:e,...t},n)=>(H.useEffect(()=>(Oc+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Oc=Math.max(0,Oc-1),Oc===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),c.jsx(cC,{ref:n,"data-slot":"dialog-overlay",className:R("oc-glass-backdrop fixed inset-0 z-50 bg-black/25 dark:bg-black/40","transition-opacity duration-150 ease-out","data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",e),...t})));bw.displayName="DialogOverlay";function su({className:e,children:t,showCloseButton:n=!0,...r}){return c.jsxs(Kj,{children:[c.jsx(bw,{className:"rounded-none"}),c.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center pointer-events-none p-4",children:c.jsxs(rC,{"data-slot":"dialog-content","data-state-slot":"dialog",className:R("relative pointer-events-auto bg-background text-foreground flex flex-col w-full max-w-lg max-h-full gap-4 rounded-xl border p-6 shadow-none overflow-y-auto pwa-dialog-content origin-center","transition-all duration-150 ease-out","data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]","data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]","data-[nested-dialog-open]:brightness-[0.55] dark:data-[nested-dialog-open]:brightness-[0.4]",e),...r,children:[t,n&&c.jsxs(sC,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[open]:bg-interactive-active data-[open]:text-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[c.jsx($,{name:"close"}),c.jsx("span",{className:"sr-only",children:"Close"})]})]})})]})}function ou({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Gj({className:e,...t}){return c.jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",e),...t})}function iu({className:e,...t}){return c.jsx(oC,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",e),...t})}function Vm({className:e,...t}){return c.jsx(iC,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",e),...t})}function Zj(...e){return t=>{for(const n of e)n&&(typeof n=="function"?n(t):n.current=t)}}function Yj(e,t){const n={...t};for(const r in e){const s=t[r],o=e[r];/^on[A-Z]/.test(r)&&typeof s=="function"&&typeof o=="function"?n[r]=(...i)=>{o(...i),s(...i)}:r==="className"&&typeof s=="string"&&typeof o=="string"?n[r]=`${o} ${s}`:r==="style"&&typeof s=="object"&&typeof o=="object"?n[r]={...o,...s}:n[r]=o}return n}const Xj=H.forwardRef(function({children:t,...n},r){if(!H.isValidElement(t))return null;const s=t;return H.cloneElement(s,{...Yj(s.props,n),ref:Zj(r,s.ref)})}),Jj=["bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","text-[var(--primary-base)]","border border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","active:bg-[color-mix(in_srgb,var(--primary-base)_22%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--primary-base)_30%,transparent)]"].join(" "),Qj=["bg-[color-mix(in_srgb,var(--status-error)_7%,var(--background))]","text-[var(--status-error)]","border border-[color-mix(in_srgb,var(--status-error)_9%,transparent)]","hover:bg-[color-mix(in_srgb,var(--status-error)_11%,var(--background))]","active:bg-[color-mix(in_srgb,var(--status-error)_16%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--status-error)_9%,transparent)]","dark:border-[color-mix(in_srgb,var(--status-error)_14%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--status-error)_14%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--status-error)_20%,transparent)]"].join(" "),e_=["bg-[color-mix(in_srgb,var(--status-info)_4%,var(--background))]","text-[var(--status-info)]","border border-[color-mix(in_srgb,var(--status-info)_8%,transparent)]","hover:bg-[color-mix(in_srgb,var(--status-info)_7%,var(--background))]","active:bg-[color-mix(in_srgb,var(--status-info)_10%,var(--background))]","dark:bg-[color-mix(in_srgb,var(--status-info)_7%,transparent)]","dark:border-[color-mix(in_srgb,var(--status-info)_12%,transparent)]","dark:hover:bg-[color-mix(in_srgb,var(--status-info)_10%,transparent)]","dark:active:bg-[color-mix(in_srgb,var(--status-info)_14%,transparent)]"].join(" "),t_=m5(["group relative inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] typography-ui-label font-medium lowercase tracking-[0.01em] shrink-0 select-none","transition-[background-color,border-color,color,opacity] duration-150 ease-out outline-none","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive","disabled:pointer-events-none disabled:opacity-50","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"],{variants:{variant:{default:Jj,destructive:R(Qj,"focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40"),info:e_,neutral:"bg-interactive-hover text-foreground border border-border/60 hover:bg-interactive-active",outline:"bg-[var(--surface-elevated)] text-foreground border border-border/60 hover:bg-interactive-hover hover:text-foreground",chip:R("border border-border/60 bg-transparent text-foreground hover:bg-interactive-hover hover:text-foreground","aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","aria-pressed:text-[var(--primary-base)]","aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","aria-pressed:hover:text-[var(--primary-base)]","dark:aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]","aria-checked:bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","aria-checked:text-[var(--primary-base)]","aria-checked:border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","aria-checked:hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","aria-checked:hover:text-[var(--primary-base)]","dark:aria-checked:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:aria-checked:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:aria-checked:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]"),secondary:"bg-interactive-hover text-foreground hover:bg-interactive-active",ghost:"text-foreground hover:bg-interactive-hover hover:text-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-3.5 has-[>svg]:px-3",sm:"h-8 gap-1.5 px-2.5 has-[>svg]:px-2 rounded-[9px] supports-[corner-shape:squircle]:rounded-[50px]",xs:"h-6 gap-1 px-2 typography-micro has-[>svg]:px-1.5 rounded-[7px] supports-[corner-shape:squircle]:rounded-[50px]",lg:"h-10 px-4 has-[>svg]:px-3.5 rounded-[12px] supports-[corner-shape:squircle]:rounded-[50px]",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function Se({className:e,variant:t,size:n,asChild:r=!1,type:s,...o}){const i=r?Xj:"button",a=r?s===void 0?{}:{type:s}:{type:s??"button"};return c.jsx(i,{"data-slot":"button",className:R(t_({variant:t,size:n,className:e})),...a,...o})}const $m="oc-glass-popover oc-glass-floating app-region-no-drag transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 z-50 max-h-[var(--available-height)] min-w-[8rem] origin-[var(--transform-origin)] overflow-visible rounded-xl p-1",n_="data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r_="data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s_="bg-border -mx-1 my-0.5 h-px",au=H.createContext(null),o_=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function ww(e,t){return e&&H.isValidElement(t)?{render:t}:{children:t}}function cu({...e}){const[t,n]=H.useState(null),r=H.useMemo(()=>({portalContainer:t,setPortalContainer:n}),[t]);return c.jsx(au.Provider,{value:r,children:c.jsx(dC,{...e})})}function lu({asChild:e,children:t,onPointerDownCapture:n,onFocusCapture:r,...s}){const o=H.useContext(au),i=H.useCallback(l=>{if(!o)return;const d=l instanceof HTMLElement?l:null;o.setPortalContainer(o_(d))},[o]),a=ww(e,t);return c.jsx(uC,{"data-slot":"dropdown-menu-trigger",onPointerDownCapture:l=>{i(l.currentTarget),n?.(l)},onFocusCapture:l=>{i(l.currentTarget),r?.(l)},...s,...a})}function du({className:e,sideOffset:t=4,align:n,side:r,alignOffset:s,portalToBody:o=!1,positionerClassName:i,style:a,children:l,onCloseAutoFocus:d,...f}){const u=H.useContext(au);return c.jsx(g5,{container:o?void 0:u?.portalContainer||void 0,children:c.jsx(y5,{sideOffset:t,align:n,side:r,alignOffset:s,className:R("app-region-no-drag z-50",i),children:c.jsx(v5,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...a},className:R($m,e),...f,children:l})})})}function ho({className:e,inset:t,variant:n="default",asChild:r,children:s,onSelect:o,onClick:i,...a}){const l=ww(r,s),d=f=>{i?.(f),f.defaultPrevented||o?.(f)};return c.jsx(fC,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:R(n_,e),...a,onClick:d,...l})}function i_({...e}){return c.jsx(pC,{"data-slot":"dropdown-menu-radio-group",...e})}function a_({className:e,children:t,...n}){return c.jsxs(mC,{"data-slot":"dropdown-menu-radio-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[checked]:bg-interactive-selection data-[checked]:text-interactive-selection-foreground relative flex cursor-pointer items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",e),...n,children:[c.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:c.jsx(gC,{children:c.jsx($,{name:"check",className:"size-3"})})}),t]})}function rX({className:e,inset:t,...n}){return c.jsx("div",{"data-slot":"dropdown-menu-label","data-inset":t,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",e),...n})}function c_({className:e,...t}){return c.jsx(hC,{"data-slot":"dropdown-menu-separator",className:R(s_,e),...t})}function sX({...e}){return c.jsx(yC,{...e})}function oX({className:e,inset:t,children:n,...r}){return c.jsxs(vC,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:R(r_,e),...r,children:[n,c.jsx($,{name:"arrow-right-s",className:"ml-auto size-3.5"})]})}function iX({className:e,children:t,...n}){const r=H.useContext(au);return c.jsx(g5,{container:r?.portalContainer||void 0,children:c.jsx(y5,{className:"z-50",children:c.jsx(v5,{"data-slot":"dropdown-menu-sub-content",style:{color:"var(--surface-elevated-foreground)"},className:R($m,e),...n,children:t})})})}const l_={local:"This computer",lan:"Local network",tailscale:"Tailscale",relay:"PiChamber Relay",tunnel:"Tunnel",direct:"Direct"},zm={checking:{label:"Checking",tone:"info",description:"Probing the server for reachability."},connected:{label:"Connected",tone:"success",description:"The server answered and accepted the saved credential."},reachable:{label:"Reachable",tone:"info",description:"The server answered, but sign-in state is not verified."},offline:{label:"Offline",tone:"error",description:"The server did not answer."},"sign-in-required":{label:"Sign-in required",tone:"warning",description:"The server rejected the saved credential."},"update-required":{label:"Update required",tone:"error",description:"The server version is too old to connect."},"update-recommended":{label:"Update recommended",tone:"warning",description:"The server works, but a newer version is available."},incompatible:{label:"Incompatible",tone:"error",description:"The server version cannot work with this app."},"wrong-service":{label:"Wrong service",tone:"error",description:"The address answered, but it is not a PiChamber server."},unknown:{label:"Unknown",tone:"muted",description:"This server has not been probed yet."}},Sw=e=>{switch(e){case"ok":return"connected";case"auth":return"sign-in-required";case"update-required":return"update-required";case"update-recommended":return"update-recommended";case"incompatible":return"incompatible";case"wrong-service":return"wrong-service";case"unreachable":return"offline";case"reachable":return"reachable"}},d_=(e,t)=>e?{status:Sw(e.status),latencyMs:Math.max(0,Math.round(e.latencyMs)),refreshing:t}:{status:t?"checking":"unknown",latencyMs:null,refreshing:t},u_=e=>e==="offline"||e==="wrong-service"||e==="incompatible",f_=e=>{try{return new URL(e).hostname.toLowerCase()}catch{return null}},h_=e=>/^10\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^192\.168\./.test(e)||/^169\.254\./.test(e),p_=e=>h_(e)?!0:e.endsWith(".local")||e.endsWith(".lan")||e.endsWith(".home")||e.endsWith(".internal"),m_=e=>{const t=f_(e);return t?t.endsWith(".ts.net")?"tailscale":t.endsWith(".trycloudflare.com")||t.endsWith(".cfargotunnel.com")?"tunnel":p_(t)?"lan":"direct":"direct"},Hc=(e,t)=>({kind:e,label:l_[e],address:t}),g_=(e,t)=>e.kind===t.kind&&(e.address||null)===(t.address||null),Sf=(e,t)=>{try{return e?e(t):t}catch{return t}},y_=(e,t)=>{const n=d_(t.probe,t.probing===!0),r=t.redactUrl?Sf(t.redactUrl,e.label):e.label;let s;if(t.isLocal){const a=(t.localOrigin||e.apiUrl||e.url||"").trim();s=[Hc("local",a?Sf(t.redactUrl,a):null)]}else if(e.relay&&!e.apiUrl)s=[Hc("relay",null)];else{const a=Sf(t.redactUrl,e.apiUrl||e.url),l=Hc(m_(e.apiUrl||e.url),a);s=e.relay?[l,Hc("relay",null)]:[l]}let o=null;t.probe&&Sw(t.probe.status)==="connected"&&(t.probe.via==="relay"?o=s.find(a=>a.kind==="relay")||s[0]||null:o=s.find(a=>a.kind!=="relay")||s[0]||null);const i=!!e.relay&&!e.apiUrl&&!t.isLocal;return{id:e.id,label:r,isCurrent:t.isCurrent,isDefault:t.isDefault,isLocal:t.isLocal,routes:s,activeRoute:o,status:n.status,latencyMs:n.latencyMs,canEdit:!t.isLocal&&!i,canRemove:!t.isLocal,canOpenInNewWindow:!0}},v_=e=>[...e].sort((t,n)=>Number(n.isCurrent)-Number(t.isCurrent)||Number(n.isDefault)-Number(t.isDefault)||t.label.localeCompare(n.label)),x_=e=>e.activeRoute?.address?e.activeRoute.address:e.routes.find(t=>t.address)?.address||null,Cl=e=>`${e.kind}::${e.address??""}`,b_=e=>{if(e.routes.length===0)return null;const t=e.activeRoute;if(t){const n=e.routes.find(r=>g_(r,t));if(n)return n}return e.routes[0]??null},w_=(e,t)=>e.routes.find(n=>Cl(n)===t)??null,S_=(e,t)=>{const n=zm[e].tone;return R("h-2 w-2 rounded-full flex-shrink-0",n==="success"&&"bg-status-success",n==="warning"&&"bg-status-warning",n==="error"&&"bg-status-error",n==="info"&&"bg-status-info",n==="muted"&&"bg-muted-foreground/40",t&&"animate-pulse")},C_=e=>{const t=zm[e].tone;return R("typography-micro truncate",t==="success"&&"text-[var(--status-success)]",t==="warning"&&"text-[var(--status-warning)]",t==="error"&&"text-[var(--status-error)]",t==="info"&&"text-[var(--status-info)]",t==="muted"&&"text-muted-foreground")},k_="typography-micro truncate text-muted-foreground";function M_({item:e,onSelectRoute:t}){const n=b_(e);return n?typeof t=="function"&&e.routes.length>1?c.jsx("span",{className:"flex min-w-0 items-center gap-1.5",children:c.jsxs(cu,{children:[c.jsx(lu,{asChild:!0,children:c.jsxs("button",{type:"button","data-route-picker":"",className:"inline-flex min-w-0 max-w-full items-center gap-0.5 rounded typography-micro text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":`Connection route for ${e.label}: ${n.label}`,children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-muted-foreground/60",children:"·"}),c.jsx("span",{className:"truncate",children:n.label}),c.jsx($,{name:"arrow-down-s",className:"size-3 shrink-0 opacity-70","aria-hidden":"true"})]})}),c.jsx(du,{align:"start",portalToBody:!0,children:c.jsx(i_,{value:Cl(n),onValueChange:s=>{const o=w_(e,s);o&&t?.(e,o)},children:e.routes.map(s=>c.jsx(a_,{value:Cl(s),children:s.label},Cl(s)))})})]})}):c.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-muted-foreground/60",children:"·"}),c.jsx("span",{className:k_,children:n.label})]}):null}const I_=({item:e,layout:t="comfortable",guardDefaultByStatus:n=!1,switchLabel:r="Switch",refreshing:s=!1,pending:o=!1,actionsDisabled:i=!1,onSwitch:a,onSetDefault:l,onOpenInNewWindow:d,onEdit:f,onRemove:u,onSelectRoute:h})=>{const[m,g]=H.useState(!1);H.useEffect(()=>{g(!1)},[e.id]);const x=zm[e.status],b=u_(e.status),S=x_(e),y=t==="touch",v=i||o,C=typeof a=="function",w=e.canOpenInNewWindow&&typeof d=="function",M=e.canEdit&&typeof f=="function",j=e.canRemove&&typeof u=="function",T=C||w||M||j,A=v||n&&!e.isDefault&&b,_=v||e.isCurrent,k=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:S_(e.status,s||e.status==="checking"),"aria-hidden":"true"}),c.jsxs("span",{className:"flex-1 min-w-0 space-y-0.5",children:[c.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0",children:[c.jsx("span",{className:"typography-ui-label font-medium truncate text-foreground min-w-0",children:e.label}),c.jsx(M_,{item:e,onSelectRoute:h}),e.isCurrent&&c.jsx("span",{className:"typography-micro flex-shrink-0 text-muted-foreground bg-muted px-1 rounded leading-none pb-px border border-border/50",children:"Current"})]}),c.jsxs("span",{className:C_(e.status),title:x.description,children:[x.label,typeof e.latencyMs=="number"&&(e.status==="connected"||e.status==="reachable")?` · ${e.latencyMs}ms`:"",s&&e.status!=="checking"?" · checking":""]}),S?c.jsx("span",{className:"typography-micro block truncate font-mono text-muted-foreground/70",children:S}):null]})]});return c.jsxs("div",{className:R("group flex gap-2 overflow-hidden rounded-md px-2.5 py-2",y?"flex-col rounded-xl bg-[var(--surface-muted)] px-3 py-2.5":"items-center",y&&e.isCurrent&&"bg-[var(--interactive-selection)]/25"),children:[c.jsxs("div",{className:R("flex min-w-0 flex-1 gap-2",y?"items-start":"items-center"),children:[C&&!e.isCurrent?c.jsxs("div",{className:R("relative flex items-center gap-2 flex-1 min-w-0",_&&"opacity-70"),children:[c.jsx("button",{type:"button",className:"absolute inset-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>a?.(e),disabled:_,"aria-label":`${r} to ${e.label}`}),o?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):null,c.jsx("span",{className:"pointer-events-none flex items-center gap-2 flex-1 min-w-0 [&_[data-route-picker]]:pointer-events-auto [&_[data-route-picker]]:relative",children:k})]}):c.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0","aria-label":e.isCurrent?`Current server ${e.label}`:void 0,children:k}),c.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[typeof l=="function"&&c.jsx("button",{type:"button",className:R("rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",y?"h-11 w-11":"h-8 w-8","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e.isDefault?"text-primary hover:text-primary/80":"text-muted-foreground/60 hover:text-primary/80",A&&"opacity-40 cursor-not-allowed"),onClick:()=>l?.(e),disabled:A,"aria-label":e.isDefault?`Default server ${e.label}`:`Set ${e.label} as default server`,"aria-pressed":e.isDefault,title:e.isDefault?"Default":"Set as default",children:c.jsx($,{name:e.isDefault?"star-fill":"star",className:"h-4 w-4","aria-hidden":"true"})}),T&&c.jsxs(cu,{children:[c.jsx(lu,{asChild:!0,children:c.jsx("button",{type:"button",className:R("rounded-md inline-flex items-center justify-center text-muted-foreground/60 hover:text-foreground hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-40",y?"h-11 w-11":"h-8 w-8"),"aria-label":`Actions for ${e.label}`,disabled:v,children:c.jsx($,{name:"more",className:"h-4 w-4","aria-hidden":"true"})})}),c.jsxs(du,{align:"end",portalToBody:!0,children:[C&&c.jsx(ho,{disabled:_,onSelect:()=>a?.(e),children:e.isCurrent?"Current server":`${r} to this server`}),w&&c.jsx(ho,{disabled:v||b,onSelect:()=>d?.(e),children:b?"Server unreachable":"Open in new window"}),M&&c.jsx(ho,{disabled:v,onSelect:()=>f?.(e),children:"Edit"}),j&&(C||w||M)&&c.jsx(c_,{}),j&&c.jsx(ho,{variant:"destructive",disabled:v,onSelect:()=>g(!0),children:"Remove"})]})]})]})]}),m&&j&&c.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-2 rounded-md border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2",children:[c.jsx("span",{className:"typography-ui-label flex-1 min-w-0 text-foreground",children:`Remove ${e.label}?`}),c.jsx(Se,{type:"button",variant:"destructive",size:y?"sm":"xs",className:y?"min-h-[44px]":void 0,disabled:v,onClick:()=>{g(!1),u?.(e)},"aria-label":`Confirm remove ${e.label}`,children:"Remove"}),c.jsx(Se,{type:"button",variant:"outline",size:y?"sm":"xs",className:y?"min-h-[44px]":void 0,onClick:()=>g(!1),"aria-label":`Keep ${e.label}`,children:"Keep"})]})]})},E_=({items:e,emptyMessage:t="No servers yet.",pendingId:n=null,...r})=>e.length===0?c.jsx("p",{className:"typography-meta text-muted-foreground",children:t}):c.jsx("div",{className:"space-y-1",role:"list","aria-label":"Servers",children:e.map(s=>c.jsx("div",{role:"listitem",children:c.jsx(I_,{item:s,pending:n===s.id,...r})},s.id))}),j_=()=>{const e=new Map;return(t,n)=>{const r=e.get(t);if(r)return r;const s=n().finally(()=>{e.get(t)===s&&e.delete(t)});return e.set(t,s),s}},__=j_(),T_=(e="",t="")=>({id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`header-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:e,value:t}),A_=e=>e.trim().toLowerCase()==="authorization",Cf=e=>{const t={};for(const n of e){const r=n.name.trim(),s=n.value.trim();r&&s&&!A_(r)&&(t[r]=s)}return Object.keys(t).length>0?t:void 0},aX=e=>Object.entries(e||{}).map(([t,n])=>T_(t,n)),u2=async e=>{const t=await gr(e);t.ok||console.error("Failed to copy to clipboard:",t.error)},cd=e=>e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(cd).join(" ").trim():H.isValidElement(e)?cd(e.props?.children):"",N_=e=>typeof e=="function"?e():e,f2=(e,t)=>{const n=cd(N_(t?.description));return n.length>0?n:cd(e)},Ce={...ai,success:(e,t)=>ai.success(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),info:(e,t)=>ai.info(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),error:(e,t)=>ai.error(e,{...t,action:t?.action||{label:"Copy",onClick:()=>u2(f2(e,t))}}),warning:(e,t)=>ai.warning(e,{...t,action:t?.action||{label:"Copy",onClick:()=>u2(f2(e,t))}})},kl=new Map,L_=()=>Object.fromEntries(kl),h2={status:"unreachable",latencyMs:0},kf=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",p2=e=>{const t=Lr(e);if(!t)return e.trim();try{const n=new URL(t);return n.pathname.endsWith("/")||(n.pathname=`${n.pathname}/`),n.toString()}catch{return t}},m2=async()=>Br()?gS().catch(()=>""):"",Mf=e=>{const t=e.trim();if(t)try{window.location.assign(t)}catch{window.location.href=t}},R_="Invalid PiChamber connection link.",Li="Invalid URL (must be http/https)",P_=e=>(e instanceof Error?e.message:String(e))==="invalid-connect-link"?R_:Li;function D_(e){const t=e?.autoLoad!==!1,[n,r]=H.useState([]),[s,o]=H.useState(null),[i,a]=H.useState(()=>lS()),[l,d]=H.useState(()=>L_()),[f,u]=H.useState(!1),[h,m]=H.useState(!1),[g,x]=H.useState(!1),[b,S]=H.useState(null),[y,v]=H.useState(null),[C,w]=H.useState(0);H.useEffect(()=>en(()=>w(B=>B+1)),[]);const M=H.useMemo(()=>{const B=mS(i),U=n.map(P=>({...P,url:Lr(P.url)||P.url}));return[B,...U]},[n,i]),j=H.useMemo(()=>dS(M),[M,C]),T=H.useMemo(()=>{const B=s||gn;return M.find(U=>U.id===B)?.label||"Local"},[M,s]),A=H.useMemo(()=>{const B=M.map(U=>y_(U,{isCurrent:U.id===j.id,isDefault:(s||gn)===U.id,isLocal:U.id===gn,probe:l[U.id]||null,probing:f,localOrigin:i,redactUrl:Wn}));return v_(B)},[M,j,s,l,f,i]),_=H.useCallback(async()=>{if(wt()){m(!0),v(null);try{const B=await tm();B.localOrigin&&a(B.localOrigin),r(B.hosts||[]),o(B.defaultHostId??null)}catch(B){v(B instanceof Error?B.message:"Failed to load"),r([]),o(null)}finally{m(!1)}}},[]);H.useEffect(()=>{t&&_()},[t,_]);const k=H.useCallback(async(B,U)=>{x(!0),v(null);try{await Vl({hosts:B,defaultHostId:U,initialHostChoiceCompleted:!0}),r(B),o(U)}catch(P){throw v(P instanceof Error?P.message:"Failed to save"),P}finally{x(!1)}},[]),E=H.useCallback(async(B,U)=>__(B.id,async()=>{const P=B.id===gn?U:B.clientToken||"",q=B.requestHeaders||null,F=async()=>{const K=await Tg(B.relay,{clientToken:P,requestHeaders:q}).catch(()=>({status:"unreachable",latencyMs:0}));return{status:K.status,latencyMs:K.latencyMs,...K.status==="ok"?{via:"relay"}:{}}};if(B.relay&&!B.apiUrl)return F();const ee=Lr(Br()?al(B):B.url);if(!ee)return{...h2};const G=await Vu(ee,{clientToken:P||null,requestHeaders:q,expectedServerId:B.serverId??B.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(kf(G.status)&&B.relay){const K=await F();if(K.status==="ok")return K}return{status:G.status,latencyMs:G.latencyMs}}),[]),I=H.useCallback(async B=>{if(!wt())return{};u(!0);try{const U=await m2(),P=await Promise.all(B.map(async q=>[q.id,await E(q,U)]));for(const[q,F]of P)kl.set(q,F);return d(q=>({...q,...Object.fromEntries(P)})),Object.fromEntries(P)}finally{u(!1)}},[E]),N=H.useCallback(async B=>{x(!0),v(null);try{const{hosts:U,hostId:P}=await uS(B,n);return await Vl({hosts:U,defaultHostId:s,initialHostChoiceCompleted:!0}),r(U),{ok:!0,hostId:P}}catch(U){const P=P_(U);return v(P),{ok:!1,error:P}}finally{x(!1)}},[n,s]),O=H.useCallback(async B=>{const U=_g(B.url);if(!U)return v(Li),{ok:!1,error:Li};const P=U.persistedUrl,F={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:B.label.trim()||Wn(P),url:P,apiUrl:P,...B.token.trim()?{clientToken:B.token.trim()}:{},...Cf(B.headers)?{requestHeaders:Cf(B.headers)}:{}};try{await k([F,...n],s)}catch{return{ok:!1,error:"Failed to save"}}return U.redeemUrl&&Mf(U.redeemUrl),{ok:!0}},[n,s,k]),L=H.useCallback(async(B,U)=>{const P=_g(U.url);if(!P)return v(Li),{ok:!1,error:Li};const q=P.persistedUrl,F=n.map(ee=>ee.id===B?{...fS(ee,q),label:U.label.trim()||Wn(q),clientToken:U.token.trim()||void 0,requestHeaders:Cf(U.headers)}:ee);try{await k(F,s)}catch{return{ok:!1,error:"Failed to save"}}return P.redeemUrl&&Mf(P.redeemUrl),{ok:!0}},[n,s,k]),D=H.useCallback(async B=>{const U=n.filter(q=>q.id!==B),P=s===B?gn:s;try{await k(U,P)}catch{}},[n,s,k]),W=H.useCallback(async B=>{try{await k(n,B)}catch{}},[n,k]),z=H.useCallback(async(B,U)=>{const P=M.find(K=>K.id===B);if(!P)return;const q=(K,se)=>{se&&yS({relayUrl:K.relayUrl,serverId:K.serverId,hostEncPubJwk:K.hostEncPubJwk},se),cl({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:P.clientToken||null,runtimeKey:Bu(P),relay:K}),vS(P.id)},F=P.id===gn?i:Lr(P.url)||"",ee=P.id===gn?i:Lr(al(P))||"",G=!!P.relay&&!P.apiUrl&&P.id!==gn;if(!(!F&&!G)){if(Br()){if(!ee&&!P.relay)return;S(P.id);try{const K=P.id===gn?await m2():P.clientToken||"",se=l[P.id];if(se?.status==="ok"){se.via==="relay"&&P.relay?q(P.relay):ee?cl({apiBaseUrl:ee,clientToken:K||null,requestHeaders:P.requestHeaders||null,runtimeKey:Bu(P)}):P.relay&&q(P.relay),U?.onSwitched?.();return}let ce={...h2},re=null;if(ee){const we=await Vu(ee,{clientToken:K||null,requestHeaders:P.requestHeaders||null,expectedServerId:P.serverId??P.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));ce={status:we.status,latencyMs:we.latencyMs},kf(we.status)||(re="direct")}let fe;if(!re&&P.relay){const we=await Tg(P.relay,{keepTunnel:!0,clientToken:K||null,requestHeaders:P.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));we.status==="ok"&&(ce={status:we.status,latencyMs:we.latencyMs,via:"relay"},re="relay",fe="tunnel"in we?we.tunnel:void 0)}const ge=ce;if(kl.set(P.id,ge),d(we=>({...we,[P.id]:ge})),!re){Ce.error(`Server "${Wn(P.label)}" is unreachable`);return}re==="relay"&&P.relay?q(P.relay,fe):cl({apiBaseUrl:ee,clientToken:K||null,requestHeaders:P.requestHeaders||null,runtimeKey:Bu(P)}),U?.onSwitched?.()}finally{S(null)}return}if(P.id!==gn&&wt()){S(P.id);try{const K=await Vu(F,{clientToken:P.clientToken||null,requestHeaders:P.requestHeaders||null,expectedServerId:P.serverId??P.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0})),se={status:K.status,latencyMs:K.latencyMs};if(kl.set(P.id,se),d(ce=>({...ce,[P.id]:se})),kf(K.status)){Ce.error(`Server "${Wn(P.label)}" is unreachable`);return}}finally{S(null)}}U?.onSwitched?.(),Mf(p2(F))}},[M,i,l]),J=H.useCallback(B=>{const U=M.find(F=>F.id===B);if(!U)return;const P=F=>{Ce.error("Failed to open new window",{description:F instanceof Error?F.message:String(F)})};if(U.relay&&U.id!==gn){hS(U.id).catch(P);return}const q=U.id===gn?i:al(U);q&&pS(p2(q),{clientToken:U.clientToken||null,requestHeaders:U.requestHeaders||null}).catch(P)},[M,i]);return{remoteHosts:n,allHosts:M,defaultHostId:s,localOrigin:i,current:j,currentDefaultLabel:T,items:A,statusById:l,probing:f,loading:h,saving:g,switchingHostId:b,error:y,setError:v,load:_,probeAll:I,importPairingLink:N,addManualServer:O,updateServer:L,removeServer:D,setDefaultServer:W,switchToHost:z,openInNewWindow:J}}function O_({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){const s=te(u=>u.setSettingsDialogOpen),o=te(u=>u.setSettingsPage),i=D_({autoLoad:!1}),a=H.useCallback(()=>{o("servers"),s(!0),t(!1)},[t,s,o]);H.useEffect(()=>{e&&i.load()},[e]);const l=i.allHosts;if(H.useEffect(()=>{e&&i.probeAll(l)},[e,l]),!wt())return null;const d=wt(),f=c.jsxs(c.Fragment,{children:[n?c.jsx("div",{className:"flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("div",{className:"min-w-0 flex items-baseline gap-1.5 typography-ui-label",children:[c.jsx("span",{className:"font-medium text-foreground",children:"Current"}),c.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:Wn(i.current.label)}),c.jsx("span",{className:"text-muted-foreground/50",children:"•"}),c.jsx("span",{className:"font-medium text-foreground",children:"Default"}),c.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:Wn(i.currentDefaultLabel)})]}),c.jsx("button",{type:"button",className:R("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:()=>{i.probeAll(i.allHosts)},disabled:!d||i.loading||i.probing,"aria-label":"Refresh servers",children:c.jsx($,{name:"refresh",className:R("h-4 w-4",i.probing&&"animate-spin")})})]})}):c.jsxs(ou,{className:"flex-shrink-0",children:[c.jsxs(iu,{className:"flex items-center gap-2",children:[c.jsx($,{name:"server",className:"h-5 w-5"}),"Servers"]}),c.jsx(Vm,{children:"Switch between this computer and remote PiChamber servers"})]}),!n&&c.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[c.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current:"}),c.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Wn(i.current.label)}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current default:"}),c.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Wn(i.currentDefaultLabel)})]}),c.jsx("div",{className:"flex items-center gap-1",children:c.jsxs(Se,{type:"button",size:"sm",variant:"ghost",onClick:()=>{i.probeAll(i.allHosts)},disabled:!d||i.loading||i.probing,children:[c.jsx($,{name:"refresh",className:R("h-4 w-4",i.probing&&"animate-spin")}),"Refresh"]})})]}),!d&&c.jsx("div",{className:"flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3",children:c.jsx("div",{className:"typography-meta text-muted-foreground",children:"Server switcher is limited on this page. Use Local to recover."})}),c.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:c.jsx("div",{className:R(n&&"px-3 py-1"),children:i.loading?c.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading..."}):c.jsx(E_,{items:i.items,layout:n?"touch":"comfortable",guardDefaultByStatus:!0,refreshing:i.probing,pendingId:i.switchingHostId,actionsDisabled:i.saving,onSwitch:u=>{i.switchToHost(u.id,{onSwitched:r})},onSetDefault:u=>{i.setDefaultServer(u.id)},onOpenInNewWindow:u=>i.openInNewWindow(u.id)})})}),c.jsx("div",{className:"flex-shrink-0 border-t border-[var(--interactive-border)]",children:c.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors",onClick:a,children:[c.jsx($,{name:"add",className:"h-4 w-4"}),c.jsx("span",{className:"typography-ui-label",children:"Add server"})]})}),i.error&&c.jsx("div",{className:"flex-shrink-0 typography-meta text-status-error",children:i.error})]});return n?c.jsx("div",{className:"w-full max-h-[70vh] flex flex-col overflow-hidden gap-2",children:f}):c.jsx(ru,{open:e,onOpenChange:t,children:c.jsx(su,{className:"w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3",children:f})})}function Cw(){const[e,t]=H.useState(!1);return wt()?c.jsxs(c.Fragment,{children:[c.jsxs(Se,{type:"button",variant:"ghost",size:"sm","data-oc-host-switcher":!0,className:"w-full justify-center",onClick:()=>t(!0),children:[c.jsx($,{name:"server",className:"h-4 w-4"}),"Switch server"]}),c.jsx(O_,{open:e,onOpenChange:t})]}):null}const g2=H.memo(function({checked:t,onChange:n,disabled:r=!1,indeterminate:s,ariaLabel:o,className:i,iconClassName:a}){const l="h-[14px] w-[14px] min-h-[14px] min-w-[14px]",d="h-[10px] w-[10px] min-h-[10px] min-w-[10px]",f=t||s;return c.jsx(xC,{checked:t,onCheckedChange:u=>n(!!u),disabled:r,indeterminate:s,"aria-label":o,className:R("group/checkbox relative flex shrink-0 self-center items-center justify-center rounded-[4px] border outline-none",l,"transition-[background-color,border-color,box-shadow] duration-200 ease-out",f?"border-[color:color-mix(in_srgb,var(--primary-base)_65%,var(--interactive-border))] bg-transparent shadow-none hover:bg-[var(--interactive-hover)] hover:border-[color:color-mix(in_srgb,var(--primary-base)_75%,var(--interactive-border))]":"border-[var(--interactive-border)] bg-transparent shadow-none hover:bg-[var(--interactive-hover)] hover:border-[var(--interactive-border)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-transparent","disabled:cursor-not-allowed disabled:opacity-50",i),children:c.jsx(bC,{keepMounted:!0,className:R("flex items-center justify-center text-[var(--primary-base)]","data-[unchecked]:hidden",a),children:s?c.jsx($,{name:"subtract",className:R(d,"text-[var(--primary-base)]")}):c.jsx($,{name:"check",className:R(d,"text-[var(--primary-base)]")})})})});function Fo({className:e,type:t,...n}){return c.jsx("input",{type:t,"data-slot":"input",className:R("text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent","focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none","aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...n})}const Um=({className:e="",width:t=70,height:n=70,isAnimated:r=!1})=>{const s=mw(),i=H.useId().replace(/[^a-zA-Z0-9_-]/g,""),a=`pc-shimmer-mask-${i}`,l=`pc-shimmer-grad-${i}`,d=H.useMemo(()=>{if(s)return s.currentTheme.colors.surface.foreground;if(typeof window<"u"){const f=getComputedStyle(document.documentElement).getPropertyValue("--splash-stroke").trim();return f||(window.matchMedia("(prefers-color-scheme: dark)").matches?"white":"black")}return"white"},[s]);return c.jsxs("svg",{width:t,height:n,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,role:"img","aria-label":"PiChamber logo",children:[r?c.jsxs(c.Fragment,{children:[c.jsxs("defs",{children:[c.jsxs("linearGradient",{id:l,gradientUnits:"userSpaceOnUse",x1:"0",y1:"0",x2:"100",y2:"100",children:[c.jsx("stop",{offset:"0%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"35%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"50%",stopColor:d,stopOpacity:"1"}),c.jsx("stop",{offset:"65%",stopColor:d,stopOpacity:"0"}),c.jsx("stop",{offset:"100%",stopColor:d,stopOpacity:"0"})]}),c.jsx("mask",{id:a,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:"0",y:"0",width:"100",height:"100",children:c.jsxs("g",{fill:"none",children:[c.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:"white",opacity:"0.3"}),c.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:"white",opacity:"0.55"}),c.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:"white",opacity:"0.85"}),c.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68",stroke:"white",strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round"})]})})]}),c.jsx("style",{children:"@keyframes pc-shimmer-anim{0%{transform:translate(-110px,-110px)}100%{transform:translate(110px,110px)}}.pc-shimmer-sweep{animation:pc-shimmer-anim 1.8s cubic-bezier(0.4,0,0.2,1) infinite}@media (prefers-reduced-motion:reduce){.pc-shimmer-sweep{animation:none}}"})]}):null,c.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:d,opacity:r?.04:.08}),c.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:d,opacity:r?.08:.14}),c.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:d,opacity:r?.13:.22}),c.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:d,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",opacity:r?.6:1}),c.jsx("path",{d:"M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68",stroke:d,strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round",opacity:r?.75:1}),r?c.jsx("g",{mask:`url(#${a})`,children:c.jsx("rect",{x:"-50",y:"-50",width:"200",height:"200",fill:`url(#${l})`,className:"pc-shimmer-sweep"})}):null]})},kw=({children:e})=>{const t=p.useMemo(()=>({height:"var(--oc-wco-titlebar-height, 0px)",right:"var(--oc-wco-right-inset, 0px)"}),[]);return c.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[c.jsx("div",{className:"app-region-drag fixed left-0 top-0 z-20",style:t,"aria-hidden":!0}),c.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),c.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),c.jsx("div",{className:"app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:e})]})},H_=()=>c.jsx("div",{className:"flex h-full min-h-screen w-full items-center justify-center overflow-hidden bg-background text-foreground",children:c.jsx(Um,{width:120,height:120,isAnimated:!0})}),y2=({onRetry:e,errorType:t="network",retryAfter:n,children:r})=>{const s=t==="rate-limit",o=n?Math.ceil(n/60):1;return c.jsx(kw,{children:c.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:s?"Too many attempts":"Unable to reach server"}),c.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:s?o>1?`Please wait ${o} minutes before trying again.`:`Please wait ${o} minute before trying again.`:"We could not verify the UI session. If you're opening PiChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings."})]}),c.jsx(Se,{type:"button",onClick:e,className:"w-full max-w-xs",children:"Retry"}),r]})})},F_=({isTunnelLocked:e,password:t,setPassword:n,passwordInputRef:r,isSubmitting:s,errorMessage:o,setErrorMessage:i,trustDevice:a,setTrustDevice:l,supportsPasskeys:d,passkeyStatus:f,isPasskeyBusy:u,activePasskeyAction:h,showHostSwitcher:m,onSubmit:g,onPasskeyUnlock:x,onPasskeySetupOnly:b})=>{const S=d&&f.hasPasskeys,y=d&&!f.hasPasskeys;return c.jsx(kw,{children:c.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[c.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[c.jsx("h1",{className:"text-xl font-semibold text-foreground",children:e?"Tunnel access required":"Unlock PiChamber"}),c.jsx("p",{className:"typography-meta text-muted-foreground",children:e?"Open this tunnel using the one-time connect link from the desktop app.":"This session is password-protected."})]}),!e&&c.jsxs("form",{onSubmit:g,className:"w-full space-y-2",children:[S&&c.jsxs(Se,{type:"button",variant:"outline",className:"w-full",onClick:()=>{x()},disabled:s||u&&h!=="auth",children:[u?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx($,{name:"lock-unlock",className:"h-4 w-4"}),c.jsx("span",{children:u&&h==="auth"?"Cancel passkey":"Use passkey"})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("div",{className:"relative flex-1",children:[c.jsx($,{name:"lock",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),c.jsx(Fo,{id:"pichamber-ui-password",ref:r,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:t,onChange:v=>{n(v.target.value),o&&i("")},className:"pl-10","aria-invalid":!!o||void 0,"aria-describedby":o?"oc-ui-auth-error":void 0,disabled:s})]}),c.jsx(Se,{type:"submit",size:"icon",disabled:!t||s,"aria-label":s?"Unlocking":"Unlock",children:s?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx($,{name:"lock-unlock",className:"h-4 w-4"})})]}),y?c.jsxs("div",{className:"flex items-center justify-between pt-1",children:[c.jsxs("label",{className:"flex items-center gap-2 text-center typography-micro text-muted-foreground",children:[c.jsx(g2,{checked:a,onChange:l,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),c.jsx("span",{children:"Trust this device"})]}),c.jsx(Se,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-foreground",onClick:()=>{b()},disabled:s,children:u&&h==="register"?"Cancel passkey setup":"Add passkey"})]}):c.jsxs("label",{className:"flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground",children:[c.jsx(g2,{checked:a,onChange:l,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),c.jsx("span",{children:"Trust this device"})]}),o&&c.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:o})]}),m&&c.jsxs("div",{className:"w-full",children:[c.jsx(Cw,{}),c.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})})},B_="/auth/passkey/authenticate/options",V_="/auth/passkey/authenticate/verify",$_="/auth/passkey/register/options",z_="/auth/passkey/register/verify",Mw="/api/passkeys",U_="/auth/passkey/status",q_="/api/auth/reset",Ml={enabled:!1,hasPasskeys:!1,passkeyCount:0,rpID:null},Ca=async(e,t)=>Nt(e,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:t===void 0?void 0:JSON.stringify(t)}),Ts=async(e,t)=>{try{const n=await e.json();if(n&&typeof n.error=="string"&&n.error.trim())return n.error}catch{}return t},If=e=>e instanceof CC&&e.code==="ERROR_CEREMONY_ABORTED",v2=()=>{wC.cancelCeremony()},Iw=()=>typeof window>"u"?{supported:!1,reason:"Passkeys are unavailable outside the browser."}:window.isSecureContext?{supported:!0,reason:""}:{supported:!1,reason:"Passkeys require HTTPS or localhost."},x2=async()=>{const e=Iw();if(!e.supported)throw new Error(e.reason);const t=typeof navigator.userAgent=="string"&&navigator.userAgent.trim()?navigator.userAgent:"This device",n=await Ca($_,{label:t});if(!n.ok)throw new Error(await Ts(n,"Could not start passkey setup."));const{requestId:r,optionsJSON:s}=await n.json(),o=await SC({optionsJSON:s}),i=await Ca(z_,{requestId:r,response:o});if(!i.ok)throw new Error(await Ts(i,"Could not finish passkey setup."));return i.json().catch(()=>null)},W_=async(e,t={})=>{const n=Iw();if(!n.supported)throw new Error(n.reason);const r=await Ca(B_);if(!r.ok)throw new Error(await Ts(r,"Passkey sign-in is not available right now."));const{requestId:s,optionsJSON:o}=await r.json(),i=await kC({optionsJSON:o}),a=await Ca(V_,{requestId:s,response:i,trustDevice:e,issueClientToken:t.issueClientToken===!0,clientLabel:t.clientLabel,clientKind:t.clientKind,dedupeKey:t.dedupeKey});if(!a.ok)throw new Error(await Ts(a,"Passkey sign-in failed."));return a.json().catch(()=>null)},K_=async()=>{const e=await Nt(U_,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)return Ml;const t=await e.json().catch(()=>null);return{enabled:t?.enabled===!0,hasPasskeys:t?.hasPasskeys===!0,passkeyCount:typeof t?.passkeyCount=="number"?t.passkeyCount:0,rpID:typeof t?.rpID=="string"&&t.rpID?t.rpID:null}},cX=async()=>{const e=await Nt(Mw,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(await Ts(e,"Could not load passkeys."));const t=await e.json().catch(()=>null);return Array.isArray(t?.passkeys)?t.passkeys:[]},lX=async e=>{const t=await Nt(`${Mw}/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(await Ts(t,"Could not remove passkey."));return t.json().catch(()=>null)},dX=async()=>{const e=await Ca(q_);if(!e.ok)throw new Error(await Ts(e,"Could not clear saved authentication."));return e.json().catch(()=>null)},G_=(e,t)=>e.apiBaseUrl===t.apiBaseUrl&&e.runtimeKey===t.runtimeKey,Z_=e=>e.shouldUseDesktopShellPasswordLogin?"locked":"error",Ew="/auth/session",Y_=4,X_=1500,jw="pichamber.uiAuth.trustDevice",J_="desktop-local",Q_="desktop-local",eT=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},tT=(e,t)=>{const n=Lr(e),r=Lr(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},lp=()=>wt(),nT=e=>{const t=e.replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"},_w=()=>{if(!wt())return!1;const e=eT();if(!e)return!1;const n=Nd()||(typeof window<"u"?window.location.origin:"");if(tT(e,n))return!0;try{const r=Lr(n);return!!(r&&nT(new URL(r).hostname))}catch{return!1}},qm=()=>_w()?{clientKind:J_,dedupeKey:Q_}:{},rT=async()=>await Nt(Ew,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),sT=()=>typeof window>"u"?!1:window.localStorage.getItem(jw)==="true",oT=async(e,t)=>{const n=lp();return await Nt(Ew,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:"PiChamber Desktop",...qm()})})},iT=async()=>{if(!wt())return"";const e=await Nt("/api/client-auth/clients",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:"PiChamber Desktop",...qm()})}).catch(()=>null);if(!e?.ok)return"";const t=await e.json().catch(()=>null);return typeof t?.token=="string"?t.token.trim():""},Ef=()=>wt()&&!_w(),ls=()=>({apiBaseUrl:Nd(),runtimeKey:Y()}),pt=e=>G_(e,ls()),jf=async(e,t,n,r)=>{if(!wt()||typeof window>"u")return null;const s=await dr("desktop_remote_password_login",{url:n.apiBaseUrl,password:e,trustDevice:t,requestHeaders:r}).catch(()=>null);if(!s||typeof s!="object")return null;const o=s.token,i=s.status;return{token:typeof o=="string"?o.trim():"",...typeof i=="number"?{status:i}:{}}},aT=async(e,t)=>{if(!wt()||!t||!pt(e))return!1;const n=await tm().catch(()=>null);if(!n||!pt(e))return!1;const r=xS({runtimeKey:e.runtimeKey,apiBaseUrl:e.apiBaseUrl,hosts:n.hosts,localOrigin:n.localOrigin});return r?r.kind==="local"?(await Vl({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>{}),pt(e)):r.host.clientToken===t?!0:pt(e)?(await Vl({hosts:n.hosts.map(s=>s.id===r.host.id?{...s,clientToken:t}:s),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{}),pt(e)):!1:!0},Fc=async(e,t,n)=>!e||!pt(t)||!await aT(t,e)||!pt(t)?!1:(cl({apiBaseUrl:t.apiBaseUrl,clientToken:e,requestHeaders:Object.keys(n).length>0?n:null,runtimeKey:t.runtimeKey}),!0);function cT(){const t=p.useMemo(()=>wt(),[]),[n,r]=p.useState(()=>"pending"),[s,o]=p.useState(""),[i,a]=p.useState(!1),[l,d]=p.useState(""),[f,u]=p.useState(void 0),[h,m]=p.useState(!1),[g,x]=p.useState(Ml),[b,S]=p.useState(!1),[y,v]=p.useState(!1),[C,w]=p.useState(()=>sT()),[M,j]=p.useState(null),T=p.useRef(null),A=p.useRef(!1);p.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(jw,C?"true":"false")},[C]);const _=p.useCallback(async(q=ls())=>{try{const F=await K_();return pt(q)&&x(F),F}catch{return pt(q)&&x(Ml),Ml}},[!1]);p.useEffect(()=>{let q=!1;return(async()=>{try{if(!window.isSecureContext||!MC()){q||S(!1);return}q||S(!0)}catch{q||S(!1)}})(),()=>{q=!0}},[!1]);const k=p.useRef(0),E=p.useRef(null),I=p.useRef(null),N=p.useCallback(()=>{E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),O=p.useCallback(()=>{k.current=0,N()},[N]),L=p.useCallback(()=>k.current>=Y_?!1:(k.current+=1,N(),E.current=window.setTimeout(()=>{E.current=null,I.current?.()},X_*k.current),!0),[N]);p.useEffect(()=>N,[N]);const D=p.useCallback(async()=>{const q=ls();r(F=>F==="authenticated"?F:"pending");try{const[F,ee]=await Promise.all([rT(),_(q)]),G=await F.text();if(!pt(q))return;if(F.ok){O(),r("authenticated"),m(!1),d(""),u(void 0);return}if(F.status===401){let K={};try{K=JSON.parse(G)}catch{K={}}O(),m(K.tunnelLocked===!0),x(ee),r("locked"),u(void 0);return}if(F.status===429){let K={};try{K=JSON.parse(G)}catch{K={}}O(),u(K.retryAfter),m(!1),r("rate-limited");return}if(L())return;r("error"),m(!1)}catch(F){if(!pt(q))return;if(console.warn("Failed to check session status:",F),Z_({shouldUseDesktopShellPasswordLogin:Ef()})==="locked"){r("locked"),u(void 0),m(!1);return}if(L())return;r("error"),m(!1)}},[_,O,L,!1]);p.useEffect(()=>{I.current=D},[D]),p.useEffect(()=>{D()},[D,!1]),p.useEffect(()=>bS(()=>{O(),D()}),[D,O,!1]),p.useEffect(()=>en(()=>{v2(),o(""),d(""),u(void 0),m(!1),a(!1),j(null),v(!1),O(),r("pending"),D()}),[D,O,!1]),p.useEffect(()=>{n==="locked"&&(A.current=!1)},[!1,n]),p.useEffect(()=>{n==="locked"&&T.current&&(T.current.focus(),T.current.select())},[n]),p.useEffect(()=>{n==="authenticated"&&(A.current=!0)},[!1,n]);const W=p.useCallback(async()=>{const q=ls();j("register"),v(!0);try{await x2()}finally{pt(q)&&(j(null),v(!1))}pt(q)&&await _(q)},[_]),z=p.useCallback(()=>{v2(),j(null),v(!1)},[]),J=p.useCallback(async q=>{if(h||!s||i)return;y&&z();const F=ls(),ee=Ag();a(!0),d("");try{if(Ef()){const K=await jf(s,C,F,ee);if(!pt(F))return;if(K?.token){if(o(""),m(!1),!await Fc(K.token,F,ee))return;r("authenticated");return}if(K?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(K?.status===429){u(void 0),m(!1),r("rate-limited");return}}const G=await oT(s,C);if(!pt(F))return;if(G.ok){const K=await G.json().catch(()=>null);if(!pt(F))return;const se=lp();let ce="";if(se&&(ce=typeof K?.clientToken=="string"&&K.clientToken.trim()?K.clientToken.trim():"",!ce)){const re=await jf(s,C,F,ee);if(!pt(F)||(ce=re?.token||await iT(),!pt(F)))return}if(o(""),m(!1),ce&&!await Fc(ce,F,ee))return;if(q&&b)try{if(await W(),!pt(F))return;Ce.success("Passkey added"),r("authenticated");return}catch(re){if(If(re))Ce.message("Passkey setup canceled");else{const fe=re instanceof Error?re.message:"Passkey setup failed.";Ce.error(fe)}r("authenticated");return}r("authenticated");return}if(G.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(G.status===429){const K=await G.json().catch(()=>({}));u(K.retryAfter),m(!1),r("rate-limited");return}d("Unexpected response from server."),m(!1),r("error")}catch(G){if(!pt(F))return;console.warn("Failed to submit UI password:",G);const K=Ef()?await jf(s,C,F,ee):null;if(!pt(F))return;if(K?.token){if(o(""),m(!1),!await Fc(K.token,F,ee))return;r("authenticated");return}if(K?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(K?.status===429){u(void 0),m(!1),r("rate-limited");return}d("Network error. Check connection and retry."),m(!1),r("error")}finally{pt(F)&&a(!1)}},[z,y,i,h,s,W,b,C]),B=p.useCallback(async()=>{if(i||!b)return;if(y){z();return}v(!0),j("auth"),d("");const q=ls(),F=Ag();try{const ee=await W_(C,{issueClientToken:lp(),clientLabel:"PiChamber Desktop",...qm()});if(!pt(q))return;if(typeof ee?.clientToken=="string"&&ee.clientToken.trim()){const G=ee.clientToken.trim();if(!await Fc(G,q,F))return}m(!1),r("authenticated")}catch(ee){if(!pt(q)||If(ee))return;const G=ee instanceof Error?ee.message:"Passkey sign-in failed.";d(G)}finally{pt(q)&&(j(null),v(!1))}},[z,y,i,b,C]),U=p.useCallback(async()=>{if(i||!b)return;if(y){z();return}const q=ls();j("register"),v(!0);try{if(await x2(),!pt(q))return;Ce.success("Passkey added"),await _(q)}catch(F){if(!pt(q))return;if(If(F))Ce.message("Passkey setup canceled");else{const ee=F instanceof Error?F.message:"Passkey setup failed.";Ce.error(ee)}}finally{pt(q)&&(j(null),v(!1))}},[z,y,i,_,b]);return{state:n,password:s,setPassword:o,passwordInputRef:T,isSubmitting:i,errorMessage:l,setErrorMessage:d,retryAfter:f,isTunnelLocked:h,passkeyStatus:g,supportsPasskeys:b,isPasskeyBusy:y,trustDevice:C,setTrustDevice:w,activePasskeyAction:M,showHostSwitcher:t,resetTransientRetry:O,checkStatus:D,handleSubmit:async q=>{q.preventDefault(),await J(!1)},handlePasswordUnlock:J,handlePasskeyUnlock:B,handlePasskeySetupOnly:U}}const uX=({children:e})=>{const{state:t,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,retryAfter:l,isTunnelLocked:d,passkeyStatus:f,supportsPasskeys:u,isPasskeyBusy:h,trustDevice:m,setTrustDevice:g,activePasskeyAction:x,showHostSwitcher:b,resetTransientRetry:S,checkStatus:y,handleSubmit:v,handlePasskeyUnlock:C,handlePasskeySetupOnly:w}=cT();return t==="pending"?c.jsx(H_,{}):t==="error"?c.jsx(y2,{onRetry:()=>{S(),y()},errorType:"network",children:b&&c.jsxs("div",{className:"w-full max-w-xs",children:[c.jsx(Cw,{}),c.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})}):t==="rate-limited"?c.jsx(y2,{onRetry:()=>{y()},errorType:"rate-limit",retryAfter:l}):t==="locked"?c.jsx(F_,{isTunnelLocked:d,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,trustDevice:m,setTrustDevice:g,supportsPasskeys:u,passkeyStatus:f,isPasskeyBusy:h,activePasskeyAction:x,showHostSwitcher:b,onSubmit:v,onPasskeyUnlock:C,onPasskeySetupOnly:w}):c.jsx(c.Fragment,{children:e})},uu=e=>{try{return new URL(e)}catch{return null}},fX=e=>{const t=uu(e.trim());return t?t.protocol==="http:"||t.protocol==="https:":!1},lT=e=>{const t=uu(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?null:`https://icons.duckduckgo.com/ip3/${t.hostname.toLowerCase()}.ico`},dT=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),uT=e=>{const t=uu(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?!1:dT.has(t.hostname.toLowerCase())},fT=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi,hT=e=>{if(!e)return[];const t=e.match(fT);if(!t||t.length===0)return[];const n=new Set,r=[];for(const s of t){const o=s.replace(/[),.;:!?'"`]+$/g,"");!o||!uT(o)||n.has(o)||(n.add(o),r.push(o))}return r},ka=async e=>{if(typeof window>"u")return!1;const t=e.trim();if(!t)return!1;const n=uu(t);if(!n||n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.toString(),s=window.__PICHAMBER_DESKTOP__;if(s?.openExternal)try{return await s.openExternal(r),!0}catch{}try{return window.open(r,"_blank","noopener,noreferrer"),!0}catch{return!1}};function pT(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=tu();return e}catch{return"unknown"}}function mT(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function gT(){const e=CS();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const t=(navigator.platform||"").toLowerCase();return t.includes("mac")?"macos":t.includes("win")?"windows":t.includes("linux")?"linux":"web"}function yT(e){const t=new URLSearchParams;return t.set("deviceClass",pT()),t.set("arch",mT()),t.set("platform",gT()),e==="desktop"?(t.set("appType","desktop-electron"),t.set("instanceMode",Ko()?"local":"remote"),t):e==="mobile"?(t.set("appType","mobile-capacitor"),t.set("instanceMode","remote"),t):(t.set("appType","web"),t.set("instanceMode","unknown"),t)}async function gi(e,t){try{const n=yT(e);t&&n.set("currentVersion",t);const r=await Nt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const s=await r.json();return{available:s.available??!1,version:s.version,currentVersion:s.currentVersion??"unknown",body:s.body,releaseUrl:s.releaseUrl,downloadUrl:s.downloadUrl,nextSuggestedCheckInSec:typeof s.nextSuggestedCheckInSec=="number"&&Number.isFinite(s.nextSuggestedCheckInSec)?s.nextSuggestedCheckInSec:void 0,packageManager:s.packageManager,updateCommand:s.updateCommand,channel:s.channel==="rc"?"rc":"stable"}}catch(n){return console.warn("Failed to check for updates:",n),null}}function vT(){return lr()?"mobile":Br()?"desktop":nm()?"web":null}const b2={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,serverInfo:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},xT=Lt()((e,t)=>({...b2,checkForUpdates:async()=>{const n=vT();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,s=null;if(n==="desktop"){const o="1.0.6-rc.2",i=!Ko(),[a,l]=await Promise.allSettled([Ng(),i?gi("web"):gi("desktop",o)]),d=a.status==="fulfilled"?a.value:null,f=l.status==="fulfilled"?l.value:null;return s=f?.nextSuggestedCheckInSec??null,e({checking:!1,available:d?.available??!1,info:d,serverInfo:i?f:null,lastChecked:Date.now(),nextCheckInSec:s}),s}else if(n==="web")r=await gi("web"),s=r?.nextSuggestedCheckInSec??null;else if(n==="mobile"){const o="1.0.6-rc.2",[i,a]=await Promise.all([gi("mobile",o),gi("web")]);return s=i?.nextSuggestedCheckInSec??a?.nextSuggestedCheckInSec??null,e({checking:!1,available:i?.available??!1,info:i,serverInfo:a,lastChecked:Date.now(),nextCheckInSec:s}),s}return e({checking:!1,available:r?.available??!1,info:r,serverInfo:null,lastChecked:Date.now(),nextCheckInSec:s}),s}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=t();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const s=await Ng();if(!s?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(i=>({info:i.info?{...i.info,...s,body:i.info.body||s.body,available:i.info.available}:s})),!await SS(i=>{e({progress:i})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(s){e({downloading:!1,error:s instanceof Error?s.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=t();if(!(r!=="desktop"||!n))try{if(!await wS())throw new Error("Desktop restart only works on Local instance")}catch(s){e({error:s instanceof Error?s.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null,serverInfo:null})},reset:()=>{e(b2)}}));function bT({className:e,...t}){return c.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",e),...t})}function wT({className:e,...t}){return c.jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ST({className:e,...t}){return c.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",e),...t})}function CT({className:e,...t}){return c.jsx("div",{"data-slot":"card-content",className:R("px-6",e),...t})}class kT extends p.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n,copied:!1}),console.error("Error caught by boundary:",t,n)}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};handleCopy=async()=>{const{strings:t}=this.props,n=this.state.error?String(this.state.error):t.unknownError,r=this.state.error?.stack?`
36
+
37
+ Stack:
38
+ ${this.state.error.stack}`:"",s=this.state.errorInfo?.componentStack?`
39
+
40
+ ${t.componentStackLabel}${this.state.errorInfo.componentStack}`:"",o=`${n}${r}${s}`;(await gr(o)).ok&&(this.setState({copied:!0}),window.setTimeout(()=>{this.setState(a=>a.copied?{copied:!1}:null)},1500))};render(){const{strings:t}=this.props;return this.state.hasError?this.props.fallback?this.props.fallback:c.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:c.jsxs(bT,{className:"w-full max-w-md",children:[c.jsx(wT,{className:"text-center",children:c.jsxs(ST,{className:"flex items-center justify-center gap-2 text-destructive",children:[c.jsx($,{name:"error-warning",className:"h-5 w-5"}),t.title]})}),c.jsxs(CT,{className:"space-y-4",children:[c.jsx("p",{className:"text-sm text-muted-foreground text-center",children:t.description}),this.state.error&&c.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[c.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:t.detailsSummary}),c.jsxs("pre",{className:"mt-2 max-h-48 overflow-auto",children:[this.state.error.toString(),this.state.errorInfo?.componentStack?`
41
+
42
+ ${t.componentStackLabel}${this.state.errorInfo.componentStack}`:""]})]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsxs(Se,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[c.jsx($,{name:"restart",className:"h-4 w-4 mr-2"}),t.tryAgain]}),c.jsx(Se,{onClick:this.handleCopy,variant:"outline",className:"flex-1",children:this.state.copied?t.copied:t.copy})]})]})]})}):this.props.children}}const hX=({children:e,fallback:t})=>{const n=p.useMemo(()=>({unknownError:"Unknown error",title:"Something went wrong",description:"The application encountered an unexpected error. This has been logged for debugging.",detailsSummary:"Error details",componentStackLabel:"Component stack:",tryAgain:"Try again",copied:"Copied",copy:"Copy"}),[]);return c.jsx(kT,{fallback:t,strings:n,children:e})},MT=1e3,w2=.5,S2={length:0,offset:0},C2=(e,t)=>Math.abs(e.length-t.length)<w2&&Math.abs(e.offset-t.offset)<w2,Tw=({containerRef:e,minThumbSize:t=32,hideDelayMs:n=1e3,className:r,disableHorizontal:s=!1,observeMutations:o=!0,suppressVisibility:i=!1,userIntentOnly:a=!1})=>{const[l,d]=p.useState(!1),[f,u]=p.useState({length:0,offset:0}),[h,m]=p.useState({length:0,offset:0}),g=p.useRef(null),x=p.useRef(null),b=p.useRef(null),S=p.useRef(!1),y=p.useRef(!1),v=p.useRef(0),C=p.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),w=p.useRef(null),M=p.useRef(new Set),j=p.useCallback(()=>{const B=e.current;if(!B)return;const{scrollHeight:U,clientHeight:P,scrollTop:q,scrollWidth:F,clientWidth:ee,scrollLeft:G}=B,K=8;let se=S2;if(U>P){const re=Math.max(P-K*2,0),fe=P/U*re,ge=Math.max(t,Math.min(re,fe)),we=Math.max(re-ge,0),Me=Math.max(U-P,1),He=q/Me*we;se={length:ge,offset:He}}u(re=>C2(re,se)?re:se);let ce=S2;if(!s&&F>ee){const re=Math.max(ee-K*2,0),fe=ee/F*re,ge=Math.max(t,Math.min(re,fe)),we=Math.max(re-ge,0),Me=Math.max(F-ee,1),He=G/Me*we;ce={length:ge,offset:He}}m(re=>C2(re,ce)?re:ce)},[e,t,s]),T=p.useCallback(()=>{b.current===null&&(b.current=requestAnimationFrame(()=>{b.current=null,j()}))},[j]),A=p.useCallback((B,U)=>{if(!U){M.current.clear();return}const P=new Set;P.add(B),Array.from(B.children).forEach(q=>{P.add(q)}),M.current.forEach(q=>{P.has(q)||U.unobserve(q)}),P.forEach(q=>{M.current.has(q)||U.observe(q)}),M.current=P},[]),_=p.useCallback(()=>{g.current&&clearTimeout(g.current),!y.current&&(g.current=setTimeout(()=>d(!1),n))},[n]),k=p.useCallback(()=>{v.current=Date.now()},[]),E=p.useCallback(()=>{x.current&&cancelAnimationFrame(x.current),x.current=requestAnimationFrame(()=>{if(j(),i&&!S.current){d(!1);return}if(a&&!S.current&&!(Date.now()-v.current<=MT)){d(!1);return}d(!0),_()})},[_,i,j,a]);p.useEffect(()=>{const B=e.current;if(!B)return;j(),d(!1);const U=()=>E(),P=K=>{(K.key==="ArrowUp"||K.key==="ArrowDown"||K.key==="PageUp"||K.key==="PageDown"||K.key==="Home"||K.key==="End"||K.key===" ")&&k()};B.addEventListener("scroll",U,{passive:!0}),a&&(B.addEventListener("wheel",k,{passive:!0}),B.addEventListener("touchstart",k,{passive:!0}),B.addEventListener("touchmove",k,{passive:!0}),B.addEventListener("keydown",P));const q=typeof ResizeObserver<"u"?new ResizeObserver(()=>{T()}):null;A(B,q);const F=o&&typeof MutationObserver<"u"?new MutationObserver(()=>{A(B,q),T()}):null;F?.observe(B,{childList:!0});const ee=()=>T(),G=()=>T();return B.addEventListener("input",ee,!0),B.addEventListener("load",G,!0),()=>{B.removeEventListener("scroll",U),B.removeEventListener("input",ee,!0),B.removeEventListener("load",G,!0),a&&(B.removeEventListener("wheel",k),B.removeEventListener("touchstart",k),B.removeEventListener("touchmove",k),B.removeEventListener("keydown",P)),q?.disconnect(),F?.disconnect(),M.current.clear(),g.current&&clearTimeout(g.current),x.current&&cancelAnimationFrame(x.current),b.current&&cancelAnimationFrame(b.current)}},[e,E,k,o,T,A,j,a]),p.useEffect(()=>{i&&(S.current||(d(!1),g.current&&(clearTimeout(g.current),g.current=null)))},[i]);const I=(B,U)=>{const P=e.current;P&&(S.current=!0,C.current={pointerX:B.clientX,pointerY:B.clientY,scrollTop:P.scrollTop,scrollLeft:P.scrollLeft},w.current=U,k(),d(!0),g.current&&clearTimeout(g.current),B.currentTarget.setPointerCapture(B.pointerId))},N=B=>{if(!S.current)return;const U=e.current;if(!U)return;const P=w.current;if(P==="vertical"){const{pointerY:q,scrollTop:F}=C.current,ee=B.clientY-q,G=U.clientHeight,K=Math.max(G-f.length,1),se=Math.max(U.scrollHeight-U.clientHeight,1),ce=ee/K*se;U.scrollTop=F+ce}else if(P==="horizontal"){const{pointerX:q,scrollLeft:F}=C.current,ee=B.clientX-q,G=U.clientWidth,K=Math.max(G-h.length,1),se=Math.max(U.scrollWidth-U.clientWidth,1),ce=ee/K*se;U.scrollLeft=F+ce}},O=B=>{S.current&&(S.current=!1,B.currentTarget.releasePointerCapture(B.pointerId),_())},L=p.useCallback(()=>{y.current=!0,g.current&&(clearTimeout(g.current),g.current=null)},[]),D=p.useCallback(()=>{y.current=!1,_()},[_]),W=f.length>0,z=h.length>0;if(!W&&!z)return null;const J=8;return c.jsxs("div",{className:R("overlay-scrollbar",r),"aria-hidden":"true",style:{opacity:l?1:0},children:[W&&c.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical","data-overlay-scrollbar-thumb":"vertical",style:{height:`${f.length}px`,top:`${J+f.offset}px`,right:`${J/2}px`},onPointerDown:B=>I(B,"vertical"),onPointerMove:N,onPointerUp:O,onPointerCancel:O,onMouseEnter:L,onMouseLeave:D}),z&&c.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal","data-overlay-scrollbar-thumb":"horizontal",style:{width:`${h.length}px`,left:`${J+h.offset}px`,bottom:`${J/2}px`},onPointerDown:B=>I(B,"horizontal"),onPointerMove:N,onPointerUp:O,onPointerCancel:O,onMouseEnter:L,onMouseLeave:D})]})};Tw.displayName="OverlayScrollbar";const Aw=Tw;function IT(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n&&typeof n=="object"&&(n.current=t)})}}const fu=p.forwardRef(({as:e="div",orientation:t="vertical",offset:n=0,size:r=48,isEnabled:s=!0,hideTopShadow:o=!1,hideBottomShadow:i=!1,observeMutations:a=!0,onVisibilityChange:l,style:d,className:f,children:u,...h},m)=>{const g=p.useRef(null),x=p.useRef("none"),b=h["data-scroll-shadow"];delete h["data-scroll-shadow"];const S=p.useMemo(()=>{const w={...d};return w["--scroll-shadow-size"]=`${r}px`,w},[r,d]),y=p.useCallback((w,M,j,T,A)=>{const _=`${T}${A.charAt(0).toUpperCase()}${A.slice(1)}Scroll`;M&&j?(w.dataset[_]="true",w.removeAttribute(`data-${T}-scroll`),w.removeAttribute(`data-${A}-scroll`)):(w.dataset[`${T}Scroll`]=String(M),w.dataset[`${A}Scroll`]=String(j),w.removeAttribute(`data-${T}-${A}-scroll`))},[]),v=p.useCallback(w=>{["top","bottom","top-bottom","left","right","left-right"].forEach(M=>{w.removeAttribute(`data-${M}-scroll`)})},[]),C=p.useCallback(()=>{const w=g.current;if(!w)return;if(!s){v(w);return}const M=1,j=t==="vertical"?w.scrollTop>n+M:w.scrollLeft>n+M;let T=t==="vertical"?w.scrollHeight-(w.scrollTop+w.clientHeight)>n+M:w.scrollWidth-(w.scrollLeft+w.clientWidth)>n+M;const A=o&&t==="vertical"?!1:j;i&&t==="vertical"&&(T=!1),y(w,A,T,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const _=A&&T?"both":A?t==="vertical"?"top":"left":T?t==="vertical"?"bottom":"right":"none";_!==x.current&&(x.current=_,l?.(_))},[v,o,i,s,n,l,t,y]);return p.useEffect(()=>{const w=g.current;if(!w)return;let M=null;const j=()=>{M===null&&(M=requestAnimationFrame(()=>{M=null,C()}))},T=()=>C(),A=typeof ResizeObserver<"u"?new ResizeObserver(j):null,_=a&&typeof MutationObserver<"u"?new MutationObserver(j):null;return C(),w.addEventListener("scroll",T,{passive:!0}),A?.observe(w),_?.observe(w,{childList:!0,subtree:!0,characterData:!0}),()=>{M!==null&&cancelAnimationFrame(M),w.removeEventListener("scroll",T),A?.disconnect(),_?.disconnect()}},[C,a]),c.jsx(e,{...h,ref:IT(g,m),className:f,"data-orientation":t,"data-scroll-shadow":b??!0,style:S,children:u})});fu.displayName="ScrollShadow";const Xn=p.forwardRef(({className:e,outerClassName:t,children:n,style:r,minThumbSize:s,hideDelayMs:o,as:i="div",scrollbarClassName:a,disableHorizontal:l=!1,observeMutations:d=!0,fillContainer:f=!0,preventOverscroll:u=!1,useScrollShadow:h=!1,scrollShadowSize:m,hideTopScrollShadow:g=!1,userIntentOnly:x=!1,...b},S)=>{const y=p.useRef(null);return p.useImperativeHandle(S,()=>y.current,[]),c.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden",u&&"overscroll-none",t),children:[h?c.jsx(fu,{as:i,ref:y,size:m,hideTopShadow:g,className:R("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",l?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,observeMutations:d,...b,children:n}):c.jsx(i,{ref:y,className:R("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",l?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,...b,children:n}),c.jsx(Aw,{containerRef:y,minThumbSize:s,hideDelayMs:o,className:a,disableHorizontal:l,observeMutations:d,userIntentOnly:x})]})});Xn.displayName="ScrollableOverlay";const k2="mobile-overlay-root",M2=16,I2=200,ET=()=>{if(typeof document>"u")return null;let e=document.getElementById(k2);return e||(e=document.createElement("div"),e.id=k2,document.body.appendChild(e)),e},Ma=({open:e,title:t,onClose:n,children:r,footer:s,className:o,contentMaxHeightClassName:i,renderHeader:a})=>{const l=p.useRef(null),[d,f]=p.useState(!1),[u,h]=p.useState(!1);if(typeof document<"u"&&!l.current&&(l.current=ET()),p.useEffect(()=>{if(!e){f(!1),h(!1);return}const x=window.setTimeout(()=>f(!0),M2),b=window.setTimeout(()=>h(!0),M2+I2+50);return()=>{window.clearTimeout(x),window.clearTimeout(b)}},[e]),p.useLayoutEffect(()=>{if(e)return window.dispatchEvent(new Event("oc:mobile-overlay-opened")),()=>{window.dispatchEvent(new Event("oc:mobile-overlay-closed"))}},[e]),p.useEffect(()=>{if(!e)return;const x=document.body.style.overflow;document.body.style.overflow="hidden";const b=S=>{S.key==="Escape"&&n()};return document.addEventListener("keydown",b),()=>{document.body.style.overflow=x,document.removeEventListener("keydown",b)}},[e,n]),!e||!l.current)return null;const m=i??"max-h-[min(70vh,520px)]",g=c.jsx("div",{className:R("oc-keyboard-inset-surface fixed inset-0 z-[60] flex flex-col bg-[rgb(0_0_0_/_0.45)] transition-opacity duration-200 ease-out",!u&&"oc-keyboard-inset-snap",d?"opacity-100":"opacity-0"),role:"dialog","aria-modal":"true",onClick:n,style:{paddingLeft:"var(--oc-chat-inset-left, 0px)",paddingRight:"var(--oc-chat-inset-right, 0px)"},children:c.jsxs("div",{className:R("mt-auto flex max-h-[calc(100dvh-0.75rem)] min-h-0 w-full flex-col rounded-t-xl border-x border-t border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",o),style:{transform:d?"none":"translateY(100%)",transition:`transform ${I2}ms cubic-bezier(0.32, 0.72, 0, 1)`},onClick:x=>x.stopPropagation(),children:[(()=>{const x=c.jsx("button",{type:"button",onClick:n,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-interactive-hover",children:c.jsx($,{name:"close",className:"h-4 w-4"})});return a?a(x):c.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[c.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:t}),x]})})(),c.jsx(Xn,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:R("min-h-0 flex-1",m),className:"px-2 py-2 pwa-overlay-scroll",children:r}),s?c.jsx("div",{className:"shrink-0 border-t border-border/40 px-3 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:s}):null]})});return pa.createPortal(g,l.current)},jT="Awaiting first prompt";function Nw(e,t="Untitled Session"){const n=e?.title?.trim();return n||(e?.messageCount===0?jT:t)}const _f=new Set,Tf=new Set,Af=new Set,Nf=new Set,hu={onDeleteRequest(e){return _f.add(e),()=>{_f.delete(e)}},requestDelete(e){e.sessions.length&&_f.forEach(t=>t(e))},onCreateRequest(e){return Tf.add(e),()=>{Tf.delete(e)}},requestCreate(e){const t=e??{};Tf.forEach(n=>n(t))},onDirectoryRequest(e){return Af.add(e),()=>{Af.delete(e)}},requestDirectoryDialog(){Af.forEach(e=>e())},onGitRefreshHint(e){return Nf.add(e),()=>{Nf.delete(e)}},requestGitRefresh(e){e.directory.trim()&&Nf.forEach(t=>t(e))}},Ra=p.createContext(null),_T=40,E2=20*1024*1024;function TT(e){const t=new Map;let n=0,r=0,s=!0,o=Promise.resolve();const i=(y,v)=>JSON.stringify([v?.directory??"",y]),a=y=>new TextEncoder().encode(y).byteLength,l=y=>{const v=t.get(y);v&&(n=Math.max(0,n-v.bytes)),t.delete(y)},d=y=>{const v=y.endsWith("/")?y:`${y}/`;for(const[C,w]of t)(w.sourcePath===y||w.sourcePath.startsWith(v))&&l(C)},f=(y,v)=>v.isFile&&v.mtimeMs!==void 0&&y.mtimeMs===v.mtimeMs&&y.size===v.size,u=()=>{t.clear(),n=0},h=(y,v,C,w)=>{if(!s||!w.isFile||w.mtimeMs===void 0)return C;const M=a(C.content);if(M>E2)return C;for(l(y),t.set(y,{...C,sourcePath:v,size:w.size,mtimeMs:w.mtimeMs,bytes:M}),n+=M;t.size>_T||n>E2;){const j=t.keys().next().value;if(!j)break;l(j)}return C},m=async(y,v,C,w)=>{const M=await e.statFile?.(v,C).catch(()=>null),j=await e.readFile(v,C),T=await e.statFile?.(v,C).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return w!==r?g(v,C):M&&T&&M.isFile&&T.isFile&&M.mtimeMs!==void 0&&T.mtimeMs!==void 0&&M.size===T.size&&M.mtimeMs===T.mtimeMs?h(y,v,j,T):j},g=e.readFile?async(y,v)=>{if(await o,!s)throw new Error("File cache owner disposed");const C=r;if(v?.allowOutsideWorkspace)return e.readFile(y,v);const w=i(y,v),M=t.get(w);if(!M)return m(w,y,v,C);const j=await e.statFile?.(y,v).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return C!==r?g(y,v):!j||!f(M,j)?(l(w),m(w,y,v,C)):(t.delete(w),t.set(w,M),{content:M.content,path:M.path,revision:M.revision})}:void 0,x=async(y,v)=>{const C=o;let w;o=new Promise(M=>{w=M}),await C,r+=1,y.forEach(d);try{return await v()}finally{y.forEach(d),r+=1,w()}},b={...e,readFile:g,writeFile:e.writeFile?(y,v,C)=>x([y],()=>e.writeFile(y,v,C)):void 0,delete:e.delete?y=>x([y],()=>e.delete(y)):void 0,rename:e.rename?(y,v)=>x([y,v],()=>e.rename(y,v)):void 0},S=l5(y=>{y.runtimeKey!==y.previousRuntimeKey&&(r+=1,u())});return{files:b,dispose:()=>{s=!1,r+=1,u(),S()}}}function pX({apis:e,children:t}){const[n,r]=p.useState(null);p.useEffect(()=>{const i=TT(e.files);return r(i),()=>{i.dispose(),r(a=>a===i?null:a)}},[e.files]);const s=n?.files??e.files,o=p.useMemo(()=>({...e,files:s}),[e,s]);return c.jsx(Ra.Provider,{value:o,children:t})}const AT=600,NT=1600,j2=10,Lw=H.createContext(null);class Rw extends H.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function LT({delayDuration:e=0,skipDelayDuration:t,delay:n,closeDelay:r,...s}){return c.jsx(IC,{delay:n??e,closeDelay:r??t,...s})}function yt({delayDuration:e,open:t,onOpenChange:n,...r}){const[s,o]=H.useState(!1),i=H.useRef(null),a=H.useRef(null),l=H.useRef(null),d=H.useRef(!1),f=t!==void 0,u=f?t:s,h=H.useCallback(()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),m=H.useCallback(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[]),g=H.useCallback(y=>{f||o(y)},[f]),x=H.useMemo(()=>({handlePointerDown:y=>{y.pointerType!=="touch"&&y.pointerType!=="pen"||(h(),m(),l.current={x:y.clientX,y:y.clientY},i.current=window.setTimeout(()=>{f||(d.current=!0,g(!0))},AT))},handlePointerMove:y=>{const v=l.current;if(!v)return;const C=Math.abs(y.clientX-v.x),w=Math.abs(y.clientY-v.y);(C>j2||w>j2)&&(h(),l.current=null)},handlePointerEnd:()=>{h(),l.current=null,d.current&&(m(),a.current=window.setTimeout(()=>{d.current=!1,g(!1)},NT))},handleClickCapture:y=>{d.current&&(d.current=!1,y.preventDefault(),y.stopPropagation())},handleContextMenu:y=>{d.current&&y.preventDefault()}}),[m,h,f,g]);H.useEffect(()=>()=>{h(),m()},[m,h]);const b=H.useCallback((y,v)=>{f||o(y),n?.(y,v)},[f,n]),S=c.jsx(Lw.Provider,{value:x,children:c.jsx(EC,{open:u,onOpenChange:b,...r})});return e===void 0?S:c.jsx(LT,{delayDuration:e,children:S})}function vt({asChild:e,children:t,onPointerDown:n,onPointerMove:r,onPointerUp:s,onPointerCancel:o,onClickCapture:i,onContextMenu:a,...l}){const d=H.useContext(Lw),f=e&&H.isValidElement(t)?{render:t}:{children:t};return c.jsx(Rw,{fallback:t,children:c.jsx(jC,{"data-slot":"tooltip-trigger",onPointerDown:u=>{n?.(u),d?.handlePointerDown(u)},onPointerMove:u=>{r?.(u),d?.handlePointerMove(u)},onPointerUp:u=>{s?.(u),d?.handlePointerEnd()},onPointerCancel:u=>{o?.(u),d?.handlePointerEnd()},onClickCapture:u=>{d?.handleClickCapture(u),!u.defaultPrevented&&i?.(u)},onContextMenu:u=>{d?.handleContextMenu(u),!u.defaultPrevented&&a?.(u)},...l,...f})})}function xt({className:e,sideOffset:t=0,side:n,align:r,children:s,style:o,...i}){return c.jsx(Rw,{children:c.jsx(_C,{children:c.jsx(TC,{sideOffset:t,side:n,align:r,className:"z-50",children:c.jsxs(AC,{"data-slot":"tooltip-content",className:R("oc-glass-tooltip text-[var(--surface-elevated-foreground)] border border-border/60 transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 data-[instant]:transition-none data-[instant]:duration-0 z-50 w-fit origin-[var(--transform-origin)] rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden",e),style:{...o},...i,children:[s,c.jsx(NC,{className:"fill-[var(--surface-elevated)] z-50 size-2"})]})})})})}const RT="inset 0 1px 0 0 rgba(255,255,255,0.12), inset 0 0 0 1px rgba(255,255,255,0.08), 0 0 0 1px rgba(0,0,0,0.36), 0 1px 1px -0.5px rgba(0,0,0,0.22), 0 3px 3px -1.5px rgba(0,0,0,0.20), 0 6px 6px -3px rgba(0,0,0,0.16)",PT="inset 0 1px 0 0 rgba(255,255,255,0.8), inset 0 0 0 1px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.10), 0 1px 2px -0.5px rgba(0,0,0,0.08), 0 4px 8px -2px rgba(0,0,0,0.08), 0 12px 20px -4px rgba(0,0,0,0.08)";function DT(){const e=()=>typeof document<"u"&&document.documentElement.classList.contains("dark"),[t,n]=H.useState(e);return H.useEffect(()=>{const r=()=>n(e()),s=new MutationObserver(r);return s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r(),()=>s.disconnect()},[]),t}function OT(e){H.useEffect(()=>{if(typeof document>"u")return;const t=s=>{s.style.setProperty("box-shadow",e,"important"),s.style.setProperty("outline","none","important"),s.getAttribute("tabindex")==="0"&&s.setAttribute("tabindex","-1")},n=()=>{document.querySelectorAll("[data-sonner-toast]").forEach(t)};n();const r=new MutationObserver(s=>{for(const o of s)o.addedNodes.forEach(i=>{i instanceof HTMLElement&&(i.matches?.("[data-sonner-toast]")&&t(i),i.querySelectorAll?.("[data-sonner-toast]").forEach(t))});n()});return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","tabindex","data-expanded","data-swiping"]}),()=>r.disconnect()},[e])}const mX=({...e})=>{const t=DT();return OT(t?RT:PT),c.jsx(LC,{theme:t?"dark":"light",className:"toaster group",closeButton:!1,toastOptions:{classNames:{toast:"group/toast toast !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground [&_[data-cancel]+[data-button]]:!ml-2",title:"typography-ui-label !font-medium !text-foreground",description:"typography-meta !text-muted-foreground !mt-0.5",actionButton:"!rounded-[var(--radius-md)] !bg-[var(--primary-base)] !text-[var(--primary-foreground)] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity",cancelButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)] !px-2 !py-1 typography-meta !font-medium transition-colors",closeButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)]",icon:"!text-muted-foreground",success:"[&_[data-icon]]:!text-[var(--status-success)]",error:"[&_[data-icon]]:!text-[var(--status-error)]",warning:"[&_[data-icon]]:!text-[var(--status-warning)]",info:"[&_[data-icon]]:!text-[var(--status-info)]"},style:{borderRadius:"var(--radius-xl)",backgroundColor:"var(--surface-elevated)"}},style:{"--normal-bg":"var(--surface-elevated)","--normal-text":"var(--foreground)","--normal-border":"transparent","--error-bg":"var(--surface-elevated)","--error-text":"var(--foreground)","--error-border":"transparent","--success-bg":"var(--surface-elevated)","--success-text":"var(--foreground)","--success-border":"transparent","--warning-bg":"var(--surface-elevated)","--warning-text":"var(--foreground)","--warning-border":"transparent","--info-bg":"var(--surface-elevated)","--info-text":"var(--foreground)","--info-border":"transparent"},...e})},$t=e=>Math.round(e*100)/100,is=e=>{if(!e)return null;const t=e.getBoundingClientRect();return{top:$t(t.top),right:$t(t.right),bottom:$t(t.bottom),left:$t(t.left),width:$t(t.width),height:$t(t.height)}},En=e=>{const t=Number.parseFloat(e);return Number.isFinite(t)?$t(t):null};function HT(){if(typeof window>"u"||typeof document>"u"||!document.body)return null;const e=document.documentElement,t=document.querySelector(".oc-mobile-composer"),n=document.querySelector(".oc-mobile-app-shell"),r=t?.querySelector("[data-composer-card]")??null,s=t?.querySelector("[data-chat-input-footer]")??null,o=t?window.getComputedStyle(t):null,i=is(n),a=is(t),l=is(r),d=window.visualViewport,f=window.getComputedStyle(document.body,"::after"),u=document.createElement("div");u.setAttribute("aria-hidden","true"),u.style.cssText="position:fixed;top:0;left:0;visibility:hidden;pointer-events:none;contain:strict;box-sizing:content-box;width:0;height:0;width:100dvh;height:100lvh;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)",document.body.appendChild(u);let h;try{const m=window.getComputedStyle(u);h={safeTop:En(m.paddingTop),safeBottom:En(m.paddingBottom),dynamicHeight:window.CSS.supports("height","100dvh")?En(m.width):null,largeHeight:window.CSS.supports("height","100lvh")?En(m.height):null}}finally{u.remove()}return{capturedAt:Date.now(),devicePixelRatio:window.devicePixelRatio,screen:{width:window.screen.width,height:window.screen.height,availableHeight:window.screen.availHeight},window:{width:window.innerWidth,height:window.innerHeight,scrollY:$t(window.scrollY)},client:{width:e.clientWidth,height:e.clientHeight},visual:d?{width:$t(d.width),height:$t(d.height),offsetTop:$t(d.offsetTop),offsetLeft:$t(d.offsetLeft),scale:$t(d.scale)}:null,css:{...h,viewportBottomStrip:En(window.getComputedStyle(e).getPropertyValue("--oc-viewport-bottom-strip"))},flags:{standalone:window.matchMedia("(display-mode: standalone)").matches,capacitor:e.classList.contains("oc-capacitor-app"),browserKeyboardOpen:e.classList.contains("oc-browser-keyboard-open"),browserFullscreen:e.classList.contains("oc-browser-kb-fullscreen")},root:is(e),body:is(document.body),appRoot:is(document.getElementById("root")),shell:i,composer:a,card:l,footer:is(s),composerStyle:o?{paddingTop:En(o.paddingTop),paddingBottom:En(o.paddingBottom),marginBottom:En(o.marginBottom),position:o.position}:null,bottomOverlay:{present:f.content!=="none"&&f.content!=="normal",height:En(f.height),bottom:En(f.bottom),position:f.position,zIndex:En(f.zIndex)},gaps:{cardToShellBottom:l&&i?$t(i.bottom-l.bottom):null,shellToClientBottom:i?$t(e.clientHeight-i.bottom):null,composerToVisualBottom:a&&d?$t(d.offsetTop+d.height-a.bottom):null}}}const FT="pichamber_session_load_perf",dp=1e3,BT=new Set(["bootstrap.directory","bootstrap.sessions.all","bootstrap.sessions.archived","bootstrap.sessions.roots","global-sessions.active","global-sessions.archived","session-messages.initial","session-messages.older","session-messages.page","session-messages.refresh","session-messages.visible","session-prefetch"]),VT=new Set(["action-demand","current-directory","initial","initial-page","known-project","known-worktree","older","pagination","prefetch","project-expanded","refresh","selected-session","server-connected","worktree-expanded"]),$T=new Set(["complete","error","stale","deduplicated","canceled"]),Pw=()=>{if(Wo())return!0;if(typeof window>"u")return!1;try{return window.localStorage.getItem(FT)==="1"}catch{return!1}};function zT(){return typeof window>"u"?0:window.__pichamberSessionLoadPerformance?.events.length??0}function UT(){typeof window>"u"||window.__pichamberSessionLoadPerformance&&(window.__pichamberSessionLoadPerformance.events=[])}const _2=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),qT=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,Lf=e=>Number.isInteger(e)&&Number(e)>=0?Number(e):void 0;function WT(e){if(!Pw()||!BT.has(e.operation)||e.caller!==void 0&&!VT.has(e.caller))return()=>{};const t=_2();return(n,r)=>{if(typeof window>"u"||!$T.has(n))return;const s=window.__pichamberSessionLoadPerformance??{events:[]},o=qT(e.queuedMs),i=Lf(e.requestLimit),a=Lf(r?.retryCount??e.retryCount),l=Lf(r?.recordCount??e.recordCount);s.events.push({operation:e.operation,...e.caller!==void 0?{caller:e.caller}:{},...o!==void 0?{queuedMs:o}:{},...i!==void 0?{requestLimit:i}:{},...typeof e.cursorPresent=="boolean"?{cursorPresent:e.cursorPresent}:{},outcome:n,durationMs:Math.max(0,_2()-t),...a!==void 0?{retryCount:a}:{},...l!==void 0?{recordCount:l}:{},at:Date.now()}),s.events.length>dp&&s.events.splice(0,s.events.length-dp),window.__pichamberSessionLoadPerformance=s}}const T2="pichamber.chat.first_message_visible";function KT(e){const t=e?.enabled??Pw,n=e?.requestFrame??(l=>window.requestAnimationFrame(l)),r=e?.cancelFrame??(l=>window.cancelAnimationFrame(l)),s=e?.markVisible??(()=>{performance.mark(T2),performance.clearMarks(T2)}),o=e?.startEvent??WT,i=new Set;let a=null;return{schedule(l,d){if(!t()||i.has(l))return()=>{};a&&(r(a.frame),a=null);const f=o({operation:"session-messages.visible",caller:"selected-session",recordCount:d}),u=n(()=>{a?.key!==l||a.frame!==u||(a=null,i.add(l),i.size>dp&&i.delete(i.values().next().value),s(),f("complete"))});return a={key:l,frame:u},()=>{a?.key!==l||a.frame!==u||(r(u),a=null)}}}}const GT=1e3,ZT=6,YT=16.7,XT=50,JT=(e,t)=>{if(e.length===0)return 0;const n=e.slice().sort((s,o)=>s-o),r=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[r]??0},QT=(e=GT)=>{const t=[],n=[];let r=0,s=!1;const o=i=>{const a=i-e;for(;t.length>0&&(t[0]??0)<a;)t.shift(),n.shift()};return{reset(){t.length=0,n.length=0,r=0,s=!1},sample(i){s&&(t.push(i),n.push(i-r),o(i)),r=i,s=!0},snapshot(){if(n.length===0||t.length<1)return{fps:0,lastMs:0,p95Ms:0,samples:0};const i=(t[t.length-1]??0)-(t[0]??0);return{fps:i>0?1e3*(t.length-1)/i:0,lastMs:n[n.length-1]??0,p95Ms:JT(n,95),samples:n.length}}}},A2=(e,t=ZT)=>e.filter(n=>n.value>0&&Number.isFinite(n.value)).sort((n,r)=>r.value-n.value||n.metric.localeCompare(r.metric)).slice(0,t).map(n=>({metric:n.metric,value:n.value})),yi=(e,t=1)=>Number.isFinite(e)?e.toFixed(t):"—",eA=e=>typeof e!="number"||!Number.isFinite(e)||e<0?null:e/(1024*1024),tA=250,nA=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),rA=()=>{if(typeof performance>"u")return null;const e=performance.memory?.usedJSHeapSize;return typeof e=="number"&&Number.isFinite(e)?e:null},sA=e=>{if(typeof PerformanceObserver>"u")return()=>{};try{const t=new PerformanceObserver(n=>{for(const r of n.getEntries())typeof r.duration=="number"&&r.duration>0&&e(r.duration)});return t.observe({type:"longtask",buffered:!0}),()=>t.disconnect()}catch{return()=>{}}},oA=(e,t={})=>{const n=(t.getStreamSnapshot??MS)(),r=(t.getSyncSnapshot??Lb)(),s=(t.getSessionLoadEventCount??zT)(),o=A2(n.entries.map(a=>({metric:a.metric,value:a.count}))),i=A2(Object.entries(r??{}).map(([a,l])=>({metric:`sync.${a}`,value:typeof l=="number"?l:0})));return{...e,capturedAt:Date.now(),stream:o,sync:i,sessionLoadEvents:s}},iA=(e,t={})=>{const n=t.now??nA,r=t.requestFrame??(S=>window.requestAnimationFrame(S)),s=t.cancelFrame??(S=>window.cancelAnimationFrame(S)),o=t.observeLongTasks??sA,i=t.readHeapUsedBytes??rA,a=QT();let l=0,d=0,f=0,u=0,h=0,m=!1;const g=o(S=>{l+=1,d=S,f+=S}),x=S=>{const y=a.snapshot();e(oA({fps:y.fps,frameMs:{last:y.lastMs,p95:y.p95Ms},longTasks:{count:l,lastMs:d,totalMs:f},heapUsedMb:eA(i())},t)),u=S},b=S=>{if(m)return;const y=typeof S=="number"&&Number.isFinite(S)?S:n();a.sample(y),(u===0||y-u>=tA)&&x(y),h=r(b)};return h=r(b),{stop(){m=!0,s(h),g(),a.reset()},reset(){a.reset(),l=0,d=0,f=0,aA(),x(n())}}},aA=()=>{kS(),Nb(),UT()},cA=()=>({capturedAt:0,fps:0,frameMs:{last:0,p95:0},longTasks:{count:0,lastMs:0,totalMs:0},heapUsedMb:null,stream:[],sync:[],sessionLoadEvents:0});let up=cA();const lA=()=>p.useSyncExternalStore(ES,Wo,()=>!1),dA=e=>e>=XT?"var(--status-error)":e>=YT?"var(--status-warning)":"var(--surface-foreground)",Zs=(e,t)=>{e&&e.textContent!==t&&(e.textContent=t)},uA=e=>{const t=[...e.stream.map(n=>`${n.metric} ${n.value}`),...e.sync.map(n=>`${n.metric} ${n.value}`)];return e.sessionLoadEvents>0&&t.push(`session-load.events ${e.sessionLoadEvents}`),t.length>0?t.join(`
43
+ `):"no counters yet"},Bc=8,Rf=(e,t,n,r)=>{if(typeof window>"u")return{left:e,top:t};const s=window.visualViewport,o=s?.offsetLeft??0,i=s?.offsetTop??0,a=s?.width||window.innerWidth,l=s?.height||window.innerHeight,d=o+Bc,f=i+Bc,u=Math.max(d,o+a-n-Bc),h=Math.max(f,i+l-r-Bc);return{left:Math.round(Math.min(Math.max(e,d),u)),top:Math.round(Math.min(Math.max(t,f),h))}},N2=(e,t)=>{e.style.left=`${t.left}px`,e.style.top=`${t.top}px`,e.style.right="auto",e.style.transform="none"},fA=()=>{const[e,t]=p.useState(!1),[n,r]=p.useState(null),[s,o]=p.useState(!1),[i,a]=p.useState(null),[l,d]=p.useState(null),f=p.useRef(null),u=p.useRef(null),h=p.useRef(null),m=p.useRef(null),g=p.useRef(null),x=p.useRef(null),b=p.useRef(null),S=p.useRef(null),y=p.useRef(up),v=p.useRef(null),C=p.useCallback(k=>{const E=f.current;if(!E||u.current)return;const I=E.getBoundingClientRect(),N=Rf(k.left,k.top,I.width,I.height);N.left===k.left&&N.top===k.top||(N2(E,N),r(N))},[]);p.useLayoutEffect(()=>{n&&C(n)},[l,e,C,i,n]),p.useEffect(()=>{if(!n||typeof window>"u")return;const k=()=>{C(n)},E=window.visualViewport;return window.addEventListener("resize",k),E?.addEventListener("resize",k),()=>{window.removeEventListener("resize",k),E?.removeEventListener("resize",k)}},[C,n]);const w=p.useCallback(k=>{if(k.button!==0||u.current)return;const E=f.current;if(!E)return;const I=E.getBoundingClientRect();u.current={pointerId:k.pointerId,offsetX:k.clientX-I.left,offsetY:k.clientY-I.top,originLeft:I.left,originTop:I.top,left:I.left,top:I.top,width:I.width,height:I.height};try{k.currentTarget.setPointerCapture(k.pointerId)}catch{}o(!0),k.preventDefault()},[]),M=p.useCallback(k=>{const E=u.current;if(!E||E.pointerId!==k.pointerId)return;const I=Rf(k.clientX-E.offsetX,k.clientY-E.offsetY,E.width,E.height);I.left===E.left&&I.top===E.top||(E.left=I.left,E.top=I.top,f.current?.style.setProperty("transform",`translate3d(${I.left-E.originLeft}px, ${I.top-E.originTop}px, 0)`),k.cancelable&&k.preventDefault())},[]),j=p.useCallback((k,E)=>{const I=u.current;if(!I||I.pointerId!==k.pointerId)return;const N=f.current,O=N?.getBoundingClientRect(),L=E?{left:I.originLeft,top:I.originTop}:Rf(k.clientX-I.offsetX,k.clientY-I.offsetY,O?.width??I.width,O?.height??I.height);u.current=null,N&&(E?N.style.transform="none":N2(N,L)),o(!1),E||r(L);try{k.currentTarget.hasPointerCapture(k.pointerId)&&k.currentTarget.releasePointerCapture(k.pointerId)}catch{}},[]);p.useEffect(()=>()=>{u.current=null},[]),p.useEffect(()=>{const E=iA(I=>{up=I,y.current=I,Zs(h.current,yi(I.fps,0)),Zs(m.current,`${yi(I.frameMs.last)}ms`),Zs(g.current,`${yi(I.frameMs.p95)}ms`),g.current&&(g.current.style.color=dA(I.frameMs.p95)),Zs(x.current,`${I.longTasks.count} / ${yi(I.longTasks.lastMs,0)}ms`),Zs(b.current,I.heapUsedMb==null?"—":`${yi(I.heapUsedMb,0)}MB`),Zs(S.current,uA(I))});return v.current=E,()=>{E.stop(),v.current=null}},[]);const T=p.useCallback(()=>{try{const k=HT();return a(k),d(k?null:"Layout measurements unavailable."),k}catch{return a(null),d("Layout measurement failed."),null}},[]),A=p.useCallback(()=>{const k=T();gr(`${JSON.stringify({...y.current,layout:k},null,2)}
44
+ `).then(E=>{if(!E.ok){t(!1),d("Copy failed. Use the displayed measurements if available.");return}d(k?"Snapshot copied.":"Performance snapshot copied. Layout measurements unavailable.")}).catch(()=>{t(!1),d("Copy failed. Use the displayed measurements if available.")})},[T]),_=p.useCallback(()=>{v.current?.reset()},[]);return c.jsxs("aside",{ref:f,role:"complementary","aria-label":"Performance overlay",className:"pointer-events-auto fixed z-[300] w-[18.5rem] max-w-[calc(100vw-1.5rem)] rounded-lg border border-border bg-[var(--surface-elevated)] text-foreground [contain:layout_style]",style:{...n?{left:`${n.left}px`,top:`${n.top}px`,right:"auto"}:{top:"calc(0.5rem + env(safe-area-inset-top, 0px))",right:"calc(0.5rem + env(safe-area-inset-right, 0px))"},transform:"none"},children:[c.jsxs("div",{className:"flex items-center gap-1 px-2 py-1",children:[c.jsxs("div",{className:R("flex min-w-0 flex-1 cursor-grab touch-none select-none items-center gap-1",s?"cursor-grabbing":"active:cursor-grabbing"),title:"Drag to move performance overlay",onPointerDown:w,onPointerMove:M,onPointerUp:k=>j(k,!1),onPointerCancel:k=>j(k,!0),onLostPointerCapture:k=>j(k,!0),children:[c.jsx($,{name:"draggable",className:"size-3.5 text-muted-foreground"}),c.jsx("p",{className:"min-w-0 flex-1 typography-micro font-medium",children:"Performance"})]}),c.jsx(Se,{variant:"ghost",size:"xs","aria-label":"Copy performance and layout snapshot",onPointerDown:k=>k.preventDefault(),onClick:A,children:c.jsx($,{name:"file-copy",className:"size-3.5"})}),c.jsx(Se,{variant:"ghost",size:"xs","aria-label":"Reset performance counters",onClick:_,children:c.jsx($,{name:"refresh",className:"size-3.5"})}),c.jsx(Se,{variant:"ghost",size:"xs","aria-label":e?"Expand performance overlay":"Collapse performance overlay","aria-expanded":!e,onClick:()=>t(k=>!k),children:c.jsx($,{name:e?"arrow-down-s":"arrow-up-s",className:"size-3.5"})}),c.jsx(Se,{variant:"ghost",size:"xs","aria-label":"Turn off performance overlay",onClick:()=>$l(!1),children:c.jsx($,{name:"close",className:"size-3.5"})})]}),c.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 px-2 pb-2 font-mono typography-micro tabular-nums text-muted-foreground",children:[c.jsx("span",{children:"FPS"}),c.jsx("span",{ref:h,className:"text-right text-foreground",children:"0"}),c.jsx("span",{children:"Frame"}),c.jsx("span",{ref:m,className:"text-right text-foreground",children:"0.0ms"}),c.jsx("span",{children:"p95"}),c.jsx("span",{ref:g,className:"text-right",children:"0.0ms"}),c.jsx("span",{children:"Long"}),c.jsx("span",{ref:x,className:"text-right text-foreground",children:"0 / 0ms"}),c.jsx("span",{children:"Heap"}),c.jsx("span",{ref:b,className:"text-right text-foreground",children:"—"})]}),e?null:c.jsx("pre",{ref:S,className:"max-h-40 overflow-auto border-t border-border px-2 py-1.5 font-mono typography-micro text-muted-foreground whitespace-pre-wrap",children:"no counters yet"}),e?null:c.jsxs("div",{className:"border-t border-border px-2 py-1.5",children:[c.jsx(Se,{variant:"ghost",size:"xs",onPointerDown:k=>k.preventDefault(),onClick:T,children:"Measure layout"}),l?c.jsx("p",{role:"status",className:"typography-micro text-muted-foreground",children:l}):null,i?c.jsx("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap font-mono typography-micro text-muted-foreground",children:JSON.stringify(i,null,2)}):null]})]})},gX=()=>{const e=lA();return p.useLayoutEffect(()=>{IS()},[]),p.useEffect(()=>{if(!(typeof window>"u"))return window.__pichamberPerfHud={setEnabled:$l,isEnabled:Wo,getSnapshot:()=>up},()=>{delete window.__pichamberPerfHud}},[]),!e||typeof document>"u"||!document.body?null:pa.createPortal(c.jsx(fA,{}),document.body)},Wm=48,hA=e=>e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,Wm).replace(/-$/g,""),pA=e=>{const t=e.trim();return t.length===0||t.length>Wm?null:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)?t:null},L2=e=>{const t=hA(e.trim());return t&&t.split("-").filter(Boolean).slice(0,7).join("-").slice(0,Wm).replace(/-$/g,"")||null},mA=async(e,t)=>{const n=e.trim();if(!n||!t)return L2(n);try{const r=await Nt("/api/pi/small-model/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:n,directory:t})});if(r.ok){const s=await r.json().catch(()=>null);if(typeof s?.text=="string"){const o=pA(s.text);if(o)return o}}}catch{}return L2(n)},gA=500,Il="Worktree creation superseded.",fp=e=>{const t=de(e.projectRoot)??e.projectRoot,n=de(e.sourceDirectory)??e.sourceDirectory;return JSON.stringify([e.runtimeKey,t,n,e.startRef])},Dw=e=>e?fp(e):null,yA=e=>new Promise(t=>{setTimeout(t,e)}),vA=(e,t)=>!!(e&&t&&e.runtimeKey===t.runtimeKey&&de(e.projectRoot)===de(t.projectRoot)&&de(e.sourceDirectory)===de(t.sourceDirectory)&&e.startRef===t.startRef),xA=(e,t)=>({...e,path:t.path,branch:t.branch}),kr=new Map,vi=new Map,bA=e=>({prompt:e.prompt,confirmedMentions:Array.from(new Set(Array.isArray(e.confirmedMentions)?e.confirmedMentions:[...e.confirmedMentions])),attachments:e.attachments.map(qd)}),xi=(e,t,n)=>{e(r=>{const s=r.entries.get(t),o=n(s,Date.now());if(!o&&!s)return r;const i=new Map(r.entries);return o?i.set(t,o):i.delete(t),{entries:i}})},ln=Lt()((e,t)=>{const n=(a,l,d)=>{xi(e,a,(f,u)=>f?{...f,state:d,failedSend:null,updatedAt:u}:{key:a,intent:l,state:d,receipt:null,failedSend:null,notificationSent:!1,startedAt:u,updatedAt:u})},r=(a,l,d,f)=>{xi(e,a,(u,h)=>({key:a,intent:l,state:d,receipt:null,failedSend:f,notificationSent:u?.notificationSent??!1,path:u?.path??null,branch:u?.branch??null,startedAt:u?.startedAt??h,updatedAt:h}))},s=(a,l,d,f,u,h)=>{xi(e,a,(m,g)=>({key:a,intent:l,state:null,receipt:d,failedSend:f,notificationSent:m?.notificationSent??!1,path:u??d.path,branch:h??d.branch,startedAt:m?.startedAt??g,updatedAt:g}))},o=(a,l,d)=>{xi(e,a,(f,u)=>f?{...f,path:l,branch:d,updatedAt:u}:null)},i=async a=>{const{intent:l,prompt:d,git:f,refreshProject:u}=a,h=a.failedSend?bA(a.failedSend):null,m=a.pollIntervalMs??gA,g=a.taskId??fp(l),x=(kr.get(g)??0)+1;kr.set(g,x);const b=()=>kr.get(g)!==x||l.runtimeKey!==Y(),S=()=>{!f||l.runtimeKey!==Y()||u(l.projectRoot,f,{force:!0}).catch(()=>{})};if(n(g,l,{phase:"naming",label:"Naming worktree..."}),!f?.createGitWorktree||!f.getGitWorktreeBootstrapStatus){const y="Git worktrees are unavailable for this runtime.";throw r(g,l,{phase:"failed",label:"Worktree creation failed",error:y},h),new Error(y)}if(l.runtimeKey!==Y()){const y="The runtime changed. Select New worktree again.";throw r(g,l,{phase:"failed",label:"Worktree creation stopped",error:y},h),new Error(y)}try{const y=await mA(d,l.sourceDirectory);if(b())throw new Error(Il);const v={mode:"new",startRef:l.startRef,...y?{worktreeName:y}:{},returnAfterDirectoryCreated:!0};if(f.validateGitWorktree){const j=await f.validateGitWorktree(l.sourceDirectory,v);if(!j.ok)throw new Error(j.errors.map(T=>T.message).filter(Boolean).join(`
45
+ `)||"The worktree request is invalid.")}if(b())throw new Error(Il);n(g,l,{phase:"creating",label:"Creating worktree..."});const C=await f.createGitWorktree(l.sourceDirectory,v),w=xA(l,C);if(b())return w;o(g,C.path,C.branch);let M=C.bootstrapStatus;for(;M.status==="pending";){if(b()||(n(g,l,M.phase==="directory-created"?{phase:"checking-out",label:"Checking out files..."}:{phase:"setting-up",label:"Setting up project..."}),await yA(m),b()))return w;M=await f.getGitWorktreeBootstrapStatus(C.path)}if(M.status==="failed"||M.phase!=="setup-ready")throw new Error(M.error||"Worktree setup failed.");try{await u(l.projectRoot,f,{force:!0})}catch{}return b()||s(g,l,w,h,C.path,C.branch),w}catch(y){if(b())throw y;const v=y instanceof Error?y.message:"Failed to create the worktree.";throw v===Il||(S(),r(g,l,{phase:"failed",label:"Worktree creation failed",error:v},h)),y}};return{runtimeKey:Y(),entries:new Map,getEntry:a=>{const l=Dw(a);return l?t().entries.get(l)??null:null},getEntryByKey:a=>t().entries.get(a)??null,getActiveEntries:()=>{const a=[];for(const l of t().entries.values())l.state&&l.state.phase!=="failed"&&a.push(l);return a},clearEntry:a=>{e(l=>{if(!l.entries.has(a))return l;const d=new Map(l.entries);return d.delete(a),kr.delete(a),{entries:d}})},consumeFailedSend:(a,l)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||u.state?.phase!=="failed"||u.failedSend!==l)return f;const h=new Map(f.entries);return h.delete(a),kr.delete(a),d=!0,{entries:h}}),d},markWorktreePromptSucceeded:(a,l)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||!u.receipt||u.failedSend!==l)return f;const h=new Map(f.entries);return h.delete(a),kr.delete(a),d=!0,{entries:h}}),d},markWorktreePromptFailed:(a,l,d)=>{let f=!1;return e(u=>{const h=u.entries.get(a);if(!h||!h.receipt||h.failedSend!==l)return u;const m=new Map(u.entries);return m.set(a,{...h,state:{phase:"failed",label:"Prompt failed to send",error:d},updatedAt:Date.now()}),f=!0,{entries:m}}),f},markNotificationSent:a=>{xi(e,a,(l,d)=>!l||l.notificationSent?l??null:{...l,notificationSent:!0,updatedAt:d})},dismissFailed:a=>{e(l=>{if(l.entries.get(a)?.state?.phase!=="failed")return l;const f=new Map(l.entries);return f.delete(a),kr.delete(a),{entries:f}})},resetForRuntimeSwitch:a=>{kr.clear(),vi.clear(),e({runtimeKey:a,entries:new Map})},request:a=>{const l=a.taskId??fp(a.intent),d=vi.get(l);if(d)return d;const f=i(a).finally(()=>{vi.get(l)===f&&vi.delete(l)});return vi.set(l,f),f}}}),Ow=e=>Dw(e),wA=vA,SA=async e=>(await Ob([...e])).map(qd),CA=(e,t)=>e??t,Hw=(e,t)=>(e??t).map(n=>n.id),hp=e=>{const t=Math.max(1,e.currentCount+e.missingCount-e.limit),n=r=>r===1?"file":"files";return{title:"Too many attachments to restore",description:`Remove ${t} ${n(t)} to restore ${e.missingCount} ${n(e.missingCount)}. You can attach up to ${e.limit} files to one message.`}},kA=(e,t)=>e.ok?null:e.reason==="runtime-mismatch"?{title:"The runtime changed",description:"Your failed prompt was kept in Background tasks."}:e.reason==="target-occupied"?{title:"Draft already has content",description:t==="pending-composer"?"Your restored prompt was kept in Background tasks.":"Your failed prompt was kept in Background tasks."}:e.reason==="attachment-limit"?hp(e):(t==="background-task"?e.reason==="missing":e.reason==="dismissed"||e.reason==="navigated-away")?null:{title:"Could not restore the failed prompt",description:"Your prompt was kept in Background tasks."},Fw=()=>{try{const e=pe.getState(),t=e.newSessionDraft?.open?e.newSessionDraft.directoryOverride:null,n=e.currentSessionId,r=n?e.getDirectoryForSession(n)??e.currentSessionDirectory:t??nt.getState().currentDirectory,s=Go(Y(),r,n);return s?Jt(s):null}catch{return null}},yX=e=>{const t=ln.getState(),n=t.getEntryByKey(e),r=n?.failedSend;if(!n||!r)return{ok:!1,reason:"missing"};if(n.intent.runtimeKey!==Y())return{ok:!1,reason:"runtime-mismatch"};const s=Go(Y(),n.intent.sourceDirectory,null);if(!s)return{ok:!1,reason:"invalid-target"};const o=Jt(s);try{const d=Ud(s);if(d.text.trim().length>0&&d.text!==r.prompt)return{ok:!1,reason:"target-occupied"}}catch{return{ok:!1,reason:"invalid-target"}}const i=Fw();if(i!==null&&i===o){try{pe.getState().openNewSessionDraft({directoryOverride:n.intent.sourceDirectory,worktreeIntent:n.intent})}catch{return{ok:!1,reason:"open-failed"}}const d={entryKey:e,prompt:r.prompt,confirmedMentions:[...r.confirmedMentions],targetKey:o,attachments:r.attachments.map(qd),expectedFailedSend:r};try{Ye.getState().requestWorktreeRestore(d)}catch{return{ok:!1,reason:"open-failed"}}return{ok:!0,reason:"pending"}}const l=t.getEntryByKey(e);if(!l||l.failedSend!==r)return{ok:!1,reason:"missing"};try{pe.getState().openNewSessionDraft({directoryOverride:n.intent.sourceDirectory,worktreeIntent:n.intent})}catch{return{ok:!1,reason:"open-failed"}}try{js(s,r.prompt,r.confirmedMentions)}catch{return{ok:!1,reason:"invalid-target"}}try{Ye.getState().activateAttachmentsDraft(o);const d=Ye.getState().restoreAttachmentsForRetry(r.attachments);if(!d.ok)return{ok:!1,reason:"attachment-limit",limit:d.limit,currentCount:d.currentCount,missingCount:d.missingCount}}catch{return{ok:!1,reason:"open-failed"}}try{if(!t.consumeFailedSend(e,r))return{ok:!1,reason:"missing"}}catch{return{ok:!0}}return{ok:!0}},MA=(e,t)=>{const n=ln.getState(),r=n.getEntryByKey(e.entryKey),s=r?.failedSend;if(!r||!s)return{ok:!1,reason:"dismissed"};if(s!==e.expectedFailedSend)return{ok:!1,reason:"dismissed"};if(r.intent.runtimeKey!==Y())return{ok:!1,reason:"runtime-mismatch"};const o=Go(Y(),r.intent.sourceDirectory,null);if(!o)return{ok:!1,reason:"invalid-target"};const i=Jt(o);if(i!==e.targetKey)return{ok:!1,reason:"invalid-target"};const a=Fw();if(a!==null&&a!==i)return{ok:!1,reason:"navigated-away"};const l=t??"";if(l.trim().length>0&&l!==e.prompt)return{ok:!1,reason:"target-occupied"};try{const u=Ud(o);if(u.text.trim().length>0&&u.text!==e.prompt)return{ok:!1,reason:"target-occupied"}}catch{return{ok:!1,reason:"invalid-target"}}const d=de(r.intent.sourceDirectory),f=de(o.directory);if(!d||d!==f)return{ok:!1,reason:"invalid-target"};try{js(o,e.prompt,e.confirmedMentions),Ye.getState().activateAttachmentsDraft(i);const u=Ye.getState().restoreAttachmentsForRetry(e.attachments);if(!u.ok)return{ok:!1,reason:"attachment-limit",limit:u.limit,currentCount:u.currentCount,missingCount:u.missingCount}}catch{return{ok:!1,reason:"open-failed"}}try{if(!n.consumeFailedSend(e.entryKey,s))return{ok:!1,reason:"dismissed"}}catch{return{ok:!0}}return{ok:!0}},vX=e=>!!(e?.receipt&&e?.failedSend&&!e?.state),IA=e=>!!(e?.receipt&&!e?.state&&!e?.failedSend),xX=e=>IA(e),bX=e=>!!(e?.receipt&&!e?.notificationSent&&!e?.state&&!e?.failedSend),EA=(e,t,n)=>{if(!e||!t)return!1;try{return ln.getState().markWorktreePromptFailed(e,t,n)}catch{return!1}},jA=(e,t,n,r)=>{if(!e||!t)return!1;let s=!1;try{s=ln.getState().markWorktreePromptSucceeded(e,t)}catch{return!1}if(!s)return!1;if(!n||n.length===0)return!0;try{const o=Hw(n,r);o.length>0&&Ye.getState().detachAttachedFiles(o)}catch{}return!0},_A=600*1e3,pp="pending-input:",TA=e=>!Number.isFinite(e.ageMs)||Math.max(0,e.ageMs)>_A||e.isCurrent&&e.visible&&e.focused?"none":!e.visible||!e.focused||e.mode==="always"&&!e.isCurrent?"toast-and-notify":"toast",ld=e=>`${pp}${e}`,AA=e=>e==="approval"?"Approval needed":"Input needed",R2=e=>{const t=Ue().getState().catalog.byId.get(e);return t?Nw(Or(t),"Untitled session"):"Untitled session"},NA=(e,t,n)=>{const r=pe.getState().currentSessionId===e,s=typeof document<"u"&&document.visibilityState==="visible";let o=!1;try{o=typeof document<"u"&&document.hasFocus()}catch{o=!1}const i=te.getState().notificationMode,a=Date.now(),l=Ro(t.since,n,a)??t.since;return{isCurrent:r,visible:s,focused:o,mode:i==="always"?"always":"hidden-only",ageMs:a-l}},Bw=(e,t)=>{pe.getState().setCurrentSession(e,t)},P2=(e,t,n,r,s)=>{Ce.warning(AA(n.kind),{id:ld(e),description:r,duration:1/0,onDismiss:s,onAutoClose:s,action:{label:"Open session",onClick:()=>Bw(e,t||null)}})},LA=(e,t)=>{const n=[];for(const[r,s]of e){const o=t(r);o!==s.label&&n.push([r,o])}return n},RA=(e,t,n,r)=>{e.get(n)?.raise===r&&(e.delete(n),t.delete(ld(n)))},PA=(e,t,n)=>{const r=[];for(const s of e){if(t.has(s))continue;const o=n(s);o.exists&&o.pendingInput===null&&r.push(s)}return r},wX=()=>{const e=pe(d=>d.currentSessionId),t=p.useRef(new Map),n=p.useRef(new Set),r=p.useRef(new Map),s=p.useRef(0),o=p.useCallback((d,f)=>{RA(r.current,n.current,d,f)},[]),i=p.useCallback(d=>{const f=ld(d);n.current.delete(f),r.current.delete(d),Ce.dismiss(f);const u=t.current.get(d);if(u!==void 0){t.current.delete(d);const h=$r()?.notifications?.close;h&&h(u).catch(()=>{})}},[]),a=p.useCallback(()=>{for(const f of n.current)Ce.dismiss(f);n.current.clear(),r.current.clear();const d=$r()?.notifications?.close;if(d)for(const f of t.current.values())d(f).catch(()=>{});t.current.clear()},[]);p.useEffect(()=>qI(d=>{if(d.type==="cleared"||!d.pending){i(d.sessionId);return}const f=d.pending,u=TA(NA(d.sessionId,f,d.serverNow));if(u==="none")return;const h=R2(d.sessionId),m=++s.current,g=d.sessionId;if(n.current.add(ld(g)),r.current.set(g,{directory:d.directory,pending:f,label:h,raise:m}),P2(g,d.directory,f,h,()=>o(g,m)),u==="toast-and-notify"){const x=vm(d.sessionId,f.since);t.current.set(d.sessionId,x),Tb({sessionId:d.sessionId,directory:d.directory,since:f.since,kind:f.kind,title:h})}}),[i,o]),p.useEffect(()=>Ue().subscribe(()=>{if(r.current.size!==0)for(const[d,f]of LA(r.current,R2)){const u=r.current.get(d);u&&(r.current.set(d,{...u,label:f}),P2(d,u.directory,u.pending,f,()=>o(d,u.raise)))}},Ct),[o]),p.useEffect(()=>{e&&i(e)},[e,i]);const l=ow();return p.useEffect(()=>{const d=new Set(l.map(m=>m.sessionId)),f=new Set(t.current.keys());for(const m of n.current)m.startsWith(pp)&&f.add(m.slice(pp.length));if(f.size===0)return;const u=Ue().getState().catalog,h=PA([...f],d,m=>{const g=u.byId.get(m);return g?{exists:!0,pendingInput:g.pendingInput}:{exists:!1,pendingInput:void 0}});for(const m of h)i(m)},[l,i]),p.useEffect(()=>en(()=>{a()}),[a]),p.useEffect(()=>()=>{a()},[a]),null},SX=()=>{const t=ow().length,n=te(r=>r.dockBadgeEnabled);return p.useEffect(()=>{const r=wt()&&!n?0:t;try{$r()?.notifications?.setAttentionCount?.(r)}catch{}},[t,n]),p.useEffect(()=>()=>{try{$r()?.notifications?.setAttentionCount?.(0)}catch{}},[]),null},DA=()=>{const e=ze(t=>jm(t.catalog).length,Object.is,"catalog");return e<=0||wt()||lr()?"":`(${e}) `},CX=()=>(p.useEffect(()=>{const e=t=>{const n=t.detail,r=typeof n?.sessionId=="string"?n.sessionId.trim():"";if(!r)return;const s=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():null;Bw(r,s)};return window.addEventListener("pichamber:open-session",e),()=>window.removeEventListener("pichamber:open-session",e)},[]),null),OA="PiChamber",D2=e=>e.replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase()),HA=e=>{const n=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??""},FA=(e,t)=>[e,t,OA].filter(r=>typeof r=="string"&&r.trim().length>0).join(" | "),BA=()=>{const e=pe(l=>l.currentSessionId),t=ze(l=>e?l.reducer.bySession.get(e)?.extensionTitle??null:null,Object.is,e?`session:${e}`:"chrome"),n=at(l=>l.activeProjectId?l.projects.find(d=>d.id===l.activeProjectId)??null:null),r=p.useMemo(()=>{if(!n)return null;const l=n.label?.trim();if(l)return D2(l);const d=HA(n.path);return d?D2(d):null},[n]),[s,o]=p.useState(null),i=DA();p.useEffect(()=>{if(typeof window>"u"||!wt()){o(null);return}let l=!1;const d=async()=>{try{if(Ko()){l||o(null);return}const u=window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,h=Nd();if(h&&Lg(h,u)){l||o(null);return}const g=(await tm()).hosts.find(b=>h?Lg(h,al(b)):!1),x=g?.label?.trim()?Wn(g.label.trim()):"Instance";l||o(x)}catch{l||o("Instance")}};d();const f=()=>{d()};return window.addEventListener("focus",f),()=>{l=!0,window.removeEventListener("focus",f)}},[]);const a=p.useMemo(()=>`${i}${FA(t?.trim()||r,s)}`,[t,s,r,i]);p.useEffect(()=>{if(typeof document<"u"&&(document.title=a),!wt())return;(async()=>{try{if(typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await pj(a)}catch{return}})()},[a])},kX=()=>(BA(),null),VA=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]),$A=e=>{try{const t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;const n=t.hostname.toLowerCase();return VA.has(n)}catch{return!1}},Km=()=>Br()&&Ko()?"device":"server",MX=(e,t)=>Rg(e)??(Br()?Rg(t):null)??Km(),zA=10*6e4,mp=e=>$A(e)?"panel":"external",UA=e=>Math.max(0,e.serverNow-e.createdAt),IX=e=>({showNotice:UA(e)<=zA,target:mp(e.url)}),EX=(e,t,n)=>t==="external"?{title:"Open this page?",description:`${e}. Opens in your browser.`,canOpen:!0}:n.isMobile?{title:"A page is ready to view",description:`${e}. Open PiChamber on a larger screen to view it.`,canOpen:!1}:{title:"Open this page?",description:`${e}. Opens in the PiChamber browser.`,canOpen:!0},qA=e=>{try{const t=new URL(e),n=t.pathname==="/"?"":t.pathname,r=`${t.host}${n}`;return r.length>80?`${r.slice(0,79)}…`:r}catch{return e.slice(0,80)}},WA=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,KA=/\bhttps?:\/\/[^\s<>"'`\u0000-\u001f]+/gi,GA=(e,t=3)=>{if(!e)return[];const n=[];for(const r of e.replace(WA," ").match(KA)??[]){const s=r.replace(/[),.;:!?'"`\]]+$/g,"");let o;try{o=new URL(s)}catch{continue}if(!(o.protocol!=="http:"&&o.protocol!=="https:")&&!n.includes(s)&&(n.push(s),n.length>=t))break}return n},ZA=()=>{const{currentSessionId:e,newSessionDraft:t}=pe.getState();if(e){const n=Ue().getState(),r=n.catalog.byId.get(e)?.directory??n.directory;if(r)return r}return t?.open&&t.directoryOverride?t.directoryOverride:nt.getState().currentDirectory??void 0},YA=(e,t,n)=>{if(e==="external")return ka(t),!0;const r=te.getState();return r.isMobile?!1:(r.openContextBrowser(n,t,{route:Km()}),!0)},jX=e=>{const t=te.getState(),n=t.chatLinkTarget==="pichamber"&&!t.isMobile?ZA():void 0;if(!n){ka(e);return}t.openContextBrowser(n,e,{route:Km()})},O2=(e,t)=>{const n=de(t??null);if(!n)return;const r=n.toLowerCase();e.has(r)||e.set(r,n)},Vw=(e,t,n)=>{const r=new Map;for(const s of e)O2(r,s?.path);if(n?.includeWorktrees===!1||!t)return new Set(r.values());for(const s of t.values())if(s)for(const o of s)O2(r,o?.path);return new Set(r.values())},Vc=new Map,XA=e=>{const t=new Set;for(const n of e){const r=de(n);r&&t.add(r)}return t},JA=()=>{const e=new Set,t=at.getState().projects,n=Vw(t,Ln(t,Qt.getState()),{includeWorktrees:!0});for(const o of n){const i=de(o);i&&i!=="~"&&e.add(i)}const r=de(Ue().getState().directory);r&&e.add(r);const s=nt.getState().homeDirectory??null;for(const o of Em(s)){const i=de(o);i&&i!=="~"&&e.add(i)}return e},QA=async(e,t,n,r,s)=>{const o=e.getState().catalog.listStatusByDirectory,i=r.filter(m=>o.get(m)!=="ready");i.length>0&&await e.refreshAllDirectoryCatalogs(i).catch(()=>{});const a=Ue(),l=a!==e||Y()!==t||a.getRuntimeGeneration()!==n,d=a.getState().catalog,f=new Set,u=new Set;for(const m of r){const g=d.listStatusByDirectory.get(m);g==="ready"?f.add(m):g==="failed"&&u.add(m)}const h=!l&&u.size===0&&f.size===r.length&&(s||r.length>0);return{runtimeKey:t,catalog:d,readyDirectories:f,failedDirectories:u,complete:h,stale:l}},eN=e=>{const t=Ue(),n=Y(),r=t.getRuntimeGeneration(),s=e!==void 0,i=[...e===void 0?JA():XA(e)].sort(),a=`${n}::${i.join("|")}`,l=Vc.get(a);if(l&&l.store===t&&l.runtimeKey===n&&l.generation===r)return l.promise;const d=QA(t,n,r,i,s);Vc.set(a,{store:t,runtimeKey:n,generation:r,promise:d});const f=()=>{Vc.get(a)?.promise===d&&Vc.delete(a)};return d.then(f,f),d},tN=e=>{if(typeof Element>"u"||!(e instanceof Element))return null;const t=e.closest("[data-terminal-owner]");return t?.isConnected&&t.dataset.terminalOwner||null},Pf=e=>tN(e)!==null,nN=e=>{const t=e.info;if(t.finish==="stop"||t.finish==="error")return!0;const n=t.time?.completed,r=t.status;return typeof n!="number"||n<=0?!1:typeof r=="string"?r==="completed":!0},rN=e=>{const{activeStreamingMessageId:t,assistantMessages:n}=e;if(t&&n.some(r=>r.info.id===t))return t;for(let r=n.length-1;r>=0;r--)if(!nN(n[r]))return n[r].info.id;return null},sN=e=>e.connection==="ready"&&(e.authoritativeWorking||e.hasPendingAssistant),oN=e=>{const t=e.connection==="ready"&&!e.transportUncertain,n=e.authoritativeWorking||e.hasPendingAssistant;return{isWorking:t&&n,isAwaitingRecovery:!t&&(n||e.hasRetainedStream)}},iN=e=>e.turnIsInActiveStream||e.isLastTurn&&e.sessionIsWorking&&e.awaitingPromptEcho!==!0&&(e.isSteering===!0||!e.activeStreamingMessageId),aN=e=>e.isRetrying===!0||e.isAwaitingRecovery===!0||!!e.activeStreamingMessageId&&e.messageId===e.activeStreamingMessageId,Df={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function cN(e,t){const n=iw(),r=Xd(e??""),s=Pm(e??"");return p.useMemo(()=>{if(!e)return Df;const o=r?.type??"idle",i=s[s.length-1],a=!!(i&&i.role==="assistant"&&typeof i.time?.completed!="number"),l=r!==void 0,d=l&&o!=="idle",f=sN({connection:n,authoritativeWorking:d,hasPendingAssistant:a});return l&&!d||!f?Df:{phase:d?o:"busy",isWorking:!0,isBusy:o==="busy"||!d&&a,isCooldown:!1}},[n,e,r,s])}function Gm(){const e=pe(t=>t.currentSessionId);return pe(t=>t.currentSessionDirectory),cN(e)}const _X=.45,Zm=[{id:"context",description:"Session context and token usage",mode:"context",icon:"donut-chart-fill",label:"Context",availability:"always"},{id:"editor",description:"Edit project files",mode:"file",icon:"file-text",label:"Files",availability:"always"},{id:"git",description:"Review diffs, commit, and push",mode:"git",icon:"git-branch",label:"Git",availability:"always"},{id:"terminal",description:"Built-in terminal",mode:"terminal",icon:"terminal-box",label:"Terminal",availability:"always"},{id:"browser",description:"Built-in web browser",mode:"browser",icon:"global",label:"Browser",availability:"always"},{id:"preview",description:"Dev server preview",mode:"preview",icon:"window",label:"Preview",availability:"has-content"},{id:"pull-requests",description:"Browse pull requests for this repository",mode:"pull-requests",icon:"git-pull-request",label:"Pull requests",availability:"github-repo"},{id:"issues",description:"Browse issues for this repository",mode:"issues",icon:"task",label:"Issues",availability:"github-repo"},{id:"extensions",description:"Extension widgets for this session",mode:"extensions",icon:"plug-2",label:"Extensions",availability:"extensions"}],$w=new Map(Zm.map(e=>[e.id,e])),Of=Zm.find(e=>e.id==="git"),TX=e=>e===!1?{icon:"arrow-left-right",label:"Changes",description:"Review working and last-turn changes"}:{icon:Of?.icon??"git-branch",label:Of?.label??"Git",description:Of?.description??"Review diffs, commit, and push"},lN=e=>typeof e=="string"&&$w.has(e),dN=e=>{const t=[],n=new Set;for(const r of e){if(!lN(r)||n.has(r))continue;const s=$w.get(r);s&&(n.add(r),t.push(s))}for(const r of Zm)n.has(r.id)||t.push(r);return t},AX=e=>{if(!e)return{isLoading:!0,hasResult:!1,hasGitHubRepo:!1,hasError:!1};const t=e.scope?.repositories??[];return{isLoading:e.isLoading,hasResult:!!(e.scope||e.error),hasGitHubRepo:t.some(n=>!!(n.host&&n.owner&&n.repo&&!n.disabledReason)),hasError:!!(e.error&&!e.scope)}},uN=e=>!e||e.isLoading&&!e.hasResult?!1:e.hasError?!0:e.hasGitHubRepo,fN=e=>dN(e.railOrder).filter(t=>t.availability==="has-content"?e.tabs.some(n=>n.mode===t.mode):t.availability==="github-repo"?e.tabs.some(n=>n.mode===t.mode)?!0:uN(e.githubScope):t.availability==="extensions"?e.tabs.some(n=>n.mode===t.mode)?!0:!!e.hasExtensionContent:!0),zw=3e4,ds=()=>({scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),bi=new Map,hN=(e,t)=>`${e}
46
+ ${t}`,pN=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub scope check failed"}},El=e=>!e.host||!e.owner||!e.repo?null:d5(`${e.host}/${e.owner}/${e.repo}`),jl=e=>!!(e.host&&e.owner&&e.repo&&!e.disabledReason),Ym=(e,t)=>{if(!e)return t;const n=new Set(e.repositories.filter(jl).map(i=>El(i)).filter(i=>!!i));if(t&&n.has(t))return t;if(e.defaultSelection&&n.has(e.defaultSelection))return e.defaultSelection;const r=e.repositories.find(i=>i.kind==="containing"&&jl(i)),s=r?El(r):null;if(s&&n.has(s))return s;const o=e.repositories.find(jl);return o?El(o):null},Pa=Lt()(mr((e,t)=>({runtimeKey:Y(),entriesByDirectory:{},resetForRuntimeSwitch:n=>{const r=n??Y();bi.clear(),e({runtimeKey:r,entriesByDirectory:{}})},ensureScope:async(n,r)=>{const s=ps(n.trim());if(!s)return ds();const o=Y();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t().entriesByDirectory[s],a=Date.now();return i?.scope&&i.fetchedAt&&a-i.fetchedAt<zw&&!i.isLoading?i:t().refreshScope(s,r)},refreshScope:async(n,r,s)=>{const o=ps(n.trim());if(!o)return ds();const i=Y();t().runtimeKey!==i&&t().resetForRuntimeSwitch(i);const a=hN(i,o),l=bi.get(a);if(l&&!s?.force)return l;const d=r??null;if(!d)return t().entriesByDirectory[o]??ds();const f=t().entriesByDirectory[o]??ds();f.isLoading||e(h=>({entriesByDirectory:{...h.entriesByDirectory,[o]:{...f,isLoading:!0}}}));const u=(async()=>{try{const h=await d.scope(o);if(Y()!==i)return t().entriesByDirectory[o]??ds();const m={scope:h,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null};e(b=>({entriesByDirectory:{...b.entriesByDirectory,[o]:m}}));const g=te.getState().githubSelectedRepoByDirectory[o]??null,x=Ym(h,g);return x!==g&&te.getState().setGitHubSelectedRepo(o,x),m}catch(h){if(Y()!==i)return t().entriesByDirectory[o]??ds();const m=pN(h),g=f.scope?{...f,isLoading:!1,stale:!0,error:m}:{scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:m};return e(x=>({entriesByDirectory:{...x.entriesByDirectory,[o]:g}})),g}})();bi.set(a,u);try{return await u}finally{bi.get(a)===u&&bi.delete(a)}},setSelectedRepo:(n,r)=>{const s=ps(n.trim());if(!s)return;const o=t().entriesByDirectory[s]?.scope??null;if(r!=null){const i=d5(r);if(!i||o&&!new Set(o.repositories.filter(jl).map(l=>El(l)).filter(l=>!!l)).has(i))return;te.getState().setGitHubSelectedRepo(s,i);return}te.getState().setGitHubSelectedRepo(s,null)},invalidate:async(n,r)=>{const s=ps(n.trim());if(!s)return null;const o=r??null;if(o)try{await o.invalidate({directory:s})}catch{}return t().refreshScope(s,o??void 0,{force:!0})}}),{name:"github-scope-store"}));typeof window<"u"&&en(e=>{Pa.getState().resetForRuntimeSwitch(e.runtimeKey)});const H2=Object.freeze(ds()),mN=e=>Pa(t=>e?t.entriesByDirectory[ps(e)]??H2:H2),gN=e=>{const t=Pa(r=>e?r.entriesByDirectory[ps(e)]?.scope??null:null),n=te(r=>e?r.githubSelectedRepoByDirectory[ps(e)]??null:null);return p.useMemo(()=>e?Ym(t,n):null,[e,t,n])},NX=Object.freeze(Object.defineProperty({__proto__:null,GITHUB_SCOPE_STALE_MS:zw,resolveGitHubSelectedRepo:Ym,useGitHubScope:mN,useGitHubScopeStore:Pa,useGitHubSelectedRepo:gN},Symbol.toStringTag,{value:"Module"})),Qn=()=>{const e=pe(s=>s.currentSessionId),t=pe(s=>s.newSessionDraft),n=NE(e),r=nt(s=>s.currentDirectory);return e&&n?n:t?.open&&t.directoryOverride?t.directoryOverride:r??void 0},yN=()=>({setCurrentVariant:e=>We.getState().setCurrentVariant(e)}),Ri=(e,t=yN())=>(t.setCurrentVariant(e),"applied"),vN=async(e=1)=>{const t=We.getState(),n=fm(t.getCurrentModelVariants(),t.currentVariant,e);return Ri(n),n},xN='[data-chat-input="true"] .cm-content';function Io(){document.querySelector(xN)?.focus()}const bN=new Set(["address","article","aside","blockquote","dd","div","dl","dt","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","ul"]),Xm=e=>e.replace(/\r\n?/g,`
47
+ `),wn=e=>Xm(e).trim(),wN=e=>e.replace(/\s+/g," ").trim(),Uw=e=>(e.match(/language-([\w+#.-]+)/)?.[1]||"").trim(),SN=e=>e.closest("pre")?.getAttribute("data-md-lang")||Uw(e.className),qw=e=>{if(e.nodeType===3)return{type:"text",value:e.textContent||""};if(e.nodeType!==1)return null;const t=e;return{type:"element",tag:t.tagName.toLowerCase(),className:t.getAttribute("class")||"",href:t.getAttribute("href")||"",component:t.getAttribute("data-component")||"",markdownLanguage:t.getAttribute("data-md-lang")||"",isMarkdownBlock:t.hasAttribute("data-md-block"),isCodeLines:t.hasAttribute("data-md-code-lines"),isCodeLineNumber:t.hasAttribute("data-md-code-line-number"),children:Array.from(t.childNodes).map(n=>qw(n)).filter(n=>n!==null)}},Jm=e=>e.filter(t=>t.type==="text"||!t.isCodeLineNumber).map(t=>t.type==="text"?t:{...t,children:Jm(t.children)}),CN=e=>Array.from(e.childNodes).map(t=>qw(t)).filter(t=>t!==null),oa=e=>e.type==="text"?e.value:e.children.map(t=>oa(t)).join(""),gp=(e,t)=>{if(e.type==="text")return null;if(t(e))return e;for(const n of e.children){const r=gp(n,t);if(r)return r}return null},Qm=(e,t="")=>{const n=Xm(e).replace(/\n$/,""),r=Math.max(0,...Array.from(n.matchAll(/`+/g),o=>o[0].length)),s="`".repeat(Math.max(3,r+1));return`${s}${t}
48
+ ${n}
49
+ ${s}`},Eo=e=>{if(e.type==="text")return wN(e.value);const t=e.children.map(n=>Eo(n)).join("").replace(/\s+/g," ").trim();return!t&&e.tag!=="br"?"":e.tag==="br"?`
50
+ `:e.tag==="strong"||e.tag==="b"?`**${t}**`:e.tag==="em"||e.tag==="i"?`*${t}*`:e.tag==="code"?`\`${t.replace(/`/g,"\\`")}\``:e.tag==="a"&&e.href?`[${t}](${e.href})`:t},F2=(e,t)=>e.children.filter(n=>n.type==="element"&&n.tag==="li").map((n,r)=>{const s=n.children.map(o=>Eo(o)).join("").replace(/\s+/g," ").trim();return s?`${t?`${r+1}.`:"-"} ${s}`:""}).filter(Boolean).join(`
51
+ `),Pi=e=>{if(e.type==="text")return wn(e.value);if(e.isMarkdownBlock)return e.children.map(n=>Pi(n)).filter(n=>n.length>0).join(`
52
+
53
+ `);if(e.component==="markdown-code"){const n=gp(e,r=>r.tag==="pre");return n?Pi(n):""}if(e.tag==="pre"||e.tag==="code"&&e.isCodeLines){const n=e.tag==="code"?e:gp(e,r=>r.tag==="code");return Qm(oa(n||e),e.markdownLanguage||Uw(n?.className||""))}if(e.tag==="code"){const n=Xm(oa(e)).trim();return n?`\`${n.replace(/`/g,"\\`")}\``:""}if(e.tag==="ul")return F2(e,!1);if(e.tag==="ol")return F2(e,!0);if(e.tag==="blockquote")return wn(e.children.map(r=>Pi(r)).join(`
54
+ `)).split(`
55
+ `).filter(r=>r.length>0).map(r=>`> ${r}`).join(`
56
+ `);if(/^h[1-6]$/.test(e.tag)){const n=Number.parseInt(e.tag[1],10),r=wn(e.children.map(s=>Eo(s)).join(""));return r?`${"#".repeat(n)} ${r}`:""}if(e.tag==="p"||e.tag==="div"||e.tag==="li")return wn(e.children.map(n=>Eo(n)).join(""));const t=e.children.map(n=>Pi(n)).filter(n=>n.length>0);return t.length>0?t.join(`
57
+
58
+ `):wn(e.children.map(n=>Eo(n)).join(""))},kN=e=>e.type==="text"?!0:!e.isMarkdownBlock&&!e.isCodeLines&&e.component!=="markdown-code"&&!bN.has(e.tag),MN=(e,t)=>{const n=Jm(e);if(n.every(s=>kN(s))){const s=wn(n.map(o=>Eo(o)).join(""));if(s)return s}return n.map(s=>Pi(s)).filter(s=>s.length>0).join(`
59
+
60
+ `).trim()||wn(t)},B2=e=>(e.nodeType===1?e:e.parentElement)?.closest("pre code")??null,Ww=(e,t)=>{const n=B2(e.startContainer),r=B2(e.endContainer),s=Jm(CN(e.cloneContents()));return n&&n===r?Qm(s.map(o=>oa(o)).join(""),SN(n)):MN(s,t)},e1=e=>{const t=Math.max(0,...Array.from(e.matchAll(/`+/g),r=>r[0].length)),n="`".repeat(Math.max(3,t+1));return`${n}md
61
+ ${e}
62
+ ${n}`},IN='[data-chat-input="true"]',t1=e=>{if(!e)return!1;const t=e;return!!(typeof t.closest=="function"?t:e.parentElement)?.closest(IN)},EN=e=>{if(t1(e))return null;const t=e.tagName?.toLowerCase();if(t==="textarea"){const n=e,r=n.selectionStart??0,s=n.selectionEnd??0,o=wn(n.value.slice(r,s));return o?(n.selectionStart=s,n.selectionEnd=s,o):null}if(t==="input"){const n=e,r=n.type?.toLowerCase()??"text";if(!["text","search","url","tel","password"].includes(r))return null;const s=n.selectionStart??0,o=n.selectionEnd??0,i=wn(n.value.slice(s,o));return i?(n.selectionStart=o,n.selectionEnd=o,i):null}return null},jN=()=>{if(typeof document>"u")return null;const e=document.activeElement;if(!e||typeof e.tagName!="string")return null;const t=EN(e);return t?e1(t):null},_N=()=>{if(typeof document>"u")return null;const e=document.querySelector(".cm-editor.cm-focused");if(!e||t1(e))return null;const t=bn.findFromDOM(e);if(!t)return null;const{from:n,to:r}=t.state.selection.main;if(n===r)return null;const s=wn(t.state.sliceDoc(n,r));return s?(t.dispatch({selection:{anchor:r}}),Qm(s)):null},TN=()=>{if(typeof window>"u")return null;const e=window.getSelection();if(!e||e.rangeCount===0||e.isCollapsed)return null;const t=e.getRangeAt(0);if(t1(t.commonAncestorContainer))return null;const n=wn(e.toString());if(!n)return null;const r=Ww(t,n);return e.removeAllRanges(),e1(r)},AN=()=>_N()??jN()??TN(),Kw=()=>{const e=AN();return te.getState().setActiveMainTab("chat"),te.getState().setSessionSwitcherOpen(!1),e&&Ye.getState().setPendingInputText(e,"append"),queueMicrotask(()=>{Io()}),e!==null},Gw="file://";function NN(e){let t=e.replace(/\\/g,"/");return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split("/").map((n,r)=>r===1&&/^[A-Za-z]:$/.test(n)?n:encodeURIComponent(n)).join("/")}function LN(e){const t=e.replace(/\\/g,"/").trim();return t.toLowerCase().startsWith(Gw)?t:`file://${NN(t)}`}function RN(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function V2(e){const t=e.trim().replace(/^['"]+|['"]+$/g,"");return!t||/[\r\n]/.test(t)?null:t.toLowerCase().startsWith(Gw)||RN(t)?t:null}function yp(e,t,n=0){if(!(n>6||e==null)){if(typeof e=="string"){t.add(e);return}if(Array.isArray(e)){for(const r of e)yp(r,t,n+1);return}if(typeof e=="object")for(const r of Object.values(e))yp(r,t,n+1)}}function PN(e){const t=new Set,n=r=>{const s=V2(r);if(s){t.add(s);return}for(const o of r.split(/\r?\n/)){const i=V2(o);i&&t.add(i)}};n(e);try{const r=JSON.parse(e),s=new Set;yp(r,s);for(const o of s)n(o)}catch{}return Array.from(t)}function Yt(e){if(typeof e!="string")return null;const t=e.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return n==="/"?"/":n.length>1?n.replace(/\/+$/,""):n}function DN(e,t){const n=e.replace(/\\/g,"/").trim(),r=(t||"").replace(/\\/g,"/").replace(/\/+$/,"");if(!r||n===r)return n;const s=`${r}/`;return n.startsWith(s)?n.slice(s.length):n}const ON=["CodeFiles","codefiles","application/vnd.code.tree","application/vnd.code.tree.explorer","text/uri-list","text/plain"],ur="__home__",HN="Don't work in a folder",FN=()=>"~",BN=e=>e.enabled&&e.isDraftOpen&&!!e.activeProjectId&&e.selectedProjectId!==ur&&e.selectedProjectId!==e.activeProjectId,VN=e=>{if(e.selectedProjectId===ur)return null;const t=e.selectedProjectId??e.activeProjectId,n=(t?e.projects.find(r=>r.id===t):null)??e.projects[0]??null;return n?n.label?.trim()||u5(n.path):null};function Zw(e,t){const n=e.flatMap(o=>{const i={...o,id:o.id,ownerProjectId:o.id,kind:"project"},a=t.get(Yt(o.path)??o.path)??[];return[i,...a.map(l=>({id:`worktree:${o.id}:${l.path}`,ownerProjectId:o.id,kind:"worktree",path:l.path,branch:l.branch,label:l.branch||(l.detached?"Detached HEAD":l.name)}))]}),r=FN();return[{id:ur,ownerProjectId:ur,kind:"project",path:r,label:HN},...n]}const Yw=Lt()(mr(e=>({selectedSpaceId:null,selectedWorktreePath:null,selectSpace:t=>{e({selectedSpaceId:t,selectedWorktreePath:null})},selectWorktree:(t,n)=>{e({selectedSpaceId:t,selectedWorktreePath:n})},clearSpaceSelection:()=>{e({selectedSpaceId:null,selectedWorktreePath:null})},clearSelectedWorktree:()=>{e({selectedWorktreePath:null})}}),{name:"sidebar-space"}));function Xw(e,t){if(e.length<=1)return null;const n=t?e.indexOf(t):-1;return e[(n+1)%e.length]??null}function vp(e=1){const t=at.getState(),n=t.projects;if(n.length<=1)return!1;const r=n.map(f=>f.id);let s=t.activeProjectId;if(!s||!r.includes(s)){const f=de(nt.getState().currentDirectory??null);s=Zn(n,Ln(n,Qt.getState()),f)?.id??null}const o=e===1?Xw(r,s):r[((s?r.indexOf(s):0)-1+r.length)%r.length]??null;if(!o)return!1;const i=n.find(f=>f.id===o),a=de(i?.path??null);if(!i||!a)return!1;t.setActiveProjectIdOnly(o),Yw.getState().selectSpace(o),te.getState().closeMainSurfaces();const l=Ln(n,Qt.getState()),d=Yb().find(f=>{const u=de(f.directory??null);return u?Zn(n,l,u)?.id===o:!1});if(d){const f=de(d.directory??null);return pe.getState().setCurrentSession(d.id,f),!0}return pe.getState().openNewSessionDraft({selectedProjectId:o,directoryOverride:a}),!0}function $N(){const e=pe.getState(),t=e.newSessionDraft;if(!t?.open)return!1;const n=at.getState(),r=n.projects,s=Zw(r,Ln(r,Qt.getState()));if(s.length<=1)return!1;const o=de(t.directoryOverride??null),i=t.selectedProjectId?s.find(f=>f.ownerProjectId===t.selectedProjectId&&(!o||de(f.path)===o))??s.find(f=>f.id===t.selectedProjectId)??(o?s.find(f=>de(f.path)===o)??null:null):o?s.find(f=>de(f.path)===o)??null:null,a=Xw(s.map(f=>f.id),i?.id??null),l=s.find(f=>f.id===a),d=de(l?.path??null);return!l||!d?!1:l.ownerProjectId===ur?(e.setNewSessionDraftTarget({projectId:ur,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0):(n.activeProjectId!==l.ownerProjectId&&(n.setActiveProjectIdOnly(l.ownerProjectId),Yw.getState().selectSpace(l.ownerProjectId)),e.setNewSessionDraftTarget({projectId:l.ownerProjectId,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0)}const zN=['[data-slot="dropdown-menu-content"][data-open]','[data-slot="select-content"][data-open]'].join(",");function UN(e=document){return!!e.querySelector(zN)}const qN=(e,t)=>!e.repeat&&_t(e,t),WN=e=>{const t=pe.getState().currentSessionId;t&&Ue().prompt(t,NS(e),"prompt").catch(()=>{})},KN=()=>{const e=pe(I=>I.openNewSessionDraft),t=pe(I=>I.armAbortPrompt),n=pe(I=>I.clearAbortPrompt),r=pe(I=>I.currentSessionId),s=Dm,o=te(I=>I.toggleCommandPalette),i=te(I=>I.toggleHelpDialog),a=te(I=>I.toggleSidebar),l=nt(I=>I.currentDirectory),d=Qn(),f=p.useCallback(()=>{l&&te.getState().openContextSurface(Wi(l),"terminal")},[l]),u=te(I=>I.isMobile),h=te(I=>I.setSessionSwitcherOpen),m=te(I=>I.setActiveMainTab),g=te(I=>I.setSettingsDialogOpen),x=te(I=>I.setModelSelectorOpen),b=te(I=>I.setTimelineDialogOpen),S=te(I=>I.setPromptNavigatorPanelOpen),y=te(I=>I.shortcutOverrides),v=nt(I=>I.currentDirectory),C=at(I=>I.getActiveProject()),{themeMode:w,setThemeMode:M}=Jn(),{phase:j}=Gm(),T=p.useRef(null),A=p.useRef(null),_=p.useRef(w),k=p.useRef(new Set);p.useEffect(()=>{_.current=w},[w]);const E=p.useCallback(()=>{A.current&&(clearTimeout(A.current),A.current=null),T.current=null,n()},[n]);p.useEffect(()=>{const I=P=>AS(P,y),N=jS("switch_context_surface",y),O=['[data-slot="dropdown-menu-content"]','[data-slot="select-content"]','[role="combobox"]','[role="listbox"]','[role="menu"]','[role="menuitem"]','[role="option"]',"[data-radix-popper-content-wrapper]"].join(","),L=P=>P instanceof Element&&!!P.closest(O),D=P=>{if(Pf(P.target)&&_t(P,I("toggle_terminal"))){const{isMobile:q}=te.getState();if(q)return;P.preventDefault(),P.stopPropagation(),f();return}},W=P=>{if(P.key!=="Escape")return;const q=P.target,F=!!q?.closest('[role="dialog"]'),ee=!!document.querySelector('[data-settings-view="true"]'),G=Pf(q),K=L(q)||UN(),{isSettingsDialogOpen:se,isCommandPaletteOpen:ce,isHelpDialogOpen:re,isSessionSwitcherOpen:fe,isImagePreviewOpen:ge,activeMainTab:we,isPromptNavigatorPanelOpen:Me}=te.getState();if(F||G||K){E();return}if(Me){P.preventDefault(),S(!1),E();return}if(se){P.preventDefault(),g(!1),E();return}if(ee){E();return}if(ce||re||fe||ge||!(we==="chat")){E();return}const Ge=r,et=!!(Ge&&Ue().getState().reducer.bySession.get(Ge)?.bashExecutions?.some(be=>be.phase==="running"));if(j==="idle"&&!et||!Ge){E();return}const Xe=Date.now(),oe=T.current;if(oe&&Xe<oe){P.preventDefault(),E(),et?dw(Ge).catch(()=>{Ce.error("Failed to stop the shell command")}):s(Ge);return}P.preventDefault();const Q=t(3e3)??Xe+3e3;T.current=Q,A.current&&clearTimeout(A.current);const ue=Math.max(Q-Xe,0);A.current=setTimeout(()=>{T.current&&Date.now()>=T.current&&E()},ue||0)},z=P=>{if(P.key==="Escape"||Pf(P.target))return;if(_t(P,I("open_command_palette"))){P.preventDefault(),o();return}if(_t(P,I("open_timeline_dialog"))){P.preventDefault(),b(!0);return}if(_t(P,I("open_help"))){P.preventDefault(),i();return}if(_S()&&_t(P,I("new_mini_chat"))){P.preventDefault(),dr("desktop_open_draft_mini_chat_window",{directory:v||C?.path||"",projectId:C?.id??null}).catch(G=>{console.warn("[keyboard-shortcuts] failed to open draft mini chat window",G)});return}if(_t(P,I("new_chat"))){P.preventDefault(),m("chat"),h(!1),e();return}if(_t(P,I("cycle_theme"))){P.preventDefault();const G=["light","dark","system"],K=document.activeElement,ce=(G.indexOf(_.current)+1)%G.length;M(G[ce]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),K&&document.contains(K)&&K.focus({preventScroll:!0}))});return}if(_t(P,I("open_settings"))){P.preventDefault();const{isSettingsDialogOpen:G}=te.getState();g(!G);return}if(_t(P,I("add_selection_to_chat"))){P.preventDefault(),Kw();return}if(_t(P,I("toggle_sidebar"))){P.preventDefault();const{isMobile:G,isSessionSwitcherOpen:K}=te.getState();G?h(!K):a();return}if(_t(P,I("focus_input"))){P.preventDefault(),Io();return}if(_t(P,I("cycle_session_folder"))){if(!vp())return;P.preventDefault();return}if(_t(P,I("cycle_draft_folder"))){if(!$N())return;P.preventDefault();return}if(_t(P,I("open_right_sidebar"))){const G=te.getState();if(G.isMobile||!v)return;P.preventDefault();const K=Wi(v),se=G.contextPanelByDirectory[K];if(se?.isOpen)return;se?.activeTabId?G.setActiveContextPanelTab(K,se.activeTabId):G.openContextSurface(K,"git");return}if(_t(P,I("toggle_terminal"))){const{isMobile:G}=te.getState();if(G)return;P.preventDefault(),f();return}const F=P.key.length===1&&P.key>="0"&&P.key<="9"?P.key==="0"?10:Number(P.key):null;if(F!==null&&!P.repeat&&TS(P,N,k.current)){const G=te.getState();if(G.isMobile||!d)return;const K=Wi(d),se=G.contextPanelByDirectory[K];let ce;const re=Pa.getState().entriesByDirectory[K]??null;if(re){const we=re.scope?.repositories??[];ce={isLoading:re.isLoading,hasResult:!!(re.scope||re.error),hasGitHubRepo:we.some(Me=>!!(Me.host&&Me.owner&&Me.repo&&!Me.disabledReason)),hasError:!!(re.error&&!re.scope)}}const ge=fN({railOrder:G.contextRailOrder,tabs:se?.tabs??[],githubScope:ce})[F-1];if(!ge)return;P.preventDefault(),G.openContextSurface(K,ge.mode);return}if(qN(P,I("open_model_selector"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:ce,activeMainTab:re,isModelSelectorOpen:fe}=te.getState();if(G||K||se||ce||!(re==="chat"))return;P.preventDefault(),x(!fe);return}if(_t(P,I("cycle_thinking_variant"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:ce,activeMainTab:re}=te.getState();if(G||K||se||ce||!(re==="chat")||We.getState().getCurrentModelVariants().length===0)return;P.preventDefault(),vN(1).catch(()=>{Ce.error("Couldn't update thinking")});return}if(_t(P,I("cycle_favorite_model_forward"))||_t(P,I("cycle_favorite_model_backward"))){const{isSettingsDialogOpen:G,isCommandPaletteOpen:K,isHelpDialogOpen:se,isSessionSwitcherOpen:ce,activeMainTab:re,favoriteModels:fe,addRecentModel:ge}=te.getState();if(G||K||se||ce||!(re==="chat")||fe.length===0)return;P.preventDefault();const{currentProviderId:He,currentModelId:Ae,setProvider:Ge,setModel:et}=We.getState(),Xe=fe.length,oe=fe.findIndex(be=>be.providerID===He&&be.modelID===Ae),Q=_t(P,I("cycle_favorite_model_forward"))?1:-1,ue=fe[(oe+Q+Xe)%Xe];Ge(ue.providerID),et(ue.modelID),ge(ue.providerID,ue.modelID);return}const ee=te.getState().commandTriggers;if(ee.length>0&&!L(P.target)){for(const G of ee)if(!(!G.combo||!_t(P,G.combo))){P.preventDefault(),P.stopPropagation(),WN(G);return}}},J=P=>{k.current.add(P.key.toLowerCase())},B=P=>{k.current.delete(P.key.toLowerCase())},U=()=>{k.current.clear()};return window.addEventListener("keydown",J,!0),window.addEventListener("keyup",B,!0),window.addEventListener("blur",U),window.addEventListener("keydown",D,!0),window.addEventListener("keydown",W,!0),window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",J,!0),window.removeEventListener("keyup",B,!0),window.removeEventListener("blur",U),window.removeEventListener("keydown",D,!0),window.removeEventListener("keydown",W,!0),window.removeEventListener("keydown",z)}},[e,s,o,i,a,f,u,h,m,g,x,b,S,M,j,t,E,r,v,d,C?.id,C?.path,y]),p.useEffect(()=>()=>{E()},[E])},GN=3,ZN=(e,t)=>{if(typeof e!="string")return t;const n=e.trim().replace(/\s+/g," ");return n?n.slice(0,48):t},YN=(e,t)=>{const n=t?[...e.filter(o=>o.id===t),...e.filter(o=>o.id!==t)]:e,r=[],s=new Set;for(const o of n){const i=typeof o.id=="string"?o.id.trim():"";if(!(!i||s.has(i))&&(s.add(i),r.push({sessionId:i,title:ZN(o.title,`Session ${r.length+1}`)}),r.length>=GN))break}return r},XN=()=>{const e=cw(),t=pe(o=>o.currentSessionId),n=p.useMemo(()=>YN(e,t),[t,e]),r=p.useMemo(()=>JSON.stringify(n),[n]),s=n.length>0;p.useEffect(()=>{if(typeof window>"u"||!nm())return;try{s?localStorage.setItem(Pg,r):localStorage.removeItem(Pg)}catch{return}window.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[s,r])},JN=e=>{if(!e||typeof e!="object")return"unknown";const t=e;if(t.status==="accepted"){const n=t.receipt;return n?.accepted===!0&&typeof n.messageId=="string"?"accepted":"unknown"}return t.status==="pending"?"pending":t.status==="expired"?"expired":(t.status==="unknown","unknown")},QN=async(e,t)=>{try{const n=RS(e.runtimeKey);if(!t.streamEpoch||t.streamEpoch!==n)return"unknown";const r=await Ee.getSendReceipt({sessionId:e.sessionId,kind:t.kind,operationId:t.operationId,streamEpoch:t.streamEpoch},{directory:e.directory,runtimeKey:e.runtimeKey});return JN(r)}catch{return"unknown"}},Jw=e=>e instanceof LS,eL=2e3,Mr="hydrate-demand",Qw=2e3,tL=6e4,nL=e=>Math.min(Qw*2**Math.max(e-1,0),tL),$2=(e,t,n)=>e!==void 0&&e.messageId===t&&n<e.nextAttemptAt,rL=(e,t=Date.now,n=setTimeout,r=clearTimeout)=>{let s=null,o=null;return{schedule(i){o!==null&&o<=i||(s!==null&&r(s),o=i,s=n(()=>{s=null,o=null,e()},Math.max(0,i-t())))},dispose(){s!==null&&r(s),s=null,o=null}}},sL=e=>{const t=pe.getState().sessionAbortFlags.get(e);if(!t)return null;const n=t.timestamp+eL;return Date.now()<n?n:null},oL=e=>{const t=e[0];return t?{queuedMessageId:t.id,primaryText:t.content,primaryAttachments:t.attachments??[],agentMentionName:void 0,sendConfig:t.sendConfig}:null},iL=(e,t,n,r)=>pe.getState().sendMessage(t.primaryText,n.providerID,n.modelID,n.agent,t.primaryAttachments,t.agentMentionName,void 0,n.variant,"normal",{target:e,delivery:"followUp",operationId:t.queuedMessageId,...r?{streamEpoch:r}:{}}),aL=e=>{const t=We.getState(),n=At.getState(),r=n.getSessionAgentSelection(e)??void 0,s=n.getSessionModelSelection(e),o=r?n.getAgentModelForSession(e,r):null,i=o?.providerId??s?.providerId??t.currentProviderId??n.lastUsedProvider?.providerID,a=o?.modelId??s?.modelId??t.currentModelId??n.lastUsedProvider?.modelID,l=r&&i&&a?n.getAgentModelVariantForSession(e,r,i,a):void 0;return{providerID:i,modelID:a,agent:r,variant:l}},cL=(e,t)=>{if(e.connection!=="ready")return"unknown";const n=e.catalog.byId.get(t.sessionId);return!n||de(n.directory)!==de(t.directory)||n.archived?"unknown":n.lifecycle==="busy"||n.lifecycle==="retry"?"busy":n.hydrated?"ready":"unknown"};function lL(e){const t=typeof e=="boolean"?e:e?.enabled??!0,n=ft(h=>h.queuedMessages),r=nt(h=>h.currentDirectory),s=La(),o=ze(h=>h.catalog,void 0,Ct),i=ze(h=>h.connection,void 0,Pt),a=p.useRef(new Set),l=p.useRef(new Map),[d,f]=p.useState(0),u=p.useMemo(()=>rL(()=>f(h=>h+1)),[]);p.useEffect(()=>()=>u.dispose(),[u]),p.useEffect(()=>{if(!t)return;const h=ft.getState().queuedMessages;for(const[S,y]of l.current)y.messageId===Mr&&!(S in h)&&l.current.delete(S);const m=S=>{l.current.get(S)?.messageId===Mr&&l.current.delete(S)},g=async(S,y,v)=>{const C=s.getState();if(C.connection!=="ready")return;const w=C.catalog.byId.get(y);if(!w||w.archived||de(w.directory)!==de(S.directory))return;const M=l.current.get(v);if(M?.messageId===Mr&&$2(M,Mr,Date.now())){u.schedule(M.nextAttemptAt);return}if(a.current.has(v))return;a.current.add(v);try{await s.ensureHydrated(y)}finally{a.current.delete(v),f(E=>E+1)}const j=s.getState();if(s.isDeleted(y)||!j.catalog.byId.has(y)){m(v);return}if(j.catalog.byId.get(y)?.hydrated){m(v);return}const _=(M?.messageId===Mr?M.failures:0)+1,k=Date.now()+nL(_);l.current.set(v,{messageId:Mr,failures:_,nextAttemptAt:k}),u.schedule(k)},x=async(S,y)=>{const{sessionId:v}=S,C=f5(S);if(y.length===0||S.runtimeKey!==Y()||a.current.has(C))return;const w=sL(v);if(w!==null){u.schedule(w);return}const M=s.getState(),j=cL(M,S);if(j==="busy")return;if(j==="unknown"){await g(S,v,C);return}const T=ft.getState().getAutoSendCandidate(S);if(!T)return;const A=l.current.get(C);if(A&&A.messageId!==T.id&&A.messageId!==Mr)l.current.delete(C);else if(A&&A.messageId!==Mr&&$2(A,T.id,Date.now())){Number.isFinite(A.nextAttemptAt)&&u.schedule(A.nextAttemptAt);return}const _=ft.getState().claimQueuedMessage(S,T.id);if(!_)return;const k=oL([_]);if(!k){ft.getState().clearSending(S,_.id);return}const E=k.sendConfig,I=E?.providerID&&E?.modelID?E:aL(v);if(!I.providerID||!I.modelID){ft.getState().clearSending(S,_.id),u.schedule(Date.now()+Qw);return}a.current.add(C);const N=ft.getState().markDeliveryAttempt(S,_.id,"followUp");if(!N?.streamEpoch){a.current.delete(C),ft.getState().clearSending(S,_.id);return}try{await iL(S,k,{providerID:I.providerID,modelID:I.modelID,agent:I.agent,variant:I.variant},N.streamEpoch),ft.getState().completeQueuedSend(S,k.queuedMessageId),l.current.delete(C)}catch(O){console.warn("[follow-up] auto-send failed:",O);const L=A?.messageId===k.queuedMessageId?A.failures:0;l.current.set(C,{messageId:k.queuedMessageId,failures:L+1,nextAttemptAt:Number.POSITIVE_INFINITY}),Jw(O)?(ft.getState().markSendUnconfirmed(S,k.queuedMessageId,"followUp"),Ce.error("Follow-up status uncertain. Check status before retrying.",{id:`follow-up-unconfirmed:${C}:${k.queuedMessageId}`})):(ft.getState().markSendFailed(S,k.queuedMessageId),Ce.error("Follow-up message failed to send. Use Send now to retry.",{id:`follow-up-failed:${C}:${k.queuedMessageId}`}))}finally{a.current.delete(C),ft.getState().clearSending(S,k.queuedMessageId)}};Object.entries(n).forEach(([S,y])=>{const v=PS(S);!v||v.runtimeKey!==Y()||v.directory!==r||y.length!==0&&x(v,y)})},[t,n,r,o,i,d,u,s])}const dL=1440*60*1e3,e3=5,t3=1440*60*1e3,uL=[],Hf=e=>e.time?.updated??e.time?.created??0,xp=({sessions:e,currentSessionId:t,cutoffDays:n,keepRecent:r=e3,now:s=Date.now()})=>{if(!Array.isArray(e)||n<=0)return[];const o=s-n*dL,i=[...e].sort((l,d)=>Hf(d)-Hf(l)),a=new Set(i.slice(0,r).map(l=>l.id));return i.filter(l=>{if(!l?.id||a.has(l.id)||l.id===t||l.share)return!1;const d=Hf(l);return d?d<o:!1}).map(l=>l.id)},fL=(e,t,n)=>{const r=[],s=[];for(const o of e){const i=t.get(o),a=i?Fm(i):null;a&&n.has(a)?r.push(o):s.push(o)}return{actionable:r,unready:s}},hL=()=>{try{const e=Ue();return{store:e,runtimeKey:Y(),generation:e.getRuntimeGeneration()}}catch{return null}},Ff=e=>{try{const t=Ue();return t!==e.store||Y()!==e.runtimeKey?!1:t.getRuntimeGeneration()===e.generation}catch{return!1}};let _l=!1;const pL=()=>_l,mL=async({force:e=!1,now:t}={})=>{const n=()=>{try{return te.getState().sessionRetentionAction??"archive"}catch{return"archive"}};if(_l)return{completedIds:[],failedIds:[],action:n(),skippedReason:"running"};let r;try{const i=te.getState();r={enabled:i.autoDeleteEnabled,days:i.autoDeleteAfterDays,action:i.sessionRetentionAction??"archive",lastRunAt:i.autoDeleteLastRunAt??null}}catch{return{completedIds:[],failedIds:[],action:"archive",skippedReason:"partial"}}if((!r.enabled||r.days<=0)&&!e)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"disabled"};const s=t??Date.now();if(!e&&r.lastRunAt&&s-r.lastRunAt<t3)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"cooldown"};const o=hL();if(!o)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"stale"};_l=!0;try{try{let i;try{i=await eN()}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}if(i.stale||!Ff(o))return{completedIds:[],failedIds:[],action:r.action,skippedReason:"stale"};if(i.readyDirectories.size===0)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"};const a=[];for(const w of i.catalog.byId.values())w.archived||a.push(Or(w));if(a.length===0){if(i.failedDirectories.size>0)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"};try{te.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:[],failedIds:[],action:r.action,skippedReason:"no-candidates"}}let l,d,f;try{l=pe.getState().currentSessionId??null;const w=te.getState();d=w.sessionRetentionAction??r.action,f=w.autoDeleteAfterDays??r.days}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}const u=xp({sessions:a,currentSessionId:l,cutoffDays:f,now:s});if(u.length===0){if(i.failedDirectories.size>0)return{completedIds:[],failedIds:[],action:d,skippedReason:"partial"};try{te.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:[],failedIds:[],action:d,skippedReason:"no-candidates"}}const h=new Map(a.map(w=>[w.id,w])),{actionable:m,unready:g}=fL(u,h,i.readyDirectories);if(m.length===0)return{completedIds:[],failedIds:[...g],action:d,skippedReason:"partial"};const x=[],b=new Set(g),S=[...g],y=w=>{b.has(w)||(b.add(w),S.push(w))};let v=!1,C=d;for(let w=0;w<m.length;w+=1){const M=m[w];if(!Ff(o)){for(let N=w;N<m.length;N+=1)y(m[N]);v=!0;break}let j,T,A,_;try{j=pe.getState().currentSessionId??null;const N=te.getState();T=N.sessionRetentionAction??d,A=N.autoDeleteAfterDays??f,_=Ue().getState().catalog}catch{y(M);continue}C=T;let k=!1,E=null;try{const N=[];for(const L of _.byId.values())L.archived||N.push(Or(L));if(k=new Set(xp({sessions:N,currentSessionId:j,cutoffDays:A,now:s})).has(M),k){const L=_.byId.get(M);E=L?Fm(Or(L)):null}}catch{y(M);continue}if(!k||!E){y(M);continue}let I;try{I=_.listStatusByDirectory.get(E)}catch{y(M);continue}if(I!=="ready"){y(M);continue}try{const N=Ue();T==="archive"?await N.archive(M,!0,E):await N.remove(M,E)}catch{y(M);continue}if(!Ff(o)){y(M);for(let N=w+1;N<m.length;N+=1)y(m[N]);v=!0;break}x.push(M)}if(v)return{completedIds:x,failedIds:S,action:C,skippedReason:"stale"};if(i.failedDirectories.size>0||S.length>0)return{completedIds:x,failedIds:S,action:C,skippedReason:"partial"};try{te.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:x,failedIds:S,action:C}}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}}finally{_l=!1}},gL=e=>{const t=typeof e=="object"?e:void 0,n=t?.autoRun!==!1,r=typeof e=="boolean"?e:t?.enabled??!0,s=pe(b=>b.currentSessionId),o=te(b=>b.autoDeleteEnabled),i=te(b=>b.autoDeleteAfterDays),a=te(b=>b.sessionRetentionAction),l=te(b=>b.autoDeleteLastRunAt),d=r&&(!n||o),f=ze(b=>Sa(b.catalog,{archived:!1}),Gb,"catalog"),u=d?f:uL,[h,m]=p.useState(!1),g=p.useMemo(()=>i<=0?[]:xp({sessions:u,currentSessionId:s,cutoffDays:i}),[i,s,u]),x=p.useCallback(async({force:b=!1}={})=>{m(!0);try{return await mL({force:b})}finally{m(!1)}},[]);return p.useEffect(()=>{if(!r||!n||!o||i<=0||g.length===0)return;const b=Date.now();l&&b-l<t3||pL()||x()},[i,o,l,n,g.length,r,x]),{candidates:g,isRunning:h,runCleanup:x,keepRecentCount:e3,action:a}},Bf=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:"0px",Vf=(e,t,n)=>{const r=e.style.getPropertyValue(t);r===n||!r&&n==="0px"||e.style.setProperty(t,n)},$f=(e,t,n,r)=>{Vf(e,"--oc-wco-left-inset",Bf(t)),Vf(e,"--oc-wco-right-inset",Bf(n)),Vf(e,"--oc-wco-titlebar-height",Bf(r))},yL=()=>{p.useEffect(()=>{if(typeof window>"u"||!nm())return;const e=document.documentElement,t=typeof window.matchMedia=="function"?window.matchMedia("(display-mode: window-controls-overlay)"):null,r=window.navigator.windowControlsOverlay,s=()=>{if(!r||!t?.matches||!r.visible){$f(e,0,0,0);return}const i=r.getTitlebarAreaRect(),a=Math.max(0,Number(i.x)||0),l=Math.max(0,Number(i.width)||0),d=Math.max(0,Number(i.height)||0),f=Math.max(0,window.innerWidth-(a+l));$f(e,a,f,d)},o=()=>{s()};return s(),window.addEventListener("resize",s),window.addEventListener("focus",s),t&&(typeof t.addEventListener=="function"?t.addEventListener("change",o):typeof t.addListener=="function"&&t.addListener(o)),r&&typeof r.addEventListener=="function"&&r.addEventListener("geometrychange",s),()=>{window.removeEventListener("resize",s),window.removeEventListener("focus",s),t&&(typeof t.removeEventListener=="function"?t.removeEventListener("change",o):typeof t.removeListener=="function"&&t.removeListener(o)),r&&typeof r.removeEventListener=="function"&&r.removeEventListener("geometrychange",s),$f(e,0,0,0)}},[])},vL=()=>{};async function xL(e,t){if(!e?.listen)return vL;const n=[];try{n.push(await e.listen("pichamber:menu-action",r=>{typeof r.payload=="string"&&t.onAction(r.payload)})),n.push(await e.listen("pichamber:check-for-updates",()=>{t.onCheckForUpdates()})),n.push(await e.listen("pichamber:open-mini-chat",()=>{t.onOpenMiniChat?.()}))}catch(r){for(const s of n)s();throw r}return()=>{for(const r of n)r()}}const $c=e=>{const t=te.getState();e&&t.setSettingsPage(e),t.setSettingsDialogOpen(!0)},z2=e=>{const t=Yb();if(t.length<2)return;const n=pe.getState(),r=t.findIndex(i=>i.id===n.currentSessionId),s=r<0?e===1?-1:0:r,o=t[(s+e+t.length)%t.length];o&&n.setCurrentSession(o.id,Fm(o))};function bL(){const{setThemeMode:e}=Jn(),t=p.useCallback(s=>{const o=te.getState();switch(s){case"about":$c("about");return;case"settings":$c();return;case"command-palette":o.setCommandPaletteOpen(!0);return;case"new-session":o.setActiveMainTab("chat"),o.setSessionSwitcherOpen(!1),pe.getState().openNewSessionDraft();return;case"change-workspace":hu.requestDirectoryDialog();return;case"add-selection-to-chat":Kw();return;case"open-right-sidebar":{const i=nt.getState().currentDirectory;if(!i)return;const a=Wi(i),l=o.contextPanelByDirectory[a];if(l?.isOpen)return;l?.activeTabId?o.setActiveContextPanelTab(a,l.activeTabId):o.openContextSurface(a,"git");return}case"toggle-terminal":{const i=nt.getState().currentDirectory;i&&o.openContextSurface(Wi(i),"terminal");return}case"theme-light":e("light");return;case"theme-dark":e("dark");return;case"theme-system":e("system");return;case"toggle-sidebar":o.isMobile?o.setSessionSwitcherOpen(!o.isSessionSwitcherOpen):o.toggleSidebar();return;case"toggle-memory-debug":$l(!Wo());return;case"go-back":window.history.back();return;case"go-forward":window.history.forward();return;case"previous-session":z2(-1);return;case"next-session":z2(1);return;case"previous-project":vp(-1);return;case"next-project":vp(1);return;case"help-dialog":o.setHelpDialogOpen(!0);return;case"download-logs":$c("general"),$l(!0);return;case"copy":return;default:return}},[e]),n=p.useCallback(()=>{$c("about"),xT.getState().checkForUpdates()},[]),r=p.useCallback(()=>{const s=at.getState().getActiveProject();dr("desktop_open_draft_mini_chat_window",{directory:nt.getState().currentDirectory||s?.path||"",projectId:s?.id??null}).catch(o=>{console.warn("[desktop-menu] failed to open draft mini chat window",o)})},[]);p.useEffect(()=>{if(!Br())return;let s=!1,o=()=>{};return xL(DS(),{onAction:t,onCheckForUpdates:n,onOpenMiniChat:r}).then(i=>{s?i():o=i}).catch(i=>{console.warn("[desktop-menu] failed to subscribe to application menu events",i)}),()=>{s=!0,o()}},[t,n,r])}const wL=()=>{const e=at.getState().projects,t=Ln(e,Qt.getState()),n=[...Vw(e,t,{includeWorktrees:!0})];try{const r=[nt.getState().homeDirectory,Gt().getItem("homeDirectory"),typeof window<"u"?window.__PICHAMBER_HOME__:null],s=new Set(n.map(o=>de(o)?.toLowerCase()??o));for(const o of r){if(!o)continue;const i=de(o);if(!i)continue;const a=i.toLowerCase();s.has(a)||(s.add(a),n.push(i))}}catch{}return n},SL=e=>e.length===0?"":[...e].sort().join("|"),CL=()=>(H.useEffect(()=>{let e=!1,t="";const n=Ue(),r=()=>{if(e)return;const a=wL();if(a.length===0)return;const l=SL(a);if(l===t)return;const d=n.getState();if(d.connection!=="ready"||d.sessionsListStatus==="loading"||d.selectedSessionId&&d.focusPending&&d.sessionsListStatus!=="failed")return;const f=a.filter(u=>{const h=n.getState().catalog.listStatusByDirectory.get(u);return h!=="ready"&&h!=="loading"});if(f.length===0){t=l;return}t=l,n.refreshAllDirectoryCatalogs(f)};r();const s=at.subscribe(r),o=Qt.subscribe(r),i=n.subscribe(r,"chrome");return()=>{e=!0,s(),o(),i()}},[]),null),Da=()=>{const e=p.useContext(Ra);if(!e)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return e},kL=6e4,ML=2,IL=()=>{const e=at(l=>l.projects),t=Qt(l=>l.refreshProject),{git:n}=Da(),r=p.useMemo(()=>e.map(l=>l.path).filter(l=>!!l),[e]),s=p.useMemo(()=>[...r].sort().join("\0"),[r]),o=Y(),i=p.useCallback(async()=>{if(!n||r.length===0)return;let l=0;const d=async()=>{for(;l<r.length;){const f=r[l];l+=1,await t(f,n)}};await Promise.all(Array.from({length:Math.min(ML,r.length)},()=>d()))},[n,r,t]),a=p.useRef(null);return p.useEffect(()=>{const l=`${o}\0${s}`;a.current!==l&&(a.current=l,i())},[o,s,i]),p.useEffect(()=>{const l=()=>{i()},d=()=>{document.visibilityState==="visible"&&i()};window.addEventListener("focus",l),document.addEventListener("visibilitychange",d);const f=window.setInterval(()=>{document.visibilityState==="visible"&&i()},kL);return()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",d),window.clearInterval(f)}},[i]),null},U2=2e3,EL=3e4,jL=2;class _L{constructor(t){this.options=t}options;timer=null;currentDelayMs=U2;inFlight=!1;disposed=!1;get isRunning(){return this.inFlight||this.timer!==null}get currentBackoffDelayMs(){return this.currentDelayMs}isMismatched(){return this.options.getConnection()==="ready"&&(!this.options.getIsInitialized()||!this.options.getIsConnected())}isHidden(){return this.options.isDocumentHidden?this.options.isDocumentHidden():typeof document<"u"&&document.visibilityState==="hidden"}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}resetDelay(){this.currentDelayMs=U2}reconcile(){this.check(!1)}wake(){this.check(!0)}check(t){if(!this.disposed){if(!this.isMismatched()){this.clearTimer(),this.resetDelay();return}if(this.isHidden()){this.clearTimer();return}!t&&(this.inFlight||this.timer!==null)||this.executeAttempt()}}resetForRuntimeSwitch(){this.clearTimer(),this.resetDelay()}dispose(){this.disposed=!0,this.clearTimer()}async executeAttempt(){if(this.clearTimer(),this.disposed||this.inFlight)return;if(!this.isMismatched()){this.resetDelay();return}if(this.isHidden())return;this.inFlight=!0,Nr("config-reconcile",{code:"attempt"});try{await this.options.initializeApp()}catch{}finally{this.inFlight=!1}if(this.disposed)return;if(!this.isMismatched()){Nr("config-reconcile",{code:"success"}),this.resetDelay();return}if(Nr("config-reconcile",{code:"failure"}),this.isHidden())return;const t=this.currentDelayMs;this.currentDelayMs=Math.min(t*jL,EL),this.timer=setTimeout(()=>{this.timer=null,this.executeAttempt()},t)}}function TL({connection:e,isInitialized:t,isConnected:n,initializeApp:r}){const s=p.useRef({connection:e,isInitialized:t,isConnected:n,initializeApp:r});s.current={connection:e,isInitialized:t,isConnected:n,initializeApp:r};const o=p.useRef(null);p.useEffect(()=>{o.current?.reconcile()},[e,t,n]),p.useEffect(()=>{const i=new _L({getConnection:()=>s.current.connection,getIsInitialized:()=>s.current.isInitialized,getIsConnected:()=>s.current.isConnected,initializeApp:()=>s.current.initializeApp()});o.current=i,i.reconcile();const a=()=>{typeof document<"u"&&document.visibilityState==="visible"?i.wake():i.reconcile()},l=()=>{i.wake()};typeof document<"u"&&document.addEventListener("visibilitychange",a),typeof window<"u"&&window.addEventListener("online",l);const d=en(()=>{i.resetForRuntimeSwitch(),i.reconcile()});return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",a),typeof window<"u"&&window.removeEventListener("online",l),d(),i.dispose(),o.current===i&&(o.current=null)}},[])}const AL="pichamber:mini-chat-presence",NL=()=>(p.useEffect(()=>{if(typeof BroadcastChannel>"u")return;const e=new BroadcastChannel(AL);return e.onmessage=t=>{const n=t.data;if(n?.type!=="mini-chat-session-presence"||!n.sessionId||!n.directory)return;n.viewed!==!1&&zd(n.sessionId)},()=>e.close()},[]),null);function LL({embeddedBackgroundWorkEnabled:e}){return gL(e),lL(e),c.jsx(CL,{})}const RL=()=>{const e=p.useMemo(()=>Ue(),[]),t=p.useMemo(()=>a=>e.subscribe(a,"chrome"),[e]),n=p.useSyncExternalStore(t,e.getState,e.getState),{selectedSessionId:r,directory:s,connection:o,focusPending:i}=n;return p.useEffect(()=>{if(!s)return;const a=nt.getState().currentDirectory;de(a)!==de(s)&&nt.getState().setDirectory(s,{showOverlay:!1}),We.getState().activateDirectory(s)},[s]),p.useEffect(()=>{const a=pe.getState();if(!r||!s){if(o==="loading"||i)return;(a.currentSessionId!==null||a.currentSessionDirectory!==null)&&pe.setState({currentSessionId:null,currentSessionDirectory:null});return}if(!i&&!Lm(a.newSessionDraft,a.currentSessionId)&&(a.currentSessionId!==r||a.currentSessionDirectory!==s)){const l=a.newSessionDraft?.open?{newSessionDraft:{id:null,open:!1,selectedProjectId:null,directoryOverride:null,branchIntent:null,worktreeIntent:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0}}:{};pe.setState({currentSessionId:r,currentSessionDirectory:s,...l}),zd(r)}},[r,s,o,i]),null},PL=()=>{const e=p.useMemo(()=>Ue(),[]),t=p.useMemo(()=>l=>e.subscribe(l,"chrome"),[e]),n=p.useSyncExternalStore(t,e.getState,e.getState),r=We(l=>l.initializeApp),s=We(l=>l.isInitialized),o=We(l=>l.isConnected),i=We(l=>l.loadProviders),a=We(l=>l.providers.length);return TL({connection:n.connection,isInitialized:s,isConnected:o,initializeApp:r}),p.useEffect(()=>{!n.directory||n.connection!=="ready"||!o||a===0&&i({source:"webApp:recovery"})},[o,i,n.connection,n.directory,a]),null};function LX({embeddedBackgroundWorkEnabled:e}){return XN(),yL(),KN(),bL(),c.jsxs(c.Fragment,{children:[c.jsx(PL,{}),c.jsx(LL,{embeddedBackgroundWorkEnabled:e}),c.jsx(RL,{}),c.jsx(NL,{}),c.jsx(IL,{})]})}const n3=({text:e})=>c.jsx("span",{"aria-hidden":"true",className:"oc-shimmer-clip",children:c.jsx("span",{className:"oc-shimmer-band","data-shimmer-text":e})}),DL=Array.from({length:9},(e,t)=>{const n=Math.floor(t/3);return(t%3+Math.abs(n-1))*90}),OL=650;function zf({compact:e=!1}){return c.jsx("span",{"aria-hidden":"true",className:e?"grid shrink-0 grid-cols-[repeat(3,3px)] gap-[1px]":"grid shrink-0 grid-cols-[repeat(3,4px)] gap-[1.5px]",children:DL.map((t,n)=>c.jsx("span",{className:e?"pixel-loader-cell size-[3px] rounded-full bg-current":"pixel-loader-cell size-[4px] rounded-full bg-current",style:{opacity:.15,animation:`pixel-on ${OL}ms ease-in-out ${t}ms infinite`}},n))})}function HL(e,t){const[n,r]=p.useState(0),[s]=p.useState(()=>Date.now());if(p.useEffect(()=>{if(!e||t===null)return;const a=setInterval(()=>r(l=>l+1),100);return()=>clearInterval(a)},[e,t]),!e||t===null)return null;const o=t??s,i=Math.max(0,(Date.now()-o)/1e3);return i<60?`${i.toFixed(1)}s`:`${Math.floor(i/60)}m ${(i%60).toFixed(1)}s`}const q2=({text:e="Thinking",className:t,variant:n="inline",showText:r=!0,showElapsed:s=!0,animateText:o=!1,startedAt:i})=>{const a=r&&e!=null&&e!=="",l=HL(a&&s,i),d=a?c.jsxs("span",{className:R("pixel-loader-label min-w-0 truncate whitespace-nowrap typography-markdown font-medium",o&&"agent-thinking-label-enter"),children:[e,c.jsx(n3,{text:e})]},o?e:void 0):null,f=a&&s&&l!==null?c.jsx("span",{className:"shrink-0 whitespace-nowrap font-mono typography-code text-muted-foreground tabular-nums",children:l}):null;return n==="badge"?c.jsxs("span",{className:R("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-normal","bg-primary/10 text-primary border border-primary/20","transition-opacity duration-300",t),role:"status","aria-live":"polite",children:[c.jsx(zf,{compact:!a}),d,f]}):n==="full"?c.jsxs("div",{className:R("flex items-center gap-2.5 rounded-lg border border-primary/25 bg-primary/5 px-3 py-1.5 text-sm text-foreground",t),role:"status","aria-live":"polite",children:[c.jsx(zf,{compact:!a}),d,f]}):c.jsxs("span",{className:R("inline-flex min-w-0 items-center gap-2.5",t),role:"status","aria-live":"polite",children:[c.jsx(zf,{compact:!a}),d,f]})},W2="pichamber:chunk-import-reload",FL=250,BL=3e4,VL=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function r3(e){if(e instanceof Error)return`${e.name}
63
+ ${e.message}
64
+ ${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function K2(e){const t=r3(e);return VL.some(n=>n.test(t))}function $L(e){return`1.0.6-rc.2:${r3(e).slice(0,500)}`}function zL(e){if(typeof window>"u")return;const t=Date.now(),n=$L(e);let r=null;try{const o=window.sessionStorage.getItem(W2);if(o)try{r=JSON.parse(o)}catch{r=null}}catch{return}const s=typeof r?.timestamp=="number"?r.timestamp:0;if(!(r?.signature===n&&t-s<BL)){try{window.sessionStorage.setItem(W2,JSON.stringify({signature:n,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function UL(e,t={}){const n=t.retries??1;let r;for(let s=0;s<=n;s+=1)try{return await e()}catch(o){if(r=o,!K2(o)||s>=n)break;await new Promise(i=>setTimeout(i,FL*(s+1)))}throw K2(r)&&zL(r),r}const Rs=e=>H.lazy(()=>UL(e)),qL=Rs(()=>Bm().then(e=>({default:e.MarkdownRenderer}))),WL=Rs(()=>Bm().then(e=>({default:e.SimpleMarkdownRenderer}))),KL=c.jsx("div",{className:"break-words w-full min-w-0"}),GL=e=>e==="tool"?"markdown-content markdown-tool":e==="reasoning"?"markdown-content markdown-reasoning":"markdown-content leading-relaxed",s3=e=>!un()||typeof e.content!="string"||e.content.length===0?KL:c.jsx("div",{className:R("break-words w-full min-w-0 whitespace-pre-wrap",GL(e.variant),typeof e.className=="string"?e.className:void 0),children:e.content}),Bo=e=>c.jsx(p.Suspense,{fallback:c.jsx(s3,{...e}),children:c.jsx(qL,{...e})}),Oa=e=>c.jsx(p.Suspense,{fallback:c.jsx(s3,{...e}),children:c.jsx(WL,{...e})}),ZL=m5(["border-input flex items-center justify-between gap-2 rounded-md border bg-transparent","typography-ui-label whitespace-nowrap shadow-none outline-none text-left","hover:bg-interactive-hover data-[popup-open]:bg-interactive-active","focus-visible:outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","disabled:cursor-not-allowed disabled:opacity-50","[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='text-'])]:text-muted-foreground"].join(" "),{variants:{size:{sm:"h-6 min-h-6 px-2 [&_svg:not([class*='size-'])]:size-3.5",default:"h-8 min-h-8 px-3 [&_svg:not([class*='size-'])]:size-4"}},defaultVariants:{size:"default"}}),n1=H.createContext(null),YL=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function G2({onValueChange:e,modal:t=!1,...n}){const[r,s]=H.useState(null),o=H.useMemo(()=>({portalContainer:r,setPortalContainer:s}),[r]),i=H.useCallback((a,l)=>{typeof a=="string"&&e?.(a,l)},[e]);return c.jsx(n1.Provider,{value:o,children:c.jsx(RC,{...n,modal:t,onValueChange:i})})}function XL({...e}){return c.jsx(UC,{"data-slot":"select-group",...e})}function Z2({placeholder:e,children:t,...n}){return c.jsx(OC,{"data-slot":"select-value",...n,children:r=>{const s=typeof r=="string"||r===void 0?r:r===null?void 0:String(r);return typeof t=="function"?t(s):t??(s===void 0||s===""?e:s)}})}function Y2({className:e,size:t="default",children:n,asChild:r,onPointerDownCapture:s,onFocusCapture:o,...i}){const a=H.useContext(n1),l=H.useCallback(f=>{if(!a)return;const u=f instanceof HTMLElement?f:null;a.setPortalContainer(YL(u))},[a]),d=r&&H.isValidElement(n)?{render:n}:null;return c.jsx(PC,{"data-slot":"select-trigger","data-size":t,className:R(ZL({size:t==="settings"||t==="lg"?"default":"sm"}),"w-fit data-[placeholder]:text-muted-foreground aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2",e),onPointerDownCapture:f=>{l(f.currentTarget),s?.(f)},onFocusCapture:f=>{l(f.currentTarget),o?.(f)},...i,...d??{},children:d?void 0:c.jsxs(c.Fragment,{children:[n,c.jsx(DC,{children:c.jsx($,{name:"arrow-down-s",className:"size-4 opacity-50"})})]})})}function X2({className:e,children:t,position:n="popper",fitContent:r=!1,portalToBody:s=!1,sideOffset:o,side:i,align:a,...l}){const d=H.useContext(n1),f=n==="item-aligned",u=d?.portalContainer??null;return c.jsx(HC,{container:s?void 0:u||void 0,children:c.jsx(FC,{alignItemWithTrigger:f,sideOffset:o,side:i,align:a,className:"absolute z-[120] pointer-events-auto",children:c.jsx(BC,{"data-slot":"select-content",style:{color:"var(--surface-elevated-foreground)"},className:R("oc-glass-popover oc-glass-floating pointer-events-auto transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 relative z-[120] max-h-[var(--oc-select-max-height,var(--available-height))] min-w-[8rem] origin-[var(--transform-origin)] overflow-x-hidden rounded-xl","data-[side=top]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-top,0px))] data-[side=bottom]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-bottom,0px))]",!f&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r&&"w-max min-w-0",e),...l,children:c.jsx(Xn,{outerClassName:R("max-h-[var(--oc-select-max-height,var(--available-height))]",r?"w-max":"w-full"),className:R("p-1",!f&&(r?"w-max min-w-0 scroll-my-1":"w-full min-w-[var(--anchor-width)] scroll-my-1")),preventOverscroll:!0,children:t})})})})}function JL({className:e,...t}){return c.jsx(qC,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",e),...t})}function J2({className:e,children:t,...n}){return c.jsxs(VC,{"data-slot":"select-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[selected]:bg-interactive-selection data-[selected]:text-interactive-selection-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-pointer items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[c.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:c.jsx($C,{children:c.jsx($,{name:"check",className:"size-4"})})}),c.jsx(zC,{children:t})]})}const Q2=e=>e.some(t=>t.source==="local"&&(t.uploadState?.status==="preparing"||t.uploadState?.status==="uploading")),QL=e=>e.some(t=>t.source==="local"&&t.uploadState?.status==="failed"),Uf=(e,t=Date.now())=>e.every(n=>n.source==="server"||n.uploadState?.status==="ready"&&n.uploadState.expiresAt>t),Tl=200,ey={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:600*1e3},o3=()=>Tl,eR=()=>Math.round(o3()*.6),tR={MAX_SESSIONS:ey.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(Tl*.6),HISTORICAL_MESSAGES:Tl,FETCH_BUFFER:20,HISTORY_CHUNK:Tl,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:ey.ZOMBIE_TIMEOUT},ty=()=>{const e=o3(),t=eR();return{...tR,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},nR=5e3,jn=new Map,_r=new Map,cr=new Map,ia=new Map,so=(e,t)=>`${e}
65
+ ${t?.trim()??""}`,jo=e=>{ia.set(e,(ia.get(e)??0)+1),_r.delete(e)},rR=e=>{const t=Y();if(typeof e=="string"&&e.trim().length>0){const r=so(t,e);jn.delete(r),jo(r);return}const n=new Set([...jn.keys(),..._r.keys(),...cr.keys()]);for(const r of n)r.startsWith(`${t}
66
+ `)&&(jn.delete(r),jo(r))},qf=e=>{const t=new Set([...jn.keys(),..._r.keys(),...cr.keys()]);for(const n of t)n.startsWith(`${e}
67
+ `)&&(jn.delete(n),jo(n))},zc=e=>e.snippets.map(t=>({id:t.id,name:t.name,content:t.content,aliases:t.aliases??[],...t.description?{description:t.description}:{},source:t.scope==="project"?"project":"global",...typeof t.directory=="string"?{directory:t.directory}:{}})),Pr=Lt()(mr((e,t)=>({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null,setSelectedSnippet:n=>e({selectedSnippetId:n}),setSnippetDraft:n=>e({snippetDraft:n}),resetForRuntimeSwitch:()=>{jn.clear(),_r.clear(),cr.clear(),ia.clear(),e({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null})},loadSnippets:async n=>{const r=Y(),s=so(r,n),o=Date.now(),i=cr.get(s);e({activeCacheKey:s,snippets:i??[],isLoading:!0});const a=jn.get(s)??0;if(a>0&&o-a<nR)return e({isLoading:!1}),!0;const l=_r.get(s);if(l)return l;const d=ia.get(s)??0,f=(async()=>{try{const u=await Ee.listSnippets(n,{runtimeKey:r});if(Y()!==r)return!1;if((ia.get(s)??0)!==d)return e(m=>m.activeCacheKey===s?{isLoading:!1}:m),!0;const h=zc(u);return cr.set(s,h),jn.set(s,Date.now()),e(m=>m.activeCacheKey===s?{snippets:h,isLoading:!1,...m.selectedSnippetId&&!h.some(g=>g.id===m.selectedSnippetId)?{selectedSnippetId:null}:{}}:m),!0}catch{return e(u=>u.activeCacheKey===s?{isLoading:!1}:u),!1}})();_r.set(s,f);try{return await f}finally{_r.get(s)===f&&_r.delete(s)}},createSnippet:async(n,r,s={})=>{const o=Y(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ee.createSnippet({name:n,content:r,...s.description!==void 0?{description:s.description}:{},...s.aliases!==void 0?{aliases:s.aliases}:{},scope:s.scope??"global",...i?{directory:i}:{}},{runtimeKey:o});if(Y()!==o)return!1;const l=so(o,i),d=zc(a);jo(l),cr.set(l,d),qf(o),jn.set(l,Date.now());const f=d.find(u=>u.name===n&&u.source===(s.scope??"global"));return e(u=>u.activeCacheKey===l?{snippets:d,snippetDraft:null,selectedSnippetId:f?.id??null,isLoading:!1}:u),!0}catch{return!1}},updateSnippet:async(n,r,s)=>{const o=Y(),i=t().snippets.find(l=>l.id===n);if(!i)return!1;const a=s?.trim()?s.trim():i.source==="project"&&i.directory?i.directory:void 0;try{const l=await Ee.updateSnippet(i.id,{...r.name!==void 0?{name:r.name}:{},...r.content!==void 0?{content:r.content}:{},...r.description!==void 0?{description:r.description}:{},...r.aliases!==void 0?{aliases:r.aliases}:{},...r.scope!==void 0?{scope:r.scope}:{},...r.directory!==void 0?{directory:r.directory}:{}},a,{runtimeKey:o});if(Y()!==o)return!1;const d=so(o,a),f=zc(l);return jo(d),cr.set(d,f),qf(o),jn.set(d,Date.now()),e(u=>u.activeCacheKey===d?{snippets:f,isLoading:!1}:u),!0}catch{return!1}},deleteSnippet:async(n,r)=>{const s=Y(),o=t().snippets.find(a=>a.id===n);if(!o)return!1;const i=r?.trim()?r.trim():o.source==="project"&&o.directory?o.directory:void 0;try{const a=await Ee.deleteSnippet(o.id,i,{runtimeKey:s});if(Y()!==s)return!1;const l=so(s,i),d=zc(a);return jo(l),cr.set(l,d),qf(s),jn.set(l,Date.now()),e(f=>f.activeCacheKey===l?{snippets:d,isLoading:!1,...f.selectedSnippetId===n?{selectedSnippetId:null}:{}}:f),!0}catch{return!1}},expandText:(n,r)=>{if(!n||!n.includes("#"))return n;const s=so(Y(),r),o=cr.get(s)??(t().activeCacheKey===s?t().snippets:[]),i=new Map,a=[...o].sort((l,d)=>+(d.source==="project")-+(l.source==="project"));for(const l of a){const d=l.name.toLowerCase();i.has(d)||i.set(d,l.content);for(const f of l.aliases??[]){const u=f.toLowerCase();i.has(u)||i.set(u,l.content)}}return i.size===0?n:n.replace(/(^|\s)#([A-Za-z0-9][A-Za-z0-9_-]*)/g,(l,d,f)=>{const u=i.get(f.toLowerCase());return u!==void 0?`${d}${u}`:l})},getSnippetByName:n=>t().snippets.find(r=>r.name===n)}),{name:"snippets-store"})),RX=Object.freeze(Object.defineProperty({__proto__:null,invalidateSnippetsLoadCache:rR,useSnippetsStore:Pr},Symbol.toStringTag,{value:"Module"}));function i3(e){const t=e.split(".").pop()?.toLowerCase(),n=e.split("/").pop()?.toLowerCase()||"",r={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return r[n]?r[n]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"html",heex:"html",leex:"html",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[t||""]||null}const sR=["drawio","dio"];function a3(e){const t=e.split(".").pop()?.toLowerCase();return sR.includes(t||"")}const c3=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function PX(e){const t=e.split(".").pop()?.toLowerCase();return c3.includes(t||"")}function DX(e){return e.split(".").pop()?.toLowerCase()==="pdf"}function oR(e){return e.toLowerCase().endsWith(".svg")}const iR=new Set(["pdf","doc","docx","xls","xlsx","ppt","pptx","odt","ods","odp","zip","rar","7z","gz","tgz","tar","bz2","xz","jar","war","apk","dmg","iso","deb","rpm","msi",...c3.filter(e=>e!=="svg"),"mp3","mp4","m4a","aac","flac","ogg","wav","wma","avi","mov","mkv","webm","wmv","ttf","otf","woff","woff2","eot","exe","dll","so","dylib","bin","class","o","a","lib","wasm","node","sqlite","sqlite3","db","dat","parquet","feather","pickle","pyc","pyo","lockb"]);function aR(e){const t=e.split(/[/\\]/).pop()??e,n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n+1).toLowerCase()}function OX(e){if(oR(e))return!1;const t=aR(e);return iR.has(t)}function HX(e){if(!e)return!1;const t=e.length>8192?e.slice(0,8192):e;if(t.includes("\0")||t.startsWith("%PDF")||t.startsWith("PK")||t.startsWith("PK")||t.startsWith("PK\x07\b"))return!0;let n=0;for(let r=0;r<t.length;r+=1){const s=t.charCodeAt(r);if(s===65533){n+=1;continue}(s<9||s>13&&s<32||s===127)&&(n+=1)}return t.length>0&&n/t.length>.1}function FX(e){const t=e.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[t||""]||"image/png"}const cR={read:{displayName:"Read File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"offset",label:"Start Line",type:"text"},{key:"limit",label:"Lines to Read",type:"text"}]},write:{displayName:"Write File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit File",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace All",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},apply_patch:{displayName:"Apply Patch",category:"file",outputLanguage:"diff",inputFields:[{key:"patchText",label:"Patch",type:"code",language:"diff"}]},bash:{displayName:"Shell Command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include Pattern",type:"pattern"}]},glob:{displayName:"Find Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List Directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore Patterns",type:"pattern"}]},task:{displayName:"Agent Task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent Type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"numResults",label:"Results Count",type:"text"},{key:"type",label:"Search Type",type:"text"}]},codesearch:{displayName:"Code Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update Todo List",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo Items",type:"code",language:"json"}]},todoread:{displayName:"Read Todo List",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill Name",type:"text"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]},lsp:{displayName:"LSP",category:"code",outputLanguage:"json",inputFields:[{key:"operation",label:"Operation",type:"text"},{key:"filePath",label:"File Path",type:"file"},{key:"line",label:"Line",type:"text"},{key:"character",label:"Character",type:"text"},{key:"query",label:"Query",type:"text"}]},pichamber:{displayName:"PiChamber",category:"system",outputLanguage:"json",inputFields:[]},plan_enter:{displayName:"Plan Mode",category:"ai",outputLanguage:"text",inputFields:[]},plan_exit:{displayName:"Build Mode",category:"ai",outputLanguage:"text",inputFields:[]},StructuredOutput:{displayName:"Structured Output",category:"ai",outputLanguage:"json",inputFields:[]},structuredoutput:{displayName:"Structured Output",category:"ai",outputLanguage:"json",inputFields:[]}};function lR(e){return e.trim().replace(/[_-]+/g," ").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function Ha(e){return cR[e]||{displayName:lR(e),category:"system",outputLanguage:"text",inputFields:[]}}function dR(e,t,n){const r=Ha(e);if(r.outputLanguage==="auto"){if(n?.filePath||n?.file_path||n?.sourcePath){const s=n.filePath||n.file_path||n.sourcePath,o=i3(s);if(o)return o}if(e==="webfetch"){if(t.trim().startsWith("{")||t.trim().startsWith("["))try{return JSON.parse(t),"json"}catch{}if(t.trim().startsWith("<"))return"html";if(t.includes("```"))return"markdown"}return"text"}return r.outputLanguage||"text"}function uR(e,t){if(!e)return"";const n=r=>{const s=e[r];return typeof s=="string"?s:typeof s=="number"?String(s):null};if(t==="bash"){const r=n("command");if(r)return r}if(t==="lsp"){const r=n("operation")||"lsp",s=n("filePath")||n("file_path")||n("path"),o=n("line"),i=n("character"),a=n("query"),l=o&&i?` (Line: ${o}; Character: ${i})`:"";if(r==="workspaceSymbol")return a?`Operation: ${r} (Query: "${a}")`:`Operation: ${r}`;const d=`Operation: ${r}${l}`;return s?`${d}
68
+ ${s}`:d}if(t==="task"){const r=n("prompt");if(r)return r;const s=n("description");if(s)return s}if(t==="apply_patch"&&typeof e=="object"){const r=n("patchText")||n("patch_text")||n("patch");if(r)return r}if((t==="edit"||t==="multiedit")&&typeof e=="object"){const r=n("filePath")||n("file_path")||n("path");if(r)return`File path: ${r}`}if(t==="write"&&typeof e=="object"){const r=n("content");if(r)return r}return typeof e=="object"?Object.entries(e).filter(([,s])=>s!=null&&s!=="").map(([s,o])=>{const i=s.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,l=>l.toUpperCase());let a=o;return typeof o=="object"?a=JSON.stringify(o,null,2):typeof o=="boolean"&&(a=o?"Yes":"No"),`${i}: ${a}`}).join(`
69
+ `):String(e)}const l3="p-1.5 max-w-[260px] overflow-hidden rounded-xl bg-popover/95 border border-border shadow-lg";function d3({imageUrl:e,filename:t,metaLine:n}){return e?c.jsxs("div",{children:[c.jsx("img",{src:e,alt:t,loading:"lazy",decoding:"async",className:"max-h-48 w-auto rounded-lg object-contain mx-auto"}),c.jsxs("div",{className:"mt-1 px-1 py-0.5",children:[c.jsx("p",{className:"truncate text-xs font-medium text-foreground",children:t}),n?c.jsx("p",{className:"text-[11px] text-muted-foreground",children:n}):null]})]}):c.jsxs("p",{children:[t,n?` (${n})`:""]})}const r1=new Set(["3d","3d_light","abap","abap_light","abc","abc_light","actionscript","actionscript_light","ada","ada_light","adobe-illustrator","adobe-illustrator_light","adobe-photoshop","adobe-photoshop_light","adobe-swc","adobe-swc_light","adonis","adonis_light","advpl","advpl_light","amplify","amplify_light","android","android_light","angular","angular_light","antlr","antlr_light","apiblueprint","apiblueprint_light","apollo","apollo_light","applescript","applescript_light","apps-script","apps-script_light","appveyor","appveyor_light","architecture","architecture_light","arduino","arduino_light","asciidoc","asciidoc_light","assembly","assembly_light","astro","astro_light","astro-config","astro-config_light","astyle","astyle_light","audio","audio_light","aurelia","aurelia_light","authors","authors_light","auto","auto_light","autohotkey","autohotkey_light","autoit","autoit_light","azure","azure_light","azure-pipelines","azure-pipelines_light","babel","babel_light","ballerina","ballerina_light","bazel","bazel_light","bbx","bbx_light","beancount","beancount_light","bench-js","bench-js_light","bench-jsx","bench-jsx_light","bench-ts","bench-ts_light","bibliography","bibliography_light","bibtex-style","bibtex-style_light","bicep","bicep_light","biome","biome_light","bitbucket","bitbucket_light","bithound","bithound_light","blender","blender_light","blink","blink_light","blitz","blitz_light","bower","bower_light","brainfuck","brainfuck_light","browserlist","browserlist_light","bruno","bruno_light","buck","buck_light","bucklescript","bucklescript_light","buildkite","buildkite_light","bun","bun_light","c","c_light","c3","c3_light","cabal","cabal_light","caddy","caddy_light","cadence","cadence_light","cairo","cairo_light","cake","cake_light","capacitor","capacitor_light","capnp","capnp_light","cbx","cbx_light","cds","cds_light","certificate","certificate_light","changelog","changelog_light","chess","chess_light","chrome","chrome_light","circleci","circleci_light","citation","citation_light","clangd","clangd_light","claude","claude_light","cline","cline_light","clojure","clojure_light","cloudfoundry","cloudfoundry_light","cmake","cmake_light","coala","coala_light","cobol","cobol_light","coconut","coconut_light","code-climate","code-climate_light","codecov","codecov_light","codeowners","codeowners_light","coderabbit-ai","coderabbit-ai_light","coffee","coffee_light","coldfusion","coldfusion_light","coloredpetrinets","coloredpetrinets_light","command","command_light","commitizen","commitizen_light","commitlint","commitlint_light","concourse","concourse_light","conduct","conduct_light","console","console_light","contentlayer","contentlayer_light","context","context_light","contributing","contributing_light","controller","controller_light","copilot","copilot_light","cpp","cpp_light","craco","craco_light","credits","credits_light","crystal","crystal_light","csharp","csharp_light","css","css_light","css-map","css-map_light","cucumber","cucumber_light","cuda","cuda_light","cursor","cursor_light","cypress","cypress_light","d","d_light","dart","dart_generated","dart_generated_light","dart_light","database","database_light","deepsource","deepsource_light","denizenscript","denizenscript_light","deno","deno_light","dependabot","dependabot_light","dependencies-update","dependencies-update_light","dhall","dhall_light","diff","diff_light","dinophp","dinophp_light","disc","disc_light","django","django_light","dll","dll_light","docker","docker_light","doctex-installer","doctex-installer_light","document","document_light","dotjs","dotjs_light","drawio","drawio_light","drizzle","drizzle_light","drone","drone_light","duc","duc_light","dune","dune_light","edge","edge_light","editorconfig","editorconfig_light","ejs","ejs_light","elixir","elixir_light","elm","elm_light","email","email_light","ember","ember_light","epub","epub_light","erlang","erlang_light","esbuild","esbuild_light","eslint","eslint_light","excalidraw","excalidraw_light","exe","exe_light","fastlane","fastlane_light","favicon","favicon_light","figma","figma_light","firebase","firebase_light","flash","flash_light","flow","flow_light","folder","folder_light","folder-admin","folder-admin_light","folder-admin-open","folder-admin-open_light","folder-android","folder-android_light","folder-android-open","folder-android-open_light","folder-angular","folder-angular_light","folder-angular-open","folder-angular-open_light","folder-animation","folder-animation_light","folder-animation-open","folder-animation-open_light","folder-ansible","folder-ansible_light","folder-ansible-open","folder-ansible-open_light","folder-api","folder-api_light","folder-api-open","folder-api-open_light","folder-apollo","folder-apollo_light","folder-apollo-open","folder-apollo-open_light","folder-app","folder-app_light","folder-app-open","folder-app-open_light","folder-archive","folder-archive_light","folder-archive-open","folder-archive-open_light","folder-astro","folder-astro_light","folder-astro-open","folder-astro-open_light","folder-atom","folder-atom_light","folder-atom-open","folder-atom-open_light","folder-attachment","folder-attachment_light","folder-attachment-open","folder-attachment-open_light","folder-audio","folder-audio_light","folder-audio-open","folder-audio-open_light","folder-aurelia","folder-aurelia_light","folder-aurelia-open","folder-aurelia-open_light","folder-aws","folder-aws_light","folder-aws-open","folder-aws-open_light","folder-azure-pipelines","folder-azure-pipelines_light","folder-azure-pipelines-open","folder-azure-pipelines-open_light","folder-backup","folder-backup_light","folder-backup-open","folder-backup-open_light","folder-base","folder-base_light","folder-base-open","folder-base-open_light","folder-batch","folder-batch_light","folder-batch-open","folder-batch-open_light","folder-benchmark","folder-benchmark_light","folder-benchmark-open","folder-benchmark-open_light","folder-bibliography","folder-bibliography_light","folder-bibliography-open","folder-bibliography-open_light","folder-bicep","folder-bicep_light","folder-bicep-open","folder-bicep-open_light","folder-blender","folder-blender_light","folder-blender-open","folder-blender-open_light","folder-bloc","folder-bloc_light","folder-bloc-open","folder-bloc-open_light","folder-bower","folder-bower_light","folder-bower-open","folder-bower-open_light","folder-buildkite","folder-buildkite_light","folder-buildkite-open","folder-buildkite-open_light","folder-cart","folder-cart_light","folder-cart-open","folder-cart-open_light","folder-changesets","folder-changesets_light","folder-changesets-open","folder-changesets-open_light","folder-ci","folder-ci_light","folder-ci-open","folder-ci-open_light","folder-circleci","folder-circleci_light","folder-circleci-open","folder-circleci-open_light","folder-class","folder-class_light","folder-class-open","folder-class-open_light","folder-claude","folder-claude_light","folder-claude-open","folder-claude-open_light","folder-client","folder-client_light","folder-client-open","folder-client-open_light","folder-cline","folder-cline_light","folder-cline-open","folder-cline-open_light","folder-cloud-functions","folder-cloud-functions_light","folder-cloud-functions-open","folder-cloud-functions-open_light","folder-cloudflare","folder-cloudflare_light","folder-cloudflare-open","folder-cloudflare-open_light","folder-cluster","folder-cluster_light","folder-cluster-open","folder-cluster-open_light","folder-cobol","folder-cobol_light","folder-cobol-open","folder-cobol-open_light","folder-command","folder-command_light","folder-command-open","folder-command-open_light","folder-components","folder-components_light","folder-components-open","folder-components-open_light","folder-config","folder-config_light","folder-config-open","folder-config-open_light","folder-connection","folder-connection_light","folder-connection-open","folder-connection-open_light","folder-console","folder-console_light","folder-console-open","folder-console-open_light","folder-constant","folder-constant_light","folder-constant-open","folder-constant-open_light","folder-container","folder-container_light","folder-container-open","folder-container-open_light","folder-content","folder-content_light","folder-content-open","folder-content-open_light","folder-context","folder-context_light","folder-context-open","folder-context-open_light","folder-contract","folder-contract_light","folder-contract-open","folder-contract-open_light","folder-controller","folder-controller_light","folder-controller-open","folder-controller-open_light","folder-core","folder-core_light","folder-core-open","folder-core-open_light","folder-coverage","folder-coverage_light","folder-coverage-open","folder-coverage-open_light","folder-css","folder-css_light","folder-css-open","folder-css-open_light","folder-cursor","folder-cursor_light","folder-cursor-open","folder-cursor-open_light","folder-custom","folder-custom_light","folder-custom-open","folder-custom-open_light","folder-cypress","folder-cypress_light","folder-cypress-open","folder-cypress-open_light","folder-dart","folder-dart_light","folder-dart-open","folder-dart-open_light","folder-database","folder-database_light","folder-database-open","folder-database-open_light","folder-debug","folder-debug_light","folder-debug-open","folder-debug-open_light","folder-decorators","folder-decorators_light","folder-decorators-open","folder-decorators-open_light","folder-delta","folder-delta_light","folder-delta-open","folder-delta-open_light","folder-desktop","folder-desktop_light","folder-desktop-open","folder-desktop-open_light","folder-directive","folder-directive_light","folder-directive-open","folder-directive-open_light","folder-dist","folder-dist_light","folder-dist-open","folder-dist-open_light","folder-docker","folder-docker_light","folder-docker-open","folder-docker-open_light","folder-docs","folder-docs_light","folder-docs-open","folder-docs-open_light","folder-download","folder-download_light","folder-download-open","folder-download-open_light","folder-drizzle","folder-drizzle_light","folder-drizzle-open","folder-drizzle-open_light","folder-dump","folder-dump_light","folder-dump-open","folder-dump-open_light","folder-element","folder-element_light","folder-element-open","folder-element-open_light","folder-enum","folder-enum_light","folder-enum-open","folder-enum-open_light","folder-environment","folder-environment_light","folder-environment-open","folder-environment-open_light","folder-error","folder-error_light","folder-error-open","folder-error-open_light","folder-event","folder-event_light","folder-event-open","folder-event-open_light","folder-examples","folder-examples_light","folder-examples-open","folder-examples-open_light","folder-expo","folder-expo_light","folder-expo-open","folder-expo-open_light","folder-export","folder-export_light","folder-export-open","folder-export-open_light","folder-fastlane","folder-fastlane_light","folder-fastlane-open","folder-fastlane-open_light","folder-favicon","folder-favicon_light","folder-favicon-open","folder-favicon-open_light","folder-firebase","folder-firebase_light","folder-firebase-open","folder-firebase-open_light","folder-firestore","folder-firestore_light","folder-firestore-open","folder-firestore-open_light","folder-flow","folder-flow_light","folder-flow-open","folder-flow-open_light","folder-flutter","folder-flutter_light","folder-flutter-open","folder-flutter-open_light","folder-font","folder-font_light","folder-font-open","folder-font-open_light","folder-forgejo","folder-forgejo_light","folder-forgejo-open","folder-forgejo-open_light","folder-functions","folder-functions_light","folder-functions-open","folder-functions-open_light","folder-gamemaker","folder-gamemaker_light","folder-gamemaker-open","folder-gamemaker-open_light","folder-generator","folder-generator_light","folder-generator-open","folder-generator-open_light","folder-gh-workflows","folder-gh-workflows_light","folder-gh-workflows-open","folder-gh-workflows-open_light","folder-git","folder-git_light","folder-git-open","folder-git-open_light","folder-gitea","folder-gitea_light","folder-gitea-open","folder-gitea-open_light","folder-github","folder-github_light","folder-github-open","folder-github-open_light","folder-gitlab","folder-gitlab_light","folder-gitlab-open","folder-gitlab-open_light","folder-global","folder-global_light","folder-global-open","folder-global-open_light","folder-godot","folder-godot_light","folder-godot-open","folder-godot-open_light","folder-gradle","folder-gradle_light","folder-gradle-open","folder-gradle-open_light","folder-graphql","folder-graphql_light","folder-graphql-open","folder-graphql-open_light","folder-guard","folder-guard_light","folder-guard-open","folder-guard-open_light","folder-gulp","folder-gulp_light","folder-gulp-open","folder-gulp-open_light","folder-helm","folder-helm_light","folder-helm-open","folder-helm-open_light","folder-helper","folder-helper_light","folder-helper-open","folder-helper-open_light","folder-home","folder-home_light","folder-home-open","folder-home-open_light","folder-hook","folder-hook_light","folder-hook-open","folder-hook-open_light","folder-husky","folder-husky_light","folder-husky-open","folder-husky-open_light","folder-i18n","folder-i18n_light","folder-i18n-open","folder-i18n-open_light","folder-images","folder-images_light","folder-images-open","folder-images-open_light","folder-import","folder-import_light","folder-import-open","folder-import-open_light","folder-include","folder-include_light","folder-include-open","folder-include-open_light","folder-intellij","folder-intellij_light","folder-intellij-open","folder-intellij-open_light","folder-interceptor","folder-interceptor_light","folder-interceptor-open","folder-interceptor-open_light","folder-interface","folder-interface_light","folder-interface-open","folder-interface-open_light","folder-ios","folder-ios_light","folder-ios-open","folder-ios-open_light","folder-java","folder-java_light","folder-java-open","folder-java-open_light","folder-javascript","folder-javascript_light","folder-javascript-open","folder-javascript-open_light","folder-jinja","folder-jinja_light","folder-jinja-open","folder-jinja-open_light","folder-job","folder-job_light","folder-job-open","folder-job-open_light","folder-json","folder-json_light","folder-json-open","folder-json-open_light","folder-jupyter","folder-jupyter_light","folder-jupyter-open","folder-jupyter-open_light","folder-keys","folder-keys_light","folder-keys-open","folder-keys-open_light","folder-kubernetes","folder-kubernetes_light","folder-kubernetes-open","folder-kubernetes-open_light","folder-kusto","folder-kusto_light","folder-kusto-open","folder-kusto-open_light","folder-layout","folder-layout_light","folder-layout-open","folder-layout-open_light","folder-lefthook","folder-lefthook_light","folder-lefthook-open","folder-lefthook-open_light","folder-less","folder-less_light","folder-less-open","folder-less-open_light","folder-lib","folder-lib_light","folder-lib-open","folder-lib-open_light","folder-link","folder-link_light","folder-link-open","folder-link-open_light","folder-linux","folder-linux_light","folder-linux-open","folder-linux-open_light","folder-liquibase","folder-liquibase_light","folder-liquibase-open","folder-liquibase-open_light","folder-log","folder-log_light","folder-log-open","folder-log-open_light","folder-lottie","folder-lottie_light","folder-lottie-open","folder-lottie-open_light","folder-lua","folder-lua_light","folder-lua-open","folder-lua-open_light","folder-luau","folder-luau_light","folder-luau-open","folder-luau-open_light","folder-macos","folder-macos_light","folder-macos-open","folder-macos-open_light","folder-mail","folder-mail_light","folder-mail-open","folder-mail-open_light","folder-mappings","folder-mappings_light","folder-mappings-open","folder-mappings-open_light","folder-markdown","folder-markdown_light","folder-markdown-open","folder-markdown-open_light","folder-mercurial","folder-mercurial_light","folder-mercurial-open","folder-mercurial-open_light","folder-messages","folder-messages_light","folder-messages-open","folder-messages-open_light","folder-meta","folder-meta_light","folder-meta-open","folder-meta-open_light","folder-middleware","folder-middleware_light","folder-middleware-open","folder-middleware-open_light","folder-mjml","folder-mjml_light","folder-mjml-open","folder-mjml-open_light","folder-mobile","folder-mobile_light","folder-mobile-open","folder-mobile-open_light","folder-mock","folder-mock_light","folder-mock-open","folder-mock-open_light","folder-mojo","folder-mojo_light","folder-mojo-open","folder-mojo-open_light","folder-molecule","folder-molecule_light","folder-molecule-open","folder-molecule-open_light","folder-moon","folder-moon_light","folder-moon-open","folder-moon-open_light","folder-netlify","folder-netlify_light","folder-netlify-open","folder-netlify-open_light","folder-next","folder-next_light","folder-next-open","folder-next-open_light","folder-ngrx-store","folder-ngrx-store_light","folder-ngrx-store-open","folder-ngrx-store-open_light","folder-node","folder-node_light","folder-node-open","folder-node-open_light","folder-nuxt","folder-nuxt_light","folder-nuxt-open","folder-nuxt-open_light","folder-obsidian","folder-obsidian_light","folder-obsidian-open","folder-obsidian-open_light","folder-open","folder-open_light","folder-organism","folder-organism_light","folder-organism-open","folder-organism-open_light","folder-other","folder-other_light","folder-other-open","folder-other-open_light","folder-packages","folder-packages_light","folder-packages-open","folder-packages-open_light","folder-pdf","folder-pdf_light","folder-pdf-open","folder-pdf-open_light","folder-pdm","folder-pdm_light","folder-pdm-open","folder-pdm-open_light","folder-php","folder-php_light","folder-php-open","folder-php-open_light","folder-phpmailer","folder-phpmailer_light","folder-phpmailer-open","folder-phpmailer-open_light","folder-pipe","folder-pipe_light","folder-pipe-open","folder-pipe-open_light","folder-plastic","folder-plastic_light","folder-plastic-open","folder-plastic-open_light","folder-plugin","folder-plugin_light","folder-plugin-open","folder-plugin-open_light","folder-policy","folder-policy_light","folder-policy-open","folder-policy-open_light","folder-powershell","folder-powershell_light","folder-powershell-open","folder-powershell-open_light","folder-prisma","folder-prisma_light","folder-prisma-open","folder-prisma-open_light","folder-private","folder-private_light","folder-private-open","folder-private-open_light","folder-project","folder-project_light","folder-project-open","folder-project-open_light","folder-prompts","folder-prompts_light","folder-prompts-open","folder-prompts-open_light","folder-proto","folder-proto_light","folder-proto-open","folder-proto-open_light","folder-public","folder-public_light","folder-public-open","folder-public-open_light","folder-python","folder-python_light","folder-python-open","folder-python-open_light","folder-pytorch","folder-pytorch_light","folder-pytorch-open","folder-pytorch-open_light","folder-quasar","folder-quasar_light","folder-quasar-open","folder-quasar-open_light","folder-queue","folder-queue_light","folder-queue-open","folder-queue-open_light","folder-react-components","folder-react-components_light","folder-react-components-open","folder-react-components-open_light","folder-redux-reducer","folder-redux-reducer_light","folder-redux-reducer-open","folder-redux-reducer-open_light","folder-repository","folder-repository_light","folder-repository-open","folder-repository-open_light","folder-resolver","folder-resolver_light","folder-resolver-open","folder-resolver-open_light","folder-resource","folder-resource_light","folder-resource-open","folder-resource-open_light","folder-review","folder-review_light","folder-review-open","folder-review-open_light","folder-robot","folder-robot_light","folder-robot-open","folder-robot-open_light","folder-routes","folder-routes_light","folder-routes-open","folder-routes-open_light","folder-rules","folder-rules_light","folder-rules-open","folder-rules-open_light","folder-rust","folder-rust_light","folder-rust-open","folder-rust-open_light","folder-sandbox","folder-sandbox_light","folder-sandbox-open","folder-sandbox-open_light","folder-sass","folder-sass_light","folder-sass-open","folder-sass-open_light","folder-scala","folder-scala_light","folder-scala-open","folder-scala-open_light","folder-scons","folder-scons_light","folder-scons-open","folder-scons-open_light","folder-scripts","folder-scripts_light","folder-scripts-open","folder-scripts-open_light","folder-secure","folder-secure_light","folder-secure-open","folder-secure-open_light","folder-seeders","folder-seeders_light","folder-seeders-open","folder-seeders-open_light","folder-server","folder-server_light","folder-server-open","folder-server-open_light","folder-serverless","folder-serverless_light","folder-serverless-open","folder-serverless-open_light","folder-shader","folder-shader_light","folder-shader-open","folder-shader-open_light","folder-shared","folder-shared_light","folder-shared-open","folder-shared-open_light","folder-snapcraft","folder-snapcraft_light","folder-snapcraft-open","folder-snapcraft-open_light","folder-snippet","folder-snippet_light","folder-snippet-open","folder-snippet-open_light","folder-src","folder-src_light","folder-src-open","folder-src-open_light","folder-src-tauri","folder-src-tauri_light","folder-src-tauri-open","folder-src-tauri-open_light","folder-stack","folder-stack_light","folder-stack-open","folder-stack-open_light","folder-stencil","folder-stencil_light","folder-stencil-open","folder-stencil-open_light","folder-store","folder-store_light","folder-store-open","folder-store-open_light","folder-storybook","folder-storybook_light","folder-storybook-open","folder-storybook-open_light","folder-stylus","folder-stylus_light","folder-stylus-open","folder-stylus-open_light","folder-sublime","folder-sublime_light","folder-sublime-open","folder-sublime-open_light","folder-supabase","folder-supabase_light","folder-supabase-open","folder-supabase-open_light","folder-svelte","folder-svelte_light","folder-svelte-open","folder-svelte-open_light","folder-svg","folder-svg_light","folder-svg-open","folder-svg-open_light","folder-syntax","folder-syntax_light","folder-syntax-open","folder-syntax-open_light","folder-target","folder-target_light","folder-target-open","folder-target-open_light","folder-taskfile","folder-taskfile_light","folder-taskfile-open","folder-taskfile-open_light","folder-tasks","folder-tasks_light","folder-tasks-open","folder-tasks-open_light","folder-television","folder-television_light","folder-television-open","folder-television-open_light","folder-temp","folder-temp_light","folder-temp-open","folder-temp-open_light","folder-template","folder-template_light","folder-template-open","folder-template-open_light","folder-terraform","folder-terraform_light","folder-terraform-open","folder-terraform-open_light","folder-test","folder-test_light","folder-test-open","folder-test-open_light","folder-theme","folder-theme_light","folder-theme-open","folder-theme-open_light","folder-tools","folder-tools_light","folder-tools-open","folder-tools-open_light","folder-trash","folder-trash_light","folder-trash-open","folder-trash-open_light","folder-trigger","folder-trigger_light","folder-trigger-open","folder-trigger-open_light","folder-turborepo","folder-turborepo_light","folder-turborepo-open","folder-turborepo-open_light","folder-typescript","folder-typescript_light","folder-typescript-open","folder-typescript-open_light","folder-ui","folder-ui_light","folder-ui-open","folder-ui-open_light","folder-unity","folder-unity_light","folder-unity-open","folder-unity-open_light","folder-update","folder-update_light","folder-update-open","folder-update-open_light","folder-upload","folder-upload_light","folder-upload-open","folder-upload-open_light","folder-utils","folder-utils_light","folder-utils-open","folder-utils-open_light","folder-vercel","folder-vercel_light","folder-vercel-open","folder-vercel-open_light","folder-verdaccio","folder-verdaccio_light","folder-verdaccio-open","folder-verdaccio-open_light","folder-video","folder-video_light","folder-video-open","folder-video-open_light","folder-views","folder-views_light","folder-views-open","folder-views-open_light","folder-vm","folder-vm_light","folder-vm-open","folder-vm-open_light","folder-vscode","folder-vscode_light","folder-vscode-open","folder-vscode-open_light","folder-vue","folder-vue_light","folder-vue-directives","folder-vue-directives_light","folder-vue-directives-open","folder-vue-directives-open_light","folder-vue-open","folder-vue-open_light","folder-vuepress","folder-vuepress_light","folder-vuepress-open","folder-vuepress-open_light","folder-vuex-store","folder-vuex-store_light","folder-vuex-store-open","folder-vuex-store-open_light","folder-wakatime","folder-wakatime_light","folder-wakatime-open","folder-wakatime-open_light","folder-webpack","folder-webpack_light","folder-webpack-open","folder-webpack-open_light","folder-windows","folder-windows_light","folder-windows-open","folder-windows-open_light","folder-wordpress","folder-wordpress_light","folder-wordpress-open","folder-wordpress-open_light","folder-yarn","folder-yarn_light","folder-yarn-open","folder-yarn-open_light","folder-zeabur","folder-zeabur_light","folder-zeabur-open","folder-zeabur-open_light","font","font_light","forth","forth_light","fortran","fortran_light","foxpro","foxpro_light","freemarker","freemarker_light","fsharp","fsharp_light","fusebox","fusebox_light","gamemaker","gamemaker_light","garden","garden_light","gatsby","gatsby_light","gcp","gcp_light","gemfile","gemfile_light","gemini","gemini_light","gemini-ai","gemini-ai_light","git","git_light","github-actions-workflow","github-actions-workflow_light","github-sponsors","github-sponsors_light","gitlab","gitlab_light","gitpod","gitpod_light","gleam","gleam_light","gnuplot","gnuplot_light","go","go_gopher","go_gopher_light","go_light","go-mod","go-mod_light","godot","godot_light","godot-assets","godot-assets_light","gradle","gradle_light","grafana-alloy","grafana-alloy_light","grain","grain_light","graphcool","graphcool_light","graphql","graphql_light","gridsome","gridsome_light","groovy","groovy_light","grunt","grunt_light","gulp","gulp_light","h","h_light","hack","hack_light","hadolint","hadolint_light","haml","haml_light","handlebars","handlebars_light","hardhat","hardhat_light","harmonix","harmonix_light","haskell","haskell_light","haxe","haxe_light","hcl","hcl_light","helm","helm_light","heroku","heroku_light","hex","hex_light","histoire","histoire_light","hjson","hjson_light","horusec","horusec_light","hosts","hosts_light","hpp","hpp_light","html","html_light","http","http_light","huff","huff_light","hurl","hurl_light","husky","husky_light","i18n","i18n_light","idris","idris_light","ifanr-cloud","ifanr-cloud_light","image","image_light","imba","imba_light","installation","installation_light","ionic","ionic_light","istanbul","istanbul_light","jar","jar_light","java","java_light","javaclass","javaclass_light","javascript","javascript_light","javascript-map","javascript-map_light","jenkins","jenkins_light","jest","jest_light","jinja","jinja_light","jsconfig","jsconfig_light","json","json_light","jsr","jsr_light","julia","julia_light","jupyter","jupyter_light","just","just_light","karma","karma_light","kcl","kcl_light","key","key_light","keystatic","keystatic_light","kivy","kivy_light","kl","kl_light","knip","knip_light","kotlin","kotlin_light","kubernetes","kubernetes_light","kusto","kusto_light","label","label_light","laravel","laravel_light","latexmk","latexmk_light","lbx","lbx_light","lefthook","lefthook_light","lerna","lerna_light","less","less_light","liara","liara_light","lib","lib_light","lighthouse","lighthouse_light","lilypond","lilypond_light","lintstaged","lintstaged_light","liquid","liquid_light","lisp","lisp_light","livescript","livescript_light","lock","lock_light","log","log_light","lolcode","lolcode_light","lottie","lottie_light","lua","lua_light","luau","luau_light","lyric","lyric_light","makefile","makefile_light","markdoc","markdoc_light","markdoc-config","markdoc-config_light","markdown","markdown_light","markdownlint","markdownlint_light","markojs","markojs_light","mathematica","mathematica_light","matlab","matlab_light","maven","maven_light","mdsvex","mdsvex_light","mdx","mdx_light","mercurial","mercurial_light","merlin","merlin_light","mermaid","mermaid_light","meson","meson_light","minecraft","minecraft_light","minecraft-fabric","minecraft-fabric_light","mint","mint_light","mjml","mjml_light","mocha","mocha_light","modernizr","modernizr_light","mojo","mojo_light","moon","moon_light","moonscript","moonscript_light","mxml","mxml_light","nano-staged","nano-staged_light","ndst","ndst_light","nest","nest_light","netlify","netlify_light","next","next_light","nginx","nginx_light","ngrx-actions","ngrx-actions_light","ngrx-effects","ngrx-effects_light","ngrx-entity","ngrx-entity_light","ngrx-reducer","ngrx-reducer_light","ngrx-selectors","ngrx-selectors_light","ngrx-state","ngrx-state_light","nim","nim_light","nix","nix_light","nodejs","nodejs_alt","nodejs_alt_light","nodejs_light","nodemon","nodemon_light","npm","npm_light","nuget","nuget_light","nunjucks","nunjucks_light","nuxt","nuxt_light","nx","nx_light","objective-c","objective-c_light","objective-cpp","objective-cpp_light","ocaml","ocaml_light","odin","odin_light","opa","opa_light","opam","opam_light","openapi","openapi_light","otne","otne_light","oxlint","oxlint_light","packship","packship_light","palette","palette_light","panda","panda_light","parcel","parcel_light","pascal","pascal_light","pawn","pawn_light","payload","payload_light","pdf","pdf_light","pdm","pdm_light","percy","percy_light","perl","perl_light","php","php_elephant","php_elephant_light","php_elephant_pink","php_elephant_pink_light","php_light","php-cs-fixer","php-cs-fixer_light","phpstan","phpstan_light","phpunit","phpunit_light","pinejs","pinejs_light","pipeline","pipeline_light","pkl","pkl_light","plastic","plastic_light","playwright","playwright_light","plop","plop_light","pm2-ecosystem","pm2-ecosystem_light","pnpm","pnpm_light","poetry","poetry_light","postcss","postcss_light","posthtml","posthtml_light","powerpoint","powerpoint_light","powershell","powershell_light","pre-commit","pre-commit_light","prettier","prettier_light","prisma","prisma_light","processing","processing_light","prolog","prolog_light","prompt","prompt_light","proto","proto_light","protractor","protractor_light","pug","pug_light","puppet","puppet_light","puppeteer","puppeteer_light","purescript","purescript_light","python","python_light","python-misc","python-misc_light","pytorch","pytorch_light","qsharp","qsharp_light","quarto","quarto_light","quasar","quasar_light","quokka","quokka_light","qwik","qwik_light","r","r_light","racket","racket_light","raml","raml_light","razor","razor_light","rbxmk","rbxmk_light","rc","rc_light","react","react_light","react_ts","react_ts_light","readme","readme_light","reason","reason_light","red","red_light","redux-action","redux-action_light","redux-reducer","redux-reducer_light","redux-selector","redux-selector_light","redux-store","redux-store_light","regedit","regedit_light","remark","remark_light","remix","remix_light","renovate","renovate_light","replit","replit_light","rescript","rescript_light","rescript-interface","rescript-interface_light","restql","restql_light","riot","riot_light","roadmap","roadmap_light","roblox","roblox_light","robot","robot_light","robots","robots_light","rocket","rocket_light","rojo","rojo_light","rollup","rollup_light","rome","rome_light","routing","routing_light","rspec","rspec_light","rubocop","rubocop_light","ruby","ruby_light","ruff","ruff_light","rust","rust_light","salesforce","salesforce_light","san","san_light","sas","sas_light","sass","sass_light","sbt","sbt_light","scala","scala_light","scheme","scheme_light","scons","scons_light","screwdriver","screwdriver_light","search","search_light","semantic-release","semantic-release_light","semgrep","semgrep_light","sentry","sentry_light","sequelize","sequelize_light","serverless","serverless_light","settings","settings_light","shader","shader_light","silverstripe","silverstripe_light","simulink","simulink_light","siyuan","siyuan_light","sketch","sketch_light","slim","slim_light","slint","slint_light","slug","slug_light","smarty","smarty_light","sml","sml_light","snakemake","snakemake_light","snapcraft","snapcraft_light","snowpack","snowpack_light","snyk","snyk_light","solidity","solidity_light","sonarcloud","sonarcloud_light","spwn","spwn_light","stackblitz","stackblitz_light","stan","stan_light","steadybit","steadybit_light","stencil","stencil_light","stitches","stitches_light","storybook","storybook_light","stryker","stryker_light","stylable","stylable_light","stylelint","stylelint_light","stylus","stylus_light","sublime","sublime_light","subtitles","subtitles_light","supabase","supabase_light","svelte","svelte_light","svg","svg_light","svgo","svgo_light","svgr","svgr_light","swagger","swagger_light","sway","sway_light","swc","swc_light","swift","swift_light","syncpack","syncpack_light","systemd","systemd_light","table","table_light","tailwindcss","tailwindcss_light","taskfile","taskfile_light","tauri","tauri_light","taze","taze_light","tcl","tcl_light","teal","teal_light","templ","templ_light","template","template_light","terraform","terraform_light","test-js","test-js_light","test-jsx","test-jsx_light","test-ts","test-ts_light","tex","tex_light","textlint","textlint_light","tilt","tilt_light","tldraw","tldraw_light","tobi","tobi_light","tobimake","tobimake_light","todo","todo_light","toml","toml_light","travis","travis_light","tree","tree_light","trigger","trigger_light","tsconfig","tsconfig_light","tsdoc","tsdoc_light","tsil","tsil_light","tune","tune_light","turborepo","turborepo_light","twig","twig_light","twine","twine_light","typescript","typescript_light","typescript-def","typescript-def_light","typst","typst_light","umi","umi_light","uml","uml_light","unity","unity_light","unocss","unocss_light","url","url_light","uv","uv_light","vagrant","vagrant_light","vala","vala_light","vanilla-extract","vanilla-extract_light","varnish","varnish_light","vedic","vedic_light","velite","velite_light","velocity","velocity_light","vercel","vercel_light","verdaccio","verdaccio_light","verified","verified_light","verilog","verilog_light","vfl","vfl_light","video","video_light","vim","vim_light","virtual","virtual_light","visualstudio","visualstudio_light","vite","vite_light","vitest","vitest_light","vlang","vlang_light","vscode","vscode_light","vue","vue_light","vue-config","vue-config_light","vuex-store","vuex-store_light","wakatime","wakatime_light","wallaby","wallaby_light","wally","wally_light","watchman","watchman_light","webassembly","webassembly_light","webhint","webhint_light","webpack","webpack_light","wepy","wepy_light","werf","werf_light","windicss","windicss_light","wolframlanguage","wolframlanguage_light","word","word_light","wrangler","wrangler_light","wxt","wxt_light","xaml","xaml_light","xmake","xmake_light","xml","xml_light","yaml","yaml_light","yang","yang_light","yarn","yarn_light","zeabur","zeabur_light","zig","zig_light","zip","zip_light"]),bp="oc-file-type-icon-sprite-root",ny="http://www.w3.org/2000/svg";let s1=null,wi=null,aa=null;const dd=new Set,ca=new Set;let u3=0;const wp=new Set,ry=()=>u3,fR=e=>(wp.add(e),()=>{wp.delete(e)}),hR=()=>{u3+=1;for(const e of Array.from(wp))e()},pR=()=>mt(()=>import("./sprite-HGQGInUp.js"),[]);let mR=pR;const gR=e=>{const t=new Map;for(const n of e.matchAll(/<symbol\b[^>]*\bid="([^"]+)"[^>]*>[\s\S]*?<\/symbol>/g))t.set(n[1],n[0]);return t},f3=()=>{if(typeof document>"u"||!document.body)return null;const e=document.getElementById(bp),t=e?.querySelector("defs");if(t)return t;e?.remove(),dd.clear();const n=document.createElement("div");n.id=bp,n.setAttribute("aria-hidden","true"),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden";const r=document.createElementNS(ny,"svg");r.setAttribute("width","0"),r.setAttribute("height","0");const s=document.createElementNS(ny,"defs");return r.appendChild(s),n.appendChild(r),document.body.appendChild(n),s},yR=()=>typeof document>"u"||!document.body?!1:!!document.getElementById(bp)?.querySelector("defs"),o1=e=>{const t=f3();if(!t||dd.has(e)||!aa)return;const n=aa.get(e);if(n){dd.add(e),t.insertAdjacentHTML("beforeend",n);for(const r of n.matchAll(/href="#([^"]+)"/g))aa.has(r[1])&&o1(r[1])}},vR=e=>{if(!(dd.has(e)&&yR())){if(s1===null||aa===null){ca.add(e),h3().catch(()=>{});return}ca.delete(e),o1(e)}},xR=e=>{if(s1=e,aa=gR(e),ca.size>0&&f3()!==null){const t=Array.from(ca);ca.clear();for(const n of t)o1(n)}hR()},h3=()=>s1!==null?Promise.resolve():(wi||(wi=mR().then(e=>{wi=null,xR(typeof e=="string"?e:e.default)},()=>{throw wi=null,new Error("file-type sprite failed to load")})),wi),bR=()=>{if(typeof window>"u"||typeof document>"u")return;const e=()=>{h3().catch(()=>{})};if(typeof window.requestIdleCallback=="function"){window.requestIdleCallback(()=>e());return}window.setTimeout(e,0)};bR();const sy={dockerfile:"docker",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake","package-lock.json":"npm","yarn.lock":"yarn","pnpm-lock.yaml":"pnpm","bun.lock":"bun","bun.lockb":"bun","tsconfig.json":"tsconfig","jsconfig.json":"jsconfig",".gitignore":"git",".gitattributes":"git",".gitmodules":"git",".editorconfig":"editorconfig",".npmrc":"npm",".yarnrc":"yarn",".prettierrc":"prettier",".eslintrc":"eslint",".babelrc":"babel"},oy={javascript:"javascript",jsx:"react",typescript:"typescript",tsx:"react_ts",html:"html",handlebars:"handlebars",twig:"twig",liquid:"liquid",css:"css",scss:"sass",sass:"sass",less:"less",stylus:"stylus",json:"json",yaml:"yaml",toml:"toml",xml:"xml",ini:"settings",properties:"settings",bash:"console",powershell:"powershell",batch:"console",python:"python",ruby:"ruby",erb:"ruby",php:"php",java:"java",kotlin:"kotlin",scala:"scala",groovy:"groovy",c:"c",cpp:"cpp",objectivec:"objective-c",csharp:"csharp",fsharp:"fsharp",go:"go",rust:"rust",swift:"swift",dart:"dart",lua:"lua",perl:"perl",r:"r",julia:"julia",haskell:"haskell",elixir:"elixir",erlang:"erlang",clojure:"clojure",lisp:"lisp",scheme:"scheme",ocaml:"ocaml",reason:"reason",nim:"nim",zig:"zig",v:"vlang",crystal:"crystal",d:"d",sql:"database",graphql:"graphql",solidity:"solidity",nasm:"assembly",nix:"nix",hcl:"terraform",puppet:"puppet",latex:"tex",bibtex:"bibliography",markdown:"markdown",asciidoc:"asciidoc",text:"document",vim:"vim",makefile:"makefile",cmake:"cmake",diff:"diff",prisma:"prisma",protobuf:"proto",thrift:"document",wasm:"webassembly",glsl:"shader",hlsl:"shader",cg:"shader",apacheconf:"settings",nginx:"nginx"},iy={yml:"yaml",mdx:"mdx",md:"markdown",lock:"lock",env:"settings",zip:"zip",tgz:"zip",gz:"zip",rar:"zip","7z":"zip",png:"image",jpg:"image",jpeg:"image",gif:"image",svg:"svg",webp:"image",avif:"image",bmp:"image",ico:"favicon",mp3:"audio",wav:"audio",flac:"audio",ogg:"audio",mp4:"video",mov:"video",avi:"video",mkv:"video",webm:"video",pdf:"pdf",doc:"word",docx:"word",ppt:"powerpoint",pptx:"powerpoint"},ud="document",wR=(e,t)=>{if(!e)return t==="light"?`${ud}_light`:ud;if(t==="light"){const n=e.endsWith("_light")?e:`${e}_light`;return r1.has(n)?n:e}return e},SR=e=>typeof e=="string"&&e.trim().length>0,CR=(e,t)=>{const r=e.replace(/\\/g,"/").split("/").pop()?.toLowerCase()||"";if(sy[r])return sy[r];if(r.startsWith(".env"))return"settings";const s=i3(e);if(s&&oy[s])return oy[s];const o=SR(t)?t.toLowerCase():r.includes(".")&&r.split(".").pop()?.toLowerCase()||"";return o&&iy[o]?iy[o]:o&&r1.has(o)?o:ud},kR=(e,t)=>{const n=CR(e,t?.extension),r=r1.has(n)?n:ud,s=wR(r,t?.themeVariant);return vR(s),`#${s}`},hr=({filePath:e,extension:t,className:n})=>{const r=mw(),s=H.useSyncExternalStore(fR,ry,ry),o=r?.currentTheme.metadata.variant==="light"?"light":"dark",i=kR(e,{extension:t,themeVariant:o});return c.jsx("svg",{className:R("block h-4 w-4 flex-shrink-0",n),"aria-hidden":"true",focusable:"false",children:c.jsx("use",{href:i,xlinkHref:i},s)})},MR=e=>e===null?null:Math.min(100,Math.max(0,e));function IR({filename:e,progress:t}){const n=MR(t);return c.jsx("span",{role:"progressbar","aria-label":`Uploading ${e}`,"aria-valuemin":0,"aria-valuemax":100,...n!==null?{"aria-valuenow":n}:{},className:"relative block size-6 shrink-0",children:c.jsx("span",{className:"block size-6",style:n===null?void 0:{opacity:.35+.65*n/100,filter:`saturate(${n/100})`},children:c.jsx(hr,{filePath:e,className:"size-6 shrink-0"})})})}const ER=H.memo(()=>{const e=H.useRef(null),t=Ye(a=>a.addAttachedFile),n=te(a=>a.isMobile),r=n?"h-9 w-9":"h-7 w-7",s=n?"h-5 w-5":"h-[18px] w-[18px]",o=async a=>{await Promise.all(Array.from(a).map(async l=>{try{await t(l)}catch(d){console.error("File attach failed",d),Ce.error(d instanceof Error?d.message:"Failed to attach file")}}))},i=async a=>{const l=a.target.files;l&&(await o(l),e.current&&(e.current.value=""))};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:e,type:"file",multiple:!0,className:"hidden",onChange:i}),c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("button",{type:"button",onClick:()=>e.current?.click(),className:R("flex items-center justify-center rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring","hover:bg-muted text-muted-foreground",r),"aria-label":"Attach files",children:c.jsx($,{name:"attachment-2",className:s})})}),c.jsx(xt,{side:"top",children:c.jsx("p",{children:"Attach files"})})]})]})});ER.displayName="FileAttachmentButton";const jR=e=>!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,_R=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},p3=H.memo(({file:e,onRemove:t,onRetry:n,onShowPopup:r,gallery:s,galleryIndex:o})=>{const{isMobile:i,isTablet:a}=On(),l=i||a,d=e.uploadState,f=d?.status==="ready"&&d.expiresAt<=Date.now(),u=e.mimeType.startsWith("image/"),h=u&&e.previewUrl?e.previewUrl:u&&e.dataUrl.startsWith("data:image/")?e.dataUrl:u&&e.serverPath||"",m=_R(e.filename),g=jR(e.size),x=d?.status==="preparing"?"Preparing attachment":d?.status==="uploading"?"Uploading attachment":d?.status==="failed"||f?"Attachment upload failed":d?.status==="ready"?"Attachment ready":"Server attachment ready",b=d?.status==="uploading"?d.progress:null,S=d?.status==="uploading"||d?.status==="preparing",y=d?.status==="failed"?d.error:f?"Upload expired.":null,v=()=>{!r||!h||r({open:!0,title:e.filename||"Image",content:"",metadata:{tool:"image-preview",filename:e.filename,mime:e.mimeType,size:e.size},image:{url:h,mimeType:e.mimeType,filename:e.filename,size:e.size,gallery:s,index:o}})};return c.jsxs("article",{className:R("group relative min-w-0 overflow-hidden rounded-xl border w-full",y?"border-[var(--status-error)]/50 bg-[var(--status-error-background)]/40":"border-border/60 bg-[var(--surface-elevated)]"),children:[c.jsx("span",{className:"sr-only","aria-live":"polite",children:x}),c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("div",{role:h&&r?"button":void 0,tabIndex:h&&r?0:void 0,onClick:v,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),v())},className:R("flex min-h-14 items-center gap-2.5 px-3 py-2",y?"pr-14":"pr-8",h&&r&&"cursor-pointer select-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"),"aria-label":h?`Preview ${e.filename}`:void 0,children:[S?c.jsx(IR,{filename:e.filename,progress:b}):c.jsx(hr,{filePath:e.filename,extension:m,className:"size-6 shrink-0"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"truncate typography-ui-label text-foreground",title:e.filename,children:e.filename}),c.jsx("p",{className:"typography-meta text-muted-foreground",children:[m.toUpperCase(),g].filter(Boolean).join(" · ")})]})]})}),c.jsx(xt,{side:"top",className:R(h&&!y?l3:void 0),children:y?c.jsx("p",{children:y}):c.jsx(d3,{imageUrl:h||void 0,filename:e.filename,metaLine:h?[m.toUpperCase(),g].filter(Boolean).join(" · "):g})})]}),S?c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 overflow-hidden rounded-xl",children:c.jsx("span",{className:"attachment-upload-shimmer absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-foreground/10 to-transparent"})}):null,c.jsx(Se,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),t()},className:R("absolute right-1 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",l?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Remove ${e.filename}`,title:`Remove ${e.filename}`,children:c.jsx($,{name:"close",className:"size-3.5"})}),y?c.jsx(Se,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),n()},className:R("absolute right-8 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",l?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Retry upload of ${e.filename}`,title:"Retry upload",children:c.jsx($,{name:"refresh",className:"size-3.5"})}):null]})});p3.displayName="DraftAttachmentCard";const m3=H.memo(({onShowPopup:e,className:t,isInline:n=!1,isMobile:r=!1})=>{const s=Ye(h=>h.attachedFiles),o=Ye(h=>h.removeAttachedFile),i=Ye(h=>h.retryAttachmentUpload),[,a]=p.useState(0);if(p.useEffect(()=>{const h=s.reduce((g,x)=>x.uploadState?.status!=="ready"||x.uploadState.expiresAt<=Date.now()?g:g===null?x.uploadState.expiresAt:Math.min(g,x.uploadState.expiresAt),null);if(h===null)return;const m=setTimeout(()=>a(g=>g+1),Math.max(0,h-Date.now()+1));return()=>clearTimeout(m)},[s]),s.length===0)return null;const d=s.filter(h=>h.mimeType.startsWith("image/")).flatMap(h=>{const m=h.previewUrl||h.dataUrl||h.serverPath||"";return m?[{file:h,image:{url:m,mimeType:h.mimeType,filename:h.filename,size:h.size}}]:[]}),f=d.map(h=>h.image),u=new Map(d.map((h,m)=>[h.file.id,m]));return c.jsx("div",{className:R("grid w-full gap-2 grid-cols-2 sm:grid-cols-3",n?"px-1.5 pt-1.5 pb-1":r?"px-3 pt-2.5 pb-1.5":"px-3 pt-3 pb-1.5",t),"data-no-drawer-swipe":"true",children:s.map(h=>c.jsx(p3,{file:h,onRemove:()=>o(h.id),onRetry:()=>i(h.id),onShowPopup:e,gallery:f,galleryIndex:u.get(h.id)??0},h.id))})});m3.displayName="AttachedFilesList";const TR="application/vnd.github.issue-link",AR="application/vnd.github.pull-request-link",Wf=e=>e.mime===TR?"issue":e.mime===AR?"pr":null,i1=H.memo(({files:e,onShowPopup:t,compact:n=!1})=>{const r=e.filter(u=>u.type==="file"&&(u.mime||u.url)),s=u=>{if(!u)return"Unnamed file";const m=u.replace(/\\/g,"/").split("/");return m[m.length-1]||u},o=p.useCallback(u=>Wf(u)!==null&&typeof u.filename=="string"&&u.filename.trim().length>0?u.filename.trim():s(u.filename||u.url),[]),i=u=>!u||!Number.isFinite(u)||u<=0?"":u<1024?`${u} B`:u<1024*1024?`${(u/1024).toFixed(1)} KB`:`${(u/(1024*1024)).toFixed(1)} MB`,a=r.filter(u=>u.mime?.startsWith("image/")&&u.url),l=r.filter(u=>!u.mime?.startsWith("image/")),d=p.useMemo(()=>a.flatMap(u=>{if(!u.url)return[];const h=o(u)||"Image";return[{url:u.url,mimeType:u.mime,filename:h,size:u.size}]}),[a,o]),f=p.useCallback(u=>{if(!t)return;const h=d[u];if(!h?.url)return;const m=h.filename||"Image";t({open:!0,title:m,content:"",metadata:{tool:"image-preview",filename:m,mime:h.mimeType,size:h.size},image:{url:h.url,mimeType:h.mimeType,filename:m,size:h.size,gallery:d,index:u}})},[d,t]);return r.length===0?null:n?c.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[l.length>0&&c.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map((u,h)=>{const m=o(u),g=m.split(".").pop()||"",x=i(u.size),b=Wf(u);return c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:b&&u.url?c.jsxs("button",{type:"button",onClick:()=>{ka(u.url||"")},className:"inline-flex items-center bg-muted/30 border border-border/30 typography-meta gap-1 px-2 py-0.5 rounded-lg text-foreground hover:text-primary transition-colors",children:[b==="pr"?c.jsx($,{name:"git-pull-request",className:"text-muted-foreground h-3.5 w-3.5"}):c.jsx($,{name:"github",className:"text-muted-foreground h-3.5 w-3.5"}),c.jsx("div",{className:"overflow-hidden max-w-[220px]",children:c.jsx("span",{className:"truncate block",title:m,children:m})})]}):c.jsxs("div",{className:"inline-flex items-center bg-muted/30 border border-border/30 typography-meta gap-1 px-2 py-0.5 rounded-lg",children:[u.mime?.includes("pdf")?c.jsx($,{name:"file-pdf",className:"text-muted-foreground h-3.5 w-3.5"}):c.jsx(hr,{filePath:m,extension:g,className:"text-muted-foreground h-3.5 w-3.5"}),c.jsx("div",{className:"overflow-hidden max-w-[140px]",children:c.jsx("span",{className:"truncate block",title:m,children:m})})]})}),c.jsx(xt,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},`file-${u.url||u.filename||h}`)})}),a.length>0&&c.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-0.5 scrollbar-thin","data-no-drawer-swipe":"true",children:c.jsx("div",{className:"flex snap-x snap-mandatory gap-2",children:a.map((u,h)=>{const m=o(u)||"Image";return c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>f(h),className:"relative flex-none border border-border/40 bg-muted/10 overflow-hidden snap-start h-12 w-12 sm:h-14 sm:w-14 md:h-16 md:w-16 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[u.url?c.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:g=>{const x=g.target;x.style.visibility="hidden"}}):c.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:c.jsx($,{name:"file-image",className:"h-6 w-6"})}),c.jsx("span",{className:"sr-only",children:m})]})}),c.jsx(xt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u.url||u.filename||h}`)})})})]}):c.jsx("div",{className:R("grid gap-2",n?"grid-cols-1":"grid-cols-1 sm:grid-cols-2"),children:r.map((u,h)=>{const m=o(u),g=u.mime?.startsWith("image/"),x=i(u.size),b=Wf(u);if(g&&u.url)return c.jsxs("div",{className:"relative aspect-video rounded-lg border border-border/40 bg-muted/10 overflow-hidden group",children:[c.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy"}),c.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity"}),c.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-2 text-white opacity-0 group-hover:opacity-100 transition-opacity",children:[c.jsx("p",{className:"text-xs font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs opacity-80",children:x})]})]},u.url||`${m}-${h}`);if(b&&u.url)return c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{ka(u.url||"")},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[c.jsx("div",{className:"flex-shrink-0",children:b==="pr"?c.jsx($,{name:"git-pull-request",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):c.jsx($,{name:"github",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs text-muted-foreground",children:x})]})]})}),c.jsx(xt,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},u.url||`${m}-${h}`);const S=u.source,y=typeof S?.type=="string"?S.type:void 0,v=S&&typeof S.path=="string"?S.path:void 0,C=y==="file"&&v?v:u.url||"";return C&&a3(C)?c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{te.getState().navigateToDiagram(C)},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left cursor-pointer",n?"text-xs":"text-sm"),children:[c.jsx($,{name:"file",className:R("text-muted-foreground shrink-0",n?"h-3.5 w-3.5":"h-4 w-4")}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),c.jsx("p",{className:"text-xs text-status-info",children:"Open in diagram view"})]}),c.jsx($,{name:"external-link",className:R("text-muted-foreground shrink-0",n?"h-3 w-3":"h-3.5 w-3.5")})]})}),c.jsx(xt,{children:c.jsx("p",{children:"Open in diagram view"})})]},u.url||`${m}-${h}`):c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("button",{type:"button",onClick:()=>{t&&u.url&&t({open:!0,title:m,content:"",image:{url:u.url,mimeType:u.mime,filename:m}})},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[c.jsx("div",{className:"flex-shrink-0",children:u.mime?.startsWith("image/")?c.jsx($,{name:"file-image",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):u.mime?.includes("pdf")?c.jsx($,{name:"file-pdf",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):c.jsx($,{name:"file",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"font-medium truncate",children:m}),x&&c.jsx("p",{className:"text-xs text-muted-foreground",children:x})]})]})}),c.jsx(xt,{children:c.jsxs("p",{children:[m,x?` (${x})`:""]})})]},u.url||`${m}-${h}`)})})});i1.displayName="MessageFilesDisplay";const NR=H.memo(({urls:e,caption:t,onShowPopup:n})=>{if(e.length===0)return null;const r=()=>e.length===1?"grid-cols-1":e.length===2||e.length<=4?"grid-cols-2":"grid-cols-3";return c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:R("grid gap-2",r()),children:e.map((s,o)=>c.jsxs("button",{type:"button",onClick:()=>n?.({open:!0,title:t||`Image ${o+1} of ${e.length}`,content:"",image:{url:s,gallery:e.map(i=>({url:i})),index:o}}),className:"relative aspect-square rounded-lg border border-border/40 bg-muted/10 overflow-hidden group",children:[c.jsx("img",{src:s,alt:t||`Image ${o+1}`,className:"h-full w-full object-cover transition-transform group-hover:scale-105",loading:"lazy"}),c.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors"})]},s))}),t&&c.jsx("p",{className:"text-sm text-muted-foreground italic",children:t})]})});NR.displayName="ImageGallery";const g3=H.memo(({message:e,target:t,sending:n,checking:r,canSteer:s,onEdit:o,onSend:i,onCheck:a})=>{const l=ft(C=>C.removeFromQueue),{attributes:d,listeners:f,setNodeRef:u,transform:h,transition:m,isDragging:g}=am({id:e.id}),x=p.useMemo(()=>{const C=e.content.split(`
70
+ `),w=C[0]||"",M=100;return w.length>M?w.substring(0,M)+"...":w+(C.length>1?"...":"")},[e.content]),b=e.attachments?.length??0,S=e.deliveryAttempt!==void 0,y=e.sendFailed===!0,v=n||r;return c.jsxs("div",{ref:u,style:{transform:cm.Translate.toString(h),transition:m},className:R("flex min-w-0 flex-col gap-1 py-1",g&&"z-10 opacity-60"),children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx("button",{type:"button",...d,...f,className:"flex flex-shrink-0 cursor-grab touch-none select-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing","aria-label":"Drag to reorder",children:c.jsx($,{name:"draggable",className:"h-4 w-4","aria-hidden":"true"})}),c.jsxs("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:[x||"(empty)",b>0&&c.jsx("span",{className:"ml-1 text-muted-foreground",children:b===1?"+1 file":`+${b} files`})]}),c.jsxs(Se,{type:"button",variant:"secondary",size:"xs",onClick:()=>o(e),disabled:v,children:[c.jsx($,{name:"edit",className:"h-3 w-3","aria-hidden":"true"}),"Edit"]}),S?c.jsxs(Se,{type:"button",variant:"secondary",size:"xs",onClick:()=>a(e),disabled:v,"aria-label":"Check delivery status",title:"Check delivery status",children:[c.jsx($,{name:"refresh",className:"h-3 w-3","aria-hidden":"true"}),"Check status"]}):s?c.jsxs(Se,{type:"button",variant:"secondary",size:"xs",onClick:()=>i(e),disabled:v,"aria-label":"Send now with Steering",title:"Send now with Steering",children:[c.jsx($,{name:"send-plane",className:"h-3 w-3","aria-hidden":"true"}),"Steer"]}):null,c.jsx("button",{type:"button",onClick:()=>l(t,e.id),disabled:v,className:"flex items-center justify-center h-6 w-6 flex-shrink-0 hover:bg-[var(--interactive-hover)] rounded-full transition-colors disabled:pointer-events-none disabled:opacity-50","aria-label":"Remove follow-up",children:c.jsx($,{name:"close",className:"h-4 w-4 text-muted-foreground"})})]}),(n||r||y||S)&&c.jsx("p",{className:R("typography-micro pl-6",y&&!n&&!r?"text-[var(--status-error)]":S&&!n&&!r?"text-[var(--status-warning)]":"text-muted-foreground"),role:y||S?"status":void 0,children:n?"Sending…":r?"Checking status…":y?"Send failed. Retry with Steer or remove.":"Delivery uncertain. Check status before retrying."})]})});g3.displayName="QueuedMessageChip";const ay=[],cy=[],y3=H.memo(({onEditMessage:e,onSendMessage:t})=>{const n=pe(k=>k.currentSessionId),r=Jd(n??""),s=pe(p.useCallback(k=>n?k.getDirectoryForSession(n):null,[n])),o=n?em(n,s):null,i=o?f5(o):null,a=ft(p.useCallback(k=>i?k.queuedMessages[i]??ay:ay,[i])),l=ft(p.useCallback(k=>i?k.sendingIds[i]??cy:cy,[i])),d=ft(k=>k.popToInput),f=ft(k=>k.reorderQueue),[u,h]=p.useState([]),m=n?`session:${n}`:"*",g=ze(k=>k.reducer.bySession,(k,E)=>{if(Object.is(k,E)||!n)return!0;const I=k.get(n)?.queue,N=E.get(n)?.queue;return!I&&!N?!0:!I||!N?!1:I.steering===N.steering&&I.followUp===N.followUp},m),x=n?g.get(n)?.queue:void 0,b=x?.steering??0,S=x?.followUp??0,y=b>0||S>0,v=!!o&&a.length>0,C=b===1?"1 steering message waiting":`${b} steering messages waiting`,w=S===1?"1 follow-up message waiting":`${S} follow-up messages waiting`,M=rm(ma(b5,{activationConstraint:{distance:8}}),ma(x5,{activationConstraint:{delay:200,tolerance:6}})),j=p.useCallback(k=>{const{active:E,over:I}=k;!I||E.id===I.id||!o||f(o,String(E.id),String(I.id))},[o,f]),T=p.useCallback(k=>{if(!o)return;const E=d(o,k.id);if(E){if(E.attachments&&E.attachments.length>0){const I=Ye.getState().attachedFiles;Ye.getState().setAttachedFiles([...I,...E.attachments])}e(E.content,E.attachments)}},[o,d,e]),A=p.useCallback(k=>{t(k.id)},[t]),_=p.useCallback(async k=>{if(!o||!i||u.includes(k.id)||l.includes(k.id))return;const I=ft.getState().queuedMessages[i]?.find(N=>N.id===k.id)?.deliveryAttempt??k.deliveryAttempt;if(I){h(N=>N.includes(k.id)?N:[...N,k.id]);try{const N=await QN(o,I);N==="accepted"?ft.getState().completeQueuedSend(o,k.id):N==="pending"?Ce.info("Delivery still pending. Follow-ups are on hold. Check again later."):Ce.warning("Delivery status unknown. The message stays on hold. No resend attempted.")}finally{h(N=>N.filter(O=>O!==k.id))}}},[o,i,u,l]);return!v&&!y?null:c.jsx("div",{className:"pb-2 w-full px-1",children:c.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[v&&o&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex w-full items-center gap-2 px-3 py-2 text-left",children:[c.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Follow-up messages"," ",a.length]}),r?c.jsx("span",{className:"ml-auto min-w-0 truncate typography-meta text-muted-foreground",children:`Sends after ${r}`}):c.jsx($,{name:"time",className:"ml-auto h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}),c.jsx(sm,{sensors:M,collisionDetection:om,onDragEnd:j,children:c.jsx(im,{items:a.map(k=>k.id),strategy:w5,children:c.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:a.map(k=>c.jsx(g3,{message:k,target:o,sending:l.includes(k.id),checking:u.includes(k.id),canSteer:!r,onEdit:T,onSend:A,onCheck:_},k.id))})})})]}),y&&c.jsxs("div",{className:R("px-3 typography-micro text-muted-foreground",v?"pb-3 pt-1":"py-2"),children:[b>0&&c.jsx("p",{role:"status",children:C}),S>0&&c.jsx("p",{role:"status",children:w})]})]})})});y3.displayName="QueuedMessageChips";let Kf=Date.now();const LR=()=>(Kf=Math.max(Kf+1,Date.now()),Kf),ly=()=>!(typeof document>"u"||document.visibilityState!=="visible"||typeof document.hasFocus=="function"&&!document.hasFocus());function RR({sessionId:e,directory:t,text:n,debounceMs:r=250}){const s=ze(m=>e?m.reducer.bySession.get(e)?.extensionDraftTracked===!0:!1,Object.is,e?`session:${e}`:"chrome"),o=s?n:null,i=H.useRef(n);i.current=n;const a=H.useRef(t);a.current=t;const l=H.useRef(e);l.current=e;const d=H.useRef(new Map),f=H.useRef(null),u=H.useRef(new Set);H.useEffect(()=>{if(!e)return;const m=u.current,g=d.current;return()=>{m.delete(e),g.delete(e)}},[e]);const h=H.useCallback((m,g)=>{if(!ly())return;d.current.set(m,g);const x=LR(),b=a.current;Ee.updateExtensionDraft({sessionId:m,text:g,revision:x,...b?{directory:b}:{}}).catch(()=>{d.current.get(m)===g&&d.current.delete(m)})},[]);H.useEffect(()=>{if(!e||!s)return;const m=()=>{if(!ly())return;const g=i.current,x=d.current.get(e);g!==x&&(f.current!==null&&(clearTimeout(f.current),f.current=null),h(e,g))};return typeof window<"u"&&typeof window.addEventListener=="function"&&window.addEventListener("focus",m),typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",m),()=>{typeof window<"u"&&typeof window.removeEventListener=="function"&&window.removeEventListener("focus",m),typeof document<"u"&&typeof document.removeEventListener=="function"&&document.removeEventListener("visibilitychange",m)}},[e,s,h]),H.useEffect(()=>{if(!e||o===null){e&&u.current.delete(e),f.current!==null&&(clearTimeout(f.current),f.current=null);return}if(!u.current.has(e)){u.current.add(e),f.current!==null&&(clearTimeout(f.current),f.current=null),h(e,o);return}const g=d.current.get(e);if(o===g){f.current!==null&&(clearTimeout(f.current),f.current=null);return}return f.current!==null&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null;const x=i.current,b=l.current;!b||x===d.current.get(b)||h(b,x)},r),()=>{f.current!==null&&(clearTimeout(f.current),f.current=null)}},[e,o,r,h])}const PR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.9568%209.88184H22.1265L30.7753%2031.7848H35.4917L26.9568%209.88184ZM13.028%209.88184L4.4917%2031.7848H9.32203L11.2305%2027.1793H20.2166L22.0126%2031.6724H26.8444L18.0832%209.88184H13.028ZM12.5783%2023.1361L15.4987%2015.3853L18.5315%2023.1361H12.5783Z'%20fill='currentColor'/%3e%3c/svg%3e",DR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37.9998%2023.021C33.7998%2025.2889%2029.5698%2027.3649%2024.8614%2028.3069C23.8114%2028.5154%2022.6474%2028.5154%2021.5809%2028.3714C20.5639%2028.2439%2020.0554%2027.3484%2020.4169%2026.4064C20.7619%2025.5289%2021.2209%2024.635%2021.8119%2023.9C23.0899%2022.3025%2024.5329%2020.849%2025.8289%2019.268C26.6203%2018.2991%2027.3335%2017.2689%2027.9618%2016.187C28.4208%2015.4205%2028.2078%2014.4935%2027.4038%2014.111C26.0584%2013.4556%2024.6154%2012.9936%2023.1889%2012.4986C23.0239%2012.4341%2022.7779%2012.6096%2022.4509%2012.7221C22.8604%2013.0881%2023.1559%2013.3596%2023.5654%2013.727C19.3339%2014.447%2015.3305%2015.467%2011.4455%2016.874C11.4275%2016.9535%2011.396%2017.0165%2011.411%2017.0495C11.9855%2017.927%2011.723%2018.5975%2010.886%2019.1405C10.5611%2019.3531%2010.2732%2019.6176%2010.034%2019.9235C12.593%2020.6735%2014.873%2020.243%2017.0539%2018.821C16.9234%2018.6305%2016.7914%2018.455%2016.6609%2018.263C17.4799%2018.407%2017.9719%2018.854%2018.0379%2019.556C18.0544%2019.7165%2017.9569%2019.8755%2017.9074%2020.036C17.7919%2019.907%2017.6449%2019.781%2017.5474%2019.6355C17.4799%2019.5395%2017.4634%2019.4285%2017.4154%2019.268C14.8235%2020.993%2012.035%2021.425%208.96751%2020.531C8.96751%2021.137%208.93451%2021.6485%208.98401%2022.1435C9.01701%2022.574%208.83701%2022.766%208.44401%2022.9895C7.55752%2023.5325%206.63803%2024.092%205.90003%2024.8105C5.01504%2025.6879%205.34354%2026.7589%206.54053%2027.2059C7.90102%2027.7159%209.329%2027.7309%2010.7555%2027.5569C12.4445%2027.3484%2014.1005%2027.0769%2015.9394%2026.8219C13.79%2027.8269%2011.6735%2028.5319%209.4445%2028.8169C7.88452%2029.0269%206.32753%2029.1379%204.78554%2028.6909C2.57156%2028.0684%201.58607%2026.4394%202.16057%2024.251C2.70206%2022.2065%204.01455%2020.5775%205.42454%2019.076C10.133%2014.078%2016.0864%2011.5401%2022.9744%2011.0286C24.5824%2010.9176%2026.2069%2011.1246%2027.7143%2011.7951C29.8308%2012.7536%2030.7173%2014.78%2029.6838%2016.826C29.0118%2018.1835%2028.0758%2019.4285%2027.1413%2020.6585C26.2234%2021.872%2025.1899%2022.9895%2024.2224%2024.155C23.9434%2024.506%2023.6809%2024.875%2023.4679%2025.2724C23.0569%2026.0224%2023.3359%2026.5174%2024.2059%2026.4394C26.0254%2026.2624%2027.8808%2026.1199%2029.6358%2025.6729C32.2098%2025.0174%2034.7193%2024.092%2037.2618%2023.2775C37.5243%2023.213%2037.7703%2023.117%2037.9998%2023.0225V23.021Z'%20fill='currentColor'/%3e%3c/svg%3e",OR="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eCursor%3c/title%3e%3cg%20transform='translate(12%2012)%20scale(0.88)%20translate(-12%20-12)'%3e%3cpath%20d='M22.106%205.68L12.5.135a.998.998%200%2000-.998%200L1.893%205.68a.84.84%200%2000-.419.726v11.186c0%20.3.16.577.42.727l9.607%205.547a.999.999%200%2000.998%200l9.608-5.547a.84.84%200%2000.42-.727V6.407a.84.84%200%2000-.42-.726zm-.603%201.176L12.228%2022.92c-.063.108-.228.064-.228-.061V12.34a.59.59%200%2000-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264%200%20.428.286.296.514z'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",HR="data:image/svg+xml,%3csvg%20fill='%23000000'%20viewBox='0%200%2033%2025'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M79.01%205.863c-4.066%200-6.511%202.92-6.511%206.535%200%203.635%202.445%206.555%206.511%206.555%204.046%200%206.512-2.92%206.512-6.555s-2.466-6.535-6.512-6.535Zm0%2010.968c-2.633%200-4.172-1.933-4.172-4.433s1.539-4.455%204.172-4.455c2.635%200%204.151%201.933%204.151%204.434%200%202.521-1.516%204.454-4.15%204.454Zm14.393%202.096c3.393%200%205.542-1.808%205.837-4.539h-2.36c-.316%201.555-1.517%202.437-3.477%202.437-2.423%200-3.878-1.68-3.878-4.433%200-2.774%201.476-4.434%203.878-4.434%201.96%200%203.14.862%203.477%202.5h2.36c-.295-2.773-2.444-4.622-5.837-4.622-3.856%200-6.217%202.669-6.217%206.535%200%203.887%202.36%206.556%206.217%206.556Zm-29.543-.311h2.36v-6.01c0-2.752%201.348-4.244%203.772-4.244h2.276V6.177h-2.255c-2.128%200-3.288.735-3.898%202.605l-.443-.063.527-2.542h-2.36v12.439h.02Zm-24.445-7.332c.106-2.101%201.517-3.53%203.793-3.53%202.276%200%203.646%201.345%203.646%203.53h-7.439Zm9.778.4c0-3.426-2.381-5.821-5.943-5.821-3.73%200-6.174%202.563-6.174%206.535%200%204.013%202.423%206.555%206.28%206.555%202.929%200%205.247-1.597%205.669-3.887h-2.36c-.507%201.156-1.666%201.828-3.31%201.828-2.38%200-3.877-1.408-3.94-3.803h9.694c.042-.588.084-.861.084-1.408Zm5.69%206.932h1.939l5.5-12.44h-2.529L56%2015.99l-.316.021-3.793-9.833h-2.508l5.5%2012.439ZM32.23%2012.35c0-.882-.359-1.701-.99-2.437a8.594%208.594%200%200%201-1.497%201.093c.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.281.021-14.118-2.059-14.118-4.811%200-.463.168-.925.505-1.345a8.13%208.13%200%200%201-1.475-1.093c-.632.736-.99%201.555-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.87.021%2016.078-2.5%2016.078-6.535Zm-3.351%201.534c-.906-.462-1.96-.861-3.16-1.197-1.37.378-2.909.672-4.553.861%202.318.294%204.341.778%205.9%201.408.76-.336%201.37-.693%201.813-1.072Zm-17.849-.357a31.902%2031.902%200%200%201-4.467-.84c-1.18.336-2.255.735-3.16%201.197.42.379%201.01.715%201.748%201.05%201.539-.63%203.52-1.113%205.88-1.407Zm21.2-6.808c0-4.013-7.207-6.534-16.079-6.534C7.26.185.051%202.706.051%206.719c0%204.035%207.208%206.535%2016.1%206.535%208.872.021%2016.079-2.5%2016.079-6.535Zm-1.94%200c0%202.732-5.836%204.812-14.139%204.812-8.302.021-14.14-2.06-14.14-4.812%200-2.731%205.838-4.811%2014.14-4.811%207.86%200%2014.14%202.08%2014.14%204.811Zm-3.223%202.564c.758-.336%201.37-.694%201.812-1.072-2.95-1.513-7.544-2.353-12.728-2.353s-9.799.84-12.728%202.353c.422.378%201.012.715%201.75%201.05%202.507-1.05%206.363-1.68%2010.978-1.68%204.404%200%208.324.651%2010.916%201.702ZM1.042%2015.628c-.632.736-.99%201.534-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.892%200%2016.099-2.521%2016.099-6.534%200-.883-.359-1.702-.99-2.438-.422.4-.907.757-1.497%201.093.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.302%200-14.14-2.08-14.14-4.811%200-.463.17-.925.506-1.345a10.73%2010.73%200%200%201-1.475-1.093Z'/%3e%3c/svg%3e",FR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M35.3993%2026.4544C34.2871%2028.3855%2027.8314%2032.9425%2020%2032.9425C12.1686%2032.9425%205.71288%2028.3855%204.60075%2026.4544C4.5427%2026.3532%204.50826%2026.2401%204.5%2026.1237V22.418C4.51199%2022.3209%204.53496%2022.2256%204.56846%2022.1338C5.04896%2020.9261%206.30833%2019.1733%207.93325%2018.7031C8.14896%2018.149%208.468%2017.3404%208.76508%2016.7437C8.71727%2016.2776%208.69485%2015.8094%208.69792%2015.3409C8.69792%2013.6217%209.06217%2012.113%2010.1601%2010.9906C10.6729%2010.4662%2011.3097%2010.0644%2012.064%209.76091C13.871%208.29357%2016.4453%207.05745%2019.9716%207.05745C23.4978%207.05745%2026.129%208.29357%2027.936%209.76091C28.6903%2010.0644%2029.3271%2010.4662%2029.8399%2010.9906C30.9378%2012.113%2031.3021%2013.6217%2031.3021%2015.3409C31.3021%2015.8162%2031.284%2016.2877%2031.2349%2016.7437C31.532%2017.3404%2031.851%2018.149%2032.0667%2018.7031C33.6917%2019.1733%2034.951%2020.9261%2035.4315%2022.1338C35.4677%2022.2248%2035.4908%2022.3205%2035.5%2022.418V26.1237C35.4917%2026.2401%2035.4573%2026.3532%2035.3993%2026.4544ZM20.2222%2018.7147H19.7778C19.6422%2018.945%2019.4889%2019.1644%2019.3193%2019.3709C18.3247%2020.5941%2016.8419%2021.2981%2014.7881%2021.2981C12.56%2021.2981%2010.9273%2020.8344%209.90304%2019.6719C9.86495%2019.6283%209.82833%2019.5835%209.79325%2019.5375L9.66667%2019.6719V28.1775C11.5202%2029.1837%2015.4972%2030.992%2020%2030.992C24.5028%2030.992%2028.4798%2029.1837%2030.3333%2028.1775V19.6719L30.2067%2019.5375C30.2067%2019.5375%2030.1641%2019.5957%2030.097%2019.6719C29.0727%2020.8344%2027.44%2021.2981%2025.2119%2021.2981C23.1581%2021.2981%2021.6753%2020.5941%2020.6807%2019.3709C20.5111%2019.1644%2020.3578%2018.945%2020.2222%2018.7147ZM23.2292%2022.9127C23.9383%2022.9127%2024.5208%2023.4952%2024.5208%2024.2043V26.7877C24.5208%2027.4968%2023.9383%2028.0793%2023.2292%2028.0793C22.52%2028.0793%2021.9375%2027.4968%2021.9375%2026.7877V24.2043C21.9375%2023.4952%2022.52%2022.9127%2023.2292%2022.9127ZM16.7708%2022.9127C17.48%2022.9127%2018.0625%2023.4952%2018.0625%2024.2043V26.7877C18.0625%2027.4968%2017.48%2028.0793%2016.7708%2028.0793C16.0617%2028.0793%2015.4792%2027.4968%2015.4792%2026.7877V24.2043C15.4792%2023.4952%2016.0617%2022.9127%2016.7708%2022.9127ZM21.0501%2014.9237C21.2258%2016.289%2021.5707%2017.3947%2022.1842%2018.149C22.7551%2018.8517%2023.649%2019.3606%2025.2119%2019.3606C27.2437%2019.3606%2028.1724%2018.9253%2028.6438%2018.3905C29.1398%2017.8287%2029.3646%2016.9051%2029.3646%2015.3409C29.3646%2013.8684%2029.0507%2012.9552%2028.454%2012.3455C27.8378%2011.7152%2026.7502%2011.2321%2024.8063%2011.0216C22.8856%2010.8136%2021.975%2011.1998%2021.5345%2011.7049C21.187%2012.1014%2020.97%2012.7485%2020.9688%2013.7431V13.7702C20.9688%2014.1121%2020.9959%2014.4966%2021.0501%2014.9237ZM18.9499%2014.9237C19.0041%2014.4966%2019.0312%2014.1117%2019.0312%2013.7689V13.7431C19.03%2012.7485%2018.813%2012.1014%2018.4655%2011.7049C18.025%2011.1998%2017.1144%2010.8136%2015.1937%2011.0216C13.2498%2011.2321%2012.1622%2011.7152%2011.546%2012.3455C10.9493%2012.9552%2010.6354%2013.8684%2010.6354%2015.3409C10.6354%2016.9051%2010.8615%2017.8287%2011.3562%2018.3905C11.8276%2018.9253%2012.7563%2019.3606%2014.7881%2019.3606C16.351%2019.3606%2017.2449%2018.8517%2017.8158%2018.149C18.4293%2017.3947%2018.7742%2016.289%2018.9499%2014.9237Z'%20fill='currentColor'/%3e%3c/svg%3e",BR="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",VR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37%2020.034C27.8809%2020.5837%2020.5808%2027.8809%2020.0326%2037H19.966C19.4163%2027.8809%2012.1177%2020.5837%203%2020.034V19.9674C12.1191%2019.4163%2019.4163%2012.1191%2019.966%203H20.0326C20.5822%2012.1191%2027.8809%2019.4163%2037%2019.9674V20.034Z'%20fill='currentColor'/%3e%3c/svg%3e",$R="/assets/kimi-for-coding-eVEHug_h.svg",zR="/assets/llmapi-detailed-Pup_107f.svg",UR="data:image/svg+xml,%3csvg%20width='72'%20height='72'%20viewBox='0%200%2072%2072'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20fill='white'%20stroke='black'%20stroke-width='3'%20stroke-linejoin='round'%3e%3cpath%20d='M12%2040L24%2034L36%2040V52L24%2059L12%2052V40Z'/%3e%3cpath%20d='M36%2040L48%2034L60%2040V52L48%2059L36%2052V40Z'/%3e%3c/g%3e%3cg%20stroke='black'%20stroke-width='3'%20stroke-linecap='round'%20stroke-linejoin='round'%3e%3cpath%20d='M12%2040L24%2046L36%2040M24%2046V59'/%3e%3cpath%20d='M36%2040L48%2046L60%2040M48%2046V59'/%3e%3c/g%3e%3ccircle%20cx='36'%20cy='25'%20r='16'%20fill='white'%20stroke='black'%20stroke-width='3'/%3e%3crect%20x='27'%20y='22'%20width='7'%20height='9'%20rx='1.5'%20fill='black'/%3e%3crect%20x='29.5'%20y='25'%20width='2'%20height='6'%20fill='white'/%3e%3crect%20x='38'%20y='22'%20width='7'%20height='9'%20rx='1.5'%20fill='black'/%3e%3crect%20x='40.5'%20y='25'%20width='2'%20height='6'%20fill='white'/%3e%3c/svg%3e",qR="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eLM%20Studio%3c/title%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h14.107a1.273%201.273%200%20100-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H22.04a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h14.106a1.274%201.274%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H15.38a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h14.106a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h9.698a1.273%201.273%200%20100-2.547h-9.698z'%20fill-opacity='.3'%3e%3c/path%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h10.287a1.274%201.274%200%20000-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H18.22a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H11.56a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h5.78a1.273%201.273%200%20100-2.547h-5.78z'%3e%3c/path%3e%3c/svg%3e",WR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",KR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",GR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.7,5.25l2.14-1.53,10.49,13.29-16.23,19.43-2.65,3L0.42,16.83l6.87-8.64,5.78,2.21,1.79-4.46L23.3,0.1l3.42,5.15ZM31.13,13.98L22.91,1.78l-7.1,4.95-5.45,13.53,20.77-6.28ZM36.74,15.57l-8.03-10.1-0.14-0.1-1.14,0.89,5.03,7.58,4.28,1.73ZM9.06,20.35l3.53-8.84-4.89-1.92-5.62,7.1,6.98,3.66ZM37.62,17.19l-5.3-2.14-9.22,19.52,14.52-17.38ZM30.95,15.24l-20.63,6.22,10.1,15.93,10.53-22.15ZM15.79,32.41l-6.86-10.82c-1.61-0.84-3.2-1.73-4.81-2.57-0.1-0.05-0.21-0.12-0.32-0.13l11.99,13.52Z'%20fill='currentColor'/%3e%3c/svg%3e",ZR="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOllama%3c/title%3e%3cpath%20d='M7.905%201.09c.216.085.411.225.588.41.295.306.544.744.734%201.263.191.522.315%201.1.362%201.68a5.054%205.054%200%20012.049-.636l.051-.004c.87-.07%201.73.087%202.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67%201.67%200%2001.589-.41c.257-.1.53-.118.796-.042.401.114.745.368%201.016.737.248.337.434.769.561%201.287.23.934.27%202.163.115%203.645l.053.04.026.019c.757.576%201.284%201.397%201.563%202.35.435%201.487.216%203.155-.534%204.088l-.018.021.002.003c.417.762.67%201.567.724%202.4l.002.03c.064%201.065-.2%202.137-.814%203.19l-.007.01.01.024c.472%201.157.62%202.322.438%203.486l-.006.039a.651.651%200%2001-.747.536.648.648%200%2001-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643%200%2001.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644%200%2001.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229%204.229%200%2000-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653%200%2001-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288%203.288%200%2000-1.772-.332c-1.245.099-2.343.801-2.67%201.686a.652.652%200%2001-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066%201.588a4.07%204.07%200%2000-.068%201.886c.112.558.331%201.02.582%201.269l.008.007c.212.207.257.53.109.785-.36.622-.629%201.549-.673%202.44-.05%201.018.186%201.902.719%202.536l.016.019a.643.643%200%2001.095.69c-.576%201.236-.753%202.252-.562%203.052a.652.652%200%2001-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339%204.339%200%2001-.598-1.309l-.005-.019a5.764%205.764%200%2001-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352%205.352%200%2001.093-2.49c.262-.915.777-1.701%201.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622%201.015-.737.266-.076.54-.059.797.042zm4.116%209.09c.936%200%201.8.313%202.446.855.63.527%201.005%201.235%201.005%201.94%200%20.888-.406%201.58-1.133%202.022-.62.375-1.451.557-2.403.557-1.009%200-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845%200-.707.398-1.417%201.056-1.946.668-.537%201.55-.849%202.485-.849zm0%20.896a3.07%203.07%200%2000-1.916.65c-.461.37-.722.835-.722%201.25%200%20.428.21.829.61%201.134.455.347%201.124.548%201.943.548.799%200%201.473-.147%201.932-.426.463-.28.7-.686.7-1.257%200-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662%201.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375%200%2001-.376.373.375.375%200%2001-.376-.373v-.46l-.271-.218a.347.347%200%2001-.052-.49.353.353%200%2001.494-.051l.215.172.22-.174a.353.353%200%2001.49.051zm-5.04-1.919c.478%200%20.867.39.867.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zm8.706%200c.48%200%20.868.39.868.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zM7.44%202.3l-.003.002a.659.659%200%2000-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216%201.631-.124%202.782.43-.128.899-.208%201.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628%200%2000-.107-.09L7.44%202.3zm9.174.04l-.002.001a.628.628%200%2000-.107.09c-.156.163-.32.45-.453.814-.29.794-.387%201.776-.23%202.572l.058.097.008.014h.03a5.184%205.184%200%20011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659%200%2000-.285-.239h-.004z'%3e%3c/path%3e%3c/svg%3e",YR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M32.8377%2017.282C33.2127%2016.25%2033.3072%2015.218%2033.2127%2014.1875C33.1197%2013.1571%2032.7447%2012.1251%2032.2752%2011.1876C31.4322%209.78209%2030.2127%208.6571%2028.8072%208.0001C27.3072%207.34461%2025.7127%207.15711%2024.1197%207.53211C23.3698%206.78212%2022.5253%206.12512%2021.5878%205.65713C20.6503%205.18913%2019.5253%205.00013%2018.4948%205.00013C16.8851%204.99074%2015.3125%205.48246%2013.9948%206.40712C12.6824%207.34311%2011.7449%208.6571%2011.2754%2010.1571C10.1504%2010.4376%209.21289%2010.9071%208.27539%2011.4696C7.4324%2012.1251%206.77541%2012.9696%206.21291%2013.8126C5.36992%2015.2195%205.08792%2016.8125%205.27542%2018.407C5.46399%2019.9968%206.11605%2021.496%207.1504%2022.718C6.79608%2023.7086%206.66795%2024.7659%206.77541%2025.8124C6.86991%2026.8444%207.2449%2027.8749%207.7129%2028.8124C8.55739%2030.2194%209.77538%2031.3444%2011.1824%2031.9999C12.6824%2032.6569%2014.2753%2032.8444%2015.8698%2032.4694C16.6198%2033.2194%2017.4628%2033.8749%2018.4003%2034.3444C19.3378%2034.8139%2020.4628%2034.9999%2021.4948%2034.9999C23.1043%2035.0097%2024.6769%2034.5185%2025.9947%2033.5944C27.3072%2032.6569%2028.2447%2031.3444%2028.7127%2029.8444C29.7719%2029.6432%2030.7682%2029.1934%2031.6197%2028.5319C32.4627%2027.8749%2033.2127%2027.1249%2033.6822%2026.1874C34.5251%2024.7819%2034.8071%2023.1875%2034.6196%2021.5945C34.4322%2020%2033.8697%2018.5015%2032.8377%2017.282ZM21.5878%2033.0304C20.0878%2033.0304%2018.9628%2032.5609%2017.9323%2031.7179C17.9323%2031.7179%2018.0253%2031.6234%2018.1198%2031.6234L24.1197%2028.1554C24.2862%2028.0803%2024.4196%2027.9469%2024.4947%2027.7804C24.5698%2027.636%2024.6021%2027.4731%2024.5877%2027.3109V18.875L27.1197%2020.375V27.3124C27.1455%2028.0547%2027.0215%2028.7945%2026.755%2029.4878C26.4885%2030.181%2026.085%2030.8134%2025.5687%2031.3473C25.0523%2031.8811%2024.4337%2032.3054%2023.7497%2032.5949C23.0658%2032.8843%2022.3305%2033.0314%2021.5878%2033.0304ZM9.49488%2027.8749C8.83789%2026.7499%208.55739%2025.4374%208.83789%2024.125C8.83789%2024.125%208.93239%2024.2195%209.02539%2024.2195L15.0253%2027.6874C15.1693%2027.7638%2015.3325%2027.7966%2015.4948%2027.7819C15.6823%2027.7819%2015.8698%2027.7819%2015.9628%2027.6874L23.2753%2023.4695V26.3749L17.1823%2029.9374C16.5506%2030.3042%2015.8527%2030.5427%2015.1287%2030.6393C14.4046%2030.7358%2013.6686%2030.6884%2012.9629%2030.4999C11.4629%2030.1249%2010.2449%2029.1874%209.49488%2027.8749ZM7.9004%2014.8445C8.56239%2013.7234%209.58826%2012.8627%2010.8074%2012.4056V19.532C10.8074%2019.718%2010.8074%2019.907%2010.9004%2020C10.9755%2020.1665%2011.1089%2020.2998%2011.2754%2020.375L18.5878%2024.5944L16.0573%2026.0944L10.0574%2022.625C9.41842%2022.2639%208.85742%2021.7797%208.40684%2021.2004C7.95627%2020.6211%207.62506%2019.9582%207.4324%2019.25C7.05741%2017.8445%207.1504%2016.157%207.9004%2014.8445ZM28.6197%2019.625L21.3073%2015.407L23.8377%2013.9071L29.8377%2017.375C30.7752%2017.9375%2031.5252%2018.6875%2031.9947%2019.625C32.4642%2020.5625%2032.7447%2021.5945%2032.6502%2022.7195C32.5603%2023.7755%2032.1699%2024.7837%2031.5252%2025.6249C30.8697%2026.4694%2030.0252%2027.1249%2028.9947%2027.4999V20.375C28.9947%2020.1875%2028.9947%2020%2028.9002%2019.907C28.9002%2019.907%2028.8072%2019.718%2028.6197%2019.625ZM31.1502%2015.875C31.1502%2015.875%2031.0572%2015.782%2030.9627%2015.782L24.9627%2012.3126C24.7752%2012.2196%2024.6822%2012.2196%2024.4947%2012.2196C24.3072%2012.2196%2024.1197%2012.2196%2024.0252%2012.3126L16.7128%2016.532V13.6251L22.8073%2010.0626C23.7448%209.50009%2024.7752%209.31259%2025.9002%209.31259C26.9322%209.31259%2027.9627%209.68759%2028.9002%2010.3446C29.7447%2011.0001%2030.4947%2011.8446%2030.8697%2012.7821C31.2447%2013.7196%2031.3377%2014.8445%2031.1502%2015.875ZM15.4003%2021.125L12.8699%2019.625V12.5946C12.8699%2011.5626%2013.1503%2010.4376%2013.7128%209.59459C14.2753%208.6571%2015.1198%208.0001%2016.0573%207.53211C17.0127%207.05249%2018.0956%206.88812%2019.1503%207.06261C20.1823%207.15711%2021.2128%207.62511%2022.0573%208.2821C22.0573%208.2821%2021.9628%208.3751%2021.8698%208.3751L15.8698%2011.8446C15.7033%2011.9197%2015.57%2012.0531%2015.4948%2012.2196C15.4003%2012.4071%2015.4003%2012.5001%2015.4003%2012.6876V21.125ZM16.7128%2018.125L19.9948%2016.25L23.2753%2018.125V21.875L19.9948%2023.75L16.7128%2021.875V18.125Z'%20fill='currentColor'/%3e%3c/svg%3e",XR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20fill='currentColor'/%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.6%207.43108L16.0037%2010.6622V4.20001L21.6%207.43108Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20fill='currentColor'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.4909%2016.7109L15.8945%2013.4798V19.942L21.4909%2016.7109Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3c/svg%3e",JR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cimage%20width='24'%20height='24'%20xlink:href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF0AAABcCAYAAAAMLblmAAAACXBIWXMAAAAAAAAAAQCEeRdzAAAHhklEQVR4nO1d21HjSBRtjJhvMhgtxlX8DRsBJgIggjERwESAiWAgAjwRYCJAGwHMH1U8VhvBst+89hxzRRkwuG+rJet1qlwSM1KrdXR1+nb37as5UzCEYbi4sLAQPj4+rs7NzX17enpaxI/7i8khs6xfWuA+1oNZV4IkB0Gwit0NEN1FpVaxHf0fyB5t8W8zrKF/zIT0hGiQuoc/uR1ZcdXI/Qi5kk6yW63WDsjdTYiuI3IhfXl5uQuSd7C7mcf1io5MSYdlh/Pz83sgvJfldcqGTEgflxH8WVsZ+QjeSRcpOTIld+2yhFfSl5aWfoLwXZ9lVhFeSKd2Q06O6WP7KG8CbvlD+TEeavz2P/HvIbfsRJkSyFlq0kVOjo3HmwWJEcr8jd0IvdPzi4uL2Pbcsc7WqMOFcrq+6uULqUiHnOzgpg58VESI/vXw8DCM4/jWtRw5N5LfqG7tdpuuKn/fPVQ1NZxJB+F7IKqf8vqUjMP7+/uDNERPw/X19RCbId6CPlzYLvbZEw6zut40OJHugfBcyH4LXCvGZsAfrL9nZkS+mnQPhA+h0z80Op0FYP0DWP4Q+r8rY0C5QUU6NTwF4THO3b66uoocz/cOecv6IH8A2Tk1OVm9Nenipbg2modoIPt5SokGIjt/4B77eVi9Fen0w6WXqQW1ex/W7cXDyRqoZ7/T6QwfHx/pAodZXceKdMdXL0aHaevy8vJcXasZgvWFja1nKTdTSWfD6XDxGI3l+qwbS1dQbkh8Vr3sT0kXHe8ryyw14QnGiD/1TfynpDvoeCUIT8CGH8Rv+ZaaD0l3kJVbanhVCE+QWDyIPzOexpcmkk5vReuP00spW6NpCxIPqd3Cm3/qo7yJpHOKTVnOYVncQlewU9dutw+xu5O2rHek08qx6SnKiNGlrsXEBe8TsruWtmF9R7rWytlwpqlA2QB+ttF5OktTxivSHax8ULWGcxrYbqWVmVekK62c7uG+64XLDI4jgStOiDh5M2/lxToYCLr2q25WnoD+O7yZQ9fBsRfSZVDf9snFQRAMXC5YFXACBtZOiVFb+7ila+YPo7paeYI01j4inTPo2HRtT6qrlr+Fq7WPSJfJWitw1r7uVp6A1g5ZPjHKKINEXjZsT2CYhOYCVQeMcABO9KSzh5WsepgGSEukr1p1IcMDnIa0lpiAei7haFOB41TRVjWCSmICWYZidTDeiL9ca1VlgJdzjcRQXjSDN5G6RjWAhARaHx/g4ND24FarFTvUqfKQ8RhrXQ/wlL7aPqWqTlL4gIRxW6lGYLvKjY1oumpVGxLabUe6sZwHhbQUMjqrQLDmh6TbWvp/ztWpASAvt7YybU068K9zjeoBlaU38ABYeUN6kdGQ7glMjaLRdNVgTYMPYT/gZSxJT9ZqNpgMTVaPwNbV0QwX1BGanj0tPTZ2PanQvUq1QGh7IIcB/rE9eGVlJWzG0yfDdtyFCGSgxurgh4eHrnleh9lgDJ1O5yXvmA0oL9YDWcwg51KpqkPLS3B/f38+Pz9vdTDeiDWnWlUcUIsN1SSGhBHExqIh4AQ251SLuh50VtBm2kh6pJxYtYpCDYKgZyS7RIOXxXD6YCOj0HVcgDEyDekCbcwLMSKdOVag67Yr6bqNxDzDIZ5/hBHpouuRsYxnZOYIbPrai1UNmnDEcbyMMqKRPLFtEJjYEg8511wtBUW6+HS4jgNZiWHTKCzW3dolnj90OfeFdJEYBodaeTF1tnbRcucUJa8mMSAxQ8mJawNmGeWFf7hevKwQRQhdz39FukSgRsayQWVaV/ipJ0XKVpQ1XD2WcbybruNyc00Pi0kbUI8/6yIzkpwhFd6RrrV2IKyLzDjmvnmHiRPTWmunzOBBnV9fX1d2lYZj7puJmEi6Y/KBg06n87uKQaYpcphNxIchGA6rgheZcGxlZaUySXYIDnnklmRH/PZt7B4rygvv7u5Oq0K8JN/3nkDt02Aj5qiVDpNmJK0SxCeE5544jYDM7OL14oxRqCi31MRnnQ9+KumUGTSQW9BrvmaawXoSf0aJkqzOpYB8PCXTFLBWsYyypoZ+uLYF50M6hn/bv7m5KfzSdtwjZZQTNJmGGVoHkDILM3zV0CUBAZOwgfjNL1++FDKbneg37yuXtFiqqF3mogXxxpH4VcjN30WzevmKwE+TYwSbOlQ6DfEErV7Govf59riU4QPSw+Q9dPO+tlN8elrizbNVHYF8nr/PfAN5yY5Y9s4sP1DivCjAA/FEiN8RZIdkDLB/koWnQ6s2z1+C6ZkCxOKnWolB4jnQZfxoYo8/lMf9SPIQRIxA0wwbj39yByR/w3azaF+ETL38hZaJGz337Nt25fXfY8gfl4Dzo1KMpTfPod1vwaUnoSxcsF6GMit4WXOUw+cNFqf1Dsv0AVmvC71E56Pmg4Gfw/vqOpkvze2jHmVEZksaafXyKZu+Kcjny4qCTNeRitb35PNlfdOQP0Iui3cnkK8dKq4Ucl0xnZDPffYM4XF8F9ewUH501pjZMvXky4ncl3EQPoQ1zSq1sqIQuQHE44mSv6Xbviodnq9GOj/m+Y0o/VvxPy8IndI+RM9sAAAAAElFTkSuQmCC'/%3e%3c/svg%3e",QR="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.50002L17.4088%2011.1913H5.81625L8.5375%207.50002H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.50002L16.58%2032.5H5L23.42%207.50002H35Z'%20fill='currentColor'/%3e%3c/svg%3e",eP="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.5L17.4088%2011.1912H5.81625L8.5375%207.5H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.5L16.58%2032.5H5L23.42%207.5H35Z'%20fill='currentColor'/%3e%3c/svg%3e",tP=Object.assign({"../assets/provider-logos/anthropic.svg":PR,"../assets/provider-logos/bailian-coding-plan.svg":DR,"../assets/provider-logos/cursor.svg":OR,"../assets/provider-logos/evroc.svg":HR,"../assets/provider-logos/github-copilot.svg":FR,"../assets/provider-logos/gocode.svg":BR,"../assets/provider-logos/google.svg":VR,"../assets/provider-logos/kimi-for-coding.svg":$R,"../assets/provider-logos/llmapi-detailed.svg":zR,"../assets/provider-logos/llmapi.svg":UR,"../assets/provider-logos/lmstudio.svg":qR,"../assets/provider-logos/minimax-cn-coding-plan.svg":WR,"../assets/provider-logos/minimax-coding-plan.svg":KR,"../assets/provider-logos/nano-gpt.svg":GR,"../assets/provider-logos/ollama.svg":ZR,"../assets/provider-logos/openai.svg":YR,"../assets/provider-logos/openrouter.svg":XR,"../assets/provider-logos/wafer.ai.svg":JR,"../assets/provider-logos/zai-coding-plan.svg":QR,"../assets/provider-logos/zhipuai-coding-plan.svg":eP}),Sp=new Map,Gf=new Map([["codex","openai"],["openai-codex","openai"],["openai_codex","openai"],["openai.codex","openai"],["chatgpt","openai"],["claude","anthropic"],["gemini","google"],["evroc-ai","evroc"],["evrocai","evroc"],["ollama-cloud","ollama"],["wafer-ai","wafer.ai"],["wafer","wafer.ai"]]),nP=e=>(e??"").toLowerCase().trim().replace(/^models\./,"").replace(/^provider\./,"").replace(/\s+/g,"-"),rP=e=>{const t=nP(e);if(!t)return[];const n=t.replace(/[^a-z0-9_\-./:]/g,""),r=n.split(/[/:]/)[0]||n,s=r.split(/[-_.]/)[0]||r,o=[Gf.get(n),Gf.get(r),Gf.get(s),t.includes("codex")?"openai":void 0,n,r,s].filter(i=>!!(i&&i.length>0));return[...new Set(o)]};for(const[e,t]of Object.entries(tP)){const n=e.match(/provider-logos\/([^/]+)\.svg$/i);n?.[1]&&t&&Sp.set(n[1].toLowerCase(),t)}function a1(e){const t=rP(e),n=t.find(d=>Sp.has(d))??null,r=t[0]??null,s=!!n,o=n?Sp.get(n)??null:null,[i,a]=H.useState(s?"local":"remote");H.useEffect(()=>{a(s?"local":"remote")},[s,n,r]);const l=H.useCallback(()=>{a(d=>d==="local"&&s?"remote":"none")},[s]);return!n&&!r?{src:null,onError:l,hasLogo:!1}:i==="local"&&o?{src:o,onError:l,hasLogo:!0}:i==="remote"&&r?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}}const Vo=({providerId:e,alt:t,className:n,onError:r})=>{const{src:s,onError:o,hasLogo:i}=a1(e),a=p.useCallback(()=>{o(),r?.()},[o,r]);return!i||!s?null:c.jsx("img",{src:s,alt:t||`${e} logo`,className:R("dark:invert object-contain",n),loading:"eager",decoding:"async",fetchPriority:"high",draggable:!1,onError:a})},dy=Lt()(Pd(e=>({collapsedSections:{},toggleSection:t=>e(n=>{const r={...n.collapsedSections};return r[t]?delete r[t]:r[t]=!0,{collapsedSections:r}})}),{name:"model-picker-collapsed-sections",version:1})),uy=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},c1=(e,t,n)=>{const r=uy(t.limit,"context"),s=uy(t.limit,"output"),o=r??n?.limit?.context,i=s??n?.limit?.output;return o===void 0&&i===void 0?n:{...n??{id:typeof t.id=="string"?t.id:"",providerId:e,name:typeof t.name=="string"?t.name:void 0},limit:{...n?.limit,...o!==void 0?{context:o}:{},...i!==void 0?{output:i}:{}}}},Ms=e=>typeof e=="string"?e.trim():"",fy=(e,t)=>!t||t<=0||e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`,sP={ai:"AI",api:"API",ernie:"ERNIE",glm:"GLM",gpt:"GPT",it:"IT",lfm:"LFM",lm:"LM",oss:"OSS",pdf:"PDF",rp:"RP",slerp:"SLERP",tars:"TARS",ui:"UI",vl:"VL",vlm:"VLM",aion:"Aion",anthropic:"Anthropic",chatgpt:"ChatGPT",claude:"Claude",codex:"Codex",codestral:"Codestral",command:"Command",deepseek:"DeepSeek",gemini:"Gemini",gemma:"Gemma",grok:"Grok",hunyuan:"Hunyuan",kimi:"Kimi",llama:"Llama",minimax:"MiniMax",mistral:"Mistral",mixtral:"Mixtral",nemotron:"Nemotron",openai:"OpenAI",qwen:"Qwen",rekaai:"RekaAI"},hy=e=>e?e[0].toUpperCase()+e.slice(1).toLowerCase():"",oP=e=>{const t=e.startsWith("~")?e.slice(1):e,n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t},iP=e=>{const t=e.lastIndexOf(":");return t<=0||t>=e.length-1?{base:e,suffix:""}:{base:e.slice(0,t),suffix:e.slice(t+1)}},aP=e=>{const t=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").split(/[-_\s]+/).map(r=>r.trim()).filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){const s=t[r],o=t[r+1],i=t[r+2];if(/^(19|20)\d{2}$/.test(s)&&/^\d{2}$/.test(o??"")&&/^\d{2}$/.test(i??"")){n.push(`${s}-${o}-${i}`),r+=2;continue}if(/^\d$/.test(s)&&/^\d$/.test(o??"")){n.push(`${s}.${o}`),r+=1;continue}n.push(s)}return n},cP=e=>{const t=e.toLowerCase(),n=sP[t];if(n)return n;const r=t.match(/^qwen(\d(?:\.\d+)?)$/);return r?`Qwen${r[1]}`:/^o\d/.test(t)?t:/^v\d/.test(t)?`V${e.slice(1).toUpperCase()}`:/^\d+[on]$/.test(t)?t:/^[a-z]\d+[a-z]?$/.test(t)?t.toUpperCase():/^\d+(?:x\d+)?[a-z]+$/.test(t)?t.replace(/[a-z]+$/i,s=>s.toUpperCase()):/^\d+(?:\.\d+)?[a-z]$/.test(t)?t.replace(/[a-z]$/i,s=>s.toUpperCase()):/^[a-z]+\d+(?:\.\d+)?[a-z]*$/.test(t)?hy(t).replace(/([a-z])(\d)/i,"$1$2"):hy(e)},lP=e=>{const t=[...e];return t[0]==="GPT"&&t[1]&&/^(?:\d|\d+[a-z]|OSS$)/i.test(t[1])&&t.splice(0,2,`GPT-${t[1]}`),t[0]==="GLM"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`GLM-${t[1]}`),t[0]==="LFM"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`LFM${t[1]}`),t[0]==="Qwen"&&t[1]&&/^\d/.test(t[1])&&t.splice(0,2,`Qwen${t[1]}`),t},dP=e=>{const t=Ms(e).toLowerCase();return t?t==="free"||t==="thinking"?t:v3(t):""},v3=e=>{const t=Ms(e);if(!t)return"";const{base:n,suffix:r}=iP(oP(t)),s=lP(aP(n).map(cP));if(s.length>=2){const l=s[s.length-1],d=s[s.length-2];l==="Reasoning"&&d==="Non"&&s.splice(s.length-2,2,"(Non-Reasoning)")}const o=s[s.length-1];/^(19|20)\d{2}-\d{2}-\d{2}$/.test(o??"")&&(s[s.length-1]=`(${o})`);const i=s.join(" ").replace(/\s+\(/g," (").trim(),a=dP(r);return a?`${i} (${a})`:i},l1=(e,t,n={})=>{const r=Ms(e?.name);if(r)return fy(r,n.maxLength);const s=Ms(e?.id)||Ms(t);return s?fy(v3(s),n.maxLength):n.fallbackLabel??""},uP=(e,t)=>{const n=e?.models;if(!(!n||!t))return Array.isArray(n)?n.find(r=>Ms(r.id)===t):n[t]},d1=(e,t,n={})=>{const r=Ms(t),s=uP(e,r);return l1(s,r,n)},fP=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),hP=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),Al=e=>l1(e,void 0,{maxLength:40}),pP=e=>{if(typeof e!="number"||Number.isNaN(e))return"";if(e===0)return"0";const t=fP(e);return t.endsWith(".0")?t.slice(0,-2):t},py=e=>typeof e!="number"||!Number.isFinite(e)?"—":hP(e),mP=e=>e?!!(e.tool_call||e.reasoning||e.cost?.input!==void 0||e.cost?.output!==void 0||(e.modalities?.input?.length??0)>0||(e.modalities?.output?.length??0)>0):!1,gP=({metadata:e,active:t,labels:n,children:r})=>{const[s,o]=p.useState(!1);if(p.useEffect(()=>{if(!t){o(!1);return}const d=window.setTimeout(()=>o(!0),450);return()=>window.clearTimeout(d)},[t]),!mP(e))return r;const i=e?.modalities?.input??[],a=e?.modalities?.output??[],l=[e?.tool_call?n.capabilityToolCalling:null,e?.reasoning?n.capabilityReasoning:null].filter(Boolean);return c.jsxs(yt,{delayDuration:0,open:t&&s,onOpenChange:()=>{},children:[c.jsx(vt,{asChild:!0,children:r}),t&&s?c.jsxs(xt,{side:"right",align:"center",sideOffset:8,className:"z-[999] p-2 typography-micro space-y-1.5 shadow-md border pointer-events-none",children:[l.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.capabilities||"Capabilities",": "]}),c.jsx("span",{className:"font-medium",children:l.join(", ")})]}):null,i.length>0||a.length>0?c.jsxs("div",{className:"space-y-0.5",children:[i.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.input||"Input",": "]}),c.jsx("span",{className:"font-medium",children:i.join(", ")})]}):null,a.length>0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.output||"Output",": "]}),c.jsx("span",{className:"font-medium",children:a.join(", ")})]}):null]}):null,e?.cost?.input!==void 0||e?.cost?.output!==void 0?c.jsxs("div",{children:[c.jsxs("span",{className:"text-muted-foreground",children:[n.costPerMillion||"Cost / 1M tokens",": "]}),c.jsxs("span",{className:"font-medium",children:[py(e?.cost?.input)," / ",py(e?.cost?.output)]})]}):null]}):null]})},yP=p.memo(({store:e,index:t,children:n})=>{const[r,s]=p.useState(()=>e.getSnapshot()===t);return p.useEffect(()=>{const o=()=>s(e.getSnapshot()===t);return o(),e.subscribeIndex(t,o)},[t,e]),c.jsx(c.Fragment,{children:n(r)})}),vP=({id:e,disabled:t=!1,children:n})=>{const{attributes:r,listeners:s,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:l,isDragging:d}=am({id:e,disabled:t});return c.jsx("div",{ref:o,style:{transform:cm.Transform.toString(a),transition:l},className:R(d&&"opacity-60"),children:n({attributes:r,listeners:s,setActivatorNodeRef:i,isDragging:d})})},xP=({entry:e,keyPrefix:t,showProviderLogo:n,rowIndex:r,dragHandleProps:s,selectionStore:o,modelsMetadata:i,selectedModel:a,disabled:l=!1,rowClassName:d,renderVersion:f,tooltipsEnabled:u=!0,labels:h,selectionCount:m,isFavorite:g,onToggleFavorite:x,onSelect:b,selectIndex:S,itemRefs:y,lastMousePositionRef:v,keyboardOwnsSelectionRef:C,reorderFavoriteAriaLabel:w,reorderFavoriteTitle:M,renderRowEnd:j})=>{const T=c1(e.providerID,e.model,i.get(`${e.providerID}/${e.modelID}`)),A=pP(T?.limit?.context),_=m?.(e)??0,k=a?.providerID===e.providerID&&a.modelID===e.modelID,E=g?.(e)??!1,I=N=>{const O={x:N.clientX,y:N.clientY},L=v.current,D=!L||L.x!==O.x||L.y!==O.y;v.current=O,!(C.current&&!L)&&(C.current&&!D||(C.current&&D&&(C.current=!1),S(r)))};return c.jsx(yP,{store:o,index:r,renderVersion:f,children:N=>{const O=c.jsxs("div",{ref:L=>{y.current[r]=L},role:"option","aria-selected":k,"aria-disabled":l||void 0,tabIndex:-1,onClick:()=>{l||b(e)},onKeyDown:L=>{l||(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),b(e))},onMouseEnter:I,onMouseMove:I,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!l&&(N?"bg-interactive-selection":"hover:bg-interactive-hover/50"),l&&"cursor-not-allowed opacity-60",d),children:[c.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[s?c.jsx("button",{type:"button",ref:s.setActivatorNodeRef,...s.attributes,...s.listeners,disabled:l,onClick:L=>{L.preventDefault(),L.stopPropagation()},className:"model-favorite-drag-handle flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground hover:text-foreground disabled:pointer-events-none","aria-label":w,title:M,children:c.jsx($,{name:"draggable",className:"size-3.5"})}):null,n?c.jsx(Vo,{providerId:e.providerID,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsx("span",{className:"font-medium truncate",children:Al(e.model)}),A?c.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:A}):null]}),_>0?c.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["x",_]}):null,j?.(e,{isHighlighted:N,isSelected:k}),k?c.jsx($,{name:"check",className:"h-4 w-4 text-primary flex-shrink-0"}):null,x?c.jsx("button",{type:"button",disabled:l,onClick:L=>{L.preventDefault(),L.stopPropagation(),x(e)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-primary/80 flex-shrink-0 disabled:pointer-events-none",E?"text-primary":"text-muted-foreground"),"aria-label":E?h.unfavorite:h.favorite,title:E?h.unfavorite:h.favorite,children:c.jsx($,{name:E?"star-fill":"star",className:"h-3.5 w-3.5"})}):null]});return c.jsx(gP,{metadata:T,active:u&&N,labels:h,children:O})}},`${t}-${e.providerID}-${e.modelID}`)},bP=(e=0)=>{let t=e;const n=new Set,r=new Map,s=o=>{const i=r.get(o);if(i)for(const a of i)a()};return{getSnapshot:()=>t,subscribe:o=>(n.add(o),()=>{n.delete(o)}),subscribeIndex:(o,i)=>{let a=r.get(o);return a||(a=new Set,r.set(o,a)),a.add(i),()=>{a?.delete(i),a&&a.size===0&&r.delete(o)}},set:o=>{if(t===o)return;const i=t;t=o,s(i),s(o);for(const a of n)a()}}},wP=48,SP=32,CP=24;function kP({providers:e,favoriteModels:t,recentModels:n,searchQuery:r,hiddenModels:s=[],allowedProviderIds:o,isModelAllowed:i,stickyHeaders:a=!0,scrollRef:l,collapsedSections:d}){const f=p.useRef(0),u=p.useMemo(()=>o?new Set(o):null,[o]),h=p.useMemo(()=>new Map(e.map(j=>[j.id,j])),[e]),m=p.useCallback((j,T)=>s.some(A=>A.providerID===j&&A.modelID===T),[s]),g=p.useCallback((j,T)=>{const A=r.trim().toLowerCase();return A?j.toLowerCase().includes(A)||T.toLowerCase().includes(A):!0},[r]),x=p.useMemo(()=>t.filter(({model:j,providerID:T,modelID:A})=>{if(u&&!u.has(T)||i&&!i(T,A)||m(T,A))return!1;const _=h.get(T)?.name||T;return g(Al(j),_)}),[u,t,m,i,g,h]),b=p.useMemo(()=>n.filter(({model:j,providerID:T,modelID:A})=>{if(u&&!u.has(T)||i&&!i(T,A)||m(T,A))return!1;const _=h.get(T)?.name||T;return g(Al(j),_)}),[u,m,i,g,h,n]),S=p.useMemo(()=>e.filter(j=>!u||u.has(j.id)).map(j=>{const A=(Array.isArray(j.models)?j.models:[]).filter(_=>{const k=typeof _.id=="string"?_.id:"";return!k||m(j.id,k)||i&&!i(j.id,k)?!1:g(Al(_),j.name||j.id)});return{...j,models:A}}).filter(j=>j.models.length>0),[u,m,i,g,e]),y=p.useMemo(()=>[...x.length>0?["favorites"]:[],...b.length>0?["recent"]:[],...S.map(j=>`provider:${j.id}`)],[x.length,S,b.length]),v=p.useCallback(j=>{const A=j.scrollTop>1?Math.min(SP+j.scrollTop,wP):0;f.current=A,j.style.setProperty("--scroll-shadow-top-size",`${A}px`),j.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(A-8,0),CP)}px`)},[]),C=p.useCallback(j=>{j.target.closest("[data-overlay-scrollbar-thumb], [data-model-picker-sticky-header]")||j.clientY-j.currentTarget.getBoundingClientRect().top>=f.current||(j.preventDefault(),j.stopPropagation())},[]);p.useLayoutEffect(()=>{a&&l.current&&v(l.current)},[l,a,v,y]);const w=p.useMemo(()=>{const j=[];return d.has("favorites")||x.forEach(T=>j.push(T)),d.has("recent")||b.forEach(T=>j.push(T)),S.forEach(T=>{d.has(`provider:${T.id}`)||T.models.forEach(A=>j.push({model:A,providerID:T.id,modelID:A.id}))}),j},[d,x,S,b]),M=p.useMemo(()=>new Map(x.map(j=>[`${j.providerID}:${j.modelID}`,j])),[x]);return{allowedProviderSet:u,providerById:h,filteredFavorites:x,filteredRecents:b,filteredProviders:S,visibleSectionKeys:y,flatModelList:w,favoriteLookup:M,syncStickyFade:v,blockStickyFadeInteraction:C}}const my=32,MP=(e,t)=>{if(!t)return;if(!e){t.scrollIntoView({block:"nearest"});return}const n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),s=r.top-n.top+e.scrollTop,o=s+r.height,i=e.scrollTop,a=i+e.clientHeight,l=i+my,d=s<l?s-my:o>a?o-e.clientHeight:i,f=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.max(0,Math.min(d,f))},IP=({providers:e,favoriteModels:t,recentModels:n,modelsMetadata:r,searchQuery:s,onSearchQueryChange:o,onSelect:i,labels:a,selectedModel:l,hiddenModels:d=[],allowedProviderIds:f,isModelAllowed:u,includeNotSelected:h=!1,onSelectNone:m,selectionCount:g,disabled:x=!1,maxHeightClassName:b="max-h-[min(400px,calc(100dvh-12rem))] flex-1",maxHeightStyle:S,sectionHeaderClassName:y,rowClassName:v,stickyHeaders:C=!0,autoFocus:w=!0,onEscape:M,isFavorite:j,onToggleFavorite:T,renderRowEnd:A,onActiveKeyDown:_,onActiveEntryChange:k,onVariantKey:E,onReorderFavorite:I,reorderFavoriteAriaLabel:N,reorderFavoriteTitle:O,renderVersion:L,tooltipsEnabled:D=!0})=>{const W=p.useRef(null);W.current||(W.current=bP());const z=W.current,J=p.useRef([]),B=p.useRef(null),U=p.useRef(!1),P=p.useRef(null),q=dy(ye=>ye.collapsedSections),F=dy(ye=>ye.toggleSection),ee=p.useMemo(()=>new Set(Object.keys(q).filter(ye=>q[ye])),[q]),G=rm(ma(WC,{activationConstraint:{distance:8}})),{filteredFavorites:K,filteredRecents:se,filteredProviders:ce,flatModelList:re,favoriteLookup:fe,syncStickyFade:ge,blockStickyFadeInteraction:we}=kP({providers:e,favoriteModels:t,recentModels:n,searchQuery:s,hiddenModels:d,allowedProviderIds:f,isModelAllowed:u,stickyHeaders:C,scrollRef:B,collapsedSections:ee}),Me=re.length>0,He=!!I&&s.trim().length===0&&K.length>1;p.useEffect(()=>{z.set(0)},[s,z]);const Ae=p.useCallback(ye=>{z.set(ye),k?.(re[ye])},[re,k,z]),Ge=p.useCallback(ye=>{const Ze=re.length;if(Ze===0)return;U.current=!0,P.current=null;const ie=(z.getSnapshot()+ye+Ze)%Ze;z.set(ie),k?.(re[ie]),requestAnimationFrame(()=>MP(B.current,J.current[ie]))},[re,k,z]);p.useEffect(()=>{k?.(re[z.getSnapshot()])},[re,k,z]);const et=p.useCallback(ye=>{if(!ye.defaultPrevented){if(ye.stopPropagation(),ye.key==="ArrowLeft"||ye.key==="ArrowRight"){const Ze=re[z.getSnapshot()];if(Ze&&E?.(ye,Ze))return}if(_?.(ye,re[z.getSnapshot()]),!ye.defaultPrevented){if(ye.key==="ArrowDown"){ye.preventDefault(),Ge(1);return}if(ye.key==="ArrowUp"){ye.preventDefault(),Ge(-1);return}if(ye.key==="Enter"){ye.preventDefault();const Ze=re[z.getSnapshot()];Ze&&!x&&i(Ze);return}ye.key==="Escape"&&(ye.preventDefault(),M?.())}}},[x,re,Ge,_,M,i,E,z]),Xe=R("typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 px-2 py-1.5",C&&"sticky top-0 z-20",y);let oe=0;const Q=(ye,Ze,Be,ie,ke)=>c.jsx(xP,{entry:ye,keyPrefix:Ze,showProviderLogo:Be,rowIndex:ie,dragHandleProps:ke,selectionStore:z,modelsMetadata:r,selectedModel:l,disabled:x,rowClassName:v,renderVersion:L,tooltipsEnabled:D,labels:a,selectionCount:g,isFavorite:j,onToggleFavorite:T,onSelect:i,selectIndex:Ae,itemRefs:J,lastMousePositionRef:P,keyboardOwnsSelectionRef:U,reorderFavoriteAriaLabel:N,reorderFavoriteTitle:O,renderRowEnd:A},`${Ze}-${ye.providerID}-${ye.modelID}`),ue=ye=>{if(!I)return;const{active:Ze,over:Be}=ye;if(!Be||Ze.id===Be.id)return;const ie=fe.get(String(Ze.id)),ke=fe.get(String(Be.id));!ie||!ke||I(ie,ke)},be=ye=>ee.has(ye),Ie=ye=>F(ye),Fe=(ye,Ze,Be)=>{const ie=be(ye),ke=ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),Ie(ye))};return c.jsxs("button",{type:"button","aria-expanded":!ie,"data-model-picker-sticky-header":C?"true":void 0,className:R(Xe,"w-full text-left"),onClick:()=>Ie(ye),onKeyDown:ke,children:[Ze,c.jsx("span",{className:"min-w-0 truncate",children:Be}),c.jsx("span",{className:"ml-auto flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",children:c.jsx($,{name:ie?"arrow-right-s":"arrow-down-s",className:"size-4"})})]})},ht=()=>ce.map(ye=>{const Ze=be(`provider:${ye.id}`);return c.jsxs("div",{className:"relative overflow-hidden",children:[Fe(`provider:${ye.id}`,c.jsx(Vo,{providerId:ye.id,className:"h-3.5 w-3.5 flex-shrink-0"}),ye.name||ye.id),Ze?null:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:ye.models.map(Be=>{const ie={model:Be,providerID:ye.id,modelID:Be.id},ke=oe;return oe+=1,Q(ie,ye.id,!1,ke)})})]},ye.id)});return c.jsxs("div",{className:"flex flex-col min-h-0",children:[c.jsx("div",{className:"p-2 border-b",children:c.jsx(Fo,{placeholder:a.searchPlaceholder,value:s,onChange:ye=>o(ye.target.value),onKeyDown:et,autoFocus:w,className:"h-8 typography-meta"})}),c.jsx("div",{className:"relative flex flex-col min-h-0",onMouseDown:we,onPointerDown:we,children:c.jsxs(Xn,{ref:B,className:R(b,"p-2 space-y-3 min-h-0"),style:S,onScroll:ye=>{C&&ge(ye.currentTarget)},children:[h&&m?c.jsx("div",{className:"pb-1 border-b mb-1",children:c.jsxs("button",{type:"button",disabled:x,onClick:m,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!x&&"hover:bg-interactive-hover/50",x&&"cursor-not-allowed opacity-60",v),children:[c.jsx("span",{className:"font-medium text-muted-foreground",children:a.notSelected||"Not Selected"}),l?null:c.jsx($,{name:"check",className:"h-4 w-4 text-primary ml-auto flex-shrink-0"})]})}):null,K.length>0?c.jsxs("div",{className:"relative overflow-hidden",children:[Fe("favorites",c.jsx($,{name:"star-fill",className:"h-3.5 w-3.5 text-primary flex-shrink-0"}),a.favorites),be("favorites")?null:He?c.jsx(sm,{sensors:G,collisionDetection:om,onDragEnd:ue,children:c.jsx(im,{items:K.map(ye=>`${ye.providerID}:${ye.modelID}`),strategy:w5,children:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:K.map(ye=>{const Ze=`${ye.providerID}:${ye.modelID}`,Be=oe;return oe+=1,c.jsx(vP,{id:Ze,disabled:x,children:ie=>Q(ye,"favorite",!0,Be,ie)},`favorite-${Ze}`)})})})}):c.jsx("div",{className:"space-y-0.5 mt-0.5",children:K.map(ye=>{const Ze=oe;return oe+=1,Q(ye,"favorite",!0,Ze)})})]}):null,se.length>0?c.jsxs("div",{className:"relative overflow-hidden",children:[Fe("recent",c.jsx($,{name:"history",className:"h-3.5 w-3.5 flex-shrink-0"}),a.recent),be("recent")?null:c.jsx("div",{className:"space-y-0.5 mt-0.5",children:se.map(ye=>{const Ze=oe;return oe+=1,Q(ye,"recent",!0,Ze)})})]}):null,ht(),Me?null:c.jsx("div",{className:"p-4 text-center typography-meta text-muted-foreground",children:a.noResults})]})})]})};function x3(){const e=Ue();return H.useMemo(()=>({ensureSessionRenderable:async t=>{if(!t)return;if(e.getState().selectedSessionId!==t){await e.select(t);return}await e.ensureHydrated(t)},syncSession:async t=>{if(!t)return;e.getState().selectedSessionId!==t&&await e.select(t)}}),[e])}const EP=()=>{const e=We(a=>a.providers),t=te(a=>a.favoriteModels),n=te(a=>a.recentModels),r=te(a=>a.hiddenModels),s=p.useCallback((a,l)=>r.some(d=>d.providerID===a&&d.modelID===l),[r]),o=p.useMemo(()=>t.map(({providerID:a,modelID:l})=>{const d=e.find(h=>h.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(h=>h.id===l);return!u||s(a,l)?null:{provider:d,model:u,providerID:a,modelID:l}}).filter(a=>a!==null),[t,e,s]),i=p.useMemo(()=>n.map(({providerID:a,modelID:l})=>{const d=e.find(h=>h.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(h=>h.id===l);return!u||s(a,l)?null:{provider:d,model:u,providerID:a,modelID:l}}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!t.some(d=>d.providerID===a&&d.modelID===l)),[n,e,t,s]);return{favoriteModelsList:o,recentModelsList:i}},jP=typeof window<"u"?p.useLayoutEffect:p.useEffect,_P=(e,t=[])=>{const[n,r]=p.useState(!1),s=p.useCallback(()=>{const o=e.current;if(!o)return;const i=o.scrollWidth>o.clientWidth+1;r(i)},[e]);return jP(()=>{s()},[s,...t]),p.useEffect(()=>{const o=e.current;if(!o||typeof ResizeObserver>"u")return;const i=new ResizeObserver(()=>{s()});return i.observe(o),()=>i.disconnect()},[s,e]),p.useEffect(()=>{if(typeof window>"u")return;const o=()=>s();return window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[s]),n},u1=(e,t)=>t?[void 0,...e]:[...e],b3=e=>e??"default",TP=(e,t)=>t===0?50:e/t*100,Uc=10,AP={side:"none",align:"none",fallbackAxisSide:"none"};function gy({options:e,value:t,prefix:n="",className:r,truncateAt:s}){const o=i=>s==null||i.length<=s?i:`${i.slice(0,s)}...`;return c.jsxs("span",{className:R("grid min-w-0 justify-items-start",r),children:[e.map(i=>c.jsxs("span",{className:"invisible col-start-1 row-start-1 overflow-hidden whitespace-nowrap","aria-hidden":"true",children:[n,o(zr(i))]},b3(i))),c.jsxs("span",{className:"col-start-1 row-start-1 truncate",children:[n,o(t)]})]})}function NP({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=p.useRef(null),i=u1(e,s),[a,l]=p.useState(null),[d,f]=p.useState(null),u=a!==null?a:t,h=Math.max(0,i.findIndex(I=>I===u)),m=Math.max(0,i.length-1),g=m===0?0:h/m,x=d!==null?d:g,b=zr(i[h]),S=p.useRef(null),y=p.useRef(t),v=p.useRef(i),C=p.useRef(n),w=p.useRef(r),M=p.useRef(null);p.useEffect(()=>{y.current=t},[t]),p.useEffect(()=>{v.current=i},[i]),p.useEffect(()=>{C.current=n},[n]),p.useEffect(()=>{w.current=r},[r]),p.useEffect(()=>{M.current=a},[a]),p.useEffect(()=>{a!==null&&a===t&&(l(null),f(null))},[t,a]);const j=p.useCallback(I=>{const N=o.current?.getBoundingClientRect(),O=v.current;if(!N||N.width<=0||O.length===0)return{next:O[0],clamped:0};const L=Math.min(Math.max((I-N.left)/N.width,0),1),D=l6(L,O.length);return{next:O[D],clamped:L}},[]),T=I=>{I.preventDefault();const{next:N,clamped:O}=j(I.clientX);l(N),f(O),M.current=N,S.current=I.pointerId;try{I.currentTarget.setPointerCapture(I.pointerId)}catch{}!w.current&&N!==y.current&&C.current(N)},A=I=>{if(S.current!==I.pointerId)return;I.preventDefault();const{next:N,clamped:O}=j(I.clientX);f(O),N!==M.current&&(l(N),M.current=N,!w.current&&N!==y.current&&C.current(N))},_=I=>{if(S.current!==I.pointerId)return;const{next:N,clamped:O}=j(I.clientX),L=M.current??N,D=d??O;S.current=null;try{I.currentTarget.hasPointerCapture(I.pointerId)&&I.currentTarget.releasePointerCapture(I.pointerId)}catch{}w.current?(w.current(L),f(D)):L!==y.current&&C.current(L),w.current||(l(null),f(null))},k=I=>{S.current===I.pointerId&&(S.current=null,l(null),f(null))},E=I=>{let N=null;if((I.key==="ArrowRight"||I.key==="ArrowUp")&&(N=Math.min(m,h+1)),(I.key==="ArrowLeft"||I.key==="ArrowDown")&&(N=Math.max(0,h-1)),I.key==="Home"&&(N=0),I.key==="End"&&(N=m),N===null||N===h)return;I.preventDefault();const O=i[N];w.current?w.current(O):n(O)};return c.jsx("div",{role:"slider",tabIndex:0,"aria-label":"Thinking","aria-orientation":"horizontal","aria-valuemin":0,"aria-valuemax":m,"aria-valuenow":h,"aria-valuetext":b,"data-no-drawer-swipe":"true",className:"cursor-pointer touch-none select-none px-4 py-1 outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] rounded-full",style:{touchAction:"none"},onPointerDown:T,onPointerMove:A,onPointerUp:_,onPointerCancel:k,onLostPointerCapture:k,onKeyDown:E,children:c.jsxs("div",{className:"relative h-8",children:[c.jsx("div",{className:"absolute inset-x-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-muted"}),c.jsx("div",{className:"absolute left-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-primary",style:{width:`calc(${Uc}px + (100% - ${Uc*2}px) * ${x})`}}),c.jsxs("div",{ref:o,className:"absolute inset-y-0",style:{left:Uc,right:Uc},children:[i.map((I,N)=>{const O=TP(N,m),L=N<=h;return c.jsx("div",{"aria-hidden":"true",className:R("pointer-events-none absolute top-1/2 size-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full",L?"bg-primary-foreground/50":"bg-foreground/35"),style:{left:`${O}%`}},b3(I))}),c.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-1/2 h-0",children:c.jsx("div",{className:"w-full",style:{transform:`translateX(${x*100}%)`},children:c.jsx("div",{className:"absolute left-0 top-0 size-8 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground"})})})]})]})})}function f1({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=u1(e,s);return c.jsxs("div",{className:"w-full px-4 pt-3.5 pb-2","data-no-drawer-swipe":"true",children:[c.jsx(NP,{levels:e,value:t,onChange:n,onCommit:r,allowUnset:s}),c.jsxs("div",{className:"mt-1.5 flex justify-between px-4 typography-micro text-muted-foreground",children:[c.jsx("span",{children:zr(o[0])}),c.jsx("span",{className:"text-right",children:zr(o[o.length-1])})]})]})}function LP({levels:e,value:t,onChange:n,compact:r,keepLabel:s=!1,onCompactOpen:o,buttonHeight:i,iconSize:a,textSize:l,isMobile:d,isDesktop:f}){const[u,h]=p.useState(!1),m=zr(t),x=!t?"text-muted-foreground":"text-foreground",b=u1(e,!0),S=d?10:void 0,y=c.jsxs("button",{type:"button",onClick:r?o:void 0,className:R("model-controls__variant-trigger flex items-center gap-1.5 min-w-0",i,"cursor-pointer hover:bg-transparent hover:opacity-70",r?"transition-opacity focus:outline-none":"transition-opacity"),"aria-label":`Thinking: ${m}`,children:[c.jsx($,{name:"brain-ai-3",className:R(a,"flex-shrink-0",x)}),c.jsx(gy,{options:b,value:m,truncateAt:S,className:R("model-controls__variant-label",l,"font-normal",s?"min-w-max whitespace-nowrap":null,r&&d&&!s&&"max-w-[60px]",!r&&f&&"max-w-[180px]",x)})]});return r?y:c.jsxs(S5,{open:u,onOpenChange:h,children:[c.jsxs(yt,{delayDuration:600,...u?{open:!1}:{},children:[c.jsx(vt,{asChild:!0,children:c.jsx(C5,{render:y})}),c.jsx(xt,{side:"top",align:"center",children:c.jsx(gy,{options:b,value:m,prefix:"Thinking: ",className:"typography-meta"})})]}),c.jsx(k5,{children:c.jsx(M5,{className:"app-region-no-drag z-50",side:"top",align:"center",sideOffset:8,collisionPadding:8,collisionAvoidance:AP,children:c.jsx(I5,{className:R($m,"w-[min(17.5rem,calc(100vw-2rem))] p-0 max-h-none"),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},children:c.jsx(f1,{levels:e,value:t,onChange:n})})})})]})}function RP(){const e=We(i=>i.isInitialized),t=We(i=>i.connectionPhase),n=We(i=>i.lastDisconnectReason),r=We(i=>i.providers.length>0),s=e||r,o=!s&&n==="init_error";return{isReady:s,isLoading:!s&&!o,isUnavailable:o,connectionPhase:t}}const PP=({authoritative:e,observed:t,composer:n})=>{if(t&&t.providerId===e.providerId&&t.modelId===e.modelId&&(t.thinking??void 0)===(e.thinking??void 0))return"ignore";const r=t?.providerId===e.providerId&&t?.modelId===e.modelId,s=n.providerId!==e.providerId||n.modelId!==e.modelId;return r&&s||n.providerId===e.providerId&&n.modelId===e.modelId&&(e.thinking===void 0||n.thinking===e.thinking)?"observe":"apply"},DP=[{key:"tool_call",icon:"tools",label:"Tool calling",isActive:e=>e?.tool_call===!0},{key:"reasoning",icon:"brain-ai-3",label:"Reasoning",isActive:e=>e?.reasoning===!0}],OP={text:{icon:"text",label:"Text"},image:{icon:"file-image",label:"Image"},video:{icon:"file-video",label:"Video"},audio:{icon:"file-music",label:"Audio"},pdf:{icon:"file-pdf",label:"PDF"}},HP=e=>e.trim().toLowerCase(),fd=(e,t)=>{const n=t==="input"?e?.modalities?.input:e?.modalities?.output;if(!Array.isArray(n)||n.length===0)return[];const r=Array.from(new Set(n.map(o=>HP(o)))),s=[];for(const o of r){const i=OP[o];i&&s.push({key:o,icon:i.icon,label:i.label})}return s},FP=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),BP=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),VP=e=>new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(e),$P=e=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e),Ia=e=>{if(typeof e!="number"||Number.isNaN(e))return"—";if(e===0)return"0";const t=FP(e);return t.endsWith(".0")?t.slice(0,-2):t},qc=e=>typeof e!="number"||!Number.isFinite(e)?"—":BP(e),w3=e=>{const t=[];for(const n of DP)n.isActive(e)&&t.push({key:n.key,icon:n.icon,label:n.label});return t},S3=e=>{if(!e)return"—";const t=e.match(/^(\d{4})-(\d{2})$/);if(t){const n=Number.parseInt(t[1],10),r=Number.parseInt(t[2],10)-1,s=new Date(Date.UTC(n,r,1));if(!Number.isNaN(s.getTime()))return VP(s)}return e},C3=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:$P(t)},_o=({iconName:e,label:t})=>c.jsx("span",{className:"flex size-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:t,"aria-label":t,role:"img",children:c.jsx($,{name:e,className:"size-3.5"})}),zP=({currentMetadata:e,modelDisplayName:t,providerDisplayName:n,currentCapabilityIcons:r,inputModalityIcons:s,outputModalityIcons:o,costRows:i,limitRows:a})=>c.jsx(xt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e?c.jsxs("div",{className:"flex min-w-[240px] flex-col gap-3",children:[c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"typography-micro font-semibold text-foreground",children:e.name||t}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:n})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Capabilities"}),c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:r.length>0?r.map(({key:l,icon:d,label:f})=>c.jsx(_o,{iconName:d,label:f},`cap-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),c.jsx("div",{className:"flex items-center gap-1.5",children:s.length>0?s.map(({key:l,icon:d,label:f})=>c.jsx(_o,{iconName:d,label:`${f} input`},`input-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),c.jsx("div",{className:"flex items-center gap-1.5",children:o.length>0?o.map(({key:l,icon:d,label:f})=>c.jsx(_o,{iconName:d,label:`${f} output`},`output-${l}`)):c.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]})]})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),i.map(l=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:l.label}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:l.value})]},l.label))]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),a.map(l=>c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:l.label}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:l.value})]},l.label))]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:S3(e.knowledge)})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Release"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:C3(e.release_date)})]})]})]}):c.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),UP=({open:e,onClose:t,title:n,providerDisplayName:r,currentCapabilityIcons:s,inputModalityIcons:o,outputModalityIcons:i,currentMetadata:a})=>e?c.jsx(Ma,{open:!0,onClose:t,title:n,children:c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),c.jsx("div",{className:"typography-meta text-foreground font-medium",children:r})]}),s.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(({key:l,icon:d,label:f})=>c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(_o,{iconName:d,label:f},`cap-${l}`),c.jsx("span",{className:"typography-meta text-foreground",children:f})]},l))})]}),(o.length>0||i.length>0)&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[o.length>0&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Input"}),c.jsx("div",{className:"flex gap-1",children:o.map(({key:l,icon:d,label:f})=>c.jsx(_o,{iconName:d,label:`${f} input`},`input-${l}`))})]}),i.length>0&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Output"}),c.jsx("div",{className:"flex gap-1",children:i.map(({key:l,icon:d,label:f})=>c.jsx(_o,{iconName:d,label:`${f} output`},`output-${l}`))})]})]})]}),c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ia(a?.limit?.context)})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Output"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ia(a?.limit?.output)})]})]})]}),c.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Metadata"}),c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Knowledge"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:S3(a?.knowledge)})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Release"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:C3(a?.release_date)})]})]})]})]})}):null,qP=({open:e,onClose:t,targetVariants:n,selectedVariant:r,onVariantLiveChange:s,onVariantCommit:o})=>!e||n.length===0?null:c.jsx(Ma,{open:!0,onClose:t,title:"Thinking",children:c.jsx(f1,{levels:n,value:dn(r)??void 0,onChange:s,onCommit:o})}),WP=e=>{if(!e||e.trim().length===0)return zr(void 0);const t=e.trim();return/^\d+(\.\d+)?$/.test(t)?t:zr(t)},KP=(e,t)=>`${e}:${t}`,GP=({open:e,onClose:t,mobileModelQuery:n,onMobileModelQueryChange:r,filteredFavorites:s,filteredRecents:o,filteredProviders:i,expandedMobileProviders:a,onToggleMobileProviderExpansion:l,expandedMobileModelKey:d,onToggleExpandedMobileModelKey:f,currentProviderId:u,currentModelId:h,getModelDisplayName:m,getModelMetadata:g,getModelVariantOptions:x,resolveModelVariantSelection:b,pendingThinkingVariants:S,onUpdatePendingThinkingVariant:y,isFavoriteModel:v,onToggleFavoriteModel:C,onApplyModel:w})=>{if(!e)return null;const M=n.trim(),j=s.length>0||o.length>0||i.length>0,T=({model:A,providerId:_,modelId:k,showProviderLogo:E})=>{const I=KP(_,k),N=_===u&&k===h,O=c1(_,A,g(_,k)),L=x(_,k),D=L.length>0,W=b(_,k),z=S.get(I),B=S.has(I)?z:W,U=D?WP(B):null,P=d===I,q=w3(O),F=[...fd(O,"input"),...fd(O,"output")],ee=Array.from(new Map([...q,...F].map(K=>[K.key,K])).values()),G=O?.limit?.context?`${Ia(O.limit.context)} ctx`:null;return c.jsxs("div",{className:R("border-b border-border/30 last:border-b-0",N&&"bg-interactive-selection/15 text-interactive-selection-foreground"),children:[c.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5",children:[c.jsx("button",{type:"button",onClick:()=>w(_,k,B),className:R("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-lg"),children:c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[E?c.jsx(Vo,{providerId:_,className:"size-3.5 flex-shrink-0"}):null,c.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:m(A)}),N?c.jsx($,{name:"check",className:"size-4 flex-shrink-0 text-primary"}):null]}),G||ee.length>0?c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden typography-micro text-muted-foreground",children:[G?c.jsx("span",{className:"whitespace-nowrap flex-shrink-0",children:G}):null,G&&ee.length>0?c.jsx("span",{"aria-hidden":"true",className:"h-3 w-px flex-shrink-0 bg-border/50"}):null,ee.length>0?c.jsx("div",{className:"flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap pl-0.5",children:ee.map(({key:K,icon:se,label:ce})=>c.jsx("span",{className:"flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",title:ce,"aria-label":ce,children:c.jsx($,{name:se,className:"size-3"})},`meta-${_}-${k}-${K}`))}):null]}):null]})}),D?c.jsxs("button",{type:"button",onClick:()=>f(d===I?null:I),className:"flex items-center gap-0.5 typography-micro font-medium text-muted-foreground hover:text-foreground flex-shrink-0","aria-expanded":P,"aria-label":P?"Hide thinking modes":"Show thinking modes",children:[c.jsx("span",{className:"whitespace-nowrap",children:U}),P?c.jsx($,{name:"arrow-down-s",className:"size-3.5"}):c.jsx($,{name:"arrow-right-s",className:"size-3.5"})]}):null,c.jsx("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:c.jsx("button",{type:"button",onClick:K=>{K.preventDefault(),K.stopPropagation(),C(_,k)},className:R("model-favorite-button flex size-5 items-center justify-center hover:text-primary/80 flex-shrink-0",v(_,k)?"text-primary":"text-muted-foreground"),"aria-label":v(_,k)?"Unfavorite":"Favorite",title:v(_,k)?"Remove from favorites":"Add to favorites",children:v(_,k)?c.jsx($,{name:"star-fill",className:"size-4"}):c.jsx($,{name:"star",className:"size-4"})})})]}),P&&D?c.jsx("div",{className:"border-t border-border/30 px-1 py-1","data-no-drawer-swipe":"true",children:c.jsx(f1,{levels:L,value:dn(B)??void 0,onChange:()=>{},onCommit:K=>y(I,K)})}):null]},`mobile-model-${_}-${k}`)};return c.jsx(Ma,{open:!0,onClose:t,title:"Select model",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("div",{children:c.jsxs("div",{className:"relative",children:[c.jsx($,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground"}),c.jsx(Fo,{value:n,onChange:A=>{r(A.target.value),f(null)},placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-[var(--surface-elevated)] typography-meta"}),n&&c.jsx("button",{type:"button",onClick:()=>{r(""),f(null)},className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:c.jsx($,{name:"close-circle",className:"size-4"})})]})}),!j&&c.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),s.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[c.jsx($,{name:"star-fill",className:"size-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),c.jsx("div",{className:"flex flex-col border-t border-border/30",children:s.map(({model:A,providerID:_,modelID:k})=>T({model:A,providerId:_,modelId:k,showProviderLogo:!0}))})]}),o.length>0&&c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[c.jsx($,{name:"time",className:"size-3 inline-block mr-1.5"}),"Recent"]}),c.jsx("div",{className:"flex flex-col border-t border-border/30",children:o.map(({model:A,providerID:_,modelID:k})=>T({model:A,providerId:_,modelId:k,showProviderLogo:!0}))})]}),i.map(({provider:A,providerModels:_})=>{if(_.length===0)return null;const k=String(A.id||""),E=String(A.name||k),I=k===u,N=a.has(k)||M.length>0;return c.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[c.jsxs("button",{type:"button",onClick:()=>{M.length>0||l(k)},className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":N,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Vo,{providerId:k,className:"size-3.5"}),c.jsx("span",{className:"typography-meta font-medium text-foreground",children:E}),I&&c.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),N?c.jsx($,{name:"arrow-down-s",className:"size-3 text-muted-foreground"}):c.jsx($,{name:"arrow-right-s",className:"size-3 text-muted-foreground"})]}),N&&_.length>0&&c.jsx("div",{className:"flex flex-col border-t border-border/30",children:_.map(O=>T({model:O,providerId:String(A.id||""),modelId:String(O.id||""),showProviderLogo:!1}))})]},k)})]})})},Zf=(e,t)=>`${e}:${t}`,ZP="__add_provider__",YP=({className:e,keepLabels:t=!1,mobilePanel:n,onMobilePanelChange:r})=>{const{isReady:s,isUnavailable:o}=RP(),i=o?"Unavailable":"Loading...",a=We(Z=>Z.providers),l=We(Z=>Z.currentProviderId),d=We(Z=>Z.currentModelId),f=We(Z=>Z.currentVariant),u=We(Z=>Z.settingsDefaultThinking),h=We(Z=>Z.settingsDefaultThinkingByModel),m=We(Z=>Z.setProvider),g=We(Z=>Z.setSelectedProvider),x=We(Z=>Z.setModel),b=We(Z=>Z.setCurrentVariant),S=We(Z=>Z.getCurrentModelVariants),y=We(Z=>Z.getCurrentProvider),v=We(Z=>Z.getModelMetadata),C=p.useRef(!1);p.useEffect(()=>{C.current||!s||(C.current=!0,it("ModelControls:ready",{providers:a.length,currentProviderId:l,currentModelId:d}))},[d,l,s,a.length]);const w=pe(Z=>Z.currentSessionId),M=pe(Z=>Z.newSessionDraft.open),j=pe(Z=>Z.getDirectoryForSession),T=x3(),A=At(Z=>Z.getSessionModelSelection),_=At(Z=>Z.saveSessionModelSelection),k=At(Z=>Z.hasHydrated),E=te(Z=>Z.toggleFavoriteModel),I=te(Z=>Z.reorderFavoriteModel),N=te(Z=>Z.isFavoriteModel),O=te(Z=>Z.addRecentModel),L=te(Z=>Z.addRecentEffort),D=te(Z=>Z.isModelSelectorOpen),W=te(Z=>Z.setModelSelectorOpen),z=te(Z=>Z.setSettingsDialogOpen),J=te(Z=>Z.setSettingsPage),B=te(Z=>Z.hiddenModels),{favoriteModelsList:U,recentModelsList:P}=EP(),{isMobile:q}=On(),{enabled:F}=nu(),ee=te(Z=>Z.isMobile),G=(q||ee)&&!F,K=p.useMemo(()=>wt(),[]),se=G,[ce,re]=p.useState(null),fe=n!==void 0&&typeof r=="function",ge=fe?n:ce,we=fe?r:re,[Me,He]=p.useState(null),[Ae,Ge]=p.useState(""),[et,Xe]=p.useState(null),oe=p.useRef(!1),Q=p.useCallback(()=>we(null),[we]),ue=p.useCallback(()=>He(null),[]),be=p.useRef(void 0),[Ie,Fe]=p.useState(()=>{const Z=new Set;return l&&Z.add(l),Z}),ht=p.useCallback(()=>{g(ZP),J("providers"),z(!0),W(!1),Q()},[g,J,z,W,Q]),[ye,Ze]=p.useState(""),Be=p.useRef(!1),ie=p.useRef(null),ke=p.useRef(void 0),ve=p.useRef(null),[xe,_e]=p.useState(new Map),[le,X]=p.useState(new Set),[ne,he]=p.useState(0);p.useEffect(()=>{ge==="model"&&(We.getState().ensureModelMetadata(),Fe(()=>{const Z=new Set;return l&&Z.add(l),Z}))},[ge,l]),p.useEffect(()=>{ge===null&&Xe(null)},[ge]),p.useEffect(()=>{ge!=="model"&&(Ge(""),Xe(null),_e(new Map),X(new Set))},[ge]);const De=p.useRef(D);p.useEffect(()=>{const Z=De.current;De.current=D,D&&We.getState().ensureModelMetadata(),D||(Ze(""),Be.current=!1,ie.current=null,_e(new Map),X(new Set),Z&&!se&&requestAnimationFrame(Io))},[D,se]);const qe=G?"mobile":"default",st=qe==="mobile"?"h-9":"h-7",je="size-3.5",Ke="typography-micro",Et=qe==="mobile"?"gap-x-1":"gap-x-3",fn=y(),Sn=Array.isArray(fn?.models)?fn.models:[],Os=p.useMemo(()=>{const Z=[];for(const me of a){const Ne=(Array.isArray(me.models)?me.models:[]).filter(ct=>{const ot=typeof ct?.id=="string"?ct.id:"";return!B.some(dt=>dt.providerID===String(me.id)&&dt.modelID===ot)});Ne.length>0&&Z.push({...me,models:Ne})}return Z},[a,B]),Hs=p.useCallback(Z=>{const me=Z.toLowerCase().trim(),Re=me.replace(/[^a-z0-9]/g,""),Ne=me.split(/[^a-z0-9]+/).filter(Boolean);return{lower:me,compact:Re,tokens:Ne}},[]),Hn=p.useCallback((Z,me)=>{const Re=Hs(me);if(!Re.lower)return!0;const Ne=Hs(Z);return Ne.lower.includes(Re.lower)||Re.compact.length>=2&&Ne.compact.includes(Re.compact)?!0:Re.tokens.length===0?!1:Re.tokens.every(ct=>Ne.tokens.some(ot=>ot.startsWith(ct)||ot.includes(ct)))},[Hs]),za=d?Sn.find(Z=>Z.id===d):void 0,Ht=l&&d&&za?c1(l,za,v(l,d)):l&&d?v(l,d):void 0,tn=p.useCallback(Z=>Z==="Tool calling"?"Tool calling":Z==="Reasoning"?"Reasoning":Z==="Text"?"Text":Z==="Image"?"Image":Z==="Video"?"Video":Z==="Audio"?"Audio":Z==="PDF"?"PDF":Z,[]),Zr=p.useMemo(()=>w3(Ht).map(Z=>({...Z,label:tn(Z.label)})),[Ht,tn]),Xo=p.useMemo(()=>fd(Ht,"input").map(Z=>({...Z,label:tn(Z.label)})),[Ht,tn]),Jo=p.useMemo(()=>fd(Ht,"output").map(Z=>({...Z,label:tn(Z.label)})),[Ht,tn]),yr=S().filter(Ft),Ua=yr.length>0,qa=[{label:"Input",value:qc(Ht?.cost?.input)},{label:"Output",value:qc(Ht?.cost?.output)},{label:"Cache read",value:qc(Ht?.cost?.cache_read)},{label:"Cache write",value:qc(Ht?.cost?.cache_write)}],Wa=[{label:"Context",value:Ia(Ht?.limit?.context)},{label:"Output",value:Ia(Ht?.limit?.output)}],Fn=p.useRef(null),Yr=p.useRef(null);w&&j(w);const Bn=lw(w??""),Rt=ze(Z=>{if(!w)return null;const me=Z.reducer.bySession.get(w);return me?{model:me.model,thinking:me.thinking}:null},(Z,me)=>Z===me?!0:!Z||!me?!1:Z.model?.providerId===me.model?.providerId&&Z.model?.modelId===me.model?.modelId&&Z.thinking===me.thinking,w?`session:${w}`:"*"),vr=p.useCallback((Z,me)=>{if(!Z||!me)return"model-missing";const Re=a.find(Qe=>Qe.id===Z);if(!Re)return"provider-missing";const ct=(Array.isArray(Re.models)?Re.models:[]).find(Qe=>Qe.id===me);if(!ct)return"model-missing";if(l===Z&&d===me)return"applied";m(Z),x(me);const Oe=xc({providerId:Z,modelId:me,thinkingLevels:ct.thinkingLevels,reasoning:ct.reasoning,supportsThinking:ct.supportsThinking,defaultThinkingByModel:h,defaultThinking:u,previousThinking:f});return b(Oe),w&&_(w,Z,me),"applied"},[a,l,d,f,m,x,b,w,_,u,h]),Vt=p.useCallback((Z,me)=>{const Re=a.find(ct=>ct.id===Z),Ne=(Array.isArray(Re?.models)?Re.models:[]).find(ct=>ct.id===me);return um(Ne)},[a]),Xr=p.useCallback((Z,me,Re)=>{if(!Z||!me)return"model-missing";const Ne=a.find(dt=>dt.id===Z);if(!Ne)return"provider-missing";if(!(Array.isArray(Ne.models)?Ne.models:[]).some(dt=>dt.id===me))return"model-missing";l!==Z&&m(Z),(l!==Z||d!==me)&&x(me),w&&_(w,Z,me);const ot=Vt(Z,me);return b(Re&&ot.includes(Re)?Re:void 0),Yr.current={...Z?{providerId:Z}:{},...me?{modelId:me}:{},...Re?{thinking:Re}:{}},"applied"},[d,l,w,Vt,a,_,b,x,m]),Qo=p.useCallback((Z,me)=>{const Re=Vt(Z,me);if(Re.length!==0){if(l===Z&&d===me&&Ft(f)&&Re.includes(f))return f;if(!w){const Ne=a.find(ot=>ot.id===Z),ct=(Array.isArray(Ne?.models)?Ne.models:[]).find(ot=>ot.id===me);return xc({providerId:Z,modelId:me,thinkingLevels:ct?.thinkingLevels,reasoning:ct?.reasoning,supportsThinking:ct?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u})}}},[d,l,w,f,Vt,a,u,h]),Jr=p.useCallback((Z,me,Re)=>{const Ne=Vt(Z,me);if(Ne.length===0){oe.current=!1,Ri(void 0);return}const ct=Ft(Re)&&Ne.includes(Re)?Re:void 0;oe.current=!0,Ri(ct),L(Z,me,Re)},[L,Vt]),Ka=p.useCallback((Z,me,Re)=>{const Ne=vr(Z,me);return Ne!=="applied"?Ne:(O(Z,me),Jr(Z,me,Re),"applied")},[O,Jr,vr]);p.useEffect(()=>{if(!w){Fn.current=null;return}if(!k||a.length===0)return;if(!Bn){T.ensureSessionRenderable(w);return}if(Fn.current===w)return;const Z=Ne=>{if(Ne&&l&&d){const ct=Vt(l,d);b(ct.includes(Ne)?Ne:void 0);return}b(void 0)},me=Rt?.model;if(me){if(Xr(me.providerId,me.modelId,Rt?.thinking)==="provider-missing")return;Fn.current=w;return}if(Rt?.thinking){Z(Rt.thinking),Fn.current=w;return}const Re=A(w);Re&&Xr(Re.providerId,Re.modelId,Rt?.thinking)==="provider-missing"||(Fn.current=w)},[Xr,k,d,l,w,Rt,Vt,A,Bn,a.length,b,T]),p.useEffect(()=>{if(!w||!k||a.length===0||!Bn||Fn.current!==w)return;const Z=Rt?.model,me=Rt?.thinking??void 0;if(!Z?.providerId||!Z?.modelId){Yr.current=null;return}const Re=PP({authoritative:{providerId:Z.providerId,modelId:Z.modelId,thinking:me},observed:Yr.current,composer:{providerId:l,modelId:d,thinking:dn(f)??void 0}});if(Re!=="ignore"){if(Re==="apply"){Xr(Z.providerId,Z.modelId,me);return}Yr.current={providerId:Z.providerId,modelId:Z.modelId,...me?{thinking:me}:{}}}},[Xr,k,d,l,w,f,Rt,Bn,a.length]),p.useEffect(()=>{if(!k){oe.current=!1,b(void 0);return}if(!l||!d){oe.current=!1,b(void 0);return}const Z=a.find(Ne=>Ne.id===l),me=(Array.isArray(Z?.models)?Z.models:[]).find(Ne=>Ne.id===d),Re=dm(me);if(!Hd(Re)){f&&Ft(f)&&b(void 0);return}if(!w&&!f&&!oe.current){const Ne=xc({providerId:l,modelId:d,thinkingLevels:me?.thinkingLevels,reasoning:me?.reasoning,supportsThinking:me?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u});Ne&&b(Ne);return}if(f&&Ft(f)&&!Re.includes(f)){b(xc({providerId:l,modelId:d,thinkingLevels:me?.thinkingLevels,reasoning:me?.reasoning,supportsThinking:me?.supportsThinking,defaultThinkingByModel:h,defaultThinking:u,previousThinking:f}));return}if(w&&!f&&!oe.current){const Ne=dn(Rt?.thinking);Ne&&Re.includes(Ne)&&b(Ne)}},[k,w,l,d,f,Rt,a,b,u,h]),p.useEffect(()=>{oe.current=!1},[l,d]);const Cu=p.useCallback(Z=>{l&&d&&Jr(l,d,Z)},[Jr,d,l]),Fs=p.useCallback(Z=>{if(!l||!d)return;const me=Vt(l,d);if(me.length===0){oe.current=!1,Ri(void 0);return}const Re=Ft(Z)&&me.includes(Z)?Z:void 0;oe.current=!0,Ri(Re)},[l,d,Vt]),ku=p.useCallback(Z=>{Z!==f&&Fs(Z),l&&d&&L(l,d,Z)},[Fs,l,d,f,L]),Mu=(Z,me,Re)=>{try{const Ne=Re?.applyVariant?Ka(Z,me,Re.variant):vr(Z,me);if(Ne!=="applied"){Ne==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",Z):Ne==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:Z,modelId:me});return}Re?.applyVariant||O(Z,me),W(!1),se&&Q(),requestAnimationFrame(Io)}catch(Ne){console.error("[ModelControls] Handle model change error:",Ne)}},er=(Z,me)=>l1(Z,me,{maxLength:40}),Qr=()=>a.find(me=>me.id===l)?.name||l||"",nn=()=>{if(!d)return"Select model";const Z=Sn.find(me=>me.id===d);return er(Z,d)||"Select model"},ei=p.useCallback((Z,me)=>!G||Z.length<=me?Z:`${Z.slice(0,me)}...`,[G])(nn(),16),Vn=p.useRef(null),Ga=_P(Vn,[ei,se]),xr=p.useCallback(Z=>{Fe(me=>{const Re=new Set(me);return Re.has(Z)?Re.delete(Z):Re.add(Z),Re})},[]),Bs=p.useCallback(Z=>{be.current&&clearTimeout(be.current),be.current=setTimeout(()=>{He(Z)},500)},[]),Za=p.useCallback(()=>{be.current&&clearTimeout(be.current)},[]);p.useEffect(()=>()=>{be.current&&clearTimeout(be.current)},[]);const Ya=()=>!se||Me!=="model"?null:c.jsx(UP,{open:!0,onClose:ue,title:Ht?.name||nn(),providerDisplayName:Qr(),currentCapabilityIcons:Zr,inputModalityIcons:Xo,outputModalityIcons:Jo,currentMetadata:Ht}),Xa=()=>{if(!se)return null;const Z=Ae.trim(),me=U.filter(({model:ot,providerID:dt})=>{const Qe=a.find(jt=>jt.id===dt)?.name||dt,kt=er(ot);return Z.length===0||Hn(String(kt||""),Z)||Hn(String(Qe||""),Z)}),Re=P.filter(({model:ot,providerID:dt})=>{const Qe=a.find(jt=>jt.id===dt)?.name||dt,kt=er(ot);return Z.length===0||Hn(String(kt||""),Z)||Hn(String(Qe||""),Z)}),Ne=[];for(const ot of Os){const dt=Array.isArray(ot.models)?ot.models:[],Oe=Z.length===0?!0:Hn(String(ot.name||""),Z)||Hn(String(ot.id||""),Z),Qe=Z.length===0?dt:dt.filter(jt=>{const Cn=er(jt),rn=typeof jt.id=="string"?jt.id:"";return Hn(String(Cn||""),Z)||Hn(String(rn||""),Z)}),kt=Oe&&Z.length>0?dt:Qe;(Oe||kt.length>0)&&Ne.push({provider:ot,providerModels:kt,matchesProvider:Oe})}const ct=(ot,dt,Oe)=>{const Qe=Ka(ot,dt,Oe);if(Qe!=="applied"){Qe==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",ot):Qe==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:ot,modelId:dt});return}Xe(null),Q(),requestAnimationFrame(Io)};return c.jsx(GP,{open:ge==="model",onClose:Q,mobileModelQuery:Ae,onMobileModelQueryChange:Ge,filteredFavorites:me,filteredRecents:Re,filteredProviders:Ne,expandedMobileProviders:Ie,onToggleMobileProviderExpansion:xr,expandedMobileModelKey:et,onToggleExpandedMobileModelKey:Xe,currentProviderId:l,currentModelId:d,getModelDisplayName:er,getModelMetadata:v,getModelVariantOptions:Vt,resolveModelVariantSelection:Qo,pendingThinkingVariants:xe,onUpdatePendingThinkingVariant:(ot,dt)=>{_e(Oe=>{const Qe=new Map(Oe);return Qe.set(ot,dt),Qe}),X(Oe=>{const Qe=new Set(Oe);return Qe.add(ot),Qe}),he(Oe=>Oe+1)},isFavoriteModel:N,onToggleFavoriteModel:E,onApplyModel:ct})},Ja=()=>{if(!se||!l||!d)return null;const Z=Vt(l,d);return c.jsx(qP,{open:ge==="variant",onClose:Q,targetVariants:Z,selectedVariant:f,onVariantLiveChange:Fs,onVariantCommit:ku})},Qa=()=>c.jsx(zP,{currentMetadata:Ht,modelDisplayName:nn(),providerDisplayName:Qr(),currentCapabilityIcons:Zr,inputModalityIcons:Xo,outputModalityIcons:Jo,costRows:qa,limitRows:Wa}),ec=()=>{const Z=(Oe,Qe)=>{if(Be.current=!0,Oe.key!=="ArrowLeft"&&Oe.key!=="ArrowRight")return!1;const{providerID:kt,modelID:jt}=Qe,Cn=Vt(kt,jt);if(Cn.length===0)return!1;Oe.preventDefault(),Oe.stopPropagation();const rn=Zf(kt,jt),Vs=xe.has(rn),$s=xe.get(rn),tr=Vs?$s:l===kt&&d===jt?f:void 0,ti=fm(Cn,Ft(tr)?tr:void 0,Oe.key==="ArrowRight"?1:-1);return _e(br=>{const wr=new Map(br);return wr.set(rn,ti),wr}),X(br=>{const wr=new Set(br);return wr.add(rn),wr}),he(br=>br+1),!0},me=(Oe,Qe)=>{Qe&&Z(Oe,Qe)},Re=Oe=>{const Qe=Zf(Oe.providerID,Oe.modelID),kt=xe.get(Qe),jt=le.has(Qe);Mu(Oe.providerID,Oe.modelID,jt?{applyVariant:!0,variant:kt}:void 0)},Ne=Oe=>{ve.current={category:Oe.key.length===1?"printable":Oe.key.startsWith("Arrow")||Oe.key==="Escape"||Oe.key==="Enter"?"navigation":"other",modifiers:Oe.altKey||Oe.ctrlKey||Oe.metaKey||Oe.shiftKey}},ct=(Oe,Qe)=>{if(!Oe){const kt=document.activeElement;console.info("[DEBUG-model-picker-close]",{reason:Qe.reason??"unknown",eventType:Qe.event?.type??"none",draftOpen:M,focusInsidePicker:kt instanceof Element&&!!kt.closest('[data-model-picker-popup="true"]'),precedingKey:ve.current})}W(Oe)},ot={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},dt=(Oe,{isHighlighted:Qe,isSelected:kt})=>{const jt=Vt(Oe.providerID,Oe.modelID).length>0,Cn=Zf(Oe.providerID,Oe.modelID),rn=le.has(Cn);if(!jt||!Qe&&!kt)return null;const Vs=xe.has(Cn),$s=xe.get(Cn),tr=Vs?$s:kt?f:void 0,ti=zr(Ft(tr)?tr:void 0);return c.jsxs("span",{className:R("typography-micro whitespace-nowrap",rn?"text-foreground":"text-muted-foreground"),children:["Thinking: ",ti]})};return c.jsxs(yt,{delayDuration:600,children:[se?c.jsx("button",{type:"button",onClick:s?()=>we("model"):void 0,onTouchStart:s?()=>Bs("model"):void 0,onTouchEnd:s?Za:void 0,onTouchCancel:s?Za:void 0,disabled:!s,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",s?"cursor-pointer hover:bg-transparent hover:opacity-70":"opacity-60 cursor-not-allowed",st),children:s?c.jsxs(c.Fragment,{children:[l?c.jsx(Vo,{providerId:l,className:R(je,"flex-shrink-0")}):c.jsx($,{name:"pencil-ai",className:R(je,"text-muted-foreground")}),c.jsx("span",{ref:Vn,className:R("model-controls__model-label typography-micro font-normal overflow-hidden",t?"whitespace-nowrap":"min-w-0",!t&&(G?"max-w-[120px]":"max-w-[220px]")),children:c.jsx("span",{className:R("marquee-text",Ga&&"marquee-text--active"),children:ei})}),c.jsx($,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"})]}):c.jsxs(c.Fragment,{children:[c.jsx($,{name:"loader-4",className:R(je,"animate-spin text-muted-foreground flex-shrink-0")}),c.jsx("span",{className:"typography-micro font-normal text-muted-foreground min-w-0",children:i})]})}):c.jsxs(cu,{open:s&&D,onOpenChange:s?ct:void 0,children:[c.jsx(vt,{asChild:!0,children:c.jsx(lu,{asChild:!0,children:c.jsxs("button",{type:"button",className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",st),children:[s?l?c.jsxs(c.Fragment,{children:[c.jsx(Vo,{providerId:l,className:R(je,"flex-shrink-0")}),c.jsx($,{name:"pencil-ai",className:R(je,"text-primary/60 hidden")})]}):c.jsx($,{name:"pencil-ai",className:R(je,"text-muted-foreground")}):c.jsxs(c.Fragment,{children:[c.jsx($,{name:"loader-4",className:R(je,"animate-spin text-muted-foreground flex-shrink-0")}),c.jsx("span",{className:R("model-controls__model-label",Ke,"font-normal whitespace-nowrap text-muted-foreground min-w-0"),children:i})]}),s&&c.jsx("span",{ref:Vn,className:R("model-controls__model-label overflow-hidden",Ke,"font-normal whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:c.jsx("span",{className:R("marquee-text",Ga&&"marquee-text--active"),children:ei})},`${l}-${d}`),s?c.jsx($,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"}):null]})})}),c.jsxs(du,{"data-model-picker-popup":"true",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,onKeyDownCapture:Ne,children:[c.jsx("div",{className:"p-1 border-b border-border/40",children:c.jsxs("button",{type:"button",onClick:ht,className:"typography-meta group flex w-full items-center gap-1 rounded-md px-2 py-1.5 cursor-pointer hover:bg-interactive-hover/50",children:[c.jsx("span",{className:"flex size-4 items-center justify-center text-muted-foreground",children:c.jsx($,{name:"add",className:"size-4 -mr-0.5"})}),c.jsx("span",{className:"font-medium text-foreground",children:"Add new provider"})]})}),c.jsx(IP,{providers:a,favoriteModels:U,recentModels:P,modelsMetadata:We.getState().modelsMetadata,searchQuery:ye,onSearchQueryChange:Ze,onSelect:Re,labels:ot,selectedModel:l&&d?{providerID:l,modelID:d}:null,hiddenModels:B,onActiveKeyDown:me,onActiveEntryChange:Oe=>{ke.current=Oe},onVariantKey:Z,isFavorite:Oe=>N(Oe.providerID,Oe.modelID),onToggleFavorite:Oe=>E(Oe.providerID,Oe.modelID),renderRowEnd:dt,renderVersion:ne,onReorderFavorite:(Oe,Qe)=>I(Oe.providerID,Oe.modelID,Qe.providerID,Qe.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",tooltipsEnabled:D,onEscape:()=>W(!1)})]})]}),Qa()]})},tc=()=>!s||!Ua?null:c.jsx(LP,{levels:yr,value:dn(f)??void 0,onChange:Cu,compact:se,keepLabel:t,onCompactOpen:()=>we("variant"),buttonHeight:st,iconSize:je,textSize:Ke,isMobile:G,isDesktop:K}),nc=R(!t&&"@container/model-controls","flex items-center",t?"w-max shrink-0":"min-w-0",G&&!t&&"w-full",e);return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:nc,children:c.jsxs("div",{className:R("flex items-center justify-start",Et,t?"w-max shrink-0":"min-w-0",G&&!t&&"overflow-hidden"),children:[ec(),tc()]})}),Xa(),Ja(),Ya()]})},XP=1e9,JP=1e12,Yf="thinking",QP=e=>e>=JP?e:e>=XP?e*1e3:Date.now()+e,eD=e=>{if(e<60)return`${e}s`;if(e<3600){const r=Math.floor(e/60),s=e%60;return s>0?`${r}m ${s}s`:`${r}m`}if(e<86400){const r=Math.floor(e/3600),s=Math.floor(e%3600/60);return s>0?`${r}h ${s}m`:`${r}h`}const t=Math.floor(e/86400),n=Math.floor(e%86400/3600);return n>0?`${t}d ${n}h`:`${t}d`};function k3({isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:s,modelName:o,providerId:i,startedAt:a=null}){const{src:l,onError:d,hasLogo:f}=a1(i??null),{currentTheme:u}=Jn(),h=u?.metadata.variant==="dark",m=p.useRef(null),[g,x]=p.useState(null);if(p.useEffect(()=>{const M=s?.next;if(!M||M<=0){x(null);return}const j=QP(M),T=()=>{const _=Math.max(0,j-Date.now());x(Math.ceil(_/1e3))};T();const A=setInterval(T,500);return()=>clearInterval(A)},[s?.next,s?.attempt]),!e)return m.current=null,null;if(s){m.current=null;const M=s.attempt&&s.attempt>1?` (attempt ${s.attempt})`:"",T=`Retrying${g!==null&&g>0?` in ${eD(g)}`:""}${M}`;return c.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":"polite","aria-label":`${T}...`,"data-agent-thinking-row":"true",children:c.jsx(q2,{text:T,variant:"inline",showElapsed:!1,className:"min-w-0"})})}const b=r?"waiting for permission":t,S=!!r,y=!!n&&!S;m.current===null?m.current={text:y?Yf:b??Yf,permission:S}:b&&(!y||S)?m.current={text:b,permission:S}:y&&m.current.permission&&(m.current={text:Yf,permission:!1});const v=m.current;if(!v)return null;const C=typeof o=="string"?o.trim():"",w=C.length>0?`${C} is ${v.text}`:v.text.charAt(0).toUpperCase()+v.text.slice(1);return c.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":v.permission?"assertive":"polite","aria-label":w,"data-agent-thinking-row":"true","data-waiting":v.permission?"true":void 0,children:c.jsxs("span",{className:"typography-markdown inline-flex min-w-0 items-center gap-1.5 leading-5",children:[f&&l?c.jsx("img",{src:l,alt:"","aria-hidden":"true",className:"inline-block h-3.5 w-3.5 mr-0.5 align-[-2px]",style:{filter:h?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:d}):null,c.jsx(q2,{text:w,variant:"inline",animationType:"spinner",animateText:!0,startedAt:a,className:"min-w-0"})]})})}const tD={containerType:"inline-size",containerName:"status-row"},yy={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},vy={high:"text-[var(--status-warning)]",medium:"text-muted-foreground",low:"text-muted-foreground/70"},xy={high:c.jsx($,{name:"arrow-up-double",className:"h-3.5 w-3.5","aria-hidden":"true"}),medium:c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5","aria-hidden":"true"}),low:c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5","aria-hidden":"true"})},by={in_progress:"In progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},wy={high:"High priority",medium:"Medium priority",low:"Low priority"},nD=({todo:e})=>{const t=String(e.status||"pending"),n=String(e.priority||"medium"),r=yy[t]||yy.pending,s=by[t]??by.pending,o=wy[n]??wy.medium,i=t==="in_progress"?c.jsx($,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]","aria-hidden":"true"}):t==="completed"?c.jsx($,{name:"checkbox-circle",className:"h-3.5 w-3.5 text-[var(--status-success)]","aria-hidden":"true"}):c.jsx($,{name:"time",className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":"true"});return c.jsxs("div",{className:"flex items-center min-w-0 py-0.5 gap-2",children:[c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("span",{className:"flex-shrink-0",children:i})}),c.jsx(xt,{side:"left",sideOffset:6,children:s})]}),c.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:e.content}),c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("span",{className:R("typography-meta flex items-center justify-center flex-shrink-0 leading-none",vy[n]??vy.medium),children:xy[n]??xy.medium})}),c.jsx(xt,{side:"right",sideOffset:6,children:o})]})]})},rD=[],M3=({isWorking:e=!1,statusText:t=null,isGenericStatus:n,isWaitingForPermission:r,wasAborted:s,abortActive:o,retryInfo:i,showAbort:a,onAbort:l,showAbortStatus:d,showAssistantStatus:f=!0,showTodos:u=!0,agentName:h,modelName:m,providerId:g,leftAccessory:x,turnStartedAt:b=null})=>{const[S,y]=p.useState(!1),v=pe(P=>P.currentSessionId),C=rD,w=te(P=>P.isMobile),{enabled:M}=nu(),j=w&&!M,T=j,A=p.useMemo(()=>C.filter(P=>P.status!=="cancelled"),[C]),_=p.useMemo(()=>A.find(P=>P.status==="in_progress")||A.find(P=>P.status==="pending")||null,[A]),k=p.useMemo(()=>{const P=C.filter(F=>F.status!=="cancelled").length;return{completed:C.filter(F=>F.status==="completed").length,total:P}},[C]),E=p.useMemo(()=>{const P=A.filter(F=>F.status==="in_progress").length,q=A.filter(F=>F.status==="in_progress"||F.status==="pending").length;return{active:P,left:q}},[A]),I=u&&E.left>0,N=f&&(e||!!s||!!d),O=!!x,L=!d&&(s||!o),D=N||I||O,W=p.useRef(null);p.useEffect(()=>{if(!S)return;const P=q=>{W.current&&!W.current.contains(q.target)&&y(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[S]);const z=()=>y(P=>!P),J=`${E.active} active · ${E.left} left`,B=a&&l?c.jsx("button",{type:"button",onClick:l,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:c.jsx($,{name:"close-circle","aria-hidden":"true"})}):null,U=I?c.jsxs("button",{type:"button",onClick:z,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground","aria-label":J,title:J,children:[!T&&_?c.jsx("span",{className:"status-row__active-todo typography-ui-label text-foreground truncate max-w-[200px]",children:_.content}):c.jsx("span",{className:"typography-ui-label",children:"Tasks"}),c.jsxs("span",{className:"typography-meta flex items-center gap-1 tabular-nums","aria-hidden":"true",children:[c.jsxs("span",{className:"flex items-center gap-0.5",children:[c.jsx($,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]"}),E.active]}),c.jsx("span",{children:"·"}),c.jsxs("span",{className:"flex items-center gap-0.5",children:[c.jsx($,{name:"time",className:"h-3.5 w-3.5"}),E.left]})]}),S?c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5"}):c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5"})]}):null;return D?c.jsx("div",{className:R("mb-1",j&&"mt-2",!O&&"chat-column"),style:tD,children:c.jsxs("div",{className:R("flex min-h-5 items-center justify-between gap-2 py-0.5",O&&"px-0.5"),children:[c.jsx("div",{className:R("flex min-w-0 flex-1 items-center gap-2",O?"pl-1.5":"overflow-x-hidden"),children:f&&d?c.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-0.5",children:c.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[c.jsx($,{name:"close-circle","aria-hidden":"true"}),"Aborted"]})}):f&&L?c.jsx(k3,{isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:i,agentName:h,modelName:m,providerId:g,startedAt:b},`${v??"no-session"}:${b??"no-start"}`):x||null}),c.jsxs("div",{className:R("relative flex items-center gap-2 flex-shrink-0",O?"pr-1.5":"-mr-3"),ref:W,children:[B,U,S&&I&&c.jsxs("div",{style:{maxWidth:"min(28rem, calc(100cqw - 4ch))",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:R("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px] rounded-xl p-1","shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)]","dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[c.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[c.jsx("span",{children:"Tasks"}),c.jsxs("span",{className:"typography-meta tabular-nums",children:[k.completed,"/",k.total]})]}),c.jsx("div",{className:"px-1 max-h-[200px] overflow-y-auto",children:A.map((P,q)=>c.jsx(nD,{todo:P},P.id??`todo-${q}`))})]})]})]})}):null},sD=1e4,oD=6e4,iD=5e3,aD=15e3,cD=3e4,lD=6e4,Sy=5*6e4,dD=3e4,uD=10,Cy=25,fD=40,hD=2,ky=15e3,pD=500,mD=30,hd=20*1024*1024,My=200,Iy=e=>JSON.stringify({from:e.from??null,to:e.to??null,all:e.all??!1,file:e.file??null,maxCount:e.maxCount??null}),Tt=()=>({isGitRepo:null,status:null,branches:null,log:null,remotes:null,remoteUrl:null,lastRemotesFetch:0,isLoadingRemotes:!1,logQueryCache:new Map,diffCache:new Map,indexRevision:0,lastRepoCheckAt:0,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,lastBranchesFetch:0,logMaxCount:25,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1}),Ey="oc.gitBranchCache",Nl="oc.gitBranchCache.v2",gD=8,yD=50,Xf=()=>({version:2,legacyClaimed:!1,runtimes:{}}),I3=e=>{try{const t=Gt(),n=t.getItem(Nl),r=n?JSON.parse(n):Xf(),s=r?.version===2&&r.runtimes&&typeof r.runtimes=="object"?{version:2,legacyClaimed:!!r.legacyClaimed,runtimes:r.runtimes}:Xf();if(!s.legacyClaimed){const o=t.getItem(Ey);if(o){const a=JSON.parse(o),l={};for(const[d,f]of Object.entries(a??{}))d&&f&&Array.isArray(f.all)&&(l[d]={branches:f,updatedAt:0});Object.keys(l).length>0&&(s.runtimes[e]={updatedAt:0,directories:l})}s.legacyClaimed=!0;const i=JSON.stringify(s);t.setItem(Nl,i),t.getItem(Nl)===i&&t.removeItem(Ey)}return s}catch{return Xf()}},vD=(e,t,n)=>{if(!(!t||!n))try{const r=I3(e),s=Date.now(),i={...r.runtimes[e]?.directories??{},[t]:{branches:n,updatedAt:s}},a=Object.fromEntries(Object.entries(i).sort(([,l],[,d])=>d.updatedAt-l.updatedAt).slice(0,yD));r.runtimes[e]={updatedAt:s,directories:a},r.runtimes=Object.fromEntries(Object.entries(r.runtimes).sort(([,l],[,d])=>d.updatedAt-l.updatedAt).slice(0,gD)),Gt().setItem(Nl,JSON.stringify(r))}catch{}},jy=e=>{const t=new Map,n=I3(e).runtimes[e]?.directories??{};for(const[r,s]of Object.entries(n)){const o=s.branches;!r||!o||!Array.isArray(o.all)||t.set(r,{...Tt(),isGitRepo:!0,branches:o})}return t},E3=e=>{const t=new TextEncoder;return t.encode(e.original??"").byteLength+t.encode(e.modified??"").byteLength},_y=(e,t=mD,n=hd)=>{let r=0;for(const a of e.values())r+=new TextEncoder().encode(a.original??"").byteLength+new TextEncoder().encode(a.modified??"").byteLength;if(e.size<=t&&r<=n)return e;const s=Array.from(e.entries()).sort((a,l)=>a[1].fetchedAt-l[1].fetchedAt),o=new Map;let i=0;for(let a=s.length-1;a>=0;a--){const[l,d]=s[a],f=new TextEncoder().encode(d.original??"").byteLength+new TextEncoder().encode(d.modified??"").byteLength;if(o.size>=t)break;i+f>n||(o.set(l,d),i+=f)}return o},Ty=e=>{const t=[];let n=0;for(const[o,i]of e)for(const[a,l]of i.diffCache){const d=E3(l);t.push({directory:o,path:a,fetchedAt:l.fetchedAt,size:d}),n+=d}if(t.length<=My&&n<=hd)return e;const r=new Map(e);t.sort((o,i)=>o.fetchedAt-i.fetchedAt);let s=t.length;for(const o of t){if(s<=My&&n<=hd)break;const i=r.get(o.directory);if(!i?.diffCache.has(o.path))continue;const a=new Map(i.diffCache);a.delete(o.path),r.set(o.directory,{...i,diffCache:a}),s-=1,n-=o.size}return r},xD=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n){const s=e[r],o=t[r];if(!(!s&&!o)&&(!s||!o||s.insertions!==o.insertions||s.deletions!==o.deletions))return!0}return!1},bD=(e,t)=>!e&&!t?!1:!e||!t?!0:e.remote!==t.remote||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind,wD=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=e.files??[],r=t.files??[];if(n.length!==r.length||e.ahead!==t.ahead||e.behind!==t.behind||e.current!==t.current||e.tracking!==t.tracking||e.isClean!==t.isClean||t.upstreamComparison!==void 0&&bD(e.upstreamComparison,t.upstreamComparison))return!0;const s=new Set(n.map(o=>`${o.path}:${o.index}:${o.working_dir}`));for(const o of r)if(!s.has(`${o.path}:${o.index}:${o.working_dir}`))return!0;return!!(t.diffStats!==void 0&&xD(e.diffStats,t.diffStats))},SD=(e,t)=>{const n=new Set;if(!t)return n;const r=e?.files??[],s=t.files??[],o=new Map(r.map(l=>[l.path,l])),i=new Map(s.map(l=>[l.path,l])),a=new Set([...o.keys(),...i.keys()]);for(const l of a){const d=o.get(l),f=i.get(l);if(!d||!f){n.add(l);continue}if(d.index!==f.index||d.working_dir!==f.working_dir){n.add(l);continue}}if(t.diffStats!==void 0){const l=e?.diffStats??{},d=t.diffStats??{},f=new Set([...Object.keys(l),...Object.keys(d)]);for(const u of f){const h=l[u],m=d[u];if(!h||!m){n.add(u);continue}(h.insertions!==m.insertions||h.deletions!==m.deletions)&&n.add(u)}}return n},CD=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=e.files??[],r=t.files??[],s=l=>{const d=l?.trim()??"";return d==="?"?"":d},o=new Map(n.map(l=>[l.path,s(l.index)])),i=new Map(r.map(l=>[l.path,s(l.index)])),a=new Set([...o.keys(),...i.keys()]);for(const l of a)if((o.get(l)??"")!==(i.get(l)??""))return!0;return!1},Ay=e=>!e||e.trim().length===0,pd=e=>(e||"").trim()==="U",kD=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return pd(t)||pd(n)?e:{...e,index:t==="?"||n==="?"?"A":t||n||" ",working_dir:" "}},MD=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return pd(t)||pd(n)?e:{...e,index:" ",working_dir:n||(t==="A"||t==="?"?"?":t)||" "}},ID=e=>Ay(e.index)&&Ay(e.working_dir),Cp=new Map,h1=new Map,oo=new Map,Di=new Map,Oi=new Map,Hi=new Map,Fi=new Map,Bi=new Map,md=new Map,Ea=new Map;let p1=0,m1=Y();const ED=()=>m1,jD=e=>{p1+=1,m1=e,md.clear(),Ea.clear(),oo.clear(),Di.clear(),Oi.clear(),Hi.clear(),Fi.clear(),Bi.clear(),Cp.clear(),h1.clear()},fr=(e,t)=>JSON.stringify([e,t]),Ny=(e,t,n)=>JSON.stringify([e,t,n]),_D=(e,t,n)=>JSON.stringify([e,t,n]),TD=(e,t,n)=>JSON.stringify([e,t,n]),AD=(e,t,n)=>JSON.stringify([e,t,n]),as=(e,t,n=!1)=>{const r=Y(),s=AD(r,e,t),o=(md.get(s)??0)+1;return md.set(s,o),{runtimeKey:r,runtimeGeneration:p1,channelKey:s,requestGeneration:o,...n?{statusMutationRevision:Ea.get(fr(r,e))??0}:{}}},yn=(e,t)=>e.runtimeKey===Y()&&e.runtimeKey===m1&&e.runtimeGeneration===p1&&md.get(e.channelKey)===e.requestGeneration&&(e.statusMutationRevision===void 0||e.statusMutationRevision===(Ea.get(fr(e.runtimeKey,t))??0)),Jf=(e,t)=>{const n=fr(e,t);Ea.set(n,(Ea.get(n)??0)+1)},Ll=e=>h1.get(fr(Y(),e))??0,Wc=e=>{const t=Ll(e)+1;return h1.set(fr(Y(),e),t),t},ND=e=>{const t=fr(Y(),e),n=Cp.get(t);if(n)return n;const r=new Set;return Cp.set(t,r),r},Ly=ED(),bt=Lt()(mr((e,t)=>({runtimeKey:Ly,directories:jy(Ly),activeDirectory:null,resetForRuntimeSwitch:n=>{jD(n),e({runtimeKey:n,directories:jy(n),activeDirectory:null})},setActiveDirectory:n=>{const{activeDirectory:r,directories:s}=t();if(r!==n)if(r&&Wc(r),n&&Wc(n),n&&!s.has(n)){const o=new Map(s);o.set(n,Tt()),e({activeDirectory:n,directories:o})}else e({activeDirectory:n})},getDirectoryState:n=>t().directories.get(n)??null,fetchStatus:async(n,r,s={})=>{const o=s.mode??"full",i=Y(),a=Ny(i,n,o),l=oo.get(a)??(o==="light"?oo.get(Ny(i,n,"full")):void 0);if(l)return l;const d=as(n,"status",!0),f=(async()=>{const{silent:u=!1}=s,{directories:h}=t();let m=h.get(n);if(m||(m=Tt()),!u){const x=new Map(t().directories),b=x.get(n)??Tt();x.set(n,{...b,isLoadingStatus:!0}),e({directories:x})}let g=!1;try{const x=Date.now(),b=m.isGitRepo!==!0||x-(m.lastRepoCheckAt||0)>oD;let S=m.isGitRepo===!0;if(b&&(S=await r.checkIsGitRepository(n),!yn(d,n)))return!1;if(!S){const C=new Map(t().directories),w=C.get(n)??m;return C.set(n,{...w,isGitRepo:!1,status:null,isLoadingStatus:!1,lastRepoCheckAt:x,lastStatusFetch:x}),e({directories:C}),!1}const y=await r.getGitStatus(n,s.mode?{mode:s.mode}:void 0);if(!yn(d,n))return!1;const v=t().directories.get(n)??Tt();if(wD(v.status,y)){g=!0;const C=new Map(t().directories),w=C.get(n)??Tt(),M=SD(w.status,y),j=CD(w.status,y),T=new Set((w.status?.files??[]).map(I=>I.path)),A=new Set((y.files??[]).map(I=>I.path)),_=new Map(w.diffCache);for(const I of T)A.has(I)||_.delete(I);for(const I of M)_.delete(I);const k=M.size>0;k&&Wc(n);const E={...y,diffStats:y.diffStats===void 0&&w.status?.diffStats!==void 0?w.status.diffStats:y.diffStats,upstreamComparison:y.upstreamComparison===void 0?w.status?.upstreamComparison:y.upstreamComparison};C.set(n,{...w,isGitRepo:!0,status:E,diffCache:_,indexRevision:j?w.indexRevision+1:w.indexRevision,lastRepoCheckAt:b?x:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:k?Date.now():w.lastStatusChange}),e({directories:C})}else{const C=new Map(t().directories),w=C.get(n)??Tt();C.set(n,{...w,isGitRepo:!0,lastRepoCheckAt:b?x:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:w.lastStatusChange}),e({directories:C})}}catch(x){console.error("Failed to fetch git status:",x)}finally{if(!u&&yn(d,n)){const x=new Map(t().directories),b=x.get(n)??Tt();x.set(n,{...b,isLoadingStatus:!1}),e({directories:x})}}return g})();oo.set(a,f);try{return await f}finally{oo.get(a)===f&&oo.delete(a)}},moveStatusPathsOptimistically:(n,r,s)=>{const o=new Set(r.map(h=>h.trim()).filter(Boolean));if(o.size===0)return null;const{directories:i}=t(),a=i.get(n),l=a?.status??null;if(!a||!l)return l;let d=!1;const f=[];for(const h of l.files){if(!o.has(h.path)){f.push(h);continue}const m=s==="stage"?kD(h):MD(h);m!==h&&(d=!0),ID(m)?d=!0:f.push(m)}if(!d)return l;Jf(t().runtimeKey,n);const u=new Map(i);return u.set(n,{...a,status:{...l,files:f,isClean:f.length===0},indexRevision:a.indexRevision+1,lastStatusChange:Date.now()}),e({directories:u}),l},restoreStatus:(n,r)=>{const{directories:s}=t(),o=s.get(n);if(!o)return;Jf(t().runtimeKey,n);const i=new Map(s);i.set(n,{...o,status:r,indexRevision:o.indexRevision+1,lastStatusChange:Date.now()}),e({directories:i})},bumpIndexRevision:n=>{const{directories:r}=t(),s=r.get(n);if(!s)return;Jf(t().runtimeKey,n);const o=new Map(r);o.set(n,{...s,indexRevision:s.indexRevision+1}),e({directories:o})},fetchBranches:async(n,r,s={})=>{const o=Y(),i=fr(o,n),a=Di.get(i);if(a)return a;const l=as(n,"branches"),{silent:d=!1}=s,f=(async()=>{if(!d){const u=new Map(t().directories),h=u.get(n)??Tt();u.set(n,{...h,isLoadingBranches:!0}),e({directories:u})}try{const u=await r.getGitBranches(n);if(!yn(l,n))return;const h=new Map(t().directories),m=h.get(n)??Tt();h.set(n,{...m,branches:u,isLoadingBranches:!1,lastBranchesFetch:Date.now()}),e({directories:h}),vD(l.runtimeKey,n,u)}catch(u){if(console.error("Failed to fetch git branches:",u),!yn(l,n))return;const h=new Map(t().directories),m=h.get(n)??Tt();h.set(n,{...m,isLoadingBranches:!1}),e({directories:h})}})().finally(()=>{Di.get(i)===f&&Di.delete(i)});return Di.set(i,f),f},fetchLog:async(n,r,s,o={})=>{const{directories:i}=t(),a=i.get(n),l=s??a?.logMaxCount??25,d=Y(),f=_D(d,n,l),u=Oi.get(f);if(u)return u;const h=as(n,"log"),{silent:m=!1}=o,g=(async()=>{if(!m){const x=new Map(t().directories),b=x.get(n)??Tt();x.set(n,{...b,isLoadingLog:!0}),e({directories:x})}try{const x=await r.getGitLog(n,{maxCount:l});if(!yn(h,n))return;const b=new Map(t().directories),S=b.get(n)??Tt();b.set(n,{...S,log:x,isLoadingLog:!1,lastLogFetch:Date.now(),logMaxCount:l}),e({directories:b})}catch(x){if(console.error("Failed to fetch git log:",x),!yn(h,n))return;const b=new Map(t().directories),S=b.get(n)??Tt();b.set(n,{...S,isLoadingLog:!1}),e({directories:b})}})().finally(()=>{Oi.get(f)===g&&Oi.delete(f)});return Oi.set(f,g),g},fetchRemotes:async(n,r,s={})=>{const o=r.getRemotes;if(typeof o!="function")return;const i=r.getRemoteUrl,a=Y(),l=fr(a,n),d=Hi.get(l);if(d)return d;const f=as(n,"remotes"),{silent:u=!1}=s,h=(async()=>{if(!u){const m=new Map(t().directories),g=m.get(n)??Tt();m.set(n,{...g,isLoadingRemotes:!0}),e({directories:m})}try{const m=o(n),g=typeof i=="function"?i(n).then(v=>({ok:!0,value:v}),()=>({ok:!1,value:null})):Promise.resolve({ok:!0,value:null}),[x,b]=await Promise.all([m,g]);if(!yn(f,n))return;const S=new Map(t().directories),y=S.get(n)??Tt();S.set(n,{...y,remotes:x,remoteUrl:b.ok?b.value:y.remoteUrl,lastRemotesFetch:Date.now(),isLoadingRemotes:!1}),e({directories:S})}catch(m){if(console.error("Failed to fetch git remotes:",m),!yn(f,n))return;const g=new Map(t().directories),x=g.get(n)??Tt();g.set(n,{...x,isLoadingRemotes:!1}),e({directories:g})}})().finally(()=>{Hi.get(l)===h&&Hi.delete(l)});return Hi.set(l,h),h},ensureRemotes:async(n,r)=>{const s=t().directories.get(n),o=Date.now();s?.remotes!==null&&s?.remotes!==void 0&&o-(s?.lastRemotesFetch??0)<Sy||await t().fetchRemotes(n,r,{silent:s?.remotes!=null})},invalidateRemotes:n=>{const{directories:r}=t(),s=r.get(n);if(!s)return;const o=new Map(r);o.set(n,{...s,lastRemotesFetch:0}),e({directories:o})},fetchLogQuery:async(n,r,s,o={})=>{const{force:i=!1}=o,a=Iy(s),l=Y(),d=TD(l,n,a),f=Date.now(),u=t().directories.get(n)?.logQueryCache.get(a);if(!i&&u&&f-u.fetchedAt<dD)return u.log;const h=Fi.get(d);if(h)return h;const m=as(n,`log-query:${a}`),g=(async()=>{try{const x=await r.getGitLog(n,{maxCount:s.maxCount,from:s.from,to:s.to,all:s.all,file:s.file});if(!yn(m,n))return u?.log??null;const b=new Map(t().directories),S=b.get(n)??Tt(),y=new Map(S.logQueryCache);if(y.set(a,{log:x,fetchedAt:Date.now()}),y.size>uD){let v=null,C=Number.POSITIVE_INFINITY;for(const[w,M]of y)M.fetchedAt<C&&(C=M.fetchedAt,v=w);v!==null&&y.delete(v)}return b.set(n,{...S,logQueryCache:y}),e({directories:b}),x}catch(x){return console.error("Failed to fetch git log query:",x),u?.log??t().directories.get(n)?.logQueryCache.get(a)?.log??null}})().finally(()=>{Fi.get(d)===g&&Fi.delete(d)});return Fi.set(d,g),g},getCachedLogQuery:(n,r)=>{const s=Iy(r);return t().directories.get(n)?.logQueryCache.get(s)?.log??null},fetchAll:async(n,r,s={})=>{const{directories:o}=t();let i=o.get(n);if(!i){i=Tt();const h=new Map(o);h.set(n,i),e({directories:h})}const{force:a=!1,silentIfCached:l=!1}=s,d=Date.now();await t().fetchStatus(n,r,{silent:l&&!!i?.status});const f=t().directories.get(n);if(!f?.isGitRepo)return;await t().fetchBranches(n,r);const u=d-(f.lastLogFetch||0);(a||u>sD||!f.log)&&await t().fetchLog(n,r)},getDiff:(n,r)=>t().directories.get(n)?.diffCache.get(r)??null,setDiff:(n,r,s,o)=>{if(o&&o!==t().runtimeKey||E3(s)>hd)return;const i=new Map(t().directories),a=i.get(n)??Tt(),l=new Map(a.diffCache);l.set(r,{...s,fetchedAt:Date.now()});const d=_y(l);i.set(n,{...a,diffCache:d}),e({directories:Ty(i)})},clearDiffCache:(n,r)=>{Wc(n),as(n,"diff");const s=new Map(t().directories),o=s.get(n);if(!o||o.diffCache.size===0)return;const i=new Map(o.diffCache);if(r)for(const a of r)i.delete(a);else i.clear();i.size!==o.diffCache.size&&(s.set(n,{...o,diffCache:i}),e({directories:s}))},fetchAllDiffs:async(n,r)=>{const s=t().directories.get(n);if(!s?.status?.files||s.status.files.length===0)return;const o=s.status.files.map(i=>i.path).slice(0,Cy);await t().prefetchDiffs(n,r,o,{maxFiles:Cy})},prefetchDiffs:async(n,r,s,o={})=>{const i=as(n,"diff"),a=t().directories.get(n);if(!a?.status?.files||a.status.files.length===0||s.length===0)return;const{maxFiles:l=fD}=o,d=new Set(a.status.files.map(k=>k.path)),f=a.status.diffStats,u=ND(n),h=[],m=new Set;for(const k of s){if(!k||m.has(k)||(m.add(k),!d.has(k))||a.diffCache.has(k)||u.has(k))continue;const E=f?.[k];E&&E.insertions+E.deletions>pD||h.push(k)}const g=h.slice(0,Math.max(1,l));if(g.length===0)return;const x=Ll(n);if(typeof document<"u"&&document.hidden)return;g.forEach(k=>u.add(k));let b=0;const S=[],y=()=>{const k=b;return b+=1,k<g.length?g[k]:null},v=async k=>{const E=r.getGitFileDiff(n,{path:k}),I=new Promise((O,L)=>{setTimeout(()=>L(new Error(`Timed out after ${ky}ms`)),ky)}),N=await Promise.race([E,I]);return{path:k,diff:{original:N.original??"",modified:N.modified??"",isBinary:N.isBinary}}},C=async()=>{for(;;){if(x!==Ll(n)||!yn(i,n))return;const k=y();if(!k)return;try{S.push(await v(k))}catch{}finally{u.delete(k)}}},w=Math.min(hD,g.length);if(await Promise.allSettled(Array.from({length:w},()=>C())),g.forEach(k=>u.delete(k)),x!==Ll(n)||!yn(i,n))return;const M=new Map(t().directories),j=M.get(n);if(!j)return;const T=new Map(j.diffCache),A=Date.now();S.forEach(k=>{T.set(k.path,{...k.diff,fetchedAt:A})});const _=_y(T);M.set(n,{...j,diffCache:_}),e({directories:Ty(M)})},setLogMaxCount:(n,r)=>{const s=new Map(t().directories),o=s.get(n)??Tt();s.set(n,{...o,logMaxCount:r}),e({directories:s})},ensureStatus:async(n,r)=>{const s=t().directories.get(n),o=Date.now();s?.status&&o-s.lastStatusFetch<iD||await t().fetchStatus(n,r,{silent:!!s?.status})},ensureAll:(n,r)=>{const s=fr(Y(),n),o=Bi.get(s);if(o)return o;const i=(async()=>{const a=t().directories.get(n),l=Date.now();(!a?.status||a.status.diffStats===void 0||l-(a?.lastStatusFetch??0)>=aD)&&await t().fetchStatus(n,r,{silent:!!a?.status});const f=t().directories.get(n);if(!f?.isGitRepo)return;const u=[];(!f.branches||l-f.lastBranchesFetch>=lD)&&u.push(t().fetchBranches(n,r,{silent:!!f.branches})),(!f.log||l-f.lastLogFetch>=cD)&&u.push(t().fetchLog(n,r,void 0,{silent:!!f.log})),(f.remotes==null||l-(f.lastRemotesFetch??0)>=Sy)&&u.push(t().fetchRemotes(n,r,{silent:f.remotes!=null})),u.length>0&&await Promise.all(u)})();return Bi.set(s,i),i.finally(()=>{Bi.get(s)===i&&Bi.delete(s)}),i},refresh:async(n,r={})=>{const{activeDirectory:s}=t();s&&await t().fetchAll(s,n,r)}}),{name:"git-store"})),LD=e=>bt(t=>e?t.directories.get(e)?.status??null:null),j3=e=>bt(t=>e?t.directories.get(e)?.branches??null:null),RD=e=>bt(t=>e?t.directories.get(e)?.log??null:null),PD=e=>bt(t=>e?t.directories.get(e)?.remotes??null:null),DD=e=>bt(t=>e?t.directories.get(e)?.remoteUrl??null:null),OD=e=>bt(t=>e?t.directories.get(e)?.isLoadingRemotes??!1:!1),pu=e=>bt(t=>e?t.directories.get(e)?.isGitRepo??null:null),HD=e=>bt(t=>e?t.directories.get(e)?.status?.current?.trim()??null:null),Ry={current:new Map},FD=new Map,BD=(e=!0)=>bt(t=>{if(!e)return FD;const n=Ry.current;let r=n.size===t.directories.size;if(r){for(const[o,i]of t.directories)if(n.get(o)!==(i.status?.current??null)){r=!1;break}}if(r)return n;const s=new Map;for(const[o,i]of t.directories)s.set(o,i.status?.current??null);return Ry.current=s,s}),VD=e=>{const t=p.useRef(new Map);return bt(n=>{const r=t.current;let s=r.size===e.length;if(s)for(const i of e){const a=n.directories.get(i),l=r.get(i);if(!l||(a?.isGitRepo??null)!==l.isGitRepo||(a?.status?.current??null)!==l.branch){s=!1;break}}if(s)return r;const o=new Map;for(const i of e){const a=n.directories.get(i);o.set(i,{isGitRepo:a?.isGitRepo??null,branch:a?.status?.current??null})}return t.current=o,o})},$D=e=>bt(t=>e?t.directories.get(e)?.isLoadingStatus??!1:!1),zD=e=>bt(t=>e?t.directories.get(e)?.isLoadingLog??!1:!1),UD=e=>bt(t=>e?t.directories.get(e)?.isLoadingBranches??!1:!1),BX=Object.freeze(Object.defineProperty({__proto__:null,useGitAllBranches:BD,useGitBranchLabel:HD,useGitBranches:j3,useGitLoadingBranches:UD,useGitLoadingLog:zD,useGitLoadingRemotes:OD,useGitLoadingStatus:$D,useGitLog:RD,useGitRemoteUrl:DD,useGitRemotes:PD,useGitRepoStatusMap:VD,useGitStatus:LD,useGitStore:bt,useIsGitRepo:pu},Symbol.toStringTag,{value:"Module"})),_3=p.createContext(null),VX=({actions:e,children:t})=>c.jsx(_3.Provider,{value:e,children:t}),Fa=()=>p.useContext(_3),qD=/^[A-Za-z]:\/$/,g1=/^[A-Za-z]:\//,Wt=e=>{if(typeof e!="string")return"";const t=e.trim();if(!t)return"";const n=t.replace(/\\/g,"/"),r=n.startsWith("//");let s=n.replace(/\/+/g,"/");r&&!s.startsWith("//")&&(s=`/${s}`);const o=s==="/",i=qD.test(s);return!o&&!i&&(s=s.replace(/\/+$/,"")),s},WD=e=>{const t=Wt(e);return t.startsWith("/")||g1.test(t)},gd=e=>{const t=Wt(e);return g1.test(t)||t.startsWith("//")?t.toLowerCase():t},T3=e=>e.split("/").filter(Boolean),KD=(e,t)=>{const n=[...e];for(const r of T3(t))if(r!=="."){if(r===".."){n.length>0&&n.pop();continue}n.push(r)}return n},Ba=(e,t)=>{const n=Wt(t);if(!n)return Wt(e);if(WD(n))return n;const r=Wt(e);if(!r)return n;const s=g1.test(r)?r.slice(0,2):"",o=r.startsWith("//"),i=r.startsWith("/")&&!o,a=s?r.slice(2):r,d=KD(T3(a),n).join("/");return s?d?`${s}/${d}`:`${s}/`:o?`//${d}`:i?`/${d}`:d},mu=(e,t)=>{const n=Wt(e),r=Wt(t);if(!n||!r)return!1;const s=gd(n),o=gd(r);return s===o||s.startsWith(`${o}/`)},A3=(e,t)=>{const n=Wt(e),r=Wt(t);return n?r?gd(n)===gd(r)?".":mu(n,r)?n.slice(r.length+1):n:n:""},Qf=(e,t)=>{const n=Wt(e),r=Wt(t);if(n&&(!r||mu(r,n))||!r)return n;const s=r.lastIndexOf("/");return s===0?"/":s<0?n||r:/^[A-Za-z]:\//.test(r)&&s===2?r.slice(0,3):r.slice(0,s)},GD=new Set(["edit","multiedit","write","apply_patch","create","file_write"]),y1=e=>"insertions"in e,Ys=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e))},ZD=e=>{let t=0,n=0;for(const r of e.split(`
71
+ `))r.startsWith("+")&&!r.startsWith("+++")&&t++,r.startsWith("-")&&!r.startsWith("---")&&n++;return{added:t,removed:n}},$X=e=>{const t=[],n=new Set;for(const r of e){if(r.type!=="tool"||!r.tool||!GD.has(r.tool))continue;const s=r.tool,o=r.messageId??r.messageID??"",i=r.state;if(i?.status&&i.status!=="completed")continue;const a=t.length,l=i?.metadata,d=Array.isArray(l?.files)?l.files:[];for(const f of d){if(!f||typeof f!="object")continue;const u=f,h=u.relativePath||u.filePath||"";!h||n.has(h)||(n.add(h),t.push({path:h,tool:s,partId:r.id,messageID:o,additions:Ys(u.additions)??void 0,deletions:Ys(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(d.length===0&&l?.filediff&&typeof l.filediff=="object"){const f=l.filediff,u=typeof f.file=="string"?f.file:"";u&&!n.has(u)&&(n.add(u),t.push({path:u,tool:s,partId:r.id,messageID:o,additions:Ys(f.additions)??void 0,deletions:Ys(f.deletions)??void 0,patch:typeof f.patch=="string"?f.patch:void 0}))}if(d.length===0&&Array.isArray(l?.results))for(const f of l.results){if(!f||typeof f!="object")continue;const u=f.filediff;if(!u||typeof u!="object")continue;const h=typeof u.file=="string"?u.file:"";!h||n.has(h)||(n.add(h),t.push({path:h,tool:s,partId:r.id,messageID:o,additions:Ys(u.additions)??void 0,deletions:Ys(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(t.length===a){const f=i?.input,u=typeof f?.filePath=="string"?f.filePath:typeof f?.file_path=="string"?f.file_path:typeof f?.path=="string"?f.path:void 0;u&&!n.has(u)&&(n.add(u),t.push({path:u,tool:s,partId:r.id,messageID:o}))}if(t.length===a){const f=typeof l?.patch=="string"?l.patch.trim():typeof l?.diff=="string"?l.diff.trim():"";if(f&&!n.has("Diff")){n.add("Diff");const u=ZD(f);t.push({path:"Diff",tool:s,partId:r.id,messageID:o,additions:u.added,deletions:u.removed})}}}return t},N3=(e,t,n)=>{const r=[];for(const s of e){const o=s.index?.trim()??"",i=s.working_dir?.trim()??"",a=!!(o&&o!=="?"),l=!!(i||o==="?"),d=i||o;if(!d||d==="!")continue;const f=t?.[s.path];r.push({path:Ba(n,s.path),relativePath:s.path,insertions:f?.insertions??0,deletions:f?.deletions??0,status:d,hasStagedChanges:a,hasWorkingChanges:l})}return r},YD=(e,t)=>A3(e,t),XD=(e,t)=>{const n=y1(e)&&e.relativePath?e.relativePath:YD(e.path,t),r=n.split("/").pop()??n,s=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";return{fileName:r,dirPart:s}},JD=e=>y1(e)?{additions:e.insertions,deletions:e.deletions}:{additions:e.additions??0,deletions:e.deletions??0},QD=({files:e,currentDirectory:t,onOpenFile:n})=>c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[c.jsx("span",{children:"Changed files"}),c.jsx("span",{className:"typography-meta tabular-nums",children:e.length})]}),c.jsx("div",{className:"max-h-[260px] overflow-y-auto",children:e.map((r,s)=>{const{fileName:o,dirPart:i}=XD(r,t),a=JD(r);return c.jsxs("button",{type:"button",className:"relative flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none text-left hover:bg-interactive-hover",title:`Open ${r.path}`,onClick:()=>n(r),children:[c.jsx(hr,{filePath:r.path,className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 flex items-baseline overflow-hidden",title:r.path,children:i?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsxs("span",{className:"flex-shrink-0",children:[c.jsx("span",{className:"text-muted-foreground",children:"/"}),c.jsx("span",{className:"text-foreground",children:o})]})]}):c.jsx("span",{className:"truncate text-foreground",children:o})}),a.additions>0||a.deletions>0?c.jsxs("span",{className:"flex-shrink-0 inline-flex items-baseline gap-1 text-[0.75rem] tabular-nums",children:[a.additions>0?c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.additions]}):null,a.deletions>0?c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.deletions]}):null]}):null]},`${r.path}:${s}`)})})]}),L3="w-max min-w-[280px] max-w-full rounded-xl p-1 shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)] origin-[var(--transform-origin)]",R3={maxWidth:"calc(100cqw - 4ch)",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},P3=p.memo(({align:e="start"})=>{const[t,n]=p.useState(!1),r=p.useRef(null),s=Qn()??null,o=p.useContext(Ra),i=pu(s),a=bt(C=>s?C.directories.get(s)?.status??null:null),l=Fa(),d=te(C=>C.isMobile),{enabled:f}=nu(),u=d&&!f;p.useEffect(()=>{if(!t)return;const C=w=>{r.current&&!r.current.contains(w.target)&&n(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[t]);const h=p.useMemo(()=>!s||i!==!0||!a||a.isClean?[]:N3(a.files,a.diffStats,s),[i,a,s]),{totalAdded:m,totalRemoved:g}=p.useMemo(()=>{let C=0,w=0;for(const M of h)C+=M.insertions,w+=M.deletions;return{totalAdded:C,totalRemoved:w}},[h]);if(!s||i!==!0||h.length===0)return null;const x=C=>{if(!s||!y1(C))return;n(!1);const w=C.path;if(l){l.openChanges({diffPath:C.relativePath,staged:C.hasStagedChanges&&!C.hasWorkingChanges});return}const M=o?.editor;if(M){M.openFile(w);return}const j=te.getState(),T=C.hasStagedChanges&&!C.hasWorkingChanges;if(!j.isMobile){j.openContextDiff(s,C.relativePath,T);return}j.navigateToDiff(C.relativePath,T)},b=h.length,S=b===1?`${b} file`:`${b} files`,y=b===1?"1 change":`${b} changes`,v=c.jsxs(c.Fragment,{children:[c.jsx($,{name:"git-branch",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),u?c.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-ui-label",children:y}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-ui-label",children:S}),c.jsx("span",{className:"status-row__changed-label min-w-0 typography-ui-label text-foreground truncate",children:"changed"})]}),c.jsxs("span",{className:"inline-flex shrink-0 items-baseline gap-1 text-[0.75rem] tabular-nums",children:[m>0?c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}):null,g>0?c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",g]}):null]}),t?c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5 shrink-0"}):c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5 shrink-0"})]});return c.jsxs("div",{className:"relative",ref:r,children:[c.jsx("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 text-left text-muted-foreground",onClick:()=>n(C=>!C),"aria-expanded":t,children:v}),t&&c.jsx("div",{style:{...R3,maxWidth:"min(28rem, calc(100cqw - 4ch))"},className:R(L3,"absolute bottom-full mb-1 z-50",e==="end"?"right-0":"left-0","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:c.jsx(QD,{files:h,currentDirectory:s,onOpenFile:x})})]})});P3.displayName="PendingChangesBar";const eO=p.createContext("default"),gu=()=>p.useContext(eO);let kp=!1;const Mp=new Set,yd=()=>kp,zX=e=>{if(kp!==e){kp=e;for(const t of[...Mp])try{t()}catch{}}},tO=e=>(Mp.add(e),()=>{Mp.delete(e)}),D3=()=>p.useSyncExternalStore(tO,yd,yd);function nO({className:e,style:t,...n}){return c.jsx(Ls,{"data-slot":"command",style:{color:"var(--surface-elevated-foreground)",...t},className:R("flex h-full w-full flex-col overflow-hidden rounded-xl",e),...n})}const O3=H.forwardRef(({className:e,...t},n)=>c.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[c.jsx($,{name:"search",className:"size-4 shrink-0 opacity-50"}),c.jsx(Ls.Input,{ref:n,"data-slot":"command-input",className:R("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));O3.displayName="CommandInput";function rO({className:e,children:t,scrollbarClassName:n,disableHorizontal:r,...s}){return c.jsx(Xn,{as:Ls.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:R("scroll-py-1 overflow-x-hidden h-full min-h-0",e),scrollbarClassName:n??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:r??!0,...s,children:t})}function sO({...e}){return c.jsx(Ls.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...e})}function oO({className:e,...t}){return c.jsx(Ls.Group,{"data-slot":"command-group",className:R("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",e),...t})}function UX({className:e,...t}){return c.jsx(Ls.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",e),...t})}function iO({className:e,...t}){return c.jsx(Ls.Item,{"data-slot":"command-item",className:R("data-[selected=true]:bg-interactive-selection data-[selected=true]:text-interactive-selection-foreground data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function qX({className:e,...t}){const n=o=>{const i=o.trim().toLowerCase();return i==="ctrl"||i==="control"?c.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?c.jsx($,{name:"command",className:"size-3.5"}):i==="shift"||i==="⇧"?c.jsx($,{name:"arrow-up",className:"size-3.5"}):c.jsx("span",{className:"text-xs font-medium",children:o})},r=typeof t.children=="string"?t.children:"",s=r?r.split("+").map(o=>o.trim()).filter(Boolean):[];return c.jsx("span",{"data-slot":"command-shortcut",className:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",e),...t,children:s.length>0?s.map((o,i)=>c.jsxs(H.Fragment,{children:[i>0&&c.jsx("span",{className:"opacity-60 text-xs",children:"+"}),n(o)]},`${o}-${i}`)):t.children})}const eh=e=>{if(!e||typeof e!="object")return!1;const t=e;return t.code==="SESSION_BUSY"||typeof t.message=="string"&&t.message.includes("SESSION_BUSY")},WX=e=>!!(e&&typeof e=="object"&&e.deferred===!0),KX=e=>`${e} saved. It will apply when active sessions are idle.`,GX=e=>`${e} could not be changed while a session is running. Try again when it finishes.`,aO=5e3,_n=new Map,Tr=new Map,jr=new Map,la=new Map,po=(e,t)=>`${e}
72
+ ${t?.trim()??""}`,To=e=>{la.set(e,(la.get(e)??0)+1),Tr.delete(e)},ZX=e=>{const t=Y();if(typeof e=="string"&&e.trim().length>0){const r=po(t,e);_n.delete(r),To(r);return}const n=new Set([..._n.keys(),...Tr.keys(),...jr.keys()]);for(const r of n)r.startsWith(`${t}
73
+ `)&&(_n.delete(r),To(r))},th=e=>{const t=new Set([..._n.keys(),...Tr.keys(),...jr.keys()]);for(const n of t)n.startsWith(`${e}
74
+ `)&&(_n.delete(n),To(n))},Kc=e=>e.prompts.map(t=>({id:t.id,name:t.name,...typeof t.description=="string"?{description:t.description}:{},...typeof t.content=="string"?{content:t.content}:{},location:["global","project","package","path"].includes(t.location)?t.location:"path",editable:t.editable===!0})),Rl=Lt()(mr((e,t)=>({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null,setSelectedPrompt:n=>e({selectedPromptId:n}),setPromptDraft:n=>e({promptDraft:n}),resetForRuntimeSwitch:()=>{_n.clear(),Tr.clear(),jr.clear(),la.clear(),e({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null})},loadPrompts:async n=>{const r=Y(),s=typeof n=="string"&&n.trim().length>0?n.trim():void 0,o=po(r,s),i=Date.now(),a=jr.get(o);e({activeCacheKey:o,prompts:a??[],isLoading:!0});const l=_n.get(o)??0;if(l>0&&i-l<aO)return e({isLoading:!1}),!0;const d=Tr.get(o);if(d)return d;const f=la.get(o)??0,u=(async()=>{try{const h=s?await Ee.listResources(s,{runtimeKey:r}):await Ee.listResources({runtimeKey:r});if(Y()!==r)return!1;if((la.get(o)??0)!==f)return e(g=>g.activeCacheKey===o?{isLoading:!1}:g),!0;const m=Kc(h);return jr.set(o,m),_n.set(o,Date.now()),e(g=>g.activeCacheKey===o?{prompts:m,isLoading:!1,...g.selectedPromptId&&!m.some(x=>x.id===g.selectedPromptId)?{selectedPromptId:null}:{}}:g),!0}catch{return e(h=>h.activeCacheKey===o?{isLoading:!1}:h),!1}})();Tr.set(o,u);try{return await u}finally{Tr.get(o)===u&&Tr.delete(o)}},createPrompt:async(n,r,s)=>{const o=Y(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ee.createPromptTemplate({name:n,description:s.description,content:r,location:s.location},i,{runtimeKey:o});if(Y()!==o)return a.deferred===!0?"deferred":!0;const l=po(o,i),d=Kc(a);To(l),jr.set(l,d),th(o),_n.set(l,Date.now());const f=d.find(u=>u.name===n&&u.location===s.location);return e(u=>u.activeCacheKey===l?{prompts:d,promptDraft:null,selectedPromptId:f?.id??null,isLoading:!1}:u),ul(s.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return eh(a)?"busy":!1}},updatePrompt:async(n,r,s)=>{const o=Y(),i=t().prompts.find(l=>l.id===n);if(!i||i.editable!==!0)return!1;const a=typeof s=="string"&&s.trim().length>0?s.trim():void 0;if((i.location==="project"||r.location==="project")&&!a)return!1;try{const l=await Ee.updatePromptTemplate(i.id,{...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{},...r.content!==void 0?{content:r.content}:{},...r.location!==void 0?{location:r.location}:{}},a,{runtimeKey:o});if(Y()!==o)return l.deferred===!0?"deferred":!0;const d=po(o,a),f=Kc(l);To(d),jr.set(d,f),th(o),_n.set(d,Date.now());const u=f.find(h=>h.name===(r.name??i.name)&&h.location===(r.location??i.location));return e(h=>h.activeCacheKey===d?{prompts:f,selectedPromptId:u?.id??null,isLoading:!1}:h),ul(i.location==="global"||r.location==="global"?null:a),l.deferred===!0?"deferred":!0}catch(l){return eh(l)?"busy":!1}},deletePrompt:async(n,r)=>{const s=Y(),o=t().prompts.find(a=>a.id===n);if(!o||o.editable!==!0)return!1;const i=r?.trim()?r.trim():void 0;if(o.location==="project"&&!i)return!1;try{const a=await Ee.deletePromptTemplate(o.id,i,{runtimeKey:s});if(Y()!==s)return a.deferred===!0?"deferred":!0;const l=po(s,i),d=Kc(a);return To(l),jr.set(l,d),th(s),_n.set(l,Date.now()),e(f=>f.activeCacheKey===l?{prompts:d,...f.selectedPromptId===n?{selectedPromptId:null}:{},isLoading:!1}:f),ul(o.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return eh(a)?"busy":!1}},getPromptById:n=>t().prompts.find(r=>r.id===n)}),{name:"prompt-templates-store"})),cO="pichamber.json",lO=".pichamber",dO=[".config","pichamber","projects"];function v1(){const e=$r();return e?.files?e.files:null}const uO=80,fO=4e3,hO=2e3,pO=300,mO=new Set(["macos","linux","windows"]),Ao=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},ja=(e,t)=>{const n=Ao(e),r=t.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},H3=e=>ja(ja(e,lO),cO),yu=()=>{const e="/api";return e.startsWith("/"),e},x1=async(e,t)=>{try{const n=await Nt(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return n.ok?{ok:!0,data:await n.json().catch(()=>null)}:{ok:!1,data:null}}catch{return{ok:!1,data:null}}},gO=async e=>{const t=v1();if(t?.createDirectory)try{if((await t.createDirectory(e))?.success)return!0}catch{}return!!(await x1(`${yu()}/fs/mkdir`,{path:e})).ok},F3=async(e,t)=>{try{const n=await Nt(`${yu()}/fs/read`,{query:{path:e,optional:"true",...t?{directory:t}:{}},cache:"no-store"});return n.ok?await n.text():null}catch{return null}},yO=async(e,t)=>{const n=v1();if(n?.writeFile)try{if((await n.writeFile(e,t))?.success)return!0}catch{}return!!(await x1(`${yu()}/fs/write`,{path:e,content:t})).ok},B3=async()=>{const e=await OS();let t=e.home?Ao(e.home):null;const n=e.pichamberDataDir?Ao(e.pichamberDataDir):null;if(!t)try{const r=await HS();r&&r.trim().length>0&&(t=Ao(r))}catch{}return{home:t,pichamberDataDir:n}},vO=async()=>(await B3()).home,xO=async()=>(await B3()).pichamberDataDir,V3=async()=>{const e=await xO();if(e)return ja(e,"projects");const t=await vO();return t?dO.reduce((n,r)=>ja(n,r),t):null},bO=e=>{const t=typeof e?.path=="string"?e.path.trim():"",n=t?Ao(t):"";return n&&Jp(n)||null},$3=async e=>{const t=await V3();if(!t)return null;const n=bO(e);return n?ja(t,`${n}.json`):null},Gc=(e,t)=>e.length<=t?e:e.slice(0,t),wO=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(typeof r!="string")continue;const s=r.trim().toLowerCase();!mO.has(s)||n.has(s)||(n.add(s),t.push(s))}return t},SO=e=>{if(!Array.isArray(e))return[];const t=[],n=new Set;for(const r of e){if(!r||typeof r!="object")continue;const s=r,o=typeof s.id=="string"?s.id.trim():"",i=Gc(typeof s.name=="string"?s.name.trim():"",uO),a=Gc(typeof s.command=="string"?s.command.trim():"",fO);if(!o||!i||!a||n.has(o))continue;n.add(o);const l=typeof s.icon=="string"?s.icon.trim():"",d=wO(s.platforms),f=s.autoOpenUrl===!0,u=typeof s.openUrl=="string"?s.openUrl.trim():"",h=Gc(u,hO),m=typeof s.desktopOpenSshForward=="string"?s.desktopOpenSshForward.trim():"",g=Gc(m,pO);t.push({id:o,name:i,command:a,icon:l||null,...f?{autoOpenUrl:!0}:{},...h?{openUrl:h}:{},...g?{desktopOpenSshForward:g}:{},...d.length>0?{platforms:d}:{}})}return t},z3=e=>{const t=SO(e?.actions),n=typeof e?.primaryActionId=="string"?e.primaryActionId.trim():"",r=n&&t.some(s=>s.id===n)?n:null;return{actions:t,primaryActionId:r}};async function b1(e){const t=typeof e?.path=="string"?e.path.trim():"";if(!t)return null;const n=await $3(e),r=async(a,l)=>{const d=await F3(a,l);return d===null?null:d},s=a=>{if(typeof a!="string")return null;const l=a.trim();if(!l)return null;try{const d=JSON.parse(l);return!d||typeof d!="object"?null:d}catch{return null}};if(n){const a=s(await r(n));if(a)return a}const o=H3(t),i=s(await r(o,t));if(!i)return null;try{await U3(e,i)&&await MO(t)}catch{}return i}async function U3(e,t){const n=typeof e?.path=="string"?e.path.trim():"";if(!n)return!1;const r=await V3(),s=await $3(e);if(!r||!s)return!1;try{if(!await gO(r))return!1;const i=await F3(s);let a={};if(typeof i=="string"&&i.trim())try{const f=JSON.parse(i);f&&typeof f=="object"&&!Array.isArray(f)&&(a=f)}catch{a={}}const l={};a.version!==void 0&&(l.version=a.version);const d=JSON.stringify({...a,...t,...l,projectPath:Ao(n)},null,2);return await yO(s,d)}catch(o){return console.error("Failed to write pichamber config:",o),!1}}async function q3(e,t){const r={...await b1(e)||{},...t};return U3(e,r)}async function CO(e){const t=await b1(e);return h5(t?.draftStarters)}async function kO(e,t){return q3(e,{draftStarters:h5(t)})}async function YX(e){const t=await b1(e);return z3({actions:t?.projectActions,primaryActionId:t?.projectActionsPrimaryId})}async function XX(e,t){const n=z3({actions:t.actions,primaryActionId:t.primaryActionId});return q3(e,{projectActions:n.actions,projectActionsPrimaryId:n.primaryActionId??void 0})}async function MO(e){const t=H3(e),n=v1();if(n?.delete)try{await n.delete(t);return}catch{}try{await x1(`${yu()}/fs/delete`,{path:t})}catch{}}const IO=[],Si=(e,t)=>`${e}:${Ih(t)}`;function EO(){const e=te(L=>L.globalDraftStarters),t=Rl(L=>L.prompts),n=Rl(L=>L.activeCacheKey),r=Rl(L=>L.loadPrompts),s=at(L=>L.activeProjectId),o=at(L=>L.projects),i=Qn(),a=p.useMemo(()=>{if(!s)return null;const L=o.find(D=>D.id===s);return L?.path?{id:L.id,path:L.path}:null},[s,o]),[l,d]=p.useState([]),f=p.useRef(new Set),[u,h]=p.useState(0);p.useEffect(()=>{let L=!1;if(!a){d([]);return}return CO(a).then(D=>{L||d(D)}).catch(()=>{L||d([])}),()=>{L=!0}},[a]),p.useEffect(()=>en(()=>{f.current.clear(),h(D=>D+1),d([])}),[]);const m=p.useCallback(()=>{i&&r(i)},[i,r]);p.useEffect(()=>{if(!i)return;let L=!1;const D=Y();return r(i).then(W=>{L||Y()===D&&W&&(f.current.add(i),h(z=>z+1))}),()=>{L=!0}},[i,r]);const g=po(Y(),i),x=n===g,b=x?t:IO,S=p.useMemo(()=>FS(b),[b]),y=i?x&&f.current.has(i):!1,v=p.useCallback((L,D)=>{if(L.type==="text"){const z=BS[L.key];return z?{id:Si(D,L),ref:L,group:D,label:z.label,icon:z.icon,insertText:z.text,promptName:""}:null}return S.get(L.name)?{id:Si(D,L),ref:L,group:D,label:zu(L.name),icon:$u,insertText:`/${L.name} `,promptName:L.name}:y?null:{id:Si(D,L),ref:L,group:D,label:zu(L.name),icon:$u,insertText:`/${L.name} `,promptName:L.name}},[S,y]),C=p.useMemo(()=>e??gc,[e]),w=p.useMemo(()=>C.map(L=>v(L,"global")).filter(L=>L!==null),[C,v]),M=p.useMemo(()=>l.map(L=>v(L,"project")).filter(L=>L!==null),[l,v]),{global:j,project:T}=p.useMemo(()=>VS(M,w),[M,w]),A=p.useMemo(()=>{const L=new Set;for(const D of C)L.add(Ih(D));for(const D of l)L.add(Ih(D));return L},[C,l]),_=p.useMemo(()=>{const L=new Map;for(const D of b){if(D.editable!==!0||D.location!=="global"&&D.location!=="project")continue;const W=L.get(D.name),z=D.location==="project"?"project":"user",J={type:"prompt",name:D.name,label:zu(D.name),icon:$u,section:"prompt",scope:z};if(!W){L.set(D.name,J);continue}z==="project"&&W.scope!=="project"&&L.set(D.name,J)}return[...L.values()].filter(D=>!A.has(`${D.type}:${D.name}`))},[b,A]),k=p.useCallback(L=>{te.getState().setGlobalDraftStarters(L),Vr({draftStarters:L})},[]),E=p.useCallback(L=>{d(L),a&&kO(a,L)},[a]),I=p.useCallback(L=>{if(L.type!=="prompt")return;const D={type:"prompt",name:L.name};if(L.scope==="project"){if(!a||l.some(W=>yc(W,D)))return;E([...l,D])}else{const W=e??gc;if(W.some(z=>yc(z,D)))return;k([...W,D])}},[a,l,e,E,k]),N=p.useCallback((L,D)=>{L==="project"?E(l.filter(W=>!yc(W,D))):k((e??gc).filter(z=>!yc(z,D)))},[l,e,E,k]),O=p.useCallback((L,D,W)=>{const z=L==="project"?l:e??gc,J=z.findIndex(P=>Si(L,P)===D),B=z.findIndex(P=>Si(L,P)===W);if(J<0||B<0||J===B)return;const U=KC([...z],J,B);L==="project"?E(U):k(U)},[l,e,E,k]);return{global:j,project:T,pinnable:_,hasProject:!!a,ensureLoaded:m,addStarter:I,removeStarter:N,reorder:O}}const W3="__draft-starter-trash__",K3="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors",jO=[{key:"prompt",headingKey:"Prompts"}],_O=({item:e,onInsert:t,onRemove:n,hideRemove:r})=>{const{currentTheme:s}=Jn(),{attributes:o,listeners:i,setNodeRef:a,transform:l,transition:d,isDragging:f}=am({id:e.id}),u={backgroundColor:s?.colors?.surface?.elevated,borderColor:s?.colors?.interactive?.border};return c.jsxs("div",{ref:a,style:{transform:cm.Translate.toString(l),transition:d},className:R("group/chip relative",f&&"z-10 opacity-60"),children:[c.jsxs("button",{type:"button",...o,...i,onClick:()=>t(e),className:"group inline-flex touch-none select-none items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-[var(--interactive-hover)] hover:text-foreground",style:u,children:[c.jsx($,{name:e.icon,className:"h-3.5 w-3.5 shrink-0 opacity-70 transition-opacity group-hover:opacity-100"}),c.jsx("span",{className:"whitespace-nowrap",children:e.label})]}),r?null:c.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),n()},"aria-label":"Remove",title:"Remove",className:"absolute -right-1.5 -top-1.5 hidden h-4 w-4 items-center justify-center rounded-full border text-muted-foreground shadow-sm hover:text-foreground group-hover/chip:flex",style:u,children:c.jsx($,{name:"close",className:"h-2.5 w-2.5"})})]})},Py=({items:e,onInsert:t,onRemove:n,hideRemove:r})=>c.jsx(im,{items:e.map(s=>s.id),strategy:ZC,children:e.map(s=>c.jsx(_O,{item:s,onInsert:t,onRemove:()=>n(s),hideRemove:r},s.id))}),TO=()=>{const{currentTheme:e}=Jn(),{setNodeRef:t,isOver:n}=YC({id:W3});return c.jsx("button",{type:"button",ref:t,"aria-label":"Remove",title:"Remove",className:R(K3,n?"border-destructive text-destructive":"text-muted-foreground"),style:{backgroundColor:e?.colors?.surface?.elevated,borderColor:n?void 0:e?.colors?.interactive?.border},children:c.jsx($,{name:"delete-bin",className:"h-4 w-4"})})},AO=({pinnable:e,onPick:t,className:n})=>c.jsxs(nO,{className:R("min-h-0",n),children:[c.jsx(O3,{placeholder:"Search prompts…"}),c.jsxs(rO,{children:[c.jsx(sO,{children:"Nothing to add"}),jO.map(r=>{const s=e.filter(o=>o.section===r.key);return s.length===0?null:c.jsx(oO,{heading:r.headingKey,children:s.map(o=>c.jsx(iO,{value:`${o.section} ${o.label} ${o.name}`,onSelect:()=>t(o),children:c.jsx("span",{className:"truncate",children:o.label})},`${o.type}:${o.name}`))},r.key)})]})]}),NO=({pinnable:e,onOpen:t,onAdd:n})=>{const{currentTheme:r}=Jn(),[s,o]=p.useState(!1);return c.jsxs(ru,{open:s,onOpenChange:i=>{o(i),i&&t()},children:[c.jsx(Wj,{asChild:!0,children:c.jsx("button",{type:"button","aria-label":"Add a starter",title:"Add a starter",className:R(K3,"text-muted-foreground hover:bg-[var(--interactive-hover)] hover:text-foreground"),style:{backgroundColor:r?.colors?.surface?.elevated,borderColor:r?.colors?.interactive?.border},children:c.jsx($,{name:"add",className:"h-4 w-4"})})}),c.jsxs(su,{className:"gap-0 overflow-hidden p-0 sm:max-w-sm",children:[c.jsx(ou,{className:"px-4 pb-2 pt-4 text-left",children:c.jsx(iu,{children:"Add a starter"})}),c.jsx(AO,{pinnable:e,onPick:i=>{n(i),o(!1)},className:"flex max-h-[60vh] flex-col"})]})]})},LO=({onInsert:e,className:t})=>{const{global:n,project:r,pinnable:s,ensureLoaded:o,addStarter:i,removeStarter:a,reorder:l}=EO(),{isMobile:d}=On(),[f,u]=p.useState(!1),h=rm(ma(b5,{activationConstraint:{distance:8}}),ma(x5,{activationConstraint:{delay:200,tolerance:6}})),m=p.useCallback(S=>n.find(y=>y.id===S)??r.find(y=>y.id===S),[n,r]),g=()=>u(!0),x=()=>u(!1),b=S=>{u(!1);const{active:y,over:v}=S;if(!v)return;const C=String(y.id),w=m(C);if(!w)return;if(String(v.id)===W3){a(w.group,w.ref);return}const M=String(v.id);if(C===M)return;const j=m(M);j&&j.group===w.group&&l(w.group,C,M)};return c.jsx(sm,{sensors:h,collisionDetection:om,measuring:{droppable:{strategy:GC.Always}},onDragStart:g,onDragCancel:x,onDragEnd:b,children:c.jsxs("div",{className:R("flex flex-wrap items-center justify-center gap-2",t),children:[n.length>0?c.jsx(Py,{items:n,onInsert:e,onRemove:S=>a("global",S.ref),hideRemove:d}):null,r.length>0?c.jsx(Py,{items:r,onInsert:e,onRemove:S=>a("project",S.ref),hideRemove:d}):null,d&&f?c.jsx(TO,{}):c.jsx(NO,{pinnable:s,onOpen:o,onAdd:i})]})})},G3=e=>te(n=>n.draftStartersVisible)?c.jsx(LO,{...e}):null,Z3=()=>{const e=pe(i=>i.currentSessionId),t=cw(),n=pe(i=>i.newSessionDraft),r=at(i=>i.activeProjectId),s=at(i=>i.projects),o=nt(i=>i.currentDirectory);if(e){const i=t.find(a=>a.id===e);if(i?.directory)return i.directory}if(n?.open&&n.directoryOverride)return n.directoryOverride??void 0;if(r){const i=s.find(a=>a.id===r);if(i?.path)return i.path}return o??void 0},Ci=new Map,RO=(e,t)=>`${e}
75
+ ${t?.trim()??""}`;function Y3(e){const t=e?.trim()?e.trim():void 0,n=p.useSyncExternalStore(A6,Gu,Gu),r=Rl(m=>m.prompts.map(g=>`${g.id}:${g.name}:${g.location}`).join("|")),s=Dr(m=>m.skills.map(g=>`${g.id}:${g.name}:${g.scope}`).join("|")),[o,i]=p.useState(()=>{if(!t)return Cr();const m=Xg(Y(),t);return m?[...Cr(),...m]:Cr()}),[a,l]=p.useState(!1),[d,f]=p.useState(0),u=p.useRef(void 0),h=p.useRef({promptSignature:"",skillSignature:""});return p.useEffect(()=>{h.current={promptSignature:r,skillSignature:s}},[r,s]),p.useEffect(()=>en(()=>{O6(),Ci.clear(),u.current=void 0,i(Cr()),f(g=>g+1)}),[]),p.useEffect(()=>{const m=Y(),g=RO(m,t),x=`${g}
76
+ ${n}`;if(!t){u.current=g,i(Cr());return}if(u.current!==g){u.current=g;const v=Xg(m,t);i(v?[...Cr(),...v]:Cr())}const b=L6(m,t);if(b&&R6(b)){const v=b.promptSignature!==""&&b.promptSignature!==r,C=b.skillSignature!==""&&b.skillSignature!==s;if(!v&&!C){(b.promptSignature!==r||b.skillSignature!==s)&&D6(m,t,r,s),l(!1);return}}let S=!1;l(!0);const y=()=>{const v=Ci.get(x);let C;if(v)C=v;else{const w=n,M=h.current.promptSignature,j=h.current.skillSignature,T={},A=(async()=>{try{const _=await Ee.listCommands(t,{runtimeKey:m});if(Y()!==m||Gu()!==w)return null;const k=_6(_.commands);return P6(m,t,k,{promptSignature:M,skillSignature:j}),k}catch{return null}finally{Ci.get(x)?.promise===T.promise&&Ci.delete(x)}})();T.promise=A,C={promise:A,promptSignature:M,skillSignature:j},Ci.set(x,C)}C.promise.then(w=>{if(!S&&Y()===m){if(w){i([...Cr(),...w]);const M=h.current,j=C.promptSignature!==""&&C.promptSignature!==M.promptSignature,T=C.skillSignature!==""&&C.skillSignature!==M.skillSignature;if(j||T){y();return}}l(!1)}}).catch(()=>{S||l(!1)})};return y(),()=>{S=!0}},[t,r,s,d,n]),{commands:o,isLoading:a}}const PO=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer"],DO=e=>typeof e=="string"&&PO.includes(e),OO=e=>{switch(e){case"concise":return"Keep replies short. Answer first, no preamble or recap of the question. Write like you're texting a colleague who already has the context — plain sentences, not headings or bullets. Reach for a list only when the content is genuinely a list; never use one to look organised.";case"detailed":return"Take the space you need to actually explain things. Walk through what's going on, why it matters, and where the real tradeoffs are. Prefer flowing prose over bullet points and headings — structure the answer with paragraphs and let the reasoning carry it. Lists are fine when something really is enumerable, but don't fragment a normal explanation into bullets.";case"mentor":return"Talk like a patient senior engineer pairing with someone less experienced. Explain the underlying idea before the answer, think out loud about how you'd approach it, and drop in a small concrete example when it actually helps. Keep it conversational — no lecture format, no checklists, no numbered steps unless the task literally is a sequence.";case"pushback":return"Don't agree automatically. If something I say sounds off — a wrong assumption, a flawed approach, a request that won't actually do what I think it will — push back first. Explain what you disagree with and why, and only proceed once I've responded. Disagreement is welcome; sycophancy is not. Don't soften it with 'you might want to consider' — just say it.";case"noFiller":return"Cut the filler. No 'Great question', no 'Certainly', no 'I'll help you with that', no restating what I just asked. No closing summary of what you did when the diff or output already shows it. No trailing 'let me know if you need anything else'. Open with the actual content and stop when you're done.";case"matchEnergy":return"Mirror the size and register of my message. A one-line question gets a one-line answer. A casual aside gets a casual reply, not a structured breakdown. If I write three words, don't respond with three paragraphs. Match the tone too — informal stays informal, technical stays technical. Don't inflate small asks into full essays.";case"warmPeer":return"Talk like a colleague, not an assistant. First person is fine and encouraged — 'I'd do this', 'I don't love that approach', 'that was sloppy of me'. Have actual opinions and share them. Push back when you disagree. Admit when you screwed up without grovelling. Skip the corporate helpfulness and performative politeness — just be a person."}},HO=({enabled:e,preset:t,customInstructions:n})=>e?t==="custom"?(typeof n=="string"?n.trim():"")||null:DO(t)?OO(t):null:null,X3=(e,t)=>{const n=e.reducer.bySession.get(t);return e.hydratedSessionIds.has(t)&&!e.sessionLoadErrorById.has(t)&&n!==void 0&&n.hasMoreBefore!==!0&&![...n.messages.values()].some(r=>r.role==="user")},FO=e=>e.newSessionDraftOpen||(e.sessionId!==null?X3(e.storeState,e.sessionId):!1),J3=e=>HO({enabled:e.responseStyleEnabled===!0,preset:e.responseStylePreset,customInstructions:e.responseStyleCustomInstructions});let da=null,io=null;const BO=e=>{da={runtimeKey:Y(),value:J3(e)}};typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{BO(e.detail??{})});en(e=>{e.runtimeKey!==e.previousRuntimeKey&&(da=null,io=null)});const VO=async()=>{const e=Y();if(da?.runtimeKey===e)return da.value;if(io?.runtimeKey===e)return io.promise;const t=(async()=>{const n=await Nt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return null;const r=await n.json().catch(()=>null);if(!r||Y()!==e)return null;const s=J3(r);return da={runtimeKey:e,value:s},s})();io={runtimeKey:e,promise:t};try{return await t}finally{io?.promise===t&&(io=null)}},$O=async e=>{if(!FO({newSessionDraftOpen:e.newSessionDraftOpen,sessionId:e.sessionId,storeState:e.getStoreState()}))return null;const t=await VO().catch(()=>null);return!t||!e.newSessionDraftOpen&&e.sessionId!==null&&!X3(e.getStoreState(),e.sessionId)?null:t},Dy="<system-reminder>",Oy="</system-reminder>",zO=e=>{const t=e.trim();return t?t.startsWith(Dy)&&t.endsWith(Oy)?t:`${Dy}
77
+ ${t}
78
+ ${Oy}`:""},Hy=e=>e.includes("@")?"paste":"manual",UO=({value:e,cursorPosition:t,inputSource:n="manual",insertedText:r})=>{if(n==="paste"&&r?.includes("@"))return null;const s=e.substring(0,t),o=s.lastIndexOf("@");if(o===-1)return null;const i=o>0?s[o-1]:null,a=s.substring(o+1);return!(!i||/\s/.test(i))||a.includes(" ")||a.includes(`
79
+ `)?null:a},qO=/[\s()[\]{}<>"'`,.;:]/,WO=/^[`"'<([{]+/,KO=/[)\]},.;:!?`"'>]+$/,Fy=/@([^\s]+)/g;function GO(e,t){return t<=0?!0:qO.test(e[t-1])}function ZO(e){return e.trim().replace(WO,"").replace(KO,"")}function YO(e){if(!e||!e.includes("@"))return[];const t=[];Fy.lastIndex=0;let n;for(;(n=Fy.exec(e))!==null;){const r=n.index;if(!GO(e,r))continue;const s=n[1]??"",o=ZO(s);if(!o)continue;const i=r+1+s.indexOf(o);t.push({start:r,end:i+o.length,raw:n[0],name:o})}return t}function XO(e,t){return!e||e.includes("<")||e.includes(">")?null:t.knownAgentNames.has(e.toLowerCase())?"agent":JO(e,t.confirmedMentions)?"file":null}function JO(e,t){return e.includes("/")||e.includes("\\")||e.includes(".")||t.has(e)}const QO=(e,t)=>t<=0||/\s/.test(e[t-1]);function eH(e,t){if(!e.startsWith("/")||e.indexOf(" ")!==-1)return null;const r=e.indexOf(`
80
+ `),s=r===-1?e.length:r;return t>s?null:{kind:"command",query:e.substring(1,s)}}function tH(e,t,n,r){const s=e.substring(0,t),o=s.lastIndexOf(n);if(o===-1||!QO(s,o))return null;const i=s.substring(o+1);return i.includes(" ")||i.includes(`
81
+ `)?null:{kind:r,query:i}}function nH(e,t,n){return n.inputMode==="shell"?null:eH(e,t)??tH(e,t,"#","snippet")??rH(e,t,n)}function rH(e,t,n){const r=UO({value:e,cursorPosition:t,inputSource:n.inputSource,insertedText:n.insertedText});return r===null?null:{kind:"mention",query:r}}const sH=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),By=new Set(["image","screenshot","screen-shot","clipboard","pasted-image","pastedimage","untitled","unknown","file","blob"]),oH={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/heic":"heic","image/heif":"heif","image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/svg+xml":"svg","image/tiff":"tiff","image/webp":"webp"},As=e=>e.trim().toLowerCase(),iH=e=>e.charCodeAt(0)<32||'<>:"/\\|?*[]'.includes(e),aH=e=>{const t=e.replace(/\\/g,"/").split("/").pop()??"";return Array.from(t).map(n=>iH(n)?"-":n).join("").replace(/\s+/g," ").replace(/-+/g,"-").trim()},cH=e=>{const t=e?.trim().toLowerCase()??"";return oH[t]??"png"},Q3=e=>{const t=aH(e.name),n=cH(e.type),r=t.lastIndexOf(".");if(r>0&&r<t.length-1){const s=t.slice(r+1).toLowerCase();if(/^[a-z0-9]{1,10}$/.test(s))return{base:t.slice(0,r).trim()||"image",ext:s}}return{base:t.trim()||"image",ext:n}},lH=e=>{const{base:t}=Q3({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(By.has(n))return!0;const r=n.replace(/-\(\d+\)$/g,"");return r!==n&&By.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},No=(e,t)=>`${e}.${t}`,dH=(e,t,n)=>{const r=No(e,t);if(!n.has(As(r)))return r;for(let s=2;s<Number.MAX_SAFE_INTEGER;s+=1){const o=No(`${e}-${s}`,t);if(!n.has(As(o)))return o}return No(`${e}-${Date.now()}`,t)},uH=(e,t)=>{for(let n=1;n<Number.MAX_SAFE_INTEGER;n+=1){const r=No(`image-${n}`,e);if(!Array.from(t).some(o=>o.startsWith(`image-${n}.`))&&!t.has(As(r)))return r}return No(`image-${Date.now()}`,e)},fH=(e,t)=>{const n=new Set(t.map(As));return e.map(r=>{const{base:s,ext:o}=Q3(r),i=lH(No(s,o))?uH(o,n):dH(s,o,n);return n.add(As(i)),i})},hH=e=>e.map(t=>`[${t}]`).join(" "),pH=(e,t)=>{if(!e||!e.includes("[")||t.length===0)return[];const n=new Set(t.map(As)),r=[];let s=0;for(;s<e.length;){const o=e.indexOf("[",s);if(o===-1)break;const i=e.indexOf("]",o+1);if(i===-1)break;if(e[i+1]!=="("){const a=e.slice(o+1,i).trim();n.has(As(a))&&r.push({start:o,end:i+1})}s=i+1}return r},mH=e=>{switch(e){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return"shell";case"json":case"jsonc":case"json5":return"json";case"js":case"javascript":case"jsx":case"ts":case"typescript":case"tsx":return"javascript";case"html":case"heex":case"eex":case"leex":return"html";case"css":return"css";case"py":case"python":return"python";case"md":case"markdown":case"mdown":case"mkd":return"markdown";default:return null}},e4=e=>e.trim().toLowerCase(),Ip=new Map,Zc=new Map;let Yc=null;const gH=async(e,t)=>{switch(e){case"javascript":{const{javascript:n}=await mt(async()=>{const{javascript:r}=await import("./vendor-codemirror-lang-javascript-Dkzl3s07.js");return{javascript:r}},__vite__mapDeps([44,45,46,5,1,6,47]));switch(t){case"jsx":return n({jsx:!0}).language;case"ts":case"typescript":return n({typescript:!0}).language;case"tsx":return n({typescript:!0,jsx:!0}).language;default:return n().language}}case"json":{const{json:n}=await mt(async()=>{const{json:r}=await import("./vendor-codemirror-lang-json-CsdmtHhi.js");return{json:r}},__vite__mapDeps([48,49,46,5,1,6]));return n().language}case"css":{const{css:n}=await mt(async()=>{const{css:r}=await import("./vendor-codemirror-lang-css-2bFuyM70.js");return{css:r}},__vite__mapDeps([50,51,46,5,1,6]));return n().language}case"html":{const{html:n}=await mt(async()=>{const{html:r}=await import("./vendor-codemirror-lang-html-BV8lrR8v.js");return{html:r}},__vite__mapDeps([52,53,46,5,1,6,50,51,44,45,47]));return n().language}case"markdown":{const{markdown:n}=await mt(async()=>{const{markdown:r}=await import("./vendor-codemirror-lang-markdown-C0Zu3b3n.js");return{markdown:r}},__vite__mapDeps([54,5,1,6,47,55,52,53,46,50,51,44,45]));return n().language}case"python":{const{python:n}=await mt(async()=>{const{python:r}=await import("./vendor-codemirror-lang-python-Cv2exx_M.js");return{python:r}},__vite__mapDeps([56,57,46,5,1,6,47]));return n().language}case"shell":{if(Yc)return Yc;const{shell:n}=await mt(async()=>{const{shell:r}=await import("./shell-CjFT_Tl9.js");return{shell:r}},[]);return Yc=XC.define(n),Yc}}},t4=e=>e?Ip.get(e4(e))??null:null,yH=e=>{const t=e4(e);if(!t)return Promise.resolve(null);const n=Ip.get(t);if(n)return Promise.resolve(n);const r=Zc.get(t);if(r)return r;const s=mH(t);if(!s)return Promise.resolve(null);const o=gH(s,t).then(i=>(i&&Ip.set(t,i),Zc.delete(t),i)).catch(()=>(Zc.delete(t),null));return Zc.set(t,o),o},vH={mentionFile:100,mentionAgent:100,mentionCommand:100,mentionSnippet:100,code:90,codeFence:90,path:85,link:80,linkUrl:78,heading:70,attention:60,strong:50,emphasis:50,blockquote:40,listMarker:35,marker:10},Vy={mentionFile:"text-[var(--status-info)]",mentionAgent:"text-[var(--status-success)]",mentionCommand:"text-[var(--primary)]",mentionSnippet:"text-[var(--status-warning)]",code:"rounded-[3px] bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]",codeFence:"bg-[var(--surface-subtle)] text-[var(--markdown-inline-code)]",path:"text-[var(--status-info)]",link:"text-[var(--status-info)] underline",linkUrl:"text-muted-foreground",heading:"text-[var(--syntax-keyword)]",attention:"font-semibold text-[var(--status-warning)]",blockquote:"text-muted-foreground",listMarker:"text-[var(--syntax-keyword)]",marker:"text-muted-foreground",strong:"font-semibold",emphasis:"italic"},xH=new Set(["strong","emphasis"]),n4="text-foreground";function bH(e,t,n){const r=t>0?e[t-1]:"",s=e[t+n];return!s||/\s/.test(s)||e[t]==="_"&&/[\w]/.test(r)?!1:r===""||!/[\w]/.test(r)||e[t]==="*"}function wH(e,t,n){const r=e[t-1],s=e[t+n];return!(!r||/\s/.test(r)||e[t]==="_"&&s&&/[\w]/.test(s))}function SH(e,t){const n=e[t],r=/^(\*{1,3}|_{1,3})/.exec(e.slice(t))?.[1]??"";if(!r||!bH(e,t,r.length))return null;let s=t+r.length;for(;s<e.length;){const o=e.indexOf(r,s);if(o===-1)return null;if(e[o+r.length]===n){s=o+r.length+1;continue}if(wH(e,o,r.length))return{end:o+r.length,runLength:r.length};s=o+r.length}return null}function ao(e,t,n){let r=0;const s=e.length;for(;r<s;){const o=e[r];if(o==="`"){const i=/^`+/.exec(e.slice(r))?.[0]??"",a=e.indexOf(i,r+i.length);if(a!==-1){const l=a+i.length;n.push({start:t+r,end:t+l,style:"code"}),r=l;continue}}if(o==="["){const i=/^\[([^\]\n]*)\]\(([^)\n]*)\)/.exec(e.slice(r));if(i){const a=t+r,l=i[1].length,d=i[2].length,f=a+1,u=f+l,h=u+2,m=h+d,g=m+1;n.push({start:a,end:f,style:"marker"}),l>0&&n.push({start:f,end:u,style:"link"}),n.push({start:u,end:h,style:"marker"}),d>0&&n.push({start:h,end:m,style:"linkUrl"}),n.push({start:m,end:g,style:"marker"}),r+=i[0].length;continue}}if(o==="*"||o==="_"){const i=SH(e,r);if(i){const a=t+r+i.runLength,l=t+i.end-i.runLength;n.push({start:t+r,end:a,style:"marker"}),i.runLength>=2&&n.push({start:a,end:l,style:"strong"}),i.runLength!==2&&n.push({start:a,end:l,style:"emphasis"}),n.push({start:l,end:t+i.end,style:"marker"}),ao(e.slice(r+i.runLength,i.end-i.runLength),a,n),r=i.end;continue}}r+=1}}const CH=/^(\s*)(`{3,}|~{3,})\s*(\S*)/;function w1(e){const t=CH.exec(e);return t?{marker:t[2],lang:t[3]||""}:null}function r4(e,t){return new RegExp(`^\\s*\\${t[0]}{${t.length},}\\s*$`).test(e)}function kH(e){const t=[];if(!e)return t;let n=0,r=!1,s="";const o=e.split(`
82
+ `);for(let i=0;i<o.length;i+=1){const a=o[i],l=n,d=l+a.length;if(n=d+1,r){t.push({start:l,end:d,style:"codeFence"}),r4(a,s)&&(r=!1);continue}const f=w1(a);if(f){r=!0,s=f.marker,t.push({start:l,end:d,style:"codeFence"});continue}const u=/^(\s*)(!!!)(\s+)/.exec(a);if(u){const x=l+u[1].length,b=x+u[2].length;t.push({start:x,end:b,style:"marker"});const S=b+u[3].length;d>S&&(t.push({start:S,end:d,style:"attention"}),ao(a.slice(S-l),S,t));continue}const h=/^(\s*)(#{1,6})(\s+)/.exec(a);if(h){const x=l+h[1].length,b=x+h[2].length;t.push({start:x,end:b,style:"marker"});const S=b+h[3].length;d>S&&(t.push({start:S,end:d,style:"heading"}),ao(a.slice(S-l),S,t));continue}const m=/^(\s*)(>+)(\s?)/.exec(a);if(m){const x=l+m[1].length,b=x+m[2].length;t.push({start:x,end:b,style:"marker"});const S=b+m[3].length;d>S&&(t.push({start:S,end:d,style:"blockquote"}),ao(a.slice(S-l),S,t));continue}const g=/^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(a);if(g){const x=l+g[1].length,b=x+g[2].length;t.push({start:x,end:b,style:"listMarker"});const S=b+g[3].length;ao(a.slice(S-l),S,t);continue}ao(a,l,t)}return t}function MH(e,t){if(!e||t.length===0)return[];const n=e.length,r=new Set([0,n]);for(const d of t)d.start>0&&d.start<n&&r.add(d.start),d.end>0&&d.end<n&&r.add(d.end);const s=[...r].sort((d,f)=>d-f),o=t.map((d,f)=>({range:d,index:f})).filter(d=>d.range.end>d.range.start).sort((d,f)=>d.range.start-f.range.start),i=[],a=[];let l=0;for(let d=0;d<s.length-1;d+=1){const f=s[d],u=s[d+1];if(u<=f)continue;for(;l<o.length&&o[l].range.start<=f;)a.push(o[l]),l+=1;for(let v=a.length-1;v>=0;v-=1)a[v].range.end<=f&&a.splice(v,1);let h=null,m=-1,g=1/0;const x=[];for(const{range:v,index:C}of a){if(xH.has(v.style)){const M=v.className??Vy[v.style];x.includes(M)||x.push(M);continue}const w=v.priority??vH[v.style];(w>m||w===m&&C<g)&&(m=w,g=C,h=v)}const b=h?h.className??Vy[h.style]:n4,S=x.length>0?[b,...x].join(" "):b,y=i[i.length-1];y&&y.className===S&&y.end===f?y.end=u:i.push({start:f,end:u,className:S})}return i}const IH=n4;function EH(e){return e.map(t=>({start:t.start,end:t.end,style:t.kind==="file"?"mentionFile":"mentionAgent"}))}const ar="bg-[var(--surface-subtle)]",jH=91,_H=94,nh={keyword:8,function:7,type:6,string:5,number:5,variable:4,operator:3,comment:2},TH={keyword:`${ar} text-[var(--syntax-keyword)]`,string:`${ar} text-[var(--syntax-string)]`,number:`${ar} text-[var(--syntax-number)]`,comment:`${ar} text-[var(--syntax-comment)]`,function:`${ar} text-[var(--syntax-function)]`,type:`${ar} text-[var(--syntax-type)]`,variable:`${ar} text-[var(--syntax-variable)]`,operator:`${ar} text-[var(--syntax-operator)]`},AH=QC([{tag:[Pe.comment,Pe.lineComment,Pe.blockComment,Pe.docComment,Pe.meta],class:"comment"},{tag:[Pe.keyword,Pe.modifier,Pe.controlKeyword,Pe.operatorKeyword,Pe.definitionKeyword,Pe.moduleKeyword,Pe.self,Pe.null],class:"keyword"},{tag:[Pe.string,Pe.special(Pe.string),Pe.docString,Pe.character,Pe.regexp],class:"string"},{tag:[Pe.number,Pe.integer,Pe.float,Pe.bool,Pe.atom],class:"number"},{tag:[Pe.function(Pe.variableName),Pe.function(Pe.propertyName),Pe.macroName,Pe.standard(Pe.variableName)],class:"function"},{tag:[Pe.typeName,Pe.className,Pe.namespace,Pe.tagName],class:"type"},{tag:[Pe.variableName,Pe.propertyName,Pe.attributeName,Pe.labelName,Pe.definition(Pe.variableName)],class:"variable"},{tag:[Pe.operator,Pe.punctuation,Pe.bracket,Pe.derefOperator,Pe.separator],class:"operator"},{tag:[Pe.heading,Pe.heading1,Pe.heading2,Pe.heading3,Pe.heading4,Pe.heading5,Pe.heading6,Pe.strong],class:"keyword"},{tag:[Pe.emphasis,Pe.quote],class:"type"},{tag:[Pe.link,Pe.url],class:"function"},{tag:[Pe.monospace],class:"string"},{tag:[Pe.strikethrough],class:"comment"}]),NH=e=>{let t=null;for(const n of e.split(" ")){const r=n;nh[r]!==void 0&&(t===null||nh[r]>nh[t])&&(t=r)}return t?TH[t]:null},LH=2e4,RH=e=>e?t4(e):null;async function PH(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return!1;const t=new Set;for(const r of e.split(`
83
+ `)){const s=w1(r);s?.lang&&(t4(s.lang)||t.add(s.lang))}return t.size===0?!1:(await Promise.all([...t].map(r=>yH(r)))).some(r=>r!==null)}function DH(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return[];const t=[],n=e.split(`
84
+ `);let r=0;for(let s=0;s<n.length;s+=1){const o=n[s];r+=o.length+1;const i=w1(o);if(!i)continue;const a=RH(i.lang),l=r,d=[];let f=s+1,u=r;for(;f<n.length;f+=1){const m=n[f];if(r4(m,i.marker)){u+=m.length+1;break}d.push(m),u+=m.length+1}if(s=f,r=u,!a||d.length===0)continue;const h=d.join(`
85
+ `);if(h.trim()&&(t.push({start:l,end:l+h.length,style:"codeFence",className:`${ar} text-[var(--syntax-foreground)]`,priority:jH}),!(h.length>LH)))try{const m=a.parser.parse(h);JC(m,AH,(g,x,b)=>{const S=NH(b);S&&t.push({start:l+g,end:l+x,style:"codeFence",className:S,priority:_H})})}catch{}}return t}const $y=/~([^\s~]+)/g,OH=/[)\]},.;:!?`"'>]+$/,HH=/[\s()[\]{}<>"'`,;:]/;function FH(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z]/.test(e)}function BH(e){if(!e||!e.includes("~"))return[];const t=[];$y.lastIndex=0;let n;for(;(n=$y.exec(e))!==null;){const r=n.index,s=r>0?e[r-1]:"";if(s&&!HH.test(s))continue;const o=(n[1]??"").replace(OH,"");!o||!FH(o)||t.push({start:r,end:r+1+o.length,path:o})}return t}function VH(e){return BH(e).map(t=>({start:t.start,end:t.end,style:"path"}))}const $H="[A-Za-z0-9][A-Za-z0-9_-]*",zH="[A-Za-z0-9][^\\s/]*",UH={"/":new RegExp(`(^|\\s)\\/(${zH})`,"g"),"#":new RegExp(`(^|\\s)#(${$H})`,"g")};function Ep(e,t){if(!e||!e.includes(t))return[];const n=UH[t],r=[];n.lastIndex=0;let s;for(;(s=n.exec(e))!==null;){const o=s[2],i=s.index+s[1].length;r.push({start:i,end:i+1+o.length,prefix:t,name:o})}return r}function jp(e,t,n="case-insensitive"){return t.size===0?[]:e.filter(r=>t.has(n==="exact"?r.name:r.name.toLowerCase()))}function qH(e,t,n,r="case-insensitive"){const s=new Set,o=[];for(const i of jp(Ep(e,t),n,r))s.has(i.name)||(s.add(i.name),o.push(i.name));return o}function WH(e,t){const n=[];for(const r of YO(e)){const s=XO(r.name,t);s&&n.push({start:r.start,end:r.end,kind:s})}return n}function KH(e,t){if(!e||t.inputMode==="shell")return[];const n=[...kH(e),...DH(e),...EH(WH(e,t)),...VH(e)];for(const r of jp(Ep(e,"/"),t.knownSlashNames))n.push({start:r.start,end:r.end,style:"mentionCommand"});for(const r of jp(Ep(e,"#"),t.knownSnippetTriggers))n.push({start:r.start,end:r.end,style:"mentionSnippet"});if(t.attachmentFilenames.length>0&&e.includes("["))for(const r of pH(e,[...t.attachmentFilenames]))n.push({...r,style:"mentionFile"});return n}const S1=E5.define(),s4=E5.define(),_p=j5.define({create:()=>o4,update(e,t){for(const n of t.effects)if(n.is(S1))return n.value;return e}}),o4={inputMode:"normal",knownAgentNames:new Set,confirmedMentions:new Set,knownSlashNames:new Set,knownSnippetTriggers:new Set,attachmentFilenames:[]};function zy(e,t){const n=new t8;for(const r of MH(e,KH(e,t)))r.className!==IH&&n.add(r.start,r.end,n8.mark({class:r.className}));return n.finish()}const GH=j5.define({create:e=>zy(e.doc.toString(),e.field(_p)),update(e,t){const n=t.effects.some(s=>s.is(S1)),r=t.effects.some(s=>s.is(s4));return!t.docChanged&&!n&&!r?e:zy(t.state.doc.toString(),t.state.field(_p))},provide:e=>bn.decorations.from(e)}),ZH=e8.fromClass(class{generation=0;constructor(e){this.ensure(e)}update(e){e.docChanged&&this.ensure(e.view)}async ensure(e){const t=++this.generation,n=e.state.doc.toString();if(!n.includes("```")&&!n.includes("~~~"))return;let r=!1;try{r=await PH(n)}catch{return}t===this.generation&&r&&e.state.doc.toString()===n&&e.dispatch({effects:s4.of(void 0)})}});function YH(e=o4){return[_p.init(()=>e),GH,ZH]}const XH={"&":{backgroundColor:"transparent",color:"var(--surface-foreground)"},"&.cm-focused":{outline:"none"},".cm-content":{padding:"0",fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",minHeight:"100%"},"&.cm-editor .cm-cursor, &.cm-editor .cm-dropCursor":{borderLeftColor:"var(--surface-foreground)",borderLeftWidth:"2px",marginLeft:"0",transform:"scaleY(1.15)",transformOrigin:"center"},".cm-line":{padding:"0"},".cm-scroller":{fontFamily:"inherit",fontSize:"inherit",lineHeight:"inherit",overflowX:"hidden"},".cm-placeholder":{color:"var(--surface-muted-foreground)"},"&.cm-editor .cm-selectionBackground, & .cm-selectionBackground":{background:"color-mix(in srgb, var(--interactive-selection) 45%, transparent)"},"&.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"color-mix(in srgb, var(--interactive-selection) 55%, transparent)"},"& ::selection":{background:"color-mix(in srgb, var(--primary) 25%, transparent)"}},JH=bn.theme(XH),QH={"& .cm-content .cm-line ::selection, & .cm-content .cm-line::selection":{backgroundColor:"color-mix(in srgb, var(--primary) 25%, transparent) !important"},"&.cm-editor.oc-native-range .cm-content, &.cm-editor.oc-native-range .cm-content .cm-line":{caretColor:"var(--surface-foreground) !important"},"&.oc-native-range .cm-scroller > .cm-cursorLayer":{display:"none"},"& .cm-scroller > .cm-selectionLayer":{display:"none"}},eF=bn.theme(QH),tF=[eF,bn.editorAttributes.of(e=>e.state.selection.main.empty?null:{class:"oc-native-range"})];function nF(e,t){if(!e||e.state.readOnly||!e.contentDOM.isContentEditable||e.contentDOM.contains(t.target))return;t.preventDefault();const n=e.posAtCoords({x:t.clientX,y:t.clientY})??e.state.doc.length;e.focus(),e.dispatch({selection:{anchor:n}})}function rF(e){let t="";return e.changes.iterChanges((n,r,s,o,i)=>{t+=i.toString()}),t}function Uy(e){return!!e.synthetic}const qy=new _5,Wy=new _5,sF=p.forwardRef(function(t,n){const{value:r,languageContext:s,placeholder:o,editable:i=!0,spellCheck:a=!1,autoCorrect:l=!1,autoCapitalize:d="none",fillContainer:f=!1,maxLines:u=8,boundSelector:h,boundGapPx:m=0,className:g,contentClassName:x,commandComboboxExpanded:b,commandComboboxListboxId:S,commandComboboxActiveOptionId:y}=t,v=p.useRef(null),C=p.useRef(null),w=p.useRef(!1),M=p.useRef({element:null,role:null}),j=p.useRef(t),T=t.viewStore??null;T&&!T.handlers&&(T.handlers={current:t});const A=T?.handlers??j;A.current=t,p.useLayoutEffect(()=>{const k=v.current;if(!k)return;const E=T?.view;if(E){k.appendChild(E.dom),E.requestMeasure();const{anchor:L,head:D}=E.state.selection.main;return E.dispatch({selection:{anchor:L,head:D}}),C.current=E,()=>{E.dom.remove(),C.current=null}}const I=[{any:(L,D)=>(D.key==="Enter"&&Uy(D)&&w.current&&Object.defineProperty(D,"shiftKey",{value:!0}),A.current.onKeyDown?.(D)??!1)}],N=new bn({state:r8.create({doc:A.current.value,extensions:[s8(),o8(),tF,bn.lineWrapping,i8.highest(Og.of(I)),Og.of([...a8,...c8]),YH(A.current.languageContext),qy.of(bn.editable.of(A.current.editable??!0)),Wy.of(Hg(A.current.placeholder??"")),JH,bn.updateListener.of(L=>{const D=A.current,W=Gy(L.state);if(L.docChanged){const z=L.transactions.some(B=>B.isUserEvent("input.paste"));let J="";for(const B of L.transactions)J+=rF(B);D.onChange({value:L.state.doc.toString(),selection:W,fromPaste:z,insertedText:J})}else L.selectionSet&&D.onSelectionChange?.(W);(L.docChanged||L.heightChanged||L.geometryChanged)&&D.onVisualLineCount?.(Ky(L.view))}),bn.domEventHandlers({focus:()=>(A.current.onFocus?.(),!1),blur:()=>(A.current.onBlur?.(),!1),paste:L=>(A.current.onPaste?.(L),!1)}),bn.contentAttributes.of({spellcheck:String(A.current.spellCheck??!1),autocorrect:A.current.autoCorrect?"on":"off",autocapitalize:A.current.autoCapitalize??"none",...A.current["aria-label"]?{"aria-label":A.current["aria-label"]}:{}})]}),parent:k});C.current=N,T&&(T.view=N);const O=L=>{L.key!=="Enter"||Uy(L)||(w.current=L.shiftKey)};return N.contentDOM.addEventListener("keydown",O),()=>{if(C.current=null,T){N.dom.remove();return}N.destroy()}},[]),p.useEffect(()=>{const k=C.current;if(!k)return;const E=k.state.doc.toString();E!==r&&(k.dispatch({changes:{from:0,to:E.length,insert:r},selection:{anchor:r.length}}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{C.current===k&&(k.scrollDOM.scrollTop=k.scrollDOM.scrollHeight)})}))},[r]),p.useEffect(()=>{C.current?.dispatch({effects:S1.of(s)})},[s]),p.useEffect(()=>{C.current?.dispatch({effects:qy.reconfigure(bn.editable.of(i))})},[i]),p.useEffect(()=>{C.current?.dispatch({effects:Wy.reconfigure(Hg(o??""))})},[o]),p.useEffect(()=>{const k=C.current,E=v.current;if(!k||!E)return;if(f){k.scrollDOM.style.maxHeight="";return}const I=h?E.closest(h):null;let N=null;if(I)for(N=E;N.parentElement&&N.parentElement!==I;)N=N.parentElement;const O=()=>{const D=parseFloat(getComputedStyle(k.contentDOM).lineHeight||"");if(!Number.isFinite(D)||D<=0)return;let W=D*u;if(I&&N){const J=N.offsetHeight-k.scrollDOM.offsetHeight,B=I.clientHeight-J-m;B>0&&(W=Math.min(W,B))}const z=`${W}px`;k.scrollDOM.style.maxHeight!==z&&(k.scrollDOM.style.maxHeight=z)};if(O(),A.current.onVisualLineCount?.(Ky(k)),typeof ResizeObserver>"u")return;const L=new ResizeObserver(O);return L.observe(E),N&&L.observe(N),I&&L.observe(I),()=>L.disconnect()},[m,h,f,u]),p.useEffect(()=>{const k=C.current;if(!k)return;const E=k.contentDOM;E.setAttribute("spellcheck",String(a)),E.setAttribute("autocorrect",l?"on":"off"),E.setAttribute("autocapitalize",d)},[d,l,a]),p.useLayoutEffect(()=>{const k=C.current;if(!k)return;const E=k.contentDOM;if(M.current.element!==E){const D=M.current;D.element&&D.element!==E&&(D.role===null?D.element.getAttribute("role")==="combobox"&&D.element.removeAttribute("role"):D.element.setAttribute("role",D.role),D.element.removeAttribute("aria-expanded"),D.element.removeAttribute("aria-controls"),D.element.removeAttribute("aria-activedescendant")),M.current={element:E,role:E.getAttribute("role")}}const I=M.current.role,N=()=>{I===null?E.getAttribute("role")==="combobox"&&E.removeAttribute("role"):E.getAttribute("role")!==I&&E.setAttribute("role",I)},O=()=>{E.removeAttribute("aria-expanded"),E.removeAttribute("aria-controls"),E.removeAttribute("aria-activedescendant"),N()};return!!(b&&S)&&S?(E.setAttribute("role","combobox"),E.setAttribute("aria-expanded","true"),E.setAttribute("aria-controls",S),y?E.setAttribute("aria-activedescendant",y):E.removeAttribute("aria-activedescendant"),O):(O(),O)},[b,S,y]);const _=p.useCallback(k=>{nF(C.current,k)},[]);return p.useImperativeHandle(n,()=>({focus(k){const E=C.current;E&&E.contentDOM.focus({preventScroll:k?.preventScroll})},blur(){C.current?.contentDOM.blur()},isFocused(){return C.current?.hasFocus??!1},getValue(){return C.current?.state.doc.toString()??""},getSelection(){const k=C.current;return k?Gy(k.state):{start:0,end:0}},setSelection(k,E=k){const I=C.current;if(!I)return;const N=I.state.doc.length;I.dispatch({selection:{anchor:Math.min(Math.max(k,0),N),head:Math.min(Math.max(E,0),N)}})},selectAll(){const k=C.current;k&&k.dispatch({selection:{anchor:0,head:k.state.doc.length}})},insertText(k){const E=C.current;if(!E||!k)return;const{from:I,to:N}=E.state.selection.main;E.dispatch({changes:{from:I,to:N,insert:k},selection:{anchor:I+k.length},userEvent:"input.type"})},replaceRange(k,E,I,N){const O=C.current;O&&O.dispatch({changes:{from:k,to:E,insert:I},selection:{anchor:N??k+I.length},userEvent:"input.type"})},caretCoords(k){const E=C.current;if(!E)return null;const I=k??E.state.selection.main.head,N=E.coordsAtPos(I);return N?{top:N.top,bottom:N.bottom,left:N.left}:null},getScrollDOM(){return C.current?.scrollDOM??null}}),[]),c.jsx("div",{ref:v,"data-testid":t["data-testid"],"data-chat-input":"true",onMouseDown:_,className:R("composer-editor w-full","[&_.cm-editor]:h-full",f&&"flex min-h-0 flex-1 flex-col",g,x)})});function Ky(e){const t=e.defaultLineHeight;return!Number.isFinite(t)||t<=0?1:Math.max(1,Math.round(e.contentHeight/t))}function Gy(e){const t=e.selection.main;return{start:t.from,end:t.to}}function oF(){return{view:null,handlers:null}}function iF(e,t){const n=e?e.endsWith(`
86
+
87
+ `)?"":e.endsWith(`
88
+ `)?`
89
+ `:`
90
+
91
+ `:"",r=t.endsWith(`
92
+
93
+ `)?t:t.endsWith(`
94
+ `)?`${t}
95
+ `:`${t}
96
+
97
+ `;return`${e}${n}${r}`}function i4(e,t){const n=t.trim();if(!n)return e;if(!e)return`${n} `;const r=/[\s\n]$/.test(e)?"":" ";return`${e}${r}${n} `}function a4(e,t,n){if(!e)return e;const r=t.length>0&&!/\s$/.test(t)&&!/^\s/.test(e)&&!/[([{]$/.test(t),s=n.length>0&&!/\s$/.test(e)&&!/^\s/.test(n)&&!/^[\])}.,;:!?]/.test(n);return`${r?" ":""}${e}${s?" ":""}`}function aF(e,t){return e?`${e}${/\s$/.test(e)?"":" "}${t}`:t}const cF=/^(https?:\/\/|mailto:)\S+$/i;function lF(e,t){return cF.test(e)&&!/\s/.test(e)&&t.trim().length>0&&!t.includes("](")}const dF="application/x-pichamber-file-path",uF=["files","text/uri-list","codefiles",dF];function fF(e,t){try{return e.getData(t)}catch{return""}}function Xc(e){if(!e)return!1;if(e.files&&e.files.length>0)return!0;if(e.types){const t=Array.from(e.types).map(n=>n.toLowerCase());if(uF.some(n=>t.includes(n))||t.some(n=>n.includes("vnd.code.tree")))return!0}for(const t of ON){const n=fF(e,t);if(n&&PN(n).length>0)return!0}return!1}function hF(e){if(!e)return[];const t=Array.from(e.files||[]);return t.length>0?t:Array.from(e.items||[]).filter(n=>n.kind==="file").map(n=>n.getAsFile()).filter(n=>!!n)}function pF({enabled:e,composerRef:t,messageRef:n,cursorPosRef:r,confirmedMentionsRef:s,setMessage:o,addAttachedFile:i}){const[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=p.useRef(0),h=p.useCallback(y=>{if(!Xc(y.dataTransfer))return;y.preventDefault(),y.stopPropagation(),u.current++;const v=y.dataTransfer.types?.includes("application/x-pichamber-file-path")??!1;v!==d&&f(v),e&&!a&&l(!0)},[e,a,d]),m=p.useCallback(y=>{Xc(y.dataTransfer)&&(y.preventDefault(),y.stopPropagation(),y.dataTransfer.dropEffect="copy",e&&!a&&l(!0))},[e,a]),g=p.useCallback(y=>{y.preventDefault(),y.stopPropagation(),u.current--,u.current<=0&&(u.current=0,l(!1),f(!1))},[]),x=p.useCallback(()=>{u.current=0,l(!1),f(!1)},[]),b=p.useCallback(async y=>{if(u.current=0,!Xc(y.dataTransfer)||(y.preventDefault(),y.stopPropagation(),l(!1),!e))return;const C=y.dataTransfer.getData("application/x-pichamber-file-path");if(C&&C!=="."){s.current.add(C);const M=`@${C}`,j=t.current,T=n.current;if(j){const{start:A,end:_}=j.getSelection(),k=T.slice(0,A),E=T.slice(_),I=k.length>0&&!/\s$/.test(k),N=E.length>0&&!/^\s/.test(E),O=`${I?" ":""}${M}${N?" ":""}`;j.replaceRange(A,_,O),r.current=A+O.length,j.focus()}else o(A=>i4(A,M));return}const w=hF(y.dataTransfer);w.length>0&&((await Promise.all(w.map(async j=>{try{return await i(j)}catch(T){return console.error("File attach failed",T),!1}}))).some(Boolean)||Ce.error("Failed to attach file"))},[i,t,s,r,e,n,o]),S=p.useCallback(y=>{Xc(y.dataTransfer)&&y.preventDefault()},[]);return{isDragging:a,isInternalDrag:d,handleDragEnter:h,handleDragOver:m,handleDragLeave:g,handleDragEnd:x,handleDrop:b,handleDropCapture:S}}const mF=16e3,gF="pasted-text.txt";function yF(e){return e.length>mF}function Zy(e){return new File([e],gF,{type:"text/plain"})}function vF({inputMode:e,enabled:t,composerRef:n,message:r,setMessage:s,insertTextAtSelection:o,updateAutocompleteState:i,markFileMentionPasteSuppression:a,attachedFiles:l,addAttachedFile:d}){const f=p.useRef(new Set);return p.useCallback(async u=>{const h=u.clipboardData;if(!h)return;const m={...u,clipboardData:h,preventDefault:()=>u.preventDefault()},g=m.clipboardData.getData("text"),x=yF(g);if(e==="normal"&&t&&!x){const _=n.current,k=_?.getSelection().start??-1,E=_?.getSelection().end??-1;if(_&&E>k){const I=g.trim(),N=r.slice(k,E);if(lF(I,N)){m.preventDefault();const O=`${r.slice(0,k)}[${N}](${I})${r.slice(E)}`,L=k+1+N.length+2+I.length+1;s(O),n.current?.setSelection(L,L),i(O,L,Hy(I),I);return}}}const b=new Map;Array.from(m.clipboardData.files||[]).forEach(_=>{_.type.startsWith("image/")&&b.set(`${_.name}-${_.size}`,_)}),Array.from(m.clipboardData.items||[]).forEach(_=>{if(_.kind==="file"&&_.type.startsWith("image/")){const k=_.getAsFile();k&&b.set(`${k.name}-${k.size}`,k)}});const S=Array.from(b.values());if(x){if(!t){g.includes("@")&&a();return}if(m.preventDefault(),S.length===0){const _=Zy(g);try{await d(_)||Ce.error("Failed to attach pasted text as file")}catch{Ce.error("Failed to attach pasted text as file")}return}}else{if(S.length===0){g.includes("@")&&a();return}if(!t){g.includes("@")&&a();return}m.preventDefault()}const y=fH(S,[...l.map(_=>_.filename),...f.current]),v=hH(y),C=n.current,w=C?.getSelection().start??r.length,M=C?.getSelection().end??r.length,j=a4(aF(x?"":g,v),r.slice(0,w),r.slice(M));o(j,Hy(j));const T=x?(async()=>{try{await d(Zy(g))||Ce.error("Failed to attach pasted text as file")}catch{Ce.error("Failed to attach pasted text as file")}})():null,A=S.map(async(_,k)=>{const E=y[k],I=sH(_,E);f.current.add(E);try{await d(I)}catch(N){console.error("Clipboard image attach failed",N),Ce.error(N instanceof Error?N.message:"Failed to attach image from clipboard")}finally{f.current.delete(E)}});await Promise.all(T?[T,...A]:A)},[d,l,n,t,e,o,a,r,s,i])}const xF=(e,t)=>{if(t.size===0)return[];const n=new Map;for(const a of t){const l=a.toLowerCase();n.has(l)||n.set(l,a)}const r=new Set;for(const a of n.keys())r.add(`skill:${a}`);const s=qH(e,"/",r,"case-insensitive"),o=new Set,i=[];for(const a of s){const l=a.slice(6),d=n.get(l.toLowerCase())??l,f=d.toLowerCase();o.has(f)||(o.add(f),i.push(d))}return i},bF=e=>e.length===0?null:`The user explicitly mentioned these skills in their message: ${e.map(n=>`/skill:${n}`).join(", ")}. Use the corresponding skill tool when it is relevant to accomplishing the user's request.`;function wF(e,t){let n="",r=[],s;const o=[],i=[],a=u=>{for(const h of t.collectSkillNames(u))i.includes(h)||i.push(h)},l=u=>{!s&&u&&(s=u)},d=u=>{const h=t.parseAgentMention(u);l(h.agentName);const m=t.extractFileMentions(h.text);return a(m.text),m};if(e.queued.forEach((u,h)=>{const m=d(u.content),g=[...t.sanitizeAttachments(u.attachments),...m.attachments];if(h===0){n=m.text,r=g;return}o.push({text:m.text,attachments:g})}),e.composerText!==null){const u=d(e.composerText.replace(/^\n+|\n+$/g,"")),h=[...t.sanitizeAttachments(e.composerAttachments),...u.attachments];e.queued.length===0?(n=u.text,r=h):o.push({text:u.text,attachments:h})}for(const u of e.syntheticTexts)o.push({text:u,synthetic:!0});const f=t.buildSkillInstruction(i);return f&&o.push({text:f,synthetic:!0}),{primaryText:n,primaryAttachments:r,additionalParts:o,agentMentionName:s,isEmpty:!n&&r.length===0&&o.length===0}}function Yy(e){const t=e.trimStart();if(!t.startsWith("/"))return null;const n=t.slice(1),r=n.trim().split(/\s+/)[0]?.toLowerCase()??"";return r?{name:r,argument:n.slice(r.length).trim()}:null}const SF=["undo","redo","timeline","compact"];function c4(e){return SF.includes(e)}async function CF({command:e,currentSessionId:t,scrollToBottom:n,setTimelineDialogOpen:r,onCompactSession:s,onUndoSession:o,onRedoSession:i}){const{name:a,argument:l}=e;return c4(a)?a==="undo"&&t?(await o(t),n?.(),!0):a==="redo"&&t?(await i(t),n?.(),!0):a==="timeline"&&t?(r(!0),!0):a==="compact"?t?(await s(t,l.trim()||void 0),!0):(Ce.error("Open a session before compacting."),!0):!1:!1}function kF(e){const{enabled:t,openAutocomplete:n,message:r,editorRef:s,containerRef:o}=e,[i,a]=p.useState(null),l=p.useCallback(()=>{if(!t){a(null);return}if(n===null){a(null);return}const d=s.current,f=o.current;if(!d||!f)return;const u=d.caretCoords();if(!u)return;const h=f.getBoundingClientRect(),m=u.top-h.top,g=u.left-h.left,x=8,b=260,S=m-x,y=h.height-m-x,v=y>=b||y>=S?"below":"above",C=n==="mention"?520:450,w=Math.max(x,Math.min(g-24,h.width-C-x)),M=Math.max(120,Math.min(b,v==="below"?y:S));a({top:v==="below"?m+22:m-6,left:w,place:v,maxHeight:M})},[o,s,t,n]);return p.useLayoutEffect(()=>{l()},[l,r,n,t]),p.useEffect(()=>{if(!t)return;const d=()=>l();return window.addEventListener("resize",d),()=>{window.removeEventListener("resize",d)}},[t,l]),{position:i,update:l}}const vu=-1,Tp={index:vu,stashedDraft:""},Ap=e=>({state:e,text:null});function MF(e,t,n){if(t.length===0)return Ap(e);if(e.index===vu)return{state:{index:0,stashedDraft:n},text:t[0]};if(e.index>=t.length-1)return Ap(e);const r=e.index+1;return{state:{...e,index:r},text:t[r]}}function IF(e,t){if(e.index===vu)return Ap(e);if(e.index===0)return{state:Tp,text:e.stashedDraft};const n=e.index-1;return{state:{...e,index:n},text:t[n]}}function EF(e){const[t,n]=p.useState(Tp),r=p.useCallback(i=>{const a=MF(t,e,i);return a.text===null?null:(n(a.state),a.text)},[e,t]),s=p.useCallback(()=>{const i=IF(t,e);return i.text===null?null:(n(i.state),i.text)},[e,t]),o=p.useCallback(()=>n(Tp),[]);return{isBrowsing:t.index!==vu,older:r,newer:s,reset:o}}const jF=500;function Xy(e,t){return`${e}\0${[...t].sort().join("\0")}`}function _F(e){const{message:t,messageRef:n,setMessage:r,confirmedMentionsRef:s,identity:o,persistEnabled:i,initialDraft:a,onIdentityChange:l,onDraftRestored:d}=e,f=p.useRef(null),u=p.useRef(!1),h=p.useRef(new Map),m=p.useRef(a.identity),g=p.useRef({onIdentityChange:l,onDraftRestored:d});g.current={onIdentityChange:l,onDraftRestored:d},p.useEffect(()=>{m.current=o},[o]);const x=p.useCallback((v,C)=>{if(!v)return;const w=Jt(v),M=new Set;for(const T of s.current)C.includes(`@${T}`)&&M.add(T);s.current=M;const j=Xy(C,M);h.current.get(w)!==j&&(js(v,C,M),h.current.set(w,j))},[s]),b=p.useCallback(()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]),S=p.useRef(!1);p.useEffect(()=>{if(!S.current&&(S.current=!0,!!a.text)){if(!i){r(""),js(a.identity,"",[]);return}requestAnimationFrame(()=>g.current.onDraftRestored?.())}},[i]);const y=p.useRef(a.identity);return p.useEffect(()=>{const v=y.current,C=v?Jt(v):null,w=o?Jt(o):null;if(C===w)return;if(y.current=o,g.current.onIdentityChange?.(),b(),u.current=!0,!i){r(""),s.current=new Set;return}x(v,n.current);const M=Ud(o);r(M.text),s.current=M.confirmedMentions,M.text&&requestAnimationFrame(()=>g.current.onDraftRestored?.())},[b,s,o,n,i,x,r]),p.useEffect(()=>SM(v=>{const C=Jt(v);h.current.set(C,Xy("",[]));const w=m.current;!w||Jt(w)!==C||(b(),u.current=!0,n.current="",s.current=new Set,r(""))}),[b,s,n,r]),p.useEffect(()=>{if(!i){b(),x(o,"");return}if(u.current){u.current=!1;return}b();const v=t,C=o;return f.current=setTimeout(()=>{f.current=null,x(C,v)},jF),b},[b,o,t,i,x]),p.useEffect(()=>{const v=()=>{b(),i&&x(m.current,n.current)},C=()=>{document.visibilityState==="hidden"&&v()};return document.addEventListener("visibilitychange",C),document.addEventListener("freeze",v),window.addEventListener("pagehide",v),()=>{document.removeEventListener("visibilitychange",C),document.removeEventListener("freeze",v),window.removeEventListener("pagehide",v),v()}},[b,n,i,x]),{persistNow:x}}function TF(e,t,n){const s=e.substring(0,t).lastIndexOf("@");if(s!==-1){const a=e.substring(0,s)+`@${n} `+e.substring(t),l=s+n.length+2;return{newMessage:a,nextCursor:l}}const o=e.substring(0,t)+`@${n} `+e.substring(t),i=t+n.length+2;return{newMessage:o,nextCursor:i}}function Jy(e,t,n,r){const o=e.substring(0,t).lastIndexOf(n),i=o!==-1?o:t,a=`${e.substring(0,i)}${n}${r} ${e.substring(t)}`,l=i+r.length+2;return{newMessage:a,nextCursor:l}}function AF({composerRef:e,message:t,setMessage:n,updateAutocompleteState:r,closeAutocomplete:s,confirmedMentionsRef:o,toMentionPath:i}){const a=p.useCallback(u=>{const h=e.current?.getSelection().start||0,m=u.relativePath&&u.relativePath.trim().length>0?u.relativePath.trim():i(u.path)||u.name;o.current.add(m);const{newMessage:g,nextCursor:x}=TF(t,h,m);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(x),r(g,x)}),s(),e.current?.focus()},[s,e,o,t,n,i,r]),l=p.useCallback(u=>{const h=e.current?.getSelection().start??t.length,{newMessage:m,nextCursor:g}=Jy(t,h,"@",u);n(m),requestAnimationFrame(()=>{e.current&&e.current.setSelection(g),r(m,g)}),s(),e.current?.focus()},[s,e,t,n,r]),d=p.useCallback((u,h)=>{const m=e.current?.getSelection().start??t.length,{newMessage:g,nextCursor:x}=Jy(t,m,"#",h);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(x),r(g,x)}),s(),e.current?.focus()},[s,e,t,n,r]),f=p.useCallback(u=>{const h=u.invocationName??u.name;n(`/${h} `),s();const m=()=>{if(e.current){try{e.current.focus({preventScroll:!0})}catch{e.current.focus()}e.current.setSelection(e.current.getValue().length,e.current.getValue().length)}};requestAnimationFrame(()=>{m(),requestAnimationFrame(m)}),setTimeout(m,60)},[s,e,n]);return{handleFileSelect:a,handleAgentSelect:l,handleSnippetSelect:d,handleCommandSelect:f}}const NF=e=>{const t="nativeEvent"in e?e.nativeEvent:e;return t.isComposing||t.keyCode===229},LF={"`":["`","`"],"*":["*","*"],_:["_","_"],"~":["~","~"],"(":["(",")"],"[":["[","]"],"{":["{","}"],'"':['"','"'],"'":["'","'"]};function RF(e,t,n,r){if(n<=t)return null;const s=LF[r];if(!s)return null;const[o,i]=s,a=e.slice(t,n);return{next:`${e.slice(0,t)}${o}${a}${i}${e.slice(n)}`,caretStart:t+o.length,caretEnd:n+o.length}}function PF(e,t,n,r){if(r!=="`"||t!==n)return null;const s=e.slice(0,t);if(/(^|\n)``$/.test(s)){const o=e.slice(n),i=`${s}\`
98
+
99
+ \`\`\`${o}`,a=s.length+2;return{next:i,caret:a}}return null}function DF({inputMode:e,setInputMode:t,shellExcludeFromContext:n,setShellExcludeFromContext:r,message:s,setMessage:o,openAutocomplete:i,commandRef:a,snippetRef:l,mentionRef:d,composerRef:f,messageHistory:u,updateAutocompleteState:h,isMobile:m,hasContent:g,currentSessionId:x,sessionPhase:b,commandRunning:S=!1,followUpBehavior:y,handleSubmit:v,handleQueueMessage:C}){return p.useCallback(w=>{if(NF(w))return;if(e==="shell"&&w.key==="Escape"){w.preventDefault(),t("normal");return}if(e==="shell"&&w.key==="Backspace"&&s.length===0){w.preventDefault(),n&&r?r(!1):t("normal");return}if(i==="command"&&a.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),a.current.handleKeyDown(w.key);return}if(i==="snippet"&&l.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),l.current.handleKeyDown(w.key);return}if(i==="mention"&&d.current&&(w.key==="Enter"||w.key==="ArrowUp"||w.key==="ArrowDown"||w.key==="Escape"||w.key==="Tab")){w.preventDefault(),w.stopPropagation(),d.current.handleKeyDown(w.key);return}const M=i!==null,j=f.current?.getSelection().start===0&&f.current?.getSelection().end===0,T=f.current?.getSelection().start===s.length&&f.current?.getSelection().end===s.length,A=!M&&(s.length===0||j),_=!M&&(s.length===0||T);if(e==="normal"&&!M&&!w.metaKey&&!w.ctrlKey&&!w.altKey){const k=f.current,E=k?.getSelection().start??-1,I=k?.getSelection().end??-1;if(k&&E>=0){const N=(D,W,z)=>{w.preventDefault(),o(D),f.current?.setSelection(W,z),h(D,z)},O=RF(s,E,I,w.key);if(O){N(O.next,O.caretStart,O.caretEnd);return}const L=PF(s,E,I,w.key);if(L){N(L.next,L.caret,L.caret);return}}}if(w.key==="ArrowUp"&&A){w.preventDefault();const k=u.older(s);k!==null&&(o(k),requestAnimationFrame(()=>f.current?.setSelection(0,0)));return}if(w.key==="ArrowDown"&&_){w.preventDefault();const k=u.newer();k!==null&&o(k);return}if(w.key==="Enter"&&!w.shiftKey&&(!m||w.ctrlKey||w.metaKey)){w.preventDefault();const k=w.ctrlKey||w.metaKey,E=e==="normal"&&g&&x&&b!=="idle";S&&E?C():y==="queue"?k||!E?v():C():k||!E?v():v({delivery:"steer"})}},[a,S,f,x,y,C,v,g,e,m,d,s,u,i,b,t,o,r,n,l,h])}const OF=e=>e.enabled&&e.draftOpen&&!!e.directory&&e.gitAvailable&&e.isGitRepository,HF=(e,t)=>{const n=(e??[]).filter(r=>r.length>0&&!r.startsWith("remotes/")).sort((r,s)=>r.localeCompare(s)).map(r=>({value:r,label:r}));return t&&!n.some(r=>r.value===t)&&n.push({value:t,label:t}),n};function C1(e){return e.label?.trim()||u5(e.path)}function FF(e){const t=at(z=>z.projects),n=Qt(z=>z.projects),r=p.useMemo(()=>Ln(t,{projects:n}),[t,n]),s=nt(z=>z.homeDirectory),o=p.useMemo(()=>Zw(t,r),[r,t]),i=at(z=>z.activeProjectId),a=at(z=>z.setActiveProjectIdOnly),l=pe(z=>z.newSessionDraft),d=pe(z=>z.currentSessionId),f=pe(z=>z.currentSessionDirectory),u=pe(z=>z.setNewSessionDraftTarget),h=!!l?.open,m=bt(z=>z.fetchBranches),{git:g}=Da(),x=p.useMemo(()=>{if(h){const J=Yt(l?.directoryOverride??null),B=l?.selectedProjectId?o.find(U=>U.ownerProjectId===l.selectedProjectId&&(!J||Yt(U.path)===J))??o.find(U=>U.id===l.selectedProjectId)??null:null;if(B)return B;if(J){const U=o.find(P=>Yt(P.path)===J)??null;if(U)return U}}else if(d){const J=Yt(f??null);if(J&&CI(J,s)){const U=o.find(P=>P.ownerProjectId===ur)??null;if(U)return U}const B=Zn(t,r,f);if(B){const U=Yt(f??null);return o.find(P=>P.ownerProjectId===B.id&&Yt(P.path)===U)??o.find(P=>P.id===B.id)??null}}return(i?o.find(J=>J.id===i)??null:null)??o[0]??null},[i,r,f,d,s,h,l?.directoryOverride,l?.selectedProjectId,o,t]),b=p.useMemo(()=>Yt(x?.path??null),[x?.path]),S=p.useMemo(()=>h?Yt(l?.directoryOverride??null)??b:Yt(f??null)??b,[f,h,l?.directoryOverride,b]),y=x?t.find(z=>z.id===x.ownerProjectId)??null:null,v=Yt(y?.path??null),C=x?C1(x):null;p.useEffect(()=>{if(!BN({enabled:e,isDraftOpen:h,activeProjectId:i,selectedProjectId:l?.selectedProjectId}))return;const z=o.find(J=>J.id===i);z&&u({projectId:z.id,directoryOverride:z.path,branchIntent:null,worktreeIntent:null})},[i,e,h,l?.selectedProjectId,o,u]);const w=pu(S),M=bt(z=>S&&z.directories.get(S)?.status?.current?.trim()||null),j=j3(h?S:null),[T,A]=p.useState(!1);p.useEffect(()=>{const z=S?bt.getState().directories.get(S)?.branches??null:null;if(!OF({enabled:e,draftOpen:h,directory:S,gitAvailable:!!g,isGitRepository:w===!0})){A(!1);return}if(!S||!g)return;let J=!1;return A(z===null),m(S,g).finally(()=>{J||A(!1)}),()=>{J=!0}},[e,m,h,g,w,S]);const _=j?.current?.trim()||M,k=h&&(l?.worktreeIntent?.startRef?.trim()||l?.branchIntent?.branch?.trim())||null,E=k??_,I=p.useMemo(()=>h?HF(j?.all,k):[],[k,h,j?.all]),N=E??(w===!0?"Detached HEAD":null),O=w===!0&&!!(N||I.length>0||T),L=p.useCallback(z=>{if(!h)return;const J=o.find(U=>U.id===z),B=Yt(J?.path??null);if(!(!J||!B)){if(J.ownerProjectId===ur){u({projectId:ur,directoryOverride:B,branchIntent:null,worktreeIntent:null});return}i!==J.ownerProjectId&&a(J.ownerProjectId),u({projectId:J.ownerProjectId,directoryOverride:B,branchIntent:null,worktreeIntent:null})}},[i,h,o,a,u]),D=p.useCallback(z=>{if(!h||!S)return;const J=z.trim();if(!(!J||J.startsWith("remotes/"))){if(l?.worktreeIntent&&v){u({branchIntent:null,worktreeIntent:{runtimeKey:Y(),projectRoot:v,sourceDirectory:S,startRef:J}});return}u({worktreeIntent:null,branchIntent:{runtimeKey:Y(),directory:S,branch:J}})}},[h,l?.worktreeIntent,S,v,u]),W=p.useCallback(z=>{if(!(!h||!S||!v||!E)){if(z){u({branchIntent:null,worktreeIntent:{runtimeKey:Y(),projectRoot:v,sourceDirectory:S,startRef:E}});return}u({worktreeIntent:null,branchIntent:E===_?null:{runtimeKey:Y(),directory:S,branch:E}})}},[_,h,E,S,v,u]);return{projects:o,selectedDraftProject:x,selectedDraftProjectPath:b,selectedDraftProjectRoot:v,draftProjectLabel:C,selectedDraftDirectory:S,selectedDraftBranchLabel:N,selectedBranchName:E,currentBranch:_,draftBranchItems:I,isDiscoveringDraftBranches:T,shouldShowDraftBranchSelector:O,worktreeMode:!!(h&&l?.worktreeIntent),handleDraftProjectChange:L,handleDraftBranchChange:D,handleWorktreeModeChange:W}}const BF=e=>{const t=de(e.targetDirectory)??e.targetDirectory,r=(e.projectId?e.projects.find(i=>i.id===e.projectId)??null:null)??e.projects.reduce((i,a)=>{const l=de(a.path);if(!l||t!==l&&!t.startsWith(`${l}/`))return i;const d=de(i?.path??null);return!d||l.length>d.length?a:i},null),s=de(r?.path??null),o=new Set([t]);if(!s)return o;o.add(s);for(const[i,a]of e.availableWorktreesByProject)if(de(i)===s)for(const l of a??[]){const d=de(l?.path??null);d&&o.add(d)}return o},VF=(e,t)=>{const n=new Set(e.map(r=>r.id));return t.some(r=>!n.has(r.id))},Qy=(e,t)=>{const n=at.getState(),r=Ln(n.projects,Qt.getState()),s=BF({targetDirectory:e,projectId:t,projects:n.projects,availableWorktreesByProject:r});return ZI().filter(o=>s.has(o.directory)).sort((o,i)=>(o.title??"").localeCompare(i.title??"")||o.id.localeCompare(i.id))};function $F(e){const{activeRuntimeKey:t,intent:n,onReady:r}=e,{git:s}=Da(),o=bt(M=>M.fetchStatus),i=bt(M=>M.fetchBranches),a=bt(M=>M.clearDiffCache),[l,d]=p.useState(null),f=p.useRef(!1),u=p.useRef(0),h=p.useRef(null),m=p.useRef(r);m.current=r;const g=n?.runtimeKey??"",x=n?.directory??"",b=n?.branch??"";p.useEffect(()=>{u.current+=1,h.current=null,d(null)},[t,b,x,g]);const S=p.useCallback(M=>{s&&(a(M),hu.requestGitRefresh({directory:M}),Promise.all([o(M,s,{silent:!0}),i(M,s)]))},[a,i,o,s]),y=p.useCallback((M,j)=>{const T={runtimeKey:j.runtimeKey,directory:j.directory,branch:j.branch};h.current=T,m.current(M,T)},[]),v=p.useCallback(async M=>{const j=M.intent;if(!(f.current||l)){if(!s){Ce.error("Git is not available for the selected runtime.");return}if(j.runtimeKey!==Y()){Ce.error("The runtime changed. Select the branch again before sending.");return}f.current=!0;try{const[T,A]=await Promise.all([s.getGitBranches(j.directory),s.getGitStatus(j.directory,{mode:"light"})]),_=pe.getState().newSessionDraft.branchIntent;if(!sa(j,_))return;if(!T.all.includes(j.branch)||j.branch.startsWith("remotes/")){Ce.error(`Local branch ${j.branch} no longer exists.`),i(j.directory,s);return}if(A.mergeInProgress||A.rebaseInProgress||A.attentionReason){const N=A.attentionReason??(A.rebaseInProgress?"rebase":"merge");Ce.error(`Finish or abort the ${N} before switching branches.`);return}const k=A.current?.trim()||T.current?.trim()||null;if(k===j.branch){y(M.continuation,j);return}const E=M.projectId?at.getState().projects.find(N=>N.id===M.projectId)?.label?.trim():null,I=j.directory.split(/[\\/]/).filter(Boolean).pop()||j.directory;d({runtimeKey:j.runtimeKey,projectId:M.projectId??null,directory:j.directory,branch:j.branch,currentBranch:k,projectLabel:E||I,changedFileCount:A.files.length,activeSessions:Qy(j.directory,M.projectId),phase:"ready",continuation:M.continuation})}catch(T){Ce.error(T instanceof Error?T.message:"Failed to inspect the selected branch.")}finally{f.current=!1}}},[i,s,l,y]),C=p.useCallback(()=>{u.current+=1,h.current=null,d(null)},[]),w=p.useCallback(async()=>{const M=l;if(!M||M.phase==="checking"||M.phase==="terminal-error"||!s)return;const j=u.current+1;u.current=j,d({...M,phase:"checking",activeSessionsChanged:!1,error:void 0});try{const T=pe.getState().newSessionDraft;if(!T.open||!sa(T.branchIntent,M))throw Object.assign(new Error("The draft target changed. Press Send again to review the branch."),{terminal:!0});if(M.runtimeKey!==Y())throw Object.assign(new Error("The runtime changed. Select the branch again before sending."),{terminal:!0});const A=Qy(M.directory,M.projectId);if(VF(M.activeSessions,A)){d({...M,activeSessions:A,phase:"ready",activeSessionsChanged:!0,error:void 0});return}const _=await s.getGitBranches(M.directory);if(u.current!==j)return;const k=_.current?.trim()||null;if(k!==M.currentBranch&&k!==M.branch)throw Object.assign(new Error(`The current branch changed to ${k??"detached HEAD"}. Press Send again to review it.`),{terminal:!0});if(!_.all.includes(M.branch)||M.branch.startsWith("remotes/"))throw Object.assign(new Error(`Local branch ${M.branch} no longer exists.`),{terminal:!0});if(k!==M.branch&&(await s.checkoutBranch(M.directory,M.branch,{expectedCurrent:k,localOnly:!0})).currentBranch!==M.branch)throw Object.assign(new Error(`Git did not confirm checkout of ${M.branch}.`),{terminal:!0});if(u.current!==j)return;if(M.runtimeKey!==Y()){Ce.warning("The branch may have changed on the previous runtime. The message was not sent.");return}S(M.directory),d(null),y(M.continuation,M)}catch(T){if(u.current!==j)return;const A=T instanceof Error?T.message:"Failed to check out the selected branch.";let _;try{_=(await s.getGitBranches(M.directory)).current?.trim()||null}catch{_=void 0}if(u.current!==j)return;S(M.directory);const k=!!(T&&typeof T=="object"&&"terminal"in T)||T&&typeof T=="object"&&"code"in T&&T.code==="BRANCH_CHANGED"||_===M.branch||_===void 0,E=_===M.branch?`Git switched to ${M.branch}, but reported an error: ${A} Review the repository, then press Send again.`:A;d({...M,phase:k?"terminal-error":"retryable-error",error:E})}},[s,l,S,y]);return{dialogState:l,request:v,confirm:w,cancel:C,getReceipt:M=>sa(M,h.current)?h.current:null,clearReceipt:()=>{h.current=null}}}function zF(e){const{taskId:t,intent:n}=e,{git:r}=Da(),s=Qt(f=>f.refreshProject),o=t??Ow(n),a=ln(p.useCallback(f=>o?f.entries.get(o)??null:null,[o]))?.state??null,l=p.useCallback(async f=>{try{const u=await ln.getState().request({taskId:t??void 0,intent:f.intent,prompt:f.prompt,...f.failedSend?{failedSend:f.failedSend}:{},git:r??void 0,refreshProject:s});return f.intent.runtimeKey!==Y()?null:u}catch(u){return u instanceof Error&&u.message===Il,null}},[r,s,t]),d=p.useCallback(f=>{const u=o?ln.getState().getEntryByKey(o):ln.getState().getEntry(f);return!u?.receipt||!f?null:wA(f,u.receipt)?u.receipt:null},[o]);return{state:a,request:l,getReceipt:d}}function UF(e){const{isMobile:t,editorRef:n,formRef:r,controlsPanelOpen:s,attachMenuOpen:o}=e,[i,a]=p.useState(!1),[l,d]=p.useState(!1),f=p.useRef(0),u=p.useRef(!1),h=p.useRef(null);p.useEffect(()=>()=>{h.current!==null&&window.clearTimeout(h.current)},[]),p.useEffect(()=>{if(!t||typeof document>"u")return;let v=document.getElementById("mobile-overlay-root");v||(v=document.createElement("div"),v.id="mobile-overlay-root",document.body.appendChild(v));const C=v,w=()=>d(C.childElementCount>0);w();const M=new MutationObserver(w);return M.observe(C,{childList:!0}),()=>M.disconnect()},[t]);const m=l||s||o,g=p.useRef(0),x=p.useRef(0);p.useEffect(()=>{if(!t||lr()||typeof window>"u"||!window.matchMedia?.("(display-mode: standalone)")?.matches)return;const v=()=>{g.current+=1},C=()=>{if(g.current=Math.max(0,g.current-1),!u.current||g.current>0)return;u.current=!1,x.current=Date.now()+600,n.current?.focus(),n.current?.isFocused()&&a(!0);const w=()=>{const M=n.current;M?.isFocused()&&(r.current??M.getScrollDOM())?.scrollIntoView({block:"end"})};window.setTimeout(w,300),window.setTimeout(w,650)};return window.addEventListener("oc:mobile-overlay-opened",v),window.addEventListener("oc:mobile-overlay-closed",C),()=>{window.removeEventListener("oc:mobile-overlay-opened",v),window.removeEventListener("oc:mobile-overlay-closed",C)}},[n,r,t]),p.useEffect(()=>{if(!t)return;if(m){(i||Date.now()-f.current<800)&&(u.current=!0);return}if(!u.current)return;const v=window.setTimeout(()=>{u.current=!1,n.current?.focus({preventScroll:lr()})},180);return()=>window.clearTimeout(v)},[n,i,t,m]),p.useEffect(()=>{if(!t||lr()||typeof document>"u")return;const v=document.documentElement;return i?v.classList.add("oc-browser-keyboard-open"):(v.classList.remove("oc-browser-keyboard-open"),window.matchMedia?.("(display-mode: standalone)")?.matches&&window.setTimeout(()=>{v.classList.contains("oc-browser-keyboard-open")||(window.scrollTo(0,0),document.body.scrollTop=0,v.scrollTop=0)},350)),()=>v.classList.remove("oc-browser-keyboard-open")},[i,t]);const b=p.useCallback(()=>{t&&(lr()&&mE(),h.current!==null&&(window.clearTimeout(h.current),h.current=null),a(!0))},[t]),S=p.useCallback(()=>{if(t){if(Date.now()<x.current){const v=n.current;if(v){v.focus(),window.setTimeout(()=>{Date.now()<x.current&&!v.isFocused()&&v.focus()},50);return}}if(f.current=Date.now(),lr()){pa.flushSync(()=>a(!1));return}h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,a(!1)},120)}},[n,t]),y=p.useCallback(()=>{u.current=!1},[]);return{focused:i,onEditorFocus:b,onEditorBlur:S,cancelOverlayCloseRestore:y}}function ev(e){e.style.position="",e.style.left="",e.style.right="",e.style.width="",e.style.top="",e.style.height="",e.style.zIndex="",e.style.background=""}function qF(e){const{isMobile:t,isFullscreen:n,isDraftScreen:r,isFocused:s,formRef:o,editorRef:i}=e;p.useLayoutEffect(()=>{if(!t||!n||lr())return;const a=window.visualViewport,l=o.current,d=i.current;if(!a||!l)return;document.documentElement.classList.add("oc-browser-kb-fullscreen");const f=()=>{const u=Math.max(0,Math.floor(a.offsetTop)),h=document.documentElement.clientHeight;l.style.position="fixed",l.style.left="0",l.style.right="0",l.style.top=`${u}px`,l.style.height=`${Math.floor(Math.min(a.height,h-u))}px`,l.style.zIndex="40",l.style.background="var(--background)"};return f(),a.addEventListener("resize",f),a.addEventListener("scroll",f),window.addEventListener("resize",f),window.addEventListener("scroll",f,!0),()=>{a.removeEventListener("resize",f),a.removeEventListener("scroll",f),window.removeEventListener("resize",f),window.removeEventListener("scroll",f,!0),document.documentElement.classList.remove("oc-browser-kb-fullscreen"),ev(l),requestAnimationFrame(()=>{d?.isFocused()&&d.getScrollDOM()?.scrollIntoView({block:"nearest"})})}},[i,o,n,t]),p.useLayoutEffect(()=>{if(!t||lr()||!r||n||!s)return;const a=window.visualViewport,l=o.current;if(!a||!l)return;const d=l.getBoundingClientRect();l.style.position="fixed",l.style.left=`${Math.floor(d.left)}px`,l.style.width=`${Math.floor(d.width)}px`,l.style.zIndex="40",l.style.background="var(--background)";let f=Number.NaN,u=0;const h=()=>{const m=document.documentElement.clientHeight,g=a.offsetTop+a.height,x=Math.max(0,Math.floor(Math.min(g,m)-l.offsetHeight));x!==f&&(f=x,l.style.top=`${x}px`),u=requestAnimationFrame(h)};return h(),()=>{cancelAnimationFrame(u),ev(l)}},[o,r,s,n,t])}const WF=10,tv=16,nv=4,KF=/[-_./]/;function GF(e){const t=Array.from(e);let n=WF;const r=t.lastIndexOf("/");if(r>0&&r<t.length-1){const i=t.length-r-1;i>=nv&&i<=tv&&(n=i)}if(t.length<=n+4)return null;let s=t.length-n;const o=i=>KF.test(t[i-1]??"");if(!o(s)){let i=-1;for(let a=s+1;a<=t.length-nv;a+=1)if(o(a)){i=a;break}for(let a=s-1;i<0&&a>=t.length-tv&&a>4;a-=1)o(a)&&(i=a);i>0&&(s=i)}return{head:t.slice(0,s).join(""),tail:t.slice(s).join("")}}function ZF(e,t,n){t.style.clipPath="",n.style.translate="",e.removeAttribute("data-overflow");const r=t.firstChild;if(!(r instanceof Text)||t.scrollWidth<=t.clientWidth)return;e.setAttribute("data-overflow","");const s=t.clientWidth,o=t.getBoundingClientRect().left,i=document.createRange(),a=u=>(i.setStart(r,0),i.setEnd(r,u),i.getBoundingClientRect().right-o);let l=0,d=r.length;for(;d-l>1;){const u=l+d>>1;a(u)<=s?l=u:d=u}/[\uD800-\uDBFF]/.test(r.data[l-1]??"")&&(l-=1);const f=Math.max(0,s-a(l));f>0&&(t.style.clipPath=`inset(-0.25em ${f}px -0.25em 0)`,n.style.translate=`-${f}px 0`)}function k1({value:e,showTitle:t=!0,className:n,...r}){const s=GF(e),o=p.useRef(null),i=p.useRef(null),a=p.useRef(null),l=s?.head;return p.useLayoutEffect(()=>{const d=o.current,f=i.current,u=a.current;if(!d||!f||!u||l===void 0)return;const h=()=>ZF(d,f,u);if(h(),typeof ResizeObserver>"u")return;const m=new ResizeObserver(h);return m.observe(d),()=>m.disconnect()},[l]),c.jsx("span",{...r,ref:o,title:t?e:void 0,className:R("group/middle-truncate inline-flex min-w-0 max-w-full overflow-hidden whitespace-nowrap",n),children:s?c.jsxs(c.Fragment,{children:[c.jsx("span",{ref:i,className:"min-w-0 overflow-hidden",children:s.head}),c.jsxs("span",{ref:a,className:"shrink-0",children:[c.jsx("span",{"aria-hidden":"true",className:"hidden group-data-[overflow]/middle-truncate:inline",children:"…"}),s.tail]})]}):c.jsx("span",{className:"min-w-0 truncate",children:e},"whole")})}const YF=600*1e3,rv=60*1e3,XF=[2e3,5e3,15e3],JF=200,qn=new Map,vd=new Set,l4=()=>{for(const e of vd)e()},QF=e=>(vd.add(e),()=>{vd.delete(e)});en(l4);const M1=e=>{const t=e?.trim();return t?t.length>1?t.replace(/[\\/]+$/,""):t:null},I1=e=>`${Y()}\0${e}`,rh=(e,t)=>{const n=qn.get(e);for(n?.url&&n.url!==t.url&&URL.revokeObjectURL(n.url),qn.delete(e),qn.set(e,t);qn.size>JF;){const[r,s]=qn.entries().next().value;s.url&&URL.revokeObjectURL(s.url),qn.delete(r)}l4()},eB=async e=>{const t=await Nt("/api/fs/project-icon",{query:{directory:e}});if(t.status===204)return null;if(!t.ok)throw new Error(`Project icon request failed (${t.status})`);const n=await t.blob();return n.size===0||!n.type.startsWith("image/")?null:URL.createObjectURL(n)},d4=(e,t,n=!1)=>{const r=qn.get(e);if(r&&(r.loading||!n&&r.expiresAt>Date.now()))return;const s=r?.failures??0;rh(e,{url:r?.url??null,expiresAt:0,loading:!0,failures:s}),eB(t).then(o=>{if(qn.get(e)?.loading!==!0){o&&URL.revokeObjectURL(o);return}rh(e,{url:o,expiresAt:Date.now()+(o?YF:rv),loading:!1,failures:0})},()=>{const o=qn.get(e);if(o?.loading!==!0)return;const i=XF[s];rh(e,{url:o.url,expiresAt:Date.now()+(i??rv),loading:!1,failures:s+1}),i!==void 0&&setTimeout(()=>{vd.size>0&&d4(e,t,!0)},i)})},tB=e=>{const t=M1(e);return t?qn.get(I1(t))?.url??null:null},nB=e=>{const t=M1(e);t&&d4(I1(t),t)},rB=e=>{const t=p.useSyncExternalStore(QF,()=>tB(e),()=>null),n=M1(e),r=n?I1(n):null;return p.useEffect(()=>{r&&nB(e)},[r,e]),t},sh=["var(--syntax-keyword)","var(--syntax-string)","var(--syntax-number)","var(--syntax-function)","var(--syntax-type)","var(--syntax-variable)","var(--primary)"],sB=e=>{const t=e.normalize("NFKC").match(/[\p{L}\p{N}]/u)?.[0];return t?t.toLocaleUpperCase():"?"},oB=e=>{let t=0;for(const n of e.normalize("NFKC").trim().toLowerCase())t=t*31+(n.codePointAt(0)??0)>>>0;return sh[t%sh.length]??sh[0]},iB=e=>({text:sB(e),color:oB(e)}),sv=new Set,ov=new WeakMap,aB=e=>{const t=ov.get(e);if(t!==void 0)return t;const n=new Set;for(const s of e.byId.values()){if(s.archived||s.lifecycle!=="busy"&&s.lifecycle!=="retry")continue;const o=de(s.directory);o&&n.add(o)}const r=[...n].sort().join(`
100
+ `);return ov.set(e,r),r},cB=(e,t,n)=>{if(!e)return sv;const r=Ln(t,{projects:n}),s=new Set;for(const o of e.split(`
101
+ `)){const i=Zn(t,r,o),a=de(i?.path??null);a&&s.add(a)}return s.size>0?s:sv};let Xs=null;const lB=(e,t,n)=>{if(Xs&&Xs.liveDirectoriesKey===e&&Xs.projects===t&&Xs.worktreeProjects===n)return Xs.paths;const r=cB(e,t,n);return Xs={liveDirectoriesKey:e,projects:t,worktreeProjects:n,paths:r},r},dB=e=>aB(e.catalog),uB=e=>{const t=ze(dB,void 0,"catalog"),n=at(o=>o.projects),r=Qt(o=>o.projects),s=de(e??null);return!s||!t?!1:lB(t,n,r).has(s)};function fB({directory:e,label:t,className:n}){const r=rB(e),s=uB(e),[o,i]=p.useState(null),a=s?void 0:"grayscale";return r&&r!==o?c.jsx("img",{src:r,alt:"","aria-hidden":"true",draggable:!1,onError:()=>i(r),"data-project-icon":"image","data-agent-active":s?"":void 0,className:R("size-4 shrink-0 rounded-[25%] object-contain",a,n)}):c.jsx(hB,{label:t,active:s,className:R(a,n)})}function hB({label:e,active:t,className:n}){const r=p.useMemo(()=>iB(e),[e]);return c.jsx("span",{"aria-hidden":"true","data-project-icon":"mark","data-agent-active":t?"":void 0,className:R("inline-flex size-4 shrink-0 items-center justify-center overflow-hidden rounded-[25%]",n),style:{color:r.color,backgroundColor:`color-mix(in srgb, ${r.color} 20%, transparent)`},children:c.jsx("svg",{viewBox:"0 0 16 16",className:"size-full select-none",children:c.jsx("text",{x:"8",y:"11.7",textAnchor:"middle",fill:"currentColor",fontSize:"10.5",fontWeight:700,children:r.text})})})}const E1=(e,t)=>{const[n,r]=p.useState(e),s=p.useRef(null),o=p.useCallback(()=>{s.current!==null&&typeof window<"u"&&(window.clearTimeout(s.current),s.current=null)},[]);p.useEffect(()=>o,[o]);const i=p.useCallback(()=>{o(),r(e)},[o,e]),a=p.useCallback(l=>{o(),r(l),!(typeof window>"u")&&(s.current=window.setTimeout(()=>{r(e),s.current=null},t))},[o,t,e]);return{value:n,show:a,clear:i}},u4=20,pB=24,mB=(e,t)=>e.length<=t?e:`${e.slice(0,t-1)}…`;function xd({project:e,maxCharacters:t}){const n=C1(e),r=e.id==="__home__"||e.ownerProjectId==="__home__",s=e.kind==="worktree";return c.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:n,children:[s||r?c.jsx($,{name:s?"git-branch":"home",className:"size-3.5 shrink-0 text-muted-foreground"}):c.jsx(fB,{directory:e.path,label:n,className:"size-3.5"}),s?c.jsx(k1,{value:n,showTitle:!1,className:"text-muted-foreground",style:t?{maxWidth:`${t}ch`}:void 0}):c.jsx("span",{className:"truncate text-muted-foreground",children:t?mB(n,t):n})]})}const iv="h-7 min-w-0 w-fit max-w-[48vw] gap-1 border-transparent bg-transparent px-1.5 text-muted-foreground typography-micro font-normal hover:bg-transparent hover:text-foreground data-[popup-open]:bg-transparent [&_svg]:size-3.5 [&_svg]:opacity-70 sm:max-w-none",f4=({checked:e,onChange:t,showCheck:n=!0,chromeLess:r=!1})=>c.jsxs(yt,{delayDuration:300,children:[c.jsx(vt,{asChild:!0,children:c.jsxs(Se,{variant:r?"ghost":"chip",size:"xs",className:r?"min-w-0 max-w-[48vw] shrink aria-pressed:bg-interactive-hover aria-pressed:text-foreground sm:max-w-none":"min-w-0 max-w-[48vw] shrink sm:max-w-none","aria-pressed":e,onClick:()=>t?.(!e),children:[c.jsx($,{name:"git-branch",className:"size-3.5"}),c.jsx("span",{className:"truncate",children:"New worktree"}),e&&n?c.jsx($,{name:"check",className:"size-3.5"}):null]})}),c.jsx(xt,{side:"top",sideOffset:6,className:"max-w-72",children:"Starts from the selected branch's latest commit. Uncommitted changes are not copied."})]}),av=({label:e,startFrom:t=!1})=>{const n=e??"Branch";return c.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:e??void 0,children:[c.jsx($,{name:"git-branch",className:"size-3.5 shrink-0 text-muted-foreground"}),t&&e?c.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:"from"}):null,e?c.jsx(k1,{value:e,showTitle:!1}):c.jsx("span",{className:"truncate",children:n})]})};function h4({branchName:e}){const{value:t,show:n}=E1(!1,2e3),r=p.useCallback(async s=>{if(s.stopPropagation(),s.preventDefault(),!e)return;(await gr(e)).ok?n(!0):Ce.error("Failed to copy")},[e,n]);return e?c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Copy branch name",onClick:s=>{r(s)},children:t?c.jsx($,{name:"check",className:"size-3.5 text-[color:var(--status-success)]"}):c.jsx($,{name:"file-copy",className:"size-3.5"})})}),c.jsx(xt,{sideOffset:6,children:t?"Copied":"Copy branch name"})]}):null}function gB(e){const{projects:t,selectedProject:n,selectedBranchName:r,selectedBranchLabel:s,branchOptions:o,branchInteractive:i,branchLoading:a,showBranchSelector:l,showProjectSelector:d=!0,showWorktreeSelector:f=!1,worktreeMode:u=!1,endAccessory:h,onProjectChange:m,onBranchChange:g,onWorktreeModeChange:x,theme:b}=e;return c.jsxs("div",{className:"mb-3 flex min-w-0 w-full items-center justify-between gap-2 pl-2 pr-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[d?c.jsxs(G2,{value:n.id,onValueChange:m,children:[c.jsx(Y2,{size:"sm",className:iv,children:c.jsx(Z2,{children:c.jsx(xd,{project:n,theme:b,maxCharacters:u4})})}),c.jsx(X2,{className:"w-max min-w-48",children:t.map(S=>c.jsx(J2,{value:S.id,className:S.kind==="worktree"?"max-w-[24rem] truncate pl-7":"max-w-[24rem] truncate",children:c.jsx(xd,{project:S,theme:b})},S.id))})]}):null,l&&i?c.jsxs(G2,{value:r??void 0,onValueChange:g,disabled:!!(a&&o.length===0),children:[c.jsx(Y2,{size:"sm",className:iv,children:c.jsx(Z2,{children:c.jsx(av,{label:s,startFrom:u})})}),c.jsx(X2,{className:"w-max min-w-56",children:c.jsxs(XL,{children:[c.jsx(JL,{children:a?"Loading branches...":"Local branches"}),o.map(S=>c.jsx(J2,{value:S.value,className:"max-w-[28rem] truncate",children:S.label},S.value))]})})]}):l?c.jsxs("div",{className:"inline-flex h-7 min-w-0 items-center gap-0.5 px-1.5 typography-micro text-muted-foreground",children:[c.jsx(av,{label:s,startFrom:u}),c.jsx(h4,{branchName:r})]}):null,f?c.jsx(f4,{checked:u,onChange:x}):null]}),h?c.jsx("div",{className:"min-w-0 shrink-0",children:h}):null]})}function yB(e){const{selectedProject:t,selectedBranchName:n,selectedBranchLabel:r,branchInteractive:s,showBranchSelector:o,showProjectSelector:i=!0,showWorktreeSelector:a=!1,worktreeMode:l=!1,onWorktreeModeChange:d,endAccessory:f,theme:u,onOpenPicker:h}=e,m=r?c.jsx(k1,{value:r,showTitle:!1,style:{maxWidth:`${pB}ch`}}):c.jsx("span",{className:"truncate",children:"Branch"});return c.jsxs("div",{className:"mb-1.5 flex min-w-0 w-full flex-col gap-0.5 pl-2 pr-1",children:[a?c.jsx("div",{className:"flex w-full justify-end",children:c.jsx(f4,{checked:l,onChange:d,showCheck:!1,chromeLess:!0})}):null,c.jsxs("div",{className:"flex min-w-0 w-full items-center gap-x-1",children:[i?c.jsxs("button",{type:"button",className:"inline-flex h-7 min-w-0 max-w-[44%] shrink cursor-pointer items-center gap-1 rounded-lg px-1.5 typography-micro font-medium text-foreground/80 hover:bg-[var(--interactive-hover)]",onClick:()=>h("project"),children:[c.jsx(xd,{project:t,theme:u,maxCharacters:u4}),c.jsx($,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):null,o&&s?c.jsxs("button",{type:"button",className:`inline-flex h-7 min-w-0 cursor-pointer items-center gap-1 rounded-lg px-1.5 typography-micro font-medium text-foreground/80 hover:bg-[var(--interactive-hover)] ${i?"ml-auto max-w-[54%] shrink":"flex-1"}`,onClick:()=>h("branch"),title:r??void 0,children:[c.jsx($,{name:"git-branch",className:"h-3 w-3 shrink-0 text-muted-foreground"}),l&&r?c.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:"from"}):null,m,c.jsx($,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):o?c.jsxs("div",{className:`inline-flex h-7 min-w-0 items-center gap-1 px-1.5 typography-micro text-muted-foreground ${i?"ml-auto max-w-[54%] shrink":"min-w-0 flex-1"}`,title:r??void 0,children:[c.jsx($,{name:"git-branch",className:"h-3 w-3 shrink-0"}),l&&r?c.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:"from"}):null,m,c.jsx(h4,{branchName:n})]}):null,!i&&f?c.jsx("div",{className:`min-w-0 shrink-0 ${o?"":"ml-auto"}`,children:f}):null]})]})}function vB(e){const{projects:t,selectedProject:n,selectedBranchName:r,branchOptions:s,branchInteractive:o,onProjectChange:i,onBranchChange:a,theme:l,openPicker:d,onOpenPickerChange:f,showProjectSelector:u=!0,showBranchSelector:h,query:m="",onQueryChange:g}=e,[x,b]=p.useState("");p.useEffect(()=>{d!=="project"&&b(""),d!=="branch"&&g?.("")},[g,d]);const S=p.useMemo(()=>{const v=x.trim().toLowerCase();return v?t.filter(C=>C1(C).toLowerCase().includes(v)||C.path.toLowerCase().includes(v)):t},[x,t]),y=p.useMemo(()=>{const v=m.trim().toLowerCase();return v?s.filter(C=>C.label.toLowerCase().includes(v)):s},[s,m]);return c.jsxs(c.Fragment,{children:[c.jsx(Ma,{open:u&&d==="project",onClose:()=>f(null),title:"Project",children:c.jsxs("div",{className:"flex flex-col py-1",children:[t.length>5?c.jsx("div",{className:"px-3 pb-2 pt-1",children:c.jsx(Fo,{value:x,onChange:v=>b(v.target.value),placeholder:"Search projects...",className:"h-8 typography-meta",autoFocus:!0})}):null,c.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:S.map(v=>{const C=v.id===n.id;return c.jsxs("button",{type:"button",onClick:()=>{i(v.id),f(null)},className:`flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-2 text-left typography-ui-label transition-colors hover:bg-[var(--interactive-hover)] ${v.kind==="worktree"?"pl-7 ":""}${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[c.jsx(xd,{project:v,theme:l}),C?c.jsx($,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},v.id)})})]})}),c.jsx(Ma,{open:o&&h&&d==="branch",onClose:()=>f(null),title:"Branch",children:c.jsxs("div",{className:"flex flex-col py-1",children:[s.length>5?c.jsx("div",{className:"px-3 pb-2 pt-1",children:c.jsx(Fo,{value:m,onChange:v=>g?.(v.target.value),placeholder:"Search branches...",className:"h-8 typography-meta",autoFocus:!0})}):null,c.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:y.map(v=>{const C=v.value===r;return c.jsxs("button",{type:"button",onClick:()=>{a(v.value),f(null)},className:`flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-2 text-left typography-ui-label transition-colors hover:bg-[var(--interactive-hover)] ${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[c.jsx("span",{className:"truncate",children:v.label}),C?c.jsx($,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},v.value)})})]})})]})}function xB(e){const{state:t,onCancel:n,onConfirm:r}=e,s=t?.phase==="checking",o=t?.phase==="terminal-error";return c.jsx(ru,{open:t!==null,onOpenChange:i=>{!i&&!s&&n()},children:c.jsxs(su,{showCloseButton:!1,className:"max-w-md gap-5",children:[c.jsxs(ou,{children:[c.jsx(iu,{children:o?"Branch checkout needs attention":"Check out branch?"}),c.jsx(Vm,{children:t?`PiChamber will check out "${t.branch}" in "${t.projectLabel}" before creating the session. This changes the files used by every session and terminal in this folder.`:""})]}),t?.activeSessions.length?c.jsxs("section",{"aria-live":"polite",className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[c.jsx("h3",{className:"typography-ui-label font-medium text-foreground",children:t.activeSessions.length===1?"Another session is active in this project":`${t.activeSessions.length} other sessions are active in this project`}),c.jsx("p",{className:"mt-1 typography-meta text-muted-foreground",children:"Switching branches may interrupt sessions using this folder or conflict with work in a related worktree."}),c.jsx("ul",{className:"mt-2 max-h-32 list-disc space-y-1 overflow-y-auto pl-5 typography-meta text-foreground",children:t.activeSessions.map(i=>c.jsx("li",{children:i.title??"Untitled session"},i.id))}),t.activeSessionsChanged?c.jsx("p",{className:"mt-2 typography-meta font-medium text-status-warning",children:"The active session list changed. Review it before continuing."}):null]}):null,t?.changedFileCount?c.jsx("p",{className:"typography-ui-label text-muted-foreground",children:t.changedFileCount===1?"This folder has 1 uncommitted file. Git may block the checkout if it conflicts.":`This folder has ${t.changedFileCount} uncommitted files. Git may block the checkout if they conflict.`}):null,t?.error?c.jsx("p",{role:"alert",className:"typography-ui-label text-status-error",children:t.error}):null,c.jsxs(Gj,{children:[c.jsx(Se,{variant:"outline",onClick:n,disabled:s,children:o?"Close":"Cancel"}),o?null:c.jsx(Se,{onClick:r,disabled:s,children:s?"Checking out...":t?.phase==="retryable-error"?"Try Again":"Check Out and Send"})]})]})})}const j1=(e,t)=>{const[n,r]=p.useState(void 0);return p.useLayoutEffect(()=>{if(!t)return;const s=()=>{const o=e.current;if(!o)return;const i=o.closest("main");if(!i)return;const a=window.visualViewport?.offsetTop??0,l=Math.max(i.getBoundingClientRect().top,a),d=o.getBoundingClientRect().bottom-l-8,f=Math.max(120,Math.floor(d));r(u=>u===f?u:f)};return s(),window.addEventListener("resize",s),window.addEventListener("oc:keyboard-settled",s),window.visualViewport?.addEventListener("resize",s),window.visualViewport?.addEventListener("scroll",s),()=>{window.removeEventListener("resize",s),window.removeEventListener("oc:keyboard-settled",s),window.visualViewport?.removeEventListener("resize",s),window.visualViewport?.removeEventListener("scroll",s)}}),t?n:void 0},Wr=e=>e.invocationName??e.name;function cv(e,t){const n=Wr(e),r=Wr(t),s=e.searchAliases??[],o=[...s,...n===r&&e.name===t.name?[]:[t.name],...t.invocationName&&t.invocationName!==t.name&&t.invocationName!==n?[t.invocationName]:[],...t.description?[t.description]:[],...t.searchAliases??[]].filter((a,l,d)=>a!==e.description&&d.indexOf(a)===l);return o.length===s.length&&o.every((a,l)=>a===s[l])?e:{...e,searchAliases:o}}function bB(e,t,n,r=[]){const s=[],o=new Map,i=(a,l)=>{for(const d of a){const f=l(d),u=Wr(d),h=o.get(u);if(!h){o.set(u,{index:s.length,item:d,precedence:f}),s.push(d);continue}const m=f>h.precedence?cv(d,h.item):cv(h.item,d);s[h.index]=m,o.set(u,{index:h.index,item:m,precedence:Math.max(h.precedence,f)})}};return i(e,()=>4),i(t,a=>a.isBuiltIn?4:a.source==="extension"?3:a.isSkill?1:0),i(n,()=>2),i(r,()=>1),s}function lv(e,t){switch(t){case"all":return!0;case"system":return!!e.isBuiltIn||e.source==="pichamber"||e.source==="system";case"skills":return!!e.isSkill||e.source==="skill";case"extensions":return e.source==="extension";case"prompts":return e.source==="prompt"}}function wB(e,t){return fo(e.name,t)||fo(Wr(e),t)||!!(e.description&&fo(e.description,t))||!!e.searchAliases?.some(n=>fo(n,t))}function SB(e,t,n){const r=t.trim(),s=r.toLowerCase(),i=[...r?e.filter(a=>lv(a,n)&&wB(a,r)):e.filter(a=>lv(a,n))];return i.sort((a,l)=>{const d=Wr(a).toLowerCase(),f=Wr(l).toLowerCase(),u=s.length>0&&d.startsWith(s),h=s.length>0&&f.startsWith(s);return u&&!h?-1:!u&&h?1:d.localeCompare(f)}),i}function CB(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function kB(e){return`command-listbox-${e.length>0?e:"commands"}`}function Np(e,t){return`${e}-option-${t}`}function MB(e){if(!e.loading&&e.hasSelectedCommand)return Np(e.listboxId,e.selectedIndex)}const dv=e=>{if(e.source==="skill"||e.isSkill)return"Skill";if(e.source==="extension")return"Extension";if(e.source==="prompt")return"Prompt";if(e.source==="system"||e.source==="pichamber"||e.isBuiltIn)return"System";const t=[e.scope,e.agent].filter(n=>!!n);return t.length>0?t.join(" · "):null},IB=[{value:"all",label:"All"},{value:"system",label:"System"},{value:"prompts",label:"Prompts"},{value:"skills",label:"Skills"},{value:"extensions",label:"Extensions"}],p4=p.forwardRef(({searchQuery:e,onCommandSelect:t,onClose:n,style:r,onComboboxStateChange:s},o)=>{const i=pe(L=>L.currentSessionId),l=Pm(i??"").length>0,d=!!i,f=te(L=>L.isMobile),[u,h]=p.useState("all"),m=Qn(),{commands:g,isLoading:x}=Y3(m),[b,S]=p.useState([]),[y,v]=p.useState(!1),[C,w]=p.useState(0),M=p.useRef(0),j=p.useRef(!1),T=p.useRef([]),A=p.useRef(null),_=j1(A,f),k=p.useRef(!1),E=p.useRef(null),I=p.useRef(!1),N=p.useId(),O=p.useMemo(()=>kB(CB(N)),[N]);return p.useEffect(()=>{const L=D=>{const W=D.target;!W||!A.current||A.current.contains(W)||n()};return document.addEventListener("pointerdown",L,!0),()=>{document.removeEventListener("pointerdown",L,!0)}},[n]),p.useEffect(()=>{v(x);const L=g.filter(J=>J.source==="system").filter(J=>J.invocationName==="compact"?!0:d).map(J=>({id:J.id,name:J.name,invocationName:J.invocationName,source:"system",description:J.description,isBuiltIn:!0,...J.scope?{scope:J.scope}:{}})),D=g.filter(J=>J.source!=="system").map(J=>({id:J.id,name:J.name,invocationName:J.invocationName,source:J.source,description:J.description,...J.source==="skill"?{isSkill:!0}:{},...J.scope?{scope:J.scope}:{}})),W=bB(L,D.filter(J=>J.source==="extension"),D.filter(J=>J.source==="skill"),D.filter(J=>J.source==="prompt"));S(SB(W,e,f?"all":u))},[e,d,l,g,x,u,f]),p.useEffect(()=>{w(0)},[b]),p.useEffect(()=>{M.current=C},[C]),p.useEffect(()=>{s?.({listboxId:O,activeOptionId:MB({loading:y,hasSelectedCommand:!!b[C],selectedIndex:C,listboxId:O})})},[b,O,y,s,C]),p.useEffect(()=>{T.current[C]?.scrollIntoView({block:"nearest"})},[C]),p.useImperativeHandle(o,()=>({handleKeyDown:L=>{const D=b.length;if(L==="Escape"){n();return}if(D!==0){if(L==="ArrowDown"){j.current=!0,w(W=>(W+1)%D);return}if(L==="ArrowUp"){j.current=!0,w(W=>(W-1+D)%D);return}if(L==="Enter"||L==="Tab"){const W=(M.current%D+D)%D,z=b[W];z&&t(z)}}}}),[b,n,t]),f?c.jsx("div",{ref:A,className:"absolute bottom-full left-0 z-[100] mb-2 flex max-h-60 min-w-0 w-full max-w-[450px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-none",style:_!==void 0?{...r,maxHeight:_}:r,children:c.jsx(Xn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:y?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx($,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):c.jsxs("div",{children:[b.map((L,D)=>{const W=D===C,z=dv(L),J=Wr(L);return c.jsx("div",{id:Np(O,D),ref:B=>{T.current[D]=B},role:"option","aria-selected":W,className:R("flex cursor-pointer items-center gap-2 rounded-lg px-3 py-1.5 typography-ui-label",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:B=>B.preventDefault(),onPointerDown:B=>{B.pointerType==="touch"&&(E.current={x:B.clientX,y:B.clientY},I.current=!1)},onPointerMove:B=>{if(B.pointerType!=="touch"||!E.current)return;const U=B.clientX-E.current.x,P=B.clientY-E.current.y;Math.hypot(U,P)>6&&(I.current=!0)},onPointerUp:B=>{if(B.pointerType!=="touch")return;const U=I.current;E.current=null,I.current=!1,!U&&(B.preventDefault(),B.stopPropagation(),k.current=!0,t(L))},onPointerCancel:()=>{E.current=null,I.current=!1},onClick:()=>{if(k.current){k.current=!1;return}t(L)},onMouseMove:()=>{j.current=!1,w(D)},children:c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono font-semibold",children:["/",J]}),z&&c.jsx("span",{className:"shrink-0 rounded border border-[var(--interactive-border)]/60 bg-[var(--surface-muted)] px-1.5 py-1 text-[10px] font-bold uppercase leading-none tracking-tight text-muted-foreground",children:z})]})},L.id)}),b.length===0&&c.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})})}):c.jsxs("div",{ref:A,className:"absolute bottom-full left-0 z-[100] flex max-h-80 min-w-0 w-full max-w-[520px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-lg",style:_!==void 0?{...r,maxHeight:_}:r,children:[c.jsx("div",{role:"group","aria-label":"Filter commands",className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-2 py-1.5",children:IB.map(L=>c.jsx(Se,{variant:"chip",size:"xs","aria-pressed":u===L.value,onMouseDown:D=>D.preventDefault(),onClick:()=>h(L.value),children:L.label},L.value))}),c.jsx(Xn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:y?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx($,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):c.jsxs("div",{children:[b.map((L,D)=>{const W=D===C,z=dv(L),J=Wr(L);return c.jsx("div",{id:Np(O,D),ref:B=>{T.current[D]=B},role:"option","aria-selected":W,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:B=>B.preventDefault(),onPointerDown:B=>{B.pointerType==="touch"&&(E.current={x:B.clientX,y:B.clientY},I.current=!1)},onPointerMove:B=>{if(B.pointerType!=="touch"||!E.current)return;const U=B.clientX-E.current.x,P=B.clientY-E.current.y;Math.hypot(U,P)>6&&(I.current=!0)},onPointerUp:B=>{if(B.pointerType!=="touch")return;const U=I.current;E.current=null,I.current=!1,!U&&(B.preventDefault(),B.stopPropagation(),k.current=!0,t(L))},onPointerCancel:()=>{E.current=null,I.current=!1},onClick:()=>{if(k.current){k.current=!1;return}t(L)},onMouseMove:()=>{j.current=!1,w(D)},children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["/",J]}),z&&c.jsx("span",{className:R("ml-auto max-w-[45%] shrink-0 truncate text-xs leading-4",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:z})]}),L.description&&c.jsx("div",{className:R("mt-1 truncate text-xs leading-5",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:L.description}),L.source==="skill"&&L.name!==J&&c.jsx("div",{className:R("mt-0.5 truncate text-xs leading-4",W?"text-interactive-selection-foreground/60":"text-muted-foreground/80"),children:L.name})]})},L.id)}),b.length===0&&c.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),!f&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs leading-4 text-muted-foreground",children:"↑↓ Navigate · Enter Select · Esc Close"})]})});p4.displayName="CommandAutocomplete";const EB=(e,t=200)=>{const[n,r]=H.useState(e);return H.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},jB=p.forwardRef(({searchQuery:e,onFileSelect:t,onClose:n,style:r},s)=>{const o=Z3()??"",i=at(G=>G.activeProjectId),a=at(p.useCallback(G=>G.projects.find(K=>K.id===i)?.path??null,[i])),l=p.useMemo(()=>{const G=a||o;return G?G.replace(/\\/g,"/").replace(/\/+$/,""):null},[a,o]),d=$S(p.useCallback(G=>l?G.byRoot[l]:void 0,[l])),f=zS(G=>G.searchFiles),u=EB(e,180),h=US(),[m,g]=p.useState([]),[x,b]=p.useState([]),[S,y]=p.useState(!1),v=p.useRef(0),[C,w]=p.useState(0),M=p.useRef(0),[j,T]=p.useState(360),[A,_]=p.useState({}),[k,E]=p.useState({}),I=p.useRef([]),N=p.useRef([]),O=p.useRef([]),L=p.useRef(null),D=te(G=>G.isMobile),W=j1(L,D),z=(e??"").trim(),J=p.useMemo(()=>{if(!l||!d)return[];const G=[d.selectedPath,...d.openPaths.slice().reverse()].filter(re=>typeof re=="string"&&re.length>0),K=new Set,se=z.toLowerCase();return G.filter(re=>{if(K.has(re))return!1;K.add(re);const fe=re.startsWith(`${l}/`)?re.slice(l.length+1):re;return se?fe.toLowerCase().includes(se):!0}).slice(0,6).map(re=>{const fe=re.replace(/\\/g,"/"),ge=fe.split("/").filter(Boolean).pop()||fe,we=fe.startsWith(`${l}/`)?fe.slice(l.length+1):fe;return{name:ge,path:fe,relativePath:we,extension:ge.includes(".")?ge.split(".").pop()?.toLowerCase():void 0}})},[z,l,d]),B=x,U=J,P=m;p.useEffect(()=>{const G=K=>{const se=K.target;!se||!L.current||L.current.contains(se)||n()};return document.addEventListener("pointerdown",G,!0),()=>{document.removeEventListener("pointerdown",G,!0)}},[n]),p.useEffect(()=>{if(!o){g([]);return}const K=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!K){g([]);return}let se=!1;return v.current++,y(!0),f(o,K,80,{includeHidden:!0,respectGitignore:!h,type:"file"}).then(ce=>{if(se)return;const re=new Set(J.map(fe=>fe.path));g(ce.filter(fe=>!re.has(fe.path)).slice(0,15))}).catch(()=>{se||g([])}).finally(()=>{se||(v.current--,v.current<=0&&(v.current=0,y(!1)))}),()=>{se=!0,v.current=Math.max(0,v.current-1),v.current<=0&&y(!1)}},[o,u,J,f,h]),p.useEffect(()=>{if(!o){b([]);return}const K=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!K){b([]);return}let se=!1;return v.current++,y(!0),f(o,K,20,{includeHidden:!0,respectGitignore:!h,type:"directory"}).then(ce=>{se||b(ce.slice(0,10))}).catch(()=>{se||b([])}).finally(()=>{se||(v.current--,v.current<=0&&(v.current=0,y(!1)))}),()=>{se=!0,v.current=Math.max(0,v.current-1),v.current<=0&&y(!1)}},[o,u,f,h]),p.useEffect(()=>{w(0),_({}),E({})},[P,B,U.length]),p.useEffect(()=>{M.current=C},[C]),p.useEffect(()=>{I.current[C]?.scrollIntoView({block:"nearest"})},[C]),p.useEffect(()=>{let G=null;const K=()=>{G!==null&&cancelAnimationFrame(G),G=requestAnimationFrame(()=>{const se={},ce={};N.current.forEach((re,fe)=>{if(!re)return;const we=O.current[fe]?.offsetWidth??re.scrollWidth,Me=Math.max(0,we-re.clientWidth),He=Me>8;if(se[fe]=He,He){const Ae=Math.max(.6,Me/110);ce[fe]=Ae}}),_(se),E(ce)})};return K(),window.addEventListener("resize",K),()=>{G!==null&&cancelAnimationFrame(G),window.removeEventListener("resize",K)}},[P,B]),p.useEffect(()=>{const G=N.current[C];if(!G)return;const K=()=>{const ce=G.clientWidth;ce>0&&T(ce)};if(K(),typeof ResizeObserver>"u")return;const se=new ResizeObserver(K);return se.observe(G),()=>{se.disconnect()}},[C]);const q=p.useCallback(G=>{t(G)},[t]);p.useImperativeHandle(s,()=>({handleKeyDown:G=>{if(G==="Escape"){n();return}const K=B.length+U.length+P.length;if(K!==0){if(G==="ArrowDown"){w(se=>(se+1)%K);return}if(G==="ArrowUp"){w(se=>(se-1+K)%K);return}if(G==="Enter"||G==="Tab"){const ce=(M.current%K+K)%K;if(ce<B.length){const ge=B[ce];ge&&q(ge);return}const re=ce-B.length,fe=re<U.length?U[re]:P[re-U.length];fe&&q(fe)}}}}),[P,B,U,n,q]);const F=G=>{switch(G.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return c.jsx($,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-info)]"});case"json":return c.jsx($,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-warning)]"});case"md":case"mdx":return c.jsx($,{name:"file",className:"h-3.5 w-3.5 text-muted-foreground"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return c.jsx($,{name:"file-image",className:"h-3.5 w-3.5 text-[var(--status-success)]"});default:return c.jsx($,{name:"file-pdf",className:"h-3.5 w-3.5 text-muted-foreground"})}},ee=(G,K,se)=>{const ce=G.relativePath||G.name,re=Dg(ce,{maxLength:60}),fe=C===K,ge=A[K]??!1,we=k[K]??2.6;return c.jsxs("div",{ref:Me=>{I.current[K]=Me},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",fe&&"bg-interactive-selection"),onClick:()=>q(G),onMouseMove:()=>w(K),children:[F(G),c.jsxs("span",{ref:Me=>{N.current[K]=Me},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:fe?{"--file-mention-marquee-width":`${j}px`,"--file-mention-marquee-duration":`${we}s`}:void 0,"aria-label":ce,children:[c.jsx("span",{ref:Me=>{O.current[K]=Me},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:ce}),ge&&fe?c.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:ce}):c.jsx("span",{className:"block truncate",children:re})]})]},se)};return c.jsxs("div",{ref:L,className:"absolute z-[100] min-w-0 w-full max-w-[640px] max-h-64 bg-background border-2 border-border/60 rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",style:W!==void 0?{...r,maxHeight:W}:r,children:[c.jsx(Xn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-0",children:S?c.jsx("div",{className:"flex items-center justify-center py-4",children:c.jsx($,{name:"refresh",className:"h-4 w-4 animate-spin text-muted-foreground"})}):c.jsxs("div",{className:"pb-2",children:[B.map((G,K)=>{const se=K,ce=G.relativePath||G.name,re=Dg(ce,{maxLength:60}),fe=C===se;return c.jsxs("div",{ref:ge=>{I.current[se]=ge},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",fe&&"bg-interactive-selection"),onClick:()=>q(G),onMouseMove:()=>w(se),children:[c.jsx($,{name:"folder-3-fill",className:"h-3.5 w-3.5 text-primary/60"}),c.jsx("span",{className:"flex-1 min-w-0 truncate","aria-label":ce,children:re})]},`dir-${G.path}`)}),B.length>0&&(U.length>0||P.length>0)&&c.jsx("div",{className:"my-1 border-t border-border/60"}),U.map((G,K)=>ee(G,B.length+K,`recent-${G.path}`)),U.length>0&&P.length>0&&c.jsx("div",{className:"my-1 border-t border-border/60"}),P.map((G,K)=>ee(G,B.length+U.length+K,G.path)),P.length===0&&B.length===0&&U.length===0&&c.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No matches found"})]})}),!D&&c.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});function _B(e){const t=(e.description||e.content).replace(/\s+/g," ").trim();return t.length>140?`${t.slice(0,140).trimEnd()}…`:t}const m4=p.forwardRef(({searchQuery:e,onSnippetSelect:t,onClose:n,style:r},s)=>{const o=p.useRef(null),i=te(j=>j.isMobile),a=j1(o,i),[l,d]=p.useState(0),f=p.useRef(0),[u,h]=p.useState([]),m=p.useRef([]),g=Pr(j=>j.snippets),x=Pr(j=>j.loadSnippets),b=Qn(),S=Pr(j=>j.setSnippetDraft),y=Pr(j=>j.setSelectedSnippet),v=te(j=>j.setSettingsDialogOpen),C=te(j=>j.setSettingsPage);p.useEffect(()=>{x(b)},[x,b]),p.useEffect(()=>{const j=e.trim(),A=[...j.length?g.filter(_=>fo(_.name,j)||_.aliases.some(k=>fo(k,j))):g].sort((_,k)=>_.source==="project"&&k.source!=="project"?-1:_.source!=="project"&&k.source==="project"?1:_.name.localeCompare(k.name));h(A),d(A.length?1:0)},[e,g]),p.useEffect(()=>{f.current=l,m.current[l]?.scrollIntoView({block:"nearest"})},[l]),p.useEffect(()=>{const j=T=>{const A=T.target;A&&o.current&&!o.current.contains(A)&&n()};return document.addEventListener("pointerdown",j,!0),()=>document.removeEventListener("pointerdown",j,!0)},[n]);const w=p.useCallback(j=>{const T=e.trim(),A=j.aliases.includes(T)?T:j.name;t(j,A)},[t,e]),M=p.useCallback(()=>{const j=new Set(g.map(_=>_.name));let T="new-snippet",A=1;for(;j.has(T);)T=`new-snippet-${A++}`;S({name:T,scope:"global"}),y(null),C("snippets"),v(!0),n()},[n,y,v,C,S,g]);return p.useImperativeHandle(s,()=>({handleKeyDown:j=>{if(j==="Escape"){n();return}const T=u.length+1;if(j==="ArrowDown"){d(A=>(A+1)%T);return}if(j==="ArrowUp"){d(A=>(A-1+T)%T);return}if(j==="Enter"||j==="Tab"){if(f.current===0){M();return}const A=u[f.current-1];A&&w(A)}}}),[w,u,n,M]),c.jsxs("div",{ref:o,role:"listbox","aria-label":"Snippets","aria-activedescendant":l===0?"snippet-option-new":`snippet-option-${l}`,className:"absolute bottom-full left-0 z-[100] flex max-h-80 min-w-0 w-full max-w-[520px] flex-col overflow-hidden rounded-xl border border-border/80 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-lg",style:a!==void 0?{...r,maxHeight:a}:r,children:[c.jsxs(Xn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:[c.jsx("div",{id:"snippet-option-new",ref:j=>{m.current[0]=j},role:"option","aria-selected":l===0,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",l===0?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:j=>j.preventDefault(),onClick:M,onMouseMove:()=>d(0),children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"typography-ui-label font-medium",children:"Create a new snippet"}),c.jsx("div",{className:R("mt-1 text-xs leading-5",l===0?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:"Save reusable text for the # picker"})]})}),u.length?u.map((j,T)=>{const A=T+1,_=A===l,k=j.source==="project"?"Project":"Global",E=_B(j);return c.jsx("div",{id:`snippet-option-${A}`,ref:I=>{m.current[A]=I},role:"option","aria-selected":_,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",_?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:I=>I.preventDefault(),onClick:()=>w(j),onMouseMove:()=>d(A),children:c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["#",j.name]}),c.jsx("span",{className:R("ml-auto shrink-0 text-xs leading-4",_?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:k})]}),E?c.jsx("div",{className:R("mt-1 truncate text-xs leading-5",_?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:E}):null]})},`${j.source}:${j.id}`)}):c.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No snippets found"})]}),!i&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs leading-4 text-muted-foreground",children:"↑↓ Navigate · Enter Select · Esc Close"})]})});m4.displayName="SnippetAutocomplete";const TB={mention:520,command:520,snippet:520};function AB(e,t){if(t)return{left:`${t.left}px`,top:`${t.top}px`,bottom:"auto",width:`min(${TB[e]}px, calc(100% - ${t.left+8}px))`,maxHeight:`${t.maxHeight}px`,transform:t.place==="above"?"translateY(-100%)":void 0}}function NB(e){const{open:t,query:n,overlayPosition:r,onClose:s}=e;if(!t)return null;const o=AB(t,r);switch(t){case"command":return c.jsx(p4,{ref:e.commandRef,searchQuery:n,onCommandSelect:e.onCommandSelect,onClose:s,style:o,onComboboxStateChange:e.onCommandComboboxStateChange});case"snippet":return c.jsx(m4,{ref:e.snippetRef,searchQuery:n,onSnippetSelect:e.onSnippetSelect,onClose:s,style:o});case"mention":return c.jsx(jB,{ref:e.mentionRef,searchQuery:n,onFileSelect:e.onFileSelect,onClose:s,style:o})}}const uv=Object.freeze({0:"var(--primary)",1:"var(--border)",2:"var(--primary)",3:"var(--border)",4:"var(--status-success)",5:"var(--status-error)",6:"var(--status-warning)",7:"var(--muted-foreground)",8:"var(--muted-foreground)",9:"var(--foreground)",10:"var(--muted-foreground)",11:"transparent",12:"var(--oc-scrollbar-thumb, var(--muted-foreground))",13:"var(--foreground)",14:"var(--foreground)",15:"var(--foreground)",16:"var(--muted-foreground)",17:"var(--tools-title)",18:"var(--tools-description)",19:"var(--markdown-heading1, var(--primary))",20:"var(--markdown-link, var(--primary))",21:"var(--muted-foreground)",22:"var(--markdown-inline-code, var(--syntax-string, var(--status-success)))",23:"var(--syntax-foreground, var(--foreground))",24:"var(--tools-border, var(--border))",25:"var(--markdown-blockquote, var(--muted-foreground))",26:"var(--markdown-blockquote-border, var(--border))",27:"var(--markdown-hr, var(--border))",28:"var(--markdown-list-marker, var(--primary))",29:"var(--tools-edit-added, var(--status-success))",30:"var(--tools-edit-removed, var(--status-error))",31:"var(--muted-foreground)",32:"var(--syntax-comment, var(--muted-foreground))",33:"var(--syntax-keyword, var(--primary))",34:"var(--syntax-function, var(--primary))",35:"var(--syntax-variable, var(--foreground))",36:"var(--syntax-string, var(--status-success))",37:"var(--syntax-number, var(--status-warning))",38:"var(--syntax-type, var(--status-info))",39:"var(--syntax-operator, var(--foreground))",40:"var(--syntax-punctuation, var(--muted-foreground))",41:"var(--muted-foreground)",42:"var(--muted-foreground)",43:"var(--muted-foreground)",44:"var(--muted-foreground)",45:"var(--muted-foreground)",46:"var(--muted-foreground)",47:"var(--muted-foreground)",48:"var(--primary)"}),fv=Object.freeze({0:"var(--interactive-selection)",1:"var(--interactive-selection)",2:"var(--surface-elevated, var(--card))",3:"var(--surface-muted)",4:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",5:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",6:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))"}),Lp=Object.freeze({30:"var(--muted-foreground)",31:"var(--status-error)",32:"var(--status-success)",33:"var(--status-warning)",34:"var(--status-info)",35:"var(--primary)",36:"var(--status-info)",37:"var(--foreground)",90:"var(--muted-foreground)",91:"var(--status-error)",92:"var(--status-success)",93:"var(--status-warning)",94:"var(--status-info)",95:"var(--primary)",96:"var(--status-info)",97:"var(--foreground)"}),hv=Object.freeze({40:"var(--muted)",41:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))",42:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",43:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",44:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",45:"var(--surface-elevated)",46:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",47:"var(--surface-elevated)",100:"var(--muted)",101:"var(--status-error-background, color-mix(in srgb, var(--status-error) 15%, transparent))",102:"var(--status-success-background, color-mix(in srgb, var(--status-success) 15%, transparent))",103:"var(--status-warning-background, color-mix(in srgb, var(--status-warning) 15%, transparent))",104:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",105:"var(--surface-elevated)",106:"var(--status-info-background, color-mix(in srgb, var(--status-info) 15%, transparent))",107:"var(--surface-elevated)"});function pv(e){if(e<0||e>255)return"var(--foreground)";if(e<16)return Lp[e<8?e+30:e-8+90]??"var(--foreground)";if(e>=232){const i=8+(e-232)*10;return`rgb(${i}, ${i}, ${i})`}const t=e-16,n=t%6,r=Math.floor(t/6)%6,s=Math.floor(t/36),o=[0,95,135,175,215,255];return`rgb(${o[s]}, ${o[r]}, ${o[n]})`}const LB=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;function g4(e){if(e)try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t.href:void 0}catch{return}}function Nn(e){return e.replace(LB,"")}function y4(e){return e.includes("\x1B")}function v4(e){if(!e)return[];if(!y4(e))return[{text:e}];const t=[],n={bold:!1,dim:!1,italic:!1,underline:!1,strikethrough:!1,inverse:!1},r=/\u001b(?:\[([0-?]*)[ -/]*([@-~])|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;let s=0,o;const i=a=>{if(!a)return;if(t.length>0){const d=t[t.length-1];if((d.fg??void 0)===n.fg&&(d.bg??void 0)===n.bg&&!!d.bold===n.bold&&!!d.dim===n.dim&&!!d.italic===n.italic&&!!d.underline===n.underline&&!!d.strikethrough===n.strikethrough&&!!d.inverse===n.inverse&&d.href===n.href){d.text+=a;return}}const l={text:a};n.fg&&(l.fg=n.fg),n.bg&&(l.bg=n.bg),n.bold&&(l.bold=!0),n.dim&&(l.dim=!0),n.italic&&(l.italic=!0),n.underline&&(l.underline=!0),n.strikethrough&&(l.strikethrough=!0),n.inverse&&(l.inverse=!0),n.href&&(l.href=n.href),t.push(l)};for(;(o=r.exec(e))!==null;){o.index>s&&i(e.slice(s,o.index)),s=r.lastIndex;const a=o[1],l=o[2];if(o[0].startsWith("\x1B]8;")){const d=o[0].slice(4).replace(/(?:\u0007|\u001b\\)$/,""),f=d.slice(d.indexOf(";")+1);n.href=f||void 0;continue}if(l==="m"&&(!a||/^[0-9;]*$/.test(a))){const d=(a||"0").split(";").map(u=>u===""?0:parseInt(u,10));let f=0;for(;f<d.length;){const u=d[f];if(Number.isNaN(u)||u===0)n.fg=void 0,n.bg=void 0,n.bold=!1,n.dim=!1,n.italic=!1,n.underline=!1,n.strikethrough=!1,n.inverse=!1,f+=1;else if(u===1)n.bold=!0,f+=1;else if(u===2)n.dim=!0,f+=1;else if(u===3)n.italic=!0,f+=1;else if(u===4)n.underline=!0,f+=1;else if(u===7)n.inverse=!0,f+=1;else if(u===9)n.strikethrough=!0,f+=1;else if(u===22)n.bold=!1,n.dim=!1,f+=1;else if(u===23)n.italic=!1,f+=1;else if(u===24)n.underline=!1,f+=1;else if(u===27)n.inverse=!1,f+=1;else if(u===29)n.strikethrough=!1,f+=1;else if(u>=30&&u<=37)n.fg=Lp[u],f+=1;else if(u===39)n.fg=void 0,f+=1;else if(u>=40&&u<=47)n.bg=hv[u],f+=1;else if(u===49)n.bg=void 0,f+=1;else if(u>=90&&u<=97)n.fg=Lp[u],f+=1;else if(u>=100&&u<=107)n.bg=hv[u],f+=1;else if(u===38){const h=d[f+1];if(h===5){const m=d[f+2];m!==void 0&&(n.fg=pv(m)),f+=3}else if(h===2){const m=d[f+2],g=d[f+3],x=d[f+4];m!==void 0&&g!==void 0&&x!==void 0&&(m===1&&g===1&&x in uv?n.fg=uv[x]:n.fg=`rgb(${m}, ${g}, ${x})`),f+=5}else f+=1}else if(u===48){const h=d[f+1];if(h===5){const m=d[f+2];m!==void 0&&(n.bg=pv(m)),f+=3}else if(h===2){const m=d[f+2],g=d[f+3],x=d[f+4];m!==void 0&&g!==void 0&&x!==void 0&&(m===1&&g===1&&x in fv?n.bg=fv[x]:n.bg=`rgb(${m}, ${g}, ${x})`),f+=5}else f+=1}else f+=1}}}return s<e.length&&i(e.slice(s)),t}const bd=e=>{const t={};let n=!1,r=e.fg,s=e.bg;if(e.inverse){const o=r;r=s??"var(--surface-background, var(--background))",s=o??"var(--foreground)",n=!0}return r&&(t.color=r,n=!0),s&&(t.backgroundColor=s,n=!0),e.bold&&(t.fontWeight=600,n=!0),e.dim&&(t.opacity=.65,n=!0),e.italic&&(t.fontStyle="italic",n=!0),e.underline&&e.strikethrough?(t.textDecoration="underline line-through",n=!0):e.underline?(t.textDecoration="underline",n=!0):e.strikethrough&&(t.textDecoration="line-through",n=!0),n?t:void 0},x4=e=>e.mode==="overlay"&&!e.hidden&&e.frame?.visible!==!1&&!!e.frame?.layout,RB=/[\u2500-\u259f]/g,mv=(e,t)=>{for(const n of e.frame?.lines??[]){const r=Nn(n).replace(RB," ").trim().split(/\s+/)[0]??"";if(/[\p{L}\p{N}]/u.test(r))return r.length>16?`${r.slice(0,15)}…`:r}return`Panel ${t+1}`},PB=(e,t)=>{const n=new Map;for(const o of e){if(!o.parentId)continue;const i=n.get(o.parentId)??[];i.push(o),n.set(o.parentId,i)}const r=new Map(t.map((o,i)=>[o,i])),s=[];for(const[o,i]of n){const a=[...i].sort((d,f)=>f.z-d.z),l=i.find(d=>d.focused)??a.find(d=>d.capturing)??a[0];i.sort((d,f)=>(r.get(d.surfaceId)??0)-(r.get(f.surfaceId)??0)),s.push({parentId:o,members:i,front:l})}return s},DB=new Map,OB=(e,t)=>{let n=null;const r=new Set(t.map(s=>s.parentId));for(const s of t){if(s.members.length<2||e.has(s.parentId))continue;const o=s.members[0]?.frame?.layout;n??=new Map(e),n.set(s.parentId,{row:o?.row??0,col:o?.col??0})}for(const s of e.keys())r.has(s)||(n??=new Map(e),n.delete(s));return n??e},HB=(e,t,n)=>{if(!(t>0))return e.top<n?"below":"above";const r=Math.max(0,Math.min(e.top,t-e.layoutHeight));return r>=n?"above":r+e.height+n<=t?"below":"inside"},b4=e=>ze(t=>{const n=e?t.reducer.bySession.get(e)?.extensionSurfaces:void 0;if(!n)return!1;for(const r of n.values())if(r.capturing&&x4(r))return!0;return!1},Object.is,e?`session:${e}`:"*",e??"");function FB(e){return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...e,children:[c.jsx("path",{d:"M208,56V200a8,8,0,0,1-8,8H56a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H200A8,8,0,0,1,208,56Z",opacity:"0.2"}),c.jsx("path",{d:"M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z"})]})}const BB=p.memo(function(t){const{isMobile:n,footerIconButtonClass:r,sendIconSizeClass:s,stopIconSizeClass:o,canSend:i,disabledReason:a,canAbort:l,hasContent:d,currentSessionId:f,newSessionDraftOpen:u,isSending:h=!1,onPrimaryAction:m,onQueueMessage:g,onAbort:x}=t,b=c.jsx("button",{type:n?"button":"submit",disabled:!i||!f&&!u||h,onClick:S=>{n&&(S.preventDefault(),m())},className:R(r,i&&(f||u)&&!h?"text-primary hover:text-primary":"opacity-30",h&&"animate-pulse"),"aria-label":h?"Creating session…":a||"Send message",title:h?"Creating session…":a||void 0,children:h?c.jsx($,{name:"loader-4",className:R(s,"animate-spin")}):c.jsx($,{name:"send-plane-2",className:R(s)})});return l?c.jsxs("div",{className:"relative",children:[d?c.jsx("button",{type:"button",disabled:!f||!i,onClick:S=>{n&&S.preventDefault(),g()},className:R(r,"absolute z-20 bottom-full left-1/2 -translate-x-1/2 mb-1",f&&i?"text-primary hover:text-primary":"opacity-30"),"aria-label":a||"Add follow-up",title:a||void 0,children:c.jsx($,{name:"send-plane-2",className:R(s,"-rotate-90")})}):null,c.jsx("button",{type:"button",onClick:x,className:R(r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:c.jsx(FB,{className:R(o)})})]}):b},(e,t)=>e.isMobile===t.isMobile&&e.footerIconButtonClass===t.footerIconButtonClass&&e.sendIconSizeClass===t.sendIconSizeClass&&e.stopIconSizeClass===t.stopIconSizeClass&&e.canSend===t.canSend&&e.disabledReason===t.disabledReason&&e.canAbort===t.canAbort&&e.hasContent===t.hasContent&&e.currentSessionId===t.currentSessionId&&e.newSessionDraftOpen===t.newSessionDraftOpen&&e.isSending===t.isSending&&e.onPrimaryAction===t.onPrimaryAction&&e.onQueueMessage===t.onQueueMessage&&e.onAbort===t.onAbort),VB=p.memo(function(t){const{footerIconButtonClass:n,iconSizeClass:r,handlePickLocalFiles:s,onOpenSettings:o,isAttachmentDisabled:i,disabled:a=!1,onLinkGitHub:l}=t;return c.jsxs("div",{className:"flex items-center gap-x-1.5",children:[c.jsx("div",{className:"relative inline-flex",children:t.onOpenMobileSheet?c.jsx("button",{type:"button",className:n,onClick:t.onOpenMobileSheet,disabled:i,onMouseDown:d=>d.preventDefault(),onPointerDownCapture:d=>{d.pointerType==="touch"&&d.preventDefault()},title:"Add attachment","aria-label":"Add attachment",children:c.jsx($,{name:"add-circle",className:R(r,"text-current")})}):c.jsxs(cu,{onOpenChange:t.onMenuOpenChange,children:[c.jsx(lu,{asChild:!0,children:c.jsx("button",{type:"button",className:n,title:"Add attachment","aria-label":"Add attachment",disabled:i,children:c.jsx($,{name:"add-circle",className:R(r,"text-current")})})}),c.jsxs(du,{align:"start",children:[c.jsxs(ho,{onSelect:()=>{requestAnimationFrame(s)},children:[c.jsx($,{name:"attachment-2"}),"Attach files"]}),l?c.jsxs(ho,{onSelect:()=>{requestAnimationFrame(l)},children:[c.jsx($,{name:"github"}),"Link issue / pull request"]}):null]})]})}),o?c.jsx("button",{type:"button",onClick:o,className:n,title:"Model and agent settings","aria-label":"Model and agent settings",disabled:a,children:c.jsx($,{name:"ai-agent",className:R(r,"text-current")})}):null]})},(e,t)=>e.footerIconButtonClass===t.footerIconButtonClass&&e.iconSizeClass===t.iconSizeClass&&e.handlePickLocalFiles===t.handlePickLocalFiles&&e.onOpenSettings===t.onOpenSettings&&e.onMenuOpenChange===t.onMenuOpenChange&&e.onOpenMobileSheet===t.onOpenMobileSheet&&e.isAttachmentDisabled===t.isAttachmentDisabled&&e.disabled===t.disabled&&e.onLinkGitHub===t.onLinkGitHub);function $B(e){const{isMobile:t,isInline:n,alignToolsEnd:r,sessionId:s,newSessionDraftOpen:o,children:i,leadingExtra:a,trailingExtra:l,actionsOverride:d,footerPaddingClass:f,footerGapClass:u,footerIconButtonClass:h,iconSizeClass:m,sendIconSizeClass:g,stopIconSizeClass:x,canSend:b,disabledReason:S,canAbort:y,hasContent:v,isSending:C=!1,isAttachmentDisabled:w,onOpenSettings:M,onPickLocalFiles:j,onLinkGitHub:T,onPrimaryAction:A,onQueueMessage:_,onAbort:k}=e,E=c.jsx(VB,{footerIconButtonClass:h,iconSizeClass:m,handlePickLocalFiles:j,onLinkGitHub:T,onOpenSettings:M,onOpenMobileSheet:t?j:void 0,disabled:C,isAttachmentDisabled:w}),I=d??c.jsx(BB,{isMobile:t,footerIconButtonClass:h,sendIconSizeClass:g,stopIconSizeClass:x,canSend:b,disabledReason:S,canAbort:y,hasContent:v,isSending:C,currentSessionId:s,newSessionDraftOpen:o,onPrimaryAction:A,onQueueMessage:_,onAbort:k});if(t)return c.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[c.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),c.jsx("div",{className:R("flex-shrink-0",f,"flex items-center gap-x-1.5"),"data-chat-input-footer":"true",children:c.jsxs("div",{className:"flex w-full items-center justify-between gap-x-1.5",children:[c.jsxs("div",{className:"composer-mobile-actions flex min-w-0 items-center gap-x-2 overflow-x-auto pl-1","data-no-drawer-swipe":"true",children:[E,a?c.jsx("div",{className:R("w-max shrink-0",C&&"pointer-events-none opacity-60"),inert:C||void 0,children:a}):null]}),c.jsxs("div",{className:"flex min-w-0 shrink-0 items-center justify-end gap-x-1",children:[l,I]})]})})]});if(n){const N=r?"self-end":"self-center";return c.jsxs("div",{className:R("grid grid-cols-[auto_minmax(0,1fr)_auto] bg-transparent",f,u),"data-chat-input-footer":"true",children:[c.jsx("div",{className:R("flex min-w-0 items-center",u,N),children:E}),c.jsx("div",{className:"min-w-0",children:i}),c.jsxs("div",{className:R("flex min-w-0 items-center justify-end",u,N),children:[l,I]})]})}return c.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[c.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),c.jsxs("div",{className:R("flex flex-shrink-0 items-center justify-between",f,u),"data-chat-input-footer":"true",children:[c.jsxs("div",{className:R("flex min-w-0 items-center",u),children:[E,a?c.jsx("div",{className:R("w-max min-w-0 shrink-0",C&&"pointer-events-none opacity-60"),inert:C||void 0,children:a}):null]}),c.jsxs("div",{className:R("flex flex-shrink-0 items-center",u),children:[l,I]})]})]})}const w4=p.memo(({sessionId:e})=>{const t=pe(y=>y.restoreToMessage),n=pe(y=>y.forkFromMessage),r=pe(y=>y.handleSlashRedo),[s,o]=p.useState(null),[i,a]=p.useState(null),[l,d]=p.useState(!0),f=SI(e),u=f?.targetEntryId,h=p.useMemo(()=>f?f.abandoned.filter(y=>y.role==="user"):[],[f]),m="No text content",g=p.useMemo(()=>!f||h.length===0?[]:h.map(y=>({id:y.id,text:y.preview?.replace(/\s+/g," ").trim()||m})),[h,f,m]),x=g[0]?.id;p.useEffect(()=>{d(!0)},[u,x]);const b=p.useCallback(async y=>{if(!(!e||s)){o(y);try{const v=h.findIndex(w=>w.id===y),C=v>=0?h[v+1]:void 0;C?(await t(e,C.id),Ce.success("Restored messages through this point")):await r(e)}catch(v){Ce.error(v instanceof Error?v.message:"Failed to restore messages")}finally{o(null)}}},[h,r,t,s,e]),S=p.useCallback(async y=>{if(!(!e||i)){a(y);try{await n(e,y)}catch(v){Ce.error(v instanceof Error?v.message:"Failed to fork session")}finally{a(null)}}},[n,i,e]);return!e||g.length===0?null:c.jsx("div",{className:"pb-2 w-full px-1",children:c.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[c.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--interactive-hover)] transition-colors",onClick:()=>d(y=>!y),"aria-expanded":!l,children:[c.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Reverted"," messages ",g.length]}),c.jsx($,{name:"arrow-down-s",className:R("ml-auto h-4 w-4 text-muted-foreground transition-transform",!l&&"rotate-180"),"aria-hidden":"true"})]}),!l&&c.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:g.map(y=>c.jsxs("div",{className:"flex min-w-0 items-center gap-2 py-1",children:[c.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:y.text}),c.jsxs(Se,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{S(y.id)},children:[i===y.id?c.jsx($,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):c.jsx($,{name:"git-branch",className:"h-3 w-3","aria-hidden":"true"}),"Fork"]}),c.jsxs(Se,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{b(y.id)},children:[s===y.id?c.jsx($,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):c.jsx($,{name:"arrow-go-forward",className:"h-3 w-3","aria-hidden":"true"}),"Restore"]})]},y.id))})]})})});w4.displayName="RevertedMessageDock";const zB=({isInternalDrag:e,iconButtonBaseClass:t,iconSizeClass:n,radius:r,isAttachmentDisabled:s,onPickLocalFiles:o})=>c.jsx("div",{className:"absolute -inset-px z-50 flex items-center justify-center border border-border/80 bg-[var(--surface-subtle)]/90",style:{borderRadius:r},children:c.jsxs("div",{className:"text-center",children:[c.jsx("div",{className:"inline-flex justify-center",children:c.jsx("button",{type:"button",className:t,onClick:o,disabled:s,title:"Attach files","aria-label":"Attach files",children:c.jsx($,{name:"attachment-2",className:R(n,"text-current")})})}),c.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:e?"Drop to insert as mention":"Drop files here to attach"})]})}),UB={type:"file",multiple:!0,accept:kM};function qB({inputRef:e,onChange:t}){return c.jsx("input",{ref:e,...UB,className:"hidden",onChange:t})}function WB({available:e,disabled:t,className:n,iconClassName:r,onStart:s}){return e?c.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:n,disabled:t,onClick:s,title:"Start dictation","aria-label":"Start dictation",children:c.jsx($,{name:"mic",className:R("size-4",r)})}):null}const KB=48,wd=2,GB=1,gv=wd+GB,oh=.08,Lo=512,ZB=2,YB=(e,t)=>{e.values[e.cursor]=t,e.cursor=(e.cursor+1)%Lo,e.count=Math.min(Lo,e.count+1)},XB=(e,t)=>{const n=Math.min(e.count,t),r=(e.cursor-n+Lo)%Lo;return Array.from({length:n},(s,o)=>e.values[(r+o)%Lo])},yv=(e,t,n,r,s)=>{const o=Math.max(1,Math.round(wd*n.pixelRatio)),i=Math.max(1,n.height-Math.round(8*n.pixelRatio)),a=Math.max(Math.round(2*n.pixelRatio),Math.round(i*r)),l=Math.round((n.height-a)/2);e.globalAlpha=.35+r*.65,e.fillStyle=s,e.beginPath(),e.roundRect(t,l,o,a,o/2),e.fill(),e.globalAlpha=1};function JB({subscribeLevel:e}){const t=p.useRef(null),n=p.useRef(null),r=p.useRef(null),s=p.useRef(0),o=p.useRef(""),i=p.useRef({width:0,height:0,pixelRatio:1}),a=p.useRef({values:Array.from({length:Lo},()=>oh),cursor:0,count:0}),l=p.useCallback(()=>{const d=n.current,f=i.current;if(!d||f.width<=0||f.height<=0||!o.current)return;d.clearRect(0,0,f.width,f.height);const u=Math.max(1,Math.round(gv*f.pixelRatio)),h=Math.ceil(f.width/u),m=XB(a.current,h),g=h-m.length;for(let x=0;x<h;x+=1){const b=x>=g?m[x-g]:oh,S=f.width-Math.round(wd*f.pixelRatio)-(h-1-x)*u;yv(d,S,f,b,o.current)}},[]);return p.useEffect(()=>{const d=t.current;if(!d)return;const f=d.getContext("2d",{alpha:!0});if(!f)return;n.current=f;const u=g=>{const x=Math.min(ZB,Math.max(1,window.devicePixelRatio||1)),b={width:Math.max(1,Math.round(g*x)),height:Math.round(KB*x),pixelRatio:x},S=i.current;S.width===b.width&&S.height===b.height&&S.pixelRatio===b.pixelRatio||(i.current=b,d.width=b.width,d.height=b.height,o.current=getComputedStyle(d).color,l())},h=new ResizeObserver(g=>{const x=g[0]?.contentRect.width;typeof x=="number"&&x>0&&u(x)});h.observe(d);const m=new MutationObserver(()=>{o.current=getComputedStyle(d).color,l()});return m.observe(document.documentElement,{attributes:!0,attributeFilter:["class","style"]}),()=>{h.disconnect(),m.disconnect(),n.current=null}},[l]),p.useEffect(()=>{const d=()=>{r.current=null;const u=t.current,h=n.current,m=i.current;if(!u||!h||m.width<=0||!o.current)return;const g=Math.max(oh,s.current),x=Math.max(1,Math.round(gv*m.pixelRatio));m.width>x&&(h.globalCompositeOperation="copy",h.drawImage(u,x,0,m.width-x,m.height,0,0,m.width-x,m.height),h.globalCompositeOperation="source-over"),h.clearRect(Math.max(0,m.width-x),0,x,m.height),yv(h,m.width-Math.round(wd*m.pixelRatio),m,g,o.current),YB(a.current,g)},f=e(u=>{s.current=u,r.current===null&&(r.current=requestAnimationFrame(d))});return()=>{f(),r.current!==null&&cancelAnimationFrame(r.current)}},[e]),c.jsx("canvas",{ref:t,className:"h-12 w-full text-primary","aria-hidden":"true"})}const QB=e=>`${Math.floor(e/60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`;function eV({state:e,elapsedSeconds:t,buttonClassName:n,iconClassName:r,isMobile:s,onCancel:o,onDone:i}){const a=e==="recording"||e==="reconnecting";return c.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s?null:c.jsxs("div",{className:"mr-1 flex items-center gap-2 typography-ui-compact text-muted-foreground",children:[a?c.jsx("span",{className:"size-2 rounded-full bg-[var(--status-error)]","aria-hidden":"true"}):null,c.jsx("span",{className:"tabular-nums",children:QB(t)})]}),c.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:n,onClick:o,title:"Cancel dictation","aria-label":"Cancel dictation",children:c.jsx($,{name:"close",className:R("size-4",r)})}),c.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:R(n,"text-primary hover:text-primary"),onClick:i,disabled:!a,title:"Finish dictation","aria-label":"Finish dictation",children:c.jsx($,{name:"check",className:R("size-4",r)})})]})}function tV({state:e,subscribeLevel:t}){const n=e==="recording"||e==="reconnecting",r=e==="requesting-permission"?"Requesting microphone access...":e==="reconnecting"?"Recording. Reconnecting to the server...":e==="transcribing"?"Transcribing...":"Recording";return c.jsx("div",{className:"flex h-[7rem] w-full items-center px-3 py-3",role:"group","aria-label":"Dictation recorder",children:c.jsxs("div",{className:"min-w-0 flex-1",children:[n?c.jsx(JB,{subscribeLevel:t}):c.jsx("div",{className:"flex h-12 items-center justify-center typography-ui-label text-muted-foreground",children:r}),c.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:r})]})})}const nV=3e4;let Rp=null,Vi=null;const JX=()=>{Rp=null,Vi=null},rV=async e=>{const t=Y();if(!e?.fresh){const r=Rp;if(r&&r.key===t&&Date.now()<r.expiresAt)return r.status;const s=Vi;if(s&&s.key===t)return s.promise}const n=(async()=>{const r=await Nt("/api/stt/status");if(!r.ok)throw new Error("Could not load dictation settings");const s=await r.json();return!e?.fresh&&Y()===t&&(Rp={key:t,status:s,expiresAt:Date.now()+nV}),s})();e?.fresh||(Vi={key:t,promise:n});try{return await n}finally{Vi?.promise===n&&(Vi=null)}},sV=`
102
+ class PiChamberDictationProcessor extends AudioWorkletProcessor {
103
+ constructor() {
104
+ super();
105
+ this.outputRate = 16000;
106
+ this.step = sampleRate / this.outputRate;
107
+ this.position = 0;
108
+ this.source = [];
109
+ this.pending = [];
110
+ this.chunkSamples = 4000;
111
+ this.port.onmessage = (event) => {
112
+ if (event.data && event.data.type === 'flush') {
113
+ if (this.pending.length > 0) {
114
+ const samples = Int16Array.from(this.pending.splice(0));
115
+ this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
116
+ }
117
+ this.port.postMessage({ type: 'flushed' });
118
+ }
119
+ };
120
+ }
121
+ process(inputs) {
122
+ const input = inputs[0] && inputs[0][0];
123
+ if (!input || input.length === 0) return true;
124
+ let sum = 0;
125
+ for (let i = 0; i < input.length; i += 1) { this.source.push(input[i]); sum += input[i] * input[i]; }
126
+ this.port.postMessage({ type: 'level', value: Math.min(1, Math.sqrt(sum / input.length) * 3) });
127
+ while (this.position + 1 < this.source.length) {
128
+ const index = Math.floor(this.position);
129
+ const fraction = this.position - index;
130
+ const sample = this.source[index] + (this.source[index + 1] - this.source[index]) * fraction;
131
+ const clamped = Math.max(-1, Math.min(1, sample));
132
+ this.pending.push(clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767));
133
+ this.position += this.step;
134
+ }
135
+ const consumed = Math.floor(this.position);
136
+ if (consumed > 0) { this.source.splice(0, consumed); this.position -= consumed; }
137
+ while (this.pending.length >= this.chunkSamples) {
138
+ const samples = Int16Array.from(this.pending.splice(0, this.chunkSamples));
139
+ this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
140
+ }
141
+ return true;
142
+ }
143
+ }
144
+ registerProcessor('pichamber-dictation', PiChamberDictationProcessor);
145
+ `,oV=16e3,vv=4e3,S4=()=>typeof window>"u"?null:window.AudioContext??window.webkitAudioContext??null,ih=e=>{try{e?.disconnect()}catch{}};class iV{constructor(t){this.options=t}options;stream=null;context=null;source=null;processor=null;gain=null;listeners=new Set;pendingFallback=[];fallbackPosition=0;fallbackCarry=[];flushed=null;cancelled=!1;subscribeLevel(t){return this.listeners.add(t),()=>this.listeners.delete(t)}level(t){for(const n of this.listeners)n(t)}chunk(t){t.length&&this.options.onChunk(new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice())}async start(){if(this.stream)return;const t=S4();if(!t||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone recording is not supported");const n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});if(this.cancelled)throw n.getTracks().forEach(o=>o.stop()),new Error("Dictation cancelled");this.stream=n,this.options.onPermissionGranted?.();const r=new t;this.context=r,r.state==="suspended"&&await r.resume(),this.source=r.createMediaStreamSource(n),this.gain=r.createGain(),this.gain.gain.value=0;let s=null;if(r.audioWorklet&&typeof AudioWorkletNode<"u"){const o=URL.createObjectURL(new Blob([sV],{type:"text/javascript"}));try{await r.audioWorklet.addModule(o),s=new AudioWorkletNode(r,"pichamber-dictation",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1]})}catch{s=null}finally{URL.revokeObjectURL(o)}}if(s)s.port.onmessage=o=>{o.data.type==="level"?this.level(o.data.value??0):o.data.type==="chunk"&&o.data.buffer?this.chunk(new Int16Array(o.data.buffer)):o.data.type==="flushed"&&(this.flushed?.(),this.flushed=null)},this.processor=s;else{const o=r.createScriptProcessor(4096,1,1);o.onaudioprocess=i=>this.processFallback(i.inputBuffer.getChannelData(0),r.sampleRate),this.processor=o}this.source.connect(this.processor),this.processor.connect(this.gain),this.gain.connect(r.destination)}processFallback(t,n){let r=0;for(const a of t)r+=a*a;this.level(Math.min(1,Math.sqrt(r/Math.max(1,t.length))*3));const s=this.fallbackCarry.concat(Array.from(t)),o=n/oV;for(;this.fallbackPosition+1<s.length;){const a=Math.floor(this.fallbackPosition),l=this.fallbackPosition-a,d=s[a]+(s[a+1]-s[a])*l,f=Math.max(-1,Math.min(1,d));this.pendingFallback.push(f<0?Math.round(f*32768):Math.round(f*32767)),this.fallbackPosition+=o}const i=Math.floor(this.fallbackPosition);for(this.fallbackCarry=s.slice(i),this.fallbackPosition-=i;this.pendingFallback.length>=vv;)this.chunk(Int16Array.from(this.pendingFallback.splice(0,vv)))}async stop(){this.cancelled=!0;const t=this.processor;typeof AudioWorkletNode<"u"&&t instanceof AudioWorkletNode?await Promise.race([new Promise(n=>{this.flushed=n,t.port.postMessage({type:"flush"})}),new Promise(n=>window.setTimeout(n,100))]):this.pendingFallback.length&&this.chunk(Int16Array.from(this.pendingFallback.splice(0))),typeof ScriptProcessorNode<"u"&&t instanceof ScriptProcessorNode&&(t.onaudioprocess=null),ih(this.source),ih(t),ih(this.gain),this.stream?.getTracks().forEach(n=>n.stop()),await this.context?.close().catch(()=>{}),this.level(0),this.stream=null,this.context=null,this.source=null,this.processor=null,this.gain=null,this.pendingFallback=[],this.fallbackCarry=[],this.fallbackPosition=0,this.flushed=null}}const aV=()=>!!(S4()&&navigator.mediaDevices?.getUserMedia),ah=1,cV=300*16e3*2,xv=(e,t)=>{const n=new Uint8Array(4+t.byteLength);return new DataView(n.buffer).setUint32(0,e,!0),n.set(t,4),n},lV=()=>typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${crypto.getRandomValues(new Uint32Array(4)).join("-")}`;class dV{constructor(t,n,r){this.providerConfigId=t,this.onState=n,this.onError=r}providerConfigId;onState;onError;recordingId=lV();socket=null;socketStarted=!1;chunks=[];audioBytes=0;finishing=!1;cancelled=!1;failures=0;generation=0;reconnectTimer=null;finishPromise=null;resolveFinish=null;rejectFinish=null;begin(){this.connect()}append(t){if(this.cancelled||this.finishing||!t.byteLength)return;if(this.audioBytes+t.byteLength>cV){this.fail(new Error("Recording reached the five minute limit"));return}const n=t.slice(),r=this.chunks.length;this.chunks.push(n),this.audioBytes+=n.byteLength,this.socketStarted&&this.socket?.readyState===ah&&this.socket.send(xv(r,n))}finish(){return this.finishPromise?this.finishPromise:(this.finishing=!0,this.onState("transcribing"),this.finishPromise=new Promise((t,n)=>{this.resolveFinish=t,this.rejectFinish=n}),this.socketStarted?this.sendFinish():this.connect(),this.finishPromise)}cancel(){this.cancelled||(this.cancelled=!0,this.generation+=1,this.socket?.readyState===ah&&this.socketStarted&&this.socket.send(JSON.stringify({version:1,type:"cancel",recordingId:this.recordingId})),this.closeSocket(),this.clearAudio(),this.rejectFinish?.(new Error("Dictation cancelled")),this.rejectFinish=null,this.resolveFinish=null)}async connect(){if(this.cancelled||this.socket||this.reconnectTimer)return;const t=++this.generation;this.failures>0&&this.onState(this.finishing?"transcribing":"reconnecting");try{const n=await qS();if(this.cancelled||t!==this.generation)return;const r=WS(KS().websocket("/api/stt/ws",void 0,n));r.binaryType="arraybuffer",this.socket=r;let s=!1;r.onopen=()=>{s=!0,!(this.socket!==r||this.cancelled)&&r.send(JSON.stringify({version:1,type:"start",recordingId:this.recordingId,providerConfigId:this.providerConfigId}))},r.onmessage=o=>{if(typeof o.data!="string"||this.socket!==r)return;let i;try{i=JSON.parse(o.data)}catch{return}if(!(i.recordingId&&i.recordingId!==this.recordingId))if(i.type==="started"){this.failures=0,this.socketStarted=!0;const a=Number.isInteger(i.ackSequence)?i.ackSequence:-1;for(let l=a+1;l<this.chunks.length;l+=1)r.send(xv(l,this.chunks[l]));this.finishing?this.sendFinish():this.onState("recording")}else if(i.type==="transcribing")this.onState("transcribing");else if(i.type==="final"){const a=String(i.text??"").trim();this.resolveFinish?.(a),this.resolveFinish=null,this.rejectFinish=null,this.clearAudio(),this.cancelled=!0,this.closeSocket()}else i.type==="error"&&this.fail(Object.assign(new Error(i.message||"Transcription failed"),{code:i.code}))},r.onerror=()=>{},r.onclose=()=>{this.socket===r&&(this.socket=null,this.socketStarted=!1,s||GS(n),this.cancelled||this.scheduleReconnect())}}catch(n){!this.cancelled&&t===this.generation&&(this.socket=null,this.scheduleReconnect(n instanceof Error?n:new Error(String(n))))}}sendFinish(){!this.socketStarted||this.socket?.readyState!==ah||this.socket.send(JSON.stringify({version:1,type:"finish",recordingId:this.recordingId,finalSequence:this.chunks.length-1}))}scheduleReconnect(t){this.failures+=1,this.onState(this.finishing?"transcribing":"reconnecting");const r=typeof document<"u"&&(document.visibilityState==="hidden"||navigator.onLine===!1)?3e4:Math.min(1e4,300*2**Math.min(this.failures,5));if(this.failures>=8){this.fail(t??new Error("Could not reconnect to the transcription server"));return}this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},r)}fail(t){this.cancelled||(this.cancelled=!0,this.onError(t),this.rejectFinish?.(t),this.resolveFinish=null,this.rejectFinish=null,this.closeSocket(),this.clearAudio())}closeSocket(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null;const t=this.socket;if(this.socket=null,this.socketStarted=!1,t){t.onclose=null,t.onmessage=null;try{t.close()}catch{}}}clearAudio(){this.chunks=[],this.audioBytes=0}}function uV(){const[e,t]=p.useState("idle"),[n,r]=p.useState(null),[s,o]=p.useState(!1),[i,a]=p.useState(0),l=p.useRef(null),d=p.useRef(null),f=p.useRef("local"),u=p.useRef(0),h=p.useRef(0),m=p.useCallback(async()=>{const v=await rV();f.current=v.config?.providerConfigId||"local",o(v.config?.enabled===!0&&aV())},[]);p.useEffect(()=>(m().catch(()=>{}),en(()=>{h.current+=1,d.current?.cancel(),l.current?.stop(),d.current=null,l.current=null,t("idle"),r(null),o(!1),m().catch(()=>{})})),[m]),p.useEffect(()=>{if(!u.current||e!=="recording"&&e!=="reconnecting")return;const v=()=>a(Math.min(300,Math.floor((Date.now()-u.current)/1e3)));v();const C=window.setInterval(v,250);return()=>window.clearInterval(C)},[e]);const g=p.useCallback(v=>{r(v.message),t("error"),l.current?.stop(),l.current=null},[]),x=p.useCallback(async()=>{if(!s||e==="requesting-permission"||e==="recording"||e==="reconnecting"||e==="transcribing")return;r(null),a(0),t("requesting-permission");const v=++h.current,C=new dV(f.current,M=>{h.current===v&&t(M)},M=>{h.current===v&&g(M)}),w=new iV({onChunk:M=>C.append(M),onPermissionGranted:()=>{h.current===v&&(u.current=Date.now(),t("recording"))}});d.current=C,l.current=w;try{await w.start(),C.begin()}catch(M){if(C.cancel(),await w.stop().catch(()=>{}),h.current!==v)return;d.current=null,l.current=null,u.current=0;const j=M instanceof Error?M:new Error(String(M));throw r(j.name==="NotAllowedError"?"Microphone access was denied":j.message),t("error"),j}},[s,e,g]),b=p.useCallback(async()=>{const v=d.current,C=l.current;if(!v||!C)throw new Error("No dictation recording is active");const w=h.current;t("transcribing");try{if(await C.stop(),h.current!==w||d.current!==v)throw new Error("Dictation cancelled");l.current=null;const M=await v.finish();if(h.current!==w)throw new Error("Dictation cancelled");return d.current=null,u.current=0,t("idle"),r(null),M}catch(M){const j=M instanceof Error?M:new Error(String(M));throw h.current===w&&(r(j.message),t("error")),j}},[]),S=p.useCallback(()=>{h.current+=1,d.current?.cancel(),d.current=null,l.current?.stop(),l.current=null,u.current=0,a(0),r(null),t("idle")},[]);p.useEffect(()=>S,[S]);const y=p.useCallback(v=>l.current?.subscribeLevel(v)??(()=>{}),[]);return{state:e,error:n,available:s,elapsedSeconds:i,start:x,finish:b,cancel:S,subscribeLevel:y}}const fV=Rs(()=>mt(()=>import("./GitHubLinkPicker-BjJNQ7Ap.js"),__vite__mapDeps([58,5,1,6,59,17,11,8,18,19,20,60,23,61,43,42])).then(e=>({default:e.GitHubLinkPicker}))),hV=Rs(()=>mt(()=>import("./ToolOutputDialog-QC8IoeBH.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),pV=5,mV=16,gV=4,yV=560,bv=p.memo(YP),vV=p.memo(M3),xV=e=>{const t=pe.getState(),n=t.newSessionDraft?.open?t.newSessionDraft.directoryOverride:null,r=e?t.getDirectoryForSession(e)??t.currentSessionDirectory:n??nt.getState().currentDirectory;return Go(Y(),r,e)},C4=({onOpenSettings:e,scrollToBottom:t})=>{const n=p.useRef(null),r=p.useRef(null),s=p.useRef({text:"",confirmedMentions:new Set}),[o,i]=p.useState(()=>{const V=pe.getState().currentSessionId,ae=xV(V),Te=Ud(ae);return r.current=ae,s.current=Te,Te.text&&(n.current=Te.text),Te.text}),a=p.useRef(s.current.confirmedMentions),[l,d]=p.useState("normal"),[f,u]=p.useState(!1);p.useEffect(()=>{l==="normal"&&u(!1)},[l]);const[h,m]=p.useState(null),[g,x]=p.useState(""),[b,S]=p.useState(null),y=p.useCallback(()=>m(null),[]);p.useEffect(()=>{h!=="command"&&S(V=>V===null?V:null)},[h]);const v=h==="command"?b?.listboxId:void 0,C=!!v,[w,M]=p.useState(null),[j,T]=p.useState(null),[A,_]=p.useState(""),k=p.useRef(null),E=p.useRef(oF()).current;p.useEffect(()=>()=>{E.view?.destroy(),E.view=null},[E]);const I=p.useRef(null),N=p.useRef(0),O=p.useRef(null),L=p.useRef(!1),D=p.useRef(null),W=p.useRef(!1),z=p.useRef(null),J=p.useRef(null),B=p.useRef(null),U=p.useRef(o),P=p.useRef(r.current),q=p.useRef((...V)=>Promise.resolve(pe.getState().sendMessage(...V))).current,F=pe(V=>V.currentSessionId),ee=b4(F);p.useEffect(()=>{ee&&y()},[ee,y]);const K=ze(V=>F?V.sessionLoadErrorById.get(F)?.code??null:null,void 0,F?`session:${F}`:"chrome")==="SESSION_IN_USE",se=ze(V=>{if(!F)return;const ae=V.reducer.bySession.get(F);if(!ae)return;const Te=ae.extensionEditorOps??(ae.extensionEditor?[ae.extensionEditor]:void 0);if(!(!Te||Te.length===0))return{sessionId:F,ops:Te}},(V,ae)=>V===ae?!0:!V||!ae||V.sessionId!==ae.sessionId||V.ops.length!==ae.ops.length?!1:V.ops.every((Te,Ve)=>Te.sequence===ae.ops[Ve]?.sequence&&Te.text===ae.ops[Ve]?.text&&Te.mode===ae.ops[Ve]?.mode),F?`session:${F}`:"chrome"),ce=p.useRef(new Map);p.useEffect(()=>{if(!F||!se||se.sessionId!==F)return;const{ops:V}=se;if(!V||V.length===0)return;const ae=ce.current.get(F)??-1,Te=V.filter(Le=>Le.sequence>ae);if(Te.length===0)return;let Ve=ae;for(const Le of Te)Le.sequence>Ve&&(Ve=Le.sequence);let $e=-1;for(let Le=Te.length-1;Le>=0;Le--)if(Te[Le]?.mode!=="paste"){$e=Le;break}if($e!==-1){const Le=Te[$e],Je=Te.slice($e+1).map(hn=>hn.text).join(""),gt=Le.text+Je;a.current.clear(),i(gt),y()}else for(const Le of Te){const Je=k.current;Je?(Je.insertText(Le.text),Je.focus({preventScroll:!0})):i(gt=>gt+Le.text)}ce.current.set(F,Ve),Ue().consumeExtensionEditor(F,Ve)},[y,F,se]);const re=nt(V=>V.currentDirectory),fe=Qn()??re,ge=pe(p.useCallback(V=>F?V.getDirectoryForSession(F):null,[F])),we=Y();RR({sessionId:F,directory:ge??fe,text:o}),p.useEffect(()=>(Jl(),Dr.getState().loadSkills(),en(()=>{Jl(),Dr.getState().loadSkills()})),[fe]);const Me=p.useMemo(()=>Go(we,ge??fe,F),[we,fe,ge,F]),He=pe(V=>V.newSessionDraft),Ae=!!He?.open,Ge=pe(V=>V.sendingNewSessionDraftId),et=uw(He,F,Ge);pe(V=>V.openNewSessionDraft);const Xe=pe(V=>V.abortPromptSessionId),oe=pe(V=>V.clearAbortPrompt),Q=Ye(V=>V.attachedFiles),ue=Ye(V=>V.addAttachedFile),be=Ye(V=>V.detachAttachedFiles),Ie=Ye(V=>V.consumePendingInputText),Fe=Ye(V=>V.pendingStarterInsert),ht=Ye(V=>V.pendingInputText),ye=Ye(V=>V.pendingRevertText),Ze=Ye(V=>V.consumePendingRevertText),Be=Ye(V=>V.consumePendingSyntheticParts),ie=pe(V=>V.acknowledgeSessionAbort),ke=p.useCallback(V=>Dm(V??F??""),[F]),ve=We(V=>V.currentProviderId),xe=We(V=>V.currentModelId),_e=We(V=>V.getModelMetadata);We(V=>V.modelsMetadata),We(V=>V.providers);const le=ve&&xe?_e(ve,xe):void 0,X=We(V=>V.currentVariant),ne=te(V=>V.isMobile),he=uV(),De=p.useRef({start:0,end:0}),qe=p.useRef(null),st=he.state==="requesting-permission"||he.state==="recording"||he.state==="reconnecting"||he.state==="transcribing",Ke=gu()==="mini-chat",Et=xE(),{enabled:fn}=nu(),Sn=ne&&!fn,Os=te(V=>V.setImagePreviewOpen),Hs=te(V=>V.inputBarOffset),Hn=te(V=>V.isExpandedInput),za=te(V=>V.setExpandedInput),Ht=te(V=>V.setTimelineDialogOpen),{git:tn}=Da(),{currentTheme:Zr}=Jn(),Xo=Z3(),Jo=pu(fe),yr=bt(V=>fe?V.directories.get(fe)?.status??null:null),Ua=bt(V=>V.ensureStatus),qa=bt(V=>V.fetchStatus),Wa=bt(V=>V.clearDiffCache),[Fn,Yr]=p.useState(!1),Bn=p.useRef(async()=>{}),Rt=$F({activeRuntimeKey:we,intent:He?.branchIntent,onReady:V=>{Bn.current(V)}}),vr=zF({taskId:He?.id,intent:He?.worktreeIntent}),[Vt,Xr]=p.useState(!1),[Qo,Jr]=p.useState({open:!1,title:"",content:""}),[Ka,Cu]=p.useState(!1);p.useEffect(()=>{Qo.open&&Cu(!0)},[Qo.open]);const Fs=p.useRef({modelKey:`${ve??""}/${xe??""}`,modalitySignature:le?.modalities?.input?.slice().sort().join(",")??null,attachmentIds:new Set});p.useEffect(()=>{const V=`${ve??""}/${xe??""}`,ae=le?.modalities?.input,Te=ae?.slice().sort().join(",")??null,Ve=Fs.current,$e=Ve.modelKey!==V,Le=Ve.modalitySignature===null&&Te!==null,Je=$e||Le?Q:Q.filter(ut=>!Ve.attachmentIds.has(ut.id));if(Fs.current={modelKey:V,modalitySignature:Te,attachmentIds:new Set(Q.map(ut=>ut.id))},!ae||Je.length===0)return;const gt=IM(Je,ae);if(gt.length===0)return;const hn=Array.from(new Set(gt.map(({modality:ut})=>ut))),pn={text:"Text",image:"Image",pdf:"PDF",audio:"Audio",video:"Video"},Us=gt.map(({attachment:ut})=>ut.filename),Pu=Us.length>3?`${Us.slice(0,3).join(", ")} (+${Us.length-3})`:Us.join(", ");Ce.warning(`${le.name??xe??""} does not support ${hn.map(ut=>pn[ut]).join(", ")} input required by ${Pu}. You can still send the message, but these attachments may be ignored.`,{id:`attachment-modalities:${V}`})},[Q,xe,le,ve]);const ku=p.useCallback(V=>{V.image&&(Jr(V),Os(!0))},[Os]),Mu=p.useCallback(V=>{Jr(ae=>({...ae,open:V})),Os(V)},[Os]);p.useEffect(()=>{!fe||!tn||Ua(fe,tn)},[fe,tn,Ua]),p.useEffect(()=>{if(!(!fe||!tn))return hu.onGitRefreshHint(V=>{Yt(V.directory)===Yt(fe)&&(V.paths?.length&&Wa(fe,V.paths),qa(fe,tn,{silent:!0}))})},[Wa,fe,tn,qa]);const er=!1,Qr=Hn&&ne,nn=Qr,[Q1,ei]=p.useState(1),Vn=!ne&&!Ke,Ga=!!(Ae&&Vn&&!nn),xr=!ne&&!nn&&!Vn,Bs=ne||Vn?"1.5rem":"9999px",Za=ne||Vt;p.useEffect(()=>{const V=O.current;if(!V)return;const ae=Ve=>{const $e=Ve>0&&Ve<yV;Xr(Le=>Le===$e?Le:$e)};if(ae(V.clientWidth),typeof ResizeObserver>"u"){const Ve=()=>ae(V.clientWidth);return window.addEventListener("resize",Ve),()=>window.removeEventListener("resize",Ve)}const Te=new ResizeObserver(Ve=>{ae(Ve[0]?.contentRect.width??V.clientWidth)});return Te.observe(V),()=>Te.disconnect()},[]);const Ya=p.useMemo(()=>new Set,[]),{commands:Xa}=Y3(fe),Ja=p.useMemo(()=>{const V=new Set;for(const ae of Xa)V.add(ae.invocationName.toLowerCase());return V},[Xa]),Qa=Pr(V=>V.snippets),ec=Pr(V=>V.loadSnippets);p.useEffect(()=>{ec(fe)},[fe,ec]);const tc=p.useMemo(()=>{const V=new Set;for(const ae of Qa){V.add(ae.name.toLowerCase());for(const Te of ae.aliases??[])V.add(Te.toLowerCase())}return V},[Qa]),nc=p.useMemo(()=>Q.map(V=>V.filename),[Q]),Z=p.useMemo(()=>({inputMode:l,knownAgentNames:Ya,confirmedMentions:a.current,knownSlashNames:Ja,knownSnippetTriggers:tc,attachmentFilenames:nc}),[nc,l,Ya,Ja,tc]),me=p.useCallback(V=>[...V??[]].map(ae=>({...ae,dataUrl:ae.source==="server"&&ae.serverPath?LN(ae.serverPath):ae.dataUrl})),[]),Re=p.useCallback(V=>({sanitizedText:V,attachments:[]}),[]),Ne=p.useRef(null),ct=p.useRef(!1),ot=F?em(F,ge??fe):null,dt=ft(V=>V.followUpBehavior),Oe=ft(V=>V.addToQueue),Qe=EF(PE(F??""));p.useEffect(()=>{U.current=o},[o]),p.useEffect(()=>{P.current=Me},[Me]);const{persistNow:kt}=_F({message:o,messageRef:U,setMessage:i,confirmedMentionsRef:a,identity:Me,persistEnabled:!0,initialDraft:{text:n.current??"",identity:r.current},onIdentityChange:()=>d("normal"),onDraftRestored:()=>k.current?.selectAll()});p.useEffect(()=>{const V=Me?Jt(Me):"";Ye.getState().activateAttachmentsDraft(V)},[Me]);const jt=Ye(V=>V.sentDraftClear);p.useEffect(()=>{if(!jt)return;const V=Me?Jt(Me):"";if(!V||jt.draftKey!==V)return;Ye.getState().consumeSentDraftClear(jt.nonce);const ae=k.current?.getValue()??U.current;eI(jt,V,ae)&&(a.current.clear(),Qe.reset(),i(""))},[jt,Me,Qe]);const Cn=p.useRef(Ae);p.useEffect(()=>{!Cn.current&&Ae&&requestAnimationFrame(()=>{ne?k.current?.focus({preventScroll:!0}):k.current?.focus()}),Cn.current=Ae},[Ae,ne]);const{phase:rn}=Gm();p.useEffect(()=>{if(ht!==null){const V=Ie();V?.text&&(V.mode==="append"?i(ae=>{const Te=V.text;return Te.trim()?iF(ae,Te):ae}):V.mode==="append-inline"?i(ae=>i4(ae,V.text)):i(V.text),setTimeout(()=>{k.current?.focus()},0))}},[ht,Ie]),p.useEffect(()=>{if(ye!==null){const V=Ze();V&&o.trim().length===0&&(i(V),setTimeout(()=>{k.current?.focus()},0))}},[ye,Ze,o]);const Vs=Ye(V=>V.pendingWorktreeRestore),$s=Ye(V=>V.consumePendingWorktreeRestore);p.useEffect(()=>{if(Vs===null)return;const V=$s();if(!V)return;const ae=MA(V,U.current??"");if(ae.ok)a.current=new Set(V.confirmedMentions),U.current=V.prompt,i(V.prompt),y(),setTimeout(()=>{k.current?.focus()},0);else{const Te=kA(ae,"pending-composer");Te&&Ce.error(Te.title,{description:Te.description})}},[Vs,$s,y]);const tr=o.trim().length>0||Q.length>0,ti=!!(ve&&xe),br=Uf(Q),wr=D3(),h9=(wr?"Connection lost. Waiting to reconnect — your draft is kept.":null)??(Q2(Q)?"Uploading attachments…":QL(Q)||Q.length>0&&!br?"Retry or remove failed attachments":null),p9=tr&&ti&&br&&!wr,$n=!!(vr.state&&vr.state.phase!=="failed")||et||K,zs=!F&&!Ae||$n,rc=Jd(F??""),m9=rn!=="idle"&&!rc,ni=p.useCallback(()=>{const V=k.current?.getValue()??o;return{message:V,hasContent:V.trim().length>0||Q.length>0}},[Q.length,o]),ri=p.useRef(!1),sc=p.useCallback(async()=>{if(yd()){Ce.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const V=ni();if(ri.current||!V.hasContent||!F||!ot||!Uf(Q))return;ri.current=!0;let ae;try{ae=await Ob(me(Q))}catch{Ce.error("Attachment data could not be saved for the follow-up."),ri.current=!1;return}const Te=V.message.replace(/^\n+|\n+$/g,""),Ve=F?At.getState().getSessionAgentSelection(F)??void 0:void 0;if(!Oe(ot,{content:Te,attachments:ae.length>0?ae:void 0,sendConfig:ve&&xe?{providerID:ve,modelID:xe,agent:Ve,variant:X??void 0}:void 0})){ri.current=!1,Ce.error("Follow-up limit reached. Remove a pending message before adding another.");return}(k.current?.getValue()??U.current)===V.message&&i(""),ae.length>0&&be(ae.map(Le=>Le.id)),ri.current=!1,ne||k.current?.focus()},[ni,F,ot,Q,me,Oe,be,ne,ve,xe,X]),g9=p.useCallback(V=>{i(V),setTimeout(()=>{k.current?.focus()},0)},[]),y9=p.useCallback(V=>{Bn.current({queuedOnly:!0,queuedMessageId:V,delivery:"steer"})},[]),v9=(V,ae)=>{const Te=V instanceof Error?V.message:"";return Te.toLowerCase().includes("runtime changed")?"Message failed to send. Attachments restored.":Te||ae},eg=async V=>{if(yd()){Ce.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const ae=V?.queuedOnly??!1,Te=V?.queuedMessageId,Ve=V?.delivery==="steer"?"steer":void 0,$e=ot;let Le=null;if(!(ae&&(!$e||!Te||(Le=ft.getState().claimQueuedMessage($e,Te),!Le)))){try{if(!ae&&!Uf(Q)){Q2(Q)?Ce.info("Uploading attachments…"):Ce.error("Retry or remove failed attachments");return}const Je=V?.presetText!=null&&!ae?{message:V.presetText,hasContent:V.presetText.trim().length>0||Q.length>0}:ae?{message:"",hasContent:!1}:ni();if(!ae&&l==="shell"&&Q.length>0){Ce.error("Remove attachments to run a shell command.");return}if(ae){if(!F)return}else if(!Je.hasContent||!F&&!Ae)return;const gt=ae?Le?.sendConfig:void 0,hn=gt?.providerID??ve,pn=gt?.modelID??xe,Us=gt?.agent,Pu=ae?gt?.variant:X;if(!hn||!pn){console.warn("Cannot send message: provider or model not selected"),Ce.error("Select a provider and model before sending a message.");return}const ut=pe.getState().newSessionDraft,lc=!$e&&!ae&&!Te&&ut?.open===!0,dc=()=>pe.getState().newSessionDraft.id===ut.id&&pe.getState().currentSessionId===null,Du=(l==="normal"?Yy(Je.message):null)?.name==="compact",xg=!!(lc&&ut.worktreeIntent&&!Du),ts=xg?new Set(a.current):null;let mn=null;if(lc){if(ut.id&&pe.getState().sendingNewSessionDraftId===ut.id)return;if(pe.getState().setSendingNewSessionDraftId(ut.id),xg){try{mn=await SA(Q)}catch{pe.getState().sendingNewSessionDraftId===ut.id&&pe.getState().setSendingNewSessionDraftId(null),Ce.error("Attachment data could not be saved for the worktree send.");return}U.current="",i(""),a.current.clear(),kt(Me,"")}await new Promise(ns=>{let Zt=!1;const on=()=>{Zt||(Zt=!0,ns())};typeof window<"u"&&typeof window.requestAnimationFrame=="function"&&window.requestAnimationFrame(()=>on()),setTimeout(()=>on(),50)})}try{const ns=!$e&&!V?.queuedOnly&&!V?.queuedMessageId&&ut?.open&&!Du?ut.worktreeIntent:null;let Zt=vr.getReceipt(ns);if(ns&&!Zt){const rt=vr.request({intent:ns,prompt:Je.message,failedSend:{prompt:Je.message,confirmedMentions:ts?[...ts]:[],attachments:mn??[]}});if(mn&&mn.length>0&&be(mn.map(It=>It.id)),Ce.info("Worktree queued",ut.id?{id:`worktree-queued:${ut.id}`}:void 0),pe.getState().openNewSessionDraft(),te.getState().setActiveMainTab("chat"),Zt=await rt,!Zt){if((ut.id?ln.getState().getEntryByKey(ut.id):ln.getState().getEntry(ns))?.failedSend){Ce.error("Worktree creation failed",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}if(dc()){if(U.current=Je.message,a.current=ts??new Set,i(Je.message),js(Me,Je.message,ts??[]),mn){const St=Ye.getState().restoreAttachmentsForRetry(mn);if(!St.ok){const kn=hp({limit:St.limit,currentCount:St.currentCount,missingCount:St.missingCount});Ce.error(kn.title,{description:kn.description})}}}else Ce.error("Worktree creation failed",{description:"Your prompt was not sent."});return}}const on=Zt?ut.id??Ow(ns):null,Sr=on?ln.getState().getEntryByKey(on)?.failedSend??null:null,uc=!$e&&!V?.queuedOnly&&!V?.queuedMessageId&&ut?.open&&!Du?ut.branchIntent:null;if(uc&&!Rt.getReceipt(uc)){if(Rt.dialogState)return;await Rt.request({intent:uc,projectId:ut.selectedProjectId,continuation:V});return}const Ou=Rt.getReceipt(uc),bg=ae&&$e&&Le?{target:$e,delivery:"steer",operationId:Le.id}:$e?{target:$e,...Ve?{delivery:Ve}:{}}:Ve||Ou||Zt?{...Ve?{delivery:Ve}:{},...Ou?{branchCheckoutReceipt:Ou}:{},...Zt?{worktreeCreationReceipt:Zt,draftSnapshot:ut}:{}}:void 0,wg=Be(),U9=new Set(Dr.getState().skills.map(rt=>rt.name)),Hu=wF(ae&&Le?{queued:[{content:Le.content,attachments:Le.attachments}],composerText:null,composerAttachments:[],syntheticTexts:wg?.map(rt=>rt.text)??[]}:{queued:[],composerText:Je.hasContent?Je.message:null,composerAttachments:CA(mn,Q),syntheticTexts:wg?.map(rt=>rt.text)??[]},{parseAgentMention:rt=>({text:rt}),extractFileMentions:rt=>{const{sanitizedText:It,attachments:St}=Re(rt);return{text:It,attachments:St}},sanitizeAttachments:me,collectSkillNames:rt=>xF(rt,U9),buildSkillInstruction:bF});let fc=Hu.primaryText;const{primaryAttachments:Sg,additionalParts:oi}=Hu;if(Hu.isEmpty){!ae&&on&&Sr&&Zt&&EA(on,Sr,"Prompt was empty and was not sent.")&&Ce.error("Prompt was empty and was not sent.",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const hc=()=>!Zt||dc();!ae&&hc()&&(Qe.reset(),za(!1)),ne&&hc()&&k.current?.blur();const pc=l==="normal"?Yy(fc):null;if(pc&&await CF({command:pc,currentSessionId:F,scrollToBottom:t,setTimelineDialogOpen:Ht,onUndoSession:async It=>{await pe.getState().handleSlashUndo(It)},onRedoSession:async It=>{await pe.getState().handleSlashRedo(It)},onCompactSession:async(It,St)=>{try{await nj(),await rj(It,St)}catch(kn){Ce.error(v9(kn,"Failed to compact session"))}}})){!ae&&on&&Sr&&Zt&&jA(on,Sr,mn,Q),hc()&&(kt(Me,""),i(""),a.current.clear());return}let ii=!!(lc&&pc&&!c4(pc.name))?{...bg,initialInputKind:"extension-command"}:bg;const Cg=$e?.directory??fe,kg=await $O({newSessionDraftOpen:Ae,sessionId:$e?.sessionId??F,getStoreState:()=>Ue().getState()});if(kg&&oi.push({text:zO(kg),synthetic:!0}),l!=="shell")try{const rt=Pr.getState().expandText;fc=rt(fc,Cg);for(const It of oi)It.synthetic||(It.text=rt(It.text,Cg))}catch(rt){console.warn("[ChatInput] Failed to expand snippets, sending original text:",rt)}const q9=[...Sg,...oi.flatMap(rt=>rt.attachments??[])],Mg=Hw(mn,Q);if(ae&&$e&&Le){const rt=ft.getState().markDeliveryAttempt($e,Le.id,"steer");if(!rt?.streamEpoch){ft.getState().markSendUnconfirmed($e,Le.id,"steer"),Ce.error("Follow-up status uncertain. Check status before retrying.");return}ii={...ii,streamEpoch:rt.streamEpoch}}!ae&&l==="shell"&&(ii={...ii,...f?{shellExcludeFromContext:!0}:{}});const W9=q(fc,hn,pn,Us,Sg,void 0,oi.length>0?oi:void 0,Pu,l,ii);Rt.clearReceipt(),typeof window>"u"?t?.():window.requestAnimationFrame(()=>{t?.()}),await W9.then(()=>{if(ae&&$e&&Le&&ft.getState().completeQueuedSend($e,Le.id),!ae&&on&&Sr&&ln.getState().markWorktreePromptSucceeded(on,Sr),!ae&&Mg.length>0&&be(Mg),!ae&&hc()){const rt=Me?Jt(Me):"",It=P.current,St=It?Jt(It):"",kn=k.current?.getValue()??U.current,mc=!kn||kn===Je.message;rt===St?(kt(Me,mc?"":kn),mc&&(i(""),a.current.clear(),Qe.reset()),Ye.getState().publishSentDraftClear(rt,Je.message)):kt(Me,"")}}).catch(rt=>{if(ae&&$e&&Le){if(Jw(rt)){ft.getState().markSendUnconfirmed($e,Le.id,"steer"),console.warn("Follow-up send unconfirmed:",rt),Ce.error("Follow-up status uncertain. Check status before retrying.");return}ft.getState().markSendFailed($e,Le.id)}const It=rt instanceof Error?rt.message:typeof rt=="string"?rt:String(rt??""),St=It.toLowerCase();if(console.error("Message send failed:",It||rt),!ae&&on&&Sr&&Zt){const qs=It||"Prompt failed to send.";ln.getState().markWorktreePromptFailed(on,Sr,qs),Ce.error("Prompt failed to send",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const kn=k.current?.getValue()??U.current;if(dc()&&Je.message&&(!kn||kn===Je.message)&&(ts&&(a.current=ts),i(Je.message),js(Me,Je.message,ts??a.current)),dc()&&mn){const qs=Ye.getState().restoreAttachmentsForRetry(mn);if(!qs.ok){const Ig=hp({limit:qs.limit,currentCount:qs.currentCount,missingCount:qs.missingCount});Ce.error(Ig.title,{description:Ig.description})}}const mc=St.includes("timeout")||St.includes("timed out")||St.includes("may still be processing")||St.includes("being processed")||St.includes("failed to fetch")||St.includes("networkerror")||St.includes("network error")||St.includes("gateway timeout")||St==="failed to send message";if(St.includes("payload too large")||St.includes("413")||St.includes("entity too large")){Ce.error("Attachments are too large to send. Please try reducing the number or size of images.");return}if(mc){q9.length>0&&Ce.error("Failed to send attachments. Try fewer files or smaller images.");return}if(St.includes("runtime changed")){Ce.error("Message failed to send. Attachments remain available.");return}Ce.error(It||"Message failed to send. Attachments remain available.")})}finally{lc&&pe.getState().sendingNewSessionDraftId===ut.id&&pe.getState().setSendingNewSessionDraftId(null)}}finally{ae&&$e&&Le&&ft.getState().clearSending($e,Le.id)}ne||k.current?.focus()}};Bn.current=eg;const tg=p.useCallback(()=>{const V=ni(),ae=l==="normal"&&V.hasContent&&F&&rn!=="idle";(dt==="queue"||rc)&&ae?sc():dt==="steer"&&ae?Bn.current({delivery:"steer"}):Bn.current()},[l,ni,F,rn,rc,dt,sc]),sn=p.useCallback((V,ae,Te="manual",Ve)=>{const $e=nH(V,ae,{inputMode:l,inputSource:Te,insertedText:Ve});m($e?.kind??null),x($e?.query??"")},[l]),oc=p.useCallback(V=>{const ae=()=>{try{k.current?.focus({preventScroll:!0})}catch{k.current?.focus()}k.current?.setSelection(V)};requestAnimationFrame(()=>{ae(),requestAnimationFrame(ae)}),setTimeout(ae,60)},[]),Iu=p.useCallback(V=>{const ae=V.trim();if(!ae)return;const Te=`/${ae} `,Ve=k.current,$e=Ve?.getValue()??U.current??"",Le=$e.trim().length>0?`${Te}${$e.replace(/^\s+/,"")}`:Te,Je=Te.length;if(Ve)try{Ve.replaceRange(0,$e.length,Le,Je)}catch{i(Le),requestAnimationFrame(()=>Ve.setSelection(Je))}else i(Le);sn(Le,Je,"manual",Te),y(),oc(Je)},[y,oc,i,sn]),Eu=p.useCallback(V=>{const ae=V.trim();if(!ae)return;const Te=k.current,Ve=Te?.getValue()??U.current??"",$e=Ve.trim().length>0,Le=$e?`${ae} ${Ve.replace(/^\s+/,"")}`:ae,Je=$e?ae.length+1:ae.length;if(Te)try{Te.replaceRange(0,Ve.length,Le,Je)}catch{i(Le),requestAnimationFrame(()=>Te.setSelection(Je))}else i(Le);sn(Le,Je,"manual"),y(),oc(Je)},[y,oc,i,sn]);p.useEffect(()=>{if(Fe==null)return;const V=Ye.getState().consumePendingStarterInsert();V&&("text"in V?Eu(V.text):Iu(V.name))},[Fe,Iu,Eu]);const x9=DF({inputMode:l,setInputMode:d,shellExcludeFromContext:f,setShellExcludeFromContext:u,message:o,setMessage:i,openAutocomplete:h,commandRef:J,snippetRef:B,mentionRef:z,composerRef:k,messageHistory:Qe,updateAutocompleteState:sn,isMobile:ne,hasContent:tr,currentSessionId:F,sessionPhase:rn,commandRunning:!!rc,followUpBehavior:dt,handleSubmit:eg,handleQueueMessage:sc}),{update:b9}=kF({enabled:er,openAutocomplete:h,message:o,editorRef:k,containerRef:O}),ic=p.useCallback(()=>{Ne.current&&(clearTimeout(Ne.current),Ne.current=null),Yr(!0),Ne.current=setTimeout(()=>{Yr(!1),Ne.current=null},1800)},[]),w9=p.useCallback(()=>{oe(),ic(),ke(F||void 0)},[ke,oe,F,ic]),S9=p.useCallback((V,ae="manual")=>{if(!V)return;const Te=k.current;if(!Te){const gt=o+V;i(gt),sn(gt,gt.length,ae,V);return}const{start:Ve,end:$e}=Te.getSelection(),Le=`${o.substring(0,Ve)}${V}${o.substring($e)}`,Je=Ve+V.length;Te.insertText(V),sn(Le,Je,ae,V)},[o,sn]),C9=p.useCallback(()=>{const V=U.current.length;De.current=k.current?.getSelection()??{start:V,end:V},y(),he.start().catch(()=>{})},[y,he]),k9=p.useCallback(()=>{he.finish().then(V=>{const ae=U.current,Te=De.current,Ve=Math.min(Math.max(0,Te.start),ae.length),$e=Math.min(Math.max(Ve,Te.end),ae.length),Le=a4(V.trim(),ae.slice(0,Ve),ae.slice($e));if(!Le)return;const Je=k.current;if(Je)Je.replaceRange(Ve,$e,Le,Ve+Le.length),Je.focus({preventScroll:!0});else{const gt=`${ae.slice(0,Ve)}${Le}${ae.slice($e)}`;i(gt),sn(gt,Ve+Le.length,"manual",Le)}}).catch(()=>{})},[he,sn]);p.useEffect(()=>{he.state!=="error"||!he.error||qe.current===he.error||(qe.current=he.error,Ce.error(he.error))},[he.error,he.state]);const ju=p.useCallback(()=>{L.current=!1,D.current&&(clearTimeout(D.current),D.current=null)},[]),M9=p.useCallback(()=>{L.current=!0,D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{L.current=!1,D.current=null},700)},[]),I9=({value:V,selection:ae,fromPaste:Te,insertedText:Ve})=>{const $e=Te?Ve:"",Le=$e.includes("@")||L.current;L.current&&ju();const Je=Le?"paste":"manual";if(l==="shell"&&!f&&V.startsWith("!")){const gt=V.slice(1),hn=Math.max(0,ae.start-1);u(!0),i(gt);const pn=k.current;pn&&pn.getValue()!==gt?pn.replaceRange(0,1,"",hn):requestAnimationFrame(()=>k.current?.setSelection(hn));return}if(l==="normal"&&V.startsWith("!")){const gt=V.slice(1),hn=Math.max(0,ae.start-1);d("shell"),i(gt),y();const pn=k.current;pn&&pn.getValue()!==gt?(pn.replaceRange(0,1,"",hn),y()):requestAnimationFrame(()=>k.current?.setSelection(hn));return}i(V),sn(V,ae.start,Je,$e)};p.useEffect(()=>()=>{ju()},[ju]);const E9=vF({inputMode:l,enabled:!!(F||Ae),composerRef:k,message:o,setMessage:i,insertTextAtSelection:S9,updateAutocompleteState:sn,markFileMentionPasteSuppression:M9,attachedFiles:Q,addAttachedFile:ue}),j9=p.useCallback(V=>DN(V,Xo||""),[Xo]),{handleFileSelect:_9,handleSnippetSelect:T9,handleCommandSelect:A9}=AF({composerRef:k,message:o,setMessage:i,updateAutocompleteState:sn,closeAutocomplete:y,confirmedMentionsRef:a,toMentionPath:j9});p.useEffect(()=>{F&&k.current&&!ne&&k.current.focus()},[F,ne]),p.useEffect(()=>{ne||M(null)},[ne]),p.useEffect(()=>{Xe&&Xe!==F&&oe()},[Xe,F,oe]),p.useEffect(()=>{W.current=!!(F||Ae)},[F,Ae]);const{isDragging:N9,isInternalDrag:L9,handleDragEnter:ng,handleDragOver:rg,handleDragLeave:R9,handleDragEnd:sg,handleDrop:og,handleDropCapture:ig}=pF({enabled:!!(F||Ae),composerRef:k,messageRef:U,cursorPosRef:N,confirmedMentionsRef:a,setMessage:i,addAttachedFile:ue}),ag=p.useRef(null),cg=p.useCallback(async V=>{const ae=Array.isArray(V)?V:Array.from(V),Te=await Promise.all(ae.map(async Ve=>{try{return await ue(Ve)}catch($e){return console.error("File attach failed",$e),!1}}));ae.length>0&&!Te.some(Boolean)&&Ce.error("Failed to attach file")},[ue]),lg=p.useCallback(()=>{zs||ag.current?.click()},[zs]),[dg,ug]=p.useState(!1),P9=p.useCallback(()=>{zs||ug(!0)},[zs]),D9=p.useCallback(async V=>{const ae=V.target.files;ae&&(await cg(ae),V.target.value="")},[cg]),O9="gap-x-1.5 gap-y-0",H9=!0,si=(Ae||!!F)&&!Ke,{projects:fg,selectedDraftProject:es,selectedDraftBranchLabel:_u,selectedBranchName:Tu,draftBranchItems:hg,isDiscoveringDraftBranches:pg,shouldShowDraftBranchSelector:nr,worktreeMode:Au,handleDraftProjectChange:mg,handleDraftBranchChange:gg,handleWorktreeModeChange:Nu}=FF(si),yg=!!(si&&es&&(Ae||nr)),ac=p.useMemo(()=>Ke||Jo!==!0||!yr||yr.isClean?!1:N3(yr.files,yr.diffStats,fe).length>0,[fe,yr,Jo,Ke])?c.jsx(P3,{align:yg?"end":"start"}):null,Lu=UF({isMobile:ne,editorRef:k,formRef:I,controlsPanelOpen:!!w,attachMenuOpen:!1}),F9=Lu.focused;p.useEffect(()=>{_("")},[j]),qF({isMobile:ne,isFullscreen:Qr,isDraftScreen:Ae,isFocused:F9,formRef:I,editorRef:k});const B9=ne?"px-1.5 py-1.5":xr?"px-1.5 py-1":"px-3 py-2",V9=ne?"h-8 w-8":"h-6 w-6",$9="h-4 w-4",z9=ne?"h-6 w-6":"h-5 w-5",cc="h-[18px] w-[18px]",vg="flex cursor-pointer items-center justify-center text-foreground transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed",Ru=R(vg,V9);return p.useEffect(()=>{const V=!!Xe&&Xe===F;!ct.current&&V&&!Fn&&(ic(),F&&ie(F)),ct.current=V},[Xe,ie,F,Fn,ic]),p.useEffect(()=>()=>{Ne.current&&(clearTimeout(Ne.current),Ne.current=null)},[]),c.jsxs(c.Fragment,{children:[c.jsxs("form",{ref:I,onSubmit:V=>{V.preventDefault(),tg()},className:R("relative w-full pt-0 pb-4",er,Qr&&"flex h-full min-h-0 flex-col pt-2",ne&&"bottom-safe-area oc-mobile-composer"),style:ne&&Hs>0?{marginBottom:`${Hs}px`}:void 0,children:[c.jsxs("div",{className:R("chat-input-column relative overflow-visible",nn&&"flex flex-1 min-h-0 flex-col"),children:[c.jsx(y3,{onEditMessage:g9,onSendMessage:y9}),c.jsx(w4,{sessionId:F,directory:ge??fe}),c.jsx(vV,{showAbortStatus:Fn,showAssistantStatus:!1,showTodos:H9,leftAccessory:yg||Ae||!ac?null:ac}),!Sn&&si&&es&&(Ae||nr)?c.jsx("div",{inert:$n||void 0,className:R($n&&"pointer-events-none opacity-60"),children:c.jsx(gB,{projects:fg,selectedProject:es,selectedBranchName:Tu,selectedBranchLabel:_u,branchOptions:hg,branchInteractive:Ae,branchLoading:pg,showBranchSelector:nr,showProjectSelector:Ae,showWorktreeSelector:Ae&&nr,worktreeMode:Au,endAccessory:ac,onProjectChange:mg,onBranchChange:gg,onWorktreeModeChange:Nu,theme:Zr})}):null,Sn&&si&&es&&(Ae||nr)?c.jsx("div",{inert:$n||void 0,className:R($n&&"pointer-events-none opacity-60"),children:c.jsx(yB,{selectedProject:es,selectedBranchName:Tu,selectedBranchLabel:_u,branchInteractive:Ae,showBranchSelector:nr,showProjectSelector:Ae,showWorktreeSelector:Ae&&nr,worktreeMode:Au,onWorktreeModeChange:Nu,endAccessory:ac,theme:Zr,onOpenPicker:T})}):null,c.jsx("div",{className:R(!ne&&"contents",ne&&"relative",Qr&&"flex min-h-0 flex-1 flex-col"),children:c.jsx(c.Fragment,{children:c.jsxs("div",{className:R("flex flex-col relative overflow-visible",nn&&"flex-1 min-h-0",Vn&&!nn&&"min-h-[7rem]","border border-border/80","shadow-[0_4px_16px_-4px_rgb(0_0_0_/_0.12)]","focus-within:ring-1",l==="shell"?"focus-within:ring-[color:color-mix(in_srgb,var(--status-info)_45%,transparent)]":"focus-within:ring-primary/30"),style:{borderRadius:Bs,backgroundColor:Zr?.colors?.surface?.subtle},ref:O,"data-composer-card":"true",onDropCapture:ig,onDragEnter:ng,onDragOver:rg,onDragLeave:R9,onDrop:og,onDragEnd:sg,children:[N9&&c.jsx(zB,{isInternalDrag:L9,iconButtonBaseClass:vg,iconSizeClass:cc,radius:Bs,isAttachmentDisabled:zs,onPickLocalFiles:lg}),et&&c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-20 overflow-hidden",style:{borderRadius:Bs},children:c.jsx("span",{className:"attachment-upload-shimmer absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-foreground/10 to-transparent"})}),c.jsx(NB,{open:h,query:g,overlayPosition:null,commandRef:J,snippetRef:B,mentionRef:z,onCommandSelect:A9,onSnippetSelect:T9,onFileSelect:_9,onClose:y,onCommandComboboxStateChange:S}),c.jsx($B,{isMobile:ne,isInline:xr,alignToolsEnd:Q1>1,sessionId:F,directory:ge??fe,newSessionDraftOpen:Ae,messageLength:o.length,leadingExtra:Vn||ne?c.jsx(bv,{keepLabels:!0,className:"w-max shrink-0",mobilePanel:ne?w:void 0,onMobilePanelChange:ne?M:void 0}):null,trailingExtra:st?null:c.jsx(WB,{available:he.available,disabled:!F&&!Ae||$n,className:Ru,iconClassName:cc,onStart:C9}),actionsOverride:st?c.jsx(eV,{state:he.state,elapsedSeconds:he.elapsedSeconds,buttonClassName:Ru,iconClassName:cc,isMobile:ne,onCancel:he.cancel,onDone:k9}):void 0,radius:Bs,footerPaddingClass:B9,footerGapClass:O9,footerIconButtonClass:Ru,iconSizeClass:cc,sendIconSizeClass:$9,stopIconSizeClass:z9,canSend:p9&&!$n,isSending:et,isAttachmentDisabled:zs,disabledReason:h9,canAbort:m9,hasContent:!!tr,onOpenSettings:e,onPickLocalFiles:lg,onLinkGitHub:P9,onPrimaryAction:tg,onQueueMessage:sc,onAbort:w9,children:st?c.jsx(tV,{state:he.state,subscribeLevel:he.subscribeLevel}):c.jsxs("div",{className:R("overflow-hidden",nn&&"flex flex-1 min-h-0 flex-col"),children:[l==="shell"?c.jsxs("div",{className:R("typography-micro text-muted-foreground",xr?"px-1.5 pt-1":"px-3 pt-2"),"data-testid":"chat-input-shell-mode",children:[c.jsx("span",{className:"font-mono text-foreground",children:f?"!!":"!"})," ",f?"Shell command, not sent to the model":"Shell command, sent to the model",!ne||Et?c.jsx("span",{children:" · Esc to go back"}):null]}):null,c.jsx("div",{className:"relative z-10",children:c.jsx(m3,{onShowPopup:ku,isInline:xr,isMobile:ne})}),c.jsx("div",{className:R("relative overflow-hidden",nn&&"flex flex-1 min-h-0 flex-col"),onDragEnter:ng,onDragOver:rg,onDropCapture:ig,onDrop:og,onDragEnd:sg,children:c.jsx(sF,{ref:k,viewStore:E,"data-testid":"chat-input",value:o,languageContext:Z,onChange:I9,onKeyDown:V=>(x9(V),V.defaultPrevented),onPaste:E9,onSelectionChange:V=>{N.current=V.start,b9()},onVisualLineCount:V=>{ei(ae=>ae===V?ae:V)},onFocus:Lu.onEditorFocus,onBlur:Lu.onEditorBlur,placeholder:K?"Session is open elsewhere":F||Ae?l==="shell"?f?"Enter shell command...":"Enter shell command... (!! keeps it from the model)":Ga?"Plan, build, / for skills, @ for context":Za?"Use @ / ! # for helpers":"@ for files; / for commands, skills, and prompts; ! for shell; # for snippets":"Select or create a session to start chatting",editable:!!(F||Ae)&&!$n,autoCorrect:!1,autoCapitalize:"none",spellCheck:ne,fillContainer:nn,maxLines:ne?mV:pV,boundSelector:ne?"[data-composer-bound]":void 0,boundGapPx:gV,commandComboboxExpanded:C,commandComboboxListboxId:v,commandComboboxActiveOptionId:C?b?.activeOptionId:void 0,className:R("relative z-10",xr?"min-h-0 px-1.5 py-1.5":"min-h-[52px] px-3",nn?R("h-full min-h-0",ne?"py-2.5":"py-4"):ne?Q.length>0?"pt-1 pb-2.5":"py-2.5":xr?void 0:Q.length>0?"pt-1.5 pb-2":"pt-3 pb-2","typography-markdown md:typography-ui-label")})})]})})]})})}),Vn||ne?null:c.jsx("div",{className:R("mt-1.5 flex w-full shrink-0 items-center pl-2",$n&&"pointer-events-none opacity-60"),inert:$n||void 0,children:c.jsx(bv,{className:"w-full min-w-0"})})]}),Ae&&!er&&!ne&&!Ke?c.jsx(G3,{onInsert:V=>V.ref.type==="text"?Eu(V.insertText):Iu(V.promptName),className:"chat-input-column mt-3"}):null]}),Ka?c.jsx(p.Suspense,{fallback:null,children:c.jsx(hV,{popup:Qo,onOpenChange:Mu,isMobile:ne})}):null,c.jsx(qB,{inputRef:ag,onChange:D9}),c.jsx(xB,{state:Rt.dialogState,onCancel:Rt.cancel,onConfirm:()=>{Rt.confirm()}}),dg&&(ge??fe)?c.jsx(p.Suspense,{fallback:null,children:c.jsx(fV,{directory:ge??fe,open:dg,onClose:()=>ug(!1)})}):null,Sn&&si&&es?c.jsx(vB,{projects:fg,selectedProject:es,selectedBranchName:Tu,selectedBranchLabel:_u,branchOptions:hg,branchInteractive:Ae,branchLoading:pg,showBranchSelector:nr,showProjectSelector:Ae,showWorktreeSelector:Ae&&nr,worktreeMode:Au,onProjectChange:mg,onBranchChange:gg,onWorktreeModeChange:Nu,theme:Zr,openPicker:j,onOpenPickerChange:T,query:A,onQueryChange:_}):null]})};C4.displayName="ChatInput";const ki=p.memo(C4);function bV({label:e,className:t}){return c.jsx("span",{className:R("size-1.5 shrink-0 rounded-full bg-status-warning",t),"aria-label":e,title:e})}const wV=e=>e!=null&&e.count>0,QX=e=>wV(e.pendingInput)?"needs-input":e.isStreaming?"working":!e.isStreaming&&!e.isActive&&e.unseenCount>0?"unread":null,SV=(e,t)=>{const n=e==="approval"?"Needs approval":"Needs input";return t>1?`${n} (${t} requests)`:n},eJ=e=>e===1?"A session needs input":`${e} sessions need input`,CV="underline decoration-dotted underline-offset-2 hover:decoration-solid",k4=({segment:e,href:t,children:n})=>c.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:CV,style:bd(e),children:n}),qt=H.memo(({text:e,className:t,style:n,links:r=!1})=>{if(e==null||e==="")return null;if(!y4(e))return t||n?c.jsx("span",{className:t,style:n,children:e}):c.jsx(c.Fragment,{children:e});const s=v4(e);return s.length===0?null:s.length===1&&!bd(s[0])&&!(r&&s[0].href)?t||n?c.jsx("span",{className:t,style:n,children:s[0].text}):c.jsx(c.Fragment,{children:s[0].text}):c.jsx("span",{className:t,style:n,children:s.map((o,i)=>{const a=r?g4(o.href):void 0;if(a)return c.jsx(k4,{segment:o,href:a,children:o.text},i);const l=bd(o);return l?c.jsx("span",{style:l,children:o.text},i):c.jsx(H.Fragment,{children:o.text},i)})})});qt.displayName="AnsiText";const kV=(e,t,n)=>{if(n<=0)return null;switch(e){case"ArrowDown":return{kind:"highlight",index:(t+1)%n};case"ArrowUp":return{kind:"highlight",index:(t-1+n)%n};case"Home":return{kind:"highlight",index:0};case"End":return{kind:"highlight",index:n-1};case"Enter":case" ":return{kind:"submit",index:t};default:{if(e.length!==1||e<"1"||e>"9")return null;const r=Number(e)-1;return r<n?{kind:"submit",index:r}:null}}},MV=async(e,t,n)=>{try{await Ee.respondToExtensionDialog({requestId:t.requestId,...n},{runtimeKey:Y()}),Ue().dismissExtensionDialog(e,t.requestId)}catch(r){if(r instanceof lt&&r.code==="EXTENSION_DIALOG_NOT_PENDING"){Ue().dismissExtensionDialog(e,t.requestId);return}throw r}},IV=()=>{requestAnimationFrame(()=>{document.querySelector('[data-slot="composer-editor"], .chat-input-column textarea, textarea')?.focus()})},EV=(e,t)=>{const[n,r]=H.useState(()=>typeof e!="number"||e<=0?null:Math.max(0,Math.ceil(e/1e3)));return H.useEffect(()=>{if(typeof e!="number"||e<=0){r(null);return}const s=Date.now();let o=null;const i=()=>{const a=Date.now()-s,l=Math.max(0,Math.ceil((e-a)/1e3));r(l),l<=0&&o!==null&&(clearInterval(o),o=null)};return i(),o=setInterval(i,1e3),()=>{o!==null&&clearInterval(o)}},[e,t]),n},jV=e=>e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?e.value.trim().length>0:e.isContentEditable?(e.textContent??"").trim().length>0:!1:!1,_V=({request:e,onRespond:t,messageId:n,highlightedIndex:r,setHighlightedIndex:s})=>{const o=e.options??[];return c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsx("div",{className:"flex flex-col gap-1 max-h-60 overflow-y-auto",role:"listbox","aria-label":Nn(e.title),children:o.map((i,a)=>{const l=a===r,d=a<9?a+1:void 0;return c.jsxs("button",{type:"button",role:"option","aria-selected":l,tabIndex:l?0:-1,onMouseEnter:()=>s(a),onFocus:()=>s(a),onClick:()=>t({value:i}),className:R("flex w-full items-center justify-between rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors outline-none",l?"bg-interactive-selection text-interactive-selection-foreground font-medium":"text-foreground hover:bg-interactive-hover"),children:[c.jsx("span",{className:"truncate",children:c.jsx(qt,{text:i})}),d!==void 0&&c.jsx("span",{className:R("ml-2 shrink-0 font-mono text-xs opacity-70",l?"text-interactive-selection-foreground":"text-muted-foreground"),children:d})]},i)})})]})},TV=({request:e,onRespond:t,messageId:n})=>c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-3 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsxs("div",{className:"flex items-center justify-end gap-2",children:[c.jsx(Se,{type:"button",variant:"outline",size:"sm",onClick:()=>t({confirmed:!1,cancelled:!0}),children:"No (N)"}),c.jsx(Se,{type:"button",variant:"default",size:"sm",onClick:()=>t({confirmed:!0}),children:"Yes (Y)"})]})]}),AV=({request:e,onRespond:t,messageId:n})=>{const r=e.method==="editor",[s,o]=H.useState(r?e.prefill??"":""),i=()=>{t({value:s})};return c.jsxs("div",{children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),r?c.jsx("textarea",{autoFocus:!0,value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?Nn(e.placeholder):"","aria-label":Nn(e.title),rows:4,className:"w-full resize-y rounded-md border bg-transparent p-2 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing",onKeyDown:a=>{a.key==="Enter"&&(a.metaKey||a.ctrlKey)&&(a.preventDefault(),i())}}):c.jsx("input",{autoFocus:!0,type:"text",value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?Nn(e.placeholder):"","aria-label":Nn(e.title),className:"w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing",onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),i())}}),c.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[c.jsx(Se,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),c.jsx(Se,{type:"button",variant:"default",size:"sm",onClick:i,disabled:!r&&s.trim().length===0,children:"Submit"})]})]})},NV=({request:e,onRespond:t,messageId:n})=>{const r={};for(const u of e.fields??[])u.type==="checkbox"?r[u.id]=u.initial==="true"?"true":"false":u.initial!==void 0?r[u.id]=u.initial:u.type==="select"&&u.options?.[0]!==void 0?r[u.id]=u.options[0]:r[u.id]="";const[s,o]=H.useState(r),[i,a]=H.useState(!1),l=(e.fields??[]).filter(u=>u.required&&(s[u.id]??"").length===0),d=(e.fields??[]).filter(u=>{if(u.type!=="number")return!1;const h=s[u.id]??"";if(h.length===0)return!1;const m=Number(h);return!Number.isFinite(m)||"min"in u&&typeof u.min=="number"&&m<u.min||"max"in u&&typeof u.max=="number"&&m>u.max}),f=i&&(l.length>0||d.length>0);return c.jsxs("form",{onSubmit:u=>{u.preventDefault(),a(!0),!(l.length>0||d.length>0)&&t({values:{...s}})},children:[e.message&&c.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:c.jsx(qt,{text:e.message})}),c.jsx("div",{className:"flex max-h-60 flex-col gap-2.5 overflow-y-auto",children:(e.fields??[]).map(u=>{const h=f&&u.required&&(s[u.id]??"").length===0,m=f&&d.some(y=>y.id===u.id),g=h||m,x=s[u.id]??"",b=y=>o(v=>({...v,[u.id]:y})),S="w-full rounded-md border bg-transparent p-1.5 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focusRing";return u.type==="checkbox"?c.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[c.jsx("input",{type:"checkbox",checked:x==="true",onChange:y=>b(y.target.checked?"true":"false"),className:"size-4"}),c.jsx("span",{children:c.jsx(qt,{text:u.label})})]},u.id):c.jsxs("label",{className:"flex flex-col gap-1 text-sm",children:[c.jsxs("span",{className:"text-xs font-medium text-foreground",children:[c.jsx(qt,{text:u.label}),u.required&&c.jsx("span",{"aria-hidden":"true",className:"text-status-error",children:" *"})]}),u.type==="textarea"?c.jsx("textarea",{value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"",rows:2,"aria-invalid":g||void 0,className:S}):u.type==="number"?c.jsx("input",{type:"number",value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"",min:"min"in u&&typeof u.min=="number"?u.min:void 0,max:"max"in u&&typeof u.max=="number"?u.max:void 0,"aria-invalid":g||void 0,className:S}):u.type==="select"?c.jsx("select",{value:x,onChange:y=>b(y.target.value),"aria-invalid":g||void 0,className:S,children:(u.options??[]).map(y=>c.jsx("option",{value:y,children:y},y))}):c.jsx("input",{type:"text",value:x,onChange:y=>b(y.target.value),placeholder:u.placeholder?Nn(u.placeholder):"","aria-invalid":g||void 0,className:S})]},u.id)})}),f&&c.jsx("p",{role:"alert",className:"mt-2 text-xs text-status-error",children:l.length>0&&d.length>0?"Fill in all required fields and enter valid numbers within the allowed range before submitting.":d.length>0?"Enter valid numbers within the allowed range before submitting.":"Fill in all required fields before submitting."}),c.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[c.jsx(Se,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),c.jsx(Se,{type:"submit",variant:"default",size:"sm",children:"Submit"})]})]})},LV=3,RV=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(!r||!s||r.sessionId!==s.sessionId||r.directory!==s.directory||r.title!==s.title||r.pending.count!==s.pending.count||r.pending.kind!==s.pending.kind||r.pending.since!==s.pending.since)return!1}return!0},PV=e=>ze(t=>{const n=[];for(const r of jm(t.catalog)){if(e&&r.sessionId===e)continue;const s=t.catalog.byId.get(r.sessionId),o=s?Nw(Or(s),"Untitled session"):"Untitled session";n.push({sessionId:r.sessionId,directory:r.directory,pending:r.pending,title:o})}return n},RV,"catalog",e??""),DV=({sessions:e})=>{const t=pe(s=>s.setCurrentSession),n=e.slice(0,LV),r=e.length-n.length;return c.jsxs("div",{role:"region","aria-label":"Other sessions need input",className:"overflow-hidden rounded-xl border border-border/80 bg-card p-1.5 shadow-md",children:[c.jsx("ul",{className:"flex flex-col",children:n.map(s=>{const o=SV(s.pending.kind,s.pending.count);return c.jsxs("li",{className:"flex min-h-[44px] items-center gap-2 px-2 py-1",children:[c.jsx(bV,{label:o}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-foreground",title:`${s.title} — ${o}`,children:s.title}),s.pending.count>1?c.jsx("span",{className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:`${s.pending.count} requests`}):null,c.jsx(Se,{type:"button",variant:"outline",size:"sm",onClick:()=>{t(s.sessionId,s.directory)},"aria-label":`Open ${s.title}`,children:"Open"})]},s.sessionId)})}),r>0?c.jsx("p",{className:"px-2 pb-1 text-xs text-muted-foreground",children:`+${r} more`}):null]})},wv=({sessionId:e})=>{const t=ze(y=>{const v=e??y.selectedSessionId,w=(v?y.reducer.bySession.get(v):void 0)?.extensionDialogs??[],M=w[0];if(M&&v)return{sessionId:v,request:M,queueLength:w.length};if(e!==void 0)return null;for(const[j,T]of y.reducer.bySession){const A=T.extensionDialogs,_=A[0];if(_)return{sessionId:j,request:_,queueLength:A.length}}return null},(y,v)=>y?.sessionId===v?.sessionId&&y?.request.requestId===v?.request.requestId&&y?.queueLength===v?.queueLength,"dialogs",e??""),n=pe(y=>y.currentSessionId),s=PV(e??n??null),[o,i]=H.useState(!1),[a,l]=H.useState(!1),[d,f]=H.useState(0),u=H.useRef(!1),h=H.useRef(null),m=H.useId(),g=t?`${t.sessionId}\0${t.request.requestId}`:null;H.useEffect(()=>{u.current=!1,i(!1),l(!1),f(0),g!==null&&h.current&&!h.current.contains(document.activeElement)&&!jV(document.activeElement)&&h.current.focus()},[g]);const x=EV(t?.request.timeoutMs,t?.request.requestId),b=H.useCallback(y=>{!t||o||u.current||(u.current=!0,i(!0),l(!1),MV(t.sessionId,t.request,y).then(()=>{IV()}).catch(()=>{l(!0)}).finally(()=>{u.current=!1,i(!1)}))},[o,t]),S=y=>{if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),b({cancelled:!0});return}if(t){if(t.request.method==="confirm"){if(y.key==="y"||y.key==="Y"){y.preventDefault(),b({confirmed:!0});return}if(y.key==="n"||y.key==="N"){y.preventDefault(),b({confirmed:!1,cancelled:!0});return}}if(t.request.method==="select"){const v=t.request.options??[],C=kV(y.key,d,v.length);if(!C)return;const M=(y.target instanceof HTMLElement?y.target:null)?.getAttribute("role")==="option";if(C.kind==="highlight"){y.preventDefault(),f(C.index),M&&h.current?.querySelectorAll('[role="option"]')[C.index]?.focus();return}if((y.key==="Enter"||y.key===" ")&&!M&&y.target!==y.currentTarget)return;const T=v[C.index];if(T===void 0)return;y.preventDefault(),b({value:T})}}};return!t&&s.length===0?null:c.jsxs("div",{"data-extension-prompt-dock":!0,className:"chat-input-column relative mb-2 flex flex-col gap-2",children:[s.length>0?c.jsx(DV,{sessions:s}):null,t?c.jsxs("div",{ref:h,role:"dialog","aria-label":Nn(t.request.title),"aria-describedby":t.request.message?m:void 0,tabIndex:-1,onKeyDown:S,className:"relative z-40 overflow-hidden rounded-xl border border-border/80 bg-card p-3 shadow-md transition-[opacity,transform] duration-150 outline-none",children:[c.jsxs("div",{className:"mb-2.5 flex items-center justify-between gap-2 border-b border-border/40 pb-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx($,{name:"plug-2",className:"size-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"truncate text-xs font-semibold uppercase tracking-wider text-foreground",children:c.jsx(qt,{text:t.request.title})})]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.queueLength>1&&c.jsxs("span",{className:"rounded-full bg-muted px-2 py-0.5 typography-micro font-medium text-muted-foreground",children:["1 of ",t.queueLength]}),x!==null&&c.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",title:`${x}s remaining`,children:[x,"s"]}),c.jsx(Se,{type:"button",variant:"ghost",size:"xs",onClick:()=>b({cancelled:!0}),className:"h-6 px-1.5 typography-micro text-muted-foreground hover:text-foreground","aria-label":"Dismiss extension dialog",children:"Dismiss (Esc)"})]})]}),c.jsxs("div",{className:o?"pointer-events-none opacity-60":void 0,"aria-busy":o||void 0,children:[t.request.method==="select"&&c.jsx(_V,{request:t.request,onRespond:b,messageId:m,highlightedIndex:d,setHighlightedIndex:f}),t.request.method==="confirm"&&c.jsx(TV,{request:t.request,onRespond:b,messageId:m}),(t.request.method==="input"||t.request.method==="editor")&&c.jsx(AV,{request:t.request,onRespond:b,messageId:m}),t.request.method==="form"&&c.jsx(NV,{request:t.request,onRespond:b,messageId:m})]}),a&&c.jsx("p",{role:"alert",className:"mt-2 text-xs text-status-error",children:"Could not send the response. Check your connection and try again."})]}):null]})},OV=e=>{const t=e.replace(/[-_]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e},HV=({sessionId:e,className:t})=>{const n=ze(d=>d.selectedSessionId),r=e??n,s=ze(d=>r?d.reducer.bySession.get(r)?.extensionWidgets:void 0,(d,f)=>d===f,r?`session:${r}`:"chrome"),o=H.useMemo(()=>[...s?.entries()??[]],[s]),[i,a]=H.useState({}),l=H.useCallback(d=>{a(f=>({...f,[d]:!f[d]}))},[]);return o.length===0?c.jsxs("div",{className:R("flex h-full flex-col items-center justify-center gap-1.5 p-6 text-center",t),"data-testid":"extensions-surface-empty",children:[c.jsx($,{name:"plug-2","aria-hidden":"true",className:"size-6 text-muted-foreground/60"}),c.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"No extension widgets yet"}),c.jsx("p",{className:"max-w-60 typography-micro text-muted-foreground",children:"Widgets that extensions set with ctx.ui.setWidget show up here."})]}):c.jsx("div",{className:R("flex h-full min-h-0 flex-col overflow-y-auto",t),"data-testid":"extensions-surface",children:c.jsx(FV,{title:"Widgets",count:o.length,children:o.map(([d,f])=>c.jsx(BV,{title:OV(d),meta:f.placement==="belowEditor"?"below editor":"above editor",collapsed:!!i[d],onToggle:()=>l(d),testId:`extension-widget-${d}`,children:c.jsx("div",{className:"max-h-64 overflow-auto rounded-md bg-muted/40 px-2 py-1.5 font-mono typography-micro leading-relaxed text-foreground",children:f.lines.map((u,h)=>c.jsx("span",{className:"block whitespace-pre-wrap",children:c.jsx(qt,{text:u})},h))})},d))})})},FV=({title:e,count:t,children:n})=>c.jsxs("section",{"aria-label":e,className:"border-t border-border/60 first:border-t-0",children:[c.jsxs("p",{className:"flex items-center gap-1.5 px-3 pb-0.5 pt-1.5 typography-micro font-medium text-muted-foreground",children:[e,c.jsx("span",{className:"tabular-nums text-muted-foreground/70",children:t})]}),c.jsx("div",{className:"flex flex-col p-1 pt-0.5",children:n})]}),BV=({title:e,meta:t,collapsed:n,onToggle:r,testId:s,children:o})=>c.jsxs("div",{"data-testid":s,children:[c.jsxs("button",{type:"button",onClick:r,"aria-expanded":!n,className:"flex w-full items-center gap-2 rounded-md px-2 py-1 text-left hover:bg-interactive-hover",children:[c.jsx("span",{className:"inline-flex w-4 shrink-0 items-center justify-center",children:c.jsx($,{name:n?"arrow-right-s":"arrow-down-s","aria-hidden":"true",className:"size-3.5 text-muted-foreground"})}),c.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:e,children:e}),t?c.jsx("span",{className:"shrink-0 whitespace-nowrap typography-micro text-muted-foreground",children:t}):null]}),!n&&c.jsx("div",{className:"pb-2 pl-8 pr-2 pt-0.5",children:o})]}),VV=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),Sv=({sessionId:e})=>{const t=ze(u=>u.selectedSessionId),n=e??t,{isMobile:r}=On(),[s,o]=H.useState(!1),i=ze(u=>[...(n?u.reducer.bySession.get(n):void 0)?.extensionStatuses.entries()??[]],(u,h)=>VV(u.flat(),h.flat()),`session:${n??""}`),{widgetsCount:a,sessionDirectory:l}=ze(u=>{const h=n?u.reducer.bySession.get(n):void 0;return{widgetsCount:h?.extensionWidgets.size??0,sessionDirectory:h?.directory}},(u,h)=>u.widgetsCount===h.widgetsCount&&u.sessionDirectory===h.sessionDirectory,`session:${n??""}`);H.useEffect(()=>{a===0&&o(!1)},[a]);const d=a===0?"":a===1?"1 widget":`${a} widgets`,f=H.useCallback(()=>{if(r){o(h=>!h);return}const u=l||nt.getState().currentDirectory||"";te.getState().openContextSurface(u,"extensions")},[r,l]);return i.length===0&&!d?null:c.jsxs("div",{className:"chat-input-column flex flex-col gap-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2 overflow-hidden rounded-full border border-border/40 bg-card px-3 py-1.5 shadow-sm transition-[opacity,transform] duration-150",children:[c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[c.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-full bg-interactive-hover text-muted-foreground",children:c.jsx($,{name:"plug-2",className:"size-3"})}),i.length>0&&c.jsx("div",{className:"flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hidden touch-pan-x","data-no-drawer-swipe":"true",children:i.map(([u,h])=>c.jsx("span",{className:"inline-flex shrink-0 items-center whitespace-nowrap rounded-full border border-border/60 bg-muted/40 px-2 py-0.5 typography-micro font-medium text-foreground",children:c.jsx(qt,{text:h})},u))})]}),d&&c.jsxs(Se,{type:"button",variant:"ghost",size:"xs",onClick:f,"aria-label":"Open extensions panel","aria-expanded":r?s:void 0,className:"shrink-0 gap-1 rounded-full border border-border/50 bg-muted/40 px-2 py-0.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground active:bg-interactive-active",children:[c.jsx($,{name:"layout-right",className:"size-3"}),c.jsx("span",{children:d})]})]}),r&&s&&c.jsx("div",{className:"max-h-60 overflow-y-auto rounded-xl border border-border/80 bg-card p-2 shadow-md",children:c.jsx(HV,{sessionId:n,className:"h-auto"})})]})},$V=({sessionId:e})=>{const t=te(r=>r.commandTriggers),n=p.useCallback((r,s)=>{e&&Ue().prompt(e,p5(r,s),"prompt").catch(()=>{})},[e]);return!e||t.length===0?null:c.jsx("div",{className:"mb-1 flex flex-wrap items-center gap-1.5 px-1",role:"toolbar","aria-label":"Command triggers",children:t.map(r=>c.jsx(Se,{size:"xs",variant:"outline",disabled:!e,onClick:()=>n(r.command,r.args),title:r.combo?`${r.label} (${ZS(r.combo)})`:r.label,children:r.label},r.id))})},zV=e=>[...e.key].length!==1?!1:e.getModifierState?.("AltGraph")===!0?!0:e.ctrlKey&&e.altKey&&!/^[a-z]$/i.test(e.key),UV={ArrowUp:"\x1B[A",ArrowDown:"\x1B[B",ArrowRight:"\x1B[C",ArrowLeft:"\x1B[D",Home:"\x1B[H",End:"\x1B[F",Insert:"\x1B[2~",Delete:"\x1B[3~",PageUp:"\x1B[5~",PageDown:"\x1B[6~"},M4=e=>{const{key:t,ctrlKey:n,altKey:r,metaKey:s,shiftKey:o}=e;if(s)return null;if(zV(e))return t;if(t==="Enter")return!n&&!o?r?"\x1B\r":"\r":`\x1B[13;${1+(o?1:0)+(r?2:0)+(n?4:0)}u`;if(t==="Escape")return"\x1B";if(t==="Tab")return o?"\x1B[Z":" ";if(t==="Backspace")return r?"\x1B":"";const i=UV[t];if(i){if(!n&&!r&&!o)return i;const a=1+(o?1:0)+(r?2:0)+(n?4:0),l=i.at(-1);return l==="~"?i.replace("~",`;${a}~`):`\x1B[1;${a}${l}`}if([...t].length!==1)return null;if(n){const a=t.toLowerCase().charCodeAt(0);return a>=97&&a<=122?(r?"\x1B":"")+String.fromCharCode(a-96):t===" "||t==="@"?"\0":t==="["?"\x1B":t==="\\"?"":t==="]"?"":t==="_"||t==="-"?"":null}return r?`\x1B${t}`:t},Cv="\x1B[200~",kv="\x1B[201~",qV=e=>{const t=e.split(Cv).join("").split(kv).join("");return`${Cv}${t}${kv}`},WV=e=>{let n=e.action==="wheel-up"||e.action==="wheel-down"?e.action==="wheel-up"?64:65:Math.min(Math.max(e.button,0),2);e.action==="drag"&&(n+=32),e.shiftKey&&(n+=4),e.altKey&&(n+=8),e.ctrlKey&&(n+=16);const r=Math.max(0,Math.floor(e.col))+1,s=Math.max(0,Math.floor(e.row))+1;return`\x1B[<${n};${r};${s}${e.action==="release"?"m":"M"}`},Mv=(e,t)=>{const n=[...e],r=[...t];let s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;return"".repeat(n.length-s)+r.slice(s).join("").replace(/\r?\n/g,"\r")},KV=256,_1=64*1024,xu=J5,Dn=new Map,T1=new Set,GV=(e,t)=>e!==void 0&&e.columns===t.columns&&e.screenColumns===t.screenColumns&&e.rows===t.rows,A1=e=>e instanceof lt&&e.code==="EXTENSION_SURFACE_NOT_OPEN",Va=()=>({runtimeKey:Y()}),I4=(e,t,n)=>{Ee.sendExtensionSurface("viewport",{sessionId:e,clientId:xu(),viewport:t,...n?{claim:!0}:{}},Va()).catch(()=>{Dn.delete(e)})},ZV=(e,t)=>{const n=T1.delete(e);!n&&GV(Dn.get(e),t)||(Dn.set(e,t),I4(e,t,n))},E4=e=>{const t=Dn.get(e);t?I4(e,t,!0):T1.add(e)},YV=e=>{Dn.delete(e),T1.delete(e)},Pp=new Map,XV=e=>{const t=[];let n=0;for(;e.length>0&&t.length<KV;){const r=e[0];if(t.length>0&&n+r.length>_1)break;t.push(e.shift()),n+=r.length}return t},JV=async(e,t,n)=>{n.inFlight=!0;try{for(;n.pending.length>0;){const r=XV(n.pending);try{await Ee.sendExtensionSurface("input",{sessionId:e,surfaceId:t,clientId:xu(),...Dn.has(e)?{viewport:Dn.get(e)}:{},items:r},Va())}catch(s){n.pending.length=0,A1(s)?Ue().dropExtensionSurface(e,t):Ce.error("Keys did not reach the extension. Try again.")}}}finally{n.inFlight=!1,Pp.delete(`${e}\0${t}`)}},Pl=(e,t,n)=>{const r=n.filter(i=>i.length>0&&i.length<=_1);if(r.length===0)return;const s=`${e}\0${t}`;let o=Pp.get(s);o||(o={pending:[],inFlight:!1},Pp.set(s,o)),o.pending.push(...r),o.inFlight||JV(e,t,o)},$i=new Set,QV=256,e$=e=>e.reason==="cancelled"&&!e.surface.parentId&&!$i.has(`${e.sessionId}\0${e.surface.surfaceId}`),t$=async(e,t)=>{$i.add(`${e}\0${t}`),$i.size>QV&&$i.delete($i.values().next().value);try{await Ee.sendExtensionSurface("close",{sessionId:e,surfaceId:t,clientId:xu(),...Dn.has(e)?{viewport:Dn.get(e)}:{}},Va())}catch(n){if(A1(n)){Ue().dropExtensionSurface(e,t);return}Ce.error("Could not close the extension surface. Try again.")}},Iv=async(e,t)=>{try{await Ee.sendExtensionSurface("focus",{sessionId:e,surfaceId:t,clientId:xu(),...Dn.has(e)?{viewport:Dn.get(e)}:{}},Va())}catch(n){if(A1(n))return;Ce.error("Could not switch to that panel. Try again.")}},ch=new Set,n$=(e,t)=>{const n=`${e}\0${t}`;ch.has(n)||(ch.add(n),Ee.sendExtensionSurface("refresh",{sessionId:e,surfaceId:t},Va()).catch(()=>{}).finally(()=>ch.delete(n)))},r$=[{label:"Esc",data:"\x1B"},{label:"Tab",data:" "},{label:"Left",data:"\x1B[D",icon:"arrow-left"},{label:"Up",data:"\x1B[A",icon:"arrow-up"},{label:"Down",data:"\x1B[B",icon:"arrow-down"},{label:"Right",data:"\x1B[C",icon:"arrow-right"},{label:"Enter",data:"\r"}],Js=" ",j4=({sessionId:e,surfaceId:t,className:n})=>{const r=H.useRef(null),s=H.useRef(""),[o,i]=H.useState(!1),a=u=>{u&&Pl(e,t,[u])},l=()=>{s.current="";const u=r.current;u&&(u.value=Js,u.setSelectionRange(Js.length,Js.length))},d=u=>{const h=u.currentTarget,m=u.nativeEvent.isComposing;if(!h.value.startsWith(Js)){a(Mv(s.current,"")+(h.value===""?"":h.value)),l();return}const g=h.value.slice(Js.length);a(Mv(s.current,g)),s.current=g,m||l()},f=u=>{if(u.nativeEvent.isComposing||u.key==="Unidentified"||[...u.key].length===1)return;const h=M4(u);h!==null&&(u.preventDefault(),a(h))};return c.jsxs("div",{role:"toolbar","aria-label":"Extension keys",className:R("relative flex items-center gap-0.5 overflow-x-auto",n),children:[r$.map(u=>c.jsx(Se,{type:"button",variant:"outline",size:"xs",className:R("shrink-0 font-sans",u.icon?"h-7 w-6 px-0 has-[>svg]:px-0":"h-7 px-1.5"),"aria-label":u.icon?u.label:void 0,onPointerDown:h=>h.preventDefault(),onClick:()=>a(u.data),children:u.icon?c.jsx($,{name:u.icon,className:"size-3.5"}):u.label},u.label)),c.jsx(Se,{type:"button",variant:"chip",size:"xs",className:"ml-auto h-7 shrink-0 px-1.5 font-sans","aria-pressed":o,onPointerDown:u=>u.preventDefault(),onClick:()=>{o?r.current?.blur():r.current?.focus({preventScroll:!0})},children:"Keyboard"}),c.jsx("input",{ref:r,"aria-label":"Type to the extension",className:"pointer-events-none absolute left-0 top-0 size-px opacity-0",defaultValue:Js,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,enterKeyHint:"enter",onFocus:()=>{l(),i(!0)},onBlur:()=>i(!1),onInput:d,onCompositionEnd:l,onKeyDown:f})]})},s$=.5,_4=(e,t)=>{const n=[1];return e.width>0&&t.width>0&&n.push(t.width/e.width),e.height&&t.height&&e.height>0&&t.height>0&&n.push(t.height/e.height),Math.max(s$,Math.min(...n))},T4=(e,t,n=!0)=>{const[r,s]=H.useState({width:0,height:0,cell:0});return H.useEffect(()=>{const o=e.current;if(!o)return;const i=()=>{const l=o.clientWidth,d=o.clientHeight,f=(t.current?.getBoundingClientRect().width??0)/10;s(u=>u.width===l&&u.height===d&&u.cell===f?u:{width:l,height:d,cell:f})};i();const a=new ResizeObserver(i);return a.observe(o),()=>a.disconnect()},[e,t,n]),r},Mi=(e,t,n,r)=>({col:Math.min(Math.max(Math.floor((n-t.left)/Math.max(e.cellWidth,1)),0),Math.max(e.columns-1,0)),row:Math.min(Math.max(Math.floor((r-t.top)/e.lineHeight),0),Math.max(e.rows-1,0))}),Sd=5,o$=10,i$=(e,t,n,r)=>{const s=e.deltaMode===1?e.deltaY:e.deltaMode===2?e.deltaY*r:e.deltaY/n,o=t+s,i=Math.trunc(o);return{steps:Math.max(-Sd,Math.min(Sd,i)),rest:i===0?o:0}},lh={shiftKey:!1,altKey:!1,ctrlKey:!1},a$=e=>{const t=H.useRef(e);t.current=e;const n=H.useRef(null),r=H.useRef(0),s=(x,b,S,y)=>{t.current.send(WV({action:x,button:b,...S,shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.ctrlKey}))},o=(x,b,S)=>{for(let y=0;y<Math.abs(x);y+=1)s(x<0?"wheel-up":"wheel-down",0,b,S)},i=()=>({columns:t.current.columns,rows:t.current.rows,cellWidth:t.current.measureCell(),lineHeight:t.current.lineHeight}),a=()=>t.current.rows===0||t.current.columns===0,l=x=>x.target instanceof Element&&x.target.closest("a[href]")!==null,d=x=>!x.shiftKey&&x.button<=2&&!a()&&!l(x),f=x=>{const b=t.current.ref.current;if(!b||n.current)return;if(x.pointerType==="touch"){if(a()||l(x))return;const w=b.getBoundingClientRect();n.current={kind:"touch",pointerId:x.pointerId,startX:x.clientX,startY:x.clientY,lastY:x.clientY,swiping:!1,rest:0,cell:Mi(i(),{left:w.left,top:w.top},x.clientX,x.clientY)};return}if(!d(x))return;const S=b.getBoundingClientRect(),y={left:S.left,top:S.top},v=i(),C=Mi(v,y,x.clientX,x.clientY);n.current={kind:"mouse",pointerId:x.pointerId,button:x.button,...C,grid:v,origin:y},b.setPointerCapture?.(x.pointerId),t.current.onPress?.(),s("press",x.button,C,x)},u=x=>{const b=n.current;if(!b||b.pointerId!==x.pointerId)return;if(b.kind==="touch"){if(!b.swiping){if(Math.hypot(x.clientX-b.startX,x.clientY-b.startY)<o$)return;if(t.current.nativeTouchScroll){n.current=null;return}b.swiping=!0}const y=b.rest+b.lastY-x.clientY;b.lastY=x.clientY;const v=Math.trunc(y/t.current.lineHeight);b.rest=y-v*t.current.lineHeight,o(Math.max(-Sd,Math.min(Sd,v)),b.cell,lh);return}const S=Mi(b.grid,b.origin,x.clientX,x.clientY);S.col===b.col&&S.row===b.row||(b.col=S.col,b.row=S.row,s("drag",b.button,S,x))},h=x=>{const b=n.current;if(!b||b.pointerId!==x.pointerId)return;if(n.current=null,b.kind==="touch"){if(x.type!=="pointerup"||b.swiping)return;t.current.onPress?.(),s("press",0,b.cell,lh),s("release",0,b.cell,lh);return}const S=x.type==="pointercancel"?b:Mi(b.grid,b.origin,x.clientX,x.clientY);s("release",b.button,{col:S.col,row:S.row},x)},m=x=>{d(x)&&x.preventDefault()},g=H.useRef({wheel:o,grid:i,empty:a});return g.current={wheel:o,grid:i,empty:a},H.useEffect(()=>{const x=e.ref.current;if(!x)return;const b=S=>{const{wheel:y,grid:v,empty:C}=g.current;if(S.shiftKey||S.deltaY===0||C())return;S.preventDefault();const{steps:w,rest:M}=i$(S,r.current,t.current.lineHeight,t.current.rows);if(r.current=M,w===0)return;const j=x.getBoundingClientRect();y(w,Mi(v(),{left:j.left,top:j.top},S.clientX,S.clientY),S)};return x.addEventListener("wheel",b,{passive:!1}),()=>x.removeEventListener("wheel",b)},[e.ref]),{onPointerDown:f,onPointerMove:u,onPointerUp:h,onPointerCancel:h,onMouseDown:m,touchAction:e.nativeTouchScroll?"pan-y":"none"}},c$="▀",l$="▄",d$="█",u$=/[▀▄█]/,f$=/^([▀▄█])\1*$/,h$=/([▀▄█])\1*|[^▀▄█]+/g,p$=e=>u$.test(e),A4=e=>f$.test(e),m$=e=>(e.match(h$)??[]).map(t=>({text:t,block:A4(t)})),Ev=(e,t,n)=>{const{color:r,backgroundColor:s,...o}=t??{},i=String(r??"var(--foreground)"),a=String(s??"transparent"),l=e[0];return{...o,display:"inline-block",width:`${e.length}ch`,height:n,verticalAlign:"top",color:"transparent",backgroundColor:l===d$?i:a,backgroundImage:l===c$?`linear-gradient(${i} 50%, ${a} 50%)`:l===l$?`linear-gradient(${a} 50%, ${i} 50%)`:"none"}},Bt=18,$o=12,g$=24,N4=3,zo="font-mono text-[13px] leading-[18px] [font-variant-ligatures:none]",L4=[],R4=e=>ze(t=>e?t.reducer.bySession.get(e)?.extensionSurfaces:void 0,Object.is,e?`session:${e}`:"*",e??""),P4=e=>{const t=R4(e);return H.useMemo(()=>t?[...t.values()].sort((n,r)=>n.z-r.z):L4,[t])},y$=e=>ze(t=>{const n=t.reducer.bySession.get(e);return n?.lifecycle==="busy"&&!n.runningCommand||n?.lifecycle==="retry"},Object.is,`session:${e}`,e),Jc=e=>{document.querySelector(`[data-extension-surface="${CSS.escape(e)}"]`)?.focus({preventScroll:!0})},Dp=()=>{requestAnimationFrame(()=>{const e=document.activeElement;e&&e!==document.body&&!e.closest('[aria-hidden="true"]')||document.querySelector('[data-chat-input="true"] [contenteditable="true"], .chat-input-column textarea')?.focus()})},dh=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null,D4=H.memo(({line:e,cells:t})=>{if(e==="")return" ";const n=t&&dh?t:void 0;if(!n&&!p$(e))return c.jsx(qt,{text:e,links:!0});let r=0;return c.jsx(c.Fragment,{children:v4(e).map((s,o)=>{const i=bd(s),a=g4(s.href);if(!a&&A4(s.text))return r+=s.text.length,c.jsx("span",{style:Ev(s.text,i,Bt),children:s.text},o);const l=[],d=f=>{for(const u of m$(f))l.push(u.block?c.jsx("span",{style:Ev(u.text,i,Bt),children:u.text},`block-${l.length}`):u.text)};if(!n||!dh)d(s.text);else{let f="";for(const{segment:u}of dh.segment(s.text)){const h=n[r++]??1;if(h===1){f+=u;continue}f&&d(f),f="",l.push(c.jsx("span",{className:"inline-block overflow-hidden text-center align-top",style:{width:`${h}ch`,height:Bt},children:h===0?null:u},r))}f&&d(f)}return a?c.jsx(k4,{segment:s,href:a,children:l},o):c.jsx("span",{style:i,children:l},o)})})});D4.displayName="CellLine";const O4=({sessionId:e,surface:t,nativeTouchScroll:n=!1,scale:r=1,zoomSelf:s=!1})=>{const o=H.useRef(null),i=H.useRef(null),a=t.frame,l=t.capturing||t.focused,d=a$({ref:o,measureCell:()=>(i.current?.getBoundingClientRect().width??0)/10,columns:a?.columns??0,rows:a?.lines.length??0,lineHeight:Bt*r,nativeTouchScroll:n,send:h=>Pl(e,t.surfaceId,[h]),onPress:()=>{l&&o.current?.focus({preventScroll:!0})}});H.useEffect(()=>{!t.focused||!l||!o.current||o.current.contains(document.activeElement)||document.activeElement?.closest("[data-extension-tabs]")||o.current.focus({preventScroll:!0})},[t.focused,l]);const f=h=>{if(h.nativeEvent.isComposing)return;const m=h.metaKey||h.ctrlKey;if(m&&h.key.toLowerCase()==="c"&&(window.getSelection()?.toString()??"")!==""||m&&h.key.toLowerCase()==="v")return;const g=M4(h);g!==null&&(h.preventDefault(),h.stopPropagation(),Pl(e,t.surfaceId,[g]))},u=h=>{const m=h.clipboardData.getData("text/plain");if(!m)return;h.preventDefault();const g=qV(m);if(g.length>_1){Ce.error("That paste is too long for the extension (64 KB at most).");return}Pl(e,t.surfaceId,[g])};return c.jsxs("div",{ref:o,"data-extension-surface":t.surfaceId,role:"application","aria-label":`Extension: ${t.title}`,tabIndex:l?0:-1,onKeyDown:l?f:void 0,onPaste:l?u:void 0,onPointerDown:h=>{E4(e),d.onPointerDown(h)},onPointerMove:d.onPointerMove,onPointerUp:d.onPointerUp,onPointerCancel:d.onPointerCancel,onMouseDown:d.onMouseDown,style:{touchAction:d.touchAction,...s&&r!==1?{zoom:r}:{}},className:R("relative whitespace-pre text-foreground outline-none",zo),children:[c.jsx("span",{ref:i,"aria-hidden":!0,className:"invisible absolute left-0 top-0",children:"0000000000"}),(a?.lines??[]).map((h,m)=>c.jsx("div",{style:{height:Bt},children:c.jsx(D4,{line:h,cells:a?.cells[m]})},m)),a?.cursor&&t.focused?c.jsx("span",{"aria-hidden":!0,className:"pointer-events-none absolute bg-foreground/70",style:{left:`${a.cursor.col}ch`,top:a.cursor.row*Bt+1,width:"1ch",height:Bt-2}}):null]})},N1=({sessionId:e,surface:t})=>c.jsx(Se,{type:"button",variant:"ghost",size:"xs",className:"size-6 shrink-0 px-0 text-muted-foreground hover:text-foreground","aria-label":`Close ${t.title}`,title:"Close",onClick:()=>{t$(e,t.surfaceId)},children:c.jsx($,{name:"close",className:"size-3.5"})}),v$=(e,t)=>{const n=t.filter(r=>r.stale).map(r=>r.surfaceId).join("\0");H.useEffect(()=>{if(n)for(const r of n.split("\0"))n$(e,r)},[e,n])},x$=({sessionId:e})=>{const t=H.useRef(null),n=H.useRef(null),r=On().hasTouchOnlyPointer?N4:0;return H.useEffect(()=>{const s=t.current;if(!s)return;const o=s.closest("[data-composer-bound]"),i=()=>{const l=(n.current?.getBoundingClientRect().width??0)/10;!(l>0)||!o||ZV(e,{columns:Math.floor(s.clientWidth/l),screenColumns:Math.floor((o.clientWidth-2*$o)/l),rows:Math.max(1,Math.floor((o.clientHeight-2*$o)/Bt)-r)})};YV(e),i();const a=new ResizeObserver(i);return a.observe(s),o&&a.observe(o),()=>a.disconnect()},[e,r]),c.jsx("div",{"aria-hidden":!0,className:"chat-input-column pointer-events-none absolute inset-x-0 top-0 h-0 overflow-hidden",children:c.jsx("div",{className:"mx-px px-3",children:c.jsx("div",{ref:t,className:"relative w-full",children:c.jsx("span",{ref:n,className:R("invisible absolute",zo),children:"0000000000"})})})})},b$=e=>{const[t,n]=H.useState(!1);return H.useEffect(()=>{const r=e.current;if(!r)return;const s=()=>n(r.scrollHeight>r.clientHeight+1);s();const o=new ResizeObserver(s);return o.observe(r),r.firstElementChild&&o.observe(r.firstElementChild),()=>o.disconnect()},[e]),t},w$=(e,t)=>{const[n,r]=H.useState(void 0);return H.useLayoutEffect(()=>{const s=e.current,o=t.current,i=s?.closest("[data-composer-bound]");if(!s||!o||!i)return;const a=()=>{const d=s.offsetHeight-o.offsetHeight,f=s.parentElement,u=f&&Number.parseFloat(getComputedStyle(f).paddingBottom)||0;r(Math.max(4*Bt,Math.floor(i.clientHeight-d-u-$o)))};a();const l=new ResizeObserver(a);return l.observe(i),l.observe(s),()=>l.disconnect()},[e,t]),n},S$=({sessionId:e,surface:t,below:n})=>{const r=y$(e),{hasTouchOnlyPointer:s}=On(),o=H.useRef(null),i=H.useRef(null),a=H.useRef(null),l=w$(o,i),d=b$(i),f=T4(i,a),u=f.cell>0&&t.frame?_4({width:t.frame.columns*f.cell},{width:f.width-g$}):1;return c.jsx("div",{className:"chat-input-column pb-3",children:c.jsxs("div",{ref:o,role:"dialog","aria-label":`Extension: ${t.title}`,className:"pi-surface-rise overflow-hidden rounded-xl border border-border/80 bg-card shadow-md",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/40 px-3 py-1.5",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[c.jsx($,{name:"plug-2",className:"size-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"shrink-0 typography-ui-label font-medium text-foreground",children:t.title}),t.blocked?.message?c.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:t.blocked.message}):null,n>0?c.jsx("span",{className:"shrink-0 rounded-full bg-muted px-2 py-0.5 typography-micro text-muted-foreground",children:n===1?"1 more below":`${n} more below`}):null]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[r?c.jsxs(Se,{type:"button",variant:"ghost",size:"xs",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>Dm(e),children:[c.jsx($,{name:"stop",className:"size-3.5"}),"Stop"]}):null,c.jsx(N1,{sessionId:e,surface:t})]})]}),c.jsxs("div",{ref:i,className:"relative overflow-auto px-3 py-2",style:{maxHeight:l??"60vh"},children:[c.jsx(O4,{sessionId:e,surface:t,nativeTouchScroll:d,scale:u,zoomSelf:!0}),c.jsx("span",{ref:a,"aria-hidden":!0,className:R("invisible absolute left-0 top-0",zo),children:"0000000000"})]}),s&&t.capturing?c.jsx(j4,{sessionId:e,surfaceId:t.surfaceId,className:"border-t border-border/40 px-3 py-1.5"}):c.jsx("div",{className:"border-t border-border/40 px-3 py-1.5 typography-micro text-muted-foreground",children:"Keys go to the extension. Your draft is kept when it closes."})]})})},C$=({sessionId:e,surfaces:t})=>{const n=Jd(e)!==null;return t.length===0?null:c.jsx("div",{className:"chat-input-column mb-2 flex flex-col gap-1",children:t.map(r=>c.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg bg-[var(--surface-muted)] px-3 py-1",children:[c.jsxs("span",{className:"min-w-0 typography-meta text-muted-foreground [text-wrap:pretty]",children:[r.hidden?`${r.title} is hidden by the extension.`:`${r.title} is hidden because the screen is too narrow.`,n?" New messages wait until it closes.":null]}),c.jsx(N1,{sessionId:e,surface:r})]},r.surfaceId))})},k$=e=>{H.useEffect(()=>{if(e)return Ue().subscribeExtensionSurfaceDismissals(t=>{t.sessionId!==e||!e$(t)||Ce.info(`${t.surface.title} was closed on another device.`,{id:`extension-surface-closed:${t.surface.surfaceId}`})})},[e])},jv=({sessionId:e,children:t})=>{k$(e);const n=P4(e),r=n.filter(f=>f.mode==="inline"&&!f.hidden),s=r.at(-1)??null,o=n.filter(f=>f.mode==="overlay"&&!f.parentId&&(f.hidden||f.frame?.visible===!1)),[i,a]=H.useState(!1),[l,d]=H.useState({sessionId:e,hasTop:!!s});return(l.sessionId!==e||l.hasTop!==!!s)&&(d({sessionId:e,hasTop:!!s}),l.sessionId===e&&!s&&a(!0)),H.useEffect(()=>{i&&Dp()},[i]),v$(e??"",e?n:L4),c.jsxs(c.Fragment,{children:[e&&n.length>0?c.jsx(x$,{sessionId:e}):null,e?c.jsx(C$,{sessionId:e,surfaces:o}):null,e&&s?c.jsx(S$,{sessionId:e,surface:s,below:r.length-1},s.surfaceId):null,c.jsx("div",{hidden:!!s,className:i&&!s?"pi-surface-fade":void 0,onAnimationEnd:f=>{f.target===f.currentTarget&&a(!1)},children:t})]})},_v=8,M$=2,mo=5,I$=28-$o,L1="rounded-lg border border-border/80 bg-card shadow-md",H4=({sessionId:e,surface:t,scale:n})=>{const r=t.frame?.layout??{width:40,height:1};return c.jsx("div",{className:R(L1,"max-w-full p-1"),style:n!==1?{zoom:n}:void 0,children:c.jsx("div",{className:"relative overflow-hidden",style:{width:`${r.width}ch`,maxWidth:"100%",height:r.height*Bt},children:c.jsx(O4,{sessionId:e,surface:t,scale:n})})})},F4=e=>({left:`max(0px, min(${e.col}ch, 100% - ${e.width}ch - ${2*mo}px))`,top:`max(0px, min(${e.row*Bt}px, 100% - ${e.height*Bt+2*mo}px))`,maxWidth:"100%"}),E$=({sessionId:e,title:t,members:n,front:r,anchor:s,onPicked:o,scaleFor:i})=>{const a=r.frame?.layout??{width:40,height:1},l={row:s.row,col:s.col,width:a.width,height:a.height},d=n.length>1,f=Math.min(M$,n.length-1),u=l.row<3;return c.jsxs("div",{role:"group","aria-label":`${t} panels`,className:R("absolute isolate pointer-events-auto",zo),style:F4(l),children:[d?c.jsx("div",{role:"tablist","aria-label":`${t} panels`,"data-extension-tabs":!0,onKeyDown:h=>{const m=n.findIndex(x=>x.surfaceId===r.surfaceId),g=h.key==="ArrowRight"?(m+1)%n.length:h.key==="ArrowLeft"?(m-1+n.length)%n.length:h.key==="Home"?0:h.key==="End"?n.length-1:null;g!==null&&(h.preventDefault(),h.currentTarget.querySelectorAll('[role="tab"]')[g]?.focus(),g!==m&&Iv(e,n[g].surfaceId))},className:"absolute left-0 flex max-w-[calc(100vw-2rem)] items-center gap-1 overflow-x-auto rounded-md bg-card p-0.5 font-sans",style:u?{top:"calc(100% + 4px)"}:{bottom:`calc(100% + ${f*_v+4}px)`},children:n.map((h,m)=>{const g=h.surfaceId===r.surfaceId;return c.jsx(Se,{type:"button",variant:"chip",size:"xs",role:"tab","aria-selected":g,tabIndex:g?0:-1,className:R("shrink-0",g&&"bg-interactive-selection text-interactive-selection-foreground"),onMouseDown:x=>x.preventDefault(),onClick:()=>{o(),(!g||!h.focused)&&Iv(e,h.surfaceId)},children:mv(h,m)},h.surfaceId)})}):null,Array.from({length:f},(h,m)=>{const g=m+1;return c.jsx("div",{"aria-hidden":!0,className:R("absolute inset-0",L1),style:{zIndex:-g,transform:`translateY(-${g*_v}px) scale(${1-g*.04})`,transformOrigin:"top center"}},g)}),c.jsx("div",{role:d?"tabpanel":"dialog","aria-label":`Extension: ${t}, ${mv(r,n.indexOf(r))}`,className:"pi-surface-pop",children:c.jsx(H4,{sessionId:e,surface:r,scale:i(r)})},r.surfaceId)]})},j$=e=>{const[t,n]=H.useState(DB),r=OB(t,e);return r!==t&&n(r),r},_$=e=>{const[t,n]=H.useState(e),[r,s]=H.useState([]);if(t!==e){const i=new Set(e.map(l=>l.surfaceId)),a=t.filter(l=>!i.has(l.surfaceId));n(e),(a.length>0||r.some(l=>i.has(l.surfaceId)))&&s([...r.filter(l=>!i.has(l.surfaceId)),...a])}const o=H.useCallback(i=>{s(a=>a.filter(l=>l.surfaceId!==i))},[]);return{leaving:r,finish:o}},Tv=({sessionId:e})=>{const t=R4(e),n=P4(e),r=H.useMemo(()=>n.filter(x4),[n]),s=H.useMemo(()=>PB(r,t?[...t.keys()]:[]),[r,t]),o=j$(s),i=H.useMemo(()=>s.flatMap(I=>{const N=o.get(I.parentId);return N?[{...I,anchor:N}]:[]}),[s,o]),a=H.useMemo(()=>new Set(i.flatMap(I=>I.members.map(N=>N.surfaceId))),[i]),{leaving:l,finish:d}=_$(r),f=H.useRef(new Set),u=l.filter(I=>!f.current.has(I.surfaceId)),h=l.filter(I=>f.current.has(I.surfaceId)).map(I=>I.surfaceId).join("\0");H.useEffect(()=>{f.current=a},[a]),H.useEffect(()=>{if(h)for(const I of h.split("\0"))d(I)},[h,d]);const m=r.filter(I=>I.capturing).at(-1)?.surfaceId??null,g=H.useRef(!1);H.useEffect(()=>{m?g.current=!0:g.current&&(g.current=!1,Dp())},[m]);const x=(r.find(I=>I.capturing&&I.focused)??r.filter(I=>I.capturing).at(-1))?.surfaceId??null,b=H.useRef(null),{hasTouchOnlyPointer:S}=On(),y=H.useRef(null),v=H.useRef(null),C=T4(y,v,r.length>0||u.length>0),w=I=>{const N=I.frame?.layout;return!N||!(C.cell>0)?1:_4({width:N.width*C.cell+2*mo,height:N.height*Bt+2*mo},{width:C.width,height:C.height})};H.useEffect(()=>{const I=b.current,N=I?.closest("[data-composer-bound]");if(!x||!I||!N)return;const O=U=>U instanceof Element&&U.closest("[data-extension-prompt-dock]")!==null,L=()=>{O(document.activeElement)||document.activeElement?.closest("[data-extension-tabs]")||Jc(x)},D=requestAnimationFrame(L);let W=null;const z=()=>{W?.disconnect(),W=null},J=()=>{W||(W=new MutationObserver(()=>{const U=document.activeElement;U&&U!==document.body&&U.isConnected||(z(),L())}),W.observe(N,{childList:!0,subtree:!0}))},B=U=>{const P=U.target;if(!(P instanceof Node)||!N.contains(P)||I.contains(P)){z();return}if(O(P)){J();return}z(),L()};return O(document.activeElement)&&J(),document.addEventListener("focusin",B,!0),()=>{cancelAnimationFrame(D),z(),document.removeEventListener("focusin",B,!0)}},[x]);const M=x?null:r.find(I=>!I.capturing&&I.focused)?.surfaceId??null,j=H.useRef(null);if(H.useEffect(()=>{const I=j.current;j.current=M,!(M||!I)&&(document.activeElement?.getAttribute("data-extension-surface")===I&&document.activeElement.blur(),Dp())},[M]),H.useEffect(()=>{const I=b.current,N=I?.closest("[data-composer-bound]");if(!M||!I||!N)return;let O=!1;const L=W=>{W.target instanceof Node&&!I.contains(W.target)&&(O=!0)},D=W=>{const z=W.target;O||!(z instanceof Node)||!N.contains(z)||I.contains(z)||z instanceof Element&&z.closest("[data-extension-prompt-dock]")||Jc(M)};return document.addEventListener("pointerdown",L,!0),document.addEventListener("focusin",D,!0),()=>{document.removeEventListener("pointerdown",L,!0),document.removeEventListener("focusin",D,!0)}},[M]),!e||r.length===0&&u.length===0)return null;const T=r.filter(I=>I.capturing).at(-1)??null,A=x??M,_=S&&A!==null,k=C.height-(_?N4*Bt:0),E=[...r.map(I=>({surface:I,isLeaving:!1})),...u.map(I=>({surface:{...I,focused:!1,capturing:!1},isLeaving:!0}))];return c.jsxs("div",{ref:b,className:"pointer-events-none absolute inset-0 z-30",children:[T?c.jsx("div",{"aria-hidden":!0,className:"pi-surface-fade pointer-events-auto absolute inset-0 bg-background/60",onMouseDown:I=>{I.preventDefault(),E4(e),x&&Jc(x)}}):null,c.jsx("div",{className:"absolute inset-0",style:{padding:$o},children:c.jsxs("div",{ref:y,className:"relative h-full",children:[c.jsx("span",{ref:v,"aria-hidden":!0,className:R("invisible absolute left-0 top-0",zo),children:"0000000000"}),E.map(({surface:I,isLeaving:N})=>{const O=I.frame?.layout??{row:0,col:0,width:40,height:1};if(!N&&a.has(I.surfaceId)){const L=i.find(W=>W.members.includes(I));if(!L||L.members.some(W=>W.z>I.z))return null;const D=t?.get(L.parentId)?.title??I.title;return c.jsx(E$,{sessionId:e,title:D,members:L.members,front:L.front,anchor:L.anchor,onPicked:()=>{x&&Jc(x)},scaleFor:w},`stack-${L.parentId}`)}return c.jsxs("div",{role:"dialog","aria-label":`Extension: ${I.title}`,"aria-hidden":N||void 0,className:R("absolute",zo,N?"pi-surface-out pointer-events-none":"pi-surface-pop pointer-events-auto"),style:F4(O),onAnimationEnd:N?L=>{L.target===L.currentTarget&&d(I.surfaceId)}:void 0,children:[I.parentId?null:c.jsxs("div",{className:R("absolute flex items-center gap-0.5 rounded-md bg-card pl-2 font-sans",{above:"right-0 -top-7",below:"right-0 -bottom-7",inside:"right-1 top-1 z-10 shadow-sm"}[HB({top:O.row*Bt,layoutHeight:O.height*Bt+2*mo,height:(O.height*Bt+2*mo)*w(I)},k,I$)]),children:[c.jsx("span",{className:"typography-micro text-muted-foreground",children:I.title}),c.jsx(N1,{sessionId:e,surface:I})]}),c.jsx(H4,{sessionId:e,surface:I,scale:w(I)})]},I.surfaceId)})]})}),_&&A?c.jsx("div",{className:"pointer-events-auto absolute inset-x-0 bottom-0 flex justify-center",style:{padding:$o},children:c.jsx(j4,{sessionId:e,surfaceId:A,className:R(L1,"max-w-full p-1")})}):null]})},T$=({isNewSession:e=!1})=>{const{currentTheme:t}=Jn(),n=t?.colors?.surface?.mutedForeground||"var(--muted-foreground)";return c.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[c.jsx(Um,{width:120,height:120,isAnimated:!e,className:e?"opacity-20":void 0}),e?c.jsx("span",{className:"text-body-md",style:{color:n},children:"Start a new chat"}):null]})},A$=p.memo(T$),R1=2,B4=2,N$=72,L$=(e,t=R1)=>t+Math.max(0,e),R$=(e,t,n,r=R1)=>{const s=L$(n,r);return t<=s?!1:e<t-s},P$=(e,t,n=R1)=>Math.max(0,t-n-e),D$=(e,t,n=B4)=>e+Math.max(0,Math.min(n,t)),O$=({foldedCount:e,onLoadOlder:t,onLoadAll:n})=>{const r=Math.min(B4,e),s=e>r;return c.jsx("div",{className:"chat-message-column flex flex-col items-center py-4",children:c.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[c.jsxs(Se,{type:"button",variant:"secondary",size:"sm",onClick:t,"aria-label":"Load older history",className:"gap-1.5 rounded-full px-3.5",children:[c.jsx($,{name:"history",className:"size-3.5"}),"Load older history"]}),s?c.jsx(Se,{type:"button",variant:"ghost",size:"sm",onClick:n,"aria-label":"Load all history",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load all history"}):null]})})},H$=p.memo(O$),V4="The following tool was executed by the user",P1=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},F$=e=>{const t=e.info;return typeof t.parentID=="string"&&t.parentID.length>0?t.parentID:null},$4=e=>!e||P1(e)!=="user"?!1:e.parts.some(t=>{if(t?.type!=="text")return!1;const n=t.text;return t.synthetic===!0&&typeof n=="string"&&n.trim().startsWith(V4)}),z4=(e,t)=>{if(P1(e)!=="assistant")return{hide:!1,details:null};if(t&&F$(e)!==t)return{hide:!1,details:null};if(e.parts.length!==1)return{hide:!1,details:null};const n=e.parts[0];if(n?.type!=="tool")return{hide:!1,details:null};if((typeof n.tool=="string"?n.tool.toLowerCase():"")!=="bash")return{hide:!1,details:null};const s=typeof n.state?.input?.command=="string"?n.state.input.command:void 0,o=(typeof n.state?.output=="string"?n.state.output:void 0)??(typeof n.state?.metadata?.output=="string"?n.state.metadata.output:void 0),i=typeof n.state?.status=="string"?n.state.status:void 0;return{hide:!0,details:{command:s,output:o,status:i}}},B$=(e,t)=>{const n=e[t];if(!n)return null;const r=n.info.id;for(let s=t+1;s<e.length;s+=1){const o=e[s];if(P1(o)==="user")break;const{hide:i,details:a}=z4(o,r);if(i){const l=typeof a?.command=="string"?a.command.trim():"";return l.length>0?l:null}}return null},Ns=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},V$=e=>e.info.error?.name==="SessionRetry",$$=e=>{const t=e.text;if(typeof t=="string")return t;const n=e.content;return typeof n=="string"?n:""},z$=e=>{if(!e)return null;const t=e.info.id;return typeof t=="string"&&t.trim().length>0?t:null},U$=e=>{const t=e.info.parentID;return typeof t=="string"&&t.trim().length>0?t:null},q$=(e,t)=>{if(Ns(e)!=="system")return e;const r=U$(e);return!r||!t.has(r)||e.info.clientRole==="assistant"?e:{...e,info:{...e.info,clientRole:"assistant"}}},W$=e=>!e||Ns(e)!=="user"?!1:e.parts.some(t=>t?.type==="subtask"),K$=e=>{const t=e,n=t.state?.metadata,r=(typeof n?.sessionID=="string"&&n.sessionID.trim().length>0?n.sessionID.trim():null)??(typeof n?.sessionId=="string"&&n.sessionId.trim().length>0?n.sessionId.trim():null);if(r)return r;const s=t.state?.output;if(typeof s=="string"){const o=s.match(/task_id\s*:\s*([^\s<"']+)/i);if(o?.[1])return o[1]}return null},G$=e=>{if(Ns(e)!=="assistant")return{hide:!1,taskSessionId:null};if(e.parts.length!==1)return{hide:!1,taskSessionId:null};const t=e.parts[0];return t?.type!=="tool"?{hide:!1,taskSessionId:null}:(typeof t.tool=="string"?t.tool.toLowerCase():"")!=="task"?{hide:!1,taskSessionId:null}:{hide:!0,taskSessionId:K$(e.parts[0])}},Z$=(e,t)=>{if(!t)return e;const n=e.parts.map(r=>{if(r?.type!=="subtask")return r;const s=r.taskSessionID;return typeof s=="string"&&s.trim().length>0?r:{...r,taskSessionID:t}});return{...e,parts:n}},Y$=(e,t)=>{const n=typeof t?.command=="string"?t.command.trim():"",r=typeof t?.output=="string"?t.output:"",s=typeof t?.status=="string"?t.status.trim():"",o=[];let i=!1;for(const a of e.parts){if(!i&&a?.type==="text"){const l=a.text;if(a.synthetic===!0&&typeof l=="string"&&l.trim().startsWith(V4)){o.push({type:"text",text:"/shell",shellAction:{...n?{command:n}:{},...r?{output:r}:{},...s?{status:s}:{}}}),i=!0;continue}}o.push(a)}return i||o.push({type:"text",text:"/shell",shellAction:{...n?{command:n}:{},...r?{output:r}:{},...s?{status:s}:{}}}),{...e,parts:o}},uh=(e,t)=>t?e.userMessage.info.id===t?!0:e.assistantMessages.some(n=>n.info.id===t):!1,X$=40,J$=40,Q$=(e,t)=>{const n=e.reduce((a,l)=>a+(l.kind==="tool"?1:0),0),r=Math.max(0,t),s=Math.max(0,n-r);if(s===0)return{activities:e,hiddenToolCount:0};let o=s,i=0;for(let a=0;a<e.length&&!(e[a]?.kind==="tool"&&(o-=1,i=a+1,o===0));a+=1);return{activities:e.slice(i),hiddenToolCount:s}},ez=(e,t,n,r)=>n&&!r&&e.length>t.length?e:t,D1=({text:e,isStreaming:t,identityKey:n,allowTextReplacement:r=!1})=>{const s=p.useRef(n),o=p.useRef(e);if(s.current!==n)return s.current=n,o.current=e,e;if(!t)return o.current=e,e;const i=ez(o.current,e,!0,r);return o.current=i,i},tz=e=>e.isStreaming?e.throttledTextContent:e.textContent,nz=e=>!e.isFinalized&&e.displayTextContent.trim().length===0?!1:e.displayTextContent.trim().length>0,rz=({part:e,messageId:t,streamPhase:n,onShowPopup:r,withinActivityRail:s=!1})=>{const o=e,i=typeof o.text=="string"?o.text:"",a=typeof o.content=="string"?o.content:"",l=typeof o.value=="string"?o.value:"",d=[i,a,l].reduce((y,v)=>v.length>y.length?v:y,""),h=n==="streaming"||n==="cooldown";Is("ui.assistant_text_part.render"),h&&Is("ui.assistant_text_part.render.streaming");const m=D1({text:d,isStreaming:h,identityKey:`${t}:${e.id??"text"}`}),g=tz({textContent:d,throttledTextContent:m,isStreaming:h});YS("ui.assistant_text_part.display_len",g.length);const x=o.time,b=!!(x&&typeof x.end<"u");return!(e.type==="text"||e.type==="reasoning")||!nz({displayTextContent:g,isFinalized:b})?null:c.jsx("div",{className:R("group/assistant-text relative w-full min-w-0 break-words",s?"py-1":"pt-3 pb-1"),"data-chat-activity-text":s?"true":void 0,"data-chat-assistant-text":"true",children:c.jsx(Bo,{content:g,part:e,messageId:t,isAnimated:!1,isStreaming:h,variant:e.type==="reasoning"?"reasoning":"assistant",enableFileReferences:b,onShowPopup:r})},e.id||`${t}-text`)},U4=p.memo(rz),Av=300*1e3,Cd=({active:e,minDurationMs:t=300,className:n,children:r,style:s,title:o})=>{const i=p.useRef(e?Date.now():null),[a,l]=p.useState(e),d=p.useRef(null);e&&i.current===null&&(i.current=Date.now()),p.useEffect(()=>{if(e){if(d.current!==null&&(clearTimeout(d.current),d.current=null),i.current===null&&(i.current=Date.now()),Date.now()-i.current>=Av){l(!1),i.current=null;return}l(!0);return}if(!a){i.current=null;return}const u=i.current??Date.now(),h=Date.now()-u;if(h>=Av){l(!1),i.current=null;return}const m=Math.max(0,t-h);return d.current=setTimeout(()=>{l(!1),i.current=null,d.current=null},m),()=>{d.current!==null&&(clearTimeout(d.current),d.current=null)}},[e,t,a]);const f=p.useMemo(()=>{if(!a)return s;if(!s)return;const u={...s};return delete u.color,u},[a,s]);return c.jsxs("span",{className:R("transition-opacity duration-200",a&&"oc-shimmer-verb",n),style:f,title:o,children:[r,a&&typeof r=="string"?c.jsx(n3,{text:r}):null]})},sz="!text-[length:var(--text-markdown)] !leading-5 tracking-normal",Kr=R("typography-markdown font-medium",sz),Mt=R("typography-code font-mono","!text-[length:var(--text-code)] !leading-5 tracking-normal"),Op={...XS.getCollapsedStyles(),padding:0,overflow:"visible"},Nv={style:{background:"transparent",backgroundColor:"transparent"}},q4={color:"var(--status-error)"},W4={color:"var(--tools-icon)"},K4={color:"var(--status-error)"},Ps={color:"color-mix(in srgb, var(--tools-title) 72%, var(--tools-description))"},tJ=`
146
+ [data-diff-header],
147
+ [data-diff] {
148
+ [data-separator] {
149
+ height: 24px !important;
150
+ }
151
+ }
152
+ `,nJ={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},oz=e=>typeof e!="string"||e.trim().length===0?"":e.split(`
153
+ `).map(t=>t.replace(/^>\s?/,"").trimEnd()).filter(t=>t.trim().length>0).join(`
154
+ `).trim(),fh=80,iz=40,Lv=4e3,az=200,cz={duration:.2,ease:"easeOut"},G4=e=>e.replace(/<!--\s*-->/g,"").replace(/```[\w]*\n?([\s\S]*?)```/g,(t,n)=>n.trim()).replace(/`([^`]+)`/g,"$1").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^>\s?/gm,"").replace(/^[-*_]{3,}\s*$/gm,"").trim(),Z4=e=>{if(e.length<=fh)return e;const t=e.lastIndexOf(" ",fh),n=t>0?t:fh;return`${e.substring(0,n).trimEnd()}…`},lz=e=>{if(!e)return"";const t=G4(e).replace(/\s+/g," ").trim();return Z4(t)},dz=e=>{const t=e.trimEnd();if(!t)return"";const n=t.lastIndexOf(`
155
+ `),r=n===-1?t:t.slice(n+1);return Z4(G4(r).replace(/\s+/g," ").trim())},uz=e=>{let t=1,n=0;for(let s=e.length-1;s>=0;s-=1)if(e.charCodeAt(s)===10&&(t+=1,t>iz)){n=s+1;break}const r=n>0?e.slice(n):e;return r.length<=Lv?r:r.slice(-Lv)},fz=({text:e,variant:t,onContentChange:n,blockId:r,isStreaming:s=!1,actions:o,withinActivityRail:i=!1})=>{const[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=p.useRef(null),h=p.useRef(!0),m=p.useId(),g=p.useRef(s),x=p.useRef(null),b=p.useRef(null),S=p.useRef(!1),y=p.useRef(n);y.current=n;const v=p.useMemo(()=>s?dz(e):lz(e),[s,e]),C=a?"Collapse reasoning trace":"Expand reasoning trace",w=p.useCallback(()=>{f(!0),l(_=>!_),n?.("structural")},[n]),M=p.useCallback(_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),w())},[w]),j=p.useCallback(_=>{_.deltaY<0&&(h.current=!1)},[]),T=p.useCallback(_=>{const k=_.currentTarget;h.current=k.scrollHeight-k.scrollTop-k.clientHeight<=2},[]);if(p.useLayoutEffect(()=>{if(!s||!a){h.current=!0;return}const _=u.current;!_||!h.current||(_.scrollTop=_.scrollHeight)},[a,s,e]),p.useEffect(()=>{if(a){f(!0);return}if(!d)return;if(typeof window>"u"){f(!1);return}const _=window.setTimeout(()=>{f(!1)},az);return()=>{window.clearTimeout(_)}},[a,d]),p.useLayoutEffect(()=>{const _=x.current;if(!_)return;if(b.current?.stop(),!S.current){S.current=!0,_.style.height=a?"auto":"0px",_.style.overflow=a?"visible":"hidden";return}_.style.overflow="hidden",a?_.style.height="0px":(_.style.height=`${_.scrollHeight}px`,y.current?.("animation"));const k=l8(_,{height:a?"auto":"0px"},cz);return b.current=k,k.finished.then(()=>{b.current===k&&(b.current=null,a?(_.style.overflow="visible",_.style.height="auto"):_.style.overflow="hidden")}).catch(()=>{}),()=>{k.stop(),b.current===k&&(b.current=null)}},[a]),p.useEffect(()=>()=>{b.current?.stop(),b.current=null},[]),!e||e.trim().length===0)return null;const A=c.jsxs(c.Fragment,{children:[c.jsx("div",{"data-message-text-export-source":"true",children:s?c.jsx("div",{className:"markdown-content markdown-reasoning w-full min-w-0 whitespace-pre-wrap break-words",children:uz(e)}):c.jsx(Bo,{content:e,messageId:r,isAnimated:!1,isStreaming:!1,variant:"reasoning"})}),o?c.jsx("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5","data-message-actions":"true",children:c.jsx("div",{className:"flex items-center gap-1.5","data-message-action-group":"true",children:o})}):null]});return c.jsxs("div",{"data-reasoning-block-id":r,"data-message-text-export-root":"true",className:g.current?"oc-step-in":void 0,children:[c.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":a,"aria-controls":m,"aria-label":C,className:R("group/tool flex items-center gap-1.5 py-1 pr-2 pl-px cursor-pointer"),"data-chat-activity-row":"true",onClick:w,onKeyDown:M,children:[c.jsxs("div",{className:"flex h-5 items-center gap-1.5 flex-shrink-0",children:[c.jsxs("div",{className:"relative flex h-5 w-3.5 items-center justify-center",children:[c.jsx("div",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",a&&"opacity-0",!a&&"group-hover/tool:opacity-0"),style:{color:"var(--tools-icon)"},children:c.jsx($,{name:"brain-ai-3",className:"h-3.5 w-3.5"})}),c.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",a&&"opacity-100",!a&&"opacity-0 group-hover/tool:opacity-100"),style:{color:"var(--tools-icon)"},children:a?c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),c.jsx(Cd,{active:s,className:R("flex h-5 items-center typography-markdown font-medium text-[length:var(--text-markdown)] leading-none tracking-normal"),style:Ps,title:t==="justification"?"Justification":"Thinking",children:t==="justification"?"Justification":"Thinking"})]}),!a&&v?c.jsx("span",{className:R("flex h-5 flex-1 items-center min-w-0 truncate typography-code font-mono text-[length:var(--text-code)] leading-none tracking-normal"),style:{color:"var(--tools-description)",opacity:.8},title:v,children:v}):null]}),d?c.jsx("div",{ref:x,id:m,"aria-hidden":!a,style:{height:a?"auto":"0px",overflow:a?"visible":"hidden",overflowAnchor:"none"},children:c.jsxs("div",{className:R("relative pt-0.5",i?"pl-0 pb-0":"ml-2 pl-3 pb-1"),style:{opacity:a?1:0,transform:a?"translateY(0)":"translateY(-4px)",transition:"opacity 180ms ease-out, transform 180ms ease-out"},children:[i?null:c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),c.jsx(Xn,{ref:u,as:"div",outerClassName:"oc-reasoning-scroll max-h-80 w-full min-w-0",className:"p-0",useScrollShadow:!0,scrollShadowSize:36,userIntentOnly:!0,onWheelCapture:s?j:void 0,onScroll:s?T:void 0,children:A})]})}):null]})},hz=p.memo(({part:e,onContentChange:t,messageId:n,streamPhase:r,withinActivityRail:s=!1})=>{const o=e,i=o.text||o.content||"",a=p.useMemo(()=>oz(i),[i]),l=o.time,f=(r===void 0||r!=="completed")&&o.streaming===!0&&typeof l?.end!="number",u=D1({text:a,isStreaming:f,identityKey:`${n}:${e.id??"reasoning"}`});return!u||u.trim().length===0?null:c.jsx(fz,{text:u,variant:"thinking",onContentChange:t,blockId:e.id||`${n}-reasoning`,time:l,isStreaming:f,withinActivityRail:s})}),Rv=[{variant:"static",component:({children:e,className:t,...n})=>c.jsx("span",{...n,className:t,children:e})},{variant:"generate-effect",component:({children:e,className:t,...n})=>{if(e===null||typeof e>"u")return null;const r=typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(s=>typeof s=="string"||typeof s=="number"?String(s):"").join(""):"";return r?c.jsx("span",{className:R("inline-block align-baseline",t),children:r.split("").map((s,o)=>H.createElement(vc.span,{...n,key:s+String(o),className:R("inline-block whitespace-pre align-baseline"),initial:{opacity:0},animate:{opacity:1},transition:{ease:"easeOut",duration:.14,delay:Math.min(o*.0045,.14)}},s))}):null}},{variant:"glitch",component:({children:e,className:t,...n})=>c.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[c.jsx("span",{...n,className:R("invisible",t),children:e}),c.jsx("span",{...n,className:R("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",t),children:e}),c.jsx("span",{...n,className:R("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",t),children:e})]})},{variant:"hover-enter",component:({children:e,className:t,...n})=>{if(typeof e!="string")return null;const r=.25,s=.025,o=e.split("").map(i=>i===" "?" ":i);return c.jsxs(vc.span,{...n,className:R("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",t),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[c.jsx("div",{children:o.map((i,a)=>c.jsx(vc.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:r,ease:"easeInOut",delay:s*a},children:i},String(a)))}),c.jsx("div",{className:R("absolute inset-0"),children:o.map((i,a)=>c.jsx(vc.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:r,ease:"easeInOut",delay:s*a},children:i},String(a)))})]})}},{variant:"shake",component:({children:e,className:t,...n})=>c.jsx("span",{...n,className:R("text-primary-muted hover:animate-text-shake",t),children:e})},{variant:"hover-decoration",component:({children:e,className:t,...n})=>c.jsx("div",{className:R("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:c.jsx("span",{...n,className:R("text-primary-muted",t),children:e})})}];function pr({variant:e="static",className:t,...n}){const s=Rv.find(o=>o.variant===e)?.component||Rv[0].component;return c.jsx(s,{...n,className:t})}const pz=600*1e3,Hp=new Map,mz=e=>{const t=Wt(e);if(!t)return;const n=Hp.get(t);if(n){if(n.expiresAt<=Date.now()){Hp.delete(t);return}return n.outsideFileGrant}},Pv=(e,t,n)=>{const r=Wt(e);!r||!t||Hp.set(r,{outsideFileGrant:t,expiresAt:Date.now()+pz})},gz=async(e,t)=>{const n=Wt(e);if(!n||!t||mu(n,t))return;const r=mz(n);if(r)return r;const s=await JS(n);if(!(!s.success||!s.path||!s.outsideFileGrant))return Pv(s.path,s.outsideFileGrant),Wt(s.path)!==n&&Pv(n,s.outsideFileGrant),s.outsideFileGrant},Y4=(e,t)=>{const n=e.trim();if(n){if(Dr.getState().setSelectedSkill(n),te.getState().setSettingsPage("skills.installed"),t){t.openSettings("skills.installed");return}te.getState().setSettingsDialogOpen(!0)}},Dv=e=>{if(!e)return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null},Ov=e=>{const t=e?.state?.status;return typeof t=="string"?t:null},Hv=e=>e?.state,Fv=e=>e?.metadata,Qc=e=>{const t=e?.time;return{start:typeof t?.start=="number"?t.start:null,end:typeof t?.end=="number"?t.end:null}},Bv=e=>{const t=e;if(!t)return"";const n=typeof t.text=="string"?t.text:"",r=typeof t.content=="string"?t.content:"",s=typeof t.value=="string"?t.value:"";return[n,r,s].reduce((o,i)=>i.length>o.length?i:o,"")},bu=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.type!==s.type)return!1;const o=Dv(r),i=Dv(s);if(o!==i)return!1;if(r.type==="tool"){if(Hv(r)!==Hv(s)||Fv(r)!==Fv(s)||Ov(r)!==Ov(s))return!1;const d=Qc(r),f=Qc(s);if(d.start!==f.start||d.end!==f.end)return!1;const u=r.tool,h=s.tool;if(u!==h)return!1;const m=r.output,g=s.output;if(m!==g)return!1;continue}const a=Qc(r),l=Qc(s);if(a.start!==l.start||a.end!==l.end)return!1;if(r.type==="file"){const d=r,f=s;if(d.filename!==f.filename||d.mime!==f.mime||d.url!==f.url||d.size!==f.size)return!1}if(r.type==="text"||r.type==="reasoning"){if(Bv(r)!==Bv(s))return!1;const d=r.shellAction,f=s.shellAction;if((d||f)&&(d?.command!==f?.command||d?.output!==f?.output||d?.status!==f?.status))return!1}}return!0},X4=(e,t)=>e===t?!0:e.id===t.id&&e.role===t.role&&e.sessionID===t.sessionID&&e.finish===t.finish&&e.status===t.status&&e.mode===t.mode&&e.agent===t.agent&&e.providerID===t.providerID&&e.modelID===t.modelID&&e.variant===t.variant&&e.clientRole===t.clientRole&&e.userMessageMarker===t.userMessageMarker&&(e.time?.created??null)===(t.time?.created??null)&&(e.time?.completed??null)===(t.time?.completed??null)&&e.render===t.render&&e.bashExecution===t.bashExecution,J4=(e,t)=>X4(e.info,t.info)&&e.info.error===t.info.error&&bu(e.parts,t.parts),kd=(e,t)=>e===t?!0:!e||!t?!1:X4(e.info,t.info),yz=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files,vz=(e,t)=>{if(e===t)return!0;if(!e||!t)return!e&&!t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(r.file!==s.file||r.additions!==s.additions||r.deletions!==s.deletions)return!1}return!0},O1=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&bu([e.part],[t.part]),xz=(e,t,n)=>{let r=0,s=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.messageId!==n;)r+=1;for(;s<(t?.length??0)&&t?.[s]?.messageId!==n;)s+=1;const o=e?.[r],i=t?.[s];if(!o||!i)return o===i;if(!O1(o,i))return!1;r+=1,s+=1}},bz=(e,t)=>{if(e.id!==t.id||e.anchorMessageId!==t.anchorMessageId||e.afterToolPartId!==t.afterToolPartId||e.parts.length!==t.parts.length)return!1;for(let n=0;n<e.parts.length;n+=1)if(!O1(e.parts[n],t.parts[n]))return!1;return!0},Vv=(e,t)=>!!e?.some(n=>n.anchorMessageId===t),wz=(e,t,n)=>{let r=0,s=0;for(;;){for(;r<(e?.length??0)&&e?.[r]?.anchorMessageId!==n;)r+=1;for(;s<(t?.length??0)&&t?.[s]?.anchorMessageId!==n;)s+=1;const o=e?.[r],i=t?.[s];if(!o||!i)return o===i;if(!bz(o,i))return!1;r+=1,s+=1}},Q4=(e,t,n,r)=>{if(e===t)return!0;if(!e||!t)return e===t;if(r)return!0;if(e.turnId!==t.turnId||e.isFirstAssistantInTurn!==t.isFirstAssistantInTurn||e.isLastAssistantInTurn!==t.isLastAssistantInTurn||e.isLatestTurn!==t.isLatestTurn||e.isWorking!==t.isWorking||e.hasTools!==t.hasTools||e.hasReasoning!==t.hasReasoning||e.userMessageCreatedAt!==t.userMessageCreatedAt||e.userMessageVariant!==t.userMessageVariant||(e.headerMessageId===n||t.headerMessageId===n)&&e.headerMessageId!==t.headerMessageId)return!1;const o=e.activityOwnerMessageId===n||t.activityOwnerMessageId===n;if(o&&e.activityOwnerMessageId!==t.activityOwnerMessageId||!xz(e.activityParts,t.activityParts,n)||!wz(e.activityGroupSegments,t.activityGroupSegments,n))return!1;const i=Vv(e.activityGroupSegments,n)||Vv(t.activityGroupSegments,n);return!((o||i)&&!yz(e.diffStats,t.diffStats)||(o||i||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!vz(e.changedFiles,t.changedFiles))},Md=new Map,Sz=e=>{const t=Md.get(e);if(t)return t;const n={subscribers:new Set,timerId:null};return Md.set(e,n),n},Cz=(e,t)=>{const n=Sz(e);return n.subscribers.add(t),t(Date.now()),n.timerId===null&&typeof window<"u"&&(n.timerId=window.setInterval(()=>{const r=Date.now();n.subscribers.forEach(s=>{s(r)})},e)),()=>{const r=Md.get(e);r&&(r.subscribers.delete(t),!(r.subscribers.size>0)&&(r.timerId!==null&&typeof window<"u"&&window.clearInterval(r.timerId),Md.delete(e)))}},e7=(e,t=250)=>{const[n,r]=p.useState(()=>Date.now());return p.useEffect(()=>{if(e)return Cz(t,r)},[e,t]),n},$v=e=>typeof e!="string"?null:e.trim()||null,kz=e=>{const t=e.tool?.trim().toLowerCase(),n=e.state,r=n?.input&&typeof n.input=="object"?n.input:void 0;if(t==="skill")return $v(r?.name);if(t!=="read")return null;const s=n?.metadata?.pichamber;if(!s||typeof s!="object")return null;const o=s.skill;return!o||typeof o!="object"?null:$v(o.name)},_a=e=>{const t="h-3.5 w-3.5 flex-shrink-0",n=e.toLowerCase();return n==="edit"||n==="multiedit"||n==="apply_patch"||n==="str_replace"||n==="str_replace_based_edit_tool"?c.jsx($,{name:"pencil",className:t}):n==="write"||n==="create"||n==="file_write"?c.jsx($,{name:"file-edit",className:t}):n==="read"||n==="view"||n==="file_read"||n==="cat"?c.jsx($,{name:"file-text",className:t}):n==="bash"||n==="shell"||n==="cmd"||n==="terminal"?c.jsx($,{name:"terminal-box",className:t}):n==="list"||n==="ls"||n==="dir"||n==="list_files"?c.jsx($,{name:"folder-6",className:t}):n==="search"||n==="grep"||n==="find"||n==="ripgrep"?c.jsx($,{name:"menu-search",className:t}):n==="glob"?c.jsx($,{name:"file-search",className:t}):n==="fetch"||n==="curl"||n==="wget"||n==="webfetch"?c.jsx($,{name:"global",className:t}):n==="web-search"||n==="websearch"||n==="search_web"||n==="codesearch"||n==="google"||n==="bing"||n==="duckduckgo"||n==="perplexity"?c.jsx($,{name:"global",className:t}):n==="todowrite"||n==="todoread"?c.jsx($,{name:"list-check-3",className:t}):n==="structuredoutput"||n==="structured_output"?c.jsx($,{name:"list-check-2",className:t}):n==="skill"?c.jsx($,{name:"book",className:t}):n==="task"?c.jsx($,{name:"ai-agent",className:t}):n==="pichamber"?c.jsx($,{name:"pichamber",className:t}):n==="question"?c.jsx($,{name:"survey",className:t}):n==="lsp"?c.jsx($,{name:"scan-2",className:t}):n==="plan_enter"?c.jsx($,{name:"file-list-2",className:t}):n==="plan_exit"?c.jsx($,{name:"task",className:t}):n.startsWith("git")?c.jsx($,{name:"git-branch",className:t}):c.jsx($,{name:"tools",className:t})},Mz=({href:e})=>{const[t,n]=p.useState(!1),r=p.useMemo(()=>lT(e),[e]);return!r||t?null:c.jsx("span",{className:"inline-flex size-[18px] flex-shrink-0 items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)]",children:c.jsx("img",{src:r,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",className:"size-3.5 rounded-sm",onError:()=>n(!0)})})},Iz=e=>{if(e.kind!=="tool")return!1;const n=e.part.state?.status||void 0;return n==="completed"||n==="error"||n==="aborted"||n==="failed"||n==="timeout"||n==="cancelled"?!1:n==="running"||n==="pending"||n==="started"?!0:typeof e.endedAt!="number"},Ez=e=>{const n=e.part.state?.time;return{start:typeof n?.start=="number"?n.start:void 0,end:typeof n?.end=="number"?n.end:e.endedAt}},jz=(e,t,n=Date.now())=>{const r=Math.max(0,(t??n)-e)/1e3;return`${(r<.05&&typeof t=="number"?.1:r).toFixed(1)}s`},_z=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=r?.filePath||r?.file_path||r?.path||s?.filePath||s?.file_path||s?.path;if(typeof o=="string"&&o.trim().length>0){const i=o.lastIndexOf("/");return i>=0?o.slice(i+1):o}return null},Tz=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=r?.filePath||r?.file_path||r?.path||s?.filePath||s?.file_path||s?.path;return typeof o=="string"&&o.trim().length>0?o:null},Az=e=>{if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="pending"?"pending":t==="in_progress"||t==="in progress"||t==="inprogress"?"in_progress":t==="completed"||t==="done"?"completed":t==="cancelled"||t==="canceled"?"cancelled":null},Ii=e=>{if(e.length===0)return"0 tasks";let t=0,n=0;for(const s of e){if(!s||typeof s!="object")continue;const o=Az(s.status);o&&(o==="pending"&&(t+=1),o==="in_progress"&&(n+=1))}const r=t+n;return r===0?"0 tasks":`${r} ${r===1?"task":"tasks"}`},Nz=e=>{const n=e.part.state,r=n?.input,s=n?.output;if(Array.isArray(r?.todos)){const o=Ii(r.todos);if(o)return o}if(Array.isArray(s)){const o=Ii(s);if(o)return o}if(s&&typeof s=="object"&&Array.isArray(s.todos)){const o=Ii(s.todos);if(o)return o}if(typeof s=="string"&&s.trim().length>0)try{const o=JSON.parse(s);if(Array.isArray(o)){const i=Ii(o);if(i)return i}if(o&&typeof o=="object"&&Array.isArray(o.todos)){const i=Ii(o.todos);if(i)return i}}catch{}return null},Lz=e=>{const n=e.part.state,r=n?.input,s=n?.metadata,o=(typeof r?.offset=="number"&&Number.isFinite(r.offset)?r.offset:void 0)??(typeof r?.line=="number"&&Number.isFinite(r.line)?r.line:void 0)??(typeof s?.offset=="number"&&Number.isFinite(s.offset)?s.offset:void 0)??(typeof s?.line=="number"&&Number.isFinite(s.line)?s.line:void 0);if(!(typeof o!="number"||o<=0))return Math.floor(o)},Rz=(e,t=!0)=>{const n=e.lastIndexOf("/");if(n===-1)return c.jsx(pr,{variant:t?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-title)"},title:e,children:e});const r=e.slice(0,n),s=e.slice(n+1),o=r.startsWith("/"),i=o?r.slice(1):r;return c.jsxs("span",{className:R("min-w-0 inline-flex max-w-full flex-1 items-center overflow-hidden",Mt),title:e,children:[o?c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,c.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),c.jsx(pr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:s})]})},Pz=e=>{const t=e.part,n=t.tool?.toLowerCase()??"",r=t.state,s=r?.input,o=r?.metadata;if(n==="grep"||n==="search"||n==="find"||n==="ripgrep"){const i=s?.pattern;if(typeof i=="string"&&i.trim().length>0)return i.length>40?i.slice(0,40)+"...":i}if(n==="glob"){const i=s?.pattern;if(typeof i=="string"&&i.trim().length>0)return i.length>40?i.slice(0,40)+"...":i}if(n==="websearch"||n==="web-search"||n==="search_web"||n==="codesearch"||n==="perplexity"){const i=s?.query;if(typeof i=="string"&&i.trim().length>0)return i.length>50?i.slice(0,50)+"...":i}if(n==="skill"){const i=s?.name;if(typeof i=="string"&&i.trim().length>0)return i}if(n==="webfetch"||n==="fetch"||n==="curl"||n==="wget"){const i=typeof s?.url=="string"&&s.url||typeof s?.URL=="string"&&s.URL||typeof o?.url=="string"&&o.url||typeof o?.URL=="string"&&o.URL||"";if(typeof i=="string"&&i.trim().length>0)return i.trim()}return n==="todowrite"||n==="todoread"?Nz(e):_z(e)},Dz=({toolName:e,activity:t,animateTailText:n})=>{const r=p.useContext(Ra),s=Fa(),o=nt(A=>A.currentDirectory),i=Iz(t),a=Ez(t),l=typeof a.start=="number",d=e7(!!(l&&i&&typeof a.end!="number"),250),f=l?jz(a.start,a.end,d):null,u=Pz(t),h=kz(t.part),m=e.toLowerCase(),g=m==="skill"||m==="read"&&h!==null,x=m==="read"&&!g,b=g?"skill":e,S=Ha(b).displayName,y=_a(b),v=x?Tz(t):null,C=x?Lz(t):void 0,w=v?A3(v,o):null,M=p.useCallback((A,_)=>{const k=Ba(o,A);if(!k)return;if(r?.editor){r.editor.openFile(k,_);return}if(s){const N=te.getState(),O=o||Qf(o,k);_&&Number.isFinite(_)?N.openContextFileAtLine(O,k,Math.max(1,Math.trunc(_)),1):N.openContextFile(O,k),s.openFiles();return}if(!mu(k,o)){gz(k,o).then(()=>{const N=te.getState(),O=o||Qf(o,k);if(_&&Number.isFinite(_)){N.openContextFileAtLine(O,k,Math.max(1,Math.trunc(_)),1);return}N.openContextFile(O,k)});return}const E=te.getState(),I=Qf(o,k);if(_&&Number.isFinite(_)){E.openContextFileAtLine(I,k,Math.max(1,Math.trunc(_)),1);return}E.openContextFile(I,k)},[o,s,r]),j=m==="grep"||m==="search"||m==="find"||m==="ripgrep"||m==="glob",T=m==="webfetch"||m==="fetch"||m==="curl"||m==="wget";return c.jsxs("div",{className:R("oc-static-tool-row flex w-full items-center gap-x-1.5 pr-2 pl-px py-1 min-w-0"),"data-chat-activity-row":"true",children:[c.jsx("div",{className:"inline-flex h-5 items-center flex-shrink-0",style:{color:"var(--tools-icon)"},children:y}),c.jsx(Cd,{active:i,minDurationMs:1e3,className:R(Kr,"inline-flex items-center flex-shrink-0"),style:Ps,title:S,children:S}),x&&v&&w?c.jsxs("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),M(v,C)},className:R("inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left hover:text-[var(--status-info)] hover:opacity-90",Mt),style:{color:"var(--tools-description)"},title:C?`${w}:${C}`:w,children:[c.jsx(hr,{filePath:v,className:"h-3.5 w-3.5"}),Rz(w,n)]}):null,j&&u!==null?c.jsx("span",{className:"inline-flex min-w-0 flex-1",children:c.jsxs(pr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-description)"},title:u,children:['"',u,'"']})}):null,T&&u!==null?c.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:R("min-w-0 flex-1 inline-flex items-center gap-1.5 underline decoration-[color:var(--status-info)] underline-offset-2 hover:opacity-90","truncate whitespace-nowrap",Mt),style:{color:"var(--status-info)"},title:u,children:[c.jsx(Mz,{href:u}),c.jsx("span",{className:"min-w-0 truncate",children:u})]}):null,g&&h!==null?c.jsx("button",{type:"button",onClick:A=>{A.preventDefault(),A.stopPropagation(),Y4(h,s)},className:R("inline-flex !min-h-0 h-5 min-w-0 flex-1 items-center truncate whitespace-nowrap text-left hover:opacity-90",Mt),style:{color:"var(--tools-description)"},title:`Open ${h} in Settings`,"aria-label":`Open ${h} skill in Settings`,children:h}):null,!x&&!j&&!T&&!g&&u!==null?c.jsx(pr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",Mt),style:{color:"var(--tools-description)"},children:u}):null,f?c.jsx("span",{className:R("flex-shrink-0 tabular-nums text-muted-foreground/80",Mt),"aria-label":"Tool duration",children:f}):null]})},Oz=(e,t)=>e.toolName===t.toolName&&e.animateTailText===t.animateTailText&&O1(e.activity,t.activity),Hz=p.memo(Dz,Oz),Fz=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],rJ="diffs-container";(()=>{try{return!1}catch{return!1}})();const Bz=/(?=^From [a-f0-9]+ .+$)/m,t7=/(?=^diff --git)/gm,sJ=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: (.*))?/m,oJ=new RegExp("(?<=\\n)"),Vz=/^(---|\+\+\+)\s+([^\t\r\n]+)/,$z=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,zz=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,Uz=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,iJ="header-prefix",aJ="header-filename-suffix",cJ="header-metadata",lJ="header-custom",dJ={dark:"pierre-dark",light:"pierre-light"},uJ="data-theme-css",fJ="data-unsafe-css",hJ="data-diffs-scrollbar-measure",pJ="--diffs-scrollbar-gutter-measured",mJ=1e5,qz={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8};({...qz});const gJ=Object.freeze({fromStart:0,fromEnd:0}),yJ={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},vJ={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0};function zv(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}const Wz=new TextEncoder,Kz=new TextDecoder("utf-8",{ignoreBOM:!0}),Gz=/[\uD800-\uDFFF]/,Fp=1024;let go=new Uint8Array(Fp);function n7(){go.length!==Fp&&(go=new Uint8Array(Fp))}function Dt(e){if(e.length===0)return e;if(Gz.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;go.length<t&&(go=new Uint8Array(t));const{written:n}=Wz.encodeInto(e,go);return Kz.decode(go.subarray(0,n))}function Zz(e,t,n){try{return Yz(e,t,n)}finally{n7()}}function Yz(e,t,n=!1){const r=oU(e),s=r?Qz(e):eU(e);let o;const i=[];for(const a of s){if(r&&!t7.test(a)){if(o==null)o=Dt(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}else if(!r&&!tU(a)){if(o==null)o=Dt(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}const l=r7(a,{cacheKey:void 0,isGitDiff:r,throwOnError:n});l!=null&&i.push(l)}return{patchMetadata:o,files:i}}function xJ(e,t){try{return r7(e,t)}finally{n7()}}function r7(e,{cacheKey:t,isGitDiff:n=t7.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let i=0;const a=a7(e,"@@ ");let l;const d=r==null||s==null;let f=0,u=0;for(const h of a){const m=s7(h),g=m[0];if(g==null){if(o)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",h);continue}const x=i7(g);let b=0,S=0;if(x==null||l==null){if(l!=null){if(o)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",h);continue}l={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:d,additionLines:!d&&r!=null&&s!=null?Uv(s.contents):[],deletionLines:!d&&r!=null&&s!=null?Uv(r.contents):[],cacheKey:Kv(t)},l.additionLines.length===1&&s?.contents===""&&(l.additionLines.length=0),l.deletionLines.length===1&&r?.contents===""&&(l.deletionLines.length=0);for(const A of m){if(A.startsWith("diff --git")){const k=A.trim().match(zz),E=k?.[1]??k?.[2],I=k?.[3]??k?.[4];if(E==null||I==null){if(o)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",A);continue}l.name=Dt(I.trim()),E!==I&&(l.prevName=Dt(E.trim()));continue}const _=A.startsWith("---")||A.startsWith("+++")?A.match(n?$z:Vz):null;if(_!=null){const[,k,E]=_;if(k==="---"&&E!=="/dev/null"){const I=Dt(E.trim());l.prevName=I,l.name=I}else k==="+++"&&E!=="/dev/null"&&(l.name=Dt(E.trim()))}else if(n){if(A.startsWith("new mode ")&&(l.mode=Dt(A.slice(8).trim())),A.startsWith("old mode ")&&(l.prevMode=Dt(A.slice(8).trim())),A.startsWith("new file mode")&&(l.type="new",l.mode=Dt(A.slice(13).trim())),A.startsWith("deleted file mode")&&(l.type="deleted",l.mode=Dt(A.slice(17).trim())),A.startsWith("similarity index")&&(A.startsWith("similarity index 100%")?l.type="rename-pure":l.type="rename-changed"),A.startsWith("index ")){const[,k,E,I]=A.trim().match(Uz)??[];k!=null&&(l.prevObjectId=Dt(k)),E!=null&&(l.newObjectId=Dt(E)),I!=null&&(l.mode=Dt(I))}A.startsWith("rename from ")&&(l.prevName=Dt(A.slice(12).trim())),A.startsWith("rename to ")&&(l.name=Dt(A.slice(10).trim()))}}continue}let y,v;for(;m.length>0&&(m[m.length-1]===`
156
+ `||m[m.length-1]==="\r"||m[m.length-1]===`\r
157
+ `||m[m.length-1]==="");)m.pop();const{additionStart:C,deletionStart:w}=x;f=d?f:w-1,u=d?u:C-1;const M={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:x.additionCount,additionStart:C,additionLines:b,deletionCount:x.deletionCount,deletionStart:w,deletionLines:S,deletionLineIndex:f,additionLineIndex:u,hunkContent:[],hunkContext:Kv(x.hunkContext),hunkSpecs:Dt(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let j=0,T=0;for(let A=1;A<m.length;A++){const _=m[A];if(j>=M.additionCount&&T>=M.deletionCount&&!_.startsWith("\\")){if(o&&nU(_)&&!rU(_))throw Error("parsePatchContent: hunk has more lines than expected");break}const k=_[0];if(k!=="+"&&k!=="-"&&k!==" "&&k!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${k}", full line: "${_}"`),console.error("processFile: invalid rawLine:",_);continue}const E=iU(k);if(E==="addition"){if(o&&j>=M.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const I=hh(_);(y==null||y.type!=="change")&&(y=ph("change",f,u),M.hunkContent.push(y)),u++,j++,d&&l.additionLines.push(I),y.additions++,b++,v="addition"}else if(E==="deletion"){if(o&&T>=M.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const I=hh(_);(y==null||y.type!=="change")&&(y=ph("change",f,u),M.hunkContent.push(y)),f++,T++,d&&l.deletionLines.push(I),y.deletions++,S++,v="deletion"}else if(E==="context"){if(o&&(T>=M.deletionCount||j>=M.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const I=hh(_);(y==null||y.type!=="context")&&(y=ph("context",f,u),M.hunkContent.push(y)),u++,f++,j++,T++,d&&(l.deletionLines.push(I),l.additionLines.push(I)),y.lines++,v="context"}else if(E==="metadata"&&y!=null){if(y.type==="context"?(M.noEOFCRAdditions=!0,M.noEOFCRDeletions=!0):v==="deletion"?M.noEOFCRDeletions=!0:v==="addition"&&(M.noEOFCRAdditions=!0),d&&(v==="addition"||v==="context")){const I=l.additionLines.length-1;I>=0&&(l.additionLines[I]=zv(l.additionLines[I]))}if(d&&(v==="deletion"||v==="context")){const I=l.deletionLines.length-1;I>=0&&(l.deletionLines[I]=zv(l.deletionLines[I]))}}}if(o&&(j!==M.additionCount||T!==M.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");M.additionLines=b,M.deletionLines=S,M.collapsedBefore=Math.max(M.additionStart-1-i,0),l.hunks.push(M),i=M.additionStart+M.additionCount-1;for(const A of M.hunkContent)A.type==="context"?(M.splitLineCount+=A.lines,M.unifiedLineCount+=A.lines):(M.splitLineCount+=Math.max(A.additions,A.deletions),M.unifiedLineCount+=A.deletions+A.additions);M.splitLineStart=l.splitLineCount+M.collapsedBefore,M.unifiedLineStart=l.unifiedLineCount+M.collapsedBefore,l.splitLineCount+=M.collapsedBefore+M.splitLineCount,l.unifiedLineCount+=M.collapsedBefore+M.unifiedLineCount}if(l!=null){if(o&&d&&!n&&l.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(l.hunks.length>0&&!d&&l.additionLines.length>0&&l.deletionLines.length>0){const h=l.hunks[l.hunks.length-1],m=h.additionStart+h.additionCount-1,g=l.additionLines.length,x=Math.max(g-m,0);l.splitLineCount+=x,l.unifiedLineCount+=x}return n||(l.prevName!=null&&l.name!==l.prevName?l.hunks.length>0?l.type="rename-changed":l.type="rename-pure":(r==null||r.contents==="")&&s!=null&&s.contents!==""?l.type="new":r!=null&&r.contents!==""&&(s==null||s.contents==="")&&(l.type="deleted")),l.type!=="rename-pure"&&l.type!=="rename-changed"&&(l.prevName=void 0),l}}function Xz(e,t,n=!1){const r=[],s=Jz(e)?e.split(Bz):[e];for(const o of s)try{r.push(Zz(o,t!=null?`${t}-${r.length}`:void 0,n))}catch(i){if(n)throw i;console.error(i)}return r}function Jz(e){return e.startsWith("From ")||e.includes(`
158
+ From `)}function Uv(e){const t=s7(e);for(let n=0;n<t.length;n++)t[n]=Dt(t[n]);return t}function s7(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const r=e.indexOf(`
159
+ `,n);if(r===-1)break;t.push(e.slice(n,r+1)),n=r+1}return n<e.length&&t.push(e.slice(n)),t}function Qz(e){return a7(e,"diff --git")}function eU(e){if(e.length===0)return[""];const t=[];let n=0,r=0,s=0,o=0,i=!1;for(;r<e.length;){const a=Bp(e,r);if(s<=0&&o<=0){if(o7(e,r)){r>n&&t.push(e.slice(n,r)),n=r,i=!0,r=Bp(e,a);continue}if(i&&e.startsWith("@@ -",r)){const d=i7(e.slice(r,a));d!=null&&(s=d.deletionCount,o=d.additionCount)}r=a;continue}const l=e[r];if(l==="\\"){r=a;continue}l===" "?(s=Math.max(s-1,0),o=Math.max(o-1,0)):l==="-"?s=Math.max(s-1,0):l==="+"&&(o=Math.max(o-1,0)),r=a}return t.push(e.slice(n)),t}function tU(e){return o7(e,0)}function o7(e,t){const n=Bp(e,t);return qv(e,t,"---")&&qv(e,n,"+++")}function qv(e,t,n){if(!e.startsWith(n,t))return!1;const r=e[t+n.length];if(r!==" "&&r!==" ")return!1;for(let s=t+n.length+1;s<e.length;s++){const o=e[s];if(o===`
160
+ `||o==="\r")break;if(o!==" "&&o!==" ")return!0}return!1}function Bp(e,t){const n=e.indexOf(`
161
+ `,t);return n===-1?e.length:n+1}function nU(e){const t=e[0];return t==="+"||t==="-"||t===" "}function rU(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
162
+ `&&n!=="\r")return!1}return!0}function i7(e){if(!e.startsWith("@@ -"))return;let t=4;const n=el(e,t);if(n==null)return;const r=n.value;t=n.endIndex;let s=1;if(e[t]===","){const f=el(e,t+1);if(f==null)return;s=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const o=el(e,t);if(o==null)return;const i=o.value;t=o.endIndex;let a=1;if(e[t]===","){const f=el(e,t+1);if(f==null)return;a=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let l;const d=t+3;return e[d]===" "&&(l=sU(e.slice(d+1))),{additionCount:a,additionStart:i,deletionCount:s,deletionStart:r,hunkContext:l}}function el(e,t){let n=t,r=0;for(;n<e.length;n++){const s=e.charCodeAt(n)-48;if(s<0||s>9)break;r=r*10+s}if(n!==t)return{value:r,endIndex:n}}function sU(e){return e.endsWith(`\r
163
+ `)?e.slice(0,-2):e.endsWith(`
164
+ `)?e.slice(0,-1):e}function oU(e){return e.startsWith("diff --git")||e.includes(`
165
+ diff --git`)}function a7(e,t){if(e.length===0)return[""];const n=`
166
+ ${t}`,r=e.startsWith(t)?0:Wv(e,n,0);if(r===-1)return[e];const s=[];r>0&&s.push(e.slice(0,r));let o=r;for(;;){const i=Wv(e,n,o+1);if(i===-1)break;s.push(e.slice(o,i)),o=i}return s.push(e.slice(o)),s}function Wv(e,t,n){const r=e.indexOf(t,n);return r===-1?-1:r+1}function Kv(e){return e==null?e:Dt(e)}function iU(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function hh(e){const t=e.slice(1);return Dt(t===""?`
167
+ `:t)}function ph(e,t,n){return e==="change"?{type:"change",additions:0,deletions:0,additionLineIndex:n,deletionLineIndex:t}:{type:"context",lines:0,additionLineIndex:n,deletionLineIndex:t}}const c7=/^\*\*\*\s+(?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)/m,Id=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,aU=/(?=^diff --git\s+)/gm,l7=/^diff --git\s+/m,cU=/(?=^---\s+\S)/gm,d7=/^---\s+\S/m,Gr=e=>typeof e=="object"&&e!==null,lU=e=>e.replace(/\r\n/g,`
168
+ `).replace(/\r/g,`
169
+ `).trim(),dU=e=>{let t=!1;return e.split(`
170
+ `).map(n=>{if(n.startsWith("@@"))return t=!0,n;if(t)return n;const r=n.match(/^\s*(---|\+\+\+)\s+(.+)$/);if(!r)return n;const s=r[1],o=r[2]??"";return o.trim()==="/dev/null"?`${s} /dev/null`:`${s} ${o.replace(/\\/g,"/")}`}).join(`
171
+ `)},uU=e=>{let t=!1;return e.split(`
172
+ `).map(n=>{if(n.startsWith("@@"))return t=!0,n;if(!t||n.startsWith("--- ")||n.startsWith("+++ ")||n.startsWith("diff --git"))return n;if(n.length===0)return" ";const r=n[0];return r===" "||r==="+"||r==="-"||r==="\\"?n:` ${n}`}).join(`
173
+ `)},Gv=(e,t)=>t===1?e:`${e},${t}`,fU=e=>{const t=e.split(`
174
+ `),n=[...t];for(let r=0;r<t.length;r+=1){const o=(t[r]??"").match(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@(.*)$/);if(!o)continue;let i=0,a=0;for(let l=r+1;l<t.length;l+=1){const d=t[l]??"";if(d.startsWith("@@")||d.startsWith("--- ")||d.startsWith("diff --git"))break;if(!d.startsWith("\\")){if(d.startsWith("+")){a+=1;continue}if(d.startsWith("-")){i+=1;continue}i+=1,a+=1}}n[r]=`@@ -${Gv(o[1]??"0",i)} +${Gv(o[2]??"0",a)} @@${o[3]??""}`}return n.join(`
175
+ `)},u7=e=>fU(uU(dU(lU(e)))),Ut=e=>{if(typeof e=="string")return/\S/.test(e)?e:void 0;if(Gr(e)){const t=e.patch;if(typeof t=="string")return/\S/.test(t)?t:void 0}},$a=e=>Gr(e)?typeof e.movePath=="string"?e.movePath:typeof e.filePath=="string"?e.filePath:typeof e.relativePath=="string"?e.relativePath:null:null,H1=(e,t,n)=>{if(e==="apply_patch"){const r=Array.isArray(n?.files)?n.files:[];for(const s of r)if(Gr(s)&&s.type!=="delete"){const o=$a(s);if(o)return o}return null}if(e==="edit"||e==="multiedit"){const r=Gr(n?.filediff)?n.filediff:void 0;return r&&typeof r.file=="string"?r.file:typeof t?.filePath=="string"?t.filePath:typeof t?.file_path=="string"?t.file_path:typeof t?.path=="string"?t.path:null}return e==="write"?typeof t?.filePath=="string"?t.filePath:typeof t?.file_path=="string"?t.file_path:typeof t?.path=="string"?t.path:null:null},hU=(e,t,n)=>{if(e==="apply_patch"){const s=Array.isArray(n?.files)?n.files:[],o=new Set;for(const i of s){if(!Gr(i))continue;const a=$a(i);a&&o.add(a),i.type==="move"&&typeof i.filePath=="string"&&o.add(i.filePath)}return[...o]}const r=H1(e,t,n);return r?[r]:[]},pU=e=>e==="edit"||e==="multiedit"||e==="apply_patch",Zv=(e,t)=>{const n=Array.isArray(e.files)?e.files:[];if(!t){const r=n[0];return Gr(r)?r:void 0}return n.find(r=>Gr(r)&&(r.relativePath===t||r.filePath===t||r.movePath===t))},ua=e=>{if(!e)return;let t,n;for(const r of e.split(`
176
+ `)){const s=r.replace(/\r$/,""),o=s.match(/^@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/);if(o){const i=Number.parseInt(o[1]??"",10);Number.isFinite(i)&&(t=Math.max(1,i),n??=t);continue}if(t!==void 0&&!(s.startsWith("+++")||s.startsWith("---")||s.startsWith("diff "))){if(s.startsWith("+"))return t;s.startsWith(" ")&&(t+=1)}}return n},Yv=(e,t,n)=>{if(!t||!pU(e))return;if(n){const i=Zv(t,n),a=Ut(i?.patch)??Ut(i?.diff);if(a){const l=ua(a);if(l!==void 0)return l}}const r=Ut(t.patch)??Ut(t.diff);if(r){const i=ua(r);if(i!==void 0)return i}const s=Zv(t),o=Ut(s?.patch)??Ut(s?.diff);return o?ua(o):void 0},mU=e=>{const t=(e??"").trim().replace(/\t.*$/,"");return!t||t==="/dev/null"?"":t.replace(/^[ab]\//,"")},gU=e=>{const t=e.trim().replace(/\s+/g,"-");return t.length>0?t:"file"},yU=e=>{let t=!1;for(const n of e.split(`
177
+ `)){if(n.startsWith("@@")){if(!Id.test(n))return!1;t=!0;continue}if(!t||n.length===0)continue;const r=n[0];if(r!==" "&&r!=="+"&&r!=="-"&&r!=="\\")return!1}return!0},mh=e=>{const t=u7(e);if(!t||c7.test(t)||!Id.test(t)||!yU(t))return null;try{const n=Xz(t,void 0,!0);if(n.length!==1)return null;const r=n[0]?.files??[],s=r[0];return r.length!==1||!s||s.hunks.length===0?null:{patch:t,title:mU(s.name)}}catch{return null}},vU=e=>{const t=l7.test(e),n=d7.test(e);return!t&&!n?[]:e.split(t?aU:cU).map(r=>r.trim()).filter(r=>r.length>0)},Xv=(e,t,n,r)=>{const s=u7(e);if(!s)return[];const o=mh(s);if(o){const a=o.title?r(o.title):r(t);return[{id:`${n}-0`,title:a,patch:o.patch,renderMode:"diff"}]}const i=[];for(const a of vU(s)){const l=mh(a),d=l?.title?r(l.title):r(t);if(!l){(Id.test(a)||l7.test(a)||d7.test(a))&&i.push({id:`${n}-${i.length}`,title:d,patch:a,renderMode:"text"});continue}i.push({id:`${n}-${i.length}`,title:d,patch:l.patch,renderMode:"diff"})}if(i.length>0)return i;if(!c7.test(s)&&Id.test(s)){const a=gU(t),l=mh(`--- ${a}
178
+ +++ ${a}
179
+ ${s}`);if(l)return[{id:`${n}-0`,title:r(t),patch:l.patch,renderMode:"diff"}]}return[{id:`${n}-0`,title:r(t),patch:s,renderMode:"text"}]},xU=e=>{if(!Gr(e))return null;const t=Ut(e.patch)??Ut(e.diff);if(!t)return null;const n=typeof e.relativePath=="string"?e.relativePath:typeof e.filePath=="string"?e.filePath:"";return{filePath:$a(e)??void 0,patch:t,title:n}},bU=(e,t,n)=>{const s=(Array.isArray(e?.files)?e.files:[]).flatMap((i,a)=>{const l=xU(i);return l?Xv(l.patch,l.title||`File ${a+1}`,`file-${a}`,n).map(d=>({...d,filePath:l.filePath})):[]});return s.length>0?s:Xv(typeof t=="string"?t:"","Diff","fallback",n)},wU=new Set(["read","skill"]),Ds=e=>{if(typeof e!="string")return"";const t=e.trim().toLowerCase();if(!t)return"";const n=t.replace(/:\d+$/,"");if(n.includes(".")){const r=n.split(".").filter(Boolean);return r[r.length-1]??n}return n},SU=e=>!CU(e),CU=e=>wU.has(Ds(e)),kU=(e,t,n)=>{if(typeof t=="string"&&t.trim().length>0)return t;const r=Ds(e)==="glob"?n?.pattern:void 0;return typeof r=="string"?r:""},MU=(e,t)=>{const n=t.replace(/\r\n/g,`
180
+ `);if(!n.trim())return;const r=(()=>{const a=(e??"").trim();return a?a.startsWith("/")?a.slice(1):a:"new-file"})(),s=n.split(`
181
+ `),o=s.length,i=s.map(a=>`+${a}`).join(`
182
+ `);return["--- /dev/null",`+++ b/${r}`,`@@ -0,0 +1,${o} @@`,i].join(`
183
+ `)},Ed=e=>{const t=e.trim().replace(/\\/g,"/").replace(/\/{2,}/g,"/");return!t||t==="/"?t:t.replace(/\/+$/,"")},Gn=(e,t)=>{const n=Ed(e),r=Ed(t);if(!n)return"";if(!r)return n;if(n===r)return".";const s=`${r}/`;return n.startsWith(s)?n.slice(s.length):n},IU=5,fa=e=>typeof e=="object"&&e!==null,EU=e=>{if(!fa(e))return null;const t=typeof e.message=="string"?e.message.trim():"";if(!t)return null;const n=typeof e.severity=="number"&&Number.isFinite(e.severity)?Math.trunc(e.severity):void 0;if(n!==void 0&&n!==1)return null;const r=fa(e.range)?e.range:void 0,s=r&&fa(r.start)?r.start:void 0,o=typeof s?.line=="number"&&Number.isFinite(s.line)?Math.max(0,Math.trunc(s.line)):0,i=typeof s?.character=="number"&&Number.isFinite(s.character)?Math.max(0,Math.trunc(s.character)):0;return{message:t,line:o+1,character:i+1}},jU=(e,t,n,r)=>{if(!["edit","multiedit","write","apply_patch"].includes(e))return null;const s=H1(e,t,n);if(!s||!n||!fa(n.diagnostics))return null;const o=Ed(s),i=o.startsWith("/")?o:`${Ed(r)}/${o}`.replace(/\/+/g,"/"),a=n.diagnostics[o]??n.diagnostics[i];if(!Array.isArray(a))return null;const l=a.map(f=>EU(f)).filter(f=>!!f);if(l.length===0)return null;const d=l.slice(0,IU);return{displayPath:o.startsWith("/")?Gn(o,r):o,diagnostics:d,remaining:Math.max(0,l.length-d.length)}},_U=e=>{const t=e.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!t)return null;const n=[],r=t[1],s=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let o;for(;(o=s.exec(r))!==null;)n.push({question:o[1],answer:o[2]});return n.length>0?n:null},TU=e=>{const t=Ut(e?.patch)??Ut(e?.diff);if(!t)return null;let n=0,r=0,s=0;for(let o=0;o<=t.length;o+=1){if(o<t.length&&t.charCodeAt(o)!==10)continue;const i=t.slice(s,o);i.startsWith("+")&&!i.startsWith("+++")&&n++,i.startsWith("-")&&!i.startsWith("---")&&r++,s=o+1}return n===0&&r===0?null:{added:n,removed:r}},AU=e=>{if(!e?.content||typeof e.content!="string")return null;let t=1;for(let n=0;n<e.content.length;n+=1)e.content.charCodeAt(n)===10&&(t+=1);return t},f7=(e,t,n)=>{const r=t,s=r.metadata,o=r.input;if(e.tool==="apply_patch"){const i=Array.isArray(s?.files)?s?.files:[],a=i[0],l=a?.relativePath||a?.filePath;return i.length>1?null:typeof l=="string"?Gn(l,n):null}if((e.tool==="edit"||e.tool==="multiedit")&&o){const i=o?.filePath||o?.file_path||o?.path||s?.filePath||s?.file_path||s?.path;if(typeof i=="string")return Gn(i,n)}if(e.tool==="read"&&o){const i=o?.filePath||o?.file_path||o?.path||s?.filePath||s?.file_path||s?.path;if(typeof i=="string")return Gn(i,n)}if(e.tool&&["write","create","file_write"].includes(e.tool)&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Gn(i,n)}if(e.tool==="lsp"&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Gn(i,n)}return null},NU=(e,t)=>{if(!e)return"";const n=typeof e.operation=="string"?e.operation:"lsp";if(n==="workspaceSymbol"){const l=typeof e.query=="string"&&e.query.trim().length>0?` "${e.query.trim()}"`:"";return`${n}${l}`}const r=typeof e.filePath=="string"?e.filePath:typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:"",s=r?Gn(r,t):"";if(n==="documentSymbol")return s?`${n} ${s}`:n;const o=typeof e.line=="number"&&Number.isFinite(e.line)?Math.trunc(e.line):void 0,i=typeof e.character=="number"&&Number.isFinite(e.character)?Math.trunc(e.character):void 0,a=o!==void 0&&i!==void 0?`:${o}:${i}`:"";return s?`${n} ${s}${a}`:n},LU=(e,t,n)=>{const r=t,s=r.metadata,o=r.input,i=f7(e,t,n);if(i)return i;if(e.tool==="apply_patch"){const l=Array.isArray(s?.files)?s?.files:[];return l.length>1?`${l.length} files`:""}if(e.tool==="question"&&o?.questions&&Array.isArray(o.questions)){const l=o.questions.length;return`Asked ${l} question${l!==1?"s":""}`}if(e.tool==="bash"&&o?.command&&typeof o.command=="string")return o.command.split(`
184
+ `)[0].substring(0,100);if(e.tool==="task"&&o?.description&&typeof o.description=="string")return o.description.substring(0,80);if(e.tool==="lsp")return NU(o,n);const a=o?.description||s?.description||"title"in t&&t.title||"";return kU(e.tool,a,o)},h7=e=>{const t=e.state?.title;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.state?.input;if(n&&typeof n=="object"){const r=n.filePath??n.file_path??n.path;if(typeof r=="string"&&r.trim().length>0)return r.trim();const s=n.url;if(typeof s=="string"&&s.trim().length>0)return s.trim()}return""},Uo=e=>{const t=Ds(e.tool),n=e.state?.status??"",r=h7(e);return`${e.id??""}${t}${n}${r}`},RU=({isTaskTool:e,isExpanded:t,isActive:n,hasFinalMetadataSummary:r,taskSessionId:s})=>e&&!!s&&!r&&(t||n),qo=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},Jv=e=>{if(!e||typeof e!="object")return;const t=e;return qo(t.sessionID)??qo(t.sessionId)},p7=e=>{if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n=="string"){t.push({tool:"tool",state:{status:"completed",title:n}});continue}if(!n||typeof n!="object")continue;const r=n;t.push({id:typeof r.id=="string"?r.id:void 0,tool:typeof r.tool=="string"?r.tool:"tool",state:{status:typeof r.state?.status=="string"?r.state.status:typeof r.status=="string"?r.status:void 0,title:typeof r.state?.title=="string"?r.state.title:typeof r.title=="string"?r.title:void 0,input:r.state?.input&&typeof r.state.input=="object"?r.state.input:void 0}})}return t},m7=e=>{if(typeof e!="string"||e.trim().length===0)return{summaryEntries:[]};const t=e.match(/<task_metadata>\s*([\s\S]*?)\s*<\/task_metadata>/i);if(!t?.[1])return{summaryEntries:[]};try{const n=JSON.parse(t[1].trim());return{sessionId:qo(n.sessionId)??qo(n.sessionID),summaryEntries:p7(n.summary??n.entries??n.tools??n.calls)}}catch{return{summaryEntries:[]}}},PU=e=>{if(typeof e!="string"||e.trim().length===0)return;const t=m7(e);if(t.sessionId)return t.sessionId;const n=e.match(/task_id\s*:\s*([^\s<"']+)/i),r=e.match(/session[_\s-]?id\s*:\s*([^\s<"']+)/i),s=n?.[1]??r?.[1];return qo(s||Fz(e))},Qv=new WeakMap,DU=e=>e.type==="tool",OU=e=>{const t=Qv.get(e);if(t)return t;const n=[];if(e.info.role==="assistant")for(const r of e.parts){if(!DU(r))continue;const s=r.tool?.trim().toLowerCase();if(!s||s==="task"||s==="todowrite"||s==="todoread")continue;const o=r.state;n.push({id:r.id,tool:r.tool,state:{status:o?.status,title:o?.title,input:o?.input&&typeof o.input=="object"?o.input:void 0}})}return Qv.set(e,n),n},HU=e=>{const t=[];for(const n of e)t.push(...OU(n));return t},FU=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),ex=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e));if(typeof e=="string"){const t=Number.parseInt(e,10);return Number.isFinite(t)?Math.max(0,t):null}return null},tx=(e,t)=>e===null?t:t===null?e:e+t,BU=e=>{const t=Array.isArray(e?.files)?e.files:[],n=new Map;for(const r of t){if(!r||typeof r!="object")continue;const s=r,o=typeof s.relativePath=="string"?s.relativePath:typeof s.filePath=="string"?s.filePath:"";if(!o)continue;const i=ex(s.additions),a=ex(s.deletions),l=n.get(o);if(l){l.added=tx(l.added,i),l.removed=tx(l.removed,a);continue}n.set(o,{file:s,path:o,name:o.split("/").pop()||o,added:i,removed:a})}return Array.from(n.values())},VU=({animate:e=!0,metadata:t,onFileClick:n,openDiffLabel:r,showFileIcons:s=!0,textClassName:o})=>{const i=BU(t);return i.length<=1?null:c.jsx(c.Fragment,{children:i.map(a=>{const l=a.added!==null||a.removed!==null,d=c.jsxs(c.Fragment,{children:[s?c.jsx(hr,{filePath:a.path,className:"h-3.5 w-3.5"}):null,c.jsx(pr,{variant:e?"generate-effect":"static",className:R("min-w-0 max-w-full truncate",o),style:{color:"var(--tools-description)"},title:a.path,children:a.name}),l?c.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.added??0]}),c.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.removed??0]})]}):null]}),f=n&&a.file.type!=="delete"&&$a(a.file),u=`${r}: ${a.path}`;return f?c.jsx(Se,{variant:"ghost",size:"xs",className:R("min-w-0 max-w-full gap-1 normal-case font-normal tracking-normal",o),"aria-label":u,title:u,onClick:h=>n(a.file,h),children:d},a.path):c.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1",o),style:{color:"var(--tools-description)"},children:d},a.path)})})},$U=({currentDirectory:e,editor:t,file:n})=>{const r=$a(n);if(!r||n.type==="delete")return!1;const s=Ut(n.patch)??Ut(n.diff),o=s?ua(s):void 0,i=Ba(e,r);return t.openFile(i,o),!0},g7=({children:e,animate:t,className:n})=>c.jsx("div",{className:R(t&&"oc-step-in",n),children:e}),F1=({children:e,maxHeightClass:t="max-h-[60vh]",className:n,outerClassName:r,disableHorizontal:s=!1,followKey:o})=>{const i=p.useRef(null),a=p.useRef(!0);return p.useLayoutEffect(()=>{const l=i.current;if(o===void 0){a.current=!0;return}!l||!a.current||(l.scrollTop=l.scrollHeight)},[o]),c.jsx("div",{className:R("w-full min-w-0 flex-none overflow-hidden",r),children:c.jsx(fu,{ref:i,"data-scrollable":"true",onWheelCapture:l=>{o!==void 0&&l.deltaY<0&&(a.current=!1)},onScroll:l=>{if(o===void 0)return;const d=l.currentTarget;a.current=d.scrollHeight-d.scrollTop-d.clientHeight<=2},className:R("tool-output-surface p-2 rounded-xl w-full min-w-0",t,s?"overflow-y-auto overflow-x-hidden":"overflow-auto",n),children:c.jsx("div",{className:"w-full min-w-0",children:e})})})},nx=({path:e,grow:t=!0})=>{const n=e.lastIndexOf("/");if(n===-1)return c.jsx("span",{className:R("min-w-0 truncate typography-ui-label text-foreground",t&&"flex-1"),style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:e,children:e});const r=e.slice(0,n),s=e.slice(n+1),o=r.startsWith("/"),i=o?r.slice(1):r;return c.jsxs("span",{className:R("min-w-0 flex items-baseline overflow-hidden typography-ui-label",t&&"flex-1"),title:e,children:[o?c.jsx("span",{className:"flex-shrink-0 text-muted-foreground",children:"/"}):null,c.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),c.jsxs("span",{className:"flex-shrink-0",children:[c.jsx("span",{className:"text-muted-foreground",children:"/"}),c.jsx("span",{className:"text-foreground",children:s})]})]})},Vp=({path:e,animate:t=!0,grow:n=!0,showFileIcons:r=!0})=>{const s=e.lastIndexOf("/");if(s===-1)return c.jsxs("span",{className:R("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?c.jsx(hr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsx(pr,{variant:t?"generate-effect":"static",className:R("min-w-0 truncate whitespace-nowrap",Mt,n&&"flex-1"),style:{color:"var(--tools-title)"},children:e})]});const o=e.slice(0,s),i=e.slice(s+1),a=o.startsWith("/"),l=a?o.slice(1):o;return c.jsxs("span",{className:R("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?c.jsx(hr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,c.jsxs("span",{className:R("min-w-0 inline-flex max-w-full items-baseline overflow-hidden",Mt,n&&"flex-1"),children:[a?c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,c.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:l}),c.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),c.jsx(pr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:i})]})]})},zU=new Set(["read","view","file_read","cat","write","create","file_write","edit","multiedit","apply_patch"]),UU=(e,t)=>{if(!zU.has(e.toLowerCase()))return!1;const n=t.trim();if(!n||n==="Patch"||/^\d+\s+files$/.test(n))return!1;if(n.includes("/")||n.includes("\\"))return!0;const r=n.split(/[\\/]/).pop()||n;return r.startsWith(".")||r.includes(".")?!0:/^[A-Za-z0-9_-]+$/.test(r)},qU=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(Uo(e[n])!==Uo(t[n]))return!1;return!0},y7=p.memo(({entry:e,isMobile:t,animateTailText:n})=>{const r=Ds(e.tool),s=r.length>0?r:"tool",o=h7(e),i=o.trim().length>0,a=e.state?.status,l=Ha(s).displayName;return c.jsx(g7,{animate:n,children:c.jsxs("div",{className:R("flex gap-2 min-w-0 w-full",a==="error"&&t?"items-start":"items-center"),children:[c.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:_a(s)}),c.jsx("span",{className:R(Kr,"text-foreground/80 flex-shrink-0"),style:Ps,title:l,children:l}),i?a!=="error"&&UU(s,o)?c.jsx(Vp,{path:o,animate:n,showFileIcons:!0}):a==="error"?c.jsx("span",{className:R(Mt,"flex-1 min-w-0 text-[var(--status-error)]",t?"whitespace-normal break-words":"truncate"),children:o}):c.jsx(pr,{variant:n?"generate-effect":"static",className:R(Mt,"flex-1 min-w-0 truncate text-muted-foreground/70"),style:{color:"var(--tools-description)"},title:o,children:o}):null]})})},(e,t)=>e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&Uo(e.entry)===Uo(t.entry));y7.displayName="TaskSummaryEntryRow";const v7=p.memo(({entries:e,isExpanded:t,isMobile:n,animateTailText:r})=>{const s=t?e:e.slice(-6),o=Math.max(0,e.length-s.length),i=e.length-s.length;return c.jsx(F1,{maxHeightClass:t?"max-h-[40vh]":"max-h-[min(17.5rem,45vh)]",disableHorizontal:!0,children:c.jsxs("div",{className:"w-full min-w-0 space-y-1","data-chat-task-entries-list":"true",children:[o>0?c.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",o," more…"]}):null,s.map((a,l)=>{const d=t?l:i+l,f=a.id??`${Uo(a)}:${d}`;return c.jsx(y7,{entry:a,isMobile:n,animateTailText:r},f)})]})})},(e,t)=>e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&qU(e.entries,t.entries));v7.displayName="TaskSummaryEntriesList";const WU=({entries:e,isExpanded:t,isMobile:n,output:r,sessionId:s,onShowPopup:o,input:i,animateTailText:a=!0,isActive:l=!1})=>{const d=Qn(),f=pe(S=>S.setCurrentSession),u=typeof r=="string"?FU(r):"",h=u.length>0,[m,g]=p.useState(!1),x=S=>{S.stopPropagation(),s&&d&&f(s,d)},b=typeof i?.subagent_type=="string"?i.subagent_type:"subagent";return e.length===0&&!h&&!s?c.jsx("div",{className:"oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",children:c.jsx("div",{className:"typography-meta text-muted-foreground/70",children:l?"Waiting for subagent activity...":"No subagent session id on task metadata."})}):c.jsxs("div",{className:R("oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-[var(--tools-border)] before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:[e.length>0?c.jsx(v7,{entries:e,isExpanded:t,isMobile:n,animateTailText:a}):null,s&&c.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:S=>S.stopPropagation(),onClick:x,children:[c.jsx($,{name:"external-link",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"typography-meta text-primary font-medium",children:`Open ${b.charAt(0).toUpperCase()+b.slice(1)} subtask`})]}),h?c.jsxs("div",{className:R("space-y-1",(e.length>0||s)&&"pt-1"),children:[c.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),g(y=>!y)},children:[m?c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0"}):c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?c.jsx(F1,{maxHeightClass:"max-h-[50vh]",children:c.jsx("div",{className:"w-full min-w-0",children:c.jsx(Oa,{content:u,variant:"tool",onShowPopup:o})})}):null]}):null]})},KU=e=>{const t=e.colors.syntax.base,n=e.colors.syntax.tokens??{},r=e.colors.status;return{"--md-syntax-foreground":t.foreground,"--md-syntax-comment":t.comment,"--md-syntax-string":t.string,"--md-syntax-number":t.number,"--md-syntax-keyword":t.keyword,"--md-syntax-operator":t.operator,"--md-syntax-function":t.function,"--md-syntax-type":t.type,"--md-syntax-variable":t.variable,"--md-syntax-property":n.variableProperty??t.variable,"--md-syntax-inserted":r.success,"--md-syntax-deleted":r.error}},GU="/assets/markdown-shiki.worker-BVA5NZBT.js";let zn,ZU=0;const Ta=new Map,$p=new Set,rx=()=>{Ta.forEach(e=>e(null)),Ta.clear(),$p.clear(),zn?.terminate(),zn=void 0},YU=()=>{if(zn)return zn;if(!(typeof window>"u"||typeof Worker>"u")){try{zn=new Worker(GU,{type:"module"})}catch(e){console.error("Failed to create Shiki worker:",e);return}return zn.onmessage=e=>{const t=Ta.get(e.data.id);t&&(Ta.delete(e.data.id),t(e.data))},zn.onerror=rx,zn.onmessageerror=rx,zn.postMessage({type:"init"}),zn}},B1=e=>{const t=YU();if(!t)return Promise.resolve(null);const n=++ZU;return new Promise(r=>{Ta.set(n,r),t.postMessage(e(n))})},XU=async(e,t)=>{const n=await B1(r=>({type:"highlight",id:r,code:e,lang:t}));return n?.type==="highlight"?n.html:null},bJ=async(e,t)=>{const n=await B1(r=>({type:"highlightLines",id:r,code:e,lang:t}));return n?.type==="highlightLines"?n.lines:null},wJ=async(e,t,n,r)=>{const s=!$p.has(n),o=await B1(i=>({type:"highlightTokens",id:i,code:e,lang:t,themeName:n,...s?{theme:r}:{}}));return o?.type==="highlightTokens"?($p.add(n),o.lines):null},JU=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),QU=e=>e?Object.entries(e).map(([t,n])=>n==null?"":`${t.startsWith("--")?t:t.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`)}:${typeof n=="number"?`${n}px`:n};`).join(""):"",sx=(e,t,n)=>{const r=e.querySelector("pre");r&&(r.style.margin="0",r.style.background="transparent",r.style.whiteSpace=t?"pre-wrap":"pre",t&&(r.style.wordBreak="break-word",r.style.overflowWrap="break-word"));const s=e.querySelector("code");if(s){const o=QU(n);o&&s.setAttribute("style",`${s.getAttribute("style")??""}${o}`)}},eq=e=>`<pre><code>${JU(e)}</code></pre>`,jd=({code:e,language:t,className:n,style:r,codeStyle:s,wrap:o=!1})=>{const{currentTheme:i}=Jn(),a=p.useRef(null),l=p.useMemo(()=>KU(i),[i]);return p.useLayoutEffect(()=>{const d=a.current;d&&(d.innerHTML=eq(e),sx(d,o,s))},[e,o,s]),p.useEffect(()=>{const d=a.current;if(!d)return;let f=!0;return XU(e,(t||"text").toLowerCase()).then(u=>{!f||!d||!u||(d.innerHTML=u,sx(d,o,s))}),()=>{f=!1}},[e,t,o,s]),c.jsx("div",{ref:a,className:R("typography-code",n),style:{...l,...r}})},tq={maxDepth:50,maxNodes:1e5,initiallyExpandedDepth:2};function nq(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="object"?"object":typeof e=="string"?"string":typeof e=="number"?"number":typeof e=="boolean"?"boolean":"null"}function rq(e){if(e.length===0)return"root";let t="root";for(const n of e)/^\d+$/.test(n)?t+=`[${n}]`:t+=`.${n}`;return t}let zp=0;function x7(e,t,n,r,s){if(zp>=s.maxNodes)return null;zp++;const o=nq(e),i=rq(n),a=o==="object"||o==="array",l={id:i,key:t,value:e,type:o,depth:r,path:n,isExpandable:a};if(a&&r<s.maxDepth){const d=o==="array"?e.map((f,u)=>[String(u),f]):Object.entries(e);l.childCount=d.length,l.children=[];for(const[f,u]of d){const h=[...n,f],m=x7(u,f,h,r+1,s);m&&l.children.push(m)}}else a&&(l.childCount=o==="array"?e.length:Object.keys(e).length);return l}function sq(e,t){const n={...tq,...t};zp=0;try{const r=e.trim();if(!r)return null;const s=JSON.parse(r);return x7(s,"root",[],0,n)}catch{return null}}function oq(e,t){if(!e)return[];const n=[];function r(s){const o=!t.has(s.id);if(n.push({node:s,isExpanded:o}),s.isExpandable&&o&&s.children)for(const i of s.children)r(i)}return r(e),n}function iq(e){if(!e)return[];const t=[];function n(r){if(r.isExpandable&&(t.push(r.id),r.children))for(const s of r.children)n(s)}return n(e),t}function aq(e,t){if(!e)return[];const n=[];function r(s){if(s.isExpandable&&s.depth>=t&&n.push(s.id),s.children)for(const o of s.children)r(o)}return r(e),n}const ox=["var(--syntax-key)","color-mix(in oklch, var(--syntax-key) 85%, var(--syntax-string))","color-mix(in oklch, var(--syntax-key) 70%, var(--syntax-number))","color-mix(in oklch, var(--syntax-key) 55%, var(--syntax-function))","color-mix(in oklch, var(--syntax-key) 40%, var(--syntax-type))","color-mix(in oklch, var(--syntax-key) 30%, var(--syntax-keyword))"];function cq(e){return ox[e%ox.length]}function lq(e){switch(e.type){case"string":return"var(--syntax-string)";case"number":return"var(--syntax-number)";case"boolean":return"var(--syntax-keyword)";case"null":return"var(--syntax-comment)";default:return"var(--surface-foreground)"}}function Up(e){switch(e.type){case"string":{const t=e.value;return t.length>60?`"${t.slice(0,57)}..."`:`"${t}"`}case"number":case"boolean":return String(e.value);case"null":return"null";case"object":return`{${e.childCount??0} ${e.childCount===1?"item":"items"}}`;case"array":return`[${e.childCount??0}]`;default:return String(e.value)}}function dq(e){if(e.type==="object"){const t=e.children?.map(r=>r.key).slice(0,3)??[],n=(e.childCount??0)>3?", ...":"";return`{ ${t.map(r=>`"${r}": ...`).join(", ")}${n} }`}if(e.type==="array"){const t=e.childCount??0;return t<=3?`[${e.children?.map(r=>Up(r)).join(", ")??""}]`:`[${t} items]`}return Up(e)}const qp=p.memo(({flatNode:e,onToggle:t,onCopyPath:n})=>{const{node:r,isExpanded:s}=e,o=r.depth*20,i=p.useCallback(()=>{t(r.id)},[t,r.id]),a=p.useCallback(u=>{n&&(u.preventDefault(),n(r.id))},[n,r.id]),l=cq(r.depth),d=lq(r),f=r.isExpandable&&r.children&&r.children.length>0;return c.jsxs("div",{className:"flex items-center py-0.5 px-2 hover:bg-[var(--surface-hover)] rounded-sm cursor-default font-mono text-xs leading-5 whitespace-nowrap",style:{paddingLeft:`${o+8}px`},onContextMenu:a,children:[f?c.jsx("button",{type:"button",onClick:i,className:"mr-1 flex h-4 w-4 shrink-0 items-center justify-center rounded-sm hover:bg-[var(--interactive-hover)] text-muted-foreground",children:s?c.jsx($,{name:"arrow-down-s",className:"h-3 w-3"}):c.jsx($,{name:"arrow-right-s",className:"h-3 w-3"})}):c.jsx("span",{className:"mr-1 w-4"}),r.key!=="root"&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"mr-1 font-semibold",style:{color:l},children:/^\d+$/.test(r.key)?r.key:`"${r.key}"`}),c.jsx("span",{className:"mr-1 text-[var(--surface-foreground)]",children:":"})]}),r.isExpandable?s?c.jsx("span",{className:"text-[var(--surface-foreground)]",children:r.type==="object"?"{":"["}):c.jsx("span",{style:{color:"var(--surface-mutedForeground)"},children:dq(r)}):c.jsx("span",{style:{color:d},children:Up(r)})]})});qp.displayName="JsonRow";const uq=200,fq=22,hq=p.forwardRef(function({data:t,className:n,maxHeight:r="100%",initiallyExpandedDepth:s=2,onCopyPath:o},i){const a=p.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]),l=p.useMemo(()=>a?sq(a):null,[a]),[d,f]=p.useState(()=>l?new Set(aq(l,s)):new Set),u=p.useMemo(()=>oq(l,d),[l,d]),h=u.length>uq,m=p.useRef(null),g=T5({count:u.length,enabled:h,getScrollElement:()=>m.current,estimateSize:()=>fq,overscan:20,getItemKey:y=>u[y]?.node.id??y}),x=p.useCallback(y=>{f(v=>{const C=new Set(v);return C.has(y)?C.delete(y):C.add(y),C})},[]),b=p.useCallback(()=>{f(new Set)},[]),S=p.useCallback(()=>{l&&f(new Set(iq(l)))},[l]);return p.useImperativeHandle(i,()=>({expandAll:b,collapseAll:S}),[b,S]),l?h?c.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:c.jsx("div",{style:{height:g.getTotalSize(),position:"relative"},children:g.getVirtualItems().map(y=>{const v=u[y.index];return v?c.jsx("div",{"data-index":y.index,ref:g.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${y.start}px)`},children:c.jsx(qp,{flatNode:v,onToggle:x,onCopyPath:o})},v.node.id):null})})}):c.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:u.map(y=>c.jsx(qp,{flatNode:y,onToggle:x,onCopyPath:o},y.node.id))}):null}),pq=({mode:e,onModeChange:t,className:n})=>{const r=p.useCallback(s=>{s.stopPropagation(),t(e==="side-by-side"?"unified":"side-by-side")},[e,t]);return c.jsx(Se,{size:"sm",variant:"ghost",className:R("h-5 w-5 p-0 opacity-60 hover:opacity-100",n),onClick:r,title:e==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:e==="side-by-side"?c.jsx($,{name:"align-justify",className:"h-3 w-3"}):c.jsx($,{name:"layout-column",className:"h-3 w-3"})})},mq=e=>{let t=e.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return t=t.replace(/^\s*\d{5}\|\s?/gm,""),t.trim()},vn=(e,t="")=>{if(typeof e=="string")return e;if(e==null)return t;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{return JSON.stringify(e)}catch{return t}},gq=e=>e?e.includes("<diagnostics")||e.includes("<file_diagnostics>")||e.includes("LSP errors detected")||e.includes("This file has errors"):!1,yq=e=>e?e.replace(/\n{0,2}LSP errors detected[\s\S]*?<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,"").replace(/\n{0,2}This file has errors[\s\S]*?<\/file_diagnostics>/g,"").replace(/<diagnostics[^>]*>[\s\S]*?<\/diagnostics>/g,"").replace(/<file_diagnostics>[\s\S]*?<\/file_diagnostics>/g,"").trim():"",ix=(e,t)=>!e||typeof e!="object"?String(e):uR(e,t||""),tl=e=>{if(typeof e=="string"){const t=e.trim();return t.length>0?t:void 0}if(e&&typeof e=="object"){const t=e.patch;if(typeof t=="string"){const n=t.trim();return n.length>0?n:void 0}}},vq=e=>{if(!e||typeof e!="object")return;const t=tl(e.patch)??tl(e.diff);if(t)return t;const n=Array.isArray(e.files)?e.files:[];for(const r of n){if(!r||typeof r!="object")continue;const s=tl(r.patch)??tl(r.diff);if(s)return s}},xq=e=>{if(!e||typeof e!="string")return{data:null,isJson:!1};const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return{data:null,isJson:!1};if(!t.endsWith("}")&&!t.endsWith("]"))return{data:null,isJson:!1};if(t.length<2)return{data:null,isJson:!1};try{const n=JSON.parse(t);return n!==null&&typeof n=="object"?{data:n,isJson:!0}:{data:null,isJson:!1}}catch{return{data:null,isJson:!1}}},b7=(e,t,n)=>{let r=mq(e);if((t==="edit"||t==="multiedit"||t==="write"||t==="apply_patch")&&gq(r)&&(r=yq(r)),(t==="edit"||t==="multiedit"||t==="apply_patch")&&r.trim().length===0){const s=vq(n);if(s)return s}return r},SJ=e=>{const n=e.match(/<type>(file|directory)<\/type>/i)?.[1]?.toLowerCase()??"unknown",i=(e.match(/<content>([\s\S]*?)<\/content>/i)?.[1]??e).replace(/\r\n/g,`
185
+ `).split(`
186
+ `),a=f=>/\(\s*File has more lines\..*offset.*\)/i.test(f.trim()),d=i.map(f=>{const u=f.trim(),h=u.startsWith("(")&&u.endsWith(")")||a(u);if(n!=="directory"){const m=f.match(/^(\d+):\s?(.*)$/);if(m){const g=m[2],x=g.trim(),b=x.startsWith("(")&&x.endsWith(")")||a(x);return{lineNumber:b?null:Number(m[1]),text:g,isInfo:b}}}return{lineNumber:null,text:f,isInfo:h}}).filter((f,u,h)=>{if(f.text.trim().length>0)return!0;const m=h[u-1],g=h[u+1],x=!!(m?.isInfo||g?.isInfo),b=f.lineNumber!==null;return!(x&&b)});return{type:n,lines:d}},CJ=(e,t)=>{try{const n=e.trim().split(`
187
+ `).filter(Boolean);if(n.length===0)return null;const r=[];return n.forEach(s=>{const o=s.match(/^(\s*)(.+)$/);if(o){const[,i,a]=o,l=Math.floor(i.length/2),d=!a.endsWith("/");r.push({name:a.replace(/\/$/,""),depth:l,isFile:d})}}),c.jsx("div",{className:R("w-full min-w-0 font-mono space-y-0.5",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Aa.tool.popup,children:r.map((s,o)=>c.jsx("div",{className:"min-w-0",style:{paddingLeft:`${s.depth*20}px`},children:s.isFile?c.jsx("span",{className:"text-foreground/90 block truncate",children:s.name}):c.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[s.name,"/"]})},o))})}catch{return null}},bq={backgroundColor:"var(--status-info)",opacity:.6},kJ=(e,t,n)=>{try{const r=e.trim().split(`
188
+ `).filter(Boolean);if(r.length===0)return null;const s={};return r.forEach(o=>{const i=o.match(/^(.+?):(\d+):(.*)$/)||o.match(/^(.+?):(.*)$/);if(i){const[,a,l,d]=i,f=d!==void 0?l:"",u=d!==void 0?d:l;s[a]||(s[a]=[]),s[a].push({lineNum:f,content:u})}}),c.jsxs("div",{className:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Aa.tool.popup,children:[c.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," match",r.length!==1?"es":""]}),Object.entries(s).map(([o,i])=>c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:R("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:o}),c.jsx("div",{className:"pl-4 space-y-1",children:i.map((a,l)=>!a.lineNum&&!a.content?null:c.jsxs("div",{className:R("flex items-start gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[c.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:bq}),c.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[a.lineNum&&c.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",a.lineNum,":"]}),c.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:a.content||" "})]})]},l))})]},o))]})}catch{return null}},wq={backgroundColor:"var(--status-info)",opacity:.6},MJ=(e,t,n)=>{try{const r=e.trim().split(`
189
+ `).filter(Boolean);if(r.length===0)return null;const s={};r.forEach(i=>{const a=i.lastIndexOf("/"),l=a>0?i.substring(0,a):"/",d=a>=0?i.substring(a+1):i;s[l]||(s[l]=[]),s[l].push(d)});const o=Object.keys(s).sort();return c.jsxs("div",{className:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Aa.tool.popup,children:[c.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," file",r.length!==1?"s":""]}),o.map(i=>c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:R("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:[i,"/"]}),c.jsx("div",{className:R("pl-4 grid gap-1",t?"grid-cols-1":"grid-cols-2"),children:s[i].sort().map(a=>c.jsxs("div",{className:R("flex items-center gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[c.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:wq}),c.jsx("span",{className:"text-foreground font-mono truncate",children:a})]},a))})]},i))]})}catch{return null}},Sq=(e,t,n)=>{try{const r=JSON.parse(e);if(!Array.isArray(r))return null;const s=r.filter(a=>!!a&&typeof a=="object"&&typeof a.content=="string"&&typeof a.status=="string");if(s.length===0)return null;const o=s.reduce((a,l)=>{const d=l.status;return d in a&&a[d].push(l),a},{in_progress:[],pending:[],completed:[],cancelled:[]}),i=a=>{const l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return c.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return c.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return c.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return c.jsx("div",{className:l,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return c.jsxs("div",{className:R("space-y-3 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Aa.tool.popup,children:[c.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[c.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:[t.total,": ",s.length]}),o.in_progress.length>0&&c.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:[t.inProgress,": ",o.in_progress.length]}),o.pending.length>0&&c.jsxs("span",{style:{color:"var(--muted-foreground)"},children:[t.pending,": ",o.pending.length]}),o.completed.length>0&&c.jsxs("span",{style:{color:"var(--status-success)"},children:[t.completed,": ",o.completed.length]}),o.cancelled.length>0&&c.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:[t.cancelled,": ",o.cancelled.length]})]}),o.in_progress.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),c.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:t.inProgress})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.in_progress.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.pending.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),c.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:t.pending})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.pending.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.completed.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx($,{name:"check",className:"w-3 h-3",style:{color:"var(--status-success)"}}),c.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:t.completed})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.completed.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx($,{name:"check",className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),c.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]}),o.cancelled.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),c.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:t.cancelled})]}),c.jsx("div",{className:"space-y-1.5 pl-4",children:o.cancelled.map((a,l)=>c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),c.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:vn(a.content)})]},a.id||l))})]})]})}catch{return null}},IJ=(e,t)=>{try{return c.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Aa.tool.popup,children:c.jsx(Oa,{content:e,variant:"tool"})})}catch{return null}},Cq=(e,t,n)=>dR(t,e,n),kq=new Set(["id","identifier","title","name"]),Mq=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nl=e=>e.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^./,t=>t.toUpperCase()),Iq=e=>{const t=typeof e.id=="string"?e.id:typeof e.identifier=="string"?e.identifier:"",n=typeof e.title=="string"?e.title:typeof e.name=="string"?e.name:"";return t&&n?`${t} · ${n}`:n||t||null},Eq=e=>{try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},_d=p.memo(({value:e,label:t,depth:n})=>{if(Array.isArray(e)){const o=t?`${nl(t)} (${e.length})`:`(${e.length})`;return c.jsxs("details",{open:n<2,className:"group/json-summary",children:[c.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-1.5 py-1.5 typography-meta text-[var(--surface-foreground)] hover:text-[var(--surface-mutedForeground)]",children:[c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),c.jsx("span",{className:"min-w-0 truncate font-medium",children:o})]}),c.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),c.jsx("div",{className:"space-y-1",children:e.map((i,a)=>c.jsx(_d,{value:i,depth:n+1},a))})]})]})}if(Mq(e)){const o=Iq(e),i=Object.entries(e).filter(([d])=>!kq.has(d)),a=t?`${nl(t)}${o?` · ${o}`:""}`:o,l=c.jsx("div",{className:"space-y-1",children:i.map(([d,f])=>c.jsx(_d,{label:d,value:f,depth:n+1},d))});return!t&&n===0?c.jsxs("div",{className:"space-y-2",children:[o?c.jsx("div",{className:"typography-meta font-medium text-[var(--surface-foreground)]",children:o}):null,l]}):c.jsxs("details",{open:n<2,className:"group/json-summary",children:[c.jsxs("summary",{className:"flex cursor-pointer list-none items-center gap-1.5 py-1.5 typography-meta text-[var(--surface-foreground)] hover:text-[var(--surface-mutedForeground)]",children:[c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),c.jsx("span",{className:"min-w-0 truncate font-medium",children:a??(t?nl(t):"{}")})]}),c.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),l]})]})}const r=e===null?"null":typeof e=="boolean"?e?"true":"false":String(e),s=typeof e=="string"&&Eq(e)?c.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[var(--status-info)] underline underline-offset-2 hover:opacity-80",title:e,children:e}):c.jsx("span",{className:R("min-w-0 break-words",e===null?"text-[var(--surface-mutedForeground)]":"text-[var(--surface-foreground)]"),children:r});return c.jsxs("div",{className:"grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-2 py-1 typography-meta",children:[t?c.jsx("span",{className:"truncate text-[var(--surface-mutedForeground)]",title:t,children:nl(t)}):c.jsx("span",{}),s]})});_d.displayName="JsonSummaryValue";const Td=p.memo(({data:e})=>c.jsx("div",{className:"space-y-1",children:c.jsx(_d,{value:e,depth:0})}));Td.displayName="JsonSummaryView";const w7=({diff:e})=>c.jsx("pre",{className:"m-0 overflow-auto whitespace-pre-wrap break-words rounded-lg p-2 typography-code",style:{backgroundColor:"var(--syntax-base-background)",color:"var(--syntax-base-foreground)"},children:e}),S7=1e5,ax=(e,t,n)=>{const r=Math.max(0,t-e.length+1),s=S7-n.syntheticCells,o=Math.min(r,s),i=Math.min(t,e.length+o-1);for(;e.length<=i;)e.push([]);return n.syntheticCells+=o,i},jq=(e,t,n,r,s)=>{const o=e[t],i=S7-s.syntheticCells,a=Math.min(n,o.length+i),l=Math.max(0,a-o.length);for(;o.length<a;)o.push(" ");return s.syntheticCells+=l,o[a]=r,a},cx=e=>{if(!e.includes("\x1B")&&!e.includes("\r")&&!e.includes("\b"))return e;const t=[[]],n={syntheticCells:0};let r=0,s=0;for(let o=0;o<e.length;o+=1){const i=e[o];if(i===`
190
+ `){r+=1,s=0,t[r]??=[];continue}if(i==="\r"){s=0;continue}if(i==="\b"){s=Math.max(0,s-1);continue}if(i!=="\x1B"){s=jq(t,r,s,i,n)+1;continue}const a=e[o+1];if(a==="["){const l=o+2;let d=l;for(;d<e.length&&!/[\x40-\x7E]/.test(e[d]);)d+=1;if(d===e.length)break;const f=e[d],u=e.slice(l,d).split(";").map(m=>Number.parseInt(m,10)||0),h=u[0]||1;if(f==="A")r=Math.max(0,r-h);else if(f==="B")r=ax(t,r+h,n);else if(f==="C")s+=h;else if(f==="D")s=Math.max(0,s-h);else if(f==="G")s=Math.max(0,h-1);else if(f==="H"||f==="f")r=ax(t,Math.max(0,(u[0]||1)-1),n),s=Math.max(0,(u[1]||1)-1);else if(f==="K"){const m=t[r],g=u[0];if(g===1)for(let x=0;x<=s&&x<m.length;x+=1)m[x]=" ";else g===2?t[r]=[]:m.length=Math.min(m.length,s)}o=d;continue}if(a==="]"){const l=e.indexOf("\x07",o+2),d=e.indexOf("\x1B\\",o+2),f=l===-1?d:d===-1?l:Math.min(l,d);if(f===-1)break;o=e[f]==="\x07"?f:f+1;continue}o+=1}return t.map(o=>o.join("")).join(`
191
+ `)},_q=(e,t,n,r)=>{const s=e==="bash",o=s&&r!=="running";if(typeof t=="string")return o?cx(t):t;if(s&&typeof n=="string"&&n.length>0)return o?cx(n):n},Tq=(e,t)=>t.startsWith(e)?t.slice(e.length):void 0,C7=16,Aq=(e,t=C7)=>{if(t<=0||e.length===0)return e;let n=1;for(let r=e.length-1;r>=0;r-=1)if(e.charCodeAt(r)===10&&(n+=1,n>t))return e.slice(r+1);return e},Nq=(e,t,n,r)=>t.tool==="bash"?"bash":Cq(b7(e,t.tool||"",n),t.tool||"",r),Lq=(e,t,n)=>t.tool==="bash"?e:b7(e,t.tool||"",n),Rq=({output:e})=>{const t=p.useRef(null),n=p.useRef("");return p.useLayoutEffect(()=>{const r=t.current;if(!r)return;const s=r.firstChild,o=s instanceof globalThis.Text?s:document.createTextNode("");o!==s&&r.replaceChildren(o);const i=Aq(e,C7),a=Tq(n.current,i);a===void 0?o.data=i:a.length>0&&o.appendData(a),n.current=i},[e]),c.jsx("pre",{ref:t,className:"m-0 whitespace-pre-wrap break-words",style:{...Op,lineHeight:"round(var(--code-block-line-height), 1px)",overflowWrap:"break-word"}})},Wp=({output:e,part:t,metadata:n,input:r,isStreaming:s=!1})=>{const o=Lq(e,t,n),i=Nq(e,t,n,r),a=p.useMemo(()=>xq(o),[o]),[l,d]=p.useState("summary"),[f,u]=p.useState(!1);p.useEffect(()=>{d("summary"),u(!1)},[o]);const h=p.useCallback((g,x)=>{x.stopPropagation(),d(g)},[]),m=p.useCallback(async g=>{if(g.stopPropagation(),!(await gr(o)).ok){Ce.error("Failed to copy output");return}u(!0),typeof window<"u"&&window.setTimeout(()=>u(!1),1200)},[o]);return t.tool==="bash"&&s?c.jsx("div",{className:"typography-code text-muted-foreground/90",children:c.jsx(Rq,{output:o})}):a.isJson?c.jsxs("div",{className:"tool-output-surface relative p-2 rounded-xl w-full min-w-0",children:[c.jsxs("div",{className:"absolute right-2 top-2 z-10 flex items-center gap-1",children:[c.jsx(Se,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="summary"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("summary",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show navigable JSON",title:"Show navigable JSON",children:c.jsx($,{name:"list-unordered",className:"h-3.5 w-3.5"})}),c.jsx(Se,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="formatted"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("formatted",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show formatted JSON",title:"Show formatted JSON",children:c.jsx($,{name:"node-tree",className:"h-3.5 w-3.5"})}),c.jsx(Se,{variant:"ghost",size:"icon",className:R("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",l==="raw"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>h("raw",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show raw JSON",title:"Show raw JSON",children:c.jsx($,{name:"code-box",className:"h-3.5 w-3.5"})}),c.jsx(Se,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-md bg-[var(--surface-elevated)]/80 text-muted-foreground hover:text-foreground",onClick:m,onPointerDown:g=>g.stopPropagation(),"aria-label":f?"Copied output":"Copy output",title:f?"Copied output":"Copy output",children:c.jsx($,{name:f?"check":"file-copy",className:"h-3.5 w-3.5"})})]}),l==="summary"?c.jsx(Td,{data:a.data}):l==="formatted"?c.jsx(hq,{data:a.data,initiallyExpandedDepth:1,maxHeight:"400px"}):c.jsx("div",{className:"typography-code pr-12 text-muted-foreground/90",children:c.jsx(jd,{language:"json",code:o,style:Op,codeStyle:Nv.style,wrap:!0})})]}):c.jsx("div",{className:t.tool==="bash"?"typography-code text-muted-foreground/90":void 0,children:c.jsx(jd,{language:i,code:o,style:Op,codeStyle:Nv.style,wrap:!0})})};Wp.displayName="ToolScrollableTextOutput";const Pq=Rs(()=>mt(()=>import("./ToolPartDiffPreview-BigGwtul.js"),__vite__mapDeps([82,5,1,6,77,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,78,79,80,81,25,17,11,18,19,20,43,42]))),lx=({diff:e,diffViewMode:t})=>c.jsx(p.Suspense,{fallback:c.jsx(w7,{diff:e}),children:c.jsx(Pq,{diff:e,diffViewMode:t})}),k7=p.memo(({part:e,state:t,currentDirectory:n,isExpanded:r,onShowPopup:s})=>{const o=Fa(),[i,a]=p.useState("unified"),l=t,d=l.metadata,f=l.input,u=_q(e.tool||"",l.output,d?.output,t.status),h=typeof u=="string"&&u.length>0,m=typeof u=="string"?u:"",g=e.tool==="bash"&&t.status==="running",x=D1({text:m,isStreaming:g,identityKey:e.id,allowTextReplacement:g}),b=g?x:m,S=l.attachments,y=fa(d?.filediff)?d.filediff:void 0,v=Ut(d?.patch)??Ut(d?.diff)??Ut(y?.patch)??Ut(y?.diff)??null,C=p.useMemo(()=>bU(d,v??void 0,W=>Gn(W,n)),[n,v,d]),w=C.some(W=>W.renderMode==="diff"),M=e.tool==="pichamber"||e.tool==="apply_patch"||e.tool==="edit"||e.tool==="multiedit",j=p.useMemo(()=>jU(e.tool||"",f,d,n),[n,f,d,e.tool]),T=p.useMemo(()=>!f||typeof f!="object"||Object.keys(f).length===0?"":"command"in f&&typeof f.command=="string"&&e.tool==="bash"?ix(f,e.tool):typeof f.content=="string"?f.content??"":ix(f,e.tool),[f,e.tool]),A=!M&&T.trim().length>0,_=e.tool==="write"||e.tool==="create"||e.tool==="file_write",k=e.tool==="todowrite"||e.tool==="todoread",E=p.useMemo(()=>Array.isArray(f?.todos)?JSON.stringify(f.todos):b,[f?.todos,b]),I=p.useMemo(()=>{if(!_||!A)return;const W=typeof f?.filePath=="string"?f.filePath:typeof f?.file_path=="string"?f.file_path:typeof f?.path=="string"?f.path:void 0;return MU(W,T)},[A,f?.filePath,f?.file_path,f?.path,T,_]);p.useEffect(()=>{a("unified")},[e.id]);const N=(W,z)=>c.jsx(F1,{maxHeightClass:z?.maxHeightClass,className:z?.className,disableHorizontal:z?.disableHorizontal,outerClassName:z?.outerClassName,followKey:z?.followKey,children:W}),O=()=>{const W=U=>Ba(n,U.filePath??U.title),z=(U,P)=>{P.stopPropagation();const q=ua(U.patch),F=W(U);te.getState().openContextFileAtLine(n,F,q??1,1),o?.openFiles()},J=(U,P)=>{P.stopPropagation();const q=W(U),F=te.getState(),ee=Gn(q,n);if(F.isMobile){F.navigateToDiff(ee);return}F.openContextDiff(n,ee)},B=()=>j?c.jsxs("div",{className:"tool-output-surface rounded-xl border p-2 space-y-2",style:{borderColor:"var(--status-error-border)",backgroundColor:"var(--status-error-background)"},children:[c.jsx("div",{className:"typography-meta font-medium",style:{color:"var(--status-error)"},children:"LSP errors"}),c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"flex items-center gap-1 min-w-0",children:c.jsx(nx,{path:j.displayPath,grow:!1})}),c.jsx("div",{className:"space-y-1",children:j.diagnostics.map((U,P)=>c.jsx("div",{className:"rounded-md border px-2 py-1",style:{borderColor:"var(--status-error-border)",backgroundColor:"var(--surface-elevated)"},children:c.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[c.jsxs("span",{className:"typography-micro shrink-0",style:{color:"var(--status-error)"},children:["[",U.line,":",U.character,"]"]}),c.jsx("span",{className:"typography-meta text-foreground whitespace-pre-wrap break-words",children:U.message})]})},`${j.displayPath}:${U.line}:${U.character}:${P}`))}),j.remaining>0?c.jsx("div",{className:"typography-micro text-muted-foreground",children:`+${j.remaining} more errors`}):null]})]}):null;if(e.tool==="question"){if(t.status==="completed"&&h){const P=_U(b);if(P&&P.length>0)return N(c.jsx("div",{className:"space-y-2",children:P.map((q,F)=>c.jsxs("div",{className:"space-y-0.5",children:[c.jsx("div",{className:"typography-micro text-muted-foreground",children:q.question}),c.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:q.answer})]},F))}),{maxHeightClass:"max-h-[40vh]"})}if(t.status==="error"&&"error"in t)return c.jsxs("div",{children:[c.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),c.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:vn(t.error)})]});const U=f;return U?.questions&&Array.isArray(U.questions)&&U.questions.length>0?N(c.jsx("div",{className:"space-y-2",children:U.questions.map((P,q)=>c.jsxs("div",{className:"space-y-0.5",children:[P.header?c.jsx("div",{className:"typography-micro text-muted-foreground",children:vn(P.header)}):null,c.jsx("div",{className:"typography-meta text-foreground",children:vn(P.question)}),Array.isArray(P.options)&&P.options.length>0?c.jsx("div",{className:"flex flex-wrap gap-1 mt-0.5",children:P.options.map(F=>c.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-muted/30 border border-border/30 text-muted-foreground",children:vn(F.label)},vn(F.label)))}):null]},q))}),{maxHeightClass:"max-h-[40vh]"}):c.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(e.tool==="task"&&h)return N(c.jsx("div",{className:"w-full min-w-0",children:c.jsx(Oa,{content:vn(b),variant:"tool",onShowPopup:s})}));if((e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&(C.length>0||j))return N(c.jsxs("div",{className:"space-y-3",children:[C.map(U=>c.jsxs("div",{className:"w-full min-w-0",children:[c.jsxs("div",{className:"mb-1 flex min-w-0 items-center gap-1 px-2 py-1",children:[c.jsx("div",{className:"min-w-0 flex-1 typography-meta font-medium text-muted-foreground",children:c.jsx(nx,{path:U.title})}),c.jsx(Se,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:P=>z(U,P),"aria-label":"Open file at first change",title:"Open file at first change",children:c.jsx($,{name:"file-edit",className:"h-3.5 w-3.5"})}),c.jsx(Se,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:P=>J(U,P),"aria-label":"Open file diff",title:"Open file diff",children:c.jsx($,{name:"git-pull-request",className:"h-3.5 w-3.5"})})]}),U.renderMode==="diff"?c.jsx(lx,{diff:U.patch,diffViewMode:i}):c.jsx(w7,{diff:U.patch})]},U.id)),B()]}),{className:"p-1"});if(e.tool==="write"&&j)return N(c.jsx("div",{className:"space-y-3",children:B()}),{className:"p-1"});if(_)return null;if(h&&b.trim()){const U=c.jsx(Wp,{output:vn(b),part:e,metadata:d,input:f,isStreaming:g});return N(U,{className:e.tool==="bash"?"p-1 rounded-none":"p-1",maxHeightClass:g?"max-h-64":e.tool==="bash"?"max-h-[46vh]":void 0,followKey:g?b:void 0})}return N(c.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})},L=b.trim().length>0,D=t.status==="completed"&&"output"in t||e.tool==="bash"&&L;if(k){if(t.status==="error"&&"error"in t)return c.jsxs("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:[c.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),c.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:t.error})]});const W=Sq(E,{total:"Total",inProgress:"In Progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},{unstyled:!0});return c.jsx("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:N(W??c.jsx(Wp,{output:E,part:e,metadata:d,input:f}),{className:"p-2",maxHeightClass:"max-h-[46vh]"})})}return c.jsxs("div",{className:R("oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4"),children:[e.tool==="question"?O():c.jsxs(c.Fragment,{children:[A?c.jsx("div",{className:"my-1",children:N(e.tool==="bash"?c.jsx("pre",{className:"tool-input-text whitespace-pre-wrap break-words typography-code text-muted-foreground/90 m-0 p-0",children:T}):_&&I?c.jsx(lx,{diff:I,diffViewMode:i}):c.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:T}),{maxHeightClass:_&&I&&r?"max-h-[50vh]":"max-h-60",className:e.tool==="bash"?"tool-input-surface p-0 rounded-none":"tool-input-surface"})}):null,D&&c.jsxs("div",{children:[(e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&w?c.jsx("div",{className:"mb-1 flex items-center justify-end gap-2",children:c.jsx(pq,{mode:i,onModeChange:a,className:"h-5 w-5 p-0"})}):null,O()]}),t.status==="error"&&"error"in t&&c.jsxs("div",{children:[c.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),c.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:vn(t.error)})]})]}),Array.isArray(S)&&S.length>0&&t.status==="completed"?c.jsx(i1,{files:S,onShowPopup:s,compact:!0}):null]})});k7.displayName="ToolExpandedContent";const Dl=[];let ha;const M7=()=>{for(;Dl.length>0;){const e=Dl.pop();if(!e)break;if(e.active){e.fn(),ha=Dl.length>0?window.requestAnimationFrame(M7):void 0;return}}ha=void 0},Dq=e=>{if(typeof window>"u")return e(),()=>{};const t={active:!0,fn:e};return Dl.push(t),ha===void 0&&(ha=window.requestAnimationFrame(()=>{ha=window.requestAnimationFrame(M7)})),()=>{t.active=!1}},dx=e=>{const[t,n]=p.useState(e),r=p.useRef(!1);return p.useEffect(()=>{if(!e){r.current=!0,n(!1);return}if(!r.current){r.current=!0,n(!0);return}return Dq(()=>{n(!0)})},[e]),t},Oq=new Set(["bash","edit","write","apply_patch","patch"]),Hq=(e,t,n=Date.now())=>{const s=Math.max(0,(t??n)-e)/1e3;return`${(s<.05&&t!==void 0?.1:s).toFixed(1)}s`},ux=({start:e,end:t,active:n})=>{const r=e7(n,250);return c.jsx(c.Fragment,{children:Hq(e,t,r)})},fx=(e,t)=>{if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Fq=(e,t)=>fx(e.call,t.call)&&fx(e.result,t.result),Bq=p.memo(({call:e,result:t})=>{const n=Array.isArray(e)&&e.length>0,r=Array.isArray(t)&&t.length>0;return!n&&!r?null:c.jsxs("div",{className:R("my-1 ml-5 overflow-x-auto rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2","font-mono typography-micro whitespace-pre max-h-80 overflow-y-auto"),"data-chat-tool-extension-render":"true",children:[n&&e.map((s,o)=>c.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:c.jsx(qt,{text:s})},`call-${o}`)),r&&t.map((s,o)=>c.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:c.jsx(qt,{text:s})},`res-${o}`))]})},Fq),Vq=({part:e,isExpanded:t,onToggle:n,isMobile:r,onContentChange:s,onShowPopup:o,animateTailText:i=!0})=>{const a=pe(le=>le.currentSessionId),l=e.state?.deferredBody===!0,d=HE(a,e.id,t&&l),f=t&&d&&d.type==="tool"?d:e,u=f.state,h=u,m=h.metadata,g=h.input,x=Qn()??"",b=u?.render,S=!!(b&&(Array.isArray(b.call)&&b.call.length>0||Array.isArray(b.result)&&b.result.length>0||Array.isArray(b.resultExpanded)&&b.resultExpanded.length>0)),y=Ds(e.tool),v=y==="task",C=u?.status,w=C==="completed"||C==="error"||C==="aborted"||C==="failed"||C==="timeout"||C==="cancelled",M=C==="completed",j=C==="error"||C==="failed",[T,A]=p.useState(!w),_=p.useRef(e.id),k=p.useRef(!w);p.useEffect(()=>{_.current!==e.id&&(_.current=e.id,k.current=!w,A(!w))},[w,e.id]),p.useEffect(()=>{w||A(!0)},[w]),p.useEffect(()=>{if(!w){k.current=!0;return}if(!k.current)return;if(!M||!Oq.has(y)){k.current=!1;return}if(!x)return;k.current=!1;const X=hU(y,g,m).map(ne=>Gn(ne,x));hu.requestGitRefresh({directory:x,...X.length>0?{paths:X}:{}})},[x,g,w,M,m,y]);const E=w||v||S,I=p.useRef(s);I.current=s;const N=p.useRef(null);p.useLayoutEffect(()=>{if(v||S)return;const le=N.current;le&&(le.style.height=t?"auto":"0px",le.style.overflow=t?"visible":"hidden",E&&I.current?.("structural"))},[S,t,v,E]);const O=p.useRef(t);p.useEffect(()=>{const le=O.current!==t;O.current=t,!(!S||!t&&!le)&&I.current?.("structural")},[S,t,b?.call,b?.result,b?.resultExpanded]);const L=e.metadata,D=h.time,[W,z]=p.useState(()=>({start:typeof D?.start=="number"?D.start:void 0,end:typeof D?.end=="number"?D.end:void 0})),[J,B]=p.useState(void 0),[U,P]=p.useState(void 0);p.useEffect(()=>{z({}),B(void 0),P(void 0)},[e.id]),p.useEffect(()=>{w||typeof D?.start!="number"&&B(le=>le??Date.now())},[w,D?.start]),p.useEffect(()=>{z(le=>{const X={...le};let ne=!1;return typeof D?.start=="number"&&(typeof le.start!="number"||D.start<le.start)&&(X.start=D.start,ne=!0),typeof D?.end=="number"&&(typeof le.end!="number"||D.end>le.end)&&(X.end=D.end,ne=!0),ne?X:le})},[D?.end,D?.start]);const q=p.useMemo(()=>{const le=[W.start,D?.start].filter(X=>typeof X=="number");return le.length>0?Math.min(...le):J},[J,W.start,D?.start]),F=p.useMemo(()=>typeof h.output=="string"?h.output:void 0,[h.output]),ee=p.useMemo(()=>m7(F),[F]),G=p.useMemo(()=>{if(!v)return[];const le=m,X=p7(le?.summary??le?.entries??le?.tools??le?.calls);return X.length>0?X:ee.summaryEntries},[v,m,ee.summaryEntries]),K=w&&G.length>0,se=p.useMemo(()=>{if(!v)return;const le=Jv(m);if(le)return le;const X=Jv(L);return X||(ee.sessionId?ee.sessionId:PU(F))},[v,m,ee.sessionId,L,F]);p.useEffect(()=>{if(typeof D?.end=="number"||typeof W.end=="number"){P(void 0);return}typeof q=="number"&&w&&P(le=>le??Date.now())},[q,w,W.end,D?.end]);const ce=w?W.end??D?.end??U:void 0,re=!w&&T,fe=w,ge=RU({isTaskTool:v,isExpanded:t,isActive:re,hasFinalMetadataSummary:K,taskSessionId:se})?se??"":"",we=Qd(ge);VE(ge);const Me=p.useMemo(()=>!v||!se?[]:!Array.isArray(we)||we.length===0?[]:HU(we),[we,v,se]),He=p.useMemo(()=>Me.length>0?Me:G,[Me,G]),Ae=p.useMemo(()=>He.map(Uo).join("\0"),[He]),Ge=p.useRef(null);p.useEffect(()=>{if(!v){Ge.current=null;return}const le=Ge.current;Ge.current=Ae,!(le===null||le===Ae||He.length===0)&&I.current?.("structural")},[v,He.length,Ae]);const et=p.useMemo(()=>y==="edit"||y==="multiedit"||y==="apply_patch"?TU(m):null,[m,y]),Xe=p.useMemo(()=>y==="write"?AU(g):null,[g,y]),oe=y==="apply_patch"&&Array.isArray(m?.files)&&(m?.files).length>1,Q=y!==e.tool?{...e,tool:y}:e,ue=u?f7(Q,u,x):void 0,be=u?LU(Q,u,x):void 0,Ie=Ha(y||e.tool||"").displayName,Fe=p.useMemo(()=>{if(y==="bash"||y==="apply_patch"||y==="lsp"||ue&&(y==="apply_patch"||y==="edit"||y==="multiedit"||y==="write"))return null;const le=h.title;if(typeof le=="string"&&le.trim().length>0)return le;const X=g?.description;return typeof X=="string"&&X.trim().length>0?X:null},[ue,y,h,g]),ht=!!(Fe||be||et||Xe),ye=p.useContext(Ra),Ze=(le,X)=>{ye?.editor&&(X.stopPropagation(),$U({currentDirectory:x,editor:ye.editor,file:le}))},Be=le=>{if(v||S||!ye?.editor){n(e.id);return}let X,ne;if(y==="edit"||y==="multiedit")X=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path,typeof X=="string"&&(ne=Yv(y,m,X));else if(y==="apply_patch")X=H1(y,g,m),typeof X=="string"&&(ne=Yv(y,m,X));else if(["write","create","file_write"].includes(y))X=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path;else if(y==="lsp"){X=g?.filePath||g?.file_path||g?.path;const he=g?.line;ne=typeof he=="number"&&Number.isFinite(he)?Math.trunc(he):void 0}if(typeof X=="string"){le.stopPropagation();const he=Ba(x,X);ye.editor.openFile(he,ne)}else n(e.id)},ie=le=>{le.key!=="Enter"&&le.key!==" "||(le.preventDefault(),Be(le))},ke=!v&&j?q4:W4,ve=!v&&j?K4:Ps,xe=dx(v&&(He.length>0||re||fe||!!se)),_e=dx(!v&&!S&&t);return!fe&&!re&&!v?null:c.jsxs("div",{children:[c.jsxs("div",{className:R("group/tool flex w-full min-w-0 gap-x-1.5 rounded-md pr-2 pl-px py-1 transition-colors hover:bg-[var(--interactive-hover)]",oe?"flex-wrap items-start cursor-pointer":"items-center cursor-pointer"),"data-chat-activity-row":"true",onClick:oe?()=>n(e.id):Be,onKeyDown:oe?le=>{le.target===le.currentTarget&&(le.key!=="Enter"&&le.key!==" "||(le.preventDefault(),n(e.id)))}:ie,role:"button",tabIndex:0,children:[c.jsx("div",{className:R("flex min-w-0",oe?"w-full flex-wrap items-center gap-x-2 gap-y-0.5":"flex-shrink-0 items-center gap-x-1.5"),children:oe?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex h-5 flex-shrink-0 items-center gap-1.5",children:[c.jsxs("span",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[c.jsx("span",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",t?"opacity-0":"group-hover/tool:opacity-0"),style:ke,children:_a(y||e.tool)}),c.jsx($,{name:t?"arrow-down-s":"arrow-right-s",className:R("absolute inset-0 h-3.5 w-3.5 transition-opacity",t?"opacity-100":"opacity-0 group-hover/tool:opacity-100")})]}),c.jsx(Cd,{active:!!(re&&!j),minDurationMs:300,className:R(Kr,"flex-shrink-0"),style:ve,children:Ie})]}),c.jsx(VU,{metadata:m,animate:i,showFileIcons:!0,textClassName:Mt,openDiffLabel:"Open file diff",onFileClick:ye?.editor?Ze:void 0}),typeof q=="number"?c.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-muted-foreground/80",Mt),"aria-label":"Tool duration",children:c.jsx(ux,{start:q,end:typeof ce=="number"?ce:void 0,active:!!(re&&typeof ce!="number")})}):null]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"relative h-5 w-3.5 flex-shrink-0 cursor-pointer",onClick:le=>{le.stopPropagation(),n(e.id)},children:[c.jsx("div",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",t&&"opacity-0",!t&&"group-hover/tool:opacity-0"),style:ke,children:_a(y||e.tool||"")}),c.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",t&&"opacity-100",!t&&"opacity-0 group-hover/tool:opacity-100"),children:t?c.jsx($,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):c.jsx($,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),c.jsx("div",{className:"flex min-w-0 flex-shrink-0 items-center gap-x-1.5",children:c.jsx(Cd,{active:!!(re&&!j),minDurationMs:300,className:R(Kr,"flex-shrink-0"),style:ve,title:Ie,children:Ie})})]})}),!oe&&ht?c.jsx("div",{className:R("flex min-w-0 flex-1 items-center",Mt),style:{color:"var(--tools-description)"},children:c.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1 overflow-hidden rounded-md bg-[var(--surface-subtle)] px-1.5 py-0.5",Mt),children:c.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-hidden",children:[Fe&&c.jsx("span",{className:R("min-w-0 truncate",Mt),style:{color:"var(--tools-description)",opacity:.8},title:Fe,children:Fe}),!Fe&&y==="lsp"&&ue?c.jsx(Vp,{path:ue,animate:i,grow:!1,showFileIcons:!0}):null,!Fe&&y!=="lsp"&&be&&(ue&&be===ue?c.jsx(Vp,{path:ue,animate:i,grow:!1,showFileIcons:!0}):c.jsx(pr,{variant:i?"generate-effect":"static",className:R("min-w-0 truncate",Mt),style:{color:"var(--tools-description)"},title:be,children:be})),et&&c.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",et.added]}),c.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),c.jsxs("span",{style:{color:"var(--status-error)"},children:["-",et.removed]})]}),Xe&&c.jsx("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:c.jsxs("span",{style:{color:"var(--status-success)"},children:["+",Xe]})})]})})}):null,!oe&&typeof q=="number"?c.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-muted-foreground/80",Mt),"aria-label":"Tool duration",children:c.jsx(ux,{start:q,end:typeof ce=="number"?ce:void 0,active:!!(re&&typeof ce!="number")})}):null]}),S&&t?c.jsx(Bq,{call:b?.call,result:b?.resultExpanded&&b.resultExpanded.length>0?b.resultExpanded:b?.result}):null,xe?c.jsx(WU,{entries:He,isExpanded:t,isMobile:r,output:F,sessionId:se,onShowPopup:o,input:g,animateTailText:i,isActive:re}):null,!v&&!S?c.jsx("div",{ref:N,"aria-hidden":!t,style:{height:t?"auto":"0px",overflow:t?"visible":"hidden",overflowAnchor:"none"},children:_e?c.jsxs("div",{className:"relative ml-2 pl-3","data-chat-tool-indent":"true",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute left-0 top-px bottom-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),u?c.jsx(k7,{part:f,state:u,currentDirectory:x,isExpanded:t,onShowPopup:o}):null]}):null}):null]})};class $q extends p.Component{state={hasError:!1};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidUpdate(t){t.resetKey!==this.props.resetKey&&this.state.hasError&&this.setState({hasError:!1,error:void 0})}componentDidCatch(t){}render(){if(!this.state.hasError)return this.props.children;const t=this.state.error?.message;return c.jsxs("div",{className:"flex items-center gap-1.5 pr-2 pl-px py-1 min-w-0","data-chat-activity-row":"true",children:[c.jsx("div",{className:"h-3.5 w-3.5 flex-shrink-0",style:q4,children:_a(this.props.toolName)}),c.jsx("span",{className:R(Kr,"flex-shrink-0"),style:K4,children:this.props.displayName}),t?c.jsxs("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:t,children:[this.props.errorLabel,": ",t]}):null]})}}const zq=e=>{const t=Ds(e.part.tool)||"tool",n=Ha(t).displayName;return c.jsx($q,{displayName:n,errorLabel:"Error:",resetKey:e.part,toolName:t,children:c.jsx(Vq,{...e})})},Uq=p.memo(zq,(e,t)=>bu([e.part],[t.part])&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.alwaysShowActions===t.alwaysShowActions&&e.onContentChange===t.onContentChange&&e.onShowPopup===t.onShowPopup&&e.animateTailText===t.animateTailText),I7=p.createContext(!1),hx=({disabled:e,children:t})=>c.jsx(I7.Provider,{value:e,children:t}),V1=({children:e,className:t,skipAnimation:n,forceAnimation:r=!1,ignoreContextDisabled:s=!1,respectReducedMotion:o=!1})=>{const i=p.useContext(I7),a=o&&typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,l=!!n||!s&&i||a,d=r,f=p.useRef(null);f.current===null&&(f.current=d&&!l);const u=f.current,[h,m]=p.useState(!u);return p.useEffect(()=>{if(!u)return;let g=null;const x=()=>m(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?g=window.requestAnimationFrame(x):x(),()=>{g!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(g)}},[u]),u?c.jsx("div",{className:R("w-full transition-all duration-300 ease-out",h?"opacity-100 translate-y-0":"opacity-0 translate-y-2",t),children:e}):c.jsx(c.Fragment,{children:e})},qq=4e3,co=new Map,E7=e=>{const t=co.get(e);return t?new Set(t):new Set},Wq=(e,t)=>{if(co.size>=qq&&!co.has(e)){const n=co.keys().next().value;typeof n=="string"&&co.delete(n)}co.set(e,new Set(t))},Kq=e=>{const t=new Set,n=new Map;for(const r of e){const s=n.get(r.messageId)??new Set;s.add(r.id),n.set(r.messageId,s)}for(const[r,s]of n){const o=E7(r);for(const i of s)o.has(i)&&t.add(i)}return t},Gq=({messageId:e,ownerToolIds:t,nextValue:n,read:r,write:s})=>{const o=r(e);for(const i of t)n.has(i)?o.add(i):o.delete(i);s(e,o)};function Zq({activities:e}){const t=te(g=>g.setImagePreviewOpen),n=p.useMemo(()=>e.filter(g=>g.kind==="tool"&&g.part.type==="tool"),[e]),r=p.useMemo(()=>{const g=new Map;for(const x of n)g.set(x.id,x.messageId);return g},[n]),s=p.useMemo(()=>{const g=new Map;for(const x of n){const b=g.get(x.messageId)??new Set;b.add(x.id),g.set(x.messageId,b)}return g},[n]),[o,i]=p.useState(()=>Kq(n)),[a,l]=p.useState({open:!1,title:"",content:""}),d=o,f=p.useRef({ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d});f.current={ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d};const u=p.useCallback(g=>{const x=f.current,b=x.ownerByToolId.get(g);if(!b)return;const S=x.toolIdsByOwner.get(b)??new Set;i(y=>{const v=new Set(y);return v.has(g)?v.delete(g):v.add(g),Gq({messageId:b,ownerToolIds:S,nextValue:v,read:E7,write:Wq}),v})},[]),h=p.useCallback(g=>{(g.image||g.mermaid)&&(l(g),t(!0))},[t]),m=p.useCallback(g=>{l(x=>({...x,open:g})),t(g)},[t]);return{effectiveExpandedTools:d,popupContent:a,handleToggleTool:u,handleShowPopup:h,handlePopupChange:m}}const Yq=Rs(()=>mt(()=>import("./ToolOutputDialog-QC8IoeBH.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),Xq=e=>{const t=p.useRef(e),[n,r]=p.useState(e);return e&&(t.current=!0),p.useEffect(()=>{const s=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;let o;return e?s||typeof requestAnimationFrame!="function"?r(!0):o=requestAnimationFrame(()=>r(!0)):r(!1),()=>{o!==void 0&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(o)}},[e]),{isMounted:t.current,isVisible:n}},Jq=({activity:e,isLiveTurn:t,activeStreamingMessageId:n,activeStreamingPhase:r})=>t&&n&&e.messageId===n?r??"streaming":"completed",j7=p.memo(({activity:e,animate:t,isExpanded:n,isMobile:r,onContentChange:s,onToggle:o,onShowPopup:i})=>{const a=Ds(e.part.tool),l=SU(a)?c.jsx(Uq,{part:e.part,isExpanded:n,onToggle:o,isMobile:r,alwaysShowActions:r,onContentChange:s,onShowPopup:i,animateTailText:t}):c.jsx(Hz,{toolName:a,activity:e,animateTailText:t});return c.jsx(V1,{children:c.jsx(g7,{animate:t,children:l})})},(e,t)=>e.activity.id===t.activity.id&&e.activity.messageId===t.activity.messageId&&e.activity.endedAt===t.activity.endedAt&&bu([e.activity.part],[t.activity.part])&&e.animate===t.animate&&e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.onContentChange===t.onContentChange&&e.onToggle===t.onToggle&&e.onShowPopup===t.onShowPopup);j7.displayName="TurnToolActivityRow";const Qq=({turn:e,isExpanded:t,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s,onContentChange:o})=>{const{isMobile:i}=On(),[a,l]=p.useState(X$),d=Xq(t),f=p.useRef(o);f.current=o;const u=p.useCallback(T=>{f.current?.(T)},[]),h=e.activityParts,m=p.useMemo(()=>h.reduce((T,A)=>T+(A.kind==="tool"?1:0),0),[h]),g=p.useMemo(()=>Q$(h,a),[h,a]),{effectiveExpandedTools:x,popupContent:b,handleToggleTool:S,handleShowPopup:y,handlePopupChange:v}=Zq({activities:h}),C=p.useMemo(()=>h.filter(T=>T.kind==="tool").map(T=>T.id),[h]),w=p.useRef({turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set});if(w.current.turnId!==e.turnId&&(w.current={turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set}),n&&w.current.committed)for(const T of C)w.current.knownToolIds.has(T)||w.current.animatedToolIds.add(T);p.useEffect(()=>{const T=w.current;for(const A of C)T.knownToolIds.add(A);T.committed=!0},[C]);const M=p.useCallback(()=>{l(T=>Math.min(m,T+J$)),u("structural")},[u,m]),j=p.useCallback(T=>{const A=Jq({activity:T,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s}),_=w.current.animatedToolIds.has(T.id);return T.kind==="reasoning"?c.jsx(hz,{part:T.part,messageId:T.messageId,streamPhase:A,onContentChange:u,withinActivityRail:!0},T.id):T.kind==="justification"?c.jsx(U4,{part:T.part,messageId:T.messageId,streamPhase:A,onContentChange:u,withinActivityRail:!0},T.id):T.part.type!=="tool"?null:c.jsx(j7,{activity:T,animate:_,isExpanded:x.has(T.id),isMobile:i,onContentChange:u,onToggle:S,onShowPopup:y},T.id)},[r,s,x,y,S,n,i,u]);return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"chat-message-column",children:c.jsx("div",{id:`turn-${e.turnId}-activity`,className:"relative min-w-0 pl-[18px]","data-turn-activity-rail":"true","data-turn-activity-expanded":t?"true":"false","aria-hidden":!t,children:d.isMounted?c.jsxs("div",{className:R("relative grid origin-top transition-[grid-template-rows,opacity,transform] duration-200 ease-out motion-reduce:transition-none motion-reduce:transform-none",d.isVisible?"grid-rows-[1fr] translate-y-0 opacity-100":"grid-rows-[0fr] -translate-y-1 opacity-0"),"data-turn-activity-panel":"true","data-turn-activity-visible":d.isVisible?"true":"false",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 -left-[18px] top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),c.jsxs("div",{className:"relative min-h-0 overflow-hidden",children:[t&&g.hiddenToolCount>0?c.jsx(Se,{type:"button",variant:"ghost",size:"xs",className:"-ml-1.5 mb-0.5 justify-start px-1.5 text-muted-foreground","aria-label":"Load earlier activity",onClick:M,children:"Load earlier activity"}):null,c.jsx("div",{className:"min-w-0 space-y-1","data-chat-activity-list":"true",children:g.activities.map(j)})]})]}):null})}),b.open?c.jsx(p.Suspense,{fallback:null,children:c.jsx(Yq,{popup:b,onOpenChange:v,isMobile:i})}):null]})},eW=p.memo(Qq),Ol=new Map,tW=(e,t)=>{const n=Ol.get(e);if(!n)return!1;let r=!1;for(const s of n)r=s(t)||r;return r},nW=(e,t)=>{const n=Ol.get(e)??new Set;return n.add(t),Ol.set(e,n),()=>{n.delete(t),n.size===0&&Ol.delete(e)}},rW=e=>e.filter(r=>r?.type==="text").map(r=>(r.text||r.content||"").trim()).filter(r=>r.length>0).join(`
192
+ `).replace(/\n\s*\n+/g,`
193
+ `),sW="Authentication failed for this provider. Please re-authenticate and retry.",oW=e=>{if(typeof e!="string")return!1;const t=e.toLowerCase().trim();if(!t)return!1;if(t.includes("token refresh failed")||t.includes("unauthorized")||t.includes("invalid token")||t.includes("expired token"))return!0;const n=t.includes("oauth"),r=t.includes("failed")||t.includes("invalid")||t.includes("expired");if(n&&r)return!0;const s=/\b401\b/.test(t),o=t.includes("auth")||t.includes("token")||t.includes("unauthorized");return s&&o},_7=e=>{const t=e?.error;if(!t)return;const n=typeof t.data?.message=="string"?t.data.message:void 0,r=typeof t.message=="string"?t.message:void 0,s=typeof t.name=="string"?t.name:void 0,o=n||r||s;if(o){if(s==="SessionRetry")return{text:`Retrying after an error:
194
+ \`${o}\``,variant:"info"};if(s==="SessionCompaction"){const i=t.data?.phase,a=t.data?.reason;if(i==="running")return{text:a==="threshold"?"Context is nearly full. Compacting automatically...":a==="overflow"?"Context limit reached. Compacting before retrying...":"Compacting session context...",variant:"info"};if(i==="retrying"){const d=typeof t.data?.attempt=="number"?t.data.attempt:void 0,f=typeof t.data?.maxAttempts=="number"?t.data.maxAttempts:void 0,u=d&&f?` (${d}/${f})`:"",h=typeof t.data?.message=="string"&&t.data.message.trim()?`
195
+ \`${t.data.message.trim()}\``:"";return{text:`Compaction failed temporarily. Retrying${u}...${h}`,variant:"info"}}if(i==="completed"){const d=typeof t.data?.tokensBefore=="number"?t.data.tokensBefore:void 0,f=typeof t.data?.estimatedTokensAfter=="number"?t.data.estimatedTokensAfter:void 0,u=d!==void 0&&f!==void 0?`
196
+ ${d.toLocaleString()} → approximately ${f.toLocaleString()} tokens`:"",h=t.data?.willRetry===!0?`
197
+ Retrying the interrupted turn.`:"";return{text:`Session compacted${u}${h}`,variant:"info"}}return i==="aborted"?{text:"Compaction stopped.",variant:"info"}:{text:`Compaction failed.${typeof t.data?.message=="string"&&t.data.message.trim()?`
198
+ \`${t.data.message.trim()}\``:""}`,variant:"error"}}return oW(o)?{text:sW,variant:"error"}:o.trim().toLowerCase()==="aborted"?{text:"The running turn was stopped before the next message could be sent.",variant:"info"}:{text:`Failed to send message with error:
199
+ \`${o}\``,variant:"error"}}},iW=({isUser:e,displayParts:t,assistantErrorText:n})=>{if(e){const r=t.filter(a=>a.type==="text").map(a=>{const l=a.shellAction?.output;return typeof l=="string"?l.trim():""}).filter(a=>a.length>0);if(r.length>0)return r.join(`
200
+
201
+ `);const s=t.filter(a=>a.type==="text").map(a=>{const l=a.shellAction?.command;return typeof l=="string"?l.trim():""}).filter(a=>a.length>0);return s.length>0?s.join(`
202
+ `):t.filter(a=>a.type==="text").map(a=>(a.text||a.content||"").trim()).filter(a=>a.length>0).join(`
203
+ `).replace(/\n\s*\n+/g,`
204
+ `)}return n&&n.trim().length>0?n:rW(t)},T7=e=>e.type==="subtask",A7=e=>{const t=e;return t.type==="text"&&typeof t.shellAction=="object"&&t.shellAction!==null},aW=e=>!!(e&&typeof e=="object"&&typeof e.type=="string"),wu=e=>e.filter(aW),$1=e=>{const t=e,n=t.text;return typeof n=="string"?n:t.content||t.value||""},N7=e=>{if(e.type!=="text")return!1;const t=$1(e);return!t||t.trim().length===0},L7=e=>e.type==="text"?!N7(e):T7(e)||A7(e),z1=e=>e.filter(t=>N7(t)?!1:t.type!=="compaction"),R7=(e,t,n)=>e.filter((r,s)=>{if(r.type==="tool"||r.type==="reasoning")return!1;if(r.type!=="text")return!0;const o=r.id??`${n}-part-${s}-${r.type}`;return!t.has(o)}),cW=(e,t)=>typeof t=="string"&&t.trim().length>0?!0:z1(e).length>0,U1=(e,t={})=>{const{includeReasoning:n=!0}=t,r=wu(e),s=r.some(o=>!o.synthetic);return r.filter(o=>{const a=!!o.synthetic;return a&&o.type==="text"&&$1(o).includes("<system-reminder>")||a&&s||!n&&o.type==="reasoning"?!1:!(o.type==="patch")})},lW=(e,t)=>{const n=_7(e.info)?.text;if(typeof n=="string"&&n.trim().length>0)return!0;const r=U1(e.parts),s=R7(r,t,e.info.id);return z1(s).length>0},gh=32,px=32,dW=({turnId:e,assistantMessages:t,renderMessage:n,deferEarlierMessages:r,activityPartIds:s})=>{const[o,i]=p.useState(gh),a=t[0],l=p.useMemo(()=>t.filter(y=>lW(y,s)),[s,t]),d=p.useMemo(()=>l.filter(y=>y!==a),[l,a]),f=r&&l.length>gh,u=f?Math.max(0,o-1):d.length,h=u>=d.length?d:d.slice(-u),m=d.length-h.length;p.useEffect(()=>{i(gh)},[e]),p.useEffect(()=>nW(e,y=>{if(a?.info.id===y)return!0;const v=d.findIndex(w=>w.info.id===y);if(v<0)return!1;const C=d.length-h.length;return!f||v>=C||i(w=>Math.max(w,d.length-v+1)),!0}),[d,a,f,e,h.length]);const g=p.useCallback(()=>{i(y=>Math.min(d.length+1,y+px))},[d.length]),x=p.useCallback(()=>{i(d.length+1)},[d.length]),b=p.useCallback(y=>c.jsx(uW,{message:y,renderMessage:n},y.info.id),[n]);if(!f||m===0)return c.jsxs("div",{className:"relative z-0",children:[a?b(a):null,d.map(b)]});const S=m>px;return c.jsxs("div",{className:"relative z-0",children:[a?b(a):null,c.jsxs("div",{className:"chat-message-column flex flex-wrap items-center justify-center gap-2 py-3",children:[c.jsxs(Se,{type:"button",variant:"secondary",size:"sm",onClick:g,"aria-label":"Load earlier response",className:"gap-1.5 rounded-full px-3.5",children:[c.jsx($,{name:"history",className:"size-3.5"}),"Load earlier response"]}),S?c.jsx(Se,{type:"button",variant:"ghost",size:"sm",onClick:x,"aria-label":"Load full response",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load full response"}):null]}),h.map(b)]})},uW=p.memo(function({message:t,renderMessage:n}){return n(t)},(e,t)=>e.message===t.message),fW=p.memo(dW),hW="GitHub issue context (JSON)",pW="GitHub pull request context (JSON)",zi=e=>!e||typeof e!="object"?!1:!!e.synthetic,mW=e=>!Array.isArray(e)||e.length===0?!1:e.every(t=>zi(t)),gW=e=>{if(!Array.isArray(e)||e.length===0)return[];const t=e.some(r=>!zi(r)),n=r=>{if(!zi(r)||r.type!=="text")return!1;const s=r.text;if(typeof s!="string")return!1;const o=s.trimStart();return o.startsWith(hW)||o.startsWith(pW)};return t&&e.some(s=>zi(s))?e.filter(s=>!zi(s)||n(s)):e},yW={activity:"idle",hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isGenericStatus:!0,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:null},vW=new Map,P7="\0",xW=new Set(["apply_patch","create","edit","file_write","multiedit","str_replace","str_replace_based_edit_tool","write"]),bW={read:"reading files",view:"reading files",file_read:"reading files",cat:"reading files",write:"editing files",create:"editing files",file_write:"editing files",edit:"editing files",multiedit:"editing files",apply_patch:"editing files",str_replace:"editing files",str_replace_based_edit_tool:"editing files",bash:"executing commands",shell:"executing commands",cmd:"executing commands",terminal:"executing commands",grep:"searching code",search:"searching code",find:"searching files",ripgrep:"searching code",glob:"searching files",list:"listing files",ls:"listing files",dir:"listing files",list_files:"listing files",task:"delegating work",subagent:"delegating work",webfetch:"fetching a URL",fetch:"fetching a URL",websearch:"searching the web",web_search:"searching the web",search_web:"searching the web",codesearch:"searching code",todowrite:"updating tasks",todoread:"reviewing tasks",skill:"loading a skill",question:"waiting for input",lsp:"inspecting code",structuredoutput:"formatting the response",structured_output:"formatting the response",pichamber:"working in PiChamber",plan_enter:"switching to planning",plan_exit:"switching to building"},mx=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],D7=e=>{const t=e.trim().toLowerCase().replace(/:\d+$/,"");if(!t.includes("."))return t;const n=t.split(".").filter(Boolean);return n[n.length-1]??t},wW=e=>{const t=D7(e);return bW[t]??`using ${t.replaceAll("_"," ")}`},SW=e=>{let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)},CW=e=>mx[SW(e)%mx.length]??"working",gx=(e,t,n)=>{for(let r=t.length-1;r>=0;r-=1){const s=t[r],o=s?e.get(s):void 0;if(o){if(o.type==="tool"&&(o.tool?.state==="running"||o.tool?.state==="pending")){const i=D7(o.tool.name);return{activePartType:xW.has(i)?"editing":"tool",activeToolName:i,statusText:wW(i),isGenericStatus:!1}}if(o.type==="thinking"&&o.streaming)return{activePartType:"reasoning",activeToolName:void 0,statusText:"thinking",isGenericStatus:!1};if(o.type==="text"&&o.streaming&&o.text.trim().length>0)return{activePartType:"text",activeToolName:void 0,statusText:"writing response",isGenericStatus:!1}}}return{activePartType:void 0,activeToolName:void 0,statusText:CW(n),isGenericStatus:!0}},kW=e=>[e.activePartType??"",e.activeToolName??"",e.statusText,e.isGenericStatus?"1":"0"].join(P7),MW=e=>{const[t,n,r="working",s]=e.split(P7);return{activePartType:t==="text"||t==="tool"||t==="reasoning"||t==="editing"?t:void 0,activeToolName:n||void 0,statusText:r,isGenericStatus:s==="1"}},IW=e=>{let t=null,n=null;for(let r=e.length-1;r>=0;r-=1){const s=e[r];if(s?.role!=="assistant")continue;const o=s;t=s.id,n=typeof o.parentID=="string"&&o.parentID.trim().length>0?o.parentID:null;break}if(!t||!n)return{assistantId:t,model:null};for(let r=e.length-1;r>=0;r-=1){const s=e[r];if(s?.role!=="user"||s.id!==n)continue;const o=s,i=typeof o.model?.providerID=="string"?o.model.providerID.trim():"",a=typeof o.model?.modelID=="string"?o.model.modelID.trim():"";return{assistantId:t,model:i&&a?{providerId:i,modelId:a}:null}}return{assistantId:t,model:null}};function O7(){const e=pe(b=>b.currentSessionId);pe(b=>b.currentSessionDirectory);const t=Pm(e??""),n=p.useMemo(()=>IW(t),[t]),r=n.assistantId,s=ze(p.useCallback(b=>{const S=`${e??""}:${r??""}`,y=e?b.reducer.bySession.get(e):void 0,v=xa(y)??r,C=v?y?.partOrder.get(v)??[]:[],w=y?gx(y.parts,C,S):gx(vW,[],S);return kW(w)},[e,r]),void 0,e?`session:${e}`:"chrome"),o=pe(p.useCallback(b=>e?b.sessionAbortFlags?.get(e)??null:null,[e])),{phase:i,isWorking:a}=Gm(),l=Xd(e??""),d=l?.type==="retry"?l.attempt:void 0,f=l?.type==="retry"?l.next:void 0,u=p.useMemo(()=>MW(s),[s]),h=p.useMemo(()=>{const b=!!(o&&!o.acknowledged);return{wasAborted:b,abortActive:b}},[o]),m=p.useMemo(()=>{if(h.wasAborted)return{...yW,wasAborted:!0,abortActive:h.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1,retryInfo:null};const b=a,S=i==="busy",y=!1,v=i==="retry";let C="idle";b&&(u.activePartType==="tool"||u.activePartType==="editing"?C="tooling":C="streaming");const w=v?{attempt:d,next:f}:null;return{activity:C,hasWorkingContext:b,hasActiveTools:u.activePartType==="tool"||u.activePartType==="editing",isWorking:b,isStreaming:S,isCooldown:y,lifecyclePhase:S?"streaming":null,statusText:b?u.statusText:null,isGenericStatus:b?u.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:b,compactionDeadline:null,activePartType:b?u.activePartType:void 0,activeToolName:b?u.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:w}},[i,a,u,h,d,f]),g=p.useMemo(()=>({isActive:a&&u.activePartType==="text",characterCount:0}),[a,u.activePartType]),x=m;return{activeModel:n.model,forming:g,working:x}}const EW=({startedAt:e,completedAt:t,durationMs:n})=>typeof n=="number"&&Number.isFinite(n)&&n>=0?n:typeof e=="number"&&typeof t=="number"&&Number.isFinite(e)&&Number.isFinite(t)&&t>=e?t-e:null,Hl=e=>{const t=Math.max(.1,e/1e3);if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${r}s`},H7=p.memo(({isWorking:e,startedAt:t,statusText:n})=>{const r=pe(h=>h.currentSessionId),s=ze(p.useCallback(h=>(r?h.reducer.bySession.get(r):void 0)?.extensionWorking,[r]),(h,m)=>h?.message===m?.message&&h?.visible===m?.visible,r?`session:${r}`:"chrome"),{activeModel:o,working:i}=O7(),a=kb(r??""),l=We(h=>h.providers),d=p.useMemo(()=>{if(!o)return null;const h=l.find(m=>m.id===o.providerId);return d1(h,o.modelId)||null},[o,l]);if(s?.visible===!1)return null;const f=s?.message?Nn(s.message):n??i.statusText,u=s?.message||n?!1:i.isGenericStatus;return c.jsx(k3,{isWorking:e||i.isWorking,statusText:f,isGenericStatus:u,isWaitingForPermission:i.isWaitingForPermission,retryInfo:i.retryInfo,modelName:d,providerId:o?.providerId??null,startedAt:n?t??a??null:a??t??null})});H7.displayName="LiveTurnStatus";const jW=({turnId:e,isLiveTurn:t,isWorking:n,isAwaitingRecovery:r=!1,hasActivity:s,isActivityExpanded:o,onToggleActivity:i,startedAt:a,completedAt:l,durationMs:d,liveStatusText:f,wasSteered:u})=>{const h=EW({startedAt:a,completedAt:l,durationMs:d}),m=!t&&r,g=t?"Agent working":m?"Reconnecting · last seen working":h!==null?`Worked for ${Hl(h)}${u?" · Steered":""}`:s?"Agent activity":null,x=`turn-${e}-activity`;return c.jsx("div",{className:"chat-message-column mb-1","data-turn-working-header":"true","data-turn-working":t&&n?"true":"false",children:c.jsxs("div",{className:"flex min-h-6 items-center gap-1 py-0.5",children:[c.jsx("div",{className:"flex min-w-0 items-center overflow-hidden",children:t?c.jsx(H7,{isWorking:n,startedAt:a,statusText:f}):g?c.jsx("span",{className:"typography-markdown inline-flex min-w-0 items-center leading-5 text-muted-foreground",role:"status","aria-label":g,...m?{"data-turn-reconnecting":"true"}:{"data-agent-worked-row":"true"},children:g}):null}),s?c.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:R("h-6 w-6 shrink-0 rounded-md p-0 text-muted-foreground","hover:bg-interactive-hover hover:text-foreground"),"aria-expanded":o,"aria-controls":x,"aria-label":o?"Collapse activity":"Expand activity","data-turn-activity-toggle":"true",onClick:i,children:c.jsx($,{name:"arrow-right-s",className:R("size-4 transition-transform duration-200 ease-out motion-reduce:transition-none",o&&"rotate-90"),"aria-hidden":"true"})}):null]})})},_W=p.memo(jW),TW=({isExpanded:e,userToggled:t,wasAutoCollapsed:n,hasActivity:r,showWorkingStatus:s,hasFinalText:o,previousHadFinalText:i,hasNewActivity:a})=>r?s&&o&&!i?{isExpanded:!1,wasAutoCollapsed:!0,resetUserToggle:t}:t?{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1}:a&&n?{isExpanded:!0,wasAutoCollapsed:!1,resetUserToggle:!1}:s&&!o&&!e?{isExpanded:!0,wasAutoCollapsed:n,resetUserToggle:!1}:s&&o&&e?{isExpanded:!1,wasAutoCollapsed:!0,resetUserToggle:!1}:{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1}:{isExpanded:e,wasAutoCollapsed:n,resetUserToggle:!1},AW=p.memo(function({userMessage:t,renderMessage:n}){return n(t)},(e,t)=>e.userMessage===t.userMessage),NW=e=>{const t=e.summary.sourcePartId;return!t||!e.summary.text||e.summary.text.trim().length===0?!1:!e.activityParts.some(n=>n.id===t&&n.kind==="justification")},LW=({turn:e,renderMessage:t,deferEarlierAssistantMessages:n,showWorkingStatus:r=!1,isAwaitingRecovery:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,onActivityContentChange:a})=>{const l=p.useMemo(()=>e.activityParts.length>0,[e.activityParts]),d=p.useMemo(()=>NW(e),[e]),[f,u]=p.useState(()=>r&&l&&!d),h=p.useRef(!1),m=p.useRef(!1),g=p.useRef(e.activityParts.length),x=p.useRef(d);p.useLayoutEffect(()=>{const v=g.current,C=x.current,w=e.activityParts.length>v;g.current=e.activityParts.length,x.current=d;const M=TW({isExpanded:f,userToggled:h.current,wasAutoCollapsed:m.current,hasActivity:l,showWorkingStatus:r,hasFinalText:d,previousHadFinalText:C,hasNewActivity:w});m.current=M.wasAutoCollapsed,M.resetUserToggle&&(h.current=!1),M.isExpanded!==f&&u(M.isExpanded)},[l,d,f,r,e.activityParts.length]);const b=p.useCallback(()=>{h.current=!0,u(v=>!v),a?.("structural")},[a]),S=e.assistantMessages.length>0||r||s,y=p.useMemo(()=>new Set(e.activityParts.map(v=>v.id)),[e.activityParts]);return c.jsxs("section",{className:"relative w-full",id:`turn-${e.turnId}`,"data-turn-id":e.turnId,"data-scroll-spy-id":e.turnId,children:[c.jsx(AW,{userMessage:e.userMessage,renderMessage:t}),e.notices.length>0?e.notices.map(v=>c.jsx(p.Fragment,{children:t(v)},v.info.id)):null,S?c.jsx(_W,{turnId:e.turnId,isLiveTurn:r,isWorking:r,isAwaitingRecovery:s,hasActivity:l,isActivityExpanded:f,onToggleActivity:b,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,liveStatusText:e.isSteering?"Steering agent":void 0,wasSteered:e.stream.settledReason==="steered"}):null,l?c.jsx(eW,{turn:e,isExpanded:f,isLiveTurn:r,activeStreamingMessageId:o,activeStreamingPhase:i,onContentChange:a},e.turnId):null,c.jsx(fW,{turnId:e.turnId,assistantMessages:e.assistantMessages,renderMessage:t,deferEarlierMessages:n,activityPartIds:y})]})},RW=p.memo(LW),Kp="#pichamber-skill:",Gp="#pichamber-agent:",PW=e=>`${Kp}${encodeURIComponent(e)}`,DW=e=>`${Gp}${encodeURIComponent(e)}`,OW=e=>{if(!e?.startsWith(Kp))return null;try{return decodeURIComponent(e.slice(Kp.length))}catch{return null}},EJ=e=>{if(!e?.startsWith(Gp))return null;try{return decodeURIComponent(e.slice(Gp.length))}catch{return null}},HW=/(^|\s)\/skill:([A-Za-z0-9][A-Za-z0-9_-]*)/g,FW=/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g,BW=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),F7=(e,t)=>e.split(FW).map((n,r)=>r%2===1?n:t(n)).join(""),VW=e=>F7(e,t=>t.replace(/ *\n/g,`
205
+ `)),$W=({textContent:e,agentMention:t,skillNames:n})=>{let r=F7(e,BW);if(t?.token&&r.includes(t.token)){const s=`[${t.token}](${DW(t.name)})`;r=r.replace(t.token,s)}return r=r.replace(HW,(s,o,i)=>n.has(i)?`${o}[/skill:${i}](${PW(i)})`:s),VW(r)},zW=({part:e,messageId:t,agentMention:n})=>{const r=e,s=r.text,i=typeof s=="string"?s:r.content||r.value||"",[a,l]=p.useState(!1),[d,f]=p.useState(!1),u=Dr(w=>w.skills),h=Fa(),m=!a,g=p.useRef(null),x=p.useMemo(()=>new Map(u.map(w=>[w.name,w])),[u]),b=p.useCallback(w=>{x.has(w)&&Y4(w,h)},[h,x]),S=p.useCallback(w=>{if(typeof window>"u")return!1;const M=window.getSelection();if(!M||M.isCollapsed||M.rangeCount===0)return!1;const j=M.getRangeAt(0);return w.contains(j.startContainer)||w.contains(j.endContainer)},[]);p.useEffect(()=>{const w=g.current;if(!w)return;const M=()=>{a||f(w.scrollHeight>w.clientHeight)};M();const j=new ResizeObserver(M);return j.observe(w),()=>j.disconnect()},[i,a]);const y=p.useCallback(w=>{const M=w.target,T=M?.closest("[data-skill-name]")?.dataset.skillName??OW(M?.closest("a[href]")?.getAttribute("href"));if(T){w.preventDefault(),w.stopPropagation(),b(T);return}const A=g.current;A&&(S(A)||!a&&d&&l(!0))},[S,a,d,b]),v=p.useCallback(w=>{w.stopPropagation(),l(!1)},[]),C=p.useMemo(()=>$W({textContent:i,agentMention:n,skillNames:new Set(x.keys())}),[n,x,i]);return!i||i.trim().length===0?null:c.jsxs("div",{className:"relative",children:[a&&c.jsx("button",{type:"button",onClick:v,className:"absolute top-0 right-0 z-10 flex items-center justify-center rounded-sm bg-[var(--surface-elevated)] p-0.5 text-[var(--surface-mutedForeground)] hover:text-[var(--surface-foreground)] hover:bg-[var(--interactive-hover)] transition-colors","aria-label":"Collapse user message",children:c.jsx($,{name:"arrow-up-s",className:"h-3.5 w-3.5"})}),c.jsx("div",{className:R("break-words font-sans typography-markdown-body",a&&"pb-3",m&&"line-clamp-2",d&&!a&&"cursor-pointer"),ref:g,onClick:y,children:c.jsx(Oa,{content:C,className:R("[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",m&&["[&_.markdown-content>*]:my-0","[&_[data-component='markdown-code']]:my-0","[&_[data-component='markdown-code']]:inline","[&_[data-component='markdown-code']]:border-0","[&_[data-component='markdown-code']]:bg-transparent","[&_[data-component='markdown-code']>*:first-child]:hidden","[&_[data-component='markdown-code']>div]:inline","[&_[data-component='markdown-code']>div]:p-0","[&_[data-component='markdown-code']_pre]:inline","[&_[data-component='markdown-code']_code]:inline","[&_[data-md-code-line]]:!inline","[&_[data-md-code-line-number]]:hidden","[&_[data-md-code-line-break]]:!inline"]),disableLinkSafety:!0,enableFileReferences:!1})})]},e.id||`${t}-user-text`)},UW=p.memo(zW),qW="application/vnd.github.issue-link",WW="application/vnd.github.pull-request-link",B7=e=>e.mime===qW?"issue":e.mime===WW?"pr":null,V7=e=>!e||!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,KW=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},GW=e=>{if(!e)return"Unnamed file";const n=e.replace(/\\/g,"/").split("/");return n[n.length-1]||e},Zp=e=>B7(e)!==null&&typeof e.filename=="string"&&e.filename.trim().length>0?e.filename.trim():GW(e.filename||e.url),$7=H.memo(({files:e,onShowPopup:t,className:n})=>{const[r,s]=H.useState(!1),[o,i]=H.useState(null),a=H.useRef(null),l=H.useMemo(()=>e.filter(b=>b.type==="file"&&(b.filename||b.mime||b.url)),[e]),d=l.length,f=H.useCallback(()=>{const b=a.current?.closest('[data-slot="dialog-content"], [role="dialog"]');i(b||null)},[]),u=H.useCallback(b=>{te.getState().navigateToDiagram(b),s(!1)},[]);if(d===0)return null;const h=l[0],m=Zp(h),g=V7(h.size),x=d===1?`${m}${g?` (${g})`:""}`:`${d} attachments`;return c.jsxs(S5,{open:r,onOpenChange:s,children:[c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(C5,{render:c.jsxs("button",{ref:a,type:"button",className:R("inline-flex items-center gap-1.5 rounded-md px-1.5 py-1 text-xs font-medium","text-muted-foreground/80 hover:text-foreground transition-colors cursor-pointer select-none",n),"aria-label":`View ${d} attachment${d!==1?"s":""}`,onPointerDownCapture:f,onFocusCapture:f,children:[c.jsx($,{name:"attachment-2",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),c.jsx("span",{className:"truncate max-w-[200px]",children:x}),c.jsx($,{name:r?"arrow-up-s":"arrow-down-s",className:"h-3.5 w-3.5 shrink-0 opacity-60"})]})})}),c.jsx(xt,{side:"top",children:d===1?`Attachment: ${m}`:`View ${d} attachments`})]}),c.jsx(k5,{container:o||void 0,children:c.jsx(M5,{side:"top",align:"end",sideOffset:6,collisionPadding:8,children:c.jsxs(I5,{style:R3,className:R(L3,"w-84 max-h-96 overflow-y-auto p-3 space-y-3 transition-all duration-150 ease-out scrollbar-thin","data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95"),children:[c.jsx("div",{className:"flex items-center justify-between border-b border-border/30 pb-2",children:c.jsxs("span",{className:"text-xs font-semibold text-foreground flex items-center gap-1.5",children:[c.jsx($,{name:"attachment-2",className:"h-3.5 w-3.5 text-muted-foreground"}),"Attachments (",d,")"]})}),c.jsx("div",{className:"space-y-3 divide-y divide-border/20",children:l.map((b,S)=>{const y=b.url||`${Zp(b)}-${S}`;return c.jsx(ZW,{file:b,onShowPopup:t,onNavigateToDiagram:u},y)})})]})})})]})}),ZW=H.memo(function({file:t,onShowPopup:n,onNavigateToDiagram:r}){const s=Zp(t),o=KW(s),i=V7(t.size),l=!!(t.mime?.startsWith("image/")&&t.url),d=B7(t),f=t.source,u=typeof f?.type=="string"?f.type:void 0,h=f&&typeof f.path=="string"?f.path:void 0,m=u==="file"&&h?h:t.url||"",g=m&&a3(m),x=H.useCallback(()=>{n&&t.url&&n({open:!0,title:s,content:"",image:{url:t.url,mimeType:t.mime,filename:s,size:t.size}})},[n,t.url,t.mime,t.size,s]),b=H.useCallback(v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),x())},[x]),S=c.jsxs("div",{className:"flex items-start gap-2.5",children:[c.jsx(hr,{filePath:s,extension:o,className:"size-5 shrink-0 mt-0.5"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"text-xs font-medium text-foreground truncate",title:s,children:s}),c.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:[o.toUpperCase()||"FILE",t.mime,i].filter(Boolean).join(" · ")})]}),d&&t.url?c.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),ka(t.url||"")},className:"shrink-0 p-1 text-muted-foreground hover:text-foreground rounded hover:bg-muted/40 transition-colors",title:"Open on GitHub","aria-label":"Open on GitHub",children:c.jsx($,{name:"github",className:"h-4 w-4"})}):g?c.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),r(m)},className:"shrink-0 p-1 text-muted-foreground hover:text-foreground rounded hover:bg-muted/40 transition-colors",title:"Open in diagram view","aria-label":"Open in diagram view",children:c.jsx($,{name:"external-link",className:"h-4 w-4"})}):null]});if(!l||!t.url)return c.jsx("div",{className:"pt-3 first:pt-0 space-y-2",children:S});const y=t.url;return c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx("div",{role:"button",tabIndex:0,"aria-label":`Preview ${s}`,onClick:x,onKeyDown:b,className:"pt-3 first:pt-0 space-y-2 cursor-pointer rounded-lg",children:S})}),c.jsx(xt,{side:"left",className:R(l3),children:c.jsx(d3,{imageUrl:y,filename:s,metaLine:[o.toUpperCase(),i].filter(Boolean).join(" · ")})})]})});$7.displayName="UserMessageAttachments";const z7=e=>{if(e==="12h")return!0;if(e==="24h")return!1},YW=(e,t,n={})=>{const r=e instanceof Date?e:new Date(e);return Number.isFinite(r.getTime())?r.toLocaleTimeString("en-US",{hour:n.hour??"numeric",minute:"2-digit",second:n.precision==="second"?"2-digit":void 0,hour12:z7(t)}):n.fallback??""},jJ=(e,t,n)=>{const r=e instanceof Date?e:new Date(e);return Number.isFinite(r.getTime())?r.toLocaleString("en-US",{...n,hour12:n.hour?z7(t):n.hour12}):""},U7=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),XW=(e,t)=>{const n=new Date(t);return n.setDate(t.getDate()-1),U7(e,n)},JW=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),q7=(e,t)=>{if(!JW(e))return"";const n=new Date(e),r=new Date,s=YW(n,t),o="en-US";if(U7(n,r))return s;if(XW(n,r))return`Yesterday ${s}`;const i=n.toLocaleString(o,{month:"short"}),a=n.getDate(),l=`${i} ${a}`;return n.getFullYear()===r.getFullYear()?`${l}, ${s}`:`${l}, ${n.getFullYear()}, ${s}`},q1=p.memo(({sessionId:e,messageId:t,size:n="user",isLatestMessage:r=!1})=>{const s=pe(m=>m.revertToMessage),[o,i]=p.useState(!1),[a,l]=p.useState(()=>{if(!e)return!1;const g=Ue().getState().reducer.bySession.get(e);return g?.lifecycle==="busy"||g?.lifecycle==="retry"});p.useEffect(()=>{if(!e){l(!1);return}const m=()=>{const x=Ue().getState().reducer.bySession.get(e);l(x?.lifecycle==="busy"||x?.lifecycle==="retry")};return m(),Ue().subscribe(m,`session:${e}`)},[e]);const d=p.useCallback(async m=>{if(m.stopPropagation(),m.preventDefault(),!e||!t||o||a)return;const g=t.includes(":")?t.split(":")[0]??t:t;i(!0);try{await s(e,g),Ce.success("Reverted — conversation rewound. Files on disk were not changed.")}catch(x){const b=x instanceof Error?x.message:"Failed to revert conversation";Ce.error(b)}finally{i(!1)}},[o,a,t,s,e]),f=o||a||!e||!t,u=n==="user"?"h-6 w-6":"h-8 w-8",h=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return r?null:c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Se,{type:"button",variant:"ghost",size:"icon",disabled:f,"aria-label":"Revert conversation to here",className:R(u,"text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",f&&"opacity-50"),onPointerDown:m=>m.stopPropagation(),onClick:d,children:o?c.jsx($,{name:"loader-4",className:R(h,"animate-spin"),"aria-hidden":"true"}):c.jsx($,{name:"history",className:h,"aria-hidden":"true"})})}),c.jsx(xt,{sideOffset:6,children:"Revert to here"})]})});q1.displayName="MessageRevertAction";const W1=p.memo(({sessionId:e,messageId:t,size:n="user"})=>{const r=pe(h=>h.forkFromMessage),[s,o]=p.useState(!1),[i,a]=p.useState(()=>{if(!e)return!1;const m=Ue().getState().reducer.bySession.get(e);return m?.lifecycle==="busy"||m?.lifecycle==="retry"});p.useEffect(()=>{if(!e){a(!1);return}const h=()=>{const g=Ue().getState().reducer.bySession.get(e);a(g?.lifecycle==="busy"||g?.lifecycle==="retry")};return h(),Ue().subscribe(h,`session:${e}`)},[e]);const l=p.useCallback(async h=>{if(h.stopPropagation(),h.preventDefault(),!e||!t||s||i)return;const m=t.includes(":")?t.split(":")[0]??t:t;o(!0);try{await r(e,m),Ce.success("Forked — new session created from this message.")}catch(g){const x=g instanceof Error?g.message:"Failed to fork session";Ce.error(x)}finally{o(!1)}},[s,r,i,t,e]),d=s||i||!e||!t,f=n==="user"?"h-6 w-6":"h-8 w-8",u=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Se,{type:"button",variant:"ghost",size:"icon",disabled:d,"aria-label":"Fork conversation from here",className:R(f,"text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",d&&"opacity-50"),onPointerDown:h=>h.stopPropagation(),onClick:l,children:s?c.jsx($,{name:"loader-4",className:R(u,"animate-spin"),"aria-hidden":"true"}):c.jsx($,{name:"git-branch",className:u,"aria-hidden":"true"})})}),c.jsx(xt,{sideOffset:6,children:"Fork to new session"})]})});W1.displayName="MessageForkAction";const QW=e=>{if(!e||typeof e!="object")return null;const t=typeof e.providerID=="string"?e.providerID.trim():"",n=typeof e.modelID=="string"?e.modelID.trim():"";return!t||!n?null:`${t}/${n}`},eK=({part:e})=>{const[t,n]=p.useState(!1),r=Qn(),s=pe(m=>m.setCurrentSession),o=Fa(),i=typeof e.description=="string"?e.description.trim():"",a=typeof e.command=="string"?e.command.trim():"",l=typeof e.agent=="string"?e.agent.trim():"",d=typeof e.prompt=="string"?e.prompt.trim():"",f=typeof e.taskSessionID=="string"?e.taskSessionID.trim():"",u=QW(e.model),h=p.useCallback(()=>{!r||!f||(s(f,r),o?.closeDrawers?.())},[r,f,s,o]);return c.jsxs("div",{className:"mt-2",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Delegated task"}),a?c.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground",children:["/",a]}):null,l?c.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground",children:["@",l]}):null,u?c.jsx("span",{className:"inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground",children:u}):null]}),i?c.jsx("div",{className:"typography-ui-label text-foreground/90 mt-1.5",children:i}):null,d?c.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>n(m=>!m),children:t?"Hide prompt":"Show prompt"}),t?c.jsx("pre",{className:"typography-meta mt-1.5 overflow-x-auto whitespace-pre-wrap break-words text-foreground/85","data-no-drawer-swipe":"true",children:d}):null]}):null,f?c.jsx("div",{className:"mt-1.5",children:c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:h,children:"Open subtask session"})}):null]})},yx={background:"transparent",backgroundColor:"transparent"},tK=({part:e})=>{const t=typeof e.shellAction?.output=="string"?e.shellAction.output:"",[n,r]=p.useState(!0),{value:s,show:o}=E1(!1,2e3),i=typeof e.shellAction?.command=="string"?e.shellAction.command.trim():"",a=typeof e.shellAction?.status=="string"?e.shellAction.status.trim().toLowerCase():"",l=t.trim().length>0,d=p.useCallback(async()=>{!l||!(await gr(t)).ok||o(!0)},[l,t,o]);return c.jsxs("div",{className:"mt-2",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Shell command"}),a?c.jsx("span",{className:R("inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none",a==="error"?"bg-[var(--status-error-background)] text-[var(--status-error)]":"bg-foreground/5 text-muted-foreground"),children:a}):null]}),i?c.jsx("div",{className:"typography-meta mt-1.5 overflow-x-auto font-mono","data-no-drawer-swipe":"true",children:c.jsx(jd,{language:"bash",code:i,codeStyle:yx,wrap:!0})}):null,l?c.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[c.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[c.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>r(f=>!f),children:n?"Hide output":"Show output"}),c.jsx("button",{type:"button",className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:()=>{d()},"aria-label":s?"Copied":"Copy output",title:s?"Copied":"Copy output",children:s?c.jsx($,{name:"check",className:"h-3.5 w-3.5"}):c.jsx($,{name:"file-copy",className:"h-3.5 w-3.5"})})]}),n?c.jsx("div",{className:"typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85",children:c.jsx(jd,{language:"bash",code:t,codeStyle:yx,wrap:!0})}):null]}):null]})},nK={contain:"layout",transform:"translateZ(0)"},rK=p.memo(function({sessionId:t,messageId:n,parts:r,messageCreatedAt:s,isLatestMessage:o=!1,isMobile:i,alwaysShowActions:a=i,hasTouchInput:l,hasTextContent:d,onCopyMessage:f,copiedMessage:u,onShowPopup:h,agentMention:m,userActionsMode:g="inline"}){const x=te(z=>z.timeFormatPreference),[b,S]=p.useState(!1),y=p.useRef(null),v=p.useMemo(()=>r.filter(L7),[r]),C=p.useMemo(()=>r.filter(z=>z.type==="file"&&!!(z.filename||z.mime||z.url)),[r]),w=m?.token;let M=!1;const j=!!f,T=!!u,A=!!(l??i),_=!!d,k=g!=="external-actions",E=g!=="external-content",I=p.useCallback(()=>{y.current!==null&&typeof window<"u"&&(window.clearTimeout(y.current),y.current=null)},[]),N=p.useCallback(()=>{!A||!j||!_||typeof window>"u"||(I(),S(!0),y.current=window.setTimeout(()=>{S(!1),y.current=null},1800))},[j,I,_,A]);p.useEffect(()=>{_||(S(!1),I())},[I,_]);const O=p.useCallback(z=>{!f||!_||(z.stopPropagation(),z.preventDefault(),f(),A&&N())},[_,A,f,N]),L=p.useMemo(()=>{if(typeof s!="number"||s<=0)return null;const z=q7(s,x);return z.length>0?z:null},[s,x]),D=i||a,W=E?c.jsx("div",{className:R("group/user-actions",D?g==="inline"?"mt-2 mb-1 flex items-center justify-end":"flex min-h-11 items-start justify-end pt-0":g==="inline"?"absolute top-full left-0 right-0 z-10 pt-5":"flex min-h-8 items-start justify-end pt-2"),children:c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-1",children:[c.jsxs("div",{className:R("flex items-center justify-start gap-1.5",g==="inline"?"translate-x-5":"translate-x-0",a?"pointer-events-auto opacity-100":"pointer-events-none opacity-0 transition-opacity duration-150 group-hover/message:pointer-events-auto group-hover/message:opacity-100 group-hover/user-actions:pointer-events-auto group-hover/user-actions:opacity-100 group-hover/user-shell:pointer-events-auto group-hover/user-shell:opacity-100"),children:[L?c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("span",{className:"mr-1 flex items-center gap-1 text-sm tabular-nums text-muted-foreground/60","aria-label":`Message time: ${L}`,children:[c.jsx($,{name:"time",className:"h-3.5 w-3.5"}),c.jsx("span",{className:"message-footer__label",children:L})]})}),c.jsx(xt,{children:L})]}):null,o?null:c.jsx(q1,{sessionId:t??null,messageId:n,size:"assistant"}),c.jsx(W1,{sessionId:t??null,messageId:n,size:"assistant"}),j&&_&&c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Se,{type:"button",variant:"ghost",size:"icon","data-visible":b||T?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:z=>z.stopPropagation(),onClick:O,onFocus:()=>S(!0),onBlur:()=>{T||S(!1)},children:T?c.jsx($,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):c.jsx($,{name:"file-copy",className:"h-3.5 w-3.5"})})}),c.jsx(xt,{sideOffset:6,children:"Copy message"})]})]}),C.length>0?c.jsx($7,{files:C,onShowPopup:h}):null]})}):null;return k?c.jsxs("div",{className:"relative w-full group/message",style:nK,onTouchStart:A&&j&&_?N:void 0,children:[c.jsx("div",{className:R("leading-relaxed text-foreground/90 text-base overflow-x-hidden","overflow-y-hidden"),style:void 0,children:v.map((z,J)=>{if(T7(z))return c.jsx(p.Fragment,{children:c.jsx(eK,{part:z})},z.id??`user-subtask-${J}`);if(A7(z))return c.jsx(p.Fragment,{children:c.jsx(tK,{part:z})},z.id??`user-shell-${J}`);let B;return m&&w&&!M&&$1(z).includes(w)&&(B=m,M=!0),c.jsx(p.Fragment,{children:c.jsx(UW,{part:z,messageId:n,isMobile:i,agentMention:B})},z.id??`user-text-${J}`)})}),W]}):c.jsx(c.Fragment,{children:W})}),vx=8,sK=280,oK=({containerRef:e})=>{const[t,n]=p.useState({x:0,y:0,show:!1}),[r,s]=p.useState(""),[o,i]=p.useState(""),a=p.useRef(!1),[l,d]=p.useState(!1),f=p.useRef(null),u=p.useRef(sK),h=p.useRef(null),m=p.useRef(null),g=p.useRef(null),x=p.useRef(!1),b=pe(_=>_.createSession),S=Ye(_=>_.setPendingInputText),y=te(_=>_.isMobile);p.useEffect(()=>{x.current=t.show},[t.show]),p.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),g.current!==null&&(window.clearTimeout(g.current),g.current=null)},[]);const v=p.useCallback(()=>{h.current=null,x.current&&(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),d(!1),n(_=>({..._,show:!1})),s(""),i(""),x.current=!1)},[]),C=p.useCallback(_=>{if(typeof window>"u")return _;const k=window.innerWidth,I=u.current/2,N=vx+I,O=k-vx-I;return N>O?k/2:Math.min(Math.max(_,N),O)},[]),w=p.useCallback(()=>{if(!h.current)return;const{plainText:_,markdownText:k,rect:E}=h.current,I=!t.show,N=y?E.left+E.width/2:C(E.left+E.width/2),O=E.top-10;s(_),i(k),n({x:N,y:O,show:!0}),x.current=!0,I&&(d(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{d(!1),m.current=null}))},[C,y,t.show]);p.useLayoutEffect(()=>{if(!t.show||y||!f.current)return;const _=f.current.offsetWidth;!Number.isFinite(_)||_<=0||_===u.current||(u.current=_,n(k=>({...k,x:C(k.x)})))},[C,y,t.show]),p.useEffect(()=>{if(!t.show||y)return;const _=()=>{n(k=>({...k,x:C(k.x)}))};return window.addEventListener("resize",_),()=>{window.removeEventListener("resize",_)}},[C,y,t.show]);const M=p.useCallback(()=>{const _=window.getSelection(),k=e.current;if(!_||!k){a.current||v();return}const E=wn(_.toString());if(!E){a.current||v();return}const I=_.getRangeAt(0);if(!k.contains(I.commonAncestorContainer)){a.current||v();return}const N=I.getBoundingClientRect();h.current={plainText:E,markdownText:Ww(I,E),rect:N},a.current||w()},[e,v,w]);p.useEffect(()=>{const _=e.current;if(!_)return;const k=()=>{a.current=!0,v()},E=()=>{a.current=!1,h.current&&(g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{g.current=null;const N=window.getSelection();N&&N.toString().trim()?w():v()},10))};document.addEventListener("selectionchange",M),_.addEventListener("mousedown",k),document.addEventListener("mouseup",E);const I=N=>{f.current&&!f.current.contains(N.target)&&!window.getSelection()?.toString().trim()&&v()};return document.addEventListener("mousedown",I),()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null),document.removeEventListener("selectionchange",M),_.removeEventListener("mousedown",k),document.removeEventListener("mouseup",E),document.removeEventListener("mousedown",I)}},[e,M,v,w]);const j=p.useCallback(()=>{if(!o)return;const _=e1(o);S(_,"append"),v(),window.getSelection()?.removeAllRanges(),queueMicrotask(()=>{Io()})},[o,S,v]),T=p.useCallback(async()=>{if(!r)return;await b(void 0,null,null)&&S(r,"replace"),v(),window.getSelection()?.removeAllRanges()},[r,b,S,v]),A=p.useCallback(async()=>{if(!r)return;const _=await gr(r);_.ok||console.error("Failed to copy:",_.error),v(),window.getSelection()?.removeAllRanges()},[r,v]);return t.show?y?pa.createPortal(c.jsx("div",{ref:f,className:R("fixed left-3 right-3 bottom-0 z-50 mx-auto max-w-[420px]","rounded-2xl border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] p-2 shadow-lg","safe-area-bottom","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",l?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),style:{bottom:"calc(0.5rem + env(safe-area-inset-bottom, 0px))"},children:c.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[c.jsxs("button",{onClick:j,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--primary-base)] text-[var(--primary-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Add to current chat",type:"button",children:[c.jsx($,{name:"add",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"Add to chat"})]}),c.jsxs("button",{onClick:T,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Create new session with selection",type:"button",children:[c.jsx($,{name:"chat-new",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"New session"})]}),c.jsxs("button",{onClick:A,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--surface-muted)] text-[var(--surface-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Copy",type:"button",children:[c.jsx($,{name:"file-copy",className:"h-5 w-5 flex-shrink-0"}),c.jsx("span",{className:"min-w-0 whitespace-normal",children:"Copy"})]})]})}),document.body):pa.createPortal(c.jsx("div",{ref:f,className:"fixed z-50",style:{left:t.x,top:t.y,transform:"translate(-50%, -100%)"},children:c.jsxs("div",{className:R("flex items-center gap-1 whitespace-nowrap","rounded-lg border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] shadow-none","px-1.5 py-1","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",l?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),children:[c.jsxs("button",{onClick:j,className:R("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Add to current chat",type:"button",children:[c.jsx($,{name:"add",className:"h-4 w-4"}),c.jsx("span",{className:"whitespace-nowrap",children:"Add to chat"})]}),c.jsx("div",{className:"w-px h-4 bg-[var(--interactive-border)]"}),c.jsxs("button",{onClick:T,className:R("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Create new session with selection",type:"button",children:[c.jsx($,{name:"chat-new",className:"h-4 w-4"}),c.jsx("span",{className:"whitespace-nowrap",children:"New session"})]})]})}),document.body):null},rl=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function iK(e){if(!e||e==="build")return rl[0];let t=0;for(let r=0;r<e.length;r++){const s=e.charCodeAt(r);t=(t<<5)-t+s,t=t&t}const n=1+Math.abs(t)%(rl.length-1);return rl[n]}const aK=p.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,onShareImage:r,sessionId:s,messageId:o,isLatestMessage:i=!1})=>{const a=gu(),[l,d]=p.useState(!1),{value:f,show:u,clear:h}=E1(!1,2e3),[m,g]=p.useState(!1),x=p.useRef(null),b=!!n,S=p.useCallback(()=>{x.current!==null&&typeof window<"u"&&(window.clearTimeout(x.current),x.current=null)},[]);p.useEffect(()=>S,[S]),p.useEffect(()=>{(!e||!b)&&(d(!1),S(),h())},[b,S,h,e]);const y=p.useCallback(()=>{!t||!b||!e||typeof window>"u"||(S(),d(!0),x.current=window.setTimeout(()=>{d(!1),x.current=null},1800))},[b,S,e,t]),v=p.useCallback(async w=>{!n||!e||(w.stopPropagation(),w.preventDefault(),await n()===!1)||(u(!0),t&&y())},[e,t,n,y,u]),C=p.useCallback(async w=>{if(w.stopPropagation(),w.preventDefault(),!(m||!e)){g(!0);try{const j=w.currentTarget.closest("[data-message-text-export-root]")?.querySelector("[data-message-text-export-source]")??null;await r(j)}finally{g(!1)}}},[e,m,r]);return c.jsxs(c.Fragment,{children:[s&&o&&!i?c.jsx(q1,{sessionId:s,messageId:o,size:"assistant"},"message-revert"):null,s&&o?c.jsx(W1,{sessionId:s,messageId:o,size:"assistant"},"message-fork"):null,n&&c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Se,{type:"button",variant:"ghost",size:"icon","data-visible":l||f?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!e&&"opacity-50"),disabled:!e,"aria-label":"Copy message text","aria-hidden":!e,onPointerDown:w=>w.stopPropagation(),onClick:w=>{v(w)},onFocus:()=>{e&&d(!0)},onBlur:()=>{f||d(!1)},children:f?c.jsx($,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):c.jsx($,{name:"file-copy",className:"h-3.5 w-3.5"})})}),c.jsx(xt,{sideOffset:6,children:"Copy answer"})]},"message-copy"),a!=="mini-chat"?c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Se,{type:"button",size:"icon",variant:"ghost",disabled:m||!e,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",(!e||m)&&"opacity-50"),onPointerDown:w=>w.stopPropagation(),onClick:w=>{C(w)},children:m?c.jsx($,{name:"loader-4",className:"h-4 w-4 animate-spin"}):c.jsx($,{name:"image-download",className:"h-4 w-4"})})}),c.jsx(xt,{sideOffset:6,children:m?"Saving image...":"Save as image"})]},"message-share"):null]})});async function cK(e,t){const n=t;if(!n)return;let r=null;try{const{toPng:s}=await mt(async()=>{const{toPng:y}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{toPng:y}},[]),o=n,i=window.getComputedStyle(o),l=window.getComputedStyle(document.documentElement).getPropertyValue("--surface-background").trim()||i.backgroundColor||window.getComputedStyle(document.body).backgroundColor,d=24;r=document.createElement("div"),r.setAttribute("data-message-image-export","true"),r.style.cssText=`
206
+ padding: ${d}px;
207
+ background-color: ${l};
208
+ display: inline-block;
209
+ `;const f=o.cloneNode(!0);f.style.cssText=`
210
+ ${i.cssText}
211
+ transform: none;
212
+ contain: none;
213
+ `,f.querySelectorAll('[data-message-actions="true"]').forEach(y=>{y.style.display="none"}),f.querySelectorAll('[data-message-action-group="true"]').forEach(y=>{y.style.display="none"});const m=f.querySelectorAll('[aria-label^="Message time:"]'),g=new Set;m.forEach(y=>{const C=y.getAttribute("aria-label")?.replace("Message time:","").trim();if(!C||y.textContent?.includes(C))return;const w=document.createElement("span");w.style.marginLeft="4px",w.textContent=C,y.appendChild(w);const j=y.parentElement?.parentElement;!j||g.has(j)||(j.style.justifyContent="flex-start",g.add(j))}),r.appendChild(f),document.body.appendChild(r);const x=await s(r,{quality:1,pixelRatio:2,backgroundColor:l}),b=`message-${e}.png`,S=await f8({filename:b,mimeType:"image/png",data:x});S==="downloaded"?Ce.success("Image saved"):S==="shared"&&Ce.success("Image shared")}catch(s){console.error("Failed to generate image:",s),Ce.error("Failed to generate image")}finally{r&&r.parentNode&&r.parentNode.removeChild(r)}}function lK({visibleParts:e,isMessageCompleted:t,messageFinish:n,messageCompletedAt:r,messageCreatedAt:s,durationMs:o,turnGroupingContext:i,errorMessage:a,isMobile:l,isMiniChatSurface:d,timeFormatPreference:f}){const u=p.useMemo(()=>e.filter(w=>w.type==="text"),[e]),h=p.useMemo(()=>{if(l||d)return null;for(const w of u){const M=w.text;if(typeof M!="string"||M.length===0)continue;const j=hT(M)[0];if(j)return j.includes("0.0.0.0")?j.replace("0.0.0.0","127.0.0.1"):j}return null},[u,l,d]),m=i?.isLastAssistantInTurn??!1,g=!!i?.isWorking,x=p.useRef(g),b=x.current&&!g;p.useEffect(()=>{x.current=g},[g]);const S=n==="stop"||t&&!a,y=!t,v=p.useMemo(()=>{if(!m||g)return;if(typeof o=="number"&&o>0)return Hl(o);if(typeof r=="number"&&typeof s=="number"&&r>s)return Hl(r-s);const w=i?.userMessageCreatedAt;if(typeof w=="number"&&typeof r=="number"&&r>w)return Hl(r-w)},[m,g,o,r,s,i?.userMessageCreatedAt]),C=p.useMemo(()=>{const w=typeof r=="number"&&r>0?r:typeof s=="number"&&s>0?s:null;if(w===null)return null;const M=q7(w,f);return M.length>0?M:null},[r,s,f]);return{messagePreviewUrl:h,isLastAssistantInTurn:m,isTurnWorking:g,shouldAnimateTurnFooter:b,hasStopFinish:S,awaitingMessageCompletion:y,turnDurationText:v,footerTimestamp:C}}const dK={contain:"layout",transform:"translateZ(0)"},uK={containerType:"inline-size",containerName:"message-footer"},fK=p.memo(({sessionId:e,messageId:t,parts:n,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,durationMs:a,isLatestMessage:l=!1,isMobile:d,alwaysShowActions:f,hasTouchInput:u,onShowPopup:h,streamPhase:m,onContentChange:g,hasTextContent:x=!1,onCopyMessage:b,turnGroupingContext:S,errorMessage:y,errorVariant:v="error",footerProviderID:C,footerModelName:w,footerAgentName:M,footerVariant:j,isDarkTheme:T=!1})=>{const A=gu(),_=p.useRef(null),k=p.useRef(null),E=!!(u??d),I=!!(f??d),{src:N,onError:O,hasLogo:L}=a1(C??null),D=p.useMemo(()=>z1(n),[n]),W=A==="mini-chat",z=pe(ue=>ue.currentSessionId),J=pe(ue=>ue.getDirectoryForSession),B=Qn(),U=te(ue=>ue.timeFormatPreference),P=te(ue=>ue.openContextPreview),{messagePreviewUrl:q,isLastAssistantInTurn:F,isTurnWorking:ee,shouldAnimateTurnFooter:G,hasStopFinish:K,awaitingMessageCompletion:se,turnDurationText:ce,footerTimestamp:re}=lK({visibleParts:D,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,durationMs:a,turnGroupingContext:S,errorMessage:y,isMobile:d,isMiniChatSurface:W,timeFormatPreference:U}),fe=K?"completed":m,ge=!!x&&!se,we=p.useCallback(async ue=>{const be=ue??k.current??_.current;await cK(t,be)},[t]),Me=!!y,He=v==="info"?"information":"error-warning",Ae=F&&(x||!!y)&&!ee,Ge=p.useMemo(()=>c.jsx(aK,{hasCopyableText:ge,isTouchContext:E,onCopyMessage:b,onShareImage:we,sessionId:e,messageId:t,isLatestMessage:l}),[we,ge,l,E,t,b,e]),et=p.useMemo(()=>{const ue=[];let be=0;for(;be<D.length;){const Ie=D[be];if(Ie.type!=="text"){be++;continue}ue.push(c.jsx("div",{ref:k,"data-message-text-export-source":"true",children:c.jsx(U4,{part:Ie,sessionId:e,messageId:t,streamPhase:fe,onContentChange:g,onShowPopup:h})},`assistant-text-${t}-${be}`)),be++}return ue},[t,e,g,h,fe,D]),Xe="text-sm text-muted-foreground tabular-nums flex items-center gap-1",oe=!W&&!d,Q=c.jsx(c.Fragment,{children:oe&&q?c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsx(Se,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Open preview",onPointerDown:ue=>ue.stopPropagation(),onClick:()=>{const ue=B??(z?J(z):null);ue&&P(ue,q)},children:c.jsx($,{name:"global",className:"h-4 w-4"})})}),c.jsx(xt,{sideOffset:6,children:"Open preview"})]}):null});return c.jsxs("div",{ref:_,"data-message-text-export-root":"true",className:R("relative w-full group/message"),style:dK,children:[c.jsx(oK,{containerRef:_}),c.jsxs("div",{children:[c.jsxs("div",{className:"message-content-text space-y-2 leading-relaxed overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[et,Me&&c.jsx(V1,{children:c.jsx("div",{className:R("group/assistant-text relative mt-3 p-3 rounded-lg border break-words max-w-full",v==="info"?"bg-[var(--status-info-background)] border-[var(--status-info-border)]":"bg-[var(--status-error-background)] border-[var(--status-error-border)]"),children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx($,{name:He,className:R("h-4 w-4 shrink-0",v==="info"?"text-[var(--status-info)]":"text-[var(--status-error)]")}),c.jsx("div",{className:"min-w-0 flex-1 break-words",children:c.jsx(Oa,{content:y??"",onShowPopup:h,className:"[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",enableFileReferences:!1})})]})})},"assistant-error")]}),c.jsx(i1,{files:n,onShowPopup:h}),Ae&&c.jsxs("div",{className:R("mt-2 mb-1 flex flex-wrap items-center justify-start gap-x-3 gap-y-1.5",G&&"message-footer-enter"),style:uK,children:[c.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1 text-sm text-muted-foreground",children:[w?c.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[L&&N?c.jsx("img",{src:N,alt:"",className:"h-3.5 w-3.5 flex-shrink-0",style:{filter:T?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:O}):c.jsx($,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0",style:{color:`var(${iK(M).var})`}}),c.jsx("span",{className:"truncate",children:w})]}):null,j&&!["default","none"].includes(j.toLowerCase())?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx($,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"message-footer__label",children:j[0].toLowerCase()+j.slice(1)})]}):null,M?c.jsxs("span",{className:"flex items-center gap-1",children:[c.jsx($,{name:"ai-agent",className:"h-3.5 w-3.5 flex-shrink-0"}),c.jsx("span",{className:"message-footer__label",children:M})]}):null,ce?c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("span",{className:"text-sm text-muted-foreground tabular-nums flex items-center gap-1",children:[c.jsx($,{name:"hourglass",className:"h-3.5 w-3.5"}),c.jsx("span",{className:"message-footer__label",children:ce})]})}),c.jsx(xt,{children:ce})]}):null,re?c.jsxs(yt,{children:[c.jsx(vt,{asChild:!0,children:c.jsxs("span",{className:Xe,"aria-label":`Message time: ${re}`,children:[c.jsx($,{name:"time",className:"h-3.5 w-3.5"}),c.jsx("span",{className:"message-footer__label",children:re})]})}),c.jsx(xt,{children:re})]}):null]}),c.jsxs("div",{className:R("flex items-center gap-1.5",I||E?void 0:"pointer-events-none opacity-0 transition-opacity duration-150 focus-within:pointer-events-auto focus-within:opacity-100 group-hover/message:pointer-events-auto group-hover/message:opacity-100"),"data-message-action-group":"true",children:[Ge,Q]})]})]})]})}),yh=p.memo(({isUser:e,...t})=>e?c.jsx(rK,{sessionId:t.sessionId,messageId:t.messageId,parts:t.parts,messageCreatedAt:t.messageCreatedAt,isMobile:t.isMobile,alwaysShowActions:t.alwaysShowActions,hasTouchInput:t.hasTouchInput,hasTextContent:t.hasTextContent,onCopyMessage:t.onCopyMessage,copiedMessage:t.copiedMessage,onShowPopup:t.onShowPopup,agentMention:t.agentMention,userActionsMode:t.userActionsMode}):c.jsx(fK,{...t})),Ad=e=>{const t=e,n=t?.clientRole,r=t?.role;return t?.userMessageMarker===!0||n==="user"||r==="user"||t?.origin==="user"||t?.source==="user"?{role:"user",isUser:!0}:{role:n||r||"assistant",isUser:!1}},W7="GitHub issue context (JSON)",K7="GitHub pull request context (JSON)",xx=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,bx=(e,t)=>{const n=e.trimStart();if(!n.startsWith(t))return null;const r=n.indexOf("{");if(r<0)return null;try{return JSON.parse(n.slice(r))}catch{return null}},hK=e=>{const t=bx(e,W7);if(t){const r=t.issue,s=r?.number,o=r?.title,i=r?.url;return!xx(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.issue-link",filename:`Issue #${s}: ${o}`,url:i}}const n=bx(e,K7);if(n){const r=n.pr,s=r?.number,o=r?.title,i=r?.url;return!xx(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.pull-request-link",filename:`PR #${s}: ${o}`,url:i}}return null},pK=e=>!!e.trim().startsWith("The following tool was executed by the user"),K1=e=>e.filter(t=>{if(!(t.synthetic===!0))return!0;if(t.type!=="text")return!1;const r=t.text;if(typeof r!="string")return!1;const s=r.trimStart();return pK(r)||s.startsWith(W7)||s.startsWith(K7)}).map(t=>{const n=t;if(n.type==="compaction")return{type:"text",text:"/compact"};if(n.type==="text"){const r=typeof n.text=="string"?n.text.trim():"";if(n.synthetic===!0){const o=hK(r);if(o)return o}if(r.startsWith("The following tool was executed by the user"))return{type:"text",text:"/shell"}}return t}),wx=new WeakMap,G7=e=>{if(!e||!Ad(e.info).isUser)return!1;const t=wx.get(e.parts);if(t!==void 0)return t;const n=K1(wu(e.parts)),r=U1(n,{includeReasoning:!0}).length===0;return wx.set(e.parts,r),r};function vh(e){const[t,n]=p.useState(e);return p.useEffect(()=>{e!=null&&n(e)},[e]),e??t}const xn=(e,t)=>{if(typeof e=="object"&&e!==null)return e[t]},us=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},Sx=e=>{const t=xn(e,"model"),n=typeof t=="object"&&t!==null?t:null;return{providerId:us(xn(e,"providerID"))??us(n?.providerID)??us(n?.providerId),modelId:us(xn(e,"modelID"))??us(n?.modelID)??us(n?.modelId)}};function mK({message:e,previousMessage:t,isUser:n,sessionId:r,isInActiveTurn:s,turnGroupingContext:o}){const i=We(E=>E.providers),a=At(E=>E.getAgentModelForSession),l=At(E=>E.getSessionModelSelection),d=At(d8(E=>s&&r?E.sessionAgentSelections.get(r)??null:null)),f=p.useMemo(()=>{if(n||!t)return null;const E=xn(t.info,"clientRole"),I=xn(t.info,"role");if((typeof E=="string"?E:typeof I=="string"?I:void 0)!=="user")return null;const O=xn(t.info,"mode"),L=xn(t.info,"agent"),D=Sx(t.info),W=xn(t.info,"variant"),z=typeof O=="string"&&O.trim().length>0?O:typeof L=="string"&&L.trim().length>0?L:void 0,J=D.providerId,B=D.modelId,U=typeof W=="string"&&W.trim().length>0?W:void 0;return!z&&!J&&!B&&!U?null:{agentName:z,providerId:J,modelId:B,variant:U}},[n,t]),u=p.useMemo(()=>{if(n)return;const E=xn(e.info,"mode");if(typeof E=="string"&&E.trim().length>0)return E;const I=xn(e.info,"agent");if(typeof I=="string"&&I.trim().length>0)return I;if(f?.agentName)return f.agentName;if(r)return d??void 0},[n,e.info,f,r,d]),h=n?{providerId:void 0,modelId:void 0}:Sx(e.info),m=h.providerId??null,g=h.modelId??null,x=p.useMemo(()=>{if(n||!r)return null;if(f?.providerId&&f?.modelId)return{providerId:f.providerId,modelId:f.modelId};if(u){const I=a(r,u);if(I?.providerId&&I?.modelId)return I}const E=l(r);return E?.providerId&&E?.modelId?E:null},[n,r,u,f,a,l]),b=p.useMemo(()=>n?null:typeof m=="string"&&m.trim().length>0?m:x?.providerId??null,[n,m,x]),S=p.useMemo(()=>n?null:typeof g=="string"&&g.trim().length>0?g:x?.modelId??null,[n,g,x]),y=p.useMemo(()=>{if(n)return;const E=b&&i.length>0?i.find(I=>I.id===b):void 0;return d1(E,S)||void 0},[n,b,S,i]),v=p.useMemo(()=>{if(n||!b||!S)return!1;const E=i.find(O=>O.id===b);if(!E?.models||!Array.isArray(E.models))return!1;const N=E.models.find(O=>O.id===S)?.variants;return!!(N&&Object.keys(N).length>0)},[n,S,b,i]),C=vh(u),w=vh(b??void 0),M=vh(y),j=C??void 0,T=w??null,A=M??void 0,_=n?void 0:us(xn(e.info,"variant"))??o?.userMessageVariant??f?.variant;return{headerAgentName:j,headerProviderID:T,headerModelName:A,headerVariant:n?void 0:v?_??"Default":_}}class ws{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return ws.instance||(ws.instance=new ws),ws.instance}recordSessionStart(t){this.sessionStartTimes.set(t,Date.now())}getSessionStartTime(t){return this.sessionStartTimes.get(t)}shouldAnimateMessage(t,n){if(t.role!=="assistant"||this.seenMessageIds.has(t.id))return!1;const r=t.time?.created;if(typeof r!="number"||!Number.isFinite(r))return this.seenMessageIds.add(t.id),!1;const s=this.sessionStartTimes.get(n);if(!s)return this.seenMessageIds.add(t.id),this.messageCreationTimes.set(t.id,r),!1;const o=r>s-5e3;return this.seenMessageIds.add(t.id),this.messageCreationTimes.set(t.id,r),o}clearSession(t){this.sessionStartTimes.delete(t)}hasSessionTiming(t){return this.sessionStartTimes.has(t)}hasBeenAnimated(t){return this.seenMessageIds.has(t)}markMessageAsAnimated(t,n){this.seenMessageIds.add(t),this.messageCreationTimes.set(t,n)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function gK({message:e,isUser:t,sessionId:n,streamPhase:r,assistantTextParts:s,shouldCoordinateRendering:o,animationHandlers:i,messageContainerRef:a}){const l=p.useMemo(()=>t||!n?!1:ws.getInstance().shouldAnimateMessage(e.info,n),[e.info,t,n]),d=i??null,f=p.useRef(!1),u=p.useRef(!1),h=p.useRef(!1),m=p.useRef(!1),g=p.useRef(!1);p.useEffect(()=>{f.current=!1,u.current=!1,h.current=!1,m.current=!1,g.current=!1},[e.info.id]);const x=!!xn(e.info,"animationSettled"),b=r==="streaming"||r==="cooldown";b&&(g.current=!0);const S=l&&!x&&!b&&!g.current,y=!t&&l&&s.length>0&&!o;p.useEffect(()=>{if(d?.onStreamingCandidate){if(!y){u.current&&(d?.onReservationCancelled&&d.onReservationCancelled(),u.current=!1);return}m.current||(m.current=!0,d.onStreamingCandidate(),u.current=!0)}},[d,y]),p.useEffect(()=>{d?.onAnimationStart&&S&&(h.current||(d.onAnimationStart(),h.current=!0))},[d,S]),p.useEffect(()=>{if(t)return;const v=d?.onAnimatedHeightChange;if(!v||!(S||y))return;const w=a.current;if(!w)return;if(typeof window>"u"||typeof ResizeObserver>"u"){v(w.getBoundingClientRect().height);return}let M=null;const j=A=>{if(typeof window>"u"){v(A);return}M!==null&&window.cancelAnimationFrame(M),M=window.requestAnimationFrame(()=>{v(A)})},T=new ResizeObserver(A=>{const _=A[0];_&&j(_.contentRect.height)});return T.observe(w),j(w.getBoundingClientRect().height),()=>{M!==null&&(window.cancelAnimationFrame(M),M=null),T.disconnect()}},[S,t,d,y,a])}function yK(){const e=te(o=>o.setImagePreviewOpen),[t,n]=p.useState({open:!1,title:"",content:""}),r=p.useCallback(o=>{(o.image||o.mermaid)&&(n(o),e(!0))},[e]),s=p.useCallback(o=>{n(i=>({...i,open:o})),e(o)},[e]);return{popupContent:t,handleShowPopup:r,handlePopupChange:s}}const vK=Rs(()=>mt(()=>import("./ToolOutputDialog-QC8IoeBH.js"),__vite__mapDeps([62,5,1,6,63,64,65,8,66,28,29,30,31,32,33,34,35,36,37,38,39,40,41,67,26,27,68,69,70,71,72,73,74,75,76,17,11,18,19,20,77,78,79,80,81,25,43,42]))),xK=({message:e,previousMessage:t,nextMessage:n,onContentChange:r,animationHandlers:s,turnGroupingContext:o,isInActiveTurn:i=!1,activeStreamingPhase:a=null,animateUserOnMount:l=!1,onUserAnimationConsumed:d})=>{const{isMobile:f,isTablet:u,hasTouchInput:h}=On(),m=f||u,{currentTheme:g}=Jn(),x=p.useRef(null);Is("ui.chat_message.render"),i&&Is("ui.chat_message.render.streaming");const[b,S]=p.useState(!1),v=p.useMemo(()=>Ad(e.info),[e.info]).isUser,C=e.info.sessionID,{headerAgentName:w,headerProviderID:M,headerModelName:j,headerVariant:T}=mK({message:e,previousMessage:t,isUser:v,sessionId:C,isInActiveTurn:i,turnGroupingContext:o}),A=p.useMemo(()=>{const Ie=wu(e.parts);return v?K1(Ie):Ie},[v,e.parts]),_=p.useMemo(()=>{const Ie=e.info.time;return typeof Ie?.completed=="number"?Ie.completed:null},[e.info.time]),k=p.useMemo(()=>{const Ie=e.info.time;return typeof Ie?.created=="number"?Ie.created:null},[e.info.time]),E=p.useMemo(()=>v?!0:!!(_&&_>0),[v,_]),I=p.useMemo(()=>{const Ie=e.info.finish;return typeof Ie=="string"?Ie:void 0},[e.info]),N=p.useMemo(()=>U1(A,{includeReasoning:!0}),[A]),O=p.useMemo(()=>{const Ie=new Set;for(const Fe of o?.activityParts??[])Ie.add(Fe.id);return Ie},[o?.activityParts]),L=p.useMemo(()=>v?N:R7(N,O,e.info.id),[O,v,e.info.id,N]),D=v&&L.some(L7),W=p.useMemo(()=>v?[]:L.filter(Ie=>Ie.type==="text"),[L,v]),z=p.useMemo(()=>v?[]:N.filter(Ie=>Ie.type==="tool"),[v,N]),{popupContent:J,handleShowPopup:B,handlePopupChange:U}=yK(),P=p.useMemo(()=>{if(!v)return;const Ie=A.find(Ze=>Ze.type==="agent");if(!Ie)return;const Fe=Ie,ht=typeof Fe.name=="string"?Fe.name:void 0;if(!ht)return;const ye=Fe.source&&typeof Fe.source.value=="string"&&Fe.source.value.trim().length>0?Fe.source.value:`@${ht}`;return{name:ht,token:ye}},[v,A]),q=v&&L.length===0,F=!E&&typeof I!="string",ee=p.useMemo(()=>v?!1:W.length===0||z.length===0?F:!0,[W.length,z.length,F,v]),G=g?.metadata.variant,K=p.useMemo(()=>G?G==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[G]),se=p.useMemo(()=>n?Ad(n.info):null,[n]),ce=!!o,re=o?.isLastAssistantInTurn??!1,fe=p.useMemo(()=>!v&&G7(n),[v,n]),ge=p.useMemo(()=>v?!1:ce?!re:se?!se.isUser&&se.role==="assistant":!1,[ce,re,v,se]),we=p.useMemo(()=>E?"completed":i?a??"streaming":"completed",[a,i,E]);gK({message:e,isUser:v,sessionId:C,streamPhase:we,assistantTextParts:W,shouldCoordinateRendering:ee,animationHandlers:s,messageContainerRef:x}),p.useEffect(()=>{!v||!l||d?.(e.info.id)},[l,v,e.info.id,d]);const Me=p.useMemo(()=>{if(!v)return _7(e.info)},[v,e.info]),He=Me?.text,Ae=Me?.variant,Ge=p.useMemo(()=>iW({isUser:v,displayParts:L,assistantErrorText:He}),[He,L,v]),et=Ge.length>0,Xe=p.useMemo(()=>v?!1:!cW(L,He),[He,L,v]),oe=p.useCallback(async()=>{let Ie;if(v)Ie=await gr(Ge);else{const{renderMarkdownSync:Fe}=await mt(async()=>{const{renderMarkdownSync:ht}=await import("./markdownCore-DbS8DkKw.js").then(ye=>ye.m);return{renderMarkdownSync:ht}},__vite__mapDeps([21,8,22,23,24]));Ie=await hj(Ge,Fe(Ge))}return Ie.ok?(v&&(S(!0),setTimeout(()=>S(!1),2e3)),!0):!1},[v,Ge]);if(q||Xe)return null;const Q="pt-0",ue="var(--radius-xl)",be={sessionId:e.info.sessionID,messageId:e.info.id,parts:L,isUser:v,isMessageCompleted:E,messageFinish:I,messageCreatedAt:k??void 0,isMobile:f,alwaysShowActions:m,hasTouchInput:h,onShowPopup:B,streamPhase:we,onContentChange:r,hasTextContent:et,onCopyMessage:oe,copiedMessage:b,agentMention:P,errorMessage:He,errorVariant:Ae,isLatestMessage:!n};return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:R("group w-full",v?f?"pt-2":"pt-4":Q,v?f?"pb-0":"pb-2":ge||fe?"pb-0":"pb-2"),id:`message-${e.info.id}`,"data-message-id":e.info.id,ref:x,children:c.jsx("div",{className:"chat-message-column relative",children:v?L.length===0?null:c.jsx(V1,{forceAnimation:!0,skipAnimation:!l,ignoreContextDisabled:!0,respectReducedMotion:!0,children:c.jsx("div",{className:R("relative flex justify-end",f?void 0:"group/user-shell"),children:c.jsxs("div",{className:"max-w-[85%]",children:[D?c.jsx("div",{style:{backgroundColor:"var(--chat-user-message-bg)",borderRadius:ue,borderBottomRightRadius:"var(--radius-sm)"},className:R("shadow-none border border-primary/5",f?"px-3 py-2":"px-5 py-3",!f&&"pb-4"),children:c.jsx(yh,{...be,userActionsMode:"external-content"})}):null,c.jsx(yh,{...be,userActionsMode:"external-actions"})]})})}):c.jsx("div",{className:"relative",children:c.jsx(yh,{sessionId:e.info.sessionID,messageId:e.info.id,parts:L,isUser:v,isMessageCompleted:E,isLatestMessage:!n,messageFinish:I,messageCompletedAt:_??void 0,messageCreatedAt:k??void 0,durationMs:e.info.durationMs,isMobile:f,alwaysShowActions:m,hasTouchInput:h,onShowPopup:B,streamPhase:we,onContentChange:r,hasTextContent:et,onCopyMessage:oe,copiedMessage:b,agentMention:P,turnGroupingContext:o,errorMessage:He,errorVariant:Ae,footerProviderID:M,footerModelName:j,footerAgentName:w,footerVariant:T,isDarkTheme:K})})})}),c.jsx(p.Suspense,{fallback:null,children:c.jsx(vK,{popup:J,onOpenChange:U,isMobile:f})})]})},bK=p.memo(xK,(e,t)=>J4({info:e.message.info,parts:e.message.parts},{info:t.message.info,parts:t.message.parts})&&kd(e.previousMessage?{info:e.previousMessage.info,parts:e.previousMessage.parts}:void 0,t.previousMessage?{info:t.previousMessage.info,parts:t.previousMessage.parts}:void 0)&&kd(e.nextMessage?{info:e.nextMessage.info,parts:e.nextMessage.parts}:void 0,t.nextMessage?{info:t.nextMessage.info,parts:t.nextMessage.parts}:void 0)&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&Q4(e.turnGroupingContext,t.turnGroupingContext,e.message.info.id,Ad(e.message.info).isUser)),Cx={info:"bg-status-info/15 text-status-info",success:"bg-status-success/15 text-status-success",warning:"bg-status-warning/15 text-status-warning",error:"bg-status-error/15 text-status-error",neutral:"bg-interactive-hover text-muted-foreground"},wK=e=>typeof e=="string"&&e.length>0&&e in xw,SK=({action:e,variant:t,sessionId:n})=>{const[r,s]=H.useState(!1),[o,i]=H.useState(!1),[a,l]=H.useState(!1),[d,f]=H.useState(""),u=H.useCallback(async b=>{if(!(!n||r)){s(!0);try{await Ue().prompt(n,p5(e.command,b),"prompt")}finally{s(!1)}}},[n,r,e.command]),h=H.useCallback(async()=>{if(e.promptForArgs){l(!0),f("");return}await u(e.args)},[e,u]),m=H.useCallback(async()=>{if(!(!n||r||e.disabled)){if(e.confirm){i(!0);return}await h()}},[n,r,e,h]);if(!n)return null;const g=r||e.loading===!0,x=wK(e.icon)?c.jsx($,{name:e.icon,className:"size-3.5"}):null;return o?c.jsxs("div",{role:"alertdialog","aria-label":e.confirm,className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[c.jsx("span",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:e.confirm}),c.jsx(Se,{type:"button",size:"xs",variant:"default",onClick:()=>{i(!1),h()},children:"Continue"}),c.jsx(Se,{type:"button",size:"xs",variant:"ghost",onClick:()=>i(!1),children:"Cancel"})]}):a?c.jsxs("form",{className:"flex min-w-0 flex-wrap items-center gap-1.5",onSubmit:b=>{b.preventDefault(),l(!1),u(d)},children:[c.jsx("input",{autoFocus:!0,value:d,onChange:b=>f(b.target.value),placeholder:e.promptForArgs?.placeholder??"","aria-label":e.promptForArgs?.label??e.label,className:"h-6 min-w-0 flex-1 rounded-md border bg-transparent px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focus sm:w-40 sm:flex-none",onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),l(!1))}}),c.jsx(Se,{type:"submit",size:"xs",variant:"default",disabled:r,children:"Run"}),c.jsx(Se,{type:"button",size:"xs",variant:"ghost",onClick:()=>l(!1),children:"Cancel"})]}):c.jsxs(Se,{size:"xs",variant:t,onClick:()=>{m()},disabled:g||e.disabled,"aria-label":e.label,children:[g?c.jsx("span",{"aria-hidden":"true",className:"size-3.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent"}):x,e.label]})},CK=({label:e,value:t,max:n})=>{const r=Math.min(Math.max(t,0),n),s=Math.round(r/n*100);return c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:e??""}),c.jsxs("span",{className:"tabular-nums text-muted-foreground",children:[s,"%"]})]}),c.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-interactive-hover",role:"progressbar","aria-valuenow":s,"aria-valuemin":0,"aria-valuemax":100,"aria-label":e??"Progress",children:c.jsx("div",{className:"h-full rounded-full bg-primary transition-[width] duration-300",style:{width:`${s}%`}})})]})},kK=({body:e,messageId:t,text:n})=>{const[r,s]=H.useState(!1),o=typeof n=="string"&&n.trim().length>0;return c.jsxs("div",{className:"flex flex-col gap-1.5",children:[o&&c.jsx(Bo,{messageId:t,content:n,className:"text-sm text-foreground"}),e&&e!==n&&c.jsxs("div",{children:[c.jsxs(Se,{type:"button",variant:"ghost",size:"xs",onClick:()=>s(i=>!i),"aria-expanded":r,className:"h-5 gap-1 px-1.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:r?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:"Details"})]}),r&&c.jsx("pre",{className:"mt-1.5 max-h-64 overflow-auto rounded-md border border-border/40 bg-muted/40 p-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground",children:c.jsx("code",{children:e})})]})]})},MK=({sessionId:e,messageId:t,customType:n,text:r,data:s,details:o,className:i})=>{const a=H.useMemo(()=>B5({customType:n,data:s,details:o,text:r}),[n,s,o,r]),l=a.kind==="ui"?a.descriptor.title:a.title,d=a.kind==="ui"?a.descriptor.actions:void 0,f=a.kind==="ui"?a.descriptor.component:void 0,u=()=>{if(!f)return c.jsx(kK,{body:a.kind==="fallback"?a.body:"",messageId:t,text:r});switch(f.component){case"markdown":return c.jsx(Bo,{messageId:t,content:f.body,className:"text-sm"});case"kv":return c.jsx("dl",{className:"grid grid-cols-[minmax(6rem,auto)_1fr] gap-x-3 gap-y-1.5 text-sm",children:f.rows.map(h=>c.jsxs(H.Fragment,{children:[c.jsx("dt",{className:"truncate text-muted-foreground",children:h.label}),c.jsx("dd",{className:R("break-words",Cx[h.tone??"neutral"]?.split(" ")[1]),children:h.value})]},`${h.label}:${h.value}`))});case"list":return c.jsx("ul",{className:"flex flex-col gap-1.5 text-sm",children:f.items.map(h=>c.jsxs("li",{className:"flex items-baseline gap-2",children:[c.jsx("span",{className:"size-1.5 shrink-0 translate-y-[-1px] rounded-full bg-interactive-hover"}),c.jsx("span",{className:"font-medium",children:h.label}),h.value&&c.jsx("span",{className:"text-muted-foreground",children:h.value})]},`${h.label}:${h.value}`))});case"table":return c.jsx("div",{className:"overflow-x-auto",children:c.jsxs("table",{className:"w-full border-collapse text-sm",children:[c.jsx("thead",{children:c.jsx("tr",{children:f.columns.map(h=>c.jsx("th",{className:"border-b px-2 py-1.5 text-left font-medium text-muted-foreground",children:h},h))})}),c.jsx("tbody",{children:f.rows.map((h,m)=>c.jsx("tr",{children:h.map((g,x)=>c.jsx("td",{className:"border-b px-2 py-1.5 break-words",children:g},x))},m))})]})});case"progress":{const h=f.max??100;return c.jsx(CK,{label:f.label,value:f.value,max:h>0?h:100})}case"badges":return c.jsx("div",{className:"flex flex-wrap gap-1.5",children:f.items.map(h=>c.jsx("span",{className:R("rounded-full px-2 py-0.5 text-xs font-medium",Cx[h.tone??"neutral"]),children:h.label},h.label))});case"code":return c.jsx("pre",{className:"max-h-80 overflow-auto rounded-md border border-border/40 bg-muted/40 p-2 font-mono text-xs leading-relaxed",children:c.jsx("code",{children:f.code})});default:return null}};return c.jsxs("div",{className:R("my-1 flex flex-col gap-2 rounded-xl border border-border/60 bg-card p-3 text-card-foreground shadow-sm",i),"data-extension-ui":t,children:[(l!==void 0||d!==void 0)&&c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l!==void 0&&c.jsx("div",{className:"flex min-w-0 items-center gap-1.5",children:c.jsx("span",{className:"text-xs font-medium tracking-wide text-muted-foreground uppercase",children:l})}),d!==void 0&&c.jsx("div",{className:"flex shrink-0 flex-wrap gap-1.5",children:d.map(h=>c.jsx(SK,{action:h,variant:h.variant??"outline",sessionId:e},`${h.command}:${h.label}`))})]}),u()]})},IK=({messageId:e,customType:t,text:n,data:r,details:s,render:o,className:i})=>{const[a,l]=H.useState(!1),[d,f]=H.useState(!1),[u,h]=H.useState(!1),m=s!==void 0?s:r,g=m!=null,x=typeof n=="string"&&n.trim().length>0,b=t||"extension",S=Array.isArray(o?.message)&&o.message.length>0?o.message:void 0,y=Array.isArray(o?.messageExpanded)&&o.messageExpanded.length>0?o.messageExpanded:void 0,v=d&&y?y:S,C=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:{color:"var(--tools-icon)"},children:c.jsx($,{name:"plug-2",className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Kr,"shrink-0"),style:Ps,children:"Extension"}),c.jsx("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:b,children:b})]});return c.jsxs("div",{className:R("py-1",i),"data-extension-ui":e,children:[g&&!S?c.jsxs("button",{type:"button",onClick:()=>l(w=>!w),"aria-expanded":a,"aria-label":a?`Hide ${b} details`:`Show ${b} details`,className:"group/extension-note flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2 text-left",children:[C,c.jsx($,{name:"arrow-right-s","aria-hidden":"true",className:R("size-3.5 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] duration-150 group-hover/extension-note:opacity-100 group-focus-visible/extension-note:opacity-100",a&&"rotate-90 opacity-100")})]}):c.jsx("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:C}),g&&a&&!S&&c.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),c.jsx("div",{className:"max-h-80 overflow-auto",children:c.jsx(Td,{data:m})})]}),v&&c.jsx("div",{className:"my-1 max-h-80 overflow-x-auto overflow-y-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-micro","data-extension-message-render":"true",children:v.map((w,M)=>c.jsx("div",{className:"min-h-[1.25em] leading-relaxed",children:c.jsx(qt,{text:w})},M))}),S&&y&&c.jsxs(Se,{type:"button",variant:"ghost",size:"xs",onClick:()=>f(w=>!w),"aria-expanded":d,className:"h-5 gap-1 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:d?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:d?"Show less":"Show more"})]}),S&&(x||g)&&c.jsxs("div",{children:[c.jsxs(Se,{type:"button",variant:"ghost",size:"xs",onClick:()=>h(w=>!w),"aria-expanded":u,className:"h-5 gap-1 px-1.5 typography-micro font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:u?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:"Raw message"})]}),u&&c.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),x&&c.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:c.jsx(Bo,{messageId:e,content:n,variant:"assistant"})}),g&&c.jsx("div",{className:"max-h-80 overflow-auto",children:c.jsx(Td,{data:m})})]})]}),!S&&x&&c.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:c.jsx(Bo,{messageId:e,content:n,variant:"assistant"})})]})},kx=12,Mx={info:{label:"Notice",icon:"information"},warning:{label:"Warning",icon:"alert"},error:{label:"Error",icon:"error-warning"}},EK=({messageId:e,level:t,message:n,className:r})=>{const[s,o]=H.useState(!1),i=Mx[t]??Mx.info,a=typeof n=="string"&&n.trim().length>0?n:"Extension notification",l=a.split(`
214
+ `),d=H.useMemo(()=>GA(a),[a]),f=pe(S=>S.currentSessionDirectory),u=te(S=>S.isMobile),h=d.filter(S=>mp(S)==="external"||!u&&!!f),m=l.length>kx,g=!m||s?l:l.slice(0,kx),x=t==="error"?{color:"var(--status-error)"}:t==="warning"?{color:"var(--status-warning)"}:{color:"var(--tools-icon)"},b=t==="error"?{color:"var(--status-error)"}:t==="warning"?{color:"var(--status-warning)"}:Ps;return c.jsxs("div",{className:R("py-1",r),"data-extension-notice":e,children:[c.jsxs("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:x,children:c.jsx($,{name:i.icon,className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Kr,"shrink-0"),style:b,children:i.label}),c.jsx("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:"Extension notice",children:"Extension"})]}),c.jsx("div",{className:"my-1 max-h-80 overflow-x-auto overflow-y-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-micro","data-extension-notice-body":"true",children:g.map((S,y)=>c.jsx("div",{className:"min-h-[1.25em] leading-relaxed w-max min-w-full",children:c.jsx(qt,{text:S})},y))}),h.length>0&&c.jsx("div",{className:"flex min-w-0 flex-wrap gap-1",children:h.map(S=>c.jsx(Se,{type:"button",variant:"ghost",size:"xs",onClick:()=>YA(mp(S),S,f??""),title:S,className:"h-5 min-w-0 max-w-full px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:c.jsxs("span",{className:"truncate",children:["Open ",qA(S)]})},S))}),m&&c.jsxs(Se,{type:"button",variant:"ghost",size:"xs",onClick:()=>o(S=>!S),"aria-expanded":s,"aria-label":s?"Show less of the extension notice":"Show more of the extension notice",className:"h-5 gap-1 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[c.jsx($,{name:s?"arrow-down-s":"arrow-right-s",className:"size-3"}),c.jsx("span",{children:s?"Show less":"Show more"})]})]})},jK=e=>{if(e.kind==="recorded"){const{details:s}=e,o=typeof s.exitCode=="number"?s.exitCode:void 0;return{command:s.command,output:s.output,running:!1,status:s.cancelled?{text:"Cancelled",tone:"muted"}:o!==void 0&&o!==0?{text:`Exit code ${o}`,tone:"error"}:null,excludeFromContext:s.excludeFromContext===!0,truncated:s.truncated===!0,fullOutputPath:s.fullOutputPath}}const{execution:t}=e,n=typeof t.exitCode=="number"?t.exitCode:void 0,r=t.phase==="completed"||t.phase==="cancelled";return{command:t.command,output:t.output??"",running:t.phase==="running",status:t.phase==="running"?{text:"Running",tone:"muted"}:t.phase==="failed"?{text:"Failed",tone:"error"}:t.phase==="cancelled"?{text:"Cancelled",tone:"muted"}:n!==void 0&&n!==0?{text:`Exit code ${n}`,tone:"error"}:null,excludeFromContext:t.excludeFromContext===!0,truncated:t.truncated===!0,fullOutputPath:t.fullOutputPath,note:t.phase==="failed"?t.error:r?"Added to the conversation when the current response ends.":void 0}},_K=8,TK=({messageId:e,sessionId:t,state:n,className:r})=>{const s=jK(n),[o,i]=H.useState(!1),a=!!s.fullOutputPath&&wt()&&Ko(),l=H.useRef(null),d=H.useRef(!0),f=H.useCallback(()=>{const h=l.current;h&&(d.current=h.scrollHeight-h.scrollTop-h.clientHeight<=_K)},[]);H.useLayoutEffect(()=>{const h=l.current;!h||!d.current||(h.scrollTop=h.scrollHeight)},[s.output]);const u=H.useCallback(()=>{!t||o||(i(!0),dw(t).catch(h=>{Ce.error(h instanceof Error&&h.message?h.message:"Failed to stop the command")}).finally(()=>i(!1)))},[t,o]);return c.jsxs("div",{className:R("py-1",r),"data-bash-execution":e,children:[c.jsxs("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:[c.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:W4,children:c.jsx($,{name:"terminal-box",className:"size-3.5","aria-hidden":"true"})}),c.jsx("span",{className:R(Kr,"shrink-0"),style:Ps,children:"Shell"}),c.jsx("span",{className:R(Mt,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:s.command,children:s.command}),s.status?c.jsx("span",{className:"shrink-0 typography-micro",style:{color:s.status.tone==="error"?"var(--status-error)":"var(--tools-description)"},children:s.status.text}):null,s.excludeFromContext?c.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:"Not sent to the model"}):null,s.running&&t?c.jsx(Se,{type:"button",variant:"ghost",size:"xs",onClick:u,disabled:o,"aria-label":"Stop the shell command",className:"ml-auto h-5 px-1.5 typography-micro font-medium normal-case text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:"Stop"}):null]}),s.output.length>0?c.jsx("pre",{ref:l,onScroll:f,className:"my-1 max-h-80 overflow-auto whitespace-pre rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2 font-mono typography-micro leading-relaxed","data-no-drawer-swipe":"true",children:s.output}):null,s.truncated?c.jsxs("p",{className:"typography-micro text-muted-foreground text-pretty",children:["Showing the last 50 KB of output.",a?c.jsxs(c.Fragment,{children:[" ","Full output: ",c.jsx("span",{className:"font-mono break-all select-text",children:s.fullOutputPath})]}):null]}):null,s.note?c.jsx("p",{className:"typography-micro text-pretty",style:{color:n.kind==="live"&&n.execution.phase==="failed"?"var(--status-error)":"var(--tools-description)"},children:s.note}):null]})},G1="pichamber.notice",AK=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},Ix=new WeakMap,Ex=(e,t)=>{const n=Ix.get(e);if(n&&n.sessionId===t)return n.entry;const r=NK(e,t);return Ix.set(e,{sessionId:t,entry:r}),r},NK=(e,t)=>({info:{id:`notice:${e.id}`,sessionID:t,role:"extension",customType:G1,text:e.message,noticeLevel:e.level,time:{created:e.createdAt,completed:e.createdAt}},parts:[]}),LK=(e,t,n)=>{if(!n||t.length===0)return e;const r=[...t].sort((i,a)=>i.createdAt-a.createdAt),s=[];let o=0;for(const i of e){const a=AK(i);for(;o<r.length&&(a===void 0||r[o].createdAt<=a);)s.push(Ex(r[o],n)),o+=1;s.push(i)}for(;o<r.length;)s.push(Ex(r[o],n)),o+=1;return s},Z1=p.memo(({message:e,previousMessage:t,nextMessage:n,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:l,animationHandlers:d,scrollToBottom:f})=>{const u=e.info;if(u.role==="extension"&&u.customType===G1){const h=u.noticeLevel,m=h==="warning"||h==="error"?h:"info";return c.jsx("div",{className:"chat-message-column",children:c.jsx(EK,{messageId:e.info.id,level:m,message:typeof u.text=="string"?u.text:""})})}if(u.role==="extension"&&u.customType===Fl){const h=u.bashExecution,m=u.details;if(h||m&&typeof m.command=="string"&&typeof m.output=="string")return c.jsx("div",{className:"chat-message-column",children:c.jsx(TK,{messageId:e.info.id,sessionId:u.sessionID,state:h?{kind:"live",execution:h}:{kind:"recorded",details:m}})})}if(u.role==="extension"){const h=B5({customType:u.customType,data:u.data,details:u.details,text:typeof u.text=="string"?u.text:void 0});return c.jsx("div",{className:"chat-message-column",children:h.kind==="ui"?c.jsx(MK,{sessionId:u.sessionID,messageId:e.info.id,customType:u.customType,text:typeof u.text=="string"?u.text:void 0,data:u.data,details:u.details}):c.jsx(IK,{messageId:e.info.id,customType:u.customType,text:typeof u.text=="string"?u.text:void 0,data:u.data,details:u.details,render:u.render})})}return c.jsx(bK,{message:e,previousMessage:t,nextMessage:n,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:l,animationHandlers:d,scrollToBottom:f,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o})},(e,t)=>{const n=e.turnGroupingContext,r=t.turnGroupingContext;return J4(e.message,t.message)&&kd(e.previousMessage,t.previousMessage)&&kd(e.nextMessage,t.nextMessage)&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&e.onContentChange===t.onContentChange&&e.scrollToBottom===t.scrollToBottom&&Q4(n,r,e.message.info.id,Ns(e.message)==="user")&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.animationHandlers?.onChunk===t.animationHandlers?.onChunk&&e.animationHandlers?.onComplete===t.animationHandlers?.onComplete&&e.animationHandlers?.onStreamingCandidate===t.animationHandlers?.onStreamingCandidate&&e.animationHandlers?.onAnimationStart===t.animationHandlers?.onAnimationStart&&e.animationHandlers?.onReservationCancelled===t.animationHandlers?.onReservationCancelled&&e.animationHandlers?.onAnimatedHeightChange===t.animationHandlers?.onAnimatedHeightChange});Z1.displayName="MessageRow";const Z7=p.memo(({turn:e,isLastTurn:t,nextEntryFirstMessage:n,sessionIsWorking:r,sessionAwaitingRecovery:s=!1,awaitingPromptEcho:o=!1,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})=>{const m=p.useMemo(()=>{const E=[e.userMessage,...e.assistantMessages],I=new Map;return E.forEach((N,O)=>{I.set(N.info.id,O)}),{ordered:E,lookup:I}},[e.assistantMessages,e.userMessage]),g=p.useMemo(()=>rN({activeStreamingMessageId:u,assistantMessages:e.assistantMessages}),[u,e.assistantMessages]),x=e.assistantMessages,b=p.useMemo(()=>{const E=new Map;return x.forEach((I,N)=>{E.set(I.info.id,N)}),E},[x]),S=p.useMemo(()=>uh(e,g),[e,g]),y=uh(e,u),v=t&&s,C=p.useMemo(()=>S&&g?g:x[0]?.info.id,[g,S,x]),w=e.activityParts,M=e.activitySegments,j=p.useMemo(()=>{const E=new Map;for(const I of w){const N=E.get(I.messageId)??[];N.push(I),E.set(I.messageId,N)}return E},[w]),T=p.useMemo(()=>{const E=e.userMessage.info.time?.created,I=e.userMessage.info,N=I?.model?.variant??I?.variant,O=typeof N=="string"&&N.trim().length>0?N:void 0;return{turnId:e.turnId,summaryBody:e.summaryText,activityParts:w,activityGroupSegments:M,headerMessageId:e.headerMessageId,hasTools:e.hasTools,hasReasoning:e.hasReasoning,diffStats:e.diffStats,changedFiles:e.changedFiles,userMessageCreatedAt:typeof E=="number"?E:void 0,userMessageVariant:O}},[e.changedFiles,e.diffStats,e.hasReasoning,e.hasTools,e.headerMessageId,e.summaryText,e.turnId,e.userMessage.info,w,M]),A=p.useCallback(E=>{const N=Ns(E)==="user",O=m.lookup.get(E.info.id),L=b.get(E.info.id)??-1,D=L>=0,W=L===0,z=L===x.length-1,B=!!C&&E.info.id===C||W||z,U=j.get(E.info.id)??[],P=N?void 0:D?W?e.userMessage:void 0:typeof O=="number"&&O>0?m.ordered[O-1]:void 0,q=D&&z?n:void 0,F=D?{turnId:e.turnId,activityOwnerMessageId:C,isFirstAssistantInTurn:W,isLastAssistantInTurn:z,isLatestTurn:t,isWorking:aN({messageId:E.info.id,activeStreamingMessageId:u,isRetrying:V$(E),isAwaitingRecovery:v&&z}),hasTools:e.hasTools,hasReasoning:e.hasReasoning,...B?{summaryBody:T.summaryBody,activityParts:T.activityParts,activityGroupSegments:T.activityGroupSegments,headerMessageId:T.headerMessageId,diffStats:T.diffStats,changedFiles:T.changedFiles,userMessageCreatedAt:T.userMessageCreatedAt,userMessageVariant:T.userMessageVariant}:{activityParts:U}}:void 0;return c.jsx(Z1,{message:E,previousMessage:P,nextMessage:q,turnGroupingContext:F,isInActiveTurn:!!g&&E.info.id===g,activeStreamingPhase:E.info.id===g?h:null,animateUserOnMount:d(E),onUserAnimationConsumed:f,onContentChange:i,animationHandlers:a(E.info.id),scrollToBottom:l},E.info.id)},[a,t,n,m.lookup,m.ordered,i,l,e.hasReasoning,e.hasTools,e.turnId,e.userMessage,T,g,u,h,x,b,C,j,v,d,f]),_=!uh(e,u),k=iN({isLastTurn:t,sessionIsWorking:r,turnIsInActiveStream:e.stream.isStreaming&&y,activeStreamingMessageId:u,isSteering:e.isSteering,awaitingPromptEcho:o});return c.jsx(RW,{turn:e,renderMessage:A,deferEarlierAssistantMessages:_,showWorkingStatus:k,isAwaitingRecovery:v&&!k,activeStreamingMessageId:u,activeStreamingPhase:h,onActivityContentChange:i})});Z7.displayName="TurnBlock";const Y7=p.memo(({message:e,previousMessage:t,nextMessage:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,shouldAnimateUserMessage:i,onUserAnimationConsumed:a,activeStreamingMessageId:l,activeStreamingPhase:d})=>c.jsx(Z1,{message:e,previousMessage:t,nextMessage:n,isInActiveTurn:!!l&&e.info.id===l,activeStreamingPhase:e.info.id===l?d:null,animateUserOnMount:i(e),onUserAnimationConsumed:a,onContentChange:r,animationHandlers:s(e.info.id),scrollToBottom:o}));Y7.displayName="UngroupedMessageRow";const RK=new Set(["task"]),PK=e=>typeof e=="string"&&RK.has(e.toLowerCase()),DK=e=>{const t=e.state?.time?.end;if(typeof t=="number")return t;const n=e.time?.end;return typeof n=="number"?n:void 0},jx=e=>{const t=e.text;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.content;if(typeof n=="string"&&n.trim().length>0)return n},OK=e=>{const t=e.info.finish;return typeof t=="string"?t:void 0},HK=e=>e.info.summary===!0,FK=(e,t,n,r)=>({id:n.id??`${t}-part-${r}-${n.type}`,turnId:e,messageId:t,part:n,partIndex:r,endedAt:DK(n)}),BK=e=>{const t=[];let n=!1,r=!1;e.assistantMessages.forEach(g=>{g.parts.forEach(x=>{if(x.type==="tool"){n=!0;return}x.type==="reasoning"&&jx(x)&&(r=!0)})});const s=new Map,o=[],i=e.summarySourceMessageId?e.assistantMessages.findIndex(g=>g.info.id===e.summarySourceMessageId):-1,a=i>=0&&e.summarySourcePartId?e.assistantMessages[i]?.parts.findIndex((g,x)=>(g.id??`${e.assistantMessages[i]?.info.id}-part-${x}-${g.type}`)===e.summarySourcePartId)??-1:-1,l=e.assistantMessages.some(g=>g.parts.some(x=>x.type==="tool"||x.type==="reasoning")),d=new Map;let f=null;e.assistantMessages.forEach((g,x)=>{const b=OK(g),S=g.parts.some(v=>v.type==="tool"),y=HK(g);g.parts.forEach((v,C)=>{const w=v.type==="tool",M=v.type==="reasoning"||v.type==="text"?jx(v):void 0,j=v.id??`${g.info.id}-part-${C}-${v.type}`,T=w?v.tool:void 0,A=w&&PK(T);if(A){const O=j;s.has(O)||(s.set(O,g.info.id),o.push(O)),f=O}const _=v.type==="text"&&typeof M=="string"&&(b==="stop"||typeof b!="string")&&e.summarySourceMessageId===g.info.id&&e.summarySourcePartId===j,k=i>=0&&(x<i||x===i&&a>=0&&C<a);let E=null;if(w?E="tool":v.type==="reasoning"?M&&(E="reasoning"):e.showTextJustificationActivity&&v.type==="text"&&M&&(y||!_&&(S||typeof b=="string"&&b!=="stop"||l||k))&&(E="justification"),!E)return;const I={...FK(e.turnId,g.info.id,v,C),kind:E};if(t.push(I),E==="tool"&&A)return;const N=d.get(f)??[];N.push(I),d.set(f,N)})});const u=[],h=g=>{if(g.length===0)return;const x=new Map;g.forEach(S=>{x.set(S.messageId,(x.get(S.messageId)??0)+1)});let b;for(const S of e.assistantMessages)(x.get(S.info.id)??0)>0&&!b&&(b=S.info.id);return b};return[null,...o].forEach(g=>{const x=d.get(g)??[];if(x.length===0)return;const b=g===null?h(x):s.get(g);b&&u.push({id:`${e.turnId}:${b}:${g??"start"}`,anchorMessageId:b,afterToolPartId:g,parts:x})}),{activityParts:t,activitySegments:u,hasTools:n,hasReasoning:r}},VK=e=>{const t=new Map,n=new Map,r=new Map,s=new Set;e.forEach(a=>{t.set(a.turnId,a);const l=a.assistantMessages[0]?.info.id,d=a.assistantMessages[a.assistantMessages.length-1]?.info.id;n.set(a.userMessageId,a.turnId),s.add(a.userMessageId),r.set(a.userMessageId,{turnId:a.turnId,messageId:a.userMessageId,userMessageId:a.userMessageId,isUserMessage:!0,isAssistantMessage:!1,isFirstAssistantInTurn:!1,isLastAssistantInTurn:!1,headerMessageId:a.headerMessageId}),a.assistantMessageIds.forEach(f=>{n.set(f,a.turnId),s.add(f),r.set(f,{turnId:a.turnId,messageId:f,userMessageId:a.userMessageId,isUserMessage:!1,isAssistantMessage:!0,isFirstAssistantInTurn:f===l,isLastAssistantInTurn:f===d,headerMessageId:a.headerMessageId})}),(a.notices??[]).forEach(f=>{n.set(f.info.id,a.turnId),s.add(f.info.id),r.set(f.info.id,{turnId:a.turnId,messageId:f.info.id,userMessageId:a.userMessageId,isUserMessage:!1,isAssistantMessage:!1,isFirstAssistantInTurn:!1,isLastAssistantInTurn:!1,headerMessageId:a.headerMessageId})})});const o=e.length>0?e[e.length-1]:null,i=new Set;return o&&(i.add(o.userMessageId),o.assistantMessageIds.forEach(a=>{i.add(a)}),(o.notices??[]).forEach(a=>{i.add(a.info.id)})),{turns:e,indexes:{turnById:t,messageToTurnId:n,messageMetaById:r},lastTurnId:o?.turnId??null,lastTurnMessageIds:i,ungroupedMessageIds:new Set}},$K=e=>{const t=e.text;if(typeof t=="string"&&t.trim().length>0)return t;const n=e.content;if(typeof n=="string"&&n.trim().length>0)return n},zK=e=>e.info.summary===!0,_x=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!zK(r)&&!(t&&r.info.finish!=="stop"))for(let s=r.parts.length-1;s>=0;s-=1){const o=r.parts[s];if(!o||o.type!=="text")continue;const i=$K(o);if(i)return{text:i,sourceMessageId:r.info.id,sourcePartId:o.id??`${r.info.id}-part-${s}-text`}}}},UK=e=>_x(e,!0)??_x(e,!1)??{},qK=e=>{const n=e.info.summary?.diffs;if(!Array.isArray(n)||n.length===0)return;let r=0,s=0,o=0;if(n.forEach(i=>{if(!i)return;const a=typeof i.additions=="number"?i.additions:0,l=typeof i.deletions=="number"?i.deletions:0;(a!==0||l!==0)&&(o+=1),r+=a,s+=l}),o!==0)return{additions:r,deletions:s,files:o}},Yp=[],Ui=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},X7=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},J7=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},WK=e=>{const t=e.info.time?.completed;return typeof t=="number"?t:void 0},KK=e=>{const t=e.info?.summary?.body;return typeof t!="string"?void 0:t.trim().length>0?t:void 0},Q7=e=>{const t=e.info;return t.role==="extension"&&t.customType===G1},GK=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},xh=(e,t)=>{const n=Ui(e);return{messageId:e.info.id,role:n,parentMessageId:X7(e),message:e,order:t}},ZK=(e,t)=>{const n=J7(e);let r,s=!1;t.forEach(i=>{const a=WK(i);typeof a=="number"?r=Math.max(r??0,a):s=!0});const o=typeof n=="number"&&typeof r=="number"&&r>=n?r-n:void 0;return{isStreaming:s,isRetrying:t.length>1,startedAt:n,completedAt:r,durationMs:o}},YK={previousProjection:null,showTextJustificationActivity:!1,mergeHiddenUserTurns:void 0},XK=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},JK=(e,t)=>e.userMessage===t.userMessage&&e.headerMessageId===t.headerMessageId&&XK(e.assistantMessages,t.assistantMessages),Tx=(e,t)=>{e.summary=UK(e.assistantMessages),e.summaryText=e.summary.text??KK(e.userMessage),e.diffStats=qK(e.userMessage),e.changedFiles=void 0;const n=BK({turnId:e.turnId,assistantMessages:e.assistantMessages,summarySourceMessageId:e.summary.sourceMessageId,summarySourcePartId:e.summary.sourcePartId,showTextJustificationActivity:t.showTextJustificationActivity});return e.activityParts=n.activityParts,e.activitySegments=n.activitySegments,e.hasTools=n.hasTools,e.hasReasoning=n.hasReasoning,e.stream=ZK(e.userMessage,e.assistantMessages),e.startedAt=e.stream.startedAt,e.completedAt=e.stream.completedAt,e.durationMs=e.stream.durationMs,e},QK=e=>{let t=!1;const n=[...e];for(let r=1;r<e.length;r+=1){const s=n[r-1],o=n[r],i=o.startedAt;if(!s.stream.isStreaming||typeof i!="number")continue;const a=s.startedAt,l=typeof a=="number"&&i>=a?i-a:void 0;n[r-1]={...s,stream:{...s.stream,isStreaming:!1,completedAt:i,durationMs:l,settledReason:"steered"},completedAt:i,durationMs:l},n[r]=o.isSteering?o:{...o,isSteering:!0},t=!0}return t?n:e},eG=(e,t)=>{const n=t.previousProjection;if(!n||n.turns.length===0||e.length===0)return e.map(i=>Tx(i,t));let r=n.turns.length===e.length,s=!1;const o=e.map((i,a)=>{const l=n.indexes.turnById.get(i.turnId);return l&&JK(l,i)?(s=!0,n.turns[a]!==l&&(r=!1),l):(r=!1,Tx(i,t))});return r&&s?n.turns:o},tG=(e,t,n)=>{if(n.size===0&&e.every(a=>a.notices.length===0))return e;const r=new Map;e.forEach(a=>r.set(a.turnId,a));const s=new Map;t.forEach(a=>{if(!Q7(a))return;const l=n.get(a.info.id);if(!l)return;const d=r.get(l);if(!d)return;if(d.completedAt!==void 0){const u=J7(a);if(u===void 0||u>d.completedAt)return}const f=s.get(l);f?f.push(a):s.set(l,[a])});let o=!1;const i=e.map(a=>{const l=s.get(a.turnId),d=a.notices??Yp;return l?GK(d,l)?a:(o=!0,{...a,notices:l}):d.length===0?a:(o=!0,{...a,notices:Yp})});return o?i:e},e9=(e,t)=>{const n={...YK,...t},r=[],s=new Map,o=new Set,i=n.mergeHiddenUserTurns;e.forEach((h,m)=>{if(Ui(h)!=="user")return;const x=r[r.length-1];if(i&&x&&G7(h)){s.set(h.info.id,x),x.messages.push(xh(h,m)),o.add(h.info.id);return}const S={turnId:h.info.id,isSteering:!1,userMessageId:h.info.id,userMessage:h,notices:Yp,headerMessageId:void 0,messages:[xh(h,m)],assistantMessageIds:[],assistantMessages:[],activityParts:[],activitySegments:[],summary:{},summaryText:void 0,hasTools:!1,hasReasoning:!1,diffStats:void 0,changedFiles:void 0,stream:{isStreaming:!1,isRetrying:!1}};r.push(S),s.set(S.userMessageId,S),o.add(h.info.id)}),e.forEach((h,m)=>{if(Ui(h)!=="assistant")return;const x=X7(h),b=x?s.get(x):void 0;b&&(b.assistantMessages.push(h),b.assistantMessageIds.push(h.info.id),b.messages.push(xh(h,m)),b.headerMessageId||(b.headerMessageId=h.info.id),o.add(h.info.id))});const a=new Map;{let h=null;e.forEach(m=>{if(Ui(m)==="user"){h=s.get(m.info.id)??null;return}Q7(m)&&h&&a.set(m.info.id,h.turnId)})}const l=QK(eG(r,n)),d=tG(l,e,a);d.forEach(h=>{h.notices.length!==0&&h.notices.forEach(m=>o.add(m.info.id))});const f=VK(d),u=new Set;return e.forEach(h=>{Ui(h)!=="assistant"&&(o.has(h.info.id)||u.add(h.info.id))}),{...f,ungroupedMessageIds:u}},nG=30,rG=4,Ar=new Map,Ax=new WeakMap;let Nx=1;const sG=()=>un()?rG:nG,bh=e=>{const t=Ax.get(e);if(t!==void 0)return t;const n=Nx;return Nx+=1,Ax.set(e,n),n},oG=e=>e.map(t=>{const n=bh(t.info),r=bh(t.parts),s=t.parts.map(o=>bh(o)).join(",");return`${n}:${r}:${s}`}).join(";"),iG=(e,t,n,r)=>{const s=t.length>0?t[t.length-1]:void 0,o=s?.info?.id??"",i=s?.parts?.length??0;return[e,t.length,o,i,oG(t),n?"1":"0",r].join("|")},aG=e=>{const t=Ar.get(e);return t&&(Ar.delete(e),Ar.set(e,t)),t},cG=(e,t)=>{Ar.delete(e);const n=sG();for(;Ar.size>=n;){const r=Ar.keys().next().value;if(typeof r!="string")break;Ar.delete(r)}Ar.set(e,t)},lG=(e,t)=>{const n=p.useRef(null),r=p.useRef([]),s=p.useRef(void 0),o=p.useRef(t.sessionKey),i=p.useRef(t.showTextJustificationActivity);(o.current!==t.sessionKey||i.current!==t.showTextJustificationActivity)&&(o.current=t.sessionKey,i.current=t.showTextJustificationActivity,n.current=null,r.current=[],s.current=void 0),p.useEffect(()=>{n.current=null,r.current=[],s.current=void 0},[t.sessionKey,t.showTextJustificationActivity]);const a=p.useMemo(()=>{const f=t.sessionKey??"",u=iG(f,e,t.showTextJustificationActivity,"merge"),h=aG(u);return h?(n.current=h,h):ll("ui.turns.projection_ms",()=>{const m=e9(e,{previousProjection:n.current,showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:!0});return n.current=m,cG(u,m),m})},[e,t.showTextJustificationActivity,t.sessionKey]),l=p.useMemo(()=>{const f=a.turns.length<=1?[]:a.turns.slice(0,-1),u=r.current;if(u.length===f.length){let h=!0;for(let m=0;m<f.length;m+=1)if(u[m]!==f[m]){h=!1;break}if(h)return u}return r.current=f,f},[a.turns]),d=p.useMemo(()=>{const f=a.turns.length===0?void 0:a.turns[a.turns.length-1];return s.current===f?s.current:(s.current=f,f)},[a.turns]);return{projection:a,staticTurns:l,streamingTurn:d}},dG=1.5,uG=({hasMoreBefore:e,beforeCursor:t,resolveScrollContainer:n,loadOlder:r,onBeforeLoad:s,onLoadError:o})=>{p.useEffect(()=>{if(!e||!t)return;const i=n();if(!i)return;let a=!1,l,d=!0;const f=()=>{if(a||!e)return;const u=i.scrollTop<i.clientHeight*dG,h=i.scrollHeight<=i.clientHeight+1;!u&&!h||(a=!0,s(),r().then(m=>{d&&(a=!1,m&&(l=window.setTimeout(f,0)))}).catch(()=>{d&&(a=!1,o())}))};return i.addEventListener("scroll",f,{passive:!0}),f(),()=>{d=!1,l!==void 0&&window.clearTimeout(l),i.removeEventListener("scroll",f)}},[t,e,r,s,o,n])},Lx=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},Rx=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},fG=(e,t,n)=>{if(!t||!n)return e;const r={name:"SessionCompaction",message:n.message,data:{...n}},s=n.completedAt??n.startedAt;let o=-1;for(let f=e.length-1;f>=0;f-=1){const u=Rx(e[f]);if(!(s!==void 0&&u!==void 0&&u>s)&&Lx(e[f])==="user"){o=f;break}}if(o<0)return e;let i=-1;for(let f=o+1;f<e.length;f+=1){const u=Rx(e[f]);if(s!==void 0&&u!==void 0&&u>s)break;Lx(e[f])==="assistant"&&(i=f)}if(i>=0)return e.map((f,u)=>u===i?{...f,info:{...f.info,error:r}}:f);const a=s??0,l={info:{id:`synthetic_compaction_notice_${t}`,sessionID:t,role:"assistant",parentID:e[o].info.id,time:{created:a,completed:a},finish:"stop",error:r},parts:[]},d=e.slice();return d.splice(o+1,0,l),d},Px=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},hG=(e,t)=>{if(!t.sessionId)return e;const n={name:"SessionRetry",message:t.message,data:{message:t.message}};let r=-1;for(let d=e.length-1;d>=0;d-=1)if(Px(e[d])==="user"){r=d;break}if(r<0)return e;let s=-1;for(let d=e.length-1;d>r;d-=1)if(Px(e[d])==="assistant"){s=d;break}if(s>=0)return e.map((d,f)=>f!==s?d:{...d,info:{...d.info,error:n}});const o=typeof t.confirmedAt=="number"?t.confirmedAt:t.fallbackTimestamp,a={info:{id:`synthetic_retry_notice_${t.sessionId}`,sessionID:t.sessionId,role:"assistant",parentID:e[r].info.id,time:{created:o,completed:o},finish:"stop",error:n},parts:[]},l=e.slice();return l.splice(r+1,0,a),l},Dx=new WeakMap,pG=(e,t)=>{const n=Dx.get(e);if(n&&n.sessionId===t)return n.entry;const r={info:{id:`bash:${e.id}`,sessionID:t,role:"extension",customType:Fl,bashExecution:e,time:{created:e.startedAt,...e.completedAt?{completed:e.completedAt}:{}}},parts:[]};return Dx.set(e,{sessionId:t,entry:r}),r},mG=(e,t,n)=>!n||t.length===0?e:[...e,...t.map(r=>pG(r,n))],Ox=[],gG=({staticTurns:e,messages:t,ungroupedMessageIds:n,lastTurnId:r,tailUserMessageId:s})=>{const o=e.map(h=>({kind:"turn",key:`turn:${h.turnId}`,turn:h,isLastTurn:h.turnId===r}));if(n.size===0)return{entries:o,trailing:Ox};const i=new Map;o.forEach(h=>{i.set(h.turn.userMessage.info.id,h)});const a=t[t.length-1],l=!s&&a&&n.has(a.info.id)?a.info.id:void 0,d=[],f=[];let u=!1;return t.forEach((h,m)=>{if(s&&h.info.id===s){u=!0;return}const g=i.get(h.info.id);if(g){d.push(g);return}!n.has(h.info.id)||h.info.id===l||(u?f:d).push({kind:"ungrouped",key:`msg:${h.info.id}`,message:h,previousMessage:m>0?t[m-1]:void 0,nextMessage:m<t.length-1?t[m+1]:void 0})}),{entries:d,trailing:f.length>0?f:Ox}},t9=e=>e.parts.some(t=>t?.type==="compaction"),yG=e=>{if(!t9(e))return e;let t=!1;const n=e.parts.map(o=>o?.type!=="compaction"?o:(t=!0,{type:"text",text:"/compact"})),s=e.info.clientRole!=="user";return!t&&!s?e:{...e,info:s?{...e.info,clientRole:"user"}:e.info,parts:t?n:e.parts}},vG=e=>{const t=wu(e.parts);return t.length===e.parts.length?e:{...e,parts:t}},Hx=new WeakMap,n9=e=>{const t=Hx.get(e);if(t)return t;const n=vG(e),r=yG(n),s=gW(r.parts),o=s===r.parts?r:{...r,parts:s};return Hx.set(e,o),o},Fx=(e,t,n)=>e.info.id!==t||e.parts===n?e:n9({...e,parts:n}),xG=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const r=e[n],s=t[n];if(!r||!s||r.id!==s.id||r.type!==s.type||r.type!=="text"&&r!==s)return!1}return!0},Bx=(e,t)=>{if(e.messages.length===0)return e.messages;const n=new Map(t.map(o=>[o.info.id,o]));let r=!1;const s=e.messages.map(o=>{const i=n.get(o.messageId);return!i||i===o.message?o:(r=!0,{...o,message:i})});return r?s:e.messages},bG=(e,t)=>{const n=t.activeStreamingMessageId;if(!n)return e;if(e.kind==="ungrouped"){const g=Fx(e.message,n,t.liveParts);return g===e.message?e:{...e,message:g}}let r=!1;const s=e.turn.assistantMessages.map(g=>{const x=Fx(g,n,t.liveParts);return x!==g&&(r=!0),x});if(!r)return e;const o=e.turn.assistantMessages.find(g=>g.info.id===n),i=s.find(g=>g.info.id===n);if(!!(o&&i&&xG(o.parts,i.parts)))return{...e,turn:{...e.turn,assistantMessages:s,messages:Bx(e.turn,s)}};const l=new Map(s.map(g=>[g.info.id,g])),f=[...e.turn.messages.length>0?e.turn.messages.slice().sort((g,x)=>g.order-x.order).map(g=>l.get(g.messageId)??g.message):[e.turn.userMessage,...s],...e.turn.notices],h=e9(f,{showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:t.mergeHiddenUserTurns}).turns[0],m=h?h.notices.length>0||e.turn.notices.length>0?{...h,notices:e.turn.notices}:h:{...e.turn,assistantMessages:s,assistantMessageIds:s.map(g=>g.info.id),messages:Bx(e.turn,s)};return{...e,turn:m}},Vx=e=>!!(e&&e.clientHeight>0),wG=5,SG=[],CG=new Set,kG=16,MG=(e,t)=>e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r]),IG=320,EG=8,jG=16,_G=()=>un()?jG:EG,TG=30,AG=180,NG=5,LG=120,RG=1200,PG=80,DG=160,$x=1500,OG=1.5,HG=90,FG=(e,t)=>{if(e.length===0||t.length<=e.length||e[e.length-1]?.key!==t[t.length-1]?.key)return!1;const n=e[0]?.key;return t.findIndex(s=>s.key===n)>0},hs=new Map,BG=32,lo=new Map,zx=e=>lo.get(e)??0,VG=(e,t)=>{if(lo.size>=BG&&!lo.has(e)){const n=lo.keys().next().value;typeof n=="string"&&lo.delete(n)}lo.set(e,t)},$G=(e,t)=>{const n=hs.get(e);if(n){if(MG(n.keys,t))return n.items;hs.delete(e)}},zG=(e,t,n)=>{if(!(!n||t.length===0))for(hs.delete(e),hs.set(e,{keys:t.slice(),items:n.takeSnapshot()});hs.size>kG;){const r=hs.keys().next().value;if(typeof r!="string")break;hs.delete(r)}},sl=e=>{const t=p.useRef(e);return p.useEffect(()=>{t.current=e},[e]),p.useCallback((...n)=>t.current(...n),[])},Su=p.memo(({entry:e,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,sessionIsWorking:s,sessionAwaitingRecovery:o=!1,awaitingPromptEcho:i=!1,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f,onLoadOlderHistory:u,onLoadAllHistory:h})=>(Is("ui.message_list_entry.render"),e.kind==="ungrouped"?c.jsx(Y7,{message:e.message,previousMessage:e.previousMessage,nextMessage:e.nextMessage,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f}):e.kind==="history-gate"?c.jsx(H$,{foldedCount:e.turns.length,onLoadOlder:()=>u?.(e.turns.length),onLoadAll:()=>h?.(e.turns.length)}):c.jsx(Z7,{turn:e.turn,isLastTurn:e.isLastTurn,nextEntryFirstMessage:e.nextEntryFirstMessage,sessionIsWorking:s,sessionAwaitingRecovery:o,awaitingPromptEcho:i,shouldAnimateUserMessage:a,onUserAnimationConsumed:l,activeStreamingMessageId:d,activeStreamingPhase:f,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r})));Su.displayName="MessageListEntry";const r9=p.memo(({entries:e,engine:t,contentRef:n,scrollRef:r,registerTanstackVirtualizer:s,virtualizerKey:o,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,onLoadOlderHistory:u,onLoadAllHistory:h})=>{const m=t==="tanstack",g=p.useRef(!1),x=p.useRef(0),b=p.useRef(null),S=m&&un();p.useEffect(()=>{if(!S)return;const D=r?.current;if(!D)return;const W=()=>{g.current=!0},z=()=>{g.current=!1},J=()=>{x.current=performance.now()};return D.addEventListener("touchstart",W,{passive:!0}),D.addEventListener("touchend",z,{passive:!0}),D.addEventListener("touchcancel",z,{passive:!0}),D.addEventListener("scroll",J,{passive:!0}),()=>{D.removeEventListener("touchstart",W),D.removeEventListener("touchend",z),D.removeEventListener("touchcancel",z),D.removeEventListener("scroll",J)}},[S,r]);const y=p.useCallback(()=>g.current||performance.now()-x.current<DG,[]),v=p.useCallback(()=>{const D=r?.current;return D?D.scrollTop<D.clientHeight*OG:!0},[r]),[C,w]=p.useState(e);let M=C;e!==C?S&&FG(C,e)&&y()&&!v()&&(b.current===null||performance.now()-b.current<$x)?b.current===null&&(b.current=performance.now()):(b.current=null,w(e),M=e):b.current!==null&&(b.current=null);const[,j]=p.useReducer(D=>D+1,0);p.useEffect(()=>{if(!S)return;const D=window.setInterval(()=>{if(b.current===null)return;const W=performance.now()-b.current>=$x;(!y()||v()||W)&&j()},HG);return()=>window.clearInterval(D)},[S,y,v]);const T=p.useRef(M);T.current=M;const[A]=p.useState(()=>m?$G(o,e.map(D=>D.key)):void 0),_=p.useRef(null),k=p.useRef(IG),[E,I]=p.useState(null);p.useLayoutEffect(()=>{if(!m){I(B=>B===null?B:null);return}let D,W=0;const z=()=>{const B=r?.current??null;return Vx(B)?(I(U=>U===B?U:B),!0):!1};if(z())return;const J=r?.current;return J?(D=new ResizeObserver(()=>{z()&&D?.disconnect()}),D.observe(J)):typeof window<"u"&&(W=window.requestAnimationFrame(()=>{if(z())return;const B=r?.current;B&&(D=new ResizeObserver(()=>{z()&&D?.disconnect()}),D.observe(B))})),()=>{W&&window.cancelAnimationFrame(W),D?.disconnect()}},[m,r,o]);const N=m&&Vx(E),O=T5({count:M.length,enabled:N,getScrollElement:()=>E,estimateSize:D=>T.current[D]?.kind==="history-gate"?N$:k.current,overscan:_G(),scrollToFn:(D,W,z)=>{const J=_.current;J&&(J.style.height=`${z.getTotalSize()}px`),u8(D,W,z)},getItemKey:D=>T.current[D]?.key??`index:${D}`,anchorTo:"end",initialOffset:()=>Number.MAX_SAFE_INTEGER,initialMeasurementsCache:A});O.shouldAdjustScrollPositionOnItemSizeChange=(D,W,z)=>{if(z.isAtEnd(PG))return!1;const J=z.range?.startIndex;return J!==void 0&&D.index<J},p.useEffect(()=>{if(!m)return;const D=O.itemSizeCache;if(D.size>=NG){let W=0;for(const z of D.values())W+=z;k.current=Math.min(RG,Math.max(LG,Math.round(W/D.size)))}}),p.useEffect(()=>{if(N)return s?.(O),()=>{zG(o,T.current.map(D=>D.key),O),s?.(null)}},[N,s,O,o]);const L=p.useCallback(D=>c.jsx(Su,{entry:D,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:l,sessionIsWorking:!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:null,activeStreamingPhase:null,onLoadOlderHistory:u,onLoadAllHistory:h},D.key),[a,h,u,i,f,l,d]);if(t==="none"||t==="tanstack"&&!N)return c.jsx("div",{ref:n,className:"relative w-full",children:M.map(D=>c.jsx("div",{"data-turn-entry":D.key,children:L(D)},D.key))});if(t==="tanstack"){const D=O.getVirtualItems(),W=D[0]?.start??0;return c.jsx("div",{ref:_,className:"relative w-full",style:{height:O.getTotalSize()},children:c.jsx("div",{style:{paddingTop:`${W}px`},children:D.map(z=>{const J=M[z.index];return J?c.jsx("div",{"data-index":z.index,ref:O.measureElement,"data-turn-entry":J.key,children:L(J)},J.key):null})})})}return null});r9.displayName="StaticHistoryList";const s9=({entry:e,sessionId:t,directory:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a=!1,awaitingPromptEcho:l=!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})=>{const m=jE(t,u??"",n),g=p.useMemo(()=>bG(e,{activeStreamingMessageId:u,liveParts:m,showTextJustificationActivity:!0,mergeHiddenUserTurns:!0}),[u,e,m]);return c.jsx(Su,{entry:g,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a,awaitingPromptEcho:l,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:h})};s9.displayName="StreamingTailContent";const o9=p.forwardRef(({sessionKey:e,messages:t,sessionIsWorking:n=!1,sessionAwaitingRecovery:r=!1,awaitingPromptEcho:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,retryOverlay:a=null,compactionOverlay:l=null,onMessageContentChange:d,getAnimationHandlers:f,scrollToBottom:u,scrollRef:h,directory:m},g)=>{QS("react.message_list_render"),Is("ui.message_list.render");const{hasMoreBefore:x,beforeCursor:b,loadOlder:S}=BE(e),y=aw(e),v=TE(e),[C,w]=p.useState(()=>zx(e)),M=p.useRef(null),j=p.useRef(null),T=p.useCallback(()=>{const ie=h?.current;if(!ie)return null;const ke=ie.getBoundingClientRect(),ve=Array.from(ie.querySelectorAll("[data-message-id]")).find(xe=>xe.getBoundingClientRect().bottom>ke.top+1);return{top:ie.scrollTop,height:ie.scrollHeight,anchor:ve?.dataset.messageId?{messageId:ve.dataset.messageId,offsetTop:ve.getBoundingClientRect().top-ke.top}:null}},[h]),A=p.useCallback(ie=>{w(ke=>{const ve=typeof ie=="function"?ie(ke):ie;return VG(e,ve),ve})},[e]),_=p.useCallback(ie=>{M.current=T(),A(ke=>D$(ke,ie))},[T,A]),k=p.useCallback(ie=>{M.current=T(),A(ke=>ke+ie)},[T,A]),E=p.useCallback((ie,ke,ve)=>{const xe=ke.findIndex(_e=>_e.turnId===ie);xe<0||(j.current=ie,A(_e=>Math.max(_e,P$(xe,ve))))},[A]);p.useLayoutEffect(()=>{w(zx(e)),j.current=null},[e]);const I=p.useRef({sessionKey:void 0,previousOrder:[],animatedIds:new Set}),N=sl(f),O=sl(()=>{u?.()}),L=p.useMemo(()=>ll("ui.message_list.base_display_ms",()=>{const ie=new Set,ke=new Map,ve=[];for(const le of t){const X=le.info?.id;typeof X=="string"&&ke.set(X,le)}for(let le=0;le<t.length;le+=1){const X=t[le],ne=X.info?.id;if(typeof ne=="string"){if(ie.has(ne))continue;ie.add(ne)}ve.push(n9(typeof ne=="string"?ke.get(ne)??X:X))}const xe=[],_e=new Set;for(let le=0;le<ve.length;le+=1){const X=ve[le],ne=q$(X,_e);(t9(X)||X.parts.some(De=>De.type==="text"&&$$(De).trim()==="/compact"))&&_e.add(X.info.id);const he=xe.length>0?xe[xe.length-1]:void 0;if(W$(he)){const De=G$(ne);if(De.hide){xe[xe.length-1]=Z$(he,De.taskSessionId);continue}}if($4(he)){const De=z4(ne,z$(he));if(De.hide){xe[xe.length-1]=Y$(he,De.details);continue}}xe.push(ne)}return xe}),[t]),D=p.useRef(null),W=p.useCallback(()=>h?.current?h.current:typeof document>"u"?null:document.querySelector('[data-scrollbar="chat"]'),[h]),z=p.useCallback(()=>{M.current=T()},[T]),J=p.useCallback(()=>{M.current=null},[]);uG({hasMoreBefore:x,beforeCursor:b,resolveScrollContainer:W,loadOlder:S,onBeforeLoad:z,onLoadError:J});const B=p.useMemo(()=>ll("ui.message_list.retry_overlay_ms",()=>{const ie=hG(L,{sessionId:a?.sessionId??null,message:a?.message??"Quota limit reached. Retrying automatically.",confirmedAt:a?.confirmedAt,fallbackTimestamp:a?.fallbackTimestamp??0}),ke=fG(ie,l?.sessionId??null,l?.compaction??null),ve=LK(ke,y,e);return mG(ve,v,e)}),[L,l,a,v,y,e]),{projection:U,staticTurns:P,streamingTurn:q}=lG(B,{sessionKey:e,showTextJustificationActivity:!0}),F=U.ungroupedMessageIds.size>0,ee=F?B:SG,G=F?U.ungroupedMessageIds:CG,K=q?.userMessage.info.id,{entries:se,trailing:ce}=p.useMemo(()=>ll("ui.message_list.render_entries_ms",()=>gG({staticTurns:P,messages:ee,ungroupedMessageIds:G,lastTurnId:U.lastTurnId,tailUserMessageId:K})),[U.lastTurnId,ee,G,P,K]),re=p.useMemo(()=>{if(q)return{kind:"turn",key:`turn:${q.turnId}`,turn:q,isLastTurn:q.turnId===U.lastTurnId};if(U.ungroupedMessageIds.size===0)return;const ie=B[B.length-1];if(!(!ie||!U.ungroupedMessageIds.has(ie.info.id)))return{kind:"ungrouped",key:`msg:${ie.info.id}`,message:ie,previousMessage:B.length>1?B[B.length-2]:void 0,nextMessage:void 0}},[B,U.lastTurnId,U.ungroupedMessageIds,q]);re&&Is("ui.message_list.render.streaming");const fe=re?re.kind==="turn"?re.turn.userMessage:re.message:void 0,ge=p.useMemo(()=>{const ie=se.map((le,X)=>{if(le.kind!=="turn")return le;const ne=X<se.length-1?(()=>{const he=se[X+1];return he&&he.kind==="turn"?he.turn.userMessage:he?.kind==="ungrouped"?he.message:void 0})():fe;return ne?{...le,nextEntryFirstMessage:ne}:le});let ke=0;for(const le of ie)le.kind==="turn"&&(ke+=1);let ve=-1;const xe=[],_e=[];for(const le of ie){if(le.kind!=="turn"){_e.push(le);continue}if(ve+=1,R$(ve,ke,C)){xe.push(le.turn);continue}_e.push(le)}return xe.length===0?_e:[{kind:"history-gate",key:"history-gate",turns:xe},..._e]},[C,se,fe]);p.useLayoutEffect(()=>{const ie=M.current;if(ie){M.current=null;const _e=h?.current;if(_e){const le=ie.anchor?.messageId?_e.querySelector(`[data-message-id="${ie.anchor.messageId}"]`):null;if(le&&ie.anchor){const X=_e.getBoundingClientRect(),ne=le.getBoundingClientRect().top-X.top-ie.anchor.offsetTop;ne!==0&&(_e.scrollTop+=ne)}else{const X=_e.scrollHeight-ie.height;X>0?_e.scrollTop=ie.top+X:_e.scrollTop=ie.top}}}const ke=j.current;if(!ke)return;j.current=null,W()?.querySelector(`[data-turn-id="${ke}"]`)?.scrollIntoView({block:"start"})},[ge,W,h]);const we=un()||ge.length>=wG,Me=we?"tanstack":"none",He=p.useRef(null),Ae=p.useCallback(ie=>{He.current=ie},[]),Ge=p.useMemo(()=>{const ie=re?[...ge,re]:ge;return ce.length>0?[...ie,...ce]:ie},[ge,re,ce]),et=sl(ie=>{d(ie)}),Xe=sl(ie=>{d(ie)}),oe=p.useMemo(()=>t.filter(ie=>Ns(ie)==="user").map(ie=>ie.info.id),[t]);{const ie=I.current;ie.sessionKey!==e&&(ie.sessionKey=e,ie.previousOrder=oe,ie.animatedIds=new Set);const ke=ie.previousOrder;if(oe.length>ke.length&&ke.every((xe,_e)=>oe[_e]===xe)&&WI(e))for(let xe=ke.length;xe<oe.length;xe+=1){const _e=oe[xe];if(_e&&!ie.animatedIds.has(_e)){if(!KI(e))break;ie.animatedIds.add(_e)}}ie.previousOrder=oe}const Q=p.useCallback(ie=>Ns(ie)!=="user"?!1:I.current.animatedIds.has(ie.info.id),[]),ue=p.useCallback(ie=>{I.current.animatedIds.delete(ie)},[]),be=p.useMemo(()=>{const ie=new Map;return Ge.forEach((ke,ve)=>{if(ke.kind==="ungrouped"){ie.set(ke.message.info.id,ve);return}if(ke.kind==="history-gate"){ke.turns.forEach(xe=>{ie.set(xe.userMessage.info.id,ve),xe.assistantMessages.forEach(_e=>{ie.set(_e.info.id,ve)})});return}ie.set(ke.turn.userMessage.info.id,ve),ke.turn.assistantMessages.forEach(xe=>{ie.set(xe.info.id,ve)})}),ie},[Ge]),Ie=p.useMemo(()=>{const ie=new Map;return Ge.forEach((ke,ve)=>{ke.kind==="turn"&&ie.set(ke.turn.turnId,ve),ke.kind==="history-gate"&&ke.turns.forEach(xe=>{ie.set(xe.turnId,ve)})}),ie},[Ge]),Fe=p.useCallback(ie=>{const ke=W();return ke?ke.querySelector(`[data-message-id="${ie}"]`):null},[W]),ht=p.useCallback(ie=>{if(ie<0||ie>=ge.length||!we)return!1;const ke=He.current;return ke?(ke.scrollToIndex(ie,{align:"start",behavior:"auto"}),!0):!1},[ge.length,we]),ye=p.useCallback((ie,ke="auto")=>{const ve=W();if(!ve)return!1;const xe=Fe(ie);if(!xe)return!1;const _e=ve.getBoundingClientRect(),ne=xe.getBoundingClientRect().top-_e.top+ve.scrollTop-50;return ve.scrollTo({top:ne,behavior:ke}),!0},[Fe,W]),Ze=p.useCallback((ie,ke,ve)=>{if(typeof window>"u")return!1;let xe=0;const _e=()=>{tW(ie,ke),!ye(ke,ve)&&(xe+=1,xe<60&&window.requestAnimationFrame(_e))};return window.requestAnimationFrame(_e),!0},[ye]);return p.useEffect(()=>{if(!g)return;const ie={scrollToTurnId:(ve,xe)=>{const _e=ge.find(qe=>qe.kind==="history-gate");if(_e?.kind==="history-gate"){const qe=ge.reduce((st,je)=>je.kind==="turn"?st+1:st,0);E(ve,_e.turns,_e.turns.length+qe)}const le=xe?.behavior??"auto",X=Ie.get(ve);if(X===void 0)return!1;const ne=W();if(!ne)return!1;const he=ne.querySelector(`[data-turn-id="${ve}"]`);return he?(he.scrollIntoView({behavior:le,block:"start"}),!0):re!==void 0&&X>=ge.length?!1:ht(X)},scrollToMessageId:(ve,xe)=>{const _e=xe?.behavior??"auto",le=be.get(ve);if(le===void 0)return!1;const X=Ge[le];if(X?.kind==="history-gate"){const De=X.turns.find(qe=>qe.userMessage.info.id===ve||qe.assistantMessages.some(st=>st.info.id===ve));if(De){const qe=ge.reduce((st,je)=>je.kind==="turn"?st+1:st,0);E(De.turnId,X.turns,X.turns.length+qe)}}if(ye(ve,_e))return!0;re!==void 0&&le>=ge.length||ht(le);const he=U.indexes.messageToTurnId.get(ve);return he?Ze(he,ve,_e):!1},holdViewportAnchor:ve=>{const xe=W();if(!xe||typeof window>"u")return;let _e=0,le=0,X=!1;const ne=()=>{X=!0,xe.removeEventListener("touchstart",ne),xe.removeEventListener("wheel",ne)};xe.addEventListener("touchstart",ne,{passive:!0}),xe.addEventListener("wheel",ne,{passive:!0});const he=()=>{if(X)return;const De=Fe(ve.messageId);if(De){const qe=De.getBoundingClientRect().top-xe.getBoundingClientRect().top-ve.offsetTop;Math.abs(qe)>.5?(xe.scrollTop+=qe,le=0):le+=1}if(_e+=1,le>=TG||_e>=AG){xe.removeEventListener("touchstart",ne),xe.removeEventListener("wheel",ne);return}window.requestAnimationFrame(he)};window.requestAnimationFrame(he)},isHistoryVirtualized:()=>we,captureViewportAnchor:()=>{const ve=W();if(!ve)return null;const xe=ve.getBoundingClientRect(),le=Array.from(ve.querySelectorAll("[data-message-id]")).find(ne=>ne.getBoundingClientRect().bottom>xe.top+1);if(!le)return null;const X=le.dataset.messageId;return X?{messageId:X,offsetTop:le.getBoundingClientRect().top-xe.top}:null},restoreViewportAnchor:ve=>{const xe=W();if(!xe||!be.has(ve.messageId))return!1;const _e=()=>{const le=Fe(ve.messageId);if(!le)return!1;const X=xe.getBoundingClientRect(),he=le.getBoundingClientRect().top-X.top-ve.offsetTop;return he!==0&&(xe.scrollTop+=he),!0};if(!_e()){const le=be.get(ve.messageId);if(typeof le=="number"&&le<ge.length)return ht(le)}return _e()},scrollToBottom:()=>{if(we&&ge.length>0&&He.current){He.current.scrollToEnd();return}const ve=W();ve&&(ve.scrollTop=ve.scrollHeight+4096)}};if(typeof g=="function")return g(ie),()=>{g(null)};const ke=g;return ke.current=ie,()=>{ke.current=null}},[Ge,Fe,ge,be,U.indexes.messageToTurnId,W,E,Ze,ht,ye,we,re,Ie,g]),c.jsx("div",{children:c.jsx(hx,{disabled:!1,children:c.jsxs("div",{className:"relative w-full",children:[c.jsx(hx,{disabled:we,children:c.jsx(r9,{entries:ge,engine:Me,contentRef:D,scrollRef:h,registerTanstackVirtualizer:Ae,virtualizerKey:e,onMessageContentChange:et,getAnimationHandlers:N,scrollToBottom:O,shouldAnimateUserMessage:Q,onUserAnimationConsumed:ue,onLoadOlderHistory:_,onLoadAllHistory:k},e)}),re?c.jsx(s9,{entry:re,sessionId:e??null,directory:m,onMessageContentChange:Xe,getAnimationHandlers:N,scrollToBottom:O,sessionIsWorking:n,sessionAwaitingRecovery:r,awaitingPromptEcho:s,shouldAnimateUserMessage:Q,onUserAnimationConsumed:ue,activeStreamingMessageId:o,activeStreamingPhase:i}):null,ce.map(ie=>c.jsx(Su,{entry:ie,onMessageContentChange:Xe,getAnimationHandlers:N,scrollToBottom:O,sessionIsWorking:n,shouldAnimateUserMessage:Q,onUserAnimationConsumed:ue},ie.key))]})})})});o9.displayName="MessageList";const UG=p.memo(o9),qG=({visible:e,onClick:t})=>c.jsx("div",{className:R("absolute bottom-full left-1/2 -translate-x-1/2 mb-2 transition-all duration-150",e?"opacity-100 translate-y-0 scale-100 pointer-events-auto":"opacity-0 translate-y-2 scale-95 pointer-events-none"),children:c.jsx(Se,{variant:"outline",size:"sm",onClick:t,className:"size-8 rounded-full [corner-shape:round] p-0 shadow-none bg-background/95 hover:bg-interactive-hover","aria-label":"Scroll to bottom",children:c.jsx($,{name:"arrow-down",className:"h-4 w-4"})})}),WG=p.memo(qG),KG=.1,GG=40,ZG=2,Ux=1500,qx=2,i9=350,YG=300,XG=600,JG=8e3,qi=()=>typeof performance<"u"?performance.now():Date.now(),QG=(e,t)=>{if(e)return GG;const n=t?.clientHeight??0;return n<=0?96:Math.max(48,n*KG)},a9=e=>e.scrollHeight-e.scrollTop-e.clientHeight,Ei=e=>e.scrollHeight-e.clientHeight>1,Wx=(e,t)=>a9(e)<=QG(t,e),eZ=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case"ArrowUp":case"PageUp":case"Home":return!0;default:return!1}},tZ=(e,t)=>{if(!(t instanceof Element))return null;const n=t.closest("[data-scrollable]");return!n||n===e||!(n instanceof HTMLElement)?null:n},Kx=(e,t)=>{const n=tZ(e,t);return n?n.scrollTop>0:!1},nZ=100,rZ=48,sZ=.1,oZ=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=Math.max(rZ,e.clientHeight*sZ),iZ=(e,t)=>{if(e.length===0)return;let n=0,r=e.length-1,s=0;for(;n<=r;){const o=n+r>>1,i=e[o]?.top;if(i===void 0)break;if(i<=t){s=o,n=o+1;continue}r=o-1}return e[s]?.id},aZ=e=>{const t=e.raf??requestAnimationFrame,n=e.caf??cancelAnimationFrame,r=e.ResizeObserver??globalThis.ResizeObserver,s=e.MutationObserver??globalThis.MutationObserver;let o,i,a,l,d,f,u=!0;const h=new Map;let m=[];const g=()=>{l===void 0&&(l=t(()=>{l=void 0,b()}))},x=()=>{const T=o;if(!T){m=[],u=!1;return}const A=T.getBoundingClientRect().top;m=[...h].map(([_,k])=>({id:_,top:k.getBoundingClientRect().top-A+T.scrollTop})),m.sort((_,k)=>_.top-k.top),u=!1},b=()=>{const T=o;if(!T)return;u&&x();const A=oZ(T)?m[m.length-1]?.id:iZ(m,T.scrollTop+nZ);!A||A===f||(f=A,e.onActive(A))},S=()=>{const T=o;if(T){if(clearTimeout(d),d=void 0,i?.disconnect(),i=void 0,r){i=new r(()=>{clearTimeout(d),d=setTimeout(()=>{u=!0,g()},100)}),i.observe(T);for(const A of h.values())i.observe(A)}if(a?.disconnect(),a=void 0,s){a=new s(()=>{u=!0,g()});const A={subtree:!0,childList:!0};r||(A.characterData=!0,A.characterDataOldValue=!1),a.observe(T,A)}u=!0,g()}},y=T=>{o!==T&&(o=T,f=void 0,S())},v=(T,A)=>{const _=h.get(A);_&&_!==T&&i?.unobserve(_),h.set(A,T),i&&i.observe(T),u=!0,g()},C=T=>{const A=h.get(T);A&&(i?.unobserve(A),h.delete(T),u=!0,g())},w=()=>{u=!0,g()},M=()=>{for(const T of h.values())i?.unobserve(T);h.clear(),m=[],f=void 0,u=!0};return{setContainer:y,register:v,unregister:C,onScroll:g,markDirty:w,clear:M,destroy:()=>{l!==void 0&&n(l),l=void 0,clearTimeout(d),d=void 0,M(),i?.disconnect(),a?.disconnect(),i=void 0,a=void 0,o=void 0},getActiveId:()=>f}};function cZ(e,t){p.useEffect(()=>{if(!t)return;const n=e;if(!n)return;let r=null;const s=aZ({onActive:u=>{u!==r&&(r=u,t(u))}});s.setContainer(n);const o=new Map,i=u=>{const h=u.dataset.turnId;return h?(o.set(h,u),s.register(u,h),!0):!1},a=u=>{const h=u.dataset.turnId;return!h||o.get(h)!==u?!1:(o.delete(h),s.unregister(h),!0)},l=u=>{if(!(u instanceof HTMLElement))return[];const h=[];return u.matches("[data-turn-id]")&&h.push(u),u.querySelectorAll("[data-turn-id]").forEach(m=>h.push(m)),h};n.querySelectorAll("[data-turn-id]").forEach(i),s.markDirty();const d=new MutationObserver(u=>{let h=!1;u.forEach(m=>{m.removedNodes.forEach(g=>{l(g).forEach(x=>{a(x)&&(h=!0)})}),m.addedNodes.forEach(g=>{l(g).forEach(x=>{i(x)&&(h=!0)})})}),h&&s.markDirty()});d.observe(n,{subtree:!0,childList:!0});const f=()=>s.onScroll();return n.addEventListener("scroll",f,{passive:!0}),()=>{n.removeEventListener("scroll",f),d.disconnect(),s.destroy()}},[e,t])}function lZ({containerEl:e,handleScrollEvent:t,releaseFromUserIntent:n,scrollRef:r,stateRef:s,canScroll:o,scrollToBottomNow:i,updateOverflowAndButton:a,keyboardAnimRef:l,animationGuardUntilRef:d,lastScrollTopRef:f}){p.useEffect(()=>{const u=e;if(!u)return;f.current=u.scrollTop;const h=v=>{v.deltaY>=0||Kx(u,v.target)||n()};let m=null;const g=v=>{const C=v.touches.item(0);m=C?C.clientY:null},x=v=>{const C=v.touches.item(0);if(!C){m=null;return}const w=m;m=C.clientY,!(w===null||C.clientY-w<=ZG)&&(Kx(u,v.target)||n())},b=()=>{m=null},S=v=>{eZ(v)&&n()},y=v=>{const C=v.target;C instanceof Element&&C.closest("[data-overlay-scrollbar-thumb]")&&n()};return u.addEventListener("scroll",t,{passive:!0}),u.addEventListener("wheel",h,{passive:!0}),u.addEventListener("touchstart",g,{passive:!0}),u.addEventListener("touchmove",x,{passive:!0}),u.addEventListener("touchend",b,{passive:!0}),u.addEventListener("touchcancel",b,{passive:!0}),u.addEventListener("keydown",S),typeof window<"u"&&window.addEventListener("pointerdown",y,!0),()=>{u.removeEventListener("scroll",t),u.removeEventListener("wheel",h),u.removeEventListener("touchstart",g),u.removeEventListener("touchmove",x),u.removeEventListener("touchend",b),u.removeEventListener("touchcancel",b),u.removeEventListener("keydown",S),typeof window<"u"&&window.removeEventListener("pointerdown",y,!0)}},[e,t,f,n]),p.useEffect(()=>{if(typeof window>"u")return;const u=m=>{const g=m.detail;g&&(l.current=!0,d.current=qi()+g.durationMs+i9)},h=()=>{l.current=!1;const m=r.current;if(!m){a();return}s.current==="following"&&o(m)&&i("auto"),a()};return window.addEventListener("oc:keyboard-anim",u),window.addEventListener("oc:keyboard-settled",h),()=>{window.removeEventListener("oc:keyboard-anim",u),window.removeEventListener("oc:keyboard-settled",h),l.current=!1}},[d,o,l,r,i,s,a])}const dZ=({currentSessionId:e,currentSessionKey:t,sessionMessageCount:n,latestTailEntryId:r=null,sessionIsWorking:s,isMobile:o,onActiveTurnChange:i})=>{const a=p.useRef(null),[l,d]=p.useState(null),f=p.useRef(null),[u,h]=p.useState("following"),[m,g]=p.useState(!1),[x,b]=p.useState(!1),[S,y]=p.useState(!1),v=p.useRef("following"),C=p.useRef(o);C.current=o;const w=p.useRef(s);w.current=s;const M=p.useRef(!1),j=p.useRef(null),T=p.useRef(t);T.current=t;const A=p.useRef(null),_=p.useRef(null),k=p.useRef(null),E=p.useRef(0),I=p.useRef(!1),N=p.useRef(0),O=p.useRef(!1),L=p.useRef(null),D=p.useRef(null),W=p.useRef(0),z=p.useRef(null);p.useLayoutEffect(()=>{a.current!==f.current&&(f.current=a.current,d(a.current))});const J=p.useCallback(()=>w.current||M.current,[]),B=p.useCallback(Q=>{v.current!==Q&&(v.current=Q,h(Q))},[]),U=p.useCallback(Q=>{_.current={top:Math.max(0,Q.scrollHeight-Q.clientHeight),time:qi()},k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{_.current=null,k.current=null},Ux)},[]),P=p.useCallback(Q=>{const ue=_.current;return ue?qi()-ue.time>Ux?(_.current=null,!1):Math.abs(Q.scrollTop-ue.top)<qx:!1},[]),q=p.useCallback(()=>qi()<E.current,[]),F=p.useCallback(()=>{O.current=!1,L.current&&(clearTimeout(L.current),L.current=null),D.current&&(clearTimeout(D.current),D.current=null)},[]),ee=p.useCallback(()=>{L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{L.current=null,F()},XG)},[F]),G=p.useCallback(()=>{const Q=a.current;Q&&(O.current=!0,W.current=Q.scrollHeight,ee(),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{D.current=null,F()},JG))},[ee,F]),K=p.useCallback(()=>{const Q=a.current;if(!Q){g(!1),b(!1);return}const ue=Ei(Q);if(g(ue),!ue){b(!1);return}const be=v.current==="released"&&!Wx(Q,C.current);b(be)},[]),se=p.useCallback(Q=>{const ue=a.current;if(!ue)return;U(ue);const be=ue.scrollHeight+4096;if(Q==="smooth"){ue.scrollTo({top:be,behavior:Q});return}ue.scrollTop=be},[U]),ce=p.useCallback((Q,ue="auto")=>{const be=a.current;!Q&&!J()||(Q&&v.current!=="following"&&B("following"),be&&(!Q&&v.current!=="following"||se(Q?ue:"auto")))},[J,se,B]),re=p.useCallback(()=>{const Q=a.current;if(Q){if(!Ei(Q)){B("following");return}v.current!=="released"&&(B("released"),K())}},[B,K]),fe=p.useCallback((Q="instant")=>{ce(!0,Q==="smooth"?"smooth":"auto")},[ce]),ge=p.useCallback(()=>{ce(!0)},[ce]),we=p.useCallback(()=>{B("released"),K()},[B,K]),Me=p.useCallback(()=>{F(),re()},[F,re]),He=p.useCallback(async()=>{const Q=T.current;return Q?a.current?(z.current=null,B("following"),ce(!0),G(),K(),!1):(z.current=Q,B("following"),!1):!1},[G,ce,B,K]);p.useEffect(()=>{!e||!t||t===A.current||(A.current=t,ws.getInstance().recordSessionStart(e),_.current=null,z.current&&z.current!==t&&(z.current=null))},[e,t]),p.useEffect(()=>{if(M.current=!1,j.current&&(clearTimeout(j.current),j.current=null),s){v.current==="following"&&ce(!0);return}M.current=!0,j.current=setTimeout(()=>{M.current=!1,j.current=null},YG)},[s,ce]),p.useEffect(()=>{y(u==="following"&&s)},[u,s]),p.useLayoutEffect(()=>{l&&z.current&&z.current===t&&He()},[l,t,He]);const Ae=p.useCallback(()=>{const Q=a.current;if(!Q)return;const ue=N.current;N.current=Q.scrollTop;const be=Q.scrollTop>ue+.5;if(K(),!Ei(Q)){B("following");return}if(Wx(Q,C.current)){const Ie=a9(Q)<=qx;(be||v.current==="following"||Ie)&&B("following");return}if(v.current==="following"&&(P(Q)||q())){ce(!1);return}Me()},[q,P,Me,ce,B,K]);lZ({containerEl:l,handleScrollEvent:Ae,releaseFromUserIntent:Me,scrollRef:a,stateRef:v,canScroll:Ei,scrollToBottomNow:se,updateOverflowAndButton:K,keyboardAnimRef:I,animationGuardUntilRef:E,lastScrollTopRef:N}),p.useEffect(()=>{const Q=l;if(!Q||typeof ResizeObserver>"u")return;const ue=new ResizeObserver(()=>{if(I.current){K();return}const Ie=a.current;if(Ie&&!Ei(Ie)){B("following"),K();return}if(K(),O.current&&Ie){const Fe=Ie.scrollHeight>W.current+1;W.current=Ie.scrollHeight,ce(!0),Fe&&ee();return}J()&&v.current==="following"&&ce(!1)});ue.observe(Q);const be=Q.firstElementChild;return be instanceof Element&&ue.observe(be),()=>ue.disconnect()},[ee,l,J,ce,B,K]),p.useEffect(()=>{K()},[n,K]);const Ge=p.useRef(null);p.useEffect(()=>{const Q=Ge.current;Ge.current={key:t,count:n,tailId:r},!(!Q||!t||Q.key!==t||!(n>Q.count||r!==null&&r!==Q.tailId))&&(w.current||v.current!=="following"||(ce(!0),G()))},[G,t,r,ce,n]);const et=p.useCallback(Q=>{if(Q==="animation"&&(E.current=qi()+i9),K(),O.current){ce(!0),ee();return}v.current==="following"&&ce(!1)},[ee,ce,K]),Xe=p.useRef(new Map),oe=p.useCallback(Q=>{const ue=Xe.current.get(Q);if(ue)return ue;const be=()=>{v.current==="following"&&ce(!1)},Ie={onChunk:be,onComplete:()=>{K()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:be,onReservationCancelled:()=>{}};return Xe.current.set(Q,Ie),Ie},[ce,K]);return p.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),j.current&&(clearTimeout(j.current),j.current=null),F()},[F]),cZ(l,i),{scrollRef:a,state:u,isPinned:u==="following",isOverflowing:m,isFollowingProgrammatically:S,showScrollButton:x,notifyContentChange:et,getAnimationHandlers:oe,goToBottom:fe,scrollToBottomOnSend:ge,releaseAutoFollow:we,restoreSnapshot:He}},Y1=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},X1=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},Gx=e=>{if(!e)return null;const t=Y1(e),n=typeof e.info?.id=="string"?e.info.id:"",r=X1(e)??"";return`${n}::${t}::${r}`},uZ=e=>({turnIds:[...e.turnIds],turnMessageStartIndexes:[...e.turnMessageStartIndexes],turnIndexById:new Map(e.turnIndexById),messageToTurnId:new Map(e.messageToTurnId),messageToTurnIndex:new Map(e.messageToTurnIndex),turnCount:e.turnCount}),fZ=(e,t,n)=>{if(!e||!t)return null;if(t.length===n.length){let f=-1;for(let u=0;u<n.length;u+=1)if(t[u]!==n[u]){if(f!==-1)return null;f=u}return f===-1?e:f!==n.length-1?null:Gx(t[f])===Gx(n[f])?e:null}if(n.length!==t.length+1)return null;for(let f=0;f<t.length;f+=1)if(t[f]!==n[f])return null;const r=n[n.length-1];if(!r)return null;const s=Y1(r),o=r.info.id,i=uZ(e);if(s==="user"){const f=i.turnIds.length;return i.turnIds.push(o),i.turnMessageStartIndexes.push(n.length-1),i.turnIndexById.set(o,f),i.messageToTurnId.set(o,o),i.messageToTurnIndex.set(o,f),i.turnCount=i.turnIds.length,i}if(s!=="assistant"){const f=i.turnIds.length-1;if(f<0)return null;const u=i.turnIds[f];return u?(i.messageToTurnId.set(o,u),i.messageToTurnIndex.set(o,f),i):null}const a=X1(r);if(!a)return i;const l=i.turnIndexById.get(a);if(typeof l!="number"||l<0)return null;const d=i.turnIds[l];return d?(i.messageToTurnId.set(o,d),i.messageToTurnIndex.set(o,l),i):null},hZ=e=>{const t=[],n=[],r=new Map,s=new Map,o=new Map,i=new Map;let a=-1;return e.forEach((l,d)=>{const f=Y1(l),u=l.info.id;if(f==="user"){a=t.length,t.push(u),n.push(d),r.set(u,a),i.set(u,a),s.set(u,u),o.set(u,a);return}if(f!=="assistant"){if(a>=0){const x=t[a];x&&(s.set(u,x),o.set(u,a))}return}const h=X1(l);if(!h)return;const m=i.get(h);if(typeof m!="number"||m<0)return;const g=t[m];g&&(s.set(u,g),o.set(u,m))}),{turnIds:t,turnMessageStartIndexes:n,turnIndexById:r,messageToTurnId:s,messageToTurnIndex:o,turnCount:t.length}},pZ=30,mZ=1200,gZ=1.5,yZ=e=>Math.max(mZ,e*gZ),vZ=4,xZ=30,bZ=250,wZ=2e3,SZ=2500,uo=new Map,CZ=()=>un()?vZ:pZ,kZ=e=>un()?e.length<=xZ:!0,Zx=(e,t)=>{if(uo.delete(e),!kZ(t.messages))return;const n=CZ();for(;uo.size>=n;){const r=uo.keys().next().value;if(typeof r!="string")break;uo.delete(r)}uo.set(e,t)},MZ=e=>!e.sessionId||!e.isPinned||!e.canLoadEarlier||e.isLoadingOlder||e.pendingRevealWork?!1:e.scrollHeight<=e.clientHeight+1,Yx=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),IZ=20,EZ=4,Xx=(e,t)=>{const n=e.style.overflow;if(e.style.overflow="hidden",e.scrollTop=t,e.scrollHeight,e.style.overflow=n,e.scrollTop=t,typeof window>"u")return;let r=!1,s=0;const o=()=>{r=!0};e.addEventListener("touchstart",o,{passive:!0,once:!0});const i=()=>{r||(e.scrollTop<t-EZ&&(e.scrollTop=t),s+=1,s<IZ?window.requestAnimationFrame(i):e.removeEventListener("touchstart",o))};window.requestAnimationFrame(i)},Jx=(e,t,n)=>!e||!t||t===e?!1:n.some(r=>r.info.id===e);function jZ({sessionKey:e,timelineIdentityRef:t,scrollRef:n,messageListRef:r,renderedMessages:s,isPinnedRef:o,goToBottom:i,captureViewportAnchor:a,restoreViewportAnchor:l}){const d=p.useRef(null),f=p.useRef(null);return p.useLayoutEffect(()=>{d.current=null,f.current=null},[e]),p.useLayoutEffect(()=>{const u=n.current;if(!u)return;let h=d.current;const m=f.current,g=s[0]?.info?.id??null,x=s[s.length-1]?.info?.id??null,b=m?Yx({previousOldestId:m.oldestId,previousNewestId:m.newestId,currentOldestId:g,currentNewestId:x})||Jx(m.oldestId,g,s):!1;h&&h.identity!==t.current&&(d.current=null,h=null);const S=h?Yx({previousOldestId:h.oldestId,previousNewestId:h.newestId,currentOldestId:g,currentNewestId:x})||Jx(h.oldestId,g,s):!1,y=b||S,v=!!(h&&(b||S)),C=()=>{f.current={oldestId:g,newestId:x,scrollHeight:u.scrollHeight}},w=()=>{const j=d.current;j&&(d.current={...j,height:u.scrollHeight,top:u.scrollTop,anchor:a(),oldestId:g,newestId:x})};if(o.current){y?(d.current=null,i("instant")):h&&w(),C();return}const M=r.current?.isHistoryVirtualized()??!1;if(h&&v){if(d.current=null,M){!h.historyVirtualized&&h.anchor&&l(h.anchor),C();return}const j=u.scrollHeight-h.height,T=()=>j<=0?!1:(u.scrollTop=h.top+j,!0);if(un()&&j>0){Xx(u,h.top+j),C();return}h.anchor&&l(h.anchor)||T()}else if(b&&m&&!M){const j=u.scrollHeight-m.scrollHeight;if(j>0){const T=u.scrollTop+j;un()?Xx(u,T):u.scrollTop=T}}else h&&w();C()},[a,r,s,n,l,i,o,t]),{prePrependScrollRef:d}}const _Z=({sessionId:e,sessionKey:t,messages:n,historyMeta:r,scrollRef:s,messageListRef:o,loadMoreMessages:i,goToBottom:a,releaseAutoFollow:l,isPinned:d,showScrollButton:f})=>{const u=p.useRef(null),h=p.useRef(null),m=p.useRef(null),g=p.useMemo(()=>{const oe=t??"";m.current!==t&&(m.current=t,u.current=null,h.current=null);const Q=oe?uo.get(oe):void 0;if(Q&&Q.messages===n)return Zx(oe,Q),u.current=Q.model,h.current=n,Q.model;const be=fZ(u.current,h.current,n)??hZ(n);return u.current=be,h.current=n,oe&&n.length>0&&Zx(oe,{messages:n,model:be}),be},[n,t]),[x,b]=p.useState(!1),[S,y]=p.useState(!1),[v,C]=p.useState(null),w=p.useRef(g),M=p.useRef(d),j=p.useRef(x),T=p.useRef(S),A=p.useRef(e),_=p.useRef({key:t});_.current.key!==t&&(_.current={key:t});const k=p.useRef(n),E=p.useRef(r),I=p.useRef(null),N=p.useRef([]),O=p.useRef(null),L=p.useRef(null),D=p.useRef(!1),W=p.useRef(null),z=p.useMemo(()=>{const oe=ty().HISTORICAL_MESSAGES,Q=!1,ue=r?!r.complete:n.length>=oe,be=!!r?.loading;return{hasBufferedTurns:Q,hasMoreAboveTurns:ue,historyLoading:be,canLoadEarlier:ue}},[r,n.length]),J=p.useRef(z);w.current=g,M.current=d,j.current=x,T.current=S,J.current=z,A.current=e,k.current=n,E.current=r;const B=p.useCallback(()=>{D.current=!0,W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null)},[]),U=p.useCallback(()=>{if(typeof window>"u"){D.current=!1;return}W.current!==null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{W.current=null,D.current=!1},wZ)},[]);p.useLayoutEffect(()=>{if(I.current===t)return;W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),D.current=!1,I.current=t;const oe=O.current;oe&&oe.identity!==_.current&&(O.current=null,oe.resolve(!1)),b(!1),y(!1),L.current=null,C(null)},[t]),p.useLayoutEffect(()=>{if(!d)return;const oe=g.turnIds[g.turnIds.length-1];oe&&C(Q=>Q===oe?Q:oe)},[d,g.turnIds]);const P=p.useCallback(()=>{const oe=N.current;oe.length!==0&&(N.current=[],oe.forEach(Q=>Q()))},[]),q=p.useCallback(()=>new Promise(oe=>{if(typeof window>"u"){oe();return}let Q=!1;const ue=()=>{Q||(Q=!0,window.clearTimeout(be),oe())};N.current.push(ue);const be=window.setTimeout(ue,bZ)}),[]),F=p.useCallback(oe=>{const Q=O.current;Q&&(O.current=null,Q.resolve(oe))},[]),ee=p.useCallback(()=>{const oe=O.current;if(!oe)return;if(oe.identity!==_.current){F(!1);return}if(oe.kind==="turn"?o.current?.scrollToTurnId(oe.id,{behavior:oe.behavior})??!1:o.current?.scrollToMessageId(oe.id,{behavior:oe.behavior})??!1){oe.turnId&&(L.current={turnId:oe.turnId,expiresAt:Date.now()+SZ},C(oe.turnId)),F(!0);return}typeof(oe.kind==="turn"?w.current.turnIndexById.get(oe.id):w.current.messageToTurnIndex.get(oe.id))=="number"&&F(!1)},[o,F]);p.useEffect(()=>()=>{W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),P(),F(!1)},[P,F]);const G=n;p.useLayoutEffect(()=>{P(),ee()},[ee,G,P]);const K=p.useCallback(()=>o.current?.captureViewportAnchor()??null,[o]),se=p.useCallback(oe=>o.current?.restoreViewportAnchor(oe)??!1,[o]),{prePrependScrollRef:ce}=jZ({sessionKey:t,timelineIdentityRef:_,scrollRef:s,messageListRef:o,renderedMessages:G,isPinnedRef:M,goToBottom:a,captureViewportAnchor:K,restoreViewportAnchor:se}),re=p.useCallback(async()=>!1,[]),fe=p.useCallback(async oe=>{if(!A.current||!_.current.key||j.current||!J.current.hasMoreAboveTurns)return!1;const Q=A.current,ue=_.current;if(!Q||!ue.key)return!1;const be=()=>{ce.current?.identity===ue&&(ce.current=null)},Ie=s.current,Fe=k.current,ht=Fe.length,ye=Fe[0]?.info?.id??null,Ze=E.current?.limit??ty().HISTORICAL_MESSAGES;oe.preserveViewport&&Ie&&(ce.current={identity:ue,height:Ie.scrollHeight,top:Ie.scrollTop,anchor:K(),historyVirtualized:o.current?.isHistoryVirtualized()??!1,oldestId:ye,newestId:Fe[Fe.length-1]?.info?.id??null}),B(),b(!0);try{let Be=ht,ie=ye,ke=Ze;const ve=w.current.turnCount;for(;;){if(await i(Q,"up"),_.current!==ue||(await q(),_.current!==ue))return be(),!1;const xe=k.current,_e=xe.length,le=xe[0]?.info?.id??null,X=E.current?.limit??ke,ne=_e>Be||typeof ie=="string"&&typeof le=="string"&&ie!==le||X>ke;if(w.current.turnCount-ve>0)return!0;if(!ne)return be(),!1;if(!J.current.hasMoreAboveTurns)return!0;Be=_e,ie=le,ke=X}}catch(Be){throw be(),Be}finally{_.current===ue&&(b(!1),U())}},[B,K,i,o,ce,s,U,q]),ge=p.useCallback(async oe=>{const Q=_.current;B(),oe?.userInitiated&&l();try{await fe({preserveViewport:!0})}finally{_.current===Q&&U()}},[B,fe,l,U]),we=p.useCallback(()=>{if(un())return;const oe=s.current;oe&&(M.current||oe.scrollTop>=yZ(oe.clientHeight)||J.current.canLoadEarlier&&(j.current||T.current||ge({userInitiated:!0})))},[ge,s]),Me=p.useCallback(()=>{if(un()||D.current)return;const oe=s.current;oe&&MZ({sessionId:A.current,isPinned:M.current,canLoadEarlier:J.current.canLoadEarlier,isLoadingOlder:j.current,pendingRevealWork:T.current,scrollHeight:oe.scrollHeight,clientHeight:oe.clientHeight})&&ge()},[ge,s]);p.useEffect(()=>{if(typeof window>"u")return;const oe=window.requestAnimationFrame(()=>{Me()});return()=>window.cancelAnimationFrame(oe)},[z.canLoadEarlier,x,d,Me,S,G.length,t]),p.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const oe=s.current;if(!oe)return;let Q=null;const ue=()=>{Q===null&&(Q=window.requestAnimationFrame(()=>{Q=null,Me()}))},be=new ResizeObserver(ue);be.observe(oe);const Ie=oe.firstElementChild;return Ie instanceof Element&&be.observe(Ie),ue(),()=>{Q!==null&&window.cancelAnimationFrame(Q),be.disconnect()}},[Me,s,t]);const He=p.useCallback(async(oe,Q)=>{if(!oe||!A.current||!_.current.key)return!1;const ue=_.current;l(),y(!0);try{return _.current!==ue||typeof w.current.turnIndexById.get(oe)!="number"?!1:!!await new Promise(Fe=>{O.current={identity:ue,kind:"turn",id:oe,behavior:Q?.behavior??"auto",turnId:oe,resolve:Fe},ee()})}finally{_.current===ue&&y(!1)}},[ee,l]),Ae=p.useCallback(async(oe,Q)=>{if(!oe||!A.current||!_.current.key)return!1;const ue=_.current;l(),y(!0);try{if(_.current!==ue)return!1;const be=w.current.messageToTurnId.get(oe);return typeof w.current.messageToTurnIndex.get(oe)!="number"?!1:!!await new Promise(ht=>{O.current={identity:ue,kind:"message",id:oe,behavior:Q?.behavior??"auto",turnId:be??null,resolve:ht},ee()})}finally{_.current===ue&&y(!1)}},[ee,l]),Ge=p.useCallback(async()=>{y(!1),b(!1),a("smooth")},[a]),et=p.useCallback(async()=>{y(!1),b(!1),a("instant")},[a]),Xe=p.useCallback(oe=>{const Q=L.current;if(Q){if(oe!==Q.turnId&&Date.now()<Q.expiresAt)return;L.current=null}C(oe)},[]);return{turnIds:g.turnIds,turnStart:0,renderedMessages:G,historySignals:z,isLoadingOlder:x,pendingRevealWork:S,activeTurnId:v,showScrollToBottom:f&&!S,turnWindowModel:g,loadEarlier:ge,revealBufferedTurns:re,resumeToBottom:Ge,resumeToBottomInstant:et,scrollToTurn:He,scrollToMessage:Ae,handleHistoryScroll:we,captureViewportAnchor:K,restoreViewportAnchor:se,handleActiveTurnChange:Xe}};function Xp(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
215
+ `)}function c9(e,t=80){const r=Xp(e).replace(/\n/g," ");return r.length>t?`${r.slice(0,t)}…`:r}const TZ=({open:e,onOpenChange:t,onScrollToMessage:n,onScrollByTurnOffset:r,onResumeToLatest:s,canLoadEarlier:o=!1,isLoadingEarlier:i=!1,onLoadEarlier:a,onRevert:l,onFork:d})=>{const{isMobile:f}=On(),u=pe(q=>q.currentSessionId),[h,m]=p.useState(0);p.useEffect(()=>{if(!u){m(0);return}const q=()=>{try{const{getPiSessionStore:F}=require("@/apps/pi-session-store");m(F().getState().reducer.bySession.get(u)?.sessionTreeRevision??0)}catch{m(0)}};q();try{const{getPiSessionStore:F}=require("@/apps/pi-session-store");return F().subscribe(q,`session:${u}`)}catch{return}},[u]);const[g,x]=p.useState(new Map),b=p.useRef(null);p.useEffect(()=>{if(!e||!u)return;b.current!==u&&(b.current=u,x(new Map));let q=!1;return(async()=>{try{const{getPiSessionStore:F}=require("@/apps/pi-session-store"),ee=await F().tree(u);if(q)return;const G=new Map,K=se=>{se.label&&G.set(se.entryId,se.label);for(const ce of se.children)K(ce)};for(const se of ee.nodes)K(se);x(G)}catch{}})(),()=>{q=!0}},[u,e,h]);const[S,y]=p.useState(!1);p.useEffect(()=>{if(!u){y(!1);return}const q=()=>{try{const{getPiSessionStore:F}=require("@/apps/pi-session-store"),ee=F().getState().reducer.bySession.get(u);y(ee?.lifecycle==="busy"||ee?.lifecycle==="retry")}catch{y(!1)}};q();try{const{getPiSessionStore:F}=require("@/apps/pi-session-store");return F().subscribe(q,`session:${u}`)}catch{return}},[u]);const v=Qd(u??""),[C,w]=p.useState(""),[M,j]=p.useState(0),T=p.useRef([]),A=p.useRef(null),_=p.useRef(null),k=p.useRef(!1),E=p.useRef(e),I=p.useCallback(q=>new Date(q).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),[]),N=p.useCallback(q=>new Date(q).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),[]),O=p.useMemo(()=>v.filter(q=>q.info.role==="user").map(q=>({message:q})),[v]),L=p.useMemo(()=>{const q=C.trim();if(!q)return O;const F=q.toLowerCase();return O.filter(({message:ee})=>Xp(ee.parts).toLowerCase().includes(F))},[O,C]);p.useEffect(()=>{k.current||j(C.trim()?0:Math.max(0,L.length-1))},[L,C]),p.useEffect(()=>{T.current=T.current.slice(0,L.length)},[L.length]),p.useEffect(()=>{k.current||T.current[M]?.scrollIntoView({block:"nearest"})},[M]),p.useEffect(()=>{!k.current||_.current||i||(k.current=!1)},[L.length,i]),p.useLayoutEffect(()=>{const q=E.current;if(E.current=e,!e||q||k.current||C.trim())return;const F=A.current;F&&(F.scrollTop=F.scrollHeight)},[e,C]),p.useLayoutEffect(()=>{const q=_.current,F=A.current;if(!q||!F||i)return;_.current=null;const ee=T.current.find(K=>K?.dataset.timelineMessageId===q.messageId);if(!ee)return;const G=ee.getBoundingClientRect().top-F.getBoundingClientRect().top;F.scrollTop+=G-q.top},[L.length,i]);const D=p.useCallback(()=>{const q=A.current;if(q){const F=q.getBoundingClientRect().top,ee=T.current.find(G=>G?G.getBoundingClientRect().bottom>=F:!1);ee?.dataset.timelineMessageId&&(_.current={messageId:ee.dataset.timelineMessageId,top:ee.getBoundingClientRect().top-F})}k.current=!0,a?.()},[a]),W=p.useCallback(async q=>{await n?.(q)!==!1&&t(!1)},[t,n]),z=p.useCallback(q=>{const F=L.length;if(F!==0){if(q.key==="ArrowDown"){q.preventDefault(),j(ee=>(ee+1)%F);return}if(q.key==="ArrowUp"){q.preventDefault(),j(ee=>(ee-1+F)%F);return}if(q.key==="Enter"){q.preventDefault();const ee=(M%F+F)%F,G=L[ee];G&&W(G.message.info.id)}}},[L,W,M]),J=p.useCallback(async()=>{const q=L.length;if(q===0||!l||S)return;const F=(M%q+q)%q,ee=L[F];if(ee)try{await l(ee.message.info.id),t(!1)}catch(G){Ce.error(G instanceof Error?G.message:"Failed to revert")}},[L,S,l,t,M]),B=p.useCallback(async()=>{const q=L.length;if(q===0||!d||S)return;const F=(M%q+q)%q,ee=L[F];if(ee)try{await d(ee.message.info.id),t(!1)}catch(G){Ce.error(G instanceof Error?G.message:"Failed to fork")}},[L,S,d,t,M]),U=p.useCallback(q=>{const F=L.length;if(F!==0){if(q.key==="ArrowDown"){q.preventDefault(),j(ee=>(ee+1)%F);return}if(q.key==="ArrowUp"){q.preventDefault(),j(ee=>(ee-1+F)%F);return}if(q.key==="Enter"){q.preventDefault();const ee=(M%F+F)%F,G=L[ee];G&&W(G.message.info.id)}}},[L,W,M]);if(p.useEffect(()=>{if(!e||f)return;const q=window.setTimeout(()=>A.current?.focus(),100);return()=>window.clearTimeout(q)},[e,f]),!u)return null;const P=L[(M%Math.max(1,L.length)+Math.max(1,L.length))%Math.max(1,L.length)]?.message??null;return c.jsx(ru,{open:e,onOpenChange:t,children:c.jsxs(su,{className:R("flex flex-col",f?"max-w-full max-h-[85vh] rounded-t-2xl mt-auto":"max-w-2xl max-h-[70vh]"),children:[c.jsxs(ou,{children:[c.jsxs(iu,{className:"flex items-center gap-2",children:[c.jsx($,{name:"time",className:"h-5 w-5"}),"Conversation Timeline"]}),c.jsx(Vm,{children:f?"Tap a message, then Revert or Fork":"Arrow keys to move • Enter to jump"})]}),!f&&c.jsxs("div",{className:"relative mt-2",children:[c.jsx($,{name:"search",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(Fo,{placeholder:"Search messages...",value:C,onChange:q=>w(q.target.value),onKeyDown:z,className:"pl-9 w-full"})]}),o&&a&&c.jsx("div",{className:"flex justify-center py-1",children:c.jsxs(Se,{type:"button",variant:"link",size:"sm",onClick:D,disabled:i,className:"h-auto px-1 py-0 text-muted-foreground hover:text-foreground",children:[i&&c.jsx($,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),c.jsx("div",{ref:A,tabIndex:0,onKeyDown:U,className:"flex-1 overflow-y-auto outline-none focus-visible:ring-1 focus-visible:ring-ring rounded","aria-label":"Message list",children:L.length===0?c.jsx("div",{className:"text-center text-muted-foreground py-8",children:C?"No messages found":"No messages in this session yet"}):L.map(({message:q},F)=>{const ee=c9(q.parts),G=q.info.time?.created??0,K=I(G),se=L[F-1],ce=se?I(se.message.info.time?.created??0):null,re=K!==ce,fe=N(G),ge=F===M,we=g.get(q.info.id),Me=C.trim()?NZ(Xp(q.parts),C):null;return c.jsxs(p.Fragment,{children:[re&&c.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-3 bg-background/95 py-2 backdrop-blur-sm",children:[c.jsx("div",{className:"h-px flex-1 bg-border/60"}),c.jsx("span",{className:"typography-meta text-muted-foreground",children:K}),c.jsx("div",{className:"h-px flex-1 bg-border/60"})]}),c.jsxs("div",{ref:He=>{T.current[F]=He},"data-timeline-message-id":q.info.id,className:R("group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",ge&&"bg-interactive-selection text-interactive-selection-foreground"),onClick:()=>{W(q.info.id)},onMouseEnter:()=>j(F),children:[c.jsx("span",{className:R("typography-meta w-16 flex-shrink-0 text-right tabular-nums",ge?"text-interactive-selection-foreground/70":"text-muted-foreground"),children:fe}),we&&c.jsx("span",{className:"max-w-40 shrink-0 truncate rounded-full border border-border/60 bg-muted/40 px-2 py-0.5 typography-micro text-muted-foreground",children:we}),c.jsxs("p",{className:R("flex-1 min-w-0 typography-small truncate",ge?"text-interactive-selection-foreground":"text-foreground"),children:[Me??(ee||"[No text content]"),!Me&&ee&&ee.length>=80&&"…"]})]})]},q.info.id)})}),P&&c.jsxs("div",{className:R("flex gap-2 mt-3",f?"flex-col":"flex-row"),children:[c.jsxs(Se,{type:"button",variant:f?"default":"outline",size:f?"default":"sm",className:R(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{J()},children:[c.jsx($,{name:"history",className:"h-4 w-4"}),"Revert"]}),c.jsxs(Se,{type:"button",variant:"outline",size:f?"default":"sm",className:R(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{B()},children:[c.jsx($,{name:"git-branch",className:"h-4 w-4"}),"Fork"]})]})]})})},AZ=e=>e.open?c.jsx(TZ,{...e}):null;function NZ(e,t,n=30){const r=e.toLowerCase(),s=t.toLowerCase(),o=r.indexOf(s);if(o===-1)return null;const i=Math.max(0,o-n),a=Math.min(e.length,o+t.length+n);return`${i>0?"…":""}${e.slice(i,a).replace(/\n/g," ")}${a<e.length?"…":""}`}const LZ=e=>{const t=e.startsWith("#")?e.slice(1):e;if(!t)return null;const n=t.match(/^turn-(.+)$/);if(n?.[1])return{kind:"turn",id:n[1]};const r=t.match(/^message-(.+)$/);return r?.[1]?{kind:"message",id:r[1]}:null},RZ=(e,t,n)=>{if(n===0)return{kind:"noop"};if(e.length===0)return{kind:"noop"};const r=t?e.indexOf(t):e.length-1,o=(r>=0?r:e.length-1)+n;if(o>=e.length)return{kind:"resume"};const i=Math.max(0,o),a=e[i];return a?{kind:"turn",turnId:a}:{kind:"noop"}},ol=e=>{if(typeof window>"u")return;const t=e?`#${e}`:"",n=`${window.location.pathname}${window.location.search}${t}`;window.history.replaceState(window.history.state,"",n)},PZ=({sessionId:e,turnIds:t,activeTurnId:n,scrollToTurn:r,scrollToMessage:s,resumeToBottom:o})=>{const i=p.useRef(t),a=p.useRef(n);p.useEffect(()=>{i.current=t},[t]),p.useEffect(()=>{a.current=n},[n]);const l=p.useCallback(async(h,m)=>h?(m?.updateHash!==!1&&ol(`turn-${h}`),r(h,{behavior:m?.behavior})):!1,[r]),d=p.useCallback(async(h,m)=>h?(m?.updateHash!==!1&&ol(`message-${h}`),s(h,{behavior:m?.behavior})):!1,[s]),f=p.useCallback(async(h,m)=>{const g=i.current,x=RZ(g,a.current,h);if(x.kind==="noop")return h===0;if(x.kind==="resume"){if(m?.resumePastEnd===!1){const b=g[g.length-1];return b?l(b,{behavior:"auto"}):!1}return ol(null),o(),!0}return l(x.turnId,{behavior:"auto"})},[o,l]),u=p.useCallback(()=>{ol(null),o()},[o]);return p.useEffect(()=>{if(!e||typeof window>"u")return;const h=()=>{const m=LZ(window.location.hash);if(m){if(m.kind==="turn"){l(m.id,{behavior:"auto",updateHash:!1});return}d(m.id,{behavior:"auto",updateHash:!1})}};return h(),window.addEventListener("hashchange",h),()=>{window.removeEventListener("hashchange",h)}},[e,d,l,t.length]),{scrollToTurnId:l,scrollToMessageId:d,scrollByTurnOffset:f,resumeToLatest:u}},DZ=[],OZ={type:"idle"},Qx="pichamber:chat-force-scroll-bottom",HZ="Quota limit reached. Retrying automatically.",FZ={overflowAnchor:"none",overscrollBehavior:"contain",overscrollBehaviorY:"contain"},l9=e=>e?"relative":"relative z-10",wh=(e,t=!1)=>R(l9(t),"flex flex-col gap-2 bg-background",e?"flex-1 min-h-0":"shrink-0"),BZ=["a[href]","button","input","select","textarea",'[contenteditable="true"]','[role="button"]','[role="combobox"]','[role="dialog"]','[role="listbox"]','[role="menu"]','[role="menuitem"]','[role="option"]','[role="textbox"]',"[data-radix-popper-content-wrapper]"].join(","),VZ=e=>e instanceof HTMLElement,J1=e=>VZ(e)?!!e.closest(BZ):!1,$Z=(e,t)=>typeof document>"u"||!e||e===document.body||e===document.documentElement||J1(e)?!0:!t?.contains(e),zZ=()=>{const{isCommandPaletteOpen:e,isHelpDialogOpen:t,isImagePreviewOpen:n,isSessionSwitcherOpen:r,isSettingsDialogOpen:s}=te.getState();return e||t||n||r||s},UZ=(e,t)=>{if(!t)return e;const n=e.indexOf(t);return n===-1?e:c.jsxs(c.Fragment,{children:[e.slice(0,n),c.jsx("span",{className:"font-medium",children:t}),e.slice(n+t.length)]})},e5=()=>{const e=pe(n=>n.newSessionDraft.selectedProjectId??null),t=at(p.useCallback(n=>VN({selectedProjectId:e,activeProjectId:n.activeProjectId,projects:n.projects}),[e]));return c.jsxs("div",{className:"oc-draft-center flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center",children:[c.jsx("h1",{className:"text-balance text-3xl font-normal tracking-tight text-foreground",children:UZ(t?`What are we working on in ${t}?`:"What are we working on?",t)}),c.jsx(G3,{onInsert:n=>{n.ref.type==="text"?Ye.getState().requestStarterTextInsert(n.insertText):Ye.getState().requestStarterInsert(n.promptName)},className:"oc-draft-starters mt-8 max-w-md"})]})},d9=p.memo(()=>{const e=pe(l=>l.currentSessionId),t=pe(p.useCallback(l=>e?l.sessionAbortFlags?.get(e)??null:null,[e])),{activeModel:n,working:r}=O7(),s=kb(e??""),o=We(l=>l.providers),i=p.useMemo(()=>{if(!n)return null;const l=o.length>0?o.find(d=>d.id===n.providerId):void 0;return d1(l,n.modelId)||null},[n,o]),a=!!(t&&!t.acknowledged);return c.jsx(M3,{isWorking:r.isWorking,statusText:r.statusText,isGenericStatus:r.isGenericStatus,isWaitingForPermission:r.isWaitingForPermission,wasAborted:a||r.wasAborted,abortActive:a||r.abortActive,retryInfo:r.retryInfo,showAssistantStatus:!0,showTodos:!1,modelName:i,providerId:n?.providerId??null,turnStartedAt:s})});d9.displayName="StatusRowContainer";const qZ=160,Sh=28,WZ=12,ji=6,KZ=8,_i=30,Ti=12,t5=18,GZ=80,il=4,ZZ=10,YZ=14,XZ=20,an=54,n5=4,JZ=8,r5=2,QZ=160,eY=(e,t)=>e.map(n=>{const r=t.get(n)??[];return{turnId:n,preview:c9(r,qZ)}}),tY=[1,.6,.35,.15],nY=(e,t,n)=>{const r=n?YZ:ZZ;if(t===null)return r;const s=Math.abs(e-t),o=tY[s]??0;return Math.round(r+(XZ-r)*o)};function rY({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:s,isLoadingOlder:o,onLoadEarlier:i}){const a=te(X=>X.isPromptNavigatorPanelOpen),l=te(X=>X.setPromptNavigatorPanelOpen),d=p.useRef(null),f=p.useRef(null),[u,h]=p.useState(null),[m,g]=p.useState(0),[x,b]=p.useState(!1),[S,y]=p.useState(ji);p.useEffect(()=>{const X=f.current?.parentElement;if(!X||typeof ResizeObserver>"u")return;const ne=()=>{const qe=X.querySelector(".chat-message-column");if(!qe){b(!1),y(ji);return}const st=X.getBoundingClientRect(),je=qe.getBoundingClientRect(),Ke=st.right-je.right-KZ-Sh;if(Ke<=ji){y(ji);const Et=st.right-ji-Sh;b(je.right>Et);return}y(Ke),b(!1)};ne();const he=new ResizeObserver(ne);he.observe(X);const De=X.querySelector(".chat-message-column");return De&&he.observe(De),()=>he.disconnect()},[e.length]);const v=p.useMemo(()=>eY(e,t),[t,e]),C=Math.min(v.length,_i),w=Math.max(0,v.length-C),M=Math.min(m,w),j=M+C,T=M>0,A=j<v.length,_="[No text content]",k="Current prompt",E="Load more prompts",I=p.useMemo(()=>n?v.findIndex(X=>X.turnId===n):-1,[n,v]),N=p.useRef(M);N.current=M;const O=p.useRef(v.length);O.current=v.length;const L=p.useRef(null),D=p.useRef(null),W=p.useRef(0),z=p.useCallback(X=>{g(ne=>{const he=O.current,De=Math.min(he,_i),qe=Math.max(0,he-De),st=Math.min(ne,qe);return X<st?X:X>=st+De?Math.min(qe,X-De+1):st})},[]),J=p.useRef(v[0]?.turnId),B=p.useRef(v.length);p.useLayoutEffect(()=>{const X=J.current,ne=B.current,he=v.length-ne;he>0&&ne>0&&X&&v[0]?.turnId!==X&&(g(De=>De+he),h(De=>De===null?null:De+he)),J.current=v[0]?.turnId,B.current=v.length},[v]),p.useEffect(()=>{if(u!==null)return;const X=I>=0?I:v.length-1;g(()=>{const ne=O.current,he=Math.min(ne,_i),De=Math.max(0,ne-he);return Math.max(0,Math.min(De,X-Math.floor(he/2)))})},[I,u,v.length]);const U=p.useCallback(X=>{const ne=d.current;if(!ne)return null;const he=ne.getBoundingClientRect(),De=Math.floor((X-he.top)/Ti),qe=Math.min(O.current,_i);return qe===0?null:Math.max(0,Math.min(qe-1,De))},[]),P=p.useCallback(()=>{W.current=0,D.current!==null&&(window.clearInterval(D.current),D.current=null)},[]),q=p.useCallback(()=>{const X=W.current;if(X===0){P();return}const ne=O.current,he=Math.min(ne,_i),De=Math.max(0,ne-he),qe=Math.min(N.current,De),st=Math.max(0,Math.min(De,qe+X));if(st===qe){P();return}N.current=st,g(st);const je=L.current;if(je!==null){const Ke=U(je);Ke!==null&&h(Math.min(ne-1,st+Ke))}},[U,P]),F=p.useCallback(X=>{const ne=d.current;if(!ne)return;const he=ne.getBoundingClientRect(),De=X-he.top;let qe=0;if(De<=t5&&T?qe=-1:De>=he.height-t5&&A&&(qe=1),W.current=qe,qe===0){P();return}D.current===null&&(D.current=window.setInterval(q,GZ))},[q,T,A,P]);p.useEffect(()=>()=>{D.current!==null&&window.clearInterval(D.current)},[]);const ee=p.useRef(null),G=p.useCallback(()=>{ee.current!==null&&(window.clearTimeout(ee.current),ee.current=null)},[]),K=p.useCallback(()=>{G(),ee.current=window.setTimeout(()=>{ee.current=null,h(null)},QZ)},[G]);p.useEffect(()=>()=>{ee.current!==null&&window.clearTimeout(ee.current)},[]);const se=p.useCallback(X=>{G(),L.current=X.clientY;const ne=U(X.clientY);ne!==null&&h(Math.min(O.current-1,N.current+ne)),F(X.clientY)},[G,U,F]),ce=p.useCallback(()=>{L.current=null,P(),K()},[K,P]),re=p.useCallback(()=>{l(!1)},[l]),fe=p.useCallback(X=>{if(X===null)return;const ne=v[X];ne&&(r(ne.turnId),P(),h(null),re(),d.current?.blur())},[re,r,v,P]),ge=p.useCallback(X=>{const ne=U(X.clientY);ne!==null&&fe(Math.min(v.length-1,N.current+ne))},[fe,v.length,U]);p.useEffect(()=>{if(!a)return;const X=d.current;!X||X===document.activeElement||(X.focus(),h(ne=>{if(ne!==null)return ne;const he=I>=0?I:v.length-1;return z(he),he}))},[I,z,a,v.length]),p.useEffect(()=>()=>{l(!1)},[l]);const we=p.useCallback(X=>{if(v.length===0)return;const ne=u??(I>=0?I:v.length-1),he=De=>{const qe=Math.max(0,Math.min(v.length-1,De));z(qe),h(qe)};if(X.key==="ArrowUp"||X.key==="ArrowDown"){X.preventDefault(),he(ne+(X.key==="ArrowUp"?-1:1));return}if(X.key==="Home"){X.preventDefault(),he(0);return}if(X.key==="End"){X.preventDefault(),he(v.length-1);return}if(X.key==="Enter"||X.key===" "){X.preventDefault(),fe(ne);return}X.key==="Escape"&&(X.preventDefault(),h(null),re(),d.current?.blur())},[I,re,z,fe,u,v]),Me=p.useCallback(()=>{P(),h(null),re()},[re,P]),He=p.useRef(null),Ae=p.useRef(u);Ae.current=u;const Ge=u!==null,et=p.useRef(0);p.useEffect(()=>{const X=He.current;if(!X)return;const ne=he=>{he.preventDefault(),he.stopPropagation(),et.current+=he.deltaY;const De=Math.trunc(et.current/an);if(De===0)return;et.current-=De*an;const qe=Ae.current;if(qe===null)return;const st=Math.max(0,Math.min(O.current-1,qe+De));st!==qe&&(z(st),h(st))};return X.addEventListener("wheel",ne,{passive:!1}),()=>X.removeEventListener("wheel",ne)},[z,Ge]);const Xe=u!==null?v[u]:void 0,oe=Math.min(v.length,JZ),Q=oe*an,ue=v.length*an-Q,be=X=>Math.max(0,Math.min(ue,X)),Ie=p.useRef(null);let Fe=0;if(u===null)Ie.current=null;else if(Ie.current===null)Fe=be(u*an-(Q-an)/2),Ie.current=Fe;else{let X=Ie.current;const ne=(u-r5)*an,he=(u+1+r5)*an-Q;X>ne?X=ne:X<he&&(X=he),Fe=be(X),Ie.current=Fe}const ht=Math.floor(Fe/an),ye=Math.max(0,ht-il),Ze=Math.min(v.length,ht+oe+il),Be=Fe>0,ie=Fe<ue,ke=Be||ie?`linear-gradient(to bottom, ${Be?"transparent, black 10%":"black"}, ${ie?"black 90%, transparent":"black"})`:void 0,ve=Math.max(0,M-il),xe=Math.min(v.length,j+il),_e=v.slice(ve,xe),le=T||A?`linear-gradient(to bottom, ${T?"transparent, black 14%":"black"}, ${A?"black 86%, transparent":"black"})`:void 0;return v.length===0?null:c.jsx("nav",{ref:f,"aria-label":"Prompt navigation",className:"pointer-events-none absolute top-1/2 z-20 -translate-y-1/2",style:{right:`${S}px`},children:c.jsxs("div",{className:"pointer-events-auto flex flex-col items-end",children:[s?c.jsx("button",{type:"button",tabIndex:-1,className:R("-mr-px mb-1.5 flex size-5 shrink-0 items-center justify-center rounded-full","text-[var(--surface-mutedForeground)] transition-colors","hover:bg-[var(--interactive-hover)]/60 hover:text-[var(--surface-foreground)]",o?"cursor-wait opacity-70":void 0),"aria-label":E,title:E,disabled:o,onClick:X=>{X.stopPropagation(),o||i()},children:o?c.jsx($,{name:"loader-4",className:"size-3.5 animate-spin"}):c.jsx($,{name:"arrow-up-s",className:"size-3.5"})}):null,c.jsxs("div",{ref:d,role:"listbox",tabIndex:-1,"aria-activedescendant":Xe?`prompt-rail-tick-${Xe.turnId}`:void 0,className:"relative cursor-pointer outline-none",style:{width:`${x?WZ:Sh}px`,height:`${C*Ti}px`},onMouseMove:se,onMouseLeave:ce,onClick:ge,onKeyDown:we,onBlur:Me,children:[c.jsx("div",{className:"absolute inset-0 overflow-hidden",style:le?{maskImage:le,WebkitMaskImage:le}:void 0,children:c.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-300 ease-out",style:{transform:`translateY(-${M*Ti}px)`},children:_e.map((X,ne)=>{const he=ve+ne,De=X.turnId===n,qe=u===he,st=nY(he,u,De);return c.jsx("div",{id:`prompt-rail-tick-${X.turnId}`,role:"option","aria-selected":qe,"aria-current":De?"true":void 0,"aria-label":X.preview.trim()||_,className:"pointer-events-none absolute right-1 flex items-center justify-end",style:{top:`${he*Ti}px`,height:`${Ti}px`},children:c.jsx("span",{"aria-hidden":"true",className:R("block h-0.5 rounded-full transition-all duration-200 ease-out",De?"bg-[var(--surface-foreground)]":qe?"bg-[var(--surface-foreground)]/80":"bg-[var(--surface-foreground)]/30"),style:{width:`${st}px`}})},X.turnId)})},v[0]?.turnId)}),Xe&&u!==null?c.jsx("div",{ref:He,className:R("pointer-events-auto absolute right-full top-1/2 z-30 mr-3 -translate-y-1/2","w-[min(20rem,calc(100vw-6rem))] overflow-hidden rounded-xl","border border-[var(--interactive-border)]/60 bg-[var(--surface-elevated)] py-1 shadow-md"),onMouseEnter:G,onMouseLeave:K,onMouseMove:X=>X.stopPropagation(),onClick:X=>X.stopPropagation(),children:c.jsx("div",{className:"relative overflow-hidden",style:{height:`${oe*an}px`,maskImage:ke,WebkitMaskImage:ke},children:c.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-200 ease-out",style:{height:`${v.length*an}px`,transform:`translateY(-${Fe}px)`},children:v.slice(ye,Ze).map((X,ne)=>{const he=ye+ne,De=X.turnId===n,qe=u===he;return c.jsx("div",{role:"option","aria-selected":qe,"aria-current":De?"true":void 0,title:De?k:void 0,className:"absolute inset-x-0 cursor-pointer px-1.5",style:{top:`${he*an+n5}px`,height:`${an-n5*2}px`},onMouseMove:()=>{G(),Ae.current!==he&&(z(he),h(he))},onClick:()=>fe(he),children:c.jsx("div",{className:R("flex h-full items-center rounded-lg border px-2 transition-colors",De?"border-transparent bg-[var(--interactive-selection)]":qe?"border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]":"border-[var(--interactive-border)]/40"),children:c.jsx("span",{className:R("min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] typography-meta",De?"text-[var(--interactive-selectionForeground)]":"text-[var(--surface-mutedForeground)]"),children:X.preview.trim()||_})})},X.turnId)})})})}):null]})]})})}const u9=p.memo(({currentSessionId:e,currentSessionKey:t,isDesktopExpandedInput:n,isMobile:r,directory:s,scrollRef:o,messageListRef:i,pendingRevealWork:a,renderedMessages:l,isLoadingOlder:d,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:h,streamingMessageId:m,activeStreamingPhase:g,retryOverlay:x,compactionOverlay:b,handleMessageContentChange:S,getAnimationHandlers:y,handleHistoryScroll:v,scrollToBottom:C,isProgrammaticFollowActive:w,showLoadOlderButton:M,onLoadOlder:j,turnIds:T,activeTurnId:A,onSelectTurn:_,showPromptNavigator:k,canLoadEarlierPrompts:E,isLoadingOlderPrompts:I,onLoadEarlierPrompts:N})=>{const O=p.useRef(new Map),L=p.useRef(new WeakMap),D=p.useRef(new Map),W=p.useRef(e);W.current!==e&&(W.current=e,D.current.clear());const z=p.useMemo(()=>{const P=new Map;for(let F=0;F<l.length;F+=1){const ee=l[F];if(ee.info.role!=="user")continue;if($4(ee)){const K=B$(l,F)??"",se=D.current.get(ee.info.id);if(se&&se.command===K)P.set(ee.info.id,se.parts);else{const ce=[{type:"text",text:K?`$ ${K}`:"/shell"}];D.current.set(ee.info.id,{command:K,parts:ce}),P.set(ee.info.id,ce)}continue}if(mW(ee.parts))continue;let G=L.current.get(ee.parts);G||(G=K1(ee.parts),L.current.set(ee.parts,G)),G.length!==0&&P.set(ee.info.id,G)}const q=O.current;if(q.size===P.size){let F=!0;for(const[ee,G]of P)if(q.get(ee)!==G){F=!1;break}if(F)return q}return O.current=P,P},[l]),J=p.useMemo(()=>T.filter(P=>z.has(P)),[z,T]),B=p.useMemo(()=>{if(!A||z.has(A))return A;const P=T.indexOf(A);for(let q=P-1;q>=0;q-=1){const F=T[q];if(z.has(F))return F}return null},[A,z,T]),U=p.useCallback(P=>{P.defaultPrevented||J1(P.target)||typeof window<"u"&&window.getSelection()?.type==="Range"||o.current?.focus({preventScroll:!0})},[o]);return c.jsx("div",{className:R("relative min-h-0",n?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":n,children:c.jsxs("div",{className:"absolute inset-0",children:[c.jsx(fu,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:o,style:FZ,observeMutations:!1,hideTopShadow:!1,tabIndex:0,onClick:U,onScroll:v,"data-scroll-shadow":"true","data-scrollbar":"chat",children:c.jsxs("div",{className:"relative z-0 min-h-full",children:[M&&c.jsx("div",{className:"flex justify-center pt-3 pb-1",children:c.jsxs(Se,{variant:"secondary",size:"sm",onClick:j,disabled:d,children:[d&&c.jsx($,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),c.jsx(UG,{ref:i,sessionKey:e,disableStaging:a,messages:l,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:h,activeStreamingMessageId:m,activeStreamingPhase:g,retryOverlay:x,compactionOverlay:b,onMessageContentChange:S,getAnimationHandlers:y,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:s},t),T.length===0&&f?c.jsx("div",{className:"mb-3",children:c.jsx(d9,{})}):T.length===0&&u?c.jsx("div",{className:"chat-message-column mb-3",children:c.jsx("span",{className:"typography-markdown leading-5 text-muted-foreground",role:"status","data-turn-reconnecting":"true",children:"Reconnecting · last seen working"})}):null,c.jsx("div",{className:"flex-shrink-0",style:{height:r?"calc(40px + var(--oc-safe-area-bottom, 0px))":"calc(10vh + var(--oc-safe-area-bottom, 0px))"},"aria-hidden":"true"})]})}),c.jsx(Aw,{containerRef:o,suppressVisibility:w,userIntentOnly:!0,observeMutations:!1}),k&&J.length>=2?c.jsx(rY,{turnIds:J,previewsByTurnId:z,activeTurnId:B,onSelectTurn:_,canLoadEarlier:E,isLoadingOlder:I,onLoadEarlier:N}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.currentSessionKey===t.currentSessionKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.sessionAwaitingRecovery===t.sessionAwaitingRecovery&&e.awaitingPromptEcho===t.awaitingPromptEcho&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.compactionOverlay===t.compactionOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.scrollToBottom===t.scrollToBottom&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&e.onLoadOlder===t.onLoadOlder&&e.turnIds===t.turnIds&&e.activeTurnId===t.activeTurnId&&e.onSelectTurn===t.onSelectTurn&&e.showPromptNavigator===t.showPromptNavigator&&e.canLoadEarlierPrompts===t.canLoadEarlierPrompts&&e.isLoadingOlderPrompts===t.isLoadingOlderPrompts&&e.onLoadEarlierPrompts===t.onLoadEarlierPrompts);u9.displayName="ChatViewport";const sY={isWorking:!1,isAwaitingRecovery:!1},_J=({active:e=!0,autoOpenDraft:t=!0})=>{const n=pe(je=>je.currentSessionId),r=pe(je=>je.currentSessionDirectory),s=pe(je=>je.openNewSessionDraft),o=pe(je=>je.newSessionDraft),i=pe(je=>je.sendingNewSessionDraftId),a=uw(o,n,i),l=x3(),d=LE(),f=r??d,u=n?JSON.stringify([Y(),f,n]):null,h=p.useCallback(je=>l.ensureSessionRenderable(je),[l]),m=p.useCallback(async()=>{},[]),g=te(je=>je.isExpandedInput),x=te(je=>je.isTimelineDialogOpen),b=te(je=>je.setTimelineDialogOpen),S=iw(),y=D3(),v=DE(n??""),w=S==="ready"&&!y?v:null,M=w?"streaming":null,j=FE(n??""),T=lw(n??""),A=Qd(n??""),_=b4(n),k=n?A:DZ,E=aw(n??""),I=RE(n??""),[N]=p.useState(KT);p.useEffect(()=>{if(!(!e||!u||!T||k.length===0))return N.schedule(u,k.length)},[e,u,N,T,k.length]);const O=Xd(n??"")??OZ,L=Jd(n??""),D=p.useMemo(()=>{if(!n)return sY;const je=O.type??"idle",Ke=k[k.length-1]?.info,Et=typeof Ke?.finish=="string"?Ke.finish:void 0,fn=!!(Ke&&Ke.role==="assistant"&&typeof Ke.time?.completed!="number"&&Et!=="stop"&&Et!=="error");return oN({connection:S,transportUncertain:y,authoritativeWorking:je==="busy"&&!L||je==="retry",hasPendingAssistant:fn,hasRetainedStream:!!v})},[S,n,v,L,k,O.type,y]),W=D.isWorking,z=D.isAwaitingRecovery,J=AE(n??""),B=W||J,U=OE(n??""),P=p.useMemo(()=>{if(!n||O.type!=="retry")return null;const je=typeof O.message=="string"?(O.message??"").trim():"";return{sessionId:n,message:je||HZ,confirmedAt:O.confirmedAt}},[n,O]),q=_E(n??""),F=p.useMemo(()=>n&&q?{sessionId:n,compaction:q}:null,[q,n]),[ee,G]=p.useState(0),K=p.useRef(null);p.useEffect(()=>{if(!P||typeof P.confirmedAt=="number"){K.current=null,G(0);return}K.current!==P.sessionId&&(K.current=P.sessionId,G(Date.now()))},[P]);const se=p.useMemo(()=>P?{...P,fallbackTimestamp:ee}:null,[P,ee]),ce=p.useMemo(()=>n?{limit:k.length,complete:I.complete||!I.cursor,loading:I.status==="loading"}:null,[n,I.complete,I.cursor,I.status,k.length]),{isMobile:re}=On(),fe=gu(),ge=!!o?.open,we=re&&g,Me=re||fe==="mini-chat",He=p.useRef(null);p.useEffect(()=>{Jb().sessionId||t&&!n&&!ge&&s({automatic:!0})},[t,n,ge,s]);const Ae=p.useRef(()=>{}),Ge=p.useCallback(je=>{Ae.current(je)},[]),{scrollRef:et,notifyContentChange:Xe,getAnimationHandlers:oe,goToBottom:Q,scrollToBottomOnSend:ue,releaseAutoFollow:be,restoreSnapshot:Ie,isPinned:Fe,isFollowingProgrammatically:ht,showScrollButton:ye}=dZ({currentSessionId:n,currentSessionKey:u,sessionMessageCount:j,latestTailEntryId:E.at(-1)?.id??null,sessionIsWorking:B,isMobile:re,onActiveTurnChange:Ge}),Be=_Z({sessionId:n,sessionKey:u,messages:k,historyMeta:ce,scrollRef:et,messageListRef:He,loadMoreMessages:m,goToBottom:Q,releaseAutoFollow:be,isPinned:Fe,showScrollButton:ye}),ie=p.useCallback(()=>{Q("instant")},[Q]),ke=un()&&Be.historySignals.canLoadEarlier,ve=Be.loadEarlier,xe=p.useCallback(()=>{ve({userInitiated:!0})},[ve]);p.useEffect(()=>{Ae.current=Be.handleActiveTurnChange},[Be.handleActiveTurnChange]);const _e=PZ({sessionId:n,turnIds:Be.turnIds,activeTurnId:Be.activeTurnId,scrollToTurn:Be.scrollToTurn,scrollToMessage:Be.scrollToMessage,resumeToBottom:Be.resumeToBottomInstant}),le=p.useCallback(je=>{_e.scrollToTurnId(je,{behavior:"smooth"})},[_e]),X=Be.historySignals.canLoadEarlier,ne=!re&&!we&&Be.turnIds.length>=2;p.useEffect(()=>{ne||te.getState().setPromptNavigatorPanelOpen(!1)},[ne]),p.useEffect(()=>{if(typeof window>"u"||!n)return;const je=Ke=>{const Et=Ke;Et.detail?.sessionId&&Et.detail.sessionId!==n||Q("instant")};return window.addEventListener(Qx,je),()=>{window.removeEventListener(Qx,je)}},[n,Q]),p.useEffect(()=>{if(typeof window>"u"||!n||we)return;const je=Ke=>{if(Ke.defaultPrevented||Ke.isComposing||Ke.key!=="ArrowUp"&&Ke.key!=="ArrowDown"||Ke.altKey||Ke.ctrlKey||Ke.metaKey||Ke.shiftKey)return;const{activeMainTab:Et}=te.getState();if(Et!=="chat"||zZ())return;const fn=et.current;if($Z(document.activeElement,fn)||J1(Ke.target))return;Ke.preventDefault();const Sn=Ke.key==="ArrowUp"?-1:1;_e.scrollByTurnOffset(Sn,{resumePastEnd:!1})};return window.addEventListener("keydown",je),()=>{window.removeEventListener("keydown",je)}},[n,we,_e,et]),p.useLayoutEffect(()=>{const je=et.current;if(!je)return;const Ke=()=>{je.style.setProperty("--chat-scroll-height",`${je.clientHeight}px`)};Ke();let Et=0;const fn=()=>{Et||(Et=requestAnimationFrame(()=>{Et=0,Ke()}))};if(typeof ResizeObserver>"u")return window.addEventListener("resize",fn),()=>{Et&&cancelAnimationFrame(Et),window.removeEventListener("resize",fn)};const Sn=new ResizeObserver(fn);return Sn.observe(je),()=>{Et&&cancelAnimationFrame(Et),Sn.disconnect()}},[n,we,et]);const he=p.useRef(null),qe=!!n&&(!!n&&!T||I.status==="loading"),st=p.useCallback(()=>{!e||!n||l.ensureSessionRenderable(n)},[e,n,l]);return p.useEffect(()=>{if(!e||!n||he.current===u)return;const je=typeof window<"u"&&window.location.hash.length>0;if(he.current=u,je){be();return}const Ke=()=>{Ie()};typeof window>"u"?Ke():window.requestAnimationFrame(Ke)},[e,n,u,be,Ie]),p.useEffect(()=>{!e||!n||T||h(n)},[e,n,h,T]),!n&&!ge?t?c.jsx("div",{className:"flex h-full flex-col bg-background"}):c.jsx("div",{className:"flex flex-col h-full bg-background",children:c.jsx(A$,{isNewSession:!0})}):!n&&ge?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[Me&&!we?c.jsx(e5,{}):null,c.jsx("div",{className:R("relative z-10 flex min-h-0",we?"flex-1 bg-background":Me?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:c.jsx(ki,{scrollToBottom:ue})})]}):n?qe?I.status==="error"?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center px-6",children:c.jsxs("div",{className:"max-w-sm text-center",children:[c.jsx("div",{className:"mx-auto mb-3 flex size-9 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--status-error)_10%,transparent)] text-[var(--status-error)]",children:c.jsx($,{name:"error-warning",className:"size-4"})}),c.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:I.errorCode==="SESSION_IN_USE"?"Session is open elsewhere":"Session could not be loaded"}),c.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:I.errorCode==="SESSION_IN_USE"?"Another PiChamber instance is using this session. Close it there, then try again.":"Check the connection and try loading this session again."}),c.jsx(Se,{variant:"outline",size:"sm",className:"mt-4",onClick:st,children:"Try again"})]})}),c.jsx("div",{className:wh(!1),children:c.jsx(ki,{scrollToBottom:ue})})]}):c.jsxs("div",{"data-composer-bound":!0,className:"relative flex flex-col h-full bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx("div",{className:R("relative min-h-0 flex items-center justify-center",we?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":we,children:c.jsxs("div",{className:"flex flex-col items-center gap-3",children:[c.jsx(Um,{width:120,height:120,isAnimated:!0}),a?c.jsx("p",{role:"status",className:"typography-meta animate-pulse text-muted-foreground",children:"Creating session…"}):null]})}),c.jsx("div",{className:wh(we),children:c.jsx(ki,{scrollToBottom:ue})})]}):k.length===0&&E.length===0&&!W&&!z?c.jsxs("div",{"data-composer-bound":!0,className:"relative flex h-full flex-col bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[Me&&!we?c.jsx(e5,{}):null,c.jsx("div",{className:R(l9(_),"flex min-h-0",we?"flex-1 bg-background":Me?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:c.jsxs("div",{className:"flex w-full min-w-0 flex-col gap-2",children:[c.jsx(wv,{sessionId:n}),c.jsx(Sv,{sessionId:n}),c.jsx(jv,{sessionId:n,children:c.jsx(ki,{scrollToBottom:ue})})]})}),c.jsx(Tv,{sessionId:n},n)]}):c.jsxs("div",{"data-composer-bound":!0,className:"relative flex min-w-0 flex-1 flex-col h-full bg-background animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[c.jsx(u9,{currentSessionId:n,currentSessionKey:u??n,isDesktopExpandedInput:we,isMobile:re,directory:f,scrollRef:et,messageListRef:He,pendingRevealWork:Be.pendingRevealWork,renderedMessages:Be.renderedMessages,isLoadingOlder:Be.isLoadingOlder,sessionIsWorking:W,sessionAwaitingRecovery:z,awaitingPromptEcho:U,streamingMessageId:w,activeStreamingPhase:M,retryOverlay:se,compactionOverlay:F,handleMessageContentChange:Xe,getAnimationHandlers:oe,handleHistoryScroll:Be.handleHistoryScroll,scrollToBottom:ie,isProgrammaticFollowActive:ht,showLoadOlderButton:ke,onLoadOlder:xe,turnIds:Be.turnIds,activeTurnId:Be.activeTurnId,onSelectTurn:le,showPromptNavigator:ne,canLoadEarlierPrompts:X,isLoadingOlderPrompts:Be.isLoadingOlder,onLoadEarlierPrompts:xe}),c.jsxs("div",{className:wh(we,_),children:[!we&&k.length>0&&c.jsx(WG,{visible:Be.showScrollToBottom,onClick:_e.resumeToLatest}),c.jsx($V,{sessionId:n}),c.jsx(wv,{sessionId:n}),c.jsx(Sv,{sessionId:n}),c.jsx(jv,{sessionId:n,children:c.jsx(ki,{scrollToBottom:ue})})]}),c.jsx(Tv,{sessionId:n},n),c.jsx(AZ,{open:x,onOpenChange:b,onScrollToMessage:Be.scrollToMessage,onScrollByTurnOffset:_e.scrollByTurnOffset,onResumeToLatest:ie,canLoadEarlier:Be.historySignals.canLoadEarlier,isLoadingEarlier:Be.isLoadingOlder,onLoadEarlier:xe,onRevert:async je=>{if(!n)return;const Ke=je.includes(":")?je.split(":")[0]??je:je;await pe.getState().revertToMessage(n,Ke)},onFork:async je=>{if(!n)return;const Ke=je.includes(":")?je.split(":")[0]??je:je;await pe.getState().forkFromMessage(n,Ke)}})]}):null},oY=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(100,Math.round(e))),iY=e=>e>=90?"critical":e>=75?"warn":"safe",TJ=({percentage:e,size:t=18,stroke:n=3,className:r})=>{const s=oY(e),o=iY(e),i=o==="critical"?"var(--status-error)":o==="warn"?"var(--status-warning)":"var(--status-success)",a=(t-n)/2,l=2*Math.PI*a;return c.jsxs("svg",{viewBox:`0 0 ${t} ${t}`,className:r??"size-[18px] -rotate-90",role:"progressbar","aria-valuenow":Math.round(s),"aria-valuemin":0,"aria-valuemax":100,children:[c.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:"var(--interactive-border)",strokeWidth:n}),c.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:i,strokeWidth:n,strokeLinecap:"round",strokeDasharray:l,strokeDashoffset:l*(1-s/100),className:"transition-[stroke-dashoffset,stroke] duration-300"})]})},aY=()=>{const e=te(n=>n.uiFont),t=te(n=>n.monoFont);return{uiFont:e,monoFont:t}},AJ=p.memo(function({visible:t}){const[n,r]=p.useState(!1);if(H.useEffect(()=>{if(!t)return;let o=!1;dr("desktop_get_current_window_state").then(a=>{o||r(!!a?.maximized)}).catch(()=>{});const i=a=>{const l=a.detail;r(!!l?.maximized)};return window.addEventListener("pichamber:window-maximized-changed",i),()=>{o=!0,window.removeEventListener("pichamber:window-maximized-changed",i)}},[t]),!t)return null;const s="app-region-no-drag inline-flex h-12 w-11 items-center justify-center text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary";return c.jsxs("div",{className:"app-region-no-drag ml-1 flex h-12 shrink-0 items-center","aria-label":"Window controls",children:[c.jsx("button",{type:"button",className:s,onClick:()=>{dr("desktop_minimize_current_window")},title:"Minimize window","aria-label":"Minimize window",children:c.jsx($,{name:"subtract",className:"h-4 w-4"})}),c.jsx("button",{type:"button",className:s,onClick:()=>{dr("desktop_toggle_current_window_maximized").then(o=>r(!!o?.maximized)).catch(()=>{})},title:n?"Restore window":"Maximize window","aria-label":n?"Restore window":"Maximize window",children:c.jsx($,{name:n?"fullscreen-exit":"checkbox-blank",className:"h-3.5 w-3.5"})}),c.jsx("button",{type:"button",className:R(s,"hover:bg-status-error hover:text-status-error-foreground"),onClick:()=>{dr("desktop_close_current_window")},title:"Close window","aria-label":"Close window",children:c.jsx($,{name:"close",className:"h-4 w-4"})})]})}),s5=new Set,Ch=new Map,cY=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace("%40","@").replace("%2F","/")}/files/${e.filePrefix}-latin-${t}-normal.woff2`,lY=(e,t)=>{const n=`${e.family}:${t}`;if(s5.has(n))return Promise.resolve();const r=Ch.get(n);if(r)return r;if(typeof document>"u"||typeof FontFace>"u"||!document.fonts)return Promise.resolve();const s=new FontFace(e.family,`url(${cY(e,t)}) format('woff2')`,{style:"normal",weight:String(t),display:"swap"});document.fonts.add(s);const o=s.load().then(()=>{s5.add(n)}).catch(i=>{document.fonts.delete(s),console.warn(`Failed to load font: ${e.family} ${t}`,i)}).finally(()=>{Ch.delete(n)});return Ch.set(n,o),o},f9=e=>e?Promise.all(e.weights.map(t=>lY(e,t))).then(()=>{}):Promise.resolve(),dY=e=>f9(Eh[e]?.source),uY=e=>f9(jh[e]?.source);function NJ(){const{uiFont:e,monoFont:t}=aY();p.useEffect(()=>{if(typeof document>"u")return;const n=document.documentElement,r=Eh[e]?.stack??Eh[eC].stack,s=jh[t]?.stack??jh[tC].stack;dY(e),uY(t),n.style.setProperty("--font-sans",r),n.style.setProperty("--font-heading",r),n.style.setProperty("--font-family-sans",r),n.style.setProperty("--font-mono",s),n.style.setProperty("--font-family-mono",s),n.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=r)},[e,t])}export{pX as $,Pa as A,Se as B,Zm as C,AX as D,hX as E,uN as F,nu as G,QY as H,$ as I,xE as J,Hm as K,VX as L,aY as M,dY as N,We as O,Um as P,D3 as Q,zX as R,E_ as S,VY as T,$Y as U,np as V,eN as W,uE as X,NJ as Y,q2 as Z,UY as _,at as a,cu as a$,kX as a0,wX as a1,SX as a2,CX as a3,LT as a4,LX as a5,mX as a6,gX as a7,nX as a8,tu as a9,Gj as aA,hu as aB,ln as aC,bX as aD,BY as aE,FY as aF,Jb as aG,ze as aH,DY as aI,IX as aJ,EX as aK,qA as aL,YA as aM,ZA as aN,Xn as aO,Oa as aP,yt as aQ,vt as aR,xt as aS,g2 as aT,bT as aU,wT as aV,ST as aW,CT as aX,_J as aY,YX as aZ,XX as a_,YY as aa,uX as ab,XY as ac,tX as ad,eX as ae,HY as af,xa as ag,gr as ah,GI as ai,Tm as aj,oj as ak,cj as al,Yb as am,OY as an,GY as ao,Lm as ap,Rr as aq,mw as ar,On as as,Fo as at,Ma as au,ru as av,su as aw,ou as ax,iu as ay,Vm as az,oM as b,l_ as b$,lu as b0,du as b1,EP as b2,l1 as b3,Vo as b4,ZL as b5,IP as b6,ub as b7,EE as b8,Qd as b9,Yw as bA,PY as bB,EB as bC,BD as bD,Qt as bE,Ln as bF,Vw as bG,LY as bH,Fa as bI,VD as bJ,c_ as bK,Jn as bL,O_ as bM,JY as bN,kY as bO,x3 as bP,MY as bQ,AJ as bR,Pr as bS,Rl as bT,O6 as bU,Dr as bV,AY as bW,EY as bX,Ye as bY,JX as bZ,d_ as b_,At as ba,TJ as bb,vX as bc,IA as bd,yX as be,kA as bf,xX as bg,bt as bh,CI as bi,$h as bj,gN as bk,Cm as bl,NY as bm,ow as bn,TY as bo,$m as bp,n_ as bq,s_ as br,fB as bs,k1 as bt,ho as bu,HD as bv,pu as bw,zh as bx,wV as by,eJ as bz,ya as c,DX as c$,m_ as c0,G2 as c1,Y2 as c2,Z2 as c3,X2 as c4,J2 as c5,WX as c6,KX as c7,eh as c8,GX as c9,rV as cA,kb as cB,jY as cC,e7 as cD,MX as cE,gw as cF,hr as cG,LD as cH,E1 as cI,cw as cJ,Ad as cK,jd as cL,Rs as cM,Pf as cN,HV as cO,TX as cP,_X as cQ,fN as cR,dN as cS,nO as cT,O3 as cU,rO as cV,sO as cW,oO as cX,iO as cY,qX as cZ,OX as c_,Ml as ca,Iw as cb,cX as cc,K_ as cd,v2 as ce,x2 as cf,If as cg,lX as ch,dX as ci,jJ as cj,rT as ck,T_ as cl,__ as cm,D_ as cn,aX as co,a1 as cp,dm as cq,Hd as cr,Ft as cs,a6 as ct,G5 as cu,ZX as cv,CO as cw,kO as cx,gL as cy,YW as cz,uM as d,rX as d$,PX as d0,HX as d1,eO as d2,oY as d3,iY as d4,Pm as d5,Io as d6,vN as d7,LL as d8,dJ as d9,vJ as dA,lJ as dB,iJ as dC,aJ as dD,cJ as dE,rJ as dF,hq as dG,fJ as dH,hJ as dI,pJ as dJ,uJ as dK,UX as dL,j3 as dM,i_ as dN,a_ as dO,Aw as dP,RD as dQ,PD as dR,DD as dS,$D as dT,zD as dU,mN as dV,xJ as dW,oJ as dX,gJ as dY,mJ as dZ,Zn as d_,qz as da,zv as db,fX as dc,lT as dd,uT as de,WD as df,Wt as dg,jX as dh,mu as di,gz as dj,Qf as dk,Ba as dl,KU as dm,V1 as dn,EJ as dp,OW as dq,XU as dr,wJ as ds,fu as dt,a3 as du,i3 as dv,oR as dw,mz as dx,FX as dy,yJ as dz,xT as e,sX as e0,oX as e1,iX as e2,bJ as e3,tJ as e4,nJ as e5,SJ as e6,pq as e7,ix as e8,Sq as e9,CJ as ea,kJ as eb,MJ as ec,IJ as ed,xq as ee,Xz as ef,w7 as eg,sJ as eh,e9 as ei,$X as ej,IY as ek,RY as el,ZY as em,NX as en,RX as eo,BX as ep,zY as f,Ue as g,pe as h,qY as i,pM as j,WY as k,Or as l,QX as m,SV as n,ka as o,_Y as p,bV as q,Fm as r,v_ as s,Ce as t,$d as u,Nw as v,KY as w,Ho as x,Qn as y,Da as z};