@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
@@ -1,212 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-heic2any-pq-UTQQR.js","assets/vendor-react-DASdDPIk.js","assets/document-attachments-BslE4Ns7.js","assets/vendor-fflate-C7GOKjkv.js","assets/vendor-capacitor-status-bar-BsrUwiaA.js","assets/vendor-boot-EC6IyLt1.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-capacitor-app-BaupizkW.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-keyboard-9BVxykO7.js","assets/permissionStore-B9Hkrqny.js","assets/vendor-zustand-CUi8eEds.js","assets/MarkdownRendererImpl-SXAK4uOu.js","assets/vendor-morphdom-B7dS_VPB.js","assets/vendor-beautiful-mermaid-DApbjBp2.js","assets/vendor-elkjs-D27273Ms.js","assets/vendor-entities-C3BA0AJP.js","assets/index-D4n3TVp2.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BwoW_-vk.css","assets/markdownCore-C2YQ3Z0q.js","assets/vendor-marked-CX41MkDF.js","assets/vendor-dompurify-r8glNMJW.js","assets/vendor-remend-BWYYytN3.js","assets/registerCustomTheme-DmolaWWZ.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.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-BJsGPh58.js","assets/runtimeSurface-k1Eit61v.js","assets/vendor-codemirror-lang-javascript-Dw4kFO4e.js","assets/vendor-lezer-javascript-ctwLWf4v.js","assets/vendor-lezer-lr-B8TQctNw.js","assets/vendor-codemirror-autocomplete-CGpAsPWp.js","assets/vendor-codemirror-lang-json-B-b1vAv-.js","assets/vendor-lezer-json-BP_UAzLL.js","assets/vendor-codemirror-lang-css-RM2HqXZ0.js","assets/vendor-lezer-css-DUkkbMp7.js","assets/vendor-codemirror-lang-html-CHSHUpwq.js","assets/vendor-lezer-html-B3h0MOrG.js","assets/vendor-codemirror-lang-markdown-BTht2ATe.js","assets/vendor-lezer-markdown-aGLZf_3h.js","assets/vendor-codemirror-lang-python-CH6_em9L.js","assets/vendor-lezer-python-EJ4Im4y2.js","assets/GitHubLinkPicker-B0O3Vapu.js","assets/GitHubListPrimitives-DvQDU--z.js","assets/GitHubDetailScaffold-C1UHuETI.js","assets/githubLink-CbGYxsIq.js","assets/ToolOutputDialog-B3RRLhR3.js","assets/JsonTreeView-BfErTllU.js","assets/web-components-DzQ9ybbb.js","assets/computeVirtualFileMetrics-Bjhk2CQS.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.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-DP6HbEeC.js","assets/renderFileWithHighlighter-DUGluXlw.js","assets/PatchDiff-CHr79sJ6.js","assets/VirtualizedFileDiff-B8lhZGLu.js","assets/renderDiffWithHighlighter-BhMEWmHn.js","assets/vendor-diff-C3JhlQdm.js","assets/appThemeRegistry-gegrE2dq.js","assets/ToolPartDiffPreview-D9m_vrht.js"])))=>i.map(i=>d[i]);
2
- import{ay as bo,z as bt,w as Qn,aD as t7,aE as n7,aF as yc,aG as K5,aH as Y5,aA as Ne,aI as lt,d as $t,p as le,u as tt,v as Tt,aJ as yp,az as X5,a5 as Er,h as od,aK as r7,t as jr,a as J,aL as vp,aM as id,f as ne,aN as Lo,$ as xp,aO as bp,aP as ct,m as sn,aQ as ad,aR as Gf,r as br,aS as s7,aT as o7,aU as i7,aV as a7,aC as l7,aW as c7,A as ld,aX as P1,aY as d7,aZ as u7,a_ as f7,T as h7,a$ as p7,e as P,ao as m7,b0 as wr,ap as g7,ar as cn,an as wp,b1 as vc,b2 as Vl,b3 as hu,b4 as y7,b5 as D1,as as Rn,b6 as v7,s as Bl,b7 as pu,b8 as O1,b9 as x7,ba as b7,aq as w7,bb as S7,bc as C7,bd as k7,be as M7,k as I7,bf as H1,bg as _7,bh as F1,bi as E7,i as Jn,M as Sp,b as j7,bj as T7,bk as A7,bl as L7,bm as xc,bn as N7,bo as V1,n as Qr,bp as J5,a1 as Q5,G as Ri,H as R7,au as kt,L as P7,bq as D7,O as O7,br as H7,bs as B1,bt as F7,bu as V7,bv as B7,bw as ev,bx as $7,by as tv,bz as z7,bA as U7,bB as q7,bC as Z7,bD as mu,bE as gu,bF as Ja,bG as W7,bH as Kf,bI as Qa,bJ as Js,E as G7,K as K7,D as Y7,P as $1,x as X7,bK as J7,y as Q7,bL as e9,bM as nv,N as t9,a2 as us,bN as n9,bO as r9,bP as s9,bQ as va,bR as $l,a4 as o9,bS as Yf,ae as Xf,bT as i9,af as a9}from"./index-D4n3TVp2.js";import{k as l,b2 as l9,b5 as c9,b8 as d9,b6 as u9,b7 as f9,b3 as h9,b4 as p9,bk as m9,bl as rv,bm as g9,bn as y9,be as sv,bf as ov,bg as iv,bh as v9,bi as x9,bo as b9,bp as w9,bq as S9,br as C9,bs as k9,bt as Xo,bu as M9,bv as I9,bw as _9,bx as E9,by as j9,bz as T9,bA as A9,aL as na,bB as L9,bC as N9,bD as R9,bE as P9,bF as D9,bG as O9,bH as H9,bI as F9,M as hn,bJ as V9,bK as B9,bL as $9,bM as z9,bN as U9,bO as q9,bP as Z9,bQ as W9,bR as G9,bS as K9,bT as Y9,bU as X9,aO as Cp,aP as ra,aY as av,aZ as lv,aR as kp,aS as Mp,aT as Ip,a$ as cv,aW as _p,aX as Ep,aQ as J9,bV as dv,bW as uv,bX as fv,bY as hv,bZ as pv,b_ as vs,a_ as Q9,b$ as eS,c0 as tS,ba as nS,ah as rS,c1 as sS,c2 as oS,z as De,S as mv,L as gv,am as iS,an as aS,K as lS,ad as cS,c3 as dS,c4 as uS,O as fS,Q as z1,c5 as hS,c6 as pS,c7 as yv,c8 as U1,b1 as mS,aM as el,bb as vv,bj as gS,c9 as yS}from"./vendor-boot-EC6IyLt1.js";import{a as U,R as h}from"./vendor-react-DASdDPIk.js";import{c as Et,d as or,p as cd}from"./vendor-zustand-CUi8eEds.js";import{_ as ft}from"./vendor-vite-runtime-DD1OZmLC.js";import{i as nn}from"./runtimeSurface-k1Eit61v.js";import{saveOrShareFile as vS}from"./nativeFileSave-BJsGPh58.js";const DZ=()=>{if(!bo())return!1;const e=t7();return e==="win32"||e==="linux"},OZ=async()=>{if(!bt())return!1;try{return await Qn("desktop_start_window_drag"),!0}catch{return!1}},xS=24;class es{constructor(t,n,r){this.parent=t,this.overlay=n,this.depth=r}static empty(){return new es(null,new Map,0)}static from(t){return new es(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>=xS?this.compact().fork():new es(this,new Map,this.depth+1)}compact(){if(!this.parent)return this;const t=new Map;return this.collect(t),new es(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 bc=e=>e?es.from(e):es.empty(),wc=()=>({bySession:new Map,lastSequence:new Map}),xv=()=>bc(),q1=10;let bS=0;const bv=()=>`ext-${Date.now().toString(36)}-${bS+=1}`,wv=(e,t)=>{const n=[...e,t];return n.length>q1?n.slice(n.length-q1):n},Yn=(e,t,n)=>{t&&(e.lastMutatedMessageId=e.messages.get(t)?.id??t,e.lastMutationKind=n)},zr=e=>{e.parts=e.parts.fork()},wS=(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:xv(),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}-`),SS=250,Z1=new WeakMap,CS=(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},xa=e=>{const t=Z1.get(e.messages);if(t&&CS(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,c)=>a.createdAt-c.createdAt);break}}return Z1.set(e.messages,{size:e.messages.size,list:r}),r},Sv=(e,t,n)=>{if(!t)return;let r,s=Number.POSITIVE_INFINITY;for(const o of xa(e)){if(o.role!=="user"||o.text!==t||dd(o.id,e.sessionId))continue;const i=Math.abs(o.createdAt-n);i<=SS&&i<s&&(r=o,s=i)}return r},kS=(e,t,n)=>{if(n.role==="user"&&dd(t,e.sessionId)){const r=Sv(e,n.text,n.createdAt);if(r){e.messages.set(t,r);return}}e.messages.set(t,n)},ud=(e,t)=>{if(!t)return;const n=e.messages.get(t)?.id;if(n)return n;if(dd(t,e.sessionId)){const r=xa(e);for(let s=r.length-1;s>=0;s-=1){const o=r[s];if(o?.role==="user")return o.id}}return t},MS=(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=Sv(e,t.text??"",t.startedAt);if(i)return e.messages.set(t.messageId,i),i}const s=ud(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 c={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(c.id,c),i.push(c.id)}e.partOrder.set(o.id,i)}return o},Cv=(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},IS=(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}},W1=(e,t,n,r)=>{const o=(e.partOrder.get(t)??[]).map(c=>e.parts.get(c)).filter(c=>c?.type===n);if(o.length===0){if(!r)return;const c=e.messages.get(t);if(!c)return;const d=Cv(e,c,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 c of a)e.parts.set(c.id,{...c,text:"",streaming:!1})}},jp=(e,t)=>{const n=e.messages.get(t);if(n&&n.role==="assistant")return n;const r=xa(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},_S=(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})},kv=(e,t)=>{_S(e,t,n=>n.type==="thinking")},ES=256,Mv=(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(ES,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},wo=(e,t,n=Date.now())=>{if(!(typeof e!="number"||!Number.isFinite(e)))return typeof t!="number"||!Number.isFinite(t)?e:e-(t-n)},jS=(e,t)=>{if(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})}},TS=(e,t,n)=>{MS(e,n,t)},G1=(e,t,n)=>{const r=jp(e,t.messageId);if(!r)return!1;r.streaming=!0,e.streamingMessages.add(r.id),e.streamingMessages.add(t.messageId),n==="text"&&kv(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 c=[`${r.id}:${n}:${a}`,`${r.id}:${a}`,`${r.id}:${n}`];for(const d of c){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:Mv(o.text,t.delta),streaming:!0};return e.parts.set(o.id,a),s!==o.id&&e.parts.set(s,a),!0}const i=Cv(e,r,n,s);return e.parts.set(i.id,{...i,text:t.delta,streaming:!0}),!0},AS=(e,t)=>{const n=jp(e,t.messageId);if(!n)return;const{text:r,thinking:s}=IS(e,n.id);n.text=typeof t.text=="string"?t.text:r,n.thinking=typeof t.thinking=="string"?t.thinking:s,W1(e,n.id,"text",n.text),W1(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))},yu=(e,t,n)=>{const r=e.toolsByCallId.get(n.toolCallId)??n.messageId,s=jp(e,r);if(!s)return!1;kv(e,s.id);const o=Date.now(),i=wo(n.startedAt,n.serverNow,o),a=wo(n.endedAt,n.serverNow,o);t!=="end"&&(s.streaming=!0,e.streamingMessages.add(s.id));const c=e.parts.get(n.partId)??Array.from(e.parts.values()).find(p=>p.type==="tool"&&p.tool?.toolCallId===n.toolCallId);if(t==="start"&&!c){const p={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(p.id,p);const m=[...e.partOrder.get(s.id)??[]];return m.push(p.id),e.partOrder.set(s.id,m),e.toolsByCallId.set(n.toolCallId,s.id),!0}if(!c||c.type!=="tool")return!1;const d={...c},f=c.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},LS=(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()}},NS=(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,c)=>!!i&&c.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 c=e.parts.get(a);if(!c)continue;const d=c.tool?.state==="running"||c.tool?.state==="pending";if(!c.streaming&&!d)continue;const f={...c,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()},RS="pichamber.ui",PS="pichamber.",DS="pichamber-extension-ui",OS=1,HS=new Set(["info","success","warning","error","neutral"]),Pn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,Qe=e=>typeof e=="string"?e:void 0,Jf=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Iv=e=>{const t=Qe(e);return t&&HS.has(t)?t:"neutral"},K1=e=>{if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=Pn(n);if(!r)continue;const s=Qe(r.label);s!==void 0&&t.push({label:s,value:Qe(r.value)??"",...r.tone!==void 0?{tone:Iv(r.tone)}:{}})}return t},FS=128,Jo=(e,t)=>e.length>t?e.slice(0,t):e,VS=e=>n7(e),Y1=e=>{if(!Array.isArray(e))return;const t=[];for(const n of e.slice(0,8)){const r=Pn(n);if(!r)continue;const s=Qe(r.label),o=Qe(r.command);if(!s||!o||o.includes("/")||o.startsWith("."))continue;const i=Pn(r.promptForArgs),a=i?Qe(i.label):void 0,c=i?Qe(i.placeholder):void 0;t.push({label:Jo(s,FS),command:o,...Qe(r.args)!==void 0?{args:VS(Qe(r.args))}:{},...r.variant==="outline"||r.variant==="ghost"?{variant:r.variant}:{},...Qe(r.icon)!==void 0?{icon:Jo(Qe(r.icon)??"",64)}:{},...r.disabled===!0?{disabled:!0}:{},...r.loading===!0?{loading:!0}:{},...Qe(r.confirm)!==void 0?{confirm:Jo(Qe(r.confirm)??"",500)}:{},...i?{promptForArgs:{...a!==void 0?{label:Jo(a,256)}:{},...c!==void 0?{placeholder:Jo(c,256)}:{}}}:{}})}return t.length>0?t:void 0},BS=(e,t)=>{switch(e){case"markdown":{const n=Qe(t.body)??Qe(t.text);return n!==void 0?{component:"markdown",body:n}:null}case"kv":{const n=K1(t.rows);return n&&n.length>0?{component:"kv",rows:n}:null}case"list":{const n=K1(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=>Qe(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=>Qe(o)??"").slice(0,n.length));return r.length>0?{component:"table",columns:n,rows:r}:null}case"progress":{const n=Jf(t.value);if(n===void 0)return null;const r=Jf(t.max)??100;return{component:"progress",value:n,max:r>0?r:100,...Qe(t.label)!==void 0?{label:Qe(t.label)}:{}}}case"badges":{if(!Array.isArray(t.items))return null;const n=t.items.map(r=>{const s=Pn(r);if(s){const i=Qe(s.label);return i?{label:i,tone:Iv(s.tone)}:null}const o=Qe(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=Qe(t.code);return n!==void 0?{component:"code",code:n,...Qe(t.language)!==void 0?{language:Qe(t.language)}:{}}:null}default:return null}},X1=(e,t=2e3)=>e.length>t?`${e.slice(0,t)}…`:e,J1=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},_v=e=>{const t=Pn(e);if(!t)return;const n=J1(t.message);if(!n)return;if(t.messageExpanded===void 0)return{message:n};const r=J1(t.messageExpanded);return r?{message:n,messageExpanded:r}:{message:n}},Ev=e=>{const n=e.customType===RS||(e.customType?.startsWith(PS)??!1)?Pn(Pn(e.data)?.ui??null)??Pn(e.data)??Pn(e.details):null;if(n){const s=Qe(n.protocol),o=Jf(n.version);if(!(s&&s!==DS)){if(!(o!==void 0&&o!==OS)){const i=Qe(n.component)??Qe(n.type);if(i){const a=Pn(n.props)??{},c=BS(i,a),d=Y1(n.actions);if(c||d){const f=Qe(n.title);return{kind:"ui",descriptor:{...Qe(n.id)!==void 0?{id:Qe(n.id)?.slice(0,128)}:{},...f!==void 0?{title:f.slice(0,256)}:{},component:c??{component:"markdown",body:""},...d?{actions:d}:{}}}}}if(Qe(n.title)||Qe(n.text)||Qe(n.body)){const a=Qe(n.text)??Qe(n.body)??"";if(a){const c=Y1(n.actions);return{kind:"ui",descriptor:{...Qe(n.id)!==void 0?{id:Qe(n.id)?.slice(0,128)}:{},...Qe(n.title)!==void 0?{title:Qe(n.title)?.slice(0,256)}:{},component:{component:"markdown",body:a.slice(0,5e3)},...c?{actions:c}:{}}}}}}}}const r=[];if(typeof e.text=="string"&&e.text.trim().length>0&&r.push(e.text.trim()),e.data!==void 0)try{r.push(X1(JSON.stringify(e.data,null,2)))}catch{r.push("[unserializable data]")}else if(e.details!==void 0)try{r.push(X1(JSON.stringify(e.details,null,2)))}catch{r.push("[unserializable details]")}return{kind:"fallback",title:e.customType??"Extension",body:r.join(`
3
-
4
- `)}},$S=(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),Yn(e,s.id,"structure")},zS=(e,t,n,r)=>{if(!r.customType)return;const s=_v(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),Yn(e,o.id,"structure")},US=(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)},qS=(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)},ZS=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)||(e.extensionDialogs=[...e.extensionDialogs,t])},WS=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)&&(e.extensionDialogs=e.extensionDialogs.filter(n=>n.requestId!==t.requestId))},GS=(e,t)=>{e.extensionNotices=wv(e.extensionNotices,{id:bv(),message:t.message,level:t.level,createdAt:Date.now()})},KS=(e,t)=>{t.commands===!0&&(e.extensionCatalogRevision=(e.extensionCatalogRevision??0)+1)},YS=(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},XS=(e,t)=>{e.extensionTitle=t.title},JS=(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)},QS=(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)},e8=(e,t)=>{e.extensionErrors=wv(e.extensionErrors,{id:bv(),source:t.source,...t.event!==void 0?{event:t.event}:{},message:t.message,createdAt:Date.now()})},t8=(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}:{}}},n8=(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)}},mr=["off","minimal","low","medium","high","xhigh","max"],r8={off:"Off",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},Pt=e=>e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",tn=e=>Pt(e)?e:null,s8=(e,t)=>{const n=e.filter(Pt),r=n.length>0?n:["off"];if(t&&r.includes(t))return t;const s=mr.indexOf(t);if(s===-1)return r[0];for(let o=s+1;o<mr.length;o+=1)if(r.includes(mr[o]))return mr[o];for(let o=s-1;o>=0;o-=1)if(r.includes(mr[o]))return mr[o];return r[0]},Tp=e=>{if(Array.isArray(e?.thinkingLevels)&&e.thinkingLevels.length>0){const t=e.thinkingLevels,n=mr.filter(r=>t.includes(r));return n.length>0?n:["off"]}return e?.reasoning===!0||e?.supportsThinking===!0?mr.filter(t=>t!=="xhigh"&&t!=="max"):["off"]},fd=e=>e.some(t=>t!=="off"&&Pt(t)),Ap=e=>{const t=Tp(e);return fd(t)?t:[]},Tr=e=>e?Pt(e)?r8[e]:`${e.charAt(0).toUpperCase()}${e.slice(1)}`:"Default",o8=(e,t)=>t<=1||!Number.isFinite(e)?0:Math.min(t-1,Math.max(0,Math.round(e*(t-1)))),Lp=(e,t,n)=>{const r=e.filter(Pt);if(!fd(r))return;const s=[void 0,...r],o=Pt(t)&&r.includes(t)?t:void 0,i=s.indexOf(o);return s[(i+n+s.length)%s.length]},jv=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return`${t}/${n}`},Tv=(e,t)=>{if(!(!t||!e))return tn(e[t])??void 0},Q1=e=>{if(e.thinking)return e.thinking;const t=jv(e.model);return Tv(e.defaultThinkingByModel,t)??tn(e.defaultThinking)??void 0},tl=e=>{const t=Tp(e);if(!fd(t))return;const n=jv({providerId:e.providerId,modelId:e.modelId}),r=Tv(e.defaultThinkingByModel,n)??(Pt(e.previousThinking)?e.previousThinking:void 0)??tn(e.defaultThinking)??void 0;if(r)return s8(t,r)},eg=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return{providerId:t,modelId:n}},i8=e=>{let t;if(e.messages)for(const s of e.messages){if(s.role!=="assistant")continue;const o=eg(s.model),i=tn(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??eg(e.model),r=t?.thinkingLevel??tn(e.thinking)??void 0;return{...n?{model:n}:{},...r?{thinking:r}:{}}},tg=new WeakMap,a8=e=>{const t=tg.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 tg.set(e,n),n},l8=(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=ud(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},c8=(e,t,n,r)=>n.id===t.id&&n.role===t.role&&n.parentId===ud(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]),d8=(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(a8(a))}if(n&&c8(e,t,n,s))return n;const o=ud(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}},Av=(e,t)=>{const n=xa(e),r=l8(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(d8(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}},Lv=(e,t)=>{const n=[],r=[];for(const[a,c]of e.parts){const d=c.tool?.state;if(c.type!=="tool"||d!=="running"&&d!=="pending")continue;r.push(a);const f=c.tool?.toolCallId?e.toolsByCallId.get(c.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,c]of e.messages)c.streaming&&e.messages.set(a,{...c,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 c=e.parts.get(a);c&&e.parts.set(a,{...c,streaming:!0})}let o=n[n.length-1];if(!o){const a=xa(e);for(let c=a.length-1;c>=0;c-=1){const d=a[c];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))},Sc=e=>{const t=wc(),n=Date.now(),r=wS(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(o=>[o.key,o.text]))),Array.isArray(e.extensionWidgets)&&(r.extensionWidgets=new Map(e.extensionWidgets.map(o=>[o.key,{lines:o.lines,placement:o.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(e.extensionDialogs)&&(r.extensionDialogs=e.extensionDialogs.filter(o=>typeof o.requestId=="string"&&typeof o.method=="string"&&typeof o.title=="string")),Array.isArray(e.extensionPanels)&&(r.extensionPanels=new Map(e.extensionPanels.filter(o=>typeof o?.id=="string"&&o.id.length>0).map(o=>[o.id,o]))),Array.isArray(e.extensionApps)&&(r.extensionApps=new Map(e.extensionApps.filter(o=>typeof o?.appId=="string"&&o.appId.length>0).map(o=>[o.appId,o]))),r.extensionTitle=e.extensionTitle,e.extensionWorking&&(r.extensionWorking={...e.extensionWorking}),e.extensionDraftTracked===!0&&(r.extensionDraftTracked=!0);for(const{message:o,parts:i}of e.messages??[]){const a=o.role==="extension",c=a?_v(o.render):void 0,d={id:o.id,sessionId:e.session.id,directory:e.session.directory,role:o.role,...a&&o.customType?{customType:o.customType}:{},...a&&o.data!==void 0?{data:o.data}:{},...a&&o.details!==void 0?{details:o.details}:{},...c?{render:c}:{},...o.parentId?{parentId:o.parentId}:{},createdAt:o.createdAt,text:o.text??"",thinking:o.role==="assistant"?o.thinking??"":"",streaming:!1,...o.role==="assistant"&&o.durationMs!==void 0?{durationMs:o.durationMs}:{},...o.role==="assistant"&&o.error?{error:o.error}:{},...o.role==="assistant"&&o.model?{model:o.model}:{},...o.role==="assistant"&&o.thinkingLevel?{thinkingLevel:o.thinkingLevel}:{},...o.role==="assistant"&&o.usage?{usage:o.usage}:{}};r.messages.set(o.id,d);const f=[];for(const u of i){const p=u.type==="tool"?wo(u.startedAt,e.serverNow,n):void 0,m=u.type==="tool"?wo(u.endedAt,e.serverNow,n):void 0,g={id:u.id,index:u.index,type:u.type,text:u.text??"",streaming:!1,...u.type==="tool"?{tool:{toolCallId:u.toolCallId??u.id,name:u.name??"unknown",...u.input!==void 0?{input:u.input}:{},...u.output!==void 0?{output:u.output}:{},...u.render!==void 0?{render:u.render}:{},...typeof u.error=="string"?{error:u.error}:{},...u.metadata!==void 0?{metadata:u.metadata}:{},...u.isError!==void 0?{isError:u.isError}:{},state:u.state??"completed",...p!==void 0?{startedAt:p}:{},...m!==void 0?{endedAt:m}:{}}}:{},...u.type==="attachment"&&u.attachment?{attachment:u.attachment}:{},...u.type==="file"?{file:{...typeof u.mime=="string"?{mime:u.mime}:{},...typeof u.filename=="string"?{filename:u.filename}:{},...typeof u.url=="string"?{url:u.url}:{}}}:{}};r.parts.set(u.id,g),f.push(u.id),u.type==="tool"&&u.toolCallId&&r.toolsByCallId.set(u.toolCallId,o.id)}r.partOrder.set(o.id,f)}const s=i8({model:e.session.model,thinking:e.session.thinking,messages:r.messages.values()});return s.model&&(r.model=s.model),s.thinking&&(r.thinking=s.thinking),r.compaction=e.compaction,Lv(r,{...e.isStreaming!==void 0?{isStreaming:e.isStreaming}:{},...e.lifecycle?{lifecycle:e.lifecycle}:{},...e.retry?{retry:e.retry}:{},inferFromRunningTools:!0}),t.lastSequence.set(e.session.id,e.lastSequence),{state:t,session:r}},vu=(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}}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:xv(),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(i=>[i.key,i.text]))),Array.isArray(t.payload.snapshot.extensionWidgets)&&(s.extensionWidgets=new Map(t.payload.snapshot.extensionWidgets.map(i=>[i.key,{lines:i.lines,placement:i.placement==="belowEditor"?"belowEditor":"aboveEditor"}]))),Array.isArray(t.payload.snapshot.extensionDialogs)&&(s.extensionDialogs=t.payload.snapshot.extensionDialogs.filter(i=>typeof i.requestId=="string"&&typeof i.method=="string"&&typeof i.title=="string")),Array.isArray(t.payload.snapshot.extensionPanels)){const i=new Map;for(const a of t.payload.snapshot.extensionPanels)typeof a?.id=="string"&&a.id.length>0&&i.set(a.id,a);s.extensionPanels=i}if(Array.isArray(t.payload.snapshot.extensionApps)){const i=new Map;for(const a of t.payload.snapshot.extensionApps)typeof a?.appId=="string"&&a.appId.length>0&&i.set(a.appId,a);s.extensionApps=i}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,Lv(s,{isStreaming:t.payload.snapshot.isStreaming,lifecycle:s.lifecycle,...t.payload.snapshot.retry?{retry:t.payload.snapshot.retry}:{},settleWhenIdle:!0})}break;case"session.lifecycle":jS(s,t.payload);break;case"assistant.message.start":s.lifecycle=s.retry?"retry":"busy",s.messages=new Map(s.messages),s.streamingMessages=new Set(s.streamingMessages),t.payload.files?.length&&(zr(s),s.partOrder=new Map(s.partOrder)),TS(s,t.directory,t.payload),t.payload.role==="assistant"&&s.streamingMessages.add(t.payload.messageId),Yn(s,t.payload.messageId,"structure");break;case"assistant.message.delta":zr(s),G1(s,t.payload,"text")&&(s.lifecycle="busy",s.retry=void 0),Yn(s,t.payload.messageId,"part");break;case"assistant.message.end":s.messages=new Map(s.messages),zr(s),s.partOrder=new Map(s.partOrder),s.streamingMessages=new Set(s.streamingMessages),AS(s,t.payload),Yn(s,t.payload.messageId,"structure");break;case"assistant.thinking.delta":zr(s),G1(s,t.payload,"thinking")&&(s.lifecycle="busy",s.retry=void 0),Yn(s,t.payload.messageId,"part");break;case"session.tool.start":zr(s),s.partOrder=new Map(s.partOrder),s.toolsByCallId=new Map(s.toolsByCallId),yu(s,"start",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Yn(s,t.payload.messageId,"part");break;case"session.tool.update":zr(s),yu(s,"update",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Yn(s,t.payload.messageId,"part");break;case"session.tool.end":zr(s),yu(s,"end",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Yn(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.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})}NS(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})}LS(s,t.payload.streaming);break;case"extension.entry":$S(s,t.directory,t.sessionId,t.payload);break;case"extension.message":zS(s,t.directory,t.sessionId,t.payload);break;case"extension.notify":GS(s,t.payload);break;case"extension.catalog":KS(s,t.payload);break;case"extension.editor":YS(s,t.payload,t.sequence);break;case"extension.title":XS(s,t.payload);break;case"extension.status":US(s,t.payload);break;case"extension.widget":qS(s,t.payload);break;case"extension.dialog":ZS(s,t.payload);break;case"extension.dialog.dismiss":WS(s,t.payload);break;case"extension.ui":JS(s,t.payload);break;case"extension.app":QS(s,t.payload);break;case"extension.working":t8(s,t.payload);break;case"extension.editor.track":t.payload.enabled?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;break;case"extension.error":e8(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}},u8={fetchHealth:K5,createStream:yc},xu=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"},f8=async(e,t=u8)=>{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(Y5)&&typeof s.streamEpoch=="string"&&s.streamEpoch.length>0)){const c={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:c},n.phase="failed",n.errors.push({phase:"runtime-probe",error:c}),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 c of a)n.lastSequence.set(c.session.id,-1)};if(e.initialSessions)o(e.initialSessions);else try{const a=await r(()=>Ne.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:xu(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(()=>Ne.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:c}=Sc(a);n.reducerState=c,n.lastSequence.set(a.session.id,a.lastSequence)}catch(a){if(n.errors.push({phase:"session-hydrate",error:xu(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,c=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=c}catch(a){n.errors.push({phase:"stream-attach",error:xu(a)})}const i=n.errors.some(a=>a.phase==="runtime-probe");return n.phase=i?"failed":"ready",n},h8=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}),p8=()=>({bySession:new Map,lastSequence:new Map}),m8=(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,h8(t)),r.lastSequence.set(t.sessionId,t.lastSequence),{state:r,didUpdate:!0}},g8={fetchHealth:K5,createStream:yc},ng=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"},y8=async(e,t=g8)=>{const n={phase:"idle",snapshotState:p8(),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(Y5)||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(()=>Ne.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 c=Sc(a);n.reducerState=c.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.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=m8(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 c=ng(a);return c.code==="INVALID_SESSION",n.phase="failed",n.error=c,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=ng(a),n}return n.phase="ready",n},v8=new Set(["assistant.message.delta","assistant.thinking.delta","session.tool.update"]),x8=e=>v8.has(e.name),Cc=e=>e.name==="assistant.message.delta"||e.name==="assistant.thinking.delta"?e:null,b8=(e,t)=>{const n=Cc(e),r=Cc(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??"")},w8=(e,t)=>{const n=Cc(e),r=Cc(t);return!n||!r||n.name!==r.name?t:{...r,payload:{...r.payload,delta:Mv(n.payload.delta,r.payload.delta)}}},S8=(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,bu=e=>{const t=[];for(const n of e){const r=t[t.length-1];r&&b8(r,n)?t[t.length-1]=w8(r,n):r&&S8(r,n)?t[t.length-1]=n:t.push(n)}return t};class C8{constructor(t){this.publish=t}buffer=[];scheduled="none";generation=0;rafId=0;push(t){if(!x8(t)){const n=this.takeBuffer();this.publish(bu([...n,t]));return}this.buffer.push(t),this.schedule()}flush(){const t=this.takeBuffer();t.length!==0&&this.publish(bu(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(bu(r))};if(typeof globalThis.requestAnimationFrame=="function"){this.scheduled="frame",this.rafId=globalThis.requestAnimationFrame(n);return}this.scheduled="microtask",queueMicrotask(n)}}const k8=[{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"}],ur=()=>k8.map(e=>({id:`system:${e.name}`,name:e.name,invocationName:e.name,source:"system",description:e.description})),M8=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}:{}}}),I8=3e4,Zt=new Map;let Nv=0;const Qf=new Set,Rv=()=>{Nv+=1;for(const e of Qf)e()},wu=()=>Nv,_8=e=>(Qf.add(e),()=>Qf.delete(e)),E8=20,hd=(e,t)=>`${e}
5
- ${t?.trim()??""}`,rg=(e,t)=>Zt.get(hd(e,t))?.commands,j8=(e,t)=>{const n=Zt.get(hd(e,t));return n?{...n}:void 0},T8=(e,t=Date.now())=>t-e.fetchedAt<I8,A8=(e,t,n,r)=>{const s=hd(e,t);for(Zt.delete(s),Zt.set(s,{commands:n,fetchedAt:r?.fetchedAt??Date.now(),promptSignature:r?.promptSignature??"",skillSignature:r?.skillSignature??""});Zt.size>E8;){const o=Zt.keys().next().value;if(typeof o!="string")break;Zt.delete(o)}},L8=(e,t,n,r)=>{const s=hd(e,t),o=Zt.get(s);return o?(Zt.delete(s),Zt.set(s,{...o,promptSignature:n,skillSignature:r}),!0):!1},zl=e=>{if(typeof e=="string"&&e.trim().length>0){const t=`
6
- ${e.trim()}`;for(const n of[...Zt.keys()])n.endsWith(t)&&Zt.delete(n)}else Zt.clear();Rv()},N8=()=>{Zt.clear(),Rv()};function Pv(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 Su="pichamber.piSessionCatalog.v1",kc=1,R8=250,Dv=4,Ov=512,eh=2e3,sg=512,P8=8192,D8=4096,O8=16384,Qo=(e,t,n=!1)=>typeof e=="string"&&e.length<=t&&(n||e.length>0),Ul=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,og=e=>{if(!e||typeof e!="object")return null;const t=e;if(!Ul(t.updatedAt)||!Array.isArray(t.directories)||t.directories.length>Ov)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,c=i.sessions;if(!Qo(a,P8)||!Array.isArray(c))return null;const d=le(a);if(!d||r.has(d)||(o+=c.length,o>eh))return null;const f=[];for(const u of c){if(!u||typeof u!="object")return null;const p=u;if(!Qo(p.id,sg)||p.parentId!==null&&!Qo(p.parentId,sg)||!Qo(p.title,D8,!0)||typeof p.archived!="boolean"||!Ul(p.createdAt)||!Ul(p.updatedAt)||p.preview!==void 0&&!Qo(p.preview,O8,!0)||p.messageCount!==void 0&&(!Number.isSafeInteger(p.messageCount)||p.messageCount<0)||n.has(p.id))return null;const m=p.id;n.set(m,{id:m,directory:d,parentId:p.parentId,title:p.title,archived:p.archived,createdAt:p.createdAt,updatedAt:p.updatedAt,...p.preview!==void 0?{preview:p.preview}:{},...p.messageCount!==void 0?{messageCount:p.messageCount}:{},lifecycle:"idle",hydrated:!1}),f.push(m)}r.set(d,f),s.set(d,"idle")}return{byId:n,byDirectory:r,listStatusByDirectory:s}},ig=e=>{if(!e)return null;try{const t=JSON.parse(e);if(t.version!==kc||!t.runtimes||typeof t.runtimes!="object"||Array.isArray(t.runtimes))return null;const n=Object.entries(t.runtimes);return n.length>Dv?null:{version:kc,runtimes:Object.fromEntries(n)}}catch{return null}},H8=(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>=Ov||r>=eh)break;const i=le(o);if(!i)continue;const a=[];for(const c of e.byDirectory.get(o)??[]){if(r>=eh)break;const d=e.byId.get(c);!d||le(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}},F8=(e=$t(),t={})=>{const n=t.flushDelayMs??R8,r=new Map;let s=null,o=!1;const i=u=>{if(!u)return null;try{const p=ig(e.getItem(Su));return!p||!Object.prototype.hasOwnProperty.call(p.runtimes,u)?null:og(p.runtimes[u])}catch{return null}},a=()=>{if(s!==null&&clearTimeout(s),s=null,r.size===0)return;let u={version:kc,runtimes:{}};try{const b=ig(e.getItem(Su));b&&(u=b)}catch{}const p=new Map(Object.entries(u.runtimes));let m=[...p.values()].reduce((b,y)=>Ul(y?.updatedAt)?Math.max(b,y.updatedAt):b,0);for(const[b,y]of r)m=Math.max(Date.now(),m+1),p.set(b,H8(y,m));r.clear();const g=[...p.entries()].filter(([,b])=>og(b)!==null).sort(([,b],[,y])=>y.updatedAt-b.updatedAt).slice(0,Dv);try{e.setItem(Su,JSON.stringify({version:kc,runtimes:Object.fromEntries(g)}))}catch{}},c=(u,p)=>{o||!u||(r.set(u,p),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:c,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))))}}},V8={read:()=>null,schedule:()=>{},flush:()=>{},dispose:()=>{}};let ag=null;const B8=()=>typeof window>"u"?V8:(ag??=F8($t(),{registerLifecycleListeners:!0}),ag),On=$t(),th="projects",nh="activeProjectId",$8=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim().replace(/\/+$/,""):""},Np=()=>{const e=od().trim().replace(/\/+$/,"");return e||""},pd=()=>{const e=Np();return e?`${th}:${encodeURIComponent(e)}`:th},Hv=()=>{const e=Np();return e?`${nh}:${encodeURIComponent(e)}`:nh},Fv=()=>{const e=Np();if(!e)return!0;const t=$8();return!!(t&&e===t)},z8=(e,t)=>{const n=e.trim();return!n.startsWith("~")||!t?n:n==="~"?t:n.startsWith("~/")||n.startsWith("~\\")?`${t}${n.slice(1)}`:n},U8=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Vv=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},Bv=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&U8.test(t)?t.toLowerCase():null},Rp=e=>{const t=e.trim();if(!t)return"";const n=On.getItem("homeDirectory")||tt.getState().homeDirectory||"",s=z8(t,n).replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},q8=e=>{const t=Rp(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())},Z8=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}},W8=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},G8=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)}),$v=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=Rp(i);if(!a)continue;const c=yp(a);if(!c||n.has(c)||r.has(a))continue;n.add(c),r.add(a);const d={id:c,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=Z8(o.iconImage);u&&(d.iconImage=u)}typeof o.color=="string"&&o.color.trim().length>0&&(d.color=o.color.trim());const f=Vv(o.defaultModel);if(f&&(d.defaultModel=f),o.iconBackground===null)d.iconBackground=null;else{const u=Bv(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},K8=()=>{try{const e=On.getItem(pd())||(Fv()?On.getItem(th):null);return e?$v(JSON.parse(e)):[]}catch{return[]}},Y8=()=>{try{const e=On.getItem(pd()+":manualOrder");if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}},lg=()=>{try{const e=On.getItem(Hv())||(Fv()?On.getItem(nh):null);if(typeof e=="string"&&e.trim().length>0)return e.trim()}catch{return null}return null},zv=e=>{try{const t=Hv();e?On.setItem(t,e):On.removeItem(t)}catch{}},Uv=(e,t)=>{try{On.setItem(pd(),JSON.stringify(e))}catch{}zv(t)},X8=e=>{zv(e),Er({activeProjectId:e})},ei=(e,t,n)=>{Uv(e,t),n&&rh(n),Er({projects:e,activeProjectId:t??void 0})},rh=e=>{try{On.setItem(pd()+":manualOrder",JSON.stringify(e))}catch{}},sh=K8(),J8=sh.some(e=>e.id===lg())?lg():sh[0]?.id??null,it=Et()(or((e,t)=>({projects:sh,activeProjectId:J8,manualProjectOrder:Y8(),validateProjectPath:n=>{if(typeof n!="string"||n.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const r=Rp(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 c=Date.now(),d=r?.label?.trim()||q8(i),u={id:yp(i),path:i,label:d,addedAt:c,lastOpenedAt:c},p=[...t().projects,u];return e({projects:p}),X5()&&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}),ei(s,o,i),o){const a=s.find(c=>c.id===o);a&&tt.getState().setDirectory(a.path,{showOverlay:!1})}else tt.getState().goHome()},setActiveProject:n=>{const{projects:r,activeProjectId:s}=t();if(s===n)return;const o=r.find(c=>c.id===n);if(!o)return;const i=Date.now(),a=r.map(c=>c.id===n?{...c,lastOpenedAt:i}:c);e({projects:a,activeProjectId:n}),ei(a,n,t().manualProjectOrder),tt.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}),X8(n))},renameProject:(n,r)=>{const s=r.trim();if(!s)return;const{projects:o,activeProjectId:i}=t(),a=o.map(c=>c.id===n?{...c,label:s}:c);e({projects:a}),ei(a,i,t().manualProjectOrder)},updateProjectMeta:(n,r)=>{const{projects:s,activeProjectId:o}=t(),i=s.map(a=>{if(a.id!==n)return a;const c={...a};if(r.label!==void 0){const d=r.label.trim();d&&(c.label=d)}if(r.icon!==void 0&&(c.icon=r.icon),r.color!==void 0&&(c.color=r.color),r.iconBackground!==void 0&&(c.iconBackground=Bv(r.iconBackground)),r.defaultModel!==void 0){const d=Vv(r.defaultModel);d?c.defaultModel=d:delete c.defaultModel}return c});e({projects:i}),ei(i,o,t().manualProjectOrder)},uploadProjectIcon:async(n,r)=>{const s=W8(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 G8(r)).replace(/^data:[^;]+;/i,`data:${s};`),a=await Tt(`/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 c=await a.json().catch(()=>null);return c?.settings&&t().synchronizeFromSettings(c.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 Tt(`/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 c=i.map(d=>d.id);e({projects:i,manualProjectOrder:c}),ei(i,o,c)},resetForRuntimeSwitch:()=>{e({projects:[],activeProjectId:null,manualProjectOrder:[]})},synchronizeFromSettings:n=>{const r=$v(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),c=s.activeProjectId!==o,d=s.manualProjectOrder.length!==i.length||s.manualProjectOrder.some((f,u)=>f!==i[u]);if(!a&&!c){d&&(e({manualProjectOrder:i}),rh(i));return}if(e({projects:r,activeProjectId:o,manualProjectOrder:i}),Uv(r,o),rh(i),o&&(c||n.activeProjectId!==void 0)){const f=r.find(u=>u.id===o);f&&tt.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"&&it.getState().synchronizeFromSettings(t)});const ts=le,Q8=(e,t)=>{const n=ts(t);if(!n)return null;let r=null;for(const s of e){const o=ts(s.path);o&&(n!==o&&!n.startsWith(`${o}/`)||(!r||o.length>(ts(r.path)?.length??0))&&(r=s))}return r},er=(e,t,n)=>{const s=ts((typeof t=="string"?t:n)??null);if(!s)return null;const o=Q8(e,s);if(o)return o;if(!(t instanceof Map))return null;const i=new Map;for(const c of e){const d=ts(c.path);d&&i.set(d,c)}let a=null;for(const[c,d]of t){const f=ts(c),u=f?i.get(f):null;if(u)for(const p of d??[]){const m=ts(p?.path??null);m&&(s!==m&&!s.startsWith(`${m}/`)||(!a||m.length>a.worktreePath.length)&&(a={project:u,worktreePath:m}))}}return a?.project??null},cg=500,e6=()=>{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}},st=(e,t)=>{if(!e6())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>cg&&window.__PICHAMBER_STARTUP_TRACE__.splice(0,window.__PICHAMBER_STARTUP_TRACE__.length-cg)},t6=()=>{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__=t6);const oh=async(e,t,n)=>{const r=typeof performance<"u"?performance.now():Date.now();st(`${e}:start`,n);try{const s=await t(),o=typeof performance<"u"?performance.now():Date.now();return st(`${e}:end`,{durationMs:Math.round(o-r)}),s}catch(s){const o=typeof performance<"u"?performance.now():Date.now();throw st(`${e}:error`,{durationMs:Math.round(o-r),error:s instanceof Error?s.message:String(s)}),s}},nl="https://models.dev/api.json",sa=e=>typeof e=="object"&&e!==null,Mc=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),n6=e=>{if(!sa(e))return!1;const t=e;if(!t.modalities)return!0;const{input:n,output:r}=t.modalities;return(!n||Mc(n))&&(!r||Mc(r))},r6=e=>{if(!sa(e))return!1;const t=e;return t.models===void 0||sa(t.models)},qv=(e,t)=>{const n=e?.toLowerCase?.()??"";return!n||!t?"":`${n}/${t}`},dg=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},s6=(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:dg(t.capabilities.input),output:dg(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}),o6=e=>{const t=new Map;if(!sa(e))return t;for(const[n,r]of Object.entries(e)){if(!r6(r))continue;const s=typeof r.id=="string"&&r.id.length>0?r.id:n,o=r.models;if(!(!o||!sa(o)))for(const[i,a]of Object.entries(o)){if(!n6(a))continue;const c=i||a.id;if(!c)continue;const d=qv(s,c);d&&t.set(d,{id:typeof a.id=="string"&&a.id.length>0?a.id:c,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:Mc(a.modalities.input)?a.modalities.input:void 0,output:Mc(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},i6=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(nl,{signal:e?.signal,headers:{Accept:"application/json"},cache:"no-store",mode:"cors"});if(!n.ok)throw new Error(`Metadata request to ${nl} returned status ${n.status}`);return o6(await n.json())}catch(n){return n?.name==="AbortError"?console.warn(`Model metadata request aborted (${nl})`):console.warn(`Failed to fetch model metadata from ${nl}:`,n),new Map}finally{t&&clearTimeout(t)}};let Pi=null;const a6=3e4;let Vs=null;const l6=1500;let rl=null;const c6=()=>{if(typeof window<"u"&&typeof window.requestIdleCallback=="function")return window.requestIdleCallback.bind(window);const e=globalThis.requestIdleCallback;return typeof e=="function"?e:null},ih=(e,t)=>{e().size>0||Pi||Vs!==null&&Date.now()-Vs<a6||(st("modelsMetadata:queued"),Pi=oh("modelsMetadata",i6).then(n=>(n.size>0?(Vs=null,st("modelsMetadata:set",{entries:n.size}),t(n)):Vs=Date.now(),n)).catch(()=>(Vs=Date.now(),new Map)).finally(()=>{Pi=null}))},d6=()=>{Pi=null,Vs=null},u6=(e,t)=>{if(e().size>0||Pi||rl)return;st("modelsMetadata:scheduledIdle");const n=()=>{rl=null,st("modelsMetadata:idleFired"),ih(e,t)},r=c6();if(r){rl={kind:"idle",handle:r(n,{timeout:5e3})};return}rl={kind:"timeout",handle:setTimeout(n,l6)}},f6=(e,t,n,r)=>{const s=qv(t,n);if(s)return e.get(s)??(r?s6(t,r):void 0)},Zv=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)}},h6=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!Zv(n))continue;const s=tn(r);s&&(t[n]=s)}return t},p6=async()=>{try{const e=await Tt("/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:tn(n?.defaultThinking)??void 0,defaultThinkingByModel:h6(n?.defaultThinkingByModel)}}catch{return{ok:!1}}},Cu=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}},m6=async()=>{st("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 st("config.defaults:end",{source:n,durationMs:Math.round(s-e),hasDefaultModel:!!r.defaultModel}),r};try{const n=await p6(),r=(c,d)=>n.ok?t(c,{...d,defaultModel:n.defaultModel,defaultThinking:n.defaultThinking,defaultThinkingByModel:n.defaultThinkingByModel}):t(c,d),s=await r7().catch(()=>null);if(s)return r("shared-settings",Cu(s));const o=jr()?.settings;if(o)try{const d=(await o.load())?.settings;if(d)return r("runtime-settings",Cu(d))}catch{}const i=await Tt("/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)?Cu(a):{})}catch(n){return st("config.defaults:error",{error:n instanceof Error?n.message:String(n)}),t("error",{})}},g6=3e4,sl=new Map,ug=new WeakMap;let ol=0;const y6=(e,t)=>JSON.stringify([e,le(t)??t]),v6=(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}),fg=()=>({worktrees:[],status:"idle",error:null,fetchedAt:0}),rn=Et()((e,t)=>({runtimeKey:J(),projects:new Map,refreshProject:async(n,r,s)=>{const o=le(n);if(!o)return null;const i=J(),a=ol,c=y6(i,o),d=sl.get(c);if(d)return d;const f=t().projects.get(o)??fg();if(!s?.force&&f.status==="ready"&&f.error===null&&Date.now()-f.fetchedAt<g6)return f.worktrees;f.status==="idle"&&e(p=>{const m=new Map(p.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!==ol||i!==J()||t().runtimeKey!==i?null:(e(g=>{const b=g.projects.get(o)??fg(),y=v6(b.worktrees,m);if(y&&b.status==="ready"&&b.error===null)return g;const S=new Map(g.projects);return S.set(o,{worktrees:y?b.worktrees:m,status:"ready",error:null,fetchedAt:Date.now()}),{projects:S}}),m)}catch(p){if(a!==ol||i!==J()||t().runtimeKey!==i)return null;const m=p instanceof Error?p.message:"Failed to discover Git worktrees.";return e(g=>{const b=g.projects.get(o)??f,y=new Map(g.projects);return y.set(o,{...b,status:"failed",error:m}),{projects:y}}),null}finally{sl.delete(c)}})();return sl.set(c,u),u},resetForRuntimeSwitch:n=>{ol+=1,sl.clear(),e({runtimeKey:n,projects:new Map})}})),x6=(e,t)=>{const n=le(t??null);if(!n)return[];const r=e.projects.get(n)?.worktrees;if(!r)return[];const s=ug.get(r);if(s)return s;const o=r.filter(i=>!i.isPrimary&&!i.prunable);return ug.set(r,o),o},Hn=(e,t)=>{const n=new Map;for(const r of e){const s=le(r.path??null);s&&n.set(s,x6(t,s))}return n},Pp="__global__",ns=e=>{const t=typeof e=="string"?e.trim():"";return t.length>0?t:Pp},Wr=e=>e===Pp?null:e,b6=()=>typeof window>"u"?Pp:Zl(tt.getState().currentDirectory),Wv="oc.worktreeProjectMap.v2",ah="oc.worktreeProjectMap",w6=8,hg=new Map,Gv=()=>{try{const e=typeof localStorage<"u"?localStorage.getItem(Wv):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:{}}}},Kv=e=>{const t=Object.fromEntries(Object.entries(e.runtimes).sort(([,n],[,r])=>r.updatedAt-n.updatedAt).slice(0,w6));localStorage.setItem(Wv,JSON.stringify({...e,runtimes:t}))},Yv=()=>{const e=J()||"default",t=hg.get(e);if(t)return t;const n=Gv();let r=n.runtimes[e]?.entries??null;if(!r&&!n.legacyClaimed)try{const o=typeof localStorage<"u"?localStorage.getItem(ah):null;r=o?JSON.parse(o):{},n.legacyClaimed=!0,n.runtimes[e]={updatedAt:Date.now(),entries:r},Kv(n),localStorage.removeItem(ah)}catch{r={}}const s=r??{};return hg.set(e,s),s},S6=(e,t)=>{if(!e||!t||e===t)return;const n=Yv();if(n[e]!==t){n[e]=t;try{const r=J()||"default",s=Gv();s.legacyClaimed=!0,s.runtimes[r]={updatedAt:Date.now(),entries:n},Kv(s),localStorage.removeItem(ah)}catch{}}},Di=e=>{const t=le(e);return t===null?null:t||"/"},C6=()=>{try{return it.getState().projects.map(e=>Di(e.path)).filter(e=>!!e)}catch{return[]}},k6=()=>{try{const{projects:e,activeProjectId:t}=it.getState(),n=t?e.find(r=>r.id===t):null;return Di(n?.path??e[0]?.path??null)}catch{return null}},ql=e=>{const t=Di(e),n=C6();if(!t)return null;if(n.includes(t))return t;const r=Di(Yv()[t]);if(r)return r;try{const s=it.getState().projects,o=er(s,Hn(s,rn.getState()),t),i=Di(o?.path??null);if(i&&i!==t)return S6(t,i),i}catch{return null}return null},Zl=e=>ns(ql(e)),Xv="__add_provider__",Ur="zen",pg="big-pickle",Jv=e=>Zv(e),Qv=(e,t)=>{const n=tn(t);return n&&Ap(e).includes(n)?n:void 0},mg=e=>e===Xv?"":e??"",Ic=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},_c=(e,t,n)=>{const r=e.find(s=>s.id===t);return r?r.models.some(s=>s.id===n):!1},M6=({providers:e,currentProviderId:t,currentModelId:n,currentVariant:r,settingsDefaultModel:s,settingsDefaultVariant:o})=>{const i=(d,f,u)=>{if(!u)return;const p=e.find(m=>m.id===d)?.models.find(m=>m.id===f);return Qv(p,u)};if(t&&n&&_c(e,t,n))return{providerId:t,modelId:n,variant:i(t,n,r)};if(s){const d=Jv(s);if(d&&_c(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],c=a?.models[0];return a&&c?{providerId:a.id,modelId:c.id}:null},ku=({providers:e,settingsZenModel:t})=>{const n=Ic(t);if(!Array.isArray(e)||e.length===0)return n?{providerId:Ur,modelId:n}:null;if(n&&_c(e,Ur,n))return{providerId:Ur,modelId:n};if(_c(e,Ur,pg))return{providerId:Ur,modelId:pg};const r=e.find(s=>s.id===Ur);if(r?.models.length){const s=Math.floor(Math.random()*r.models.length),o=Ic(r.models[s]?.id);if(o)return{providerId:Ur,modelId:o}}return null},I6=4,_6=800,E6=3e4,j6=1e3,T6=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[c,d]of Object.entries(n)){if(!d||typeof d!="object"){a[c]=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[c]=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},gg=new Map,A6=(e,t)=>{const n=e.get(t);return typeof n=="number"&&Date.now()-n<E6},L6=e=>new Promise(t=>setTimeout(t,e)),ex=async()=>(await Ne.health({runtimeKey:J()})).state==="ready",N6=async(e=_6)=>Promise.race([ex().catch(()=>!1),L6(Math.max(1,e)).then(()=>!1)]),yg=new Set;function R6(e){return yg.add(e),()=>{yg.delete(e)}}function P6(e,t){return e.scopes.includes("all")||e.scopes.includes(t)}const D6=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(I6,r.length),i=Array.from({length:o},async()=>{for(;s<r.length;){const a=r[s];s+=1,await e.getState().loadProviders({directory:Wr(a),source:t})}});await Promise.all(i)};let vg=null,xg=null;const O6=e=>{typeof window<"u"&&(window.__zustand_config_store__=e),vg||(vg=R6(async t=>{P6(t,"providers")&&await D6(e,"configChange:providers")})),typeof window<"u"&&!xg&&(xg=tt.subscribe((t,n)=>{const r=ns(t.currentDirectory),s=ns(n.currentDirectory);r!==s&&(st("directoryStore:changed",{previous:s,next:r}),e.getState().activateDirectory(t.currentDirectory))}))},H6=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},F6=e=>e.filter(H6),V6=async()=>{const e=await Ne.listProviders({runtimeKey:J()}),n=F6(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}},Mu=e=>new Promise(t=>setTimeout(t,e)),Iu=new Map;let il=null;const Ze=Et()(or(cd((e,t)=>({activeDirectoryKey:b6(),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=ql(n),s=typeof n=="string"&&n.trim().length>0;if(!r&&s){st("activateDirectory:skippedUnknownDirectory",{directory:n});return}const o=ns(r);let i=!1;e(a=>{const c=a.directoryScoped[o];return c?(i=c.providers.length>0,{activeDirectoryKey:o,providers:c.providers,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentVariant:c.currentVariant,selectedProviderId:c.selectedProviderId,defaultProviders:c.defaultProviders,selectionSource:c.selectionSource??"auto"}):{activeDirectoryKey:o,providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{},selectionSource:"auto"}}),t().isConnected&&(i?A6(gg,o)?st("activateDirectory:providersFresh",{directoryKey:o}):(st("activateDirectory:refreshProvidersBackground",{directoryKey:o}),t().loadProviders({directory:Wr(o),source:"activateDirectory:refresh"})):await t().loadProviders({directory:Wr(o),source:"activateDirectory"}))},invalidateProviderCache:n=>{const r=n===void 0?null:ns(n);e(s=>{const o={};let i=!1;const a={...s.directoryScoped},c=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]=c(d))}else for(const[d,f]of Object.entries(s.directoryScoped))a[d]=c(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??Wr(t().activeDirectoryKey),s=ql(r),o=typeof r=="string"&&r.trim().length>0;if(!s&&o){st("loadProviders:skippedUnknownDirectory",{requestedDirectory:r,source:n?.source??"unknown"});return}const i=s??null,a=ns(s),c=n?.source??"unknown";st("loadProviders:called",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i});const d=Iu.get(a);if(d)return st("loadProviders:deduped",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i}),d;const f=(async()=>{const u=typeof performance<"u"?performance.now():Date.now();st("loadProviders:start",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i});const p=t().directoryScoped[a],m=p?.providers??(t().activeDirectoryKey===a?t().providers:[]),g=p?.defaultProviders??(t().activeDirectoryKey===a?t().defaultProviders:{});let b=null;for(let y=0;y<3;y++)try{const S=await oh("loadProviders:api",async()=>V6(),{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,attempt:y+1}),v=S?.providers??[],x=S?.defaults??{};e(w=>{const C=w.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},I=w.activeDirectoryKey===a?w.currentProviderId:C.currentProviderId,_=w.activeDirectoryKey===a?w.currentModelId:C.currentModelId,E=w.activeDirectoryKey===a?w.currentVariant:C.currentVariant,M=M6({providers:v,currentProviderId:I,currentModelId:_,currentVariant:E,settingsDefaultModel:w.settingsDefaultModel,settingsDefaultVariant:w.settingsDefaultVariant}),T=w.activeDirectoryKey===a?w.selectedProviderId:C.selectedProviderId,A=T===Xv||v.some(O=>O.id===T)?T:M?.providerId??v[0]?.id??"",j={...C,providers:v,defaultProviders:x,currentProviderId:M?.providerId??"",currentModelId:M?.modelId??"",currentVariant:M?.variant,selectedProviderId:A},R={directoryScoped:{...w.directoryScoped,[a]:j}};return w.activeDirectoryKey===a&&(R.providers=v,R.defaultProviders=x,R.currentProviderId=j.currentProviderId,R.currentModelId=j.currentModelId,R.currentVariant=j.currentVariant,R.selectedProviderId=A),R});const k=typeof performance<"u"?performance.now():Date.now();st("loadProviders:end",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,durationMs:Math.round(k-u),providers:v.length,models:v.reduce((w,C)=>w+C.models.length,0)}),gg.set(a,Date.now());return}catch(S){b=S,st("loadProviders:attemptError",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,attempt:y+1,error:S instanceof Error?S.message:String(S)});const v=200*(y+1);await new Promise(x=>setTimeout(x,v))}console.error("Failed to load providers:",b),st("loadProviders:error",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,error:b instanceof Error?b.message:String(b)}),e(y=>{const v={...y.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},providers:m,defaultProviders:g},x={directoryScoped:{...y.directoryScoped,[a]:v}};if(y.activeDirectoryKey===a&&(x.providers=m,x.defaultProviders=g,!y.currentProviderId&&!y.currentModelId&&y.settingsDefaultModel)){const k=Jv(y.settingsDefaultModel);if(k){const w=m.find(C=>C.id===k.providerId);if(w?.models.some(C=>C.id===k.modelId)){const C=w.models.find(_=>_.id===k.modelId),I=Qv(C,y.settingsDefaultVariant);x.currentProviderId=k.providerId,x.currentModelId=k.modelId,x.currentVariant=I,x.selectedProviderId=k.providerId,v.currentProviderId=k.providerId,v.currentModelId=k.modelId,v.currentVariant=I,v.selectedProviderId=k.providerId}}}return x})})().finally(()=>Iu.delete(a));return Iu.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 c=a.activeDirectoryKey,f={...a.directoryScoped[c]??{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,[c]: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:()=>Ap(t().getCurrentModel()),cycleCurrentVariant:()=>{const n=Lp(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:()=>{d6(),e({modelsMetadata:new Map})},ensureModelMetadata:()=>{ih(()=>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 ku({providers:n.providers,settingsZenModel:n.settingsZenModel})},probeConnection:async n=>{if(await N6(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()=>{st("checkConnection:start");const n=5;let r=0,s=null;for(;r<n;)try{st("checkConnection:attempt",{attempt:r+1});const o=await oh("checkConnection:health",()=>ex(),{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 Mu(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"}),st("checkConnection:end",{healthy:o,attempts:r+1}),o}catch(o){s=o,r+=1;const i=400*r;await Mu(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"}),st("checkConnection:end",{healthy:!1,attempts:n}),!1},initializeApp:async()=>{if(il)return st("initializeApp:deduped"),il;const n=(async()=>{const r=typeof performance<"u"?performance.now():Date.now();st("initializeApp:start");try{const s=X5();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..."),st("initApp:skipped",{reason:"checkConnection already verified health"});const i=tt.getState().currentDirectory??Wr(t().activeDirectoryKey),a=er(it.getState().projects,null,i??null),c=ql(a?.path??i??null),d=c??k6();d||st("initializeApp:globalConfigScope"),d&&!c&&i!==d&&(st("initializeApp:normalizedUnknownDirectoryToProject",{initialDirectory:i,configDirectory:d}),tt.getState().setDirectory(d,{showOverlay:!1}));const f=ns(d);t().activeDirectoryKey!==f&&e({activeDirectoryKey:f}),s&&console.log("Loading providers..."),await t().loadProviders({directory:d,source:"initializeApp"});const u=await m6(),p=t().providers,m=Ic(t().settingsZenModel),g=Ic(u.zenModel),y=(ku({providers:p,settingsZenModel:m})??ku({providers:p,settingsZenModel:g}))?.modelId||g||m;e({settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultThinking:u.defaultThinking,settingsDefaultThinkingByModel:u.defaultThinkingByModel??{},settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsZenModel:y}),y&&y!==g&&Er({zenModel:y,gitProviderId:"",gitModelId:""}).catch(()=>{}),e({isInitialized:!0,isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),u6(()=>t().modelsMetadata,v=>e({modelsMetadata:v})),t().prewarmProjectConfigs(d);const S=typeof performance<"u"?performance.now():Date.now();st("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"}),st("initializeApp:error",{error:s instanceof Error?s.message:String(s)})}})().finally(()=>{il=null});return il=n,n},prewarmProjectConfigs:async n=>{if(!t().isConnected)return;const r=Zl(n??Wr(t().activeDirectoryKey)),s=it.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 c=Zl(a);if(o.has(c)||(o.add(c),t().directoryScoped[c]?.providers.length))continue;const f=Wr(c);f&&i.push(f)}for(const a of i){if(await Mu(j6),!t().isConnected)return;const c=Zl(a),d=t().directoryScoped[c],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)=>{ih(()=>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 f6(s,n,r,i)}}),{name:"config-store",storage:vp(),merge:(e,t)=>T6({...t,...e&&typeof e=="object"?e:{}}),partialize:e=>({activeDirectoryKey:e.activeDirectoryKey,directoryScoped:Object.fromEntries(Object.entries(e.directoryScoped).map(([t,n])=>[t,{...n,selectedProviderId:mg(n.selectedProviderId)}])),providers:e.providers,currentProviderId:e.currentProviderId,currentModelId:e.currentModelId,currentVariant:e.currentVariant,selectedProviderId:mg(e.selectedProviderId),defaultProviders:e.defaultProviders,settingsDefaultModel:e.settingsDefaultModel,settingsDefaultVariant:e.settingsDefaultVariant,settingsDefaultThinking:e.settingsDefaultThinking,settingsDefaultThinkingByModel:e.settingsDefaultThinkingByModel,settingsAutoCreateWorktree:e.settingsAutoCreateWorktree,settingsZenModel:e.settingsZenModel})})));O6(Ze);const B6=5e3,no=new Map,ro=new Map,Ec=e=>{const t=J();no.delete(t),ro.delete(t),(!t||t==="local")&&(no.clear(),ro.clear())},tx=()=>{no.clear(),ro.clear()},kr=Et()(or(cd((e,t)=>({selectedSkillName:null,skills:[],isLoading:!1,setSelectedSkill:n=>e({selectedSkillName:n}),loadSkills:async()=>{const n=J(),r=Date.now(),s=no.get(n)??0;if(s>0&&r-s<B6)return!0;const o=ro.get(n);if(o)return o;const i=(async()=>{e({isLoading:!0});try{const c=(await Ne.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:c,isLoading:!1,...d.selectedSkillName&&!c.some(f=>f.name===d.selectedSkillName)?{selectedSkillName:null}:{}})),no.set(n,Date.now()),!0}catch{return e({isLoading:!1}),!1}})();ro.set(n,i);try{return await i}finally{ro.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 Ne.updateResource({resourceId:s.id,content:r},{runtimeKey:J()})).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}),no.set(J(),Date.now()),!0}catch{return!1}},getSkillByName:n=>t().skills.find(r=>r.name===n),resetForRuntimeSwitch:()=>{tx(),e({skills:[],isLoading:!1,selectedSkillName:null})}}),{name:"skills-store",storage:vp(),partialize:e=>({selectedSkillName:e.selectedSkillName})}),{name:"skills-store"})),HZ=Object.freeze(Object.defineProperty({__proto__:null,invalidateSkillsLoadCache:Ec,resetSkillsForRuntimeSwitch:tx,useSkillsStore:kr},Symbol.toStringTag,{value:"Module"})),$6=200,nx=1440*60*1e3,z6=3e4,U6=15e3,q6=9e4,lh="oc.session-activity.v1",Z6=new Set,W6=new Map,Mn=Et(()=>({startedAt:new Map,settledMs:new Map})),fs=new Map;let Dp=0,jc=null;const G6=()=>typeof performance<"u"&&Number.isFinite(performance.timeOrigin)?performance.timeOrigin:Date.now();let Op=G6();const rx=(e,t)=>e.start<=t&&t-e.start<=nx&&e.seen<=t&&Op-e.seen<=z6,K6=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}},Y6=()=>{const e=new Map;let t=null;try{t=id().getItem(lh)}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=K6(o);i&&rx(i,r)&&e.set(s,i)}return e},md=()=>(jc??=Y6(),jc),X6=e=>e-Op>q6?(jc?.clear(),W6):md(),as=(e,t)=>{const n={};for(const[r,s]of md())rx(s,t)&&(n[r]=s);for(const[r,s]of e)n[r]={start:s,seen:fs.get(r)??t};Dp=t;try{const r=id();if(Object.keys(n).length===0){r.removeItem(lh);return}r.setItem(lh,JSON.stringify(n))}catch{}},_u=()=>{const{startedAt:e}=Mn.getState();if(e.size===0)return;const t=Date.now();for(const n of e.keys())fs.set(n,t);as(e,t)};let bg=!1;const sx=()=>{if(!(bg||typeof window>"u")){bg=!0;try{window.addEventListener("pagehide",_u,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&_u()}),document.addEventListener("freeze",_u))}catch{}}},J6=e=>{for(;e.size>$6;){const t=e.keys().next();if(t.done)return;e.delete(t.value)}},wg=(e,t)=>{const n=Date.now(),r=X6(n),s=Mn.getState(),o={started:null,settled:null};let i=!1,a=!1;const c=()=>o.started??=new Map(s.startedAt),d=()=>o.settled??=new Map(s.settledMs);for(const u of e)i=!0,fs.set(u,n),!(o.started??s.startedAt).has(u)&&(c().set(u,r.get(u)?.start??n),(o.settled??s.settledMs).has(u)&&d().delete(u));const f=(u,p)=>{c().delete(u),fs.delete(u),d().set(u,Math.max(0,n-p))};if(t!==null){md().delete(t)&&(a=!0);const u=s.startedAt.get(t);u!==void 0&&f(t,u)}if(o.settled&&J6(o.settled),(o.started||o.settled)&&Mn.setState({startedAt:o.started??s.startedAt,settledMs:o.settled??s.settledMs}),o.started){o.started.size>0&&sx(),as(o.started,n);return}if(a){as(s.startedAt,n);return}i&&s.startedAt.size>0&&n-Dp>=U6&&as(s.startedAt,n)},Sg=(e,t)=>{if(t==="active"){wg(new Set([e]),null);return}wg(Z6,e)},vn=(e,t,n)=>{if(!Number.isFinite(t))return;const r=Date.now(),s=wo(t,n,r);if(s===void 0||r-s>nx||s>r+6e4)return;const o=Mn.getState(),i=o.startedAt.get(e);if(i!==void 0&&s>=i)return;const a=new Map(o.startedAt);a.set(e,s);const c=new Map(o.settledMs);c.delete(e),fs.set(e,r),Mn.setState({startedAt:a,settledMs:c}),sx(),as(a,r)},Cg=e=>{const t=md().delete(e),n=Mn.getState(),r=n.startedAt.has(e),s=n.settledMs.has(e);if(fs.delete(e),!r&&!s){t&&as(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}Mn.setState({startedAt:o,settledMs:i}),(r||t)&&as(o,Date.now())},FZ=(e={})=>{jc=null,fs.clear(),Dp=0,Op=e.pageLoadAt??Date.now(),Mn.setState({startedAt:new Map,settledMs:new Map})},ox=e=>Mn(U.useCallback(t=>t.startedAt.get(e),[e])),VZ=e=>Mn(U.useCallback(t=>t.settledMs.get(e),[e])),BZ=(e,t)=>Mn(U.useCallback(n=>t?n.startedAt.has(e):n.settledMs.has(e),[t,e])),ch="oc.sessions.pinned.v2",Q6="oc.sessions.pinned",Wl=$t(),dh=(e,t,n)=>{const r=le(t);return!e||!r||!n?null:JSON.stringify([e,r,n])},ix=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=le(r);return!n||!o||o!==r||!s?null:[n,o,s]}catch{return null}},uh=(e,t,n)=>{if(!t)return!1;const r=dh(J(),t,n);return r?e.has(r):!1},eC=()=>{Wl.removeItem(Q6);const e=Wl.getItem(ch);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])=>ix(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 Wl.removeItem(ch),{ids:new Set,touchedAt:{}}}},kg=(e,t)=>{const n=[...e].filter(r=>ix(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)}},Mg=({ids:e,touchedAt:t})=>{const n=Object.fromEntries([...e].map(r=>[r,t[r]??Date.now()]));Wl.setItem(ch,JSON.stringify({version:2,sessions:n}))},Ig=eC(),tC=Et((e,t)=>({ids:Ig.ids,touchedAt:Ig.touchedAt,setIds:n=>{const r=t().ids,s=typeof n=="function"?n(r):n;if(s===r)return;const o=kg(s,t().touchedAt);e(o),Mg(o)},toggle:n=>{const r=dh(J(),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=kg(s,o);e(i),Mg(i)},clearPinnedSession:(n,r,s)=>{const o=dh(n,r,s);if(!o||!t().ids.has(o))return;const i=new Set(t().ids);i.delete(o),t().setIds(i)}})),$Z=new Map,Tc=new Map,So=new Map;let Gl=0;const oa=Et(()=>({rankById:new Map})),_g=()=>(Gl=Math.max(Gl+1,Date.now()),Gl),nC=(e,t=!1)=>{const n=[...e];n.length!==0&&oa.setState(r=>{const s=new Map(r.rankById),o=t?_g():null;for(const i of n)s.set(i,o??_g());return{rankById:s}})},rC=(e,t)=>{const n=Tc.get(e);Tc.set(e,t),t==="active"&&n!=="active"&&nC([e])},sC=e=>{Tc.delete(e),So.delete(e),oa.setState(t=>{if(!t.rankById.has(e))return t;const n=new Map(t.rankById);return n.delete(e),{rankById:n}})},zZ=()=>{Tc.clear(),So.clear(),Gl=0,oa.setState({rankById:new Map})},fh=e=>typeof e=="number"&&Number.isFinite(e)?e:0,ax=e=>fh(e.time?.updated)||fh(e.time?.created),oC=e=>fh(e.time?.created),hh=e=>e.parentID??null,ph=e=>{const t=e;return le(t.directory??null)??le(t.project?.worktree??null)},bi=(e,t)=>{const n=So.get(e.id),r=t?"created":"updated",s=n?.[r];if(s!==void 0)return s;const o=t?oC(e):ax(e);return So.set(e.id,{...n,[r]:o}),o},iC=e=>{const t=oa.getState().rankById;let n=!1;for(const r of e){const s=ax(r);if(t.get(r.id)!==void 0)continue;const o=So.get(r.id);o?.updated!==void 0&&o.updated>=s||(So.set(r.id,{...o,updated:s}),n=!0)}n&&oa.setState(r=>({rankById:new Map(r.rankById)}))},Eg=(e,t,n=!1)=>t.get(e.id)??bi(e,n),lx=(e,t,n,r,s)=>{if(n!==r)return n?-1:1;const o=bi(e,n),i=bi(t,r);if(hh(e)===hh(t)){const d=Eg(t,s,r)-Eg(e,s,n);if(d!==0)return d}const a=i-o;if(a!==0)return a;const c=bi(t,!0)-bi(e,!0);return c!==0?c:e.id.localeCompare(t.id)},UZ=(e,t,n,r)=>lx(e,t,uh(n,ph(e),e.id),uh(n,ph(t),t.id),r),aC=(e,t,n=r=>r)=>{const r=new Map,s=o=>{let i=r.get(o);return i===void 0&&(i=uh(e,ph(o),o.id),r.set(o,i)),i};return(o,i)=>{const a=n(o),c=n(i);return lx(a,c,s(a),s(c),t)}},qZ=(e,t,n)=>{const r=new Set(e.map(f=>f.id)),s=[],o=new Map;for(const f of e){const u=hh(f);if(!u||!r.has(u)){s.push(f);continue}const p=o.get(u);p?p.push(f):o.set(u,[f])}const i=aC(t,n);s.sort(i);for(const f of o.values())f.sort(i);const a=[],c=new Set,d=f=>{if(!c.has(f.id)){c.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},jg=500,lC=1e3*60*60*24*30;function cC(e){const t=Date.now()-lC,n=e.filter(r=>r.time>=t);return n.length<=jg?n:n.slice(n.length-jg)}function Eu(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 gd=Et((e,t)=>({list:[],index:{session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}},append:n=>{const r=t().list,s=cC([...r,n]);e({list:s,index:Eu(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:Eu(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:Eu(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 yd(e){gd.getState().markSessionViewed(e)}function cx(e,t,n){const r=gd.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 dx(e){const t=ne.getState();if(!t.nativeNotificationsEnabled||e.kind==="completion"&&!t.notifyOnCompletion||e.kind==="error"&&!t.notifyOnError)return;const n=jr()?.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 Hp(e,t){return`pichamber:input:${e}:${t}`}function ux(e){const t=ne.getState();if(!t.nativeNotificationsEnabled||t.notifyOnInputNeeded===!1)return;const n=jr()?.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:Hp(e.sessionId,e.since),kind:"input",sessionId:e.sessionId,directory:e.directory,requireHidden:t.notificationMode!=="always"})}function dC(e){return gd(t=>t.index.session.unseenCount[e]??0)}const ZZ=Object.freeze(Object.defineProperty({__proto__:null,dispatchInputNeededNotification:ux,dispatchSessionNotification:dx,inputNeededNotificationTag:Hp,markSessionViewed:yd,notifySessionTurnComplete:cx,useNotificationStore:gd,useSessionUnseenCount:dC},Symbol.toStringTag,{value:"Module"})),uC="pichamber_sync_perf",Fp=()=>({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}),fC=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(uC)==="1"}catch{return!1}},fx=fC();let Kl=fx||Lo()?Fp():null;const hC=()=>Lo()||fx,Vp=()=>hC()?(Kl||(Kl=Fp()),Kl):null;function hx(){Vp()&&(Kl=Fp())}function px(){const e=Vp();return e?{...e}:null}function pC(e){const t=Vp();t&&(t.persistenceSerializations+=1,t.persistenceUtf8Bytes+=new TextEncoder().encode(e).byteLength)}typeof window<"u"&&(window.__pichamberSyncPerformance={getSnapshot:px,reset:hx});const mh="pichamber.chatDrafts.v2",mC=50,gh=$t(),yh=new Set;let wi,Wn;const No=(e,t,n)=>{const r=le(t);return!e||!r?null:{runtimeKey:e,directory:r,sessionId:n}},Wt=e=>JSON.stringify([e.runtimeKey,e.directory,e.sessionId]),mx=()=>{const e=gh.getItem(mh);if(e===wi&&Wn)return Wn;try{const t=JSON.parse(e??"");if(t.version!==2||!t.drafts||typeof t.drafts!="object"||Array.isArray(t.drafts))return wi=e,Wn={version:2,drafts:{}},Wn;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 wi=e,Wn={version:2,drafts:n},Wn}catch{return gh.removeItem(mh),wi=null,Wn={version:2,drafts:{}},Wn}},gC=e=>{const t=JSON.stringify(e);wi=t,Wn=e,pC(t),gh.setItem(mh,t)},vd=e=>{if(!e)return{text:"",confirmedMentions:new Set};const t=mx().drafts[Wt(e)];return t?{text:t.text,confirmedMentions:new Set(t.confirmedMentions)}:{text:"",confirmedMentions:new Set}},hs=(e,t,n)=>{if(!e)return;const r=mx(),s=Wt(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,c)=>c[1].touchedAt-a[1].touchedAt).slice(0,mC);gC({version:2,drafts:Object.fromEntries(i)})},yC=(e,t=!1)=>{hs(e,"",[]),t&&yh.forEach(n=>n(e))},vC=e=>(yh.add(e),()=>yh.delete(e)),xd=e=>({...e,previewUrl:void 0,uploadState:e.uploadState?{...e.uploadState}:e.uploadState}),xC=["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"],bC=xC.join(","),wC=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"},SC=(e,t)=>{const n=new Set(t.map(s=>s.toLowerCase())),r=[];for(const s of e){const o=wC(s.mimeType);o&&!n.has(o)&&r.push({attachment:s,modality:o})}return r},CC=new Map([["image/png","image/png"],["image/jpeg","image/jpeg"],["image/gif","image/gif"],["image/webp","image/webp"],["application/pdf","application/pdf"]]),kC=new Map([["gif","image/gif"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["pdf","application/pdf"],["png","image/png"],["webp","image/webp"]]),MC=new Set(["application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml","image/svg+xml"]),IC=4096,_C=new Set(["docx","pptx","xlsx","odt","odp","ods"]),Yl="[REDACTED]",EC="[OMITTED BY PICHAMBER]",vh=/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api[-_]?key|client[-_]?secret|password|secret|access[-_]?token|refresh[-_]?token|id[-_]?token|token)$/i,Bp=e=>{const t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()},gx=e=>e.type.split(";",1)[0]?.trim().toLowerCase()??"",jC=async e=>{const t=new Uint8Array(await e.slice(0,IC).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"},TC=e=>{const t=gx(e),n=CC.get(t);if(n)return n;const r=Bp(e.name),s=kC.get(r);return(!t||t==="application/octet-stream")&&s?s:t.startsWith("text/")||MC.has(t)||t.endsWith("+json")||t.endsWith("+xml")?"text/plain":jC(e).then(o=>o||t||"application/octet-stream")},al=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join(""):"",AC=(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,c=al(a.source).trimEnd();if(a.cell_type==="markdown"){s.push(`## Markdown cell ${i+1}
9
-
10
- ${c}`);return}if(a.cell_type!=="code"||(s.push(`## Code cell ${i+1}
11
-
12
- \`\`\`${r}
13
- ${c}
14
- \`\`\``),!Array.isArray(a.outputs)))return;const d=[];for(const f of a.outputs){if(!f||typeof f!="object")continue;const u=f,p=al(u.text)||al(u.traceback);if(p){d.push(p.trimEnd());continue}if(u.data&&typeof u.data=="object"){const m=u.data,g=al(m["text/plain"]);g&&d.push(g.trimEnd());const b=Object.keys(m).filter(y=>y!=="text/plain");b.length>0&&d.push(`[Non-text output omitted: ${b.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
- `},LC=e=>{try{const t=new URL(e);for(const n of Array.from(t.searchParams.keys()))vh.test(n)&&t.searchParams.set(n,Yl);return t.toString()}catch{return e}},xh=(e,t)=>{if(t&&vh.test(t))return Yl;if(t==="cookies"&&Array.isArray(e))return e.map(s=>!s||typeof s!="object"?s:{...s,value:Yl});if(t==="text"||t==="encoding")return EC;if(typeof e=="string")return t==="url"?LC(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"&&vh.test(n.name);return Object.fromEntries(Object.entries(n).map(([s,o])=>[s,r&&s==="value"?Yl:xh(o,s)]))},NC=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=AC(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"})},RC=async e=>{try{const t=(await ft(async()=>{const{default:o}=await import("./vendor-heic2any-pq-UTQQR.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}},Tg=e=>{const t=Bp(e.name),n=gx(e);if(n==="image/heic"||n==="image/heif"||t==="heic"||t==="heif")return RC(e).then(s=>s?{file:s,mimeType:"image/jpeg"}:void 0);if(t==="har"||t==="ipynb")return NC(e,t).then(s=>s?{file:s,mimeType:"text/plain"}:void 0);const r=TC(e);return typeof r=="string"?{file:e,mimeType:r}:r?.then(s=>s?{file:e,mimeType:s}:void 0)},PC=(e,t=[])=>{if(!_C.has(Bp(e.name))){const n=Tg(e);return n instanceof Promise?n.then(r=>r?[r]:void 0):n?[n]:void 0}return ft(()=>import("./document-attachments-BslE4Ns7.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 Tg(o);if(!i||!i.mimeType.startsWith("image/"))return;s.push(i)}return s})},DC=3,OC=3,HC=100*1024*1024,Ps=20;let Bs=0,ju=0;const Co=[],so=new Map,Xr=new Map,Ac=new Map,Ag=(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()))},ll=(e="attachment")=>`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`,FC=(e,t)=>{if(!(!t.startsWith("image/")||typeof URL.createObjectURL!="function"))return URL.createObjectURL(e)},Lg=new Set,yx=e=>{!e||Lg.has(e)||(Lg.add(e),typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e))},VC=e=>{for(const t of e)yx(t.previewUrl)},BC=(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)}),vx=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 BC(n,t.mimeType),previewUrl:void 0}})),$C=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)},zC=(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}},UC=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."},Qt=(e,t)=>{let n=!1;return Ke.setState(r=>({attachedFiles:r.attachedFiles.map(s=>s.id!==e?s:(n=!0,t(s)))})),n},xx=()=>{for(;ju<OC&&Co.length>0;){const e=Co.shift();if(!e)continue;const t=Ke.getState().attachedFiles.find(n=>n.id===e);!t||t.source!=="local"||t.uploadState?.status!=="preparing"||(ju+=1,qC(e).finally(()=>{ju-=1,xx()}))}},Tu=e=>{Co.includes(e)||so.has(e)||(Co.push(e),xx())},qC=async e=>{const t=Ke.getState().attachedFiles.find(a=>a.id===e);if(!t||t.source!=="local")return;const n=t.file instanceof Blob?t.file:zC(t.dataUrl,t.mimeType);if(!n||n.size===0){Qt(e,a=>({...a,uploadState:{status:"failed",error:"The file data is no longer available."}}));return}const r=J(),s=(Xr.get(e)??0)+1;Xr.set(e,s);const o=new AbortController;so.set(e,o);let i=-1;Qt(e,a=>({...a,uploadState:{status:"uploading",progress:n.size>0?0:null}}));try{const a=await Ne.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,!(Xr.get(e)!==s||r!==J())&&Qt(e,p=>p.uploadState?.status==="uploading"?{...p,uploadState:{status:"uploading",progress:u}}:p))}},{runtimeKey:r});if(Xr.get(e)!==s||r!==J()){Ne.deleteAttachment(a.id,{runtimeKey:r}).catch(()=>{});return}Qt(e,d=>({...d,uploadState:{status:"ready",attachmentId:a.id,expiresAt:a.expiresAt}}));const c=setTimeout(()=>{Ac.delete(e),Qt(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));Ac.set(e,c)}catch(a){if(Xr.get(e)!==s)return;Qt(e,c=>({...c,uploadState:{status:"failed",error:UC(a)}}))}finally{so.get(e)===o&&so.delete(e)}},bh=e=>{Xr.set(e.id,(Xr.get(e.id)??0)+1),so.get(e.id)?.abort(),so.delete(e.id);const t=Ac.get(e.id);t&&clearTimeout(t),Ac.delete(e.id);const n=Co.indexOf(e.id);n>=0&&Co.splice(n,1)},ZC=(e,t)=>{bh(e),yx(e.previewUrl),t&&e.uploadState?.status==="ready"&&Ne.deleteAttachment(e.uploadState.attachmentId,{runtimeKey:J()}).catch(()=>{})},qn=(e,t)=>{for(const n of e)ZC(n,t)},WC=10,GC=50*1024*1024,KC=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 Ng=0;const YC=(e,t,n)=>!e||e.draftKey!==t?!1:n===e.text,Ke=Et()((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&&(Ng+=1,e({sentDraftClear:{draftKey:n,text:r,nonce:Ng}}))},consumeSentDraftClear:n=>{t().sentDraftClear?.nonce===n&&e({sentDraftClear:null})},addAttachedFile:async n=>{const r=Bs,s=ll("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>Ps)return Qt(s,i=>({...i,uploadState:{status:"failed",error:`You can attach up to ${Ps} files to one message.`}})),!1;for(let i=0;i<DC;i+=1){const a=t().attachedFiles.filter(p=>p.id!==s).map(p=>p.filename);let c;try{const p=PC(n,a);c=p instanceof Promise?await p:p}catch{c=null}if(r!==Bs||!t().attachedFiles.some(p=>p.id===s))return!1;if(!c||c.length===0)return Qt(s,p=>({...p,uploadState:{status:"failed",error:"This file could not be prepared."}})),!1;if(t().attachedFiles.length-1+c.length>Ps)return Qt(s,p=>({...p,uploadState:{status:"failed",error:`You can attach up to ${Ps} files to one message.`}})),!1;if(c.some(p=>p.file.size>HC))return Qt(s,p=>({...p,uploadState:{status:"failed",error:"File exceeds the 100 MB upload limit."}})),!1;const d=c.slice(1).map(p=>p.file.name);if(Ag(d,t().attachedFiles.filter(p=>p.id!==s)))continue;const f=c.length>1?ll("document"):void 0,u=c.map(p=>({id:ll(),file:p.file,dataUrl:"",previewUrl:FC(p.file,p.mimeType),mimeType:p.mimeType,filename:p.file.name,size:p.file.size,source:"local",uploadState:{status:"preparing"},sourceDocumentId:f}));if(r!==Bs)return qn(u,!1),!1;if(Ag(d,t().attachedFiles.filter(p=>p.id!==s))){qn(u,!1);continue}e(p=>({attachedFiles:p.attachedFiles.flatMap(m=>m.id===s?u:[m])}));for(const p of u)Tu(p.id);return!0}return Qt(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())&&(Qt(s.id,o=>({...o,uploadState:{status:"preparing"}})),Tu(s.id));return}Qt(n,s=>({...s,uploadState:{status:"preparing"}})),Tu(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];qn(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));qn(s,!1);const o=t().stashedAttachmentsByDraft;let i=o;if(o){i={};for(const[a,c]of Object.entries(o)){const d=c.filter(f=>!r.has(f.id));VC(c.filter(f=>r.has(f.id))),d.length>0&&(i[a]=d)}}e(a=>({attachedFiles:a.attachedFiles.filter(c=>!r.has(c.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>Ps)return{ok:!1,reason:"attachment-limit",limit:Ps,currentCount:r,missingCount:i.length};const a=new Set(i.map(f=>f.id)),c=t().stashedAttachmentsByDraft??{},d={};for(const[f,u]of Object.entries(c)){const p=u.filter(m=>!a.has(m.id));p.length>0&&(d[f]=p)}return e(f=>({attachedFiles:[...f.attachedFiles,...i.map(xd)],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 c=Object.keys(a);for(;c.length>WC||KC(a)>GC;){const d=c.shift();if(!d)break;qn(a[d]??[],!0),delete a[d]}e({attachedFiles:i,stashedAttachmentsByDraft:a,activeAttachmentsDraftKey:n})},clearStashedAttachmentsForSession:n=>{const r=a=>{try{const c=JSON.parse(a);return Array.isArray(c)&&c[0]===n.runtimeKey&&c[1]===n.directory&&c[2]===n.sessionId}catch{return!1}},s=t(),o={};for(const[a,c]of Object.entries(s.stashedAttachmentsByDraft))r(a)?qn(c,!0):o[a]=c;const i=s.activeAttachmentsDraftKey!==null&&r(s.activeAttachmentsDraftKey);i&&qn(s.attachedFiles,!0),e({attachedFiles:i?[]:s.attachedFiles,stashedAttachmentsByDraft:o})},setAttachedFiles:n=>{Bs+=1;const r=new Set(n.map(s=>s.id));qn(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:()=>{Bs+=1,qn(t().attachedFiles,!0),e({attachedFiles:[]})},addRestoredAttachment:({url:n,mimeType:r,filename:s})=>{const o=ll("restored"),i=new File([],s,{type:r}),a={id:o,file:i,dataUrl:n,mimeType:r,filename:s,size:$C(n),source:"server",serverPath:n};e(c=>({attachedFiles:[...c.attachedFiles,a]}))}}));xp(()=>{Bs+=1;const e=s=>s.map(o=>o.source==="local"?{...o,uploadState:{status:"failed",error:"The runtime changed. Retry the upload."}}:o),t=Ke.getState().attachedFiles;for(const s of t)bh(s);const n=Ke.getState().stashedAttachmentsByDraft??{},r={};for(const[s,o]of Object.entries(n)){for(const i of o)bh(i);r[s]=e(o)}Ke.setState({attachedFiles:e(t),stashedAttachmentsByDraft:r,pendingWorktreeRestore:null,sentDraftClear:null})});const oo="oc.sessions.folders",io="oc.sessions.folderCollapse",Lc="oc.sessions.folders.v2.index",bx="/api/pi/session-folders",XC=250,Ht=$t(),Au=id();let rs=null,Oi=!1,Xl=!1,Hi=!1,Fi,Vi,Bi=null,$i=null,ko=null,In=J(),ls=0,Nc=0;const Rc=new Map,Ar=(e,t)=>`${e}.v2:${encodeURIComponent(t)}`,$p=()=>{try{const e=JSON.parse(Ht.getItem(Lc)??"");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:[]}}},ia=(e,t=Date.now(),n=Ht)=>{const r=$p(),s=[{runtimeKey:e,updatedAt:t},...r.runtimes.filter(o=>o.runtimeKey!==e)];n.setItem(Lc,JSON.stringify({version:2,legacyClaimed:r.legacyClaimed,runtimes:s}))},wx=e=>{const t=$p();if(t.legacyClaimed)return;const n=Ht.getItem(oo),r=Ht.getItem(io);n&&Ht.setItem(Ar(oo,e),n),r&&Ht.setItem(Ar(io,e),r);const s={...t,legacyClaimed:!0};Ht.setItem(Lc,JSON.stringify(s)),Ht.getItem(Lc)===JSON.stringify(s)&&(Ht.removeItem(oo),Ht.removeItem(io)),ia(e,0)},JC=(e,t)=>{if(typeof window>"u")return;rs&&clearTimeout(rs);const n=JSON.parse(JSON.stringify(e)),r=Array.from(t),s=In,o=ls;rs=setTimeout(()=>{if(rs=null,s!==J()||o!==ls)return;const i=Math.max(Date.now(),(Rc.get(s)??0)+1);Rc.set(s,i),Tt(bx,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:1,foldersMap:n,collapsedFolderIds:r,updatedAt:i})}).then(c=>{c.status===409&&(s!==J()||o!==ls||(Oi=!1,Hi=!0,bd()))}).catch(()=>{})},XC)},Rg=(e=In)=>{try{wx(e);const t=Ht.getItem(Ar(oo,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 c=a,d=typeof c.id=="string"?c.id.trim():"",f=typeof c.name=="string"?c.name.trim():"",u=typeof c.createdAt=="number"?c.createdAt:0;if(!d||!f)continue;const p=Array.isArray(c.sessionIds)?c.sessionIds.filter(g=>typeof g=="string"&&g.trim().length>0):[],m=typeof c.parentId=="string"?c.parentId:null;i.push({id:d,name:f,sessionIds:p,createdAt:u,parentId:m})}i.length>0&&(r[s]=i)}return r}catch{return{}}},Pg=(e=In)=>{try{wx(e);const t=Ht.getItem(Ar(io,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}},Sx=e=>{Bi=e,ko=In,clearTimeout(Fi),Fi=setTimeout(()=>{try{const t=ko??In;Ht.setItem(Ar(oo,t),JSON.stringify(e)),ia(t),Bi=null}catch{}},300)},Cx=e=>{$i=e,ko=In,clearTimeout(Vi),Vi=setTimeout(()=>{try{const t=ko??In;Ht.setItem(Ar(io,t),JSON.stringify(Array.from(e))),ia(t),$i=null}catch{}},300)},kx=()=>{Fi&&clearTimeout(Fi),Vi&&clearTimeout(Vi),Fi=void 0,Vi=void 0;const e=ko??In;let t=!1;if(Bi!==null){const n=Ar(oo,e),r=JSON.stringify(Bi);Ht.setItem(n,r),Au.setItem(n,r),Bi=null,t=!0}if($i!==null){const n=Ar(io,e),r=JSON.stringify(Array.from($i));Ht.setItem(n,r),Au.setItem(n,r),$i=null,t=!0}if(t){const n=Date.now();ia(e,n),ia(e,n,Au)}ko=null};if(typeof window<"u"){const e=()=>{try{kx()}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 Zn=(e,t)=>{Nc+=1,Sx(e),Cx(t),JC(e,t)},QC=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`folder_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,ti=(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},zp=Et()(or((e,t)=>({foldersMap:Rg(),collapsedFolderIds:Pg(),resetForRuntimeSwitch:n=>{try{kx()}catch{}In=n,ls+=1,Nc=0,Oi=!1,Xl=!1,Hi=!1,rs&&clearTimeout(rs),rs=null,e({foldersMap:Rg(n),collapsedFolderIds:Pg(n)}),queueMicrotask(()=>{bd()})},getFoldersForScope:n=>n?t().foldersMap[n]??[]:[],createFolder:(n,r,s)=>{const o=r.trim()||"New folder",i={id:QC(),name:o,sessionIds:[],createdAt:Date.now(),parentId:s??null},a=t().foldersMap,c=a[n]??[],d={...a,[n]:[...c,i]};return e({foldersMap:d}),Zn(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 c=a.map(f=>f.id===r?{...f,name:o}:f),d={...i,[n]:c};e({foldersMap:d}),Zn(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 p of o)p.parentId&&i.has(p.parentId)&&!i.has(p.id)&&(i.add(p.id),a=!0)}const c=o.filter(p=>!i.has(p.id)),d={...s,[n]:c},f=t().collapsedFolderIds,u=ti(o,c,f);e(u?{foldersMap:d,collapsedFolderIds:u}:{foldersMap:d}),Zn(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(p=>p.id===r);if(!a)return;const c=i.reduce((p,m)=>p+(m.sessionIds.includes(s)?1:0),0);if(a.sessionIds.includes(s)&&c===1)return;const d=i.map(p=>{const m=p.sessionIds.filter(g=>g!==s);return p.id===r?{...p,sessionIds:[...m,s]}:m.length!==p.sessionIds.length?{...p,sessionIds:m}:p}),f={...o,[n]:d},u=ti(i,d,t().collapsedFolderIds);e(u?{foldersMap:f,collapsedFolderIds:u}:{foldersMap:f}),Zn(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 c=i.find(m=>m.id===r);if(!c)return;let d=!1;for(const m of i){for(const g of a)if(m.sessionIds.includes(g)&&(m.id!==r||!c.sessionIds.includes(g))){d=!0;break}if(d)break}if(!d){for(const m of a)if(!c.sessionIds.includes(m)){d=!0;break}}if(!d)return;const f=i.map(m=>{const g=m.sessionIds.filter(b=>!a.has(b));return m.id===r?{...m,sessionIds:[...g,...a]}:g.length!==m.sessionIds.length?{...m,sessionIds:g}:m}),u={...o,[n]:f},p=ti(i,f,t().collapsedFolderIds);e(p?{foldersMap:u,collapsedFolderIds:p}:{foldersMap:u}),Zn(u,p??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 c=o.map(u=>{const p=u.sessionIds.filter(m=>!i.has(m));return p.length!==u.sessionIds.length?(a=!0,{...u,sessionIds:p}):u});if(!a)return;const d={...s,[n]:c},f=ti(o,c,t().collapsedFolderIds);e(f?{foldersMap:d,collapsedFolderIds:f}:{foldersMap:d}),Zn(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(p=>p!==r);return u.length!==f.sessionIds.length?(i=!0,{...f,sessionIds:u}):f});if(!i)return;const c={...s,[n]:a},d=ti(o,a,t().collapsedFolderIds);e(d?{foldersMap:c,collapsedFolderIds:d}:{foldersMap:c}),Zn(c,d??t().collapsedFolderIds)},removeSessionEverywhere:(n,r)=>{if(!n||n!==In||n!==J()||!r)return;const s=t().foldersMap;let o=null;for(const[i,a]of Object.entries(s)){let c=!1;const d=a.map(f=>{const u=f.sessionIds.filter(p=>p!==r);return u.length===f.sessionIds.length?f:(c=!0,{...f,sessionIds:u})});c&&(o??={...s},o[i]=d)}o&&(e({foldersMap:o}),Zn(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}),Zn(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"})),bd=async()=>{if(typeof window>"u"||Xl||Oi&&!Hi)return;Hi=!1,Xl=!0;const e=In,t=ls,n=Nc;let r=!1;try{const s=await Tt(bx).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!==ls||e!==J())return;const c=$p().runtimes.find(u=>u.runtimeKey===e)?.updatedAt??0,d=typeof o.updatedAt=="number"&&Number.isFinite(o.updatedAt)?o.updatedAt:0;d>0&&Rc.set(e,Math.max(Rc.get(e)??0,d)),(o.exists===!0||d>0)&&Nc===n&&d>=c&&(zp.setState({foldersMap:i,collapsedFolderIds:a}),Sx(i),Cx(a)),r=!0}catch{}finally{t===ls&&e===J()&&(Xl=!1,r&&(Oi=!0),Hi&&(Oi=!1,queueMicrotask(()=>{bd()})))}},ek=()=>{typeof window>"u"||bd()};ek();const tk=e=>{if(e.runtimeKey!==J()||!e.directory||e.directory==="global"||!e.sessionId)return;const t=bp(e.sessionId,e.directory,e.runtimeKey);t&&ct.getState().clearQueue(t),zp.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),tC.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=No(e.runtimeKey,e.directory,e.sessionId);n&&yC(n,!0),Ke.getState().clearStashedAttachmentsForSession(e)},aa=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},nk=e=>{let t=null;for(const n of e.messages.values())n.role==="user"&&(t=n.id);return t},Mx=e=>{const t=e?.awaitingPromptEcho?.baselineUserMessageId;return!e||e.awaitingPromptEcho===void 0?!1:nk(e)===t},rk=(e,t)=>{if(e===t)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=aa(t);return n?wh(e,t,n):!1},wh=(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:ok(e,t,n),sk=(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},ok=(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(!sk(i,a))return!1;for(const c of a)if(e.parts.get(c)!==t.parts.get(c))return!1}for(const r of e.messages.keys())if(!t.messages.has(r))return!1;return!0},ik="selection-store",ak=3,Dg="context-store",Og=1,ao=500,la=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ps=e=>typeof e=="string",Up=e=>typeof e=="object"&&e!==null&&typeof e.providerId=="string"&&typeof e.modelId=="string",Hg=(e,t)=>`${e}/${t}`,Fg=(e,t,n)=>JSON.stringify([e,t,n]),lk=(e,t)=>JSON.stringify([e,t]),Sn=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===3&&t.every(ps))return t}catch{}return null},Lu=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===2&&t.every(ps))return t}catch{}return null},$s=new Set,zs=new Set,pr=new Set;let Sh=!1;const ck=()=>{$s.clear(),zs.clear(),pr.clear(),Sh=!1},wd=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},dk=e=>{const t=wd(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"?Sn(s):null;o&&r(o[0])}return t},cl=(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},dl=(e,t)=>{if(!e.has(t))return e;const n=new Map(e);return n.delete(t),n},qr=(e,t=[])=>{const n=dk(e);for(const o of t){const i=n.indexOf(o);i!==-1&&n.splice(i,1),n.push(o)}if(n.length<=ao){const o=e.sessionRecency;return o.length===n.length&&o.every((a,c)=>a===n[c])?e:{...e,sessionRecency:n}}const r=new Set(n.slice(0,n.length-ao));let s=e.clearedVariantKeys;return s.some(o=>{const i=typeof o=="string"?Sn(o):null;return i!==null&&r.has(i[0])})&&(s=s.filter(o=>{const i=typeof o=="string"?Sn(o):null;return i===null||!r.has(i[0])})),{sessionModelSelections:cl(e.sessionModelSelections,r),sessionAgentSelections:cl(e.sessionAgentSelections,r),sessionAgentModelSelections:cl(e.sessionAgentModelSelections,r),sessionAgentModelVariantSelections:cl(e.sessionAgentModelVariantSelections,r),clearedVariantKeys:s,sessionRecency:n.slice(n.length-ao)}},Vg=(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=>Sn(n)?.[0]===t),uk=e=>{const t=wd(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=Sn(o);i&&r(i[0])}}return t},ul=(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,fk=(e,t)=>Array.isArray(e)?e.filter(n=>{if(typeof n!="string")return!0;const r=Sn(n);return r===null||t.has(r[0])}):e,hk=e=>{if(!la(e))return e;try{const t=uk(e),n=wd(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<=ao)return r?e:{...e,sessionRecency:t};const s=new Set(t.slice(t.length-ao));return{...e,sessionModelSelections:ul(e.sessionModelSelections,s),sessionAgentSelections:ul(e.sessionAgentSelections,s),sessionAgentModelSelections:ul(e.sessionAgentModelSelections,s),sessionAgentModelVariantSelections:ul(e.sessionAgentModelVariantSelections,s),clearedVariantKeys:fk(e.clearedVariantKeys,s),sessionRecency:t.slice(t.length-ao)}}catch{return e}},Bg=(e,t,n)=>{e.delete(t),e.set(t,n)},cs=(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}},Ix=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=cs(o,Up);i.failed&&(n=!0),(i.value.size>0||o.length===0)&&t.set(s,i.value)}return{value:t,failed:n}},_x=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[c,d]=a;if(typeof c!="string"||!Array.isArray(d)){n=!0;continue}const f=cs(d,ps);f.failed&&(n=!0),f.value.size>0&&i.set(c,f.value)}i.size>0&&t.set(s,i)}return{value:t,failed:n}},ss=()=>({models:new Map,agents:new Map,agentModels:new Map,variants:new Map,currentAgentContext:new Map}),$g=e=>{if(e===null)return{status:"missing",failed:!1,data:ss()};let t;try{t=JSON.parse(e)}catch{return{status:"failed",failed:!0,data:ss()}}if(!la(t))return{status:"failed",failed:!0,data:ss()};const n="state"in t?t.state:t;if(!la(n))return{status:"failed",failed:!0,data:ss()};const r=cs(n.sessionModelSelections??void 0,Up),s=cs(n.sessionAgentSelections??void 0,ps),o=Ix(n.sessionAgentModelSelections??void 0),i=_x(n.sessionAgentModelVariantSelections??void 0),a=cs(n.currentAgentContext??void 0,ps),c=r.failed||s.failed||o.failed||i.failed||a.failed;return{status:c?"failed":"ok",failed:c,data:{models:r.value,agents:s.value,agentModels:o.value,variants:i.value,currentAgentContext:a.value}}},pk=()=>{try{if(typeof window<"u"&&window.localStorage)return $g(window.localStorage.getItem(Dg))}catch{return{status:"failed",failed:!0,data:ss()}}try{return $g(id().getItem(Dg))}catch{return{status:"failed",failed:!0,data:ss()}}},mk=(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},_t=Et()(cd((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)=>{$s.add(n),Sh=!0,e(o=>{const i=new Map(o.sessionModelSelections);return i.delete(n),i.set(n,{providerId:r,modelId:s}),{...qr({...o,sessionModelSelections:i},[n]),lastUsedProvider:{providerID:r,modelID:s}}})},getSessionModelSelection:n=>t().sessionModelSelections.get(n)??null,saveSessionAgentSelection:(n,r)=>{t().sessionAgentSelections.get(n)!==r&&($s.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),qr({...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||(zs.add(lk(n,r)),e(a=>{const c=a.sessionAgentModelSelections.get(n)?.get(r);if(c?.providerId===s&&c?.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),qr({...a,sessionAgentModelSelections:d},[n])}))},getAgentModelForSession:(n,r)=>t().sessionAgentModelSelections.get(n)?.get(r)??null,saveAgentModelVariantForSession:(n,r,s,o,i)=>{const a=Hg(s,o),c=Fg(n,r,a);if(i===void 0){if(t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0){t().hasHydrated||(pr.add(c),e(f=>f.clearedVariantKeys.includes(c)?f:qr({...f,clearedVariantKeys:[...f.clearedVariantKeys,c]},[n])));return}pr.add(c),e(f=>{if(f.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0)return f;const u=new Map(f.sessionAgentModelVariantSelections),p=new Map(u.get(n)??new Map),m=new Map(p.get(r)??new Map);m.delete(a),m.size===0?p.delete(r):p.set(r,m),p.size===0?u.delete(n):(u.delete(n),u.set(n,p));const g=f.clearedVariantKeys.includes(c)?f.clearedVariantKeys:[...f.clearedVariantKeys,c];return qr({...f,sessionAgentModelVariantSelections:u,clearedVariantKeys:g},[n])});return}t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)!==i&&(pr.add(c),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),p=new Map(u.get(r)??new Map);return f.delete(n),p.set(a,i),u.set(r,p),f.set(n,u),qr({...d,sessionAgentModelVariantSelections:f},[n])}))},getAgentModelVariantForSession:(n,r,s,o)=>{const i=Hg(s,o);return t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(i)},forgetSession:n=>{if(!(!n||!Vg(t(),n))){$s.delete(n);for(const r of Array.from(zs))Lu(r)?.[0]===n&&zs.delete(r);for(const r of Array.from(pr))Sn(r)?.[0]===n&&pr.delete(r);e(r=>{if(!Vg(r,n))return r;let s=r.clearedVariantKeys;s.some(i=>Sn(i)?.[0]===n)&&(s=s.filter(i=>Sn(i)?.[0]!==n));let o=r.sessionRecency;return o.includes(n)&&(o=o.filter(i=>i!==n)),{sessionModelSelections:dl(r.sessionModelSelections,n),sessionAgentSelections:dl(r.sessionAgentSelections,n),sessionAgentModelSelections:dl(r.sessionAgentModelSelections,n),sessionAgentModelVariantSelections:dl(r.sessionAgentModelVariantSelections,n),clearedVariantKeys:s,sessionRecency:o}})}}}),{name:ik,version:ak,storage:vp(),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:la(e)?r=e:(n=!0,r=void 0);const s=cs(r?.sessionModelSelections??void 0,Up),o=cs(r?.sessionAgentSelections??void 0,ps),i=Ix(r?.sessionAgentModelSelections??void 0),a=_x(r?.sessionAgentModelVariantSelections??void 0);r!==void 0&&(n=n||s.failed||o.failed||i.failed||a.failed);let c=t.lastUsedProvider;if(r?.lastUsedProvider!==void 0){const w=r.lastUsedProvider;w===null||la(w)&&typeof w.providerID=="string"&&typeof w.modelID=="string"?c=w:n=!0}let d=[];if(r?.clearedVariantKeys!==void 0){const w=r.clearedVariantKeys;Array.isArray(w)&&w.every(ps)?d=[...w]:n=!0}const f=r?.contextStoreMigrationVersion===Og,u=f?{status:"missing",failed:!1,data:ss()}:pk(),p=u.failed,m=new Map(s.value),g=new Map(o.value),b=new Map(Array.from(i.value.entries()).map(([w,C])=>[w,new Map(C)])),y=new Map(Array.from(a.value.entries()).map(([w,C])=>[w,new Map(Array.from(C.entries()).map(([I,_])=>[I,new Map(_)]))])),S=new Set([...d,...t.clearedVariantKeys]);if(u.status==="ok"||u.status==="failed"){const w=u.data;for(const[C,I]of w.models)m.has(C)||m.set(C,I);for(const[C,I]of w.agents)g.has(C)||g.set(C,I);for(const[C,I]of w.currentAgentContext)g.has(C)||g.set(C,I);for(const[C,I]of w.agentModels){let _=b.get(C);_||(_=new Map,b.set(C,_));for(const[E,M]of I)_.has(E)||_.set(E,M)}for(const[C,I]of w.variants)for(const[_,E]of I)for(const[M,T]of E){if(S.has(Fg(C,_,M)))continue;let A=y.get(C);A||(A=new Map,y.set(C,A));let j=A.get(_);j||(j=new Map,A.set(_,j)),j.has(M)||j.set(M,T)}}for(const w of $s){const C=t.sessionModelSelections.get(w);C&&Bg(m,w,C);const I=t.sessionAgentSelections.get(w);I!==void 0&&Bg(g,w,I)}for(const w of zs){const C=Lu(w);if(!C)continue;const[I,_]=C,E=t.sessionAgentModelSelections.get(I)?.get(_);if(!E)continue;let M=b.get(I);M||(M=new Map,b.set(I,M)),M.set(_,E),b.delete(I),b.set(I,M)}for(const w of pr){const C=Sn(w);if(!C)continue;const[I,_,E]=C,M=t.sessionAgentModelVariantSelections.get(I)?.get(_)?.get(E);if(M!==void 0){let T=y.get(I);T||(T=new Map,y.set(I,T));let A=T.get(_);A||(A=new Map,T.set(_,A)),A.set(E,M)}else mk(y,I,_,E)}Sh&&t.lastUsedProvider!==null&&(c=t.lastUsedProvider);const v=new Set;for(const w of $s)v.add(w);for(const w of zs){const C=Lu(w);C&&v.add(C[0])}for(const w of pr){const C=Sn(w);C&&v.add(C[0])}const x=qr({sessionModelSelections:m,sessionAgentSelections:g,sessionAgentModelSelections:b,sessionAgentModelVariantSelections:y,clearedVariantKeys:Array.from(S),sessionRecency:wd(r?.sessionRecency)},Array.from(v)),k=f||!n&&!p;return ck(),{...t,sessionModelSelections:x.sessionModelSelections,sessionAgentSelections:x.sessionAgentSelections,sessionAgentModelSelections:x.sessionAgentModelSelections,sessionAgentModelVariantSelections:x.sessionAgentModelVariantSelections,lastUsedProvider:c,hasHydrated:!0,clearedVariantKeys:k?[]:x.clearedVariantKeys,sessionRecency:x.sessionRecency,contextStoreMigrationVersion:k?Og:t.contextStoreMigrationVersion}},migrate:e=>hk(e)}));if(typeof window<"u"){const e=_t.persist,t=()=>{_t.getState().hasHydrated||_t.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const qp=(e,t)=>`${e}::${t}`,Ro=Et(e=>({byKey:new Map,setEntry:t=>e(n=>{const r=new Map(n.byKey);return r.set(qp(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"&&sn(e=>{e.runtimeKey!==e.previousRuntimeKey&&e.previousRuntimeKey&&Ro.getState().clearForRuntime(e.previousRuntimeKey)});const gk=(e,t,n)=>{const r=J();Ro.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()})},Nu=e=>{Ro.getState().clearForSession(e)},Ru=()=>{Ro.getState().clearAll()},Zp=e=>{const t=J();return Ro.getState().byKey.get(qp(t,e))},yk=e=>Ro(t=>{if(e)return t.byKey.get(qp(J(),e))}),Wp=e=>{const t=["~"],n=r=>{const s=le(r);s&&!t.includes(s)&&t.push(s)};n(e);try{n($t().getItem("homeDirectory"))}catch{}try{typeof window<"u"&&n(window.__PICHAMBER_HOME__)}catch{}return t},vk=(e,t)=>{const n=le(e);return!!(n&&Wp(t).includes(n))},Ch=()=>({byId:new Map,byDirectory:new Map,listStatusByDirectory:new Map}),os=(e,t,n,r,s)=>{if(e.byId.has(t))return e;const o=Lr(n),i=s??Date.now(),a={id:t,directory:o,parentId:null,title:"",archived:!1,createdAt:i,updatedAt:i,lifecycle:r,hydrated:!1},c=new Map(e.byId);c.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:c,byDirectory:f}},Lr=e=>le(e)??e,ca=(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,Ex=(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&&ca(e.pendingInput,t.pendingInput),xk=(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])},bk=(e,t)=>e===t||!!e&&!!t&&e.attempt===t.attempt&&e.next===t.next&&e.message===t.message,wk=(e,t,n,r,s)=>{const o=Lr(t),i=[];let a=null,c=null;for(const m of n){const g=m?.session;if(!g?.id||!g.directory)continue;const b=Lr(g.directory);if(b!==o)continue;const y=typeof g.timeArchived=="number"?g.timeArchived>0:!!g.archived,S=e.byId.get(g.id),v=typeof m.updatedAt=="number"&&Number.isFinite(m.updatedAt)?m.updatedAt:typeof g.updatedAt=="number"&&Number.isFinite(g.updatedAt)?g.updatedAt:r,x=m.live&&s?.acceptLiveObservation?.(g.id,m.live.sequence)?m.live:void 0,k=x?x.lifecycle:S?.lifecycle??"idle",w=x?.lifecycle==="retry"?x.retry??{}:void 0,C=x?bk(S?.retry,w)?S?.retry:w:S?.retry,I=m.inputState&&s?.acceptPendingInputObservation?.(g.id,m.inputState.sequence)?m.inputState.pending:void 0,_=I==null||ad(I)?I:void 0,E=_!==void 0?_:S?.pendingInput,M={id:g.id,directory:b,parentId:g.parentId??null,title:g.title??"",archived:y,createdAt:g.createdAt,updatedAt:S?S.updatedAt:v,...typeof m.preview=="string"?{preview:m.preview}:{},...typeof g.messageCount=="number"?{messageCount:g.messageCount}:S?.messageCount!==void 0?{messageCount:S.messageCount}:{},lifecycle:k,...C?{retry:C}:{},...E!==void 0?{pendingInput:E}:{},hydrated:S?.hydrated??!1};if(S&&Ex(S,M)){i.push(g.id);continue}a||(a=new Map(e.byId),c=new Map(e.byDirectory)),a.set(g.id,M),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)),c||(c=new Map(e.byDirectory)),xk(a,c,o,i);let p=null;return e.listStatusByDirectory.get(o)!=="ready"&&(p=new Map(e.listStatusByDirectory),p.set(o,"ready")),{byId:a,byDirectory:c,listStatusByDirectory:p??e.listStatusByDirectory}},Sk=(e,t)=>{const n=Lr(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}},Ck=(e,t)=>{const n=Lr(t);if(e.listStatusByDirectory.get(n)==="failed")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"failed"),{...e,listStatusByDirectory:s}},Ds=(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}},Pu=(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}},Du=(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}},zg=(e,t,n,r)=>{const s=e.byId.get(t);if(!s){if(!r)return e;const i=os(e,t,r.directory,r.lifecycle,n),a=i.byId.get(t);if(!a||a.updatedAt===n)return i;const c=new Map(i.byId);return c.set(t,{...a,updatedAt:n}),{...i,byId:c}}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}},kk=(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}},zi=(e,t,n,r,s,o)=>{if(r!==null&&!ad(r))return e;const i=e.byId.get(t);if(i){if(ca(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=os(e,t,n,"idle"),c=a.byId.get(t);if(!c||ca(c.pendingInput,r))return a;const d=new Map(a.byId);return d.set(t,{...c,pendingInput:r}),{...a,byId:d}},Mk=(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 c of t.sessions)!c||typeof c.sessionId!="string"||c.sessionId.length===0||typeof c.directory!="string"||c.directory.length===0||i.has(c.sessionId)||(i.add(c.sessionId),ad(c.pending)&&o(c.sessionId,s)&&(a=zi(a,c.sessionId,c.directory,c.pending)));for(const[c,d]of a.byId)i.has(c)||d.pendingInput!=null&&o(c,s)&&(a=zi(a,c,d.directory,null));return a},Ik=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},_k=[],Gp=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?_k:(t.sort((n,r)=>n.pending.since-r.pending.since||(n.sessionId<r.sessionId?-1:n.sessionId>r.sessionId?1:0)),t)},Ek=(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||!ca(r.pending,s.pending))return!1}return!0},Ug=(e,t)=>{const n=e.byId.get(t.id);if(n&&Ex(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(c=>c!==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}},jk=(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}},qg=new WeakMap,Mr=e=>{const t=qg.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 qg.set(e,n),n},Zg=[],jx=(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},da=(e,t)=>{const n=t?.archived??!1,r=t?.directory;let s;if(typeof r=="string"&&r.length>0){const i=Lr(r),a=e.byDirectory.get(i)??[],c=Wp();if(!c.includes(i))s=a;else{const d=[],f=new Set(a);for(const u of c){if(u===i)continue;const p=e.byDirectory.get(u);if(p)for(const m of p)f.has(m)||(f.add(m),d.push(m))}s=d.length>0?[...a,...d]:a}}else{if(r===null||r==="")return Zg;s=[...e.byId.keys()]}const o=[];for(const i of s){const a=e.byId.get(i);a&&!!a.archived===n&&o.push(Mr(a))}return o.length===0?Zg:o},Tk=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n);return t},WZ=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("|")},Ou=(e,t,n,r,s,o,i)=>{const a=Lr(n),c=[],d=[],f=new Set;for(const O of r){const N=O?.session;!N?.id||!N.directory||Lr(N.directory)===a&&(f.has(N.id)||(f.add(N.id),c.push(N.id),d.push(O)))}const u=new Set(c),p=e.byDirectory.get(a)??[],m=t.byDirectory.get(a)??[],g=new Set(p),b=new Set;for(const O of g)t.byId.has(O)||b.add(O);const y=new Map,S=new Map,v=new Map,x=new Map,k=new Set,w=new Set;for(const O of p)w.add(O);for(const O of m)w.add(O);for(const O of c)w.add(O);for(const O of w){const N=t.byId.get(O);if(!N)continue;const D=e.byId.get(O);if(D===N)continue;if(N.directory!==a){D&&(D.directory===a||g.has(O)||u.has(O))&&k.add(O);continue}if(!D){if(u.has(O))continue;y.set(O,N);continue}const K=N.title!==D.title,V=N.archived!==D.archived;if(u.has(O)){(K||V)&&x.set(O,{rec:N,titleChanged:K,archivedChanged:V});continue}K||V?S.set(O,N):v.set(O,N)}const C=d.filter(O=>{const N=O.session.id;return!(b.has(N)||o?.has(N)||k.has(N))}),I=wk(t,a,C,s,i);let _=null;for(const[O,N]of x){const D=I.byId.get(O);if(!D){S.set(O,N.rec);continue}const K=N.titleChanged?N.rec.title:D.title,V=N.archivedChanged?N.rec.archived:D.archived;(D.title!==K||D.archived!==V)&&(_||(_=new Map(I.byId)),_.set(O,{...D,title:K,archived:V}))}if(y.size===0&&S.size===0&&v.size===0&&!_)return I;const E=_??I.byId,M=I.byDirectory.get(a)??[],T=new Set(M),A=new Map([...y,...S,...v]),j=[];for(const O of m)A.has(O)&&!T.has(O)&&j.push(O);let R=null;if(j.length>0){R=new Map(I.byDirectory),R.set(a,[...j,...M]),_||(_=new Map(E));for(const O of j){const N=A.get(O);N&&_.set(O,N)}}return!_&&!R?I:{byId:_??I.byId,byDirectory:R??I.byDirectory,listStatusByDirectory:I.listStatusByDirectory}},Ak=2,Lk=(e,t)=>Gf([...e],Ak,async n=>t(n)),Wg="*",xt="catalog",fl="dialogs",jt="chrome",Hu=16,Gg=2,Nk=5,Rk=300,Pk=new Set(["DAEMON_UNAVAILABLE","DAEMON_TIMEOUT","DAEMON_START_TIMEOUT","DAEMON_SPAWN_FAILED","DAEMON_REQUEST_FAILED"]),hl=e=>e==="busy"||e==="retry"?e:e==="error"?"error":"idle",Tx=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"},xn=e=>e instanceof lt?e:new lt("DAEMON_REQUEST_FAILED",e instanceof Error?e.message:void 0),ni=e=>e instanceof lt&&e.code==="INVALID_SESSION",Fu=e=>e instanceof lt&&e.code==="SESSION_IN_USE",Dk=e=>e instanceof lt&&e.code==="SESSION_RUNTIME_CONFLICT",Kg=async()=>{await new Promise(e=>setTimeout(e,Rk))},pl=(e=Ch())=>({directory:null,sessions:[],selectedSessionId:null,reducer:wc(),connection:"loading",error:null,showArchived:!1,hydratedSessionIds:new Set,sessionLoadErrorById:new Map,focusPending:!1,sessionsListStatus:"idle",catalog:e,syncReadiness:"ready",syncRecovery:{directories:[],residents:[]}}),Ok=(e,t,n)=>{const r=n?.now??Date.now(),s=t.byId.get(e.id),o=le(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}:{}}},Yg=(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 c=new Map(e.byId);return c.set(t,{...s,messageCount:r}),{...e,byId:c}}const o=os(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}},Hk=(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,c={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,...c};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:bc(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}:{}}:{},...c};if(o||a){for(const[f,u]of t.messages)(o||!d.messages.has(f))&&kS(d,f,u);for(const[f,u]of t.partOrder)if(!(!o&&d.partOrder.has(f))){d.partOrder.set(f,u);for(const p of u){const m=t.parts.get(p);m&&d.parts.set(p,m)}}for(const[f,u]of t.toolsByCallId)(o||!d.toolsByCallId.has(f))&&d.toolsByCallId.set(f,u)}return d};let Xg=null;const Fk=new Set(["session.snapshot","session.interrupted","session.deleted"]),Jg=e=>Tx(e)!==void 0||Fk.has(e.name),ri=e=>e.inputState?{pending:e.inputState.pending,sequence:e.lastSequence}:void 0,Ge=()=>(Xg??=new Kp,Xg),Vk=e=>Ge().subscribePendingInputTransitions(e);class Kp{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||le(r.directory)===le(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:(c,d)=>{if(!Number.isSafeInteger(d)||d<0)return!1;const f=Math.max(this.lifecycleSequenceById.get(c)??-1,this.hydratedSessionIds.has(c)?this.state.reducer.lastSequence.get(c)??-1:-1);if(d<f)return!1;if(this.pendingPromptById.has(c)){const u=this.promptGenerationById.get(c);return u!==void 0&&this.acceptedPromptGenerationById.get(c)===u&&o.add(c),!1}return s.add(c),!0}},commit:c=>{if(r===this.streamEpoch){for(const d of c)d.live?.lifecycle==="idle"&&o.has(d.session.id)&&this.reconcileAcceptedPromptFromList(d.session.id);if(s.size!==0)for(const d of c){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&&vn(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,c)=>{if(!Number.isSafeInteger(c)||c<0||c<(this.pendingInputSequenceById.get(a)??-1))return!1;const d=s.get(a);return(d===void 0||c>d)&&s.set(a,c),!0}},commit:a=>{if(r!==this.streamEpoch||s.size===0)return;const c=new Map;for(const d of a)d.inputState&&s.has(d.session.id)&&c.set(d.session.id,d.inputState.sequence);for(const[d,f]of s){const u=c.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:wc(),hydratedSessionIds:new Set(this.hydratedSessionIds)},this.queueSyncRecovery({directories:"all-known",residents:r}),r}handleVerifiedEpochChange(t){const n=this.applyVerifiedEpochChange(t);n&&this.emit([jt,xt,...[...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});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=Ik(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=Ds(t,n.id,"idle"),Cg(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=le(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=J(),r=this.streamEpoch,s=this.recoveryRevision,o=()=>t===this.runtimeGeneration&&n===J()&&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 Gf(a,Gg,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 p=await Ne.getSession(f,{directory:u,runtimeKey:n});if(!o()||p.session.id!==f)return;if(this.isDeleted(f)){this.recoveryResidents.delete(f);return}if(!this.isResponseEpochCurrent(p)||!o())return;const m=this.state.reducer.bySession.get(f);(!m||m.lastSequence<=p.lastSequence)&&((p.lifecycle==="busy"||p.lifecycle==="retry")&&typeof p.runStartedAt=="number"&&vn(p.session.id,p.runStartedAt,p.serverNow),this.commitSessionDetail(p)),this.recoveryResidents.delete(f)}catch(p){o()&&ni(p)&&(this.commitDeletion(f,u),this.recoveryResidents.delete(f))}this.publishSyncRecoveryState()}}),!o())return;const c=this.state.directory?le(this.state.directory):null,d=[...this.recoveryDirectories].sort((f,u)=>f===c?-1:u===c?1:0);await Gf(d,Gg,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===J()&&(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(s!==this.recoveryRevision||r!==this.streamEpoch)&&this.runSyncRecovery()}if(!(t!==this.runtimeGeneration||n!==J())&&(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<=Nk){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>Kp.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(k=>k.session.id===t)?.session.directory??this.state.reducer.bySession.get(t)?.directory;if(o&&o!=="global")try{tk({runtimeKey:J(),directory:o,sessionId:t})}catch{}try{_t.getState().forgetSession(t)}catch{}Cg(t),sC(t),Nu(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(k=>k.session.id===t),a=this.state.catalog.byId.get(t)?.pendingInput??null,c=this.state.catalog.byId.get(t)?.directory??n??"",d=this.state.sessions.filter(k=>k.session.id!==t),f=this.state.selectedSessionId===t?d.find(k=>!k.session.archived)?.session.id??null:this.state.selectedSessionId,u=new Map(this.state.reducer.bySession);u.delete(t);const p=new Map(this.state.reducer.lastSequence);s&&p.delete(s);const m=this.state.reducer.lastSequence.get(t);m!==void 0?p.set(t,m):p.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=jk(this.state.catalog,t),b=g!==this.state.catalog,y=f!==this.state.selectedSessionId;let S=this.state.sessionLoadErrorById;if(S.has(t)){const k=new Map(S);k.delete(t),S=k}const v=S!==this.state.sessionLoadErrorById;if(!i&&r&&!b&&!y&&!v)return!1;this.state={...this.state,sessions:d,selectedSessionId:f,hydratedSessionIds:new Set(this.hydratedSessionIds),reducer:{bySession:u,lastSequence:p},catalog:g,sessionLoadErrorById:S};const x=[`session:${t}`,jt];return b&&x.push(xt),this.emit(x),a!=null&&this.emitPendingInputTransitions([{type:"cleared",sessionId:t,directory:c,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 C8(t=>this.commitEvents(t));catalogCache;unsubscribeRuntime;constructor(t=B8()){this.catalogCache=t,this.state=pl(this.readCachedCatalog(J())),this.unsubscribeRuntime=sn(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=Wg)=>{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;subscribePendingInputTransitions=t=>(this.pendingInputTransitionListeners.add(t),()=>{this.pendingInputTransitionListeners.delete(t)});emitPendingInputTransitions(t){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.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=le(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(Mr(i))}s.length>0&&iC(s)}recordClusterConnectionChange(t,n){this.state.connection!==t&&br("pi-connection",{code:t,detail:(t==="error"||t==="unavailable")&&n?n.code:void 0})}dispose=()=>{this.catalogCache.flush(),this.resetLiveRuntimeState(),this.unsubscribeRuntime(),Ru(),this.navigationGenerationById.clear(),this.navigationCounter=0;const t=pl();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=xn(t);this.recordClusterConnectionChange("error",n),this.state={...this.state,error:n,connection:"error"},this.emitChrome(),this.ensureConnectionRecovery(n)};ensureConnectionRecovery(t){if(this.stream||!Pk.has(t.code))return;const n=this.runtimeGeneration,r=J(),s=this.streamGeneration+1;this.streamGeneration=s;const o=this.streamCursor();let i=null;i=yc({onEvent:()=>{},onAuthRequired:()=>this.handleStreamAuthRequired(),onReconnect:()=>{if(n!==this.runtimeGeneration||r!==J()||s!==this.streamGeneration||this.stream!==i)return;i?.dispose(),this.stream=null,this.streamGeneration+=1,this.streamReadyRevision+=1;const{directory:a,selectedSessionId:c}=this.state;this.start({...a?{directory:a}:{},...c?{sessionId:c}:{}})}},{...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.")),s7()}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={...pl(),connection:"ready"},Ru(),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=Mk(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([xt])),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=J(),r=Ne.listPendingInput({runtimeKey:n}).then(s=>{t!==this.runtimeGeneration||n!==J()||this.applyPendingInputList(s)},s=>{t!==this.runtimeGeneration||n!==J()||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:zi(t,n,r,s.pending)}async refreshDirectoryCatalog(t){const n=le(t);if(!n)return{ok:!1,error:xn(new lt("INVALID_ARGUMENT","directory is required"))};const r=J(),s=(this.directoryRefreshGenerationByDirectory.get(n)??0)+1;this.directoryRefreshGenerationByDirectory.set(n,s);const o=this.runtimeGeneration,i=this.state.catalog,a=Sk(this.state.catalog,n);a!==this.state.catalog&&(this.state={...this.state,catalog:a},this.emit([xt]));try{const c=await Ne.listSessions({directory:n,runtimeKey:r});if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==J())return{ok:!0};if(!this.isResponseEpochCurrent(c))throw new lt("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const d=this.filterDeletedListItems(c.sessions),f=this.createDirectoryListGates(c),u=Ou(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([xt]),this.raiseOrderingBaselinesForDirectory(n)):f.commit(d),{ok:!0}}catch(c){if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==J())return{ok:!0};const d=xn(c),f=Ck(this.state.catalog,n),u=le(this.state.directory)===n,p=[];return f!==this.state.catalog&&(this.state={...this.state,catalog:f},p.push(xt)),u&&(this.state={...this.state,error:d},p.push(jt)),p.length>0&&this.emit(p),{ok:!1,error:d}}}async refreshAllDirectoryCatalogs(t){const n=[...new Set(t)].map(d=>le(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 p=new Promise(m=>i.set(d,m));a.set(d,p),this.pendingCatalogPassByKey.set(f,p)}const c=Lk(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([c,...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 Ne.getSession(t.sessionId,{...r?{}:{directory:n??void 0},runtimeKey:J()});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 Ne.listProjects({runtimeKey:J()}),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 Ne.health({runtimeKey:J()});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,J()),this.emit([jt,xt]),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===J()&&r===this.streamGeneration,o=this.streamEpoch?this.streamCursor():void 0;this.stream=yc({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=le(r)===le(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 c=!!o&&this.hydratedSessionIds.has(o);this.state={...this.state,directory:r,sessions:[],selectedSessionId:c?o:o??null,sessionsListStatus:"loading",focusPending:!c,error:null},this.emitChrome(),c&&this.touchLastAccess(o),await this.resolveFocus(i,r,a)}async resolveFocus(t,n,r){const s=J(),o=this.runtimeGeneration,i=this.state.catalog;let a=this.pendingPreferredSessionId,c=n;try{try{const x=await Ne.selectProject(n,{runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;c=x.directory,le(c)!==le(this.state.directory)&&(this.state={...this.state,directory:c},this.emitChrome())}catch(x){if(!this.shouldRetryFocusError(x))throw x;if(await Kg(),t!==this.focusGeneration||o!==this.runtimeGeneration)return;c=(await Ne.selectProject(n,{runtimeKey:s})).directory,le(c)!==le(this.state.directory)&&(this.state={...this.state,directory:c},this.emitChrome())}const d=await this.fetchFocusListWithRetry(c,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,c)??a;let u=a?f.sessions.find(x=>x.session.id===a):void 0;if(a&&!u&&!this.isDeleted(a))try{const x=await Ne.getSession(a,{directory:c,runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;if(x?.session?.id)if(x.session.directory&&le(x.session.directory)!==le(c)&&t===this.focusGeneration){if(!this.newerSelection(r,c)){await this.focusProject(x.session.directory,a);return}}else f.sessions.unshift({session:x.session,updatedAt:x.session.updatedAt}),u={session:x.session,updatedAt:x.session.updatedAt}}catch(x){if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;ni(x)&&this.commitDeletion(a,c)}if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;const p=this.newerSelection(r,c),m=a&&!this.isDeleted(a),g=(p&&!this.isDeleted(p)?p:null)??u?.session.id??(m?a:f.sessions.find(x=>!x.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const b=this.createDirectoryListGates(d.payload),y=Ou(i,this.state.catalog,c,f.sessions,Date.now(),this.deletedSessionIds,b.options),S=y!==this.state.catalog;this.state={...this.state,sessions:f.sessions,selectedSessionId:g,sessionsListStatus:"ready",focusPending:!!g&&!this.hydratedSessionIds.has(g),error:null,catalog:y},b.commit(f.sessions);const v=[jt];S&&v.push(xt),this.emit(v),S&&this.raiseOrderingBaselinesForDirectory(c),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,xn(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 Ne.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:xn(o)};if(await Kg(),n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};try{const i=await Ne.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:xn(i)}}}}startTranscriptPrefetch(t,n,r,s){if(!t||this.isDeleted(t))return;const o=Ne.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(le(t)===le(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||le(this.userSelection.directory)===le(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=J(),a=this.state.catalog;this.pendingPreferredSessionId&&this.startTranscriptPrefetch(this.pendingPreferredSessionId,t,i,r);try{const c=await Ne.selectProject(t,{runtimeKey:i});if(r!==this.runtimeGeneration)return;const d={directory:c.directory,runtimeKey:i};c.directory!==t&&(this.state={...this.state,directory:c.directory},this.emitChrome());const f=await Ne.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([jt,xt])):this.adoptStreamEpoch(u);const p={state:"ready",protocolVersion:f.protocolVersion,capabilities:[...f.capabilities],...typeof f.streamEpoch=="string"?{streamEpoch:f.streamEpoch}:{}},m=await Ne.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),b=this.newerSelection(o,c.directory)??this.pendingPreferredSessionId??n;let y=b?g.find(E=>E.session.id===b):void 0,S=null;if(b&&!y&&!this.isDeleted(b))try{const E=await(this.takeTranscriptPrefetch(b,t,i,r)??Ne.getSession(b,{directory:t,runtimeKey:i}));if(r!==this.runtimeGeneration)return;if(E?.session?.directory&&E.session.directory!==t){if(r!==this.runtimeGeneration)return;if(!this.newerSelection(o,c.directory)){await this.open(E.session.directory,b);return}}else E?.session?.id&&(g.unshift({session:E.session,updatedAt:E.session.updatedAt}),y={session:E.session,updatedAt:E.session.updatedAt},S=E)}catch(E){if(r!==this.runtimeGeneration)return;ni(E)&&this.commitDeletion(b,t)}const v=this.newerSelection(o,c.directory),x=b&&!this.isDeleted(b),k=(v&&!this.isDeleted(v)?v:null)??y?.session.id??(x?b:g.find(E=>!E.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const w=this.createDirectoryListGates(m,{streamAttaching:!0}),C=Ou(a,this.state.catalog,c.directory,g,Date.now(),this.deletedSessionIds,w.options),I=C!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,sessions:g,selectedSessionId:k,connection:"ready",catalog:C},w.commit(g);const _=[jt];if(I&&_.push(xt),this.emit(_),I&&this.raiseOrderingBaselinesForDirectory(c.directory),this.refreshPendingInputList(),k){let E;k===b?E=S??await this.consumeTranscriptPrefetch(k,t,i,r):this.clearTranscriptPrefetch(),await this.hydrate(k,r,void 0,{initialHealth:p,initialSessions:g,...E?{initialDetail:E}:{}})}}catch(c){r===this.runtimeGeneration&&this.reportError(c)}}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&&le(r)!==le(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(le(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(le(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&&!Ze.getState().isInitialized){const u=await Ne.getSettings({directory:r,runtimeKey:J()});o??=u.pichamber.defaultModel,i=Q1({thinking:i,model:o,defaultThinkingByModel:u.pichamber.defaultThinkingByModel,defaultThinking:u.pichamber.defaultThinking})}else if(!i){const u=Ze.getState();i=Q1({model:o,defaultThinkingByModel:u.settingsDefaultThinkingByModel,defaultThinking:u.settingsDefaultThinking})}const a=await Ne.createSession({cwd:r,...t?{title:t}:{},...o?{model:o}:{},...i?{thinking:i}:{}},{directory:r,runtimeKey:J()});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 c=Ug(this.state.catalog,this.recordFromPiSession(a.session)),d=c!==this.state.catalog;this.state={...this.state,catalog:c};const f=[jt];return d&&f.push(xt),this.emit(f),await this.hydrate(a.session.id,s,a),a.session.id}async rename(t,n){const r=this.runtimeGeneration,s=J();if(await Ne.renameSession({sessionId:t,title:n},this.scope()),r!==this.runtimeGeneration||s!==J())return;const o=Date.now(),i=Du(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 c=[jt];a&&c.push(xt),this.emit(c)}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=J(),i=this.resolveSessionDirectory(t,r);if(await Ne.archiveSession({sessionId:t,archived:n},this.scope(i)),s!==this.runtimeGeneration||o!==J())return;const a=Date.now(),c=kk(this.state.catalog,t,n,a),d=c!==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:c};const f=[jt];d&&f.push(xt),this.emit(f)}async remove(t,n){const r=this.runtimeGeneration,s=J(),o=this.resolveSessionDirectory(t,n);if(await Ne.deleteSession({sessionId:t,ignoreMissing:!0},o?this.scope(o):this.scope()),r!==this.runtimeGeneration||s!==J())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(c=>c.session.id===t)?.session.title??this.state.catalog.byId.get(t)?.title??"",s=this.runtimeGeneration,o=J(),i=await Ne.forkSession({sessionId:t,...n?{messageId:n}:{}},this.scope());if(s!==this.runtimeGeneration||o!==J())return;this.upsertAndHydrate(i);const a=i.session.title?.trim()||r.trim()||"Untitled";if(!a.includes("(Fork)")){const c=`${a} (Fork)`;this.rename(i.session.id,c).catch(()=>{})}}async clone(t){const n=this.runtimeGeneration,r=J(),s=await Ne.cloneSession({sessionId:t},this.scope());n!==this.runtimeGeneration||r!==J()||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 c of s){const d=typeof c.text=="string"?c.text.trim():"";d&&o.set(c.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 c=await Ne.navigateSession(t,n,this.scope());if((this.navigationGenerationById.get(t)??0)!==a||i!==this.runtimeGeneration||!this.isResponseEpochCurrent(c))return c;const d=this.sessionFromDetail(c);this.commitNavigationSession(d,ri(c),c.session);const f=c.navigation;if(f&&typeof f.targetEntryId=="string"&&c.hasMoreBefore!==!0){const u=new Set(c.messages.map(y=>y.message.id)),p=s.filter(y=>!u.has(y.id)).map(y=>{const S=(o.get(y.id)??"").replace(/\s+/g," ").slice(0,120)||"[No text]",v=y.role==="assistant"?"assistant":"user";return{id:y.id,role:v,preview:S}}),m=Zp(t),g=new Set(p.map(y=>y.id)),b=[...p];for(const y of m?.abandoned??[])!u.has(y.id)&&!g.has(y.id)&&(b.push(y),g.add(y.id));b.length===0?Nu(t):gk(t,m?{...f,previousLeafId:m.previousLeafId}:f,b)}return c}catch(c){throw this.navigationGenerationById.get(t)===a&&(a<=1?this.navigationGenerationById.delete(t):this.navigationGenerationById.set(t,a-1)),c}}async prompt(t,n,r,s,o){const i=this.runtimeGeneration,a=o?.runtimeKey??J(),c={directory:this.resolveSessionDirectory(t,o?.directory),runtimeKey:a,...o?.streamEpoch?{streamEpoch:o.streamEpoch}:{}};if(a!==J())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!==J())throw new Error("Runtime changed before sending message.");d=this.state.reducer.bySession.get(t)}const u=o?.operationId??o7(),p={sessionId:t,text:n,operationId:u,messageId:`msg_${u}`,...s?.length?{attachments:s}:{}},m=d?{...d,lifecycle:"busy"}:{sessionId:t,directory:this.state.directory??this.state.sessions.find(k=>k.session.id===t)?.session.directory??"",lastSequence:this.state.reducer.lastSequence.get(t)??-1,lifecycle:"busy",messages:new Map,partOrder:new Map,parts:bc(),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 k=null;if(d)for(const w of d.messages.values())w.role==="user"&&(k=w.id);m.awaitingPromptEcho={baselineUserMessageId:k}}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 b=(this.promptGenerationById.get(t)??0)+1;this.promptGenerationById.set(t,b),this.pendingPromptById.add(t),this.promoteSession(t,"active",{reorder:!0}),this.touchSessionList(t);const y=Date.now(),S=zg(Ds(this.state.catalog,t,"busy"),t,y,{directory:m.directory||this.state.directory||"",lifecycle:"busy"}),v=S!==this.state.catalog;this.state={...this.state,catalog:S};const x=[`session:${t}`,jt];v&&x.push(xt),this.emit(x);try{let k;return r==="steer"?k=await Ne.sendSteer(p,c):r==="followUp"?k=await Ne.sendFollowUp(p,c):k=await Ne.sendPrompt(p,c),this.promptGenerationById.get(t)===b&&this.acceptedPromptGenerationById.set(t,b),Nu(t),r==="prompt"&&n.trimStart().startsWith("/")&&this.reconcileAcceptedSlashPrompt(t,b,i),k}catch(k){if(i7("prompt-send",k),i!==this.runtimeGeneration||a!==J())throw k;if(Fu(k)&&this.failSessionLoad(t,k),this.promptGenerationById.get(t)===b){this.pendingPromptById.delete(t);const w=this.state.reducer.bySession.get(t);if(w?.lifecycle==="busy"&&w.streamingMessages.size===0){const C=new Map(this.state.reducer.bySession);C.set(t,{...w,lifecycle:"error",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:C}},this.promoteSession(t,"settled"),this.emit([`session:${t}`,jt])}}throw k}}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 Ne.getSession(t,{directory:o,runtimeKey:J()});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"&&vn(i.session.id,i.runStartedAt,i.serverNow);const c=i.lifecycle!=="busy"&&i.lifecycle!=="retry"&&i.isStreaming!==!0;if(c){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),c}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=>Ne.abortSession({sessionId:t},this.scope());compact=(t,n)=>Ne.compactSession({sessionId:t,...n?{customInstructions:n}:{}},this.scope());setModel=(t,n,r)=>Ne.setSessionModel({sessionId:t,model:{providerId:n,modelId:r}},this.scope());setThinking=(t,n)=>Ne.setSessionThinking({sessionId:t,thinking:n},this.scope());tree=t=>Ne.getSessionTree(t,this.scope());providers=()=>Ne.listProviders({runtimeKey:J()});upload=t=>Ne.createAttachment(t,this.scope());uploadFile=(t,n)=>Ne.uploadAttachment(t,n,this.scope());deleteUpload=t=>Ne.deleteAttachment(t,this.scope());selected(){const t=this.state.selectedSessionId,n=t?this.state.reducer.bySession.get(t):void 0;return n?Av(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(c=>c.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=n8(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`,fl]))}sessionFromDetail(t){return Sc(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=J(),c=Ne.getSessionMessages(t,{before:i},{directory:r.directory,runtimeKey:a}).then(d=>{if(s!==this.runtimeGeneration||a!==J()||(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=Sc(d).session,p=new Map(u.messages);for(const[v,x]of f.messages)p.set(v,x);const m=new Map(u.partOrder);for(const[v,x]of f.partOrder)m.set(v,x);const g=bc(u.parts);for(const[v,x]of f.parts)g.set(v,x);const b=new Map(u.toolsByCallId);for(const[v,x]of f.toolsByCallId)b.set(v,x);const y={...f,messages:p,partOrder:m,parts:g,toolsByCallId:b,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,y),S.lastSequence.set(t,y.lastSequence),this.state={...this.state,reducer:S},this.touchLastAccess(t),this.emit([`session:${t}`]),y.hasMoreBefore===!0}).finally(()=>{this.historyInflightById.get(t)===c&&this.historyInflightById.delete(t)});return this.historyInflightById.set(t,c),c}recordFromPiSession(t,n){return Ok(t,this.state.catalog,n)}mergeHydratedSession(t,n){return Hk(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 c=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=hl(o.lifecycle);let u=this.state.catalog;u.byId.has(o.sessionId)||(u=os(u,o.sessionId,o.directory,f)),u=Pu(u,o.sessionId,!0),u=Ds(u,o.sessionId,f,o.retry),n&&(u=this.adoptDetailPendingInput(u,o.sessionId,o.directory,{pending:n.pending},n.sequence)),r&&(u=Yg(u,o.sessionId,o.directory,r.messageCount));const p=u!==this.state.catalog;this.state={...this.state,reducer:i,error:null,focusPending:c,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:d,catalog:u};const m=[`session:${o.sessionId}`,jt];p&&m.push(xt),this.emit(m),this.scheduleIdleEviction()}commitSessionDetail(t,n=[]){this.commitHydratedSession(this.sessionFromDetail(t),n,ri(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")&&Sg(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 v=vu(a,S);a=v.state,v.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 p=a.bySession.get(i.sessionId),m=p?.lifecycle,g=m?hl(m):void 0;u.byId.has(i.sessionId)||(u=os(u,i.sessionId,i.directory,g??"idle")),u=Pu(u,i.sessionId,!0),g!==void 0&&(u=Ds(u,i.sessionId,g,p?.retry)),s&&(u=Yg(u,i.sessionId,i.directory,s.messageCount));const b=u!==this.state.catalog;this.state={...this.state,reducer:a,error:null,focusPending:d,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:f,catalog:u};const y=[`session:${i.sessionId}`,jt,fl];b&&y.push(xt),this.emit(y),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=J(),c=!!(this.state.reducer.bySession.get(t)&&this.hydratedSessionIds.has(t)),d=this.navigationGenerationById.get(t)??0;if(!s?.force&&this.stream&&c&&!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 Ne.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"&&vn(w.session.id,w.runStartedAt,w.serverNow),this.commitSessionDetail(w);return}const u=[];let p=!1;const m=this.streamGeneration+1;this.streamGeneration=m;const g=()=>n===this.runtimeGeneration&&i===J()&&m===this.streamGeneration,b=w=>{g()&&(p?this.apply(w):u.push(w))},y=await f8({directory:o,selectedSessionId:t,runtimeKey:i,...s?.initialHealth?{initialHealth:s.initialHealth}:{},...s?.initialSessions?{initialSessions:s.initialSessions}:{},...s?.initialDetail?{initialDetail:s.initialDetail}:{},onEvent:b,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()){y.stream?.dispose();return}if(y.phase==="failed")throw y.stream?.dispose(),y.errors.at(-1)?.error??new lt("DAEMON_PROTOCOL_MISMATCH","The Pi runtime returned an incompatible bootstrap response.");const S=y.selectedSessionTiming;S&&S.sessionId===t&&(S.lifecycle==="busy"||S.lifecycle==="retry")&&typeof S.runStartedAt=="number"&&vn(S.sessionId,S.runStartedAt,S.serverNow);let v=r?this.sessionFromDetail(r):y.reducerState.bySession.get(t),x=r?ri(r):s?.initialDetail?ri(s.initialDetail):void 0,k=r?.session??s?.initialDetail?.session;if(r&&(r.lifecycle==="busy"||r.lifecycle==="retry")&&typeof r.runStartedAt=="number"&&vn(r.session.id,r.runStartedAt,r.serverNow),!v)try{const w=r??await Ne.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration){y.stream?.dispose();return}if(this.isDeleted(t)){y.stream?.dispose();return}if(!this.isResponseEpochCurrent(w)){y.stream?.dispose();return}(w.lifecycle==="busy"||w.lifecycle==="retry")&&typeof w.runStartedAt=="number"&&vn(w.session.id,w.runStartedAt,w.serverNow),x=ri(w),v=this.sessionFromDetail(w),k=w.session}catch(w){if(this.stream=y.stream,p=!0,n===this.runtimeGeneration&&ni(w)){this.handleInvalidSession(t,o,n,u);return}if(n===this.runtimeGeneration&&Fu(w)){u.length>0&&this.commitEvents(u),this.failSessionLoad(t,xn(w));return}throw y.stream?.dispose(),this.stream=null,w}if(v.sessionId!==t){y.stream?.dispose();return}if(this.isDeleted(t)){y.stream?.dispose();return}if((this.navigationGenerationById.get(t)??0)!==d){y.stream?.dispose();return}this.stream=y.stream,this.commitHydratedSession(v,u,x,k),p=!0}catch(u){if(n!==this.runtimeGeneration)return;if(ni(u)){this.handleInvalidSession(t,o,n);return}if(Fu(u)){this.failSessionLoad(t,xn(u));return}if(Dk(u)){try{const p=await Ne.getSession(t,{directory:o,runtimeKey:i});if(n!==this.runtimeGeneration||p.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(p)||(this.navigationGenerationById.get(t)??0)!==d)return;(p.lifecycle==="busy"||p.lifecycle==="retry")&&typeof p.runStartedAt=="number"&&vn(p.session.id,p.runStartedAt,p.serverNow),this.commitSessionDetail(p)}catch(p){if(n!==this.runtimeGeneration)return;this.failSessionLoad(t,xn(p))}return}if(f&&this.stream===f&&xn(u).code!=="DAEMON_AUTH_FAILED"){this.failSessionLoad(t,xn(u));return}this.reportError(u)}}markStreamReconnected(t,n,r){if(!(t!==this.runtimeGeneration||n!==J()||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(),c=()=>n===this.runtimeGeneration&&r===J()&&(this.streamGeneration===i||this.streamGeneration===i-1&&o===this.streamReadyRevision);let d=!1;try{let f=!1;const u=await y8({directory:this.directory(),sessionId:t,runtimeKey:r,lastKnownSequence:a,streamEpoch:this.streamEpoch??void 0,onEvent:p=>{c()&&(!f&&p.name==="session.snapshot"&&p.payload?.snapshot?.resync===!0&&(f=!0,this.queueSyncRecovery({directories:"all-known",residents:this.hydratedSessionIds})),this.apply(p))},onStreamDisconnect:()=>{c()&&this.reconnect(this.state.selectedSessionId??t,n,r)},onStreamReconnect:()=>this.markStreamReconnected(n,r,i),onAuthRequired:()=>{c()&&(d=!0,this.handleStreamAuthRequired())},onEpochChange:p=>{c()&&this.handleVerifiedEpochChange(p)}});if(n!==this.runtimeGeneration||r!==J()){u.stream?.dispose();return}if(o!==this.streamReadyRevision){u.stream?.dispose();return}if(u.phase==="ready"){typeof u.runStartedAt=="number"&&vn(t,u.runStartedAt,u.serverNow);let p=!1;typeof u.epoch=="string"&&u.epoch.length>0&&this.streamEpoch!==u.epoch&&(p=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=[],b=[];for(const[x,k]of u.reducerState.bySession.entries()){const w=m.bySession.get(x),C=this.mergeHydratedSession(k,w);m.bySession.set(x,C),m.lastSequence.set(x,C.lastSequence),this.touchLastAccess(x),g.push(x),(w?.lifecycle==="busy"||w?.lifecycle==="retry")&&C.lifecycle!=="busy"&&C.lifecycle!=="retry"&&b.push(x)}for(const x of u.reducerState.bySession.keys())this.hydratedSessionIds.add(x);let y=this.state.catalog;for(const x of g){const k=m.bySession.get(x);k&&(y=Ds(y,x,hl(k.lifecycle),k.retry))}const S=y!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,reducer:m,connection:"ready",error:null,hydratedSessionIds:new Set(this.hydratedSessionIds),...S?{catalog:y}:{}};const v=[jt,fl];for(const x of g)v.push(`session:${x}`);(S||p)&&v.push(xt),this.emit(v),this.refreshPendingInputList();for(const x of b)this.promoteSession(x,"settled");for(const x of g){if(!this.pendingPromptById.has(x))continue;const k=this.promptGenerationById.get(x);if(k===void 0||this.acceptedPromptGenerationById.get(x)!==k)continue;const w=u.reducerState.bySession.get(x)?.lifecycle;w==="busy"||w==="retry"||this.reconcileAcceptedPromptFromList(x)}this.scheduleIdleEviction(),p&&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"&&vn(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"&&vn(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.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),Sg(t,n),r?.reorder&&rC(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&&cx(t,a,o?.kind==="error"?{error:o.error??{}}:void 0),o&&dx({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 Ze.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,c=[],d=new Map,f=new Map;for(const y of t){if(y.name!=="session.deleted")continue;const S=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0,v=f.get(S)??new Set;v.add(y.sessionId),f.set(S,v)}let u=null;for(const y of t){const S=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0;if(!S&&this.streamEpoch!==null||S&&this.retiredStreamEpochs.has(S))continue;if(S&&this.streamEpoch!==null&&S!==this.streamEpoch){if(y.name!=="session.snapshot")continue;this.adoptStreamEpoch(S);const I=this.resetForEpochChange();if(n=wc(),o.clear(),u)for(const _ of I)u.add(_);else u=I;i.clear(),a.clear(),d.clear(),c.length=0,r=!1,s=!1}if(S&&this.adoptStreamEpoch(S),this.deletedSessionIds.has(y.sessionId))continue;if(y.name==="session.deleted"){const I=vu(n,y);if(n=I.state,!I.didApply)continue;r=!0,i.add(y.sessionId),c.push(y),d.set(y.sessionId,y.directory),o.delete(y.sessionId),this.restoringTranscriptById.delete(y.sessionId);continue}if(f.get(S)?.has(y.sessionId))continue;const v=!n.bySession.has(y.sessionId),x=(n.lastSequence.get(y.sessionId)??-1)>=0,k=vu(n,y);if(n=k.state,!k.didApply)continue;if(c.push(y),v&&x&&o.add(y.sessionId),y.name==="session.snapshot"&&o.add(y.sessionId),r=!0,i.add(y.sessionId),y.name==="extension.catalog"){const I=a.get(y.directory)??{providers:!1,resources:!1,commands:!1};a.set(y.directory,{providers:I.providers||y.payload.providers===!0,resources:I.resources||y.payload.resources===!0,commands:I.commands||y.payload.commands===!0})}this.notePromptProgress(y);const w=y.name==="session.error"||y.name==="session.interrupted"||y.name==="session.lifecycle"&&y.payload.state!=="busy"&&y.payload.state!=="retry",C=y.name==="assistant.message.start"&&y.payload.role==="user"||y.name==="session.snapshot";if(w||C){const I=n.bySession.get(y.sessionId);if(I?.awaitingPromptEcho!==void 0&&(w||!Mx(I))){const _=new Map(n.bySession);_.set(y.sessionId,{...I,awaitingPromptEcho:void 0}),n={...n,bySession:_}}}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){u&&(this.state={...this.state,reducer:n,hydratedSessionIds:new Set(this.hydratedSessionIds)},this.emit([jt,xt,...[...u].map(y=>`session:${y}`)]),this.queueSyncRecovery({directories:"all-known",residents:u}));return}this.state={...this.state,reducer:n,...u?{hydratedSessionIds:new Set(this.hydratedSessionIds)}:{}};for(const[y,S]of d)this.commitDeletion(y,S);for(const y of c)Jg(y)&&Number.isSafeInteger(y.sequence)&&(this.lifecycleSequenceById.get(y.sessionId)??-1)<y.sequence&&this.lifecycleSequenceById.set(y.sessionId,y.sequence);const p=this.applyCatalogFromEvents(c,n),m=p!==this.state.catalog,g=[];if(m){const y=this.state.catalog,S=new Map;for(const v of c){if(v.name!=="session.input")continue;const x=S.get(v.sessionId);x?x.push(v):S.set(v.sessionId,[v])}for(const[v,x]of S){const k=p.byId.get(v);if(!k)continue;const w=y.byId.get(v)?.pendingInput,C=k.pendingInput;let I=w;const _=[];for(const E of x){if(E.name!=="session.input")continue;const M=E.payload.pending,T=M===null?null:ad(M)?M:void 0;if(T===void 0)continue;const A=E.payload.serverNow,j=typeof A=="number"&&Number.isFinite(A)&&A>0?A:void 0,R=I!=null,O=T!=null;!R&&O&&T?_.push({type:"opened",sessionId:v,directory:k.directory??E.directory,pending:T,...j!==void 0?{serverNow:j}:{}}):R&&!O&&_.push({type:"cleared",sessionId:v,directory:k.directory??E.directory,pending:null}),I=T}if(ca(I,C))for(const E of _)g.push(E);else{const E=w!=null,M=C!=null;!E&&M&&C?g.push({type:"opened",sessionId:v,directory:k.directory,pending:C}):E&&!M&&g.push({type:"cleared",sessionId:v,directory:k.directory,pending:null})}}this.state={...this.state,catalog:p}}const b=[];(m||u)&&b.push(xt),c.some(y=>y.name==="extension.dialog"||y.name==="extension.dialog.dismiss"||y.name==="session.snapshot")&&b.push(fl);for(const y of i)b.push(`session:${y}`);b.length>0&&this.emit(b),this.emitPendingInputTransitions(g),c.some(y=>y.name==="session.input")&&this.requestNeedingSessionMetadataBackfill(c.filter(y=>y.name==="session.input").map(y=>y.sessionId)),s&&this.scheduleIdleEviction();for(const y of o)this.restoreTranscript(y);u&&this.queueSyncRecovery({directories:"all-known",residents:u});for(const[y,S]of a)S.providers&&this.requestProviderCatalogRefresh(y),S.commands&&zl(y),S.resources&&(Ec(),le(y)===le(this.state.directory??"")&&kr.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=Tx(s);if(a!==void 0&&!r.byId.has(s.sessionId)&&(r=os(r,s.sessionId,s.directory,a)),i!==void 0&&(this.hydratedSessionIds.has(s.sessionId)||Jg(s))&&(r=Ds(r,s.sessionId,hl(i),o?.retry)),s.name==="session.input"&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=zi(r,s.sessionId,s.directory,s.payload.pending,s.sequence)),s.name==="session.snapshot"){const c=s.payload.snapshot.inputState;c&&this.acceptPendingInputSequence(s.sessionId,s.sequence)&&(r=zi(r,s.sessionId,s.directory,c.pending,s.sequence))}if(s.name==="session.updated"){const c=typeof s.payload.title=="string"?s.payload.title.trim():"";if(c){r.byId.has(s.sessionId)||(r=os(r,s.sessionId,s.directory,a??"idle"));const d=r.byId.get(s.sessionId);r=Du(r,s.sessionId,c,d?.updatedAt??Date.now())}}if(s.name==="assistant.message.start"&&s.payload.role==="user"){r=zg(r,s.sessionId,Date.now(),{directory:s.directory,lifecycle:"busy"});const c=r.byId.get(s.sessionId),d=Pv(s.payload.text??"");d&&c&&c.title.trim().length===0&&(r=Du(r,s.sessionId,d,c.updatedAt))}}return r}scheduleIdleEviction(){this.evictionScheduled||this.state.reducer.bySession.size<=Hu||(this.evictionScheduled=!0,queueMicrotask(()=>{this.evictionScheduled=!1,this.evictIdleTranscripts()}))}evictIdleTranscripts(){const t=this.state.reducer.bySession;if(t.size<=Hu)return;const n=new Set;this.state.selectedSessionId&&n.add(this.state.selectedSessionId);for(const[p,m]of t)(m.lifecycle==="busy"||m.lifecycle==="retry")&&n.add(p),m.extensionDialogs.length>0&&n.add(p),this.state.catalog.byId.get(p)?.pendingInput!=null&&n.add(p);for(const p of this.pendingPromptById)n.add(p);const r=[];for(const p of t.keys()){if(n.has(p))continue;const m=this.lastAccessById.get(p)??0;r.push([p,m])}r.sort((p,m)=>p[1]-m[1]);let s=null,o=null,i=null,a=null;const c=[];let d=0;for(const[p]of r){if(t.size-d<=Hu)break;s||(s=new Map(t)),o||(o=new Set(this.hydratedSessionIds)),i||(i=new Map(this.lastAccessById)),s.delete(p),o.delete(p),i.delete(p),this.activityPhaseById.delete(p),a=a??this.state.catalog,a=Pu(a,p,!1),d+=1,c.push(p)}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=[jt];for(const p of c)u.push(`session:${p}`);f&&u.push(xt),this.emit(u)}async upsertAndHydrate(t){const n=this.runtimeGeneration,r=Ug(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=[jt];s&&o.push(xt),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:J()}}reconnectAfterTransportSwitch(){const t=this.state.selectedSessionId;!this.stream||!t||!this.state.directory||this.reconnect(t,this.runtimeGeneration,J())}resetForRuntime(){this.catalogCache.flush(),this.resetLiveRuntimeState(),this.state=pl(this.readCachedCatalog(J())),Ru(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()}emit(t){if(t.length===0)return;t.includes(xt)&&this.catalogCache.schedule(J(),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(Wg);if(r)for(const s of r)n.has(s)||(n.add(s),s())}readCachedCatalog(t){try{return this.catalogCache.read(t)??Ch()}catch{return Ch()}}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([jt])}}const lo=new Map,Qg=e=>{lo.set(e,(lo.get(e)??0)+1)},Bk=e=>(lo.get(e)??0)>0,$k=e=>{const t=lo.get(e)??0;return t<=0?!1:(t===1?lo.delete(e):lo.set(e,t-1),!0)};function Ax(){return da(Ge().getState().catalog,{archived:!1})}function Yp(){const e=Ge().getState().catalog;return[...da(e,{archived:!1}),...da(e,{archived:!0})]}function zk(e){const t=Ge().getState();return t.catalog.byId.get(e)?.directory??t.sessions.find(n=>n.session.id===e)?.session.directory??t.directory}function Uk(){return Tk(Ge().getState().catalog).map(e=>({id:e.id,title:e.title.trim()||null,directory:e.directory}))}function GZ(e,t){return[]}function KZ(e,t){return[]}const Xp=2048,e2=new WeakMap,qk=e=>e==="running"||e==="pending",Lx=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 Xp+1}},Zk=e=>{if(!e)return e;const t=e.patch??e.diff??e.filediff?.patch??e.filediff?.diff;if(Lx(t)<=Xp)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},Jp=(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=qk(e.tool?.state),r=t?.full===!0||n,s=!r&&Lx(e.tool?.output)>Xp,o=r?e.tool?.metadata:Zk(e.tool?.metadata),i=!!(!r&&(s||o?.deferredBody)),a=e.tool?.render;let c;return a&&(i&&a.resultExpanded!==void 0?c={...a.call!==void 0?{call:a.call}:{},...a.result!==void 0?{result:a.result}:{}}:c=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},...c!==void 0?{render:c}:{},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}},Wk=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}:{}}}),Gk=(e,t)=>{const n=[];if(e.parts.length>0){const i=e.parts.some(c=>c.type==="thinking"),a=e.parts.some(c=>c.type==="text");!i&&e.thinking&&n.push({id:`${e.id}:thinking`,type:"reasoning",text:e.thinking,streaming:!1}),n.push(...e.parts.map(c=>Jp(c))),!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}},Kk=e=>e?e.messages.map(t=>{const n=e2.get(t);if(n&&n.info.sessionID===e.sessionId)return n;const r=Gk(t,e.sessionId);return e2.set(t,r),r}):[],Yk=["chat","git","diff","terminal","files","diagram"],Xk=["settings","skills","providers","git-identities"],Sr={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Nx(e){const t=Jk();return{sessionId:Qk(t),tab:eM(t),settingsPath:tM(t),diffFile:nM(t)}}function Jk(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function Qk(e){const t=e.get(Sr.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 eM(e){const t=e.get(Sr.TAB);if(!t)return null;const n=t.toLowerCase().trim();return Yk.includes(n)?n:null}function tM(e){const t=e.get(Sr.SETTINGS);if(!t)return null;const n=t.toLowerCase().trim();return n.length===0?null:n==="pichamber"||n==="general"||n==="preferences"?"home":(Xk.includes(n),n)}function nM(e){const t=e.get(Sr.FILE);if(!t||t.trim().length===0)return null;try{return decodeURIComponent(t.trim())}catch{return t.trim()}}function YZ(){if(typeof window>"u")return!1;try{const e=new URLSearchParams(window.location.search);return/^\/(?:session|s)\/[^/?#]+/i.test(window.location.pathname)||e.has(Sr.SESSION)||e.has("s")||e.has(Sr.TAB)||e.has(Sr.SETTINGS)||e.has(Sr.FILE)}catch{return!1}}const Qp=(e,t)=>e?.open===!0&&t===null,XZ=e=>e.currentSessionId??(Qp(e.draft,e.currentSessionId)?null:e.piSelectedSessionId),rM=()=>{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)}},Rx="oc.lastSession.v1",sM=8,Vu=()=>({version:1,runtimes:{}}),em=e=>{try{const t=e.getItem(Rx);if(!t)return Vu();const n=JSON.parse(t);if(n.version!==1||!n.runtimes||typeof n.runtimes!="object")return Vu();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 Vu()}},Px=(e,t)=>{const n=Object.entries(t.runtimes).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,sM);try{e.setItem(Rx,JSON.stringify({...t,runtimes:Object.fromEntries(n)}))}catch{}};function oM(e,t,n=$t()){if(!t.sessionId)return;const r=em(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)},Px(n,r)}function kh(e,t=$t()){if(!e)return null;const n=em(t).runtimes[e];return n?{sessionId:n.sessionId,directory:n.directory}:null}function iM(e,t=$t()){if(!e)return;const n=em(t);n.runtimes[e]&&(delete n.runtimes[e],Px(t,n))}const aM=120,lM=600,Dx=typeof window<"u"&&typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"?window.__PICHAMBER_HARDWARE_KEYBOARD__:null;let Pc=Dx===!0,Sd=Dx!==null,Ui=null,Bu=!1;const Mh=new Set;Pc&&typeof document<"u"&&document.documentElement.classList.add("oc-hardware-keyboard");const Cd=()=>{Ui!==null&&(window.clearTimeout(Ui),Ui=null)},kd=e=>{if(Pc!==e){Pc=e,typeof document<"u"&&document.documentElement.classList.toggle("oc-hardware-keyboard",e);for(const t of Mh)t()}},cM=()=>{if(typeof window>"u")return()=>{};const e=n=>{Sd=!0,Cd(),kd(n)};if(typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"&&e(window.__PICHAMBER_HARDWARE_KEYBOARD__),Bu)return()=>{};Bu=!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),Bu=!1}},t2=e=>{Sd||!Number.isFinite(e)||(Cd(),kd(e>0&&e<aM))},dM=()=>{Sd||typeof window>"u"||typeof document>"u"||document.documentElement.classList.contains("oc-keyboard-open")||(Cd(),Ui=window.setTimeout(()=>{Ui=null,kd(!0)},lM))},uM=()=>{Cd(),!Sd&&kd(!1)},fM=()=>Pc,hM=e=>(Mh.add(e),()=>{Mh.delete(e)});function pM(){return h.useSyncExternalStore(hM,fM,()=>!1)}const Mo=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0?!0:window.location.protocol==="capacitor:",JZ=()=>{h.useEffect(()=>{if(!Mo())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"),Ox(),t.push(cM());const s=o=>{n.style.setProperty("--oc-keyboard-inset",`${Math.max(0,Math.round(o))}px`)};return ft(()=>import("./vendor-capacitor-status-bar-BsrUwiaA.js"),__vite__mapDeps([4,5,1,6])).then(async({StatusBar:o,Style:i})=>{if(e)return;const a=window.Capacitor?.getPlatform?.(),c=async()=>{if(a==="android"){const p=document.documentElement.classList.contains("dark"),m=(p?localStorage.getItem("splashBgDark"):localStorage.getItem("splashBgLight"))||(p?"#171515":"#fffdf4");await o.setOverlaysWebView({overlay:!1}).catch(()=>{}),await o.setBackgroundColor({color:m}).catch(()=>{}),await o.setStyle({style:p?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 c();const d=window.setTimeout(()=>{c()},400);t.push(()=>window.clearTimeout(d));const{App:f}=await ft(async()=>{const{App:p}=await import("./vendor-capacitor-app-BaupizkW.js");return{App:p}},__vite__mapDeps([7,8,5,1,6])),u=await f.addListener("appStateChange",({isActive:p})=>{p&&c()});if(e){u.remove();return}t.push(()=>{u.remove()})}).catch(()=>{}),ft(()=>import("./vendor-capacitor-keyboard-9BVxykO7.js"),__vite__mapDeps([9,5,1,6])).then(async({Keyboard:o})=>{if(e)return;if(window.Capacitor?.getPlatform?.()==="android"){const M=await o.addListener("keyboardWillShow",O=>{t2(O.keyboardHeight),n.classList.add("oc-keyboard-open"),window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),T=await o.addListener("keyboardDidShow",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),A=await o.addListener("keyboardWillHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-intent",{detail:{open:!1}})),n.classList.remove("oc-keyboard-open")}),j=await o.addListener("keyboardDidHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!1}}))}),R=()=>{M.remove(),T.remove(),A.remove(),j.remove()};if(e){R();return}t.push(R);return}await o.setAccessoryBarVisible({isVisible:!1}).catch(()=>{});const a=250,c=200,d="cubic-bezier(0.38, 0.7, 0.125, 1)";let f=null,u=null,p=0,m=!1,g=0,b=!1;const y=(M,T)=>{n.style.setProperty(M,`${Math.max(0,Math.round(T))}px`)},S=()=>{f!==null&&(window.clearTimeout(f),f=null)},v=(M,T)=>{window.dispatchEvent(new CustomEvent(M,{detail:T}))},x=()=>{const M=[],T=document.querySelector(".oc-mobile-composer");T&&M.push({el:T,factor:1});const A=document.querySelector(".oc-draft-center");return A&&M.push({el:A,factor:.5}),M},k=()=>{for(const{el:M}of x())M.style.transition="",M.style.transform=""},w=await o.addListener("keyboardWillShow",M=>{if(S(),t2(M.keyboardHeight),b=!0,p=M.keyboardHeight,!m){const A=document.querySelector(".oc-mobile-app-shell");g=A&&parseFloat(getComputedStyle(A).paddingBottom)||0}const T=Math.max(0,p-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(p);for(const{el:A,factor:j}of x())A.style.transition=`transform ${a}ms ${d}`,A.style.transform=`translateY(${-T*j}px)`;y("--oc-kb-scroll-inset",T),v("oc:keyboard-settled",{open:!0}),v("oc:keyboard-anim",{phase:"show",slide:T,durationMs:a,easing:d}),f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating"),y("--oc-kb-layout",p),m=!0,k(),v("oc:keyboard-settled",{open:!0}),u=window.setTimeout(()=>{u=null,n.classList.remove("oc-kb-caret-hold")},250)},a+20)}),C=()=>{if(!b)return;b=!1,S(),v("oc:keyboard-intent",{open:!1}),u!==null&&(window.clearTimeout(u),u=null),n.classList.remove("oc-kb-caret-hold");const M=Math.max(0,p-g);if(n.classList.remove("oc-keyboard-open"),s(0),y("--oc-kb-scroll-inset",0),m){n.classList.remove("oc-kb-animating"),y("--oc-kb-layout",0),m=!1;for(const{el:T,factor:A}of x())T.style.transition="none",T.style.transform=`translateY(${-M*A}px)`;document.querySelector(".oc-mobile-app-shell")?.offsetHeight}v("oc:keyboard-anim",{phase:"hide",slide:M,durationMs:c,easing:d}),n.classList.add("oc-kb-animating","oc-kb-hide");for(const{el:T}of x())T.style.transition=`transform ${c}ms ${d}`,T.style.transform="translateY(0px)";f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-animating","oc-kb-hide"),k(),v("oc:keyboard-settled",{open:!1})},c+20)},I=await o.addListener("keyboardWillHide",C),_=M=>M instanceof HTMLElement&&(M.tagName==="TEXTAREA"||M.tagName==="INPUT"||M.isContentEditable),E=M=>{b&&_(M.target)&&(_(M.relatedTarget)||window.setTimeout(()=>{b&&(_(document.activeElement)||C())},0))};if(document.addEventListener("focusout",E,!0),e){S(),document.removeEventListener("focusout",E,!0),w.remove(),I.remove();return}t.push(S,()=>{u!==null&&(window.clearTimeout(u),u=null)},()=>document.removeEventListener("focusout",E,!0),()=>{w.remove()},()=>{I.remove()})}).catch(()=>{}),()=>{e=!0,t.forEach(o=>o()),uM(),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")}},[])},QZ=e=>{const t=h.useRef(!1);h.useEffect(()=>{if(!Mo())return;let n=!1;const r=[],s=()=>{t.current&&(t.current=!1,e())},o=()=>{if(document.visibilityState==="hidden"){t.current=!0,br("app-lifecycle",{code:"hidden"});return}br("app-lifecycle",{code:"visible"}),s()};return document.addEventListener("visibilitychange",o),r.push(()=>document.removeEventListener("visibilitychange",o)),ft(()=>import("./vendor-capacitor-app-BaupizkW.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),br("app-lifecycle",{code:d?"resume":"pause"}),!d){t.current=!0;return}s()}),c=await i.addListener("resume",()=>{br("app-lifecycle",{code:"resume"}),s()});if(n){a.remove(),c.remove();return}r.push(()=>{a.remove()},()=>{c.remove()})}).catch(()=>{}),()=>{n=!0,r.forEach(i=>i())}},[e])},qi=[];let $u=null;const mM=()=>{for(let e=qi.length-1;e>=0;e--)try{if(qi[e]())return!0}catch{}return!1},Ox=()=>Mo()?($u||($u=ft(async()=>{const{App:e}=await import("./vendor-capacitor-app-BaupizkW.js");return{App:e}},__vite__mapDeps([7,8,5,1,6])).then(({App:e})=>e.addListener("backButton",()=>{mM()||e.minimizeApp().catch(()=>{})})).catch(()=>null)),$u.then(()=>{})):Promise.resolve(),eW=e=>{const t=h.useRef(e);t.current=e,h.useEffect(()=>{if(!Mo())return;Ox();const n=()=>t.current();return qi.push(n),()=>{const r=qi.lastIndexOf(n);r!==-1&&qi.splice(r,1)}},[])},Hx=h.createContext(null),ba=()=>h.useContext(Hx)??Ge(),tW=({children:e,directory:t})=>{const n=h.useMemo(()=>Ge(),[]),r=it(o=>o.projects.find(i=>i.id===o.activeProjectId)?.path??null),s=t?.trim()||r;return U.useEffect(()=>{const o=Nx(),i=pe.getState(),a=Qp(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&&!Mo()){const d=kh(J());if(d?.sessionId){n.start({sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.connectWithoutProject();return}const c=a?null:n.lastSelectedSessionForDirectory(s);if(c){n.start({directory:s,sessionId:c,sessionDirectoryKnown:!0});return}if(!a&&!Mo()){const d=kh(J());if(d?.sessionId){n.start({directory:s,sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.start({directory:s})},[n,s]),l.jsx(Hx.Provider,{value:n,children:e})},gM=e=>e;function qe(e,t,n="*",r=""){const s=ba(),o=U.useRef(e);o.current=e;const i=U.useRef(t);i.current=t;const a=U.useRef(null),c=`${n}\0${r}`;a.current?.key!==c&&(a.current={key:c,select:rM()});const d=U.useCallback(()=>{const u=o.current??gM,p=typeof i.current=="function"?i.current:Object.is;return a.current.select(s.getState(),u,p)},[s]),f=U.useMemo(()=>u=>s.subscribe(u,n),[s,n]);return U.useSyncExternalStore(f,d,d)}const Fx={type:"idle"},yM={type:"busy"},vM={type:"retry"},n2=new WeakMap,xM=[],bM=[],r2={loading:!1,complete:!0,status:"ready",cursor:void 0,error:null,errorCode:null},s2=[],o2=new WeakMap,Po="catalog",Cn="chrome",_n=e=>`session:${e}`,wM=(e,t)=>{if(e==="busy")return yM;if(e!=="retry")return Fx;if(!t)return vM;const n=n2.get(t);if(n)return n;const r={type:"retry",...t};return n2.set(t,r),r};function SM(e){const t=e?.archived??!1,n=e?.directory;return qe(r=>da(r.catalog,{archived:t,directory:n}),jx,Po)}function nW(e,t){return Md(e)}function rW(e){const t=qe(n=>n.catalog.byId,void 0,Po);if(e)return t.get(e)?.pendingInput}function Vx(){return qe(e=>Gp(e.catalog),Ek,Po)}function zu(e,t){Ge().select(t,e||void 0)}function tm(e,t){const n=Id(e);return U.useMemo(()=>n.map(r=>r.info),[n])}function CM(e,t,n){const r=qe(a=>e?a.reducer.bySession.get(e)??null:null,void 0,e?_n(e):"*"),s=qe(a=>e?null:a.reducer.bySession,void 0,e?_n(e):"*"),o=U.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 U.useMemo(()=>{if(!t||!i)return s2;const a=i.messages.get(t);if(!a)return s2;const c=i.partOrder.get(t)??[];if(c.length>0){const f=[];for(const u of c){const p=i.parts.get(u);if(!p)continue;const m=o2.get(p);if(m){f.push(m);continue}const g=Jp({id:p.id,type:p.type,text:p.text,streaming:p.streaming,...p.tool?{tool:p.tool}:{},...p.attachment?{attachment:p.attachment}:{}},{full:!0});o2.set(p,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 Md(e,t){const n=qe(s=>s.catalog.byId,void 0,Po);if(!e)return Fx;const r=n.get(e);return wM(r?.lifecycle,r?.retry)}function Bx(){return qe(e=>e.connection,void 0,Cn)}function kM(e){return qe(t=>e?t.reducer.bySession.get(e)?.compaction??null:null,void 0,e?_n(e):"*")}function $x(){const e=qe(t=>t.directory,void 0,Cn);return SM({archived:!1,directory:e||null})}function sW(e,t){const n=qe(s=>s.catalog.byId,void 0,Po),r=e?n.get(e)??null:null;return r?Mr(r):void 0}function MM(e){const t=qe(s=>s.catalog.byId,void 0,Po),n=qe(s=>s.directory,void 0,Cn);return(e?t.get(e)?.directory:void 0)??n??void 0}function IM(){return qe(e=>e.directory??"",void 0,Cn)}function _M(e,t){const n=qe(a=>a.hydratedSessionIds,void 0,Cn),r=qe(a=>a.selectedSessionId,void 0,Cn),s=qe(a=>a.connection,void 0,Cn),o=qe(a=>a.error,void 0,Cn),i=qe(a=>a.sessionLoadErrorById,void 0,Cn);return U.useMemo(()=>{if(!e||n.has(e))return r2;const c=i.get(e)??(s==="error"&&o?o:null);if(c)return{loading:!1,complete:!1,status:"error",cursor:void 0,error:c.message??"Session load failed",errorCode:c.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 zx(e,t){const n=qe(r=>r.hydratedSessionIds,void 0,Cn);return!e||n.has(e)}function EM(e){const t=qe(n=>e?n.reducer.bySession.get(e)??null:null,(n,r)=>Object.is(n,r)?!0:!n||!r?!1:rk(n,r),e?_n(e):"*");return U.useMemo(()=>{if(!t)return xM;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(c=>t.parts.get(c)).filter(c=>c?.type==="text").map(c=>c?.text??"").join(""):o.text??"";a&&n.push(a)}return n},[t])}function jM(e){return qe(t=>aa(e?t.reducer.bySession.get(e)??null:null),Object.is,e?_n(e):"*")}function TM(e){return qe(t=>Mx(e?t.reducer.bySession.get(e)??null:null),Object.is,e?_n(e):"*")}function Id(e,t,n){const r=n?.suspendPartUpdates!==!1,s=null,o=qe(a=>e?a.reducer.bySession.get(e)??null:null,(a,c)=>{if(Object.is(a,c))return!0;if(!a||!c)return!1;const d=aa(c);return d?wh(a,c,d):!1},e?_n(e):"*"),i=U.useRef(null);return U.useMemo(()=>{if(!o)return i.current=null,bM;const a=i.current,c=aa(o);if(c&&a&&a.sessionId===e&&wh(a.session,o,c))return i.current={sessionId:e,session:o,projection:a.projection,records:a.records},a.records;const d=Av(o,a&&a.sessionId===e?{session:a.session,projection:a.projection}:null),f=Kk(d),u=a?.records,p=u&&u.length===f.length&&u.every((m,g)=>m===f[g])?u:f;return i.current={sessionId:e,session:o,projection:d,records:p},p},[s,o,e,r])}function AM(e,t,n){const r=ba(),s=n&&e?_n(e):Cn,o=U.useMemo(()=>c=>r.subscribe(c,s),[r,s]),i=U.useCallback(()=>!n||!e||!t?null:r.getState().reducer.bySession.get(e)?.parts.get(t)??null,[n,t,e,r]),a=U.useSyncExternalStore(o,i,i);return U.useMemo(()=>!n||!a?null:Jp({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 LM(e,t){return qe(n=>e?n.reducer.bySession.get(e)?.messages.size??0:0,void 0,e?_n(e):"*")}function NM(e){const t=ba(),n=qe(o=>!!(e&&o.reducer.bySession.get(e)?.hasMoreBefore),void 0,e?_n(e):"*"),r=qe(o=>e?o.reducer.bySession.get(e)?.beforeCursor:void 0,void 0,e?_n(e):"*"),s=U.useCallback(()=>e?t.loadOlderMessages(e):Promise.resolve(!1),[e,t]);return{hasMoreBefore:n,beforeCursor:r,loadOlder:s}}function RM(e,t,n=!0){const r=ba();!n||!e||r.ensureHydrated(e)}const Dt=()=>Ge();async function PM(e,t,n,r){const s=await Dt().create(e,{...t?{directory:t}:{},...r?.model?{model:r.model}:{},...r?.thinking?{thinking:r.thinking}:{},...r?.select===!1?{select:!1}:{}}),o=Dt().getState().sessions.find(i=>i.session.id===s||i.session.id===Dt().getState().selectedSessionId);return o?Wk(o.session):null}async function DM(e,t){return await Dt().remove(e),!0}async function OM(e,t){const n=[],r=[];for(const s of e)try{await Dt().remove(s),n.push(s)}catch{r.push(s)}return{deletedIds:n,failedIds:r}}async function HM(e){return await Dt().archive(e,!0),!0}async function FM(e,t){for(const n of e)await Dt().archive(n,!0);return{archivedIds:e,failedIds:[]}}async function VM(e){return await Dt().archive(e,!1),!0}async function BM(e,t){for(const n of e)await Dt().archive(n,!1);return{restoredIds:e,failedIds:[]}}async function $M(e,t){await Dt().rename(e,t)}async function zM(e){return null}async function UM(e){return null}async function qM(e,t){const r=(await Dt().navigate(e,t))?.navigation?.editorText;if(typeof r=="string"&&r.length>0)try{Ke.getState().setPendingRevertText(r)}catch{}}async function ZM(e,t){if(!Zp(e))throw new Error("No reverted conversation is available to restore.");await Dt().navigate(e,t)}async function WM(e){const t=Zp(e)?.previousLeafId;if(!t)throw new Error("No reverted conversation is available to restore.");await Dt().navigate(e,t)}async function GM(e,t){await Dt().fork(e,t)}async function KM(){const e=Dt().getState();if(e.connection!=="ready")throw e.error??new Error("Pi runtime is unavailable")}async function YM(e,t){await Dt().compact(e,t)}function Ux(e){e&&Dt().abort(e)}const XM=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 i2(e){const t=Ge().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 Ih(e){const t=e.delivery==="steer"||e.delivery==="followUp"?e.delivery:"prompt",n=e.runtimeKey??J(),r=()=>{if(n!==J())throw new Error("Runtime changed before sending message.")};r();const s=Ge();let o=!1;if(e.sessionId&&e.providerID&&e.modelID){const c=i2(e.sessionId).model;(!c||c.providerId!==e.providerID||c.modelId!==e.modelID)&&(await s.setModel(e.sessionId,e.providerID,e.modelID),r(),o=!0)}if(e.sessionId&&Pt(e.variant)){const c=i2(e.sessionId).thinking;(o||c!==e.variant)&&(await s.setThinking(e.sessionId,e.variant),r())}const i=[...e.files??[],...(e.additionalParts??[]).flatMap(c=>c.files??[])].filter(c=>c.uploadState!==void 0||c.url.startsWith("data:")),a=[];try{const c=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:XM(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=c.length>0?c: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(c){throw typeof c=="object"&&c!==null&&c.name==="PiSendUnconfirmedError"||await Promise.all((n===J()?a:[]).map(d=>s.deleteUpload(d).catch(()=>{}))),c}}function JM(e){const t=le(e.session?.directory??e.currentDirectory??null);return{directory:t,source:t?"session":void 0}}function oW(e){return""}const Jl={id:null,open:!1,directoryOverride:null,branchIntent:null,worktreeIntent:null,parentID:null},qx=(e,t,n)=>!!(e.open&&e.id&&e.id===n&&t===null),Zx=e=>le(e.directory??null),Wx=$t(),Gx="oc.chatInput.lastDraftTarget",QM=()=>{try{const e=Wx.getItem(Gx);if(!e)return null;const t=JSON.parse(e);return{projectId:typeof t?.projectId=="string"?t.projectId:null,directory:le(typeof t?.directory=="string"?t.directory:null)}}catch{return null}},_h=e=>{try{Wx.setItem(Gx,JSON.stringify(e))}catch{}},eI=e=>{const t=Yp().find(s=>s.id===e),n=t?Zx(t):null;if(n)return le(n);const r=zk(e);return r?le(r):null},Dc=new Map,Uu=new Map,Gn=e=>(e??J()).trim()||"default",Eh=e=>({...e}),Os=(e,t)=>{const n=Dc.get(e);Dc.set(e,{sessionId:n?.sessionId??null,directory:n?.directory??null,draft:n?.draft?Eh(n.draft):{...Jl},...t})},tI=e=>{const t=Gn(),n=Dc.get(t),r=kh(t);return{runtime:n?.sessionId===e?le(n.directory):null,persisted:r?.sessionId===e?le(r.directory):null}};let _d=null;const a2=()=>_d,nI=e=>{_d=e},l2=()=>{_d=null},rI=(e,t)=>({session:Yp().find(n=>n.id===e)??null,currentDirectory:e===_d?null:le(t)}),c2=(e,t=null)=>e?JM(rI(e,t))?.directory??null:null,jh=async e=>{await Ze.getState().activateDirectory(le(e))},Zi=(e,t)=>!e||!t?!1:e.runtimeKey===t.runtimeKey&&le(e.directory)===le(t.directory)&&e.branch===t.branch;async function sI(e,t){const n=t.getState(),r=e.draftSnapshot??n.newSessionDraft;if(!r?.open)return null;if(r.branchIntent){const g=le(r.branchIntent.directory),b=le(r.directoryOverride);if(r.branchIntent.runtimeKey!==J()||g!==b)throw new Error("The selected branch no longer matches this draft target.");if(!Zi(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||le(g.projectRoot)!==le(r.worktreeIntent.projectRoot)||le(g.sourceDirectory)!==le(r.worktreeIntent.sourceDirectory)||g.startRef!==r.worktreeIntent.startRef||!le(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,c=r.title||(e.initialPrompt&&!e.initialPrompt.trimStart().startsWith("/")?Pv(e.initialPrompt):void 0),d=await n.createSession(c,i,r.parentID??null,{model:e.providerID&&e.modelID?{providerId:e.providerID,modelId:e.modelID}:void 0,thinking:Pt(e.variant)?e.variant:void 0,select:!1},{draftSnapshot:r,closeDraft:!1});if(!d?.id)throw new Error("Failed to create session");const f=le(d.directory??i??null),u=t.getState().newSessionDraft===r&&t.getState().currentSessionId===null;u&&_h({projectId:a,directory:f});const p=r.syntheticParts;u&&jh(f).catch(g=>{console.warn("Failed to activate directory after creating session:",g)});const m=o;return _t.getState().saveSessionModelSelection(d.id,e.providerID,e.modelID),m&&(_t.getState().saveSessionAgentSelection(d.id,m),_t.getState().saveAgentModelForSession(d.id,m,e.providerID,e.modelID),_t.getState().saveAgentModelVariantForSession(d.id,m,e.providerID,e.modelID,e.variant)),u&&n.setCurrentSession(d.id,f),s&&ft(async()=>{const{usePermissionStore:g}=await import("./permissionStore-B9Hkrqny.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:p}}let d2=0;const oI=()=>(d2+=1,`draft-${Date.now()}-${d2}`);async function Kx(e){return sI(e,pe)}const pe=Et()((e,t)=>({currentSessionId:null,currentSessionDirectory:null,newSessionDraft:{...Jl},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=Gn();Uu.set(s,n);const o=tt.getState(),i=c2(n),a=Ge().getState().directory??o.currentDirectory??null,c=(r?le(r):null)??i,d=c??a,f=c===null,u=it.getState(),p=d?er(u.projects,Hn(u.projects,rn.getState()),d):null;e({currentSessionId:n,currentSessionDirectory:n?d??null:null}),nI(f&&n?n:null);const m=f?null:d??null;Os(s,{sessionId:n,directory:m}),n&&oM(s,{sessionId:n,directory:m}),n&&Ge().select(n,f?void 0:d);try{d&&o.currentDirectory!==d&&o.setDirectory(d,{showOverlay:!1}),p&&u.activeProjectId!==p.id&&u.setActiveProjectIdOnly(p.id)}catch(g){console.warn("Failed to set Pi directory for session switch:",g)}n&&(yd(n),zu(d??"",n))},prepareForRuntimeSwitch:n=>{const r=Gn(n),s=tt.getState().currentDirectory||null,o=t().currentSessionId;Uu.set(r,t().currentSessionId),Os(r,{sessionId:o,directory:s,draft:Eh(t().newSessionDraft)})},restoreForRuntimeSwitch:n=>{const r=Gn(n),s=Dc.get(r),o=s?.sessionId??Uu.get(r)??null,i=s?.draft?Eh(s.draft):{...Jl},a=s?.directory??null;a&&tt.getState().setDirectory(a,{showOverlay:!1}),e({currentSessionId:o,currentSessionDirectory:o?a:null,newSessionDraft:o?{...Jl}:i,abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,sendingNewSessionDraftId:null,sessionAbortFlags:new Map,pendingChangesBarDismissed:new Map}),o?zu(a??Ge().getState().directory??"",o):zu("","")},openNewSessionDraft:n=>{n?.automatic||iM(Gn());const r=it.getState(),s=r.projects,o=Hn(s,rn.getState()),i=r.getActiveProject(),a=le(tt.getState().currentDirectory??null),c=QM(),d="__home__",f=n?.selectedProjectId===d,u=n?.directoryOverride!==void 0?le(n.directoryOverride):null,p=n?.selectedProjectId?f?{id:d,path:u??""}:s.find(_=>_.id===n.selectedProjectId)??null:null,m=er(s,o,u),g=i||(r.activeProjectId?s.find(_=>_.id===r.activeProjectId)??null:s[0]??null),b=c?.projectId===d,y=c?.projectId?b?{id:d,path:c.directory??""}:s.find(_=>_.id===c.projectId)??null:null,S=er(s,o,c?.directory??null),v=er(s,o,a),x=f||p?p:u!==null?m:a?v:b?y:S??y??g,k=u!==null?u:f?u??le(tt.getState().homeDirectory||$t().getItem("homeDirectory")||"~")??u:p?le(p.path??null):a||(c?.directory?c.directory:le(x?.path??null)),w=f?d:x?.id??null;_h({projectId:w,directory:k});const C={id:oI(),open:!0,selectedProjectId:w,directoryOverride:k,branchIntent:n?.branchIntent&&n.branchIntent.runtimeKey===J()&&le(n.branchIntent.directory)===k?n.branchIntent:null,worktreeIntent:n?.worktreeIntent&&n.worktreeIntent.runtimeKey===J()&&le(n.worktreeIntent.sourceDirectory)===k?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:{...C},currentSessionId:null,currentSessionDirectory:null,error:null}),Os(Gn(),{sessionId:null,directory:k,draft:C}),n?.initialPrompt&&Ke.getState().setPendingInputText(n.initialPrompt);const I=le(x?.path??null)??k;jh(I),k&&k!==tt.getState().currentDirectory&&tt.getState().setDirectory(k)},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}),Os(Gn(),{draft:r})},setNewSessionDraftTarget:n=>{let r=null,s=null;e(o=>{r=le(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"),c=le(o.newSessionDraft.directoryOverride),d=r!==c,f=s!==(o.newSessionDraft.selectedProjectId??null),u=n.branchIntent,p=u&&u.runtimeKey===J()&&le(u.directory)===r?u:null,m=n.worktreeIntent,g=m&&m.runtimeKey===J()&&le(m.sourceDirectory)===r?m:null;return{newSessionDraft:{...o.newSessionDraft,selectedProjectId:s,directoryOverride:n.directoryOverride??o.newSessionDraft.directoryOverride,branchIntent:i?p:d||f?null:o.newSessionDraft.branchIntent,worktreeIntent:a?g:d||f?null:o.newSessionDraft.worktreeIntent}}}),_h({projectId:s,directory:r}),jh(r),r&&r!==tt.getState().currentDirectory&&tt.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,c,d,f,u)=>{const p=u?.target;if(p&&p.runtimeKey!==J())throw new Error("Message was not sent because the runtime changed.");const m=p?.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,b=typeof o=="string"&&o.trim().length>0?o.trim():void 0;if(!p&&!u?.sessionId&&(u?.draftSnapshot?.open||g?.open)){const w=await Kx({providerID:r,modelID:s,agent:b,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 C=w.syntheticParts?.length?[...c||[],...w.syntheticParts]:c;Qg(w.sessionId);const I=i?.map(_=>({type:"file",mime:_.mimeType,url:_.dataUrl,filename:_.filename,uploadState:_.uploadState}));await Ih({sessionId:w.sessionId,directory:w.directory,content:n,providerID:r,modelID:s,agent:w.agent,agentMentionName:a,variant:d,inputMode:f,files:I,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,knownEmptyTranscript:!0,additionalParts:C?.map(_=>({text:_.text,synthetic:_.synthetic,files:_.attachments?.map(E=>({type:"file",mime:E.mimeType,url:E.dataUrl,filename:E.filename,uploadState:E.uploadState}))}))});return}const y=p?.sessionId??u?.sessionId??t().currentSessionId,S=y?_t.getState().getSessionAgentSelection(y):null,v=b||S||void 0;y&&_t.getState().saveSessionModelSelection(y,r,s),y&&v&&(_t.getState().saveSessionAgentSelection(y,v),_t.getState().saveAgentModelForSession(y,v,r,s),_t.getState().saveAgentModelVariantForSession(y,v,r,s,d));const x=y?le(p?.directory??u?.directory??t().getDirectoryForSession(y)):null;y&&Qg(y);const k=i?.map(w=>({type:"file",mime:w.mimeType,url:w.dataUrl,filename:w.filename,uploadState:w.uploadState}));await Ih({runtimeKey:p?.runtimeKey,sessionId:y||"",directory:x,content:n,providerID:r,modelID:s,agent:v,agentMentionName:a,variant:d,inputMode:f,files:k,delivery:u?.delivery,operationId:u?.operationId,streamEpoch:u?.streamEpoch,additionalParts:c?.map(w=>({text:w.text,synthetic:w.synthetic,files:w.attachments?.map(C=>({type:"file",mime:C.mimeType,url:C.dataUrl,filename:C.filename,uploadState:C.uploadState}))}))})},createSession:async(n,r,s,o,i)=>{const a=i?.draftSnapshot??t().newSessionDraft,c=a.targetFolderId;try{const d=r??Ge().getState().directory,f=await PM(n,d,s??null,o);if(!f)return null;if(i?.closeDraft!==!1&&t().newSessionDraft===a&&t().closeNewSessionDraft(),c){const u=r||f.directory;u&&zp.getState().addSessionToFolder(u,c,f.id)}return f}catch(d){return console.error("[session-ui-store] createSession failed",d),null}},deleteSession:async(n,r)=>{const s=await DM(n);return s&&t().currentSessionId===n&&t().openNewSessionDraft(),s},deleteSessions:async(n,r)=>{const s=await OM(n),o=t().currentSessionId;return o&&s.deletedIds.includes(o)&&t().openNewSessionDraft(),s},archiveSession:n=>HM(n),archiveSessions:(n,r)=>FM(n),unarchiveSession:n=>VM(n),unarchiveSessions:(n,r)=>BM(n),updateSessionTitle:async(n,r)=>{await $M(n,r)},shareSession:async n=>zM(),unshareSession:async n=>UM(),revertToMessage:async(n,r)=>{await qM(n,r)},restoreToMessage:async(n,r)=>{await ZM(n,r)},handleSlashUndo:async n=>{const r=Ge().getState().reducer.bySession.get(n),o=(r?[...r.messages.values()]:[]).filter(c=>c.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 ft(async()=>{const{toast:c}=await import("./vendor-boot-EC6IyLt1.js").then(d=>d.ck);return{toast:c}},__vite__mapDeps([5,1,6]));a.success("Reverted — conversation rewound. Files on disk were not changed.")},handleSlashRedo:async n=>{await WM(n);const{toast:r}=await ft(async()=>{const{toast:s}=await import("./vendor-boot-EC6IyLt1.js").then(o=>o.ck);return{toast:s}},__vite__mapDeps([5,1,6]));r.success("Restored all messages")},forkFromMessage:async(n,r)=>{await GM(n,r)},getSessionsByDirectory:n=>{const r=le(n);return r?Yp().filter(o=>Zx(o)===r):[]},getDirectoryForSession:n=>{const r=n===t().currentSessionId?t().currentSessionDirectory:null,s=c2(n,r);if(s)return s;try{return Ge().getState().catalog.byId.get(n)?.directory??null}catch{return null}},adoptAuthoritativeSessionDirectory:n=>{const r=n??t().currentSessionId;if(!r||r!==a2()||r!==t().currentSessionId)return;const s=eI(r);s&&(l2(),s!==t().currentSessionDirectory&&e({currentSessionDirectory:s}),Os(Gn(),{sessionId:r,directory:s}))},setSessionDirectory:(n,r)=>{const s=le(r);n===a2()&&l2(),n===t().currentSessionId&&(e({currentSessionDirectory:s}),Os(Gn(),{sessionId:n,directory:s}))}})),iW=Object.freeze(Object.defineProperty({__proto__:null,draftBranchCheckoutReceiptMatches:Zi,getRememberedSessionDirectory:tI,materializeOpenDraftSession:Kx,routeMessage:Ih,useSessionUIStore:pe},Symbol.toStringTag,{value:"Module"}));async function ir(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 iI(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 ir(e)}const nm=U.createContext(void 0);function Vn(){const e=U.useContext(nm);if(!e)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return e}function Yx(){return U.useContext(nm)}const Xx=async(e,t)=>{if(!a7())throw new Error("Desktop runtime is not available");return Qn(e,t)},aI=async e=>{if(bt())try{await Xx("desktop_set_window_title",{title:e})}catch{}},lI=async(e,t)=>{if(bt())try{await Xx("desktop_set_window_theme",{themeMode:e,themeVariant:t})}catch{}},qu=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 cI{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=qu(t.colors.surface.muted),s=qu(t.colors.surface.subtle),o=qu(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,c=i?.1:.3;if(r)n.push(` --sidebar-overlay-strong: rgb(${r} / ${a}) !important;`),n.push(` --sidebar-overlay-soft: rgb(${r} / ${c}) !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,c)} !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=l7;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 u2=(e,t)=>t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e),dI=e=>typeof e=="string"&&e.trim().length>0,f2=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(!dI(u2(e,r)))return!1;const n=u2(e,["metadata","variant"]);return n==="light"||n==="dark"},uI=u7,fI=d7,hI=e=>h7(e==="dark"),pI=typeof window<"u"?h.useLayoutEffect:h.useEffect,mI=()=>{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")}},gI=e=>{let t=uI,n=fI,r="system";if(typeof window<"u"){const s=localStorage.getItem("themeMode"),o=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),a=localStorage.getItem("useSystemTheme"),c=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(c){const u=P1(c);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=P1(e);s&&(s.metadata.variant==="light"?t=s.metadata.id:n=s.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function aW({children:e,defaultThemeId:t}){const n=U.useMemo(()=>new cI,[]),[r,s]=U.useState(()=>gI(t)),[o,i]=U.useState(()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches),[a,c]=U.useState([]),[d,f]=U.useState([]),[u,p]=U.useState(!1),m=U.useMemo(()=>bt(),[]),g=U.useRef(0),b=U.useMemo(()=>{const A=[],j=new Set,R=O=>{const N=O.metadata.id;j.has(N)||(j.add(N),A.push(O))};return a.forEach(R),d.forEach(R),c7.forEach(R),A},[a,d]);U.useEffect(()=>{const A=j=>{const R=j.detail;if(!f2(R))return;const O=f7(R);f(N=>{const D=N.findIndex(V=>V.metadata.id===O.metadata.id);if(D<0)return[...N,O];const K=[...N];return K[D]=O,K})};return window.addEventListener("pichamber:theme-hmr",A),()=>window.removeEventListener("pichamber:theme-hmr",A)},[]);const y=U.useCallback(A=>b.find(j=>j.metadata.id===A),[b]),S=U.useCallback((A,j)=>{const R=y(A);return R&&R.metadata.variant===j?R:b.find(N=>N.metadata.variant===j)??hI(j)},[b,y]),v=U.useMemo(()=>r.themeMode==="light"?S(r.lightThemeId,"light"):r.themeMode==="dark"||o?S(r.darkThemeId,"dark"):S(r.lightThemeId,"light"),[S,r,o]),x=U.useCallback(async()=>{if(typeof window>"u")return;const A=J(),j=++g.current;p(!0);try{const R=await Tt("/api/pi/themes",{method:"GET",credentials:ld()?"omit":"include",headers:{Accept:"application/json"}});if(R.status===401||!R.ok)return;const O=await R.json();if(j!==g.current||A!==J())return;const D=(Array.isArray(O?.themes)?O.themes:[]).filter(f2);c(D)}catch{}finally{j===g.current&&A===J()&&p(!1)}},[]);U.useEffect(()=>{x()},[x]),U.useEffect(()=>sn(A=>{A.runtimeKey!==A.previousRuntimeKey&&(g.current+=1,c([]),p(!1),x())}),[x]);const k=U.useCallback(A=>{if(typeof document>"u")return;const j=A.colors.surface.background;document.body.style.backgroundColor=j;let R=document.querySelector('meta[name="theme-color"]');R||(R=document.createElement("meta"),R.setAttribute("name","theme-color"),document.head.appendChild(R)),R.setAttribute("content",j);const O=A.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let N=document.querySelector(`meta[name="theme-color"][media="${O}"]`);N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),N.setAttribute("media",O),document.head.appendChild(N)),N.setAttribute("content",j)},[]),w=U.useRef(!1);pI(()=>{if(typeof window>"u")return;const A=w.current?mI():void 0;w.current=!0,n.apply(v),k(v);const j=document.documentElement;return j.classList.remove("light","dark"),j.classList.add(v.metadata.variant),A},[n,v,k]),U.useEffect(()=>{if(r.themeMode!=="system"||typeof window>"u")return;const A=window.matchMedia("(prefers-color-scheme: dark)"),j=R=>{i(R.matches)};return i(A.matches),A.addEventListener("change",j),()=>A.removeEventListener("change",j)},[r.themeMode]),U.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",v.metadata.id),localStorage.setItem("selectedThemeVariant",v.metadata.variant==="light"?"light":"dark");const A=S(r.lightThemeId,"light"),j=S(r.darkThemeId,"dark");localStorage.setItem("splashBgLight",A.colors.surface.background),localStorage.setItem("splashFgLight",A.colors.surface.foreground),localStorage.setItem("splashBgDark",j.colors.surface.background),localStorage.setItem("splashFgDark",j.colors.surface.foreground)},[r,v,S]),U.useEffect(()=>{if(typeof window>"u")return;const A=j=>{j.storageArea===window.localStorage&&(j.key!=="themeMode"&&j.key!=="lightThemeId"&&j.key!=="darkThemeId"||s(R=>{const O=localStorage.getItem("themeMode"),N=O==="light"||O==="dark"||O==="system"?O:R.themeMode,D=localStorage.getItem("lightThemeId"),K=typeof D=="string"&&D.trim().length>0?D.trim():R.lightThemeId,V=localStorage.getItem("darkThemeId"),W=typeof V=="string"&&V.trim().length>0?V.trim():R.darkThemeId;return N===R.themeMode&&K===R.lightThemeId&&W===R.darkThemeId?R:{themeMode:N,lightThemeId:K,darkThemeId:W}}))};return window.addEventListener("storage",A),()=>window.removeEventListener("storage",A)},[]),U.useEffect(()=>{const A=S(r.lightThemeId,"light"),j=S(r.darkThemeId,"dark");Er({themeId:v.metadata.id,themeVariant:v.metadata.variant==="light"?"light":"dark",useSystemTheme:r.themeMode==="system",lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,splashBgLight:A.colors.surface.background,splashFgLight:A.colors.surface.foreground,splashBgDark:j.colors.surface.background,splashFgDark:j.colors.surface.foreground})},[v.metadata.id,v.metadata.variant,S,r.themeMode,r.lightThemeId,r.darkThemeId]),U.useEffect(()=>{m&&(async()=>await lI(r.themeMode,v.metadata.variant))()},[v.metadata.variant,m,r.themeMode]),U.useEffect(()=>{if(typeof window>"u")return;const A=j=>{const R=j.detail;R&&s(O=>{let N=O.themeMode;R.useSystemTheme===!0?N="system":R.useSystemTheme===!1&&(R.themeVariant==="dark"||R.themeVariant==="light")&&(N=R.themeVariant);let D=O.lightThemeId;typeof R.lightThemeId=="string"&&R.lightThemeId.length>0&&(D=R.lightThemeId.trim());let K=O.darkThemeId;return typeof R.darkThemeId=="string"&&R.darkThemeId.length>0&&(K=R.darkThemeId.trim()),N===O.themeMode&&D===O.lightThemeId&&K===O.darkThemeId?O:{themeMode:N,lightThemeId:D,darkThemeId:K}})};return window.addEventListener("pichamber:settings-synced",A),()=>window.removeEventListener("pichamber:settings-synced",A)},[]);const C=U.useCallback(A=>{const j=b.find(R=>R.metadata.id===A);j&&s(R=>j.metadata.variant==="dark"?R.darkThemeId===j.metadata.id&&R.themeMode==="dark"?R:{...R,darkThemeId:j.metadata.id,themeMode:"dark"}:R.lightThemeId===j.metadata.id&&R.themeMode==="light"?R:{...R,lightThemeId:j.metadata.id,themeMode:"light"})},[b]),I=U.useCallback(A=>{r.themeMode!==A&&(s(j=>({...j,themeMode:A})),Er({themeVariant:A==="system"?v.metadata.variant:A,useSystemTheme:A==="system"}))},[v.metadata.variant,r.themeMode]),_=U.useCallback(A=>{if(A){s(R=>R.themeMode==="system"?R:{...R,themeMode:"system"});return}const j=v.metadata.variant==="dark"?"dark":"light";s(R=>R.themeMode===j?R:{...R,themeMode:j})},[v.metadata.variant]),E=U.useCallback(A=>{const j=b.find(R=>R.metadata.id===A&&R.metadata.variant==="light");j&&s(R=>R.lightThemeId===j.metadata.id?R:{...R,lightThemeId:j.metadata.id})},[b]),M=U.useCallback(A=>{const j=b.find(R=>R.metadata.id===A&&R.metadata.variant==="dark");j&&s(R=>R.darkThemeId===j.metadata.id?R:{...R,darkThemeId:j.metadata.id})},[b]),T={currentTheme:v,availableThemes:b,setTheme:C,customThemesLoading:u,reloadCustomThemes:x,isSystemPreference:r.themeMode==="system",setSystemPreference:_,themeMode:r.themeMode,setThemeMode:I,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:E,setDarkThemePreference:M};return l.jsx(nm.Provider,{value:T,children:e})}let ml=null;const lW=()=>{if(typeof window>"u"||ml)return()=>{};let e={showDeletionDialog:ne.getState().showDeletionDialog,nativeNotificationsEnabled:ne.getState().nativeNotificationsEnabled,notificationMode:ne.getState().notificationMode,notifyOnCompletion:ne.getState().notifyOnCompletion,notifyOnError:ne.getState().notifyOnError,notifyOnInputNeeded:ne.getState().notifyOnInputNeeded,summarizeLastMessage:ne.getState().summarizeLastMessage,summaryThreshold:ne.getState().summaryThreshold,summaryLength:ne.getState().summaryLength,maxLastMessageLength:ne.getState().maxLastMessageLength,autoDeleteEnabled:ne.getState().autoDeleteEnabled,autoSaveEnabled:ne.getState().autoSaveEnabled,autoDeleteAfterDays:ne.getState().autoDeleteAfterDays,sessionRetentionAction:ne.getState().sessionRetentionAction,fontSize:ne.getState().fontSize,terminalFontSize:ne.getState().terminalFontSize,terminalShell:ne.getState().terminalShell,terminalLoginShells:ne.getState().terminalLoginShells,editorFontSize:ne.getState().editorFontSize,uiFont:ne.getState().uiFont,monoFont:ne.getState().monoFont,padding:ne.getState().padding,cornerRadius:ne.getState().cornerRadius,inputBarOffset:ne.getState().inputBarOffset,mobileKeyboardMode:ne.getState().mobileKeyboardMode,diffLayoutPreference:ne.getState().diffLayoutPreference,gitChangesViewMode:ne.getState().gitChangesViewMode};const t=ne.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&&Er(i)});let n=!1;const r=()=>{n||(n=!0,t(),ml===r&&(ml=null))};return ml=r,r},Us={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Jx={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1,hasTouchOnlyPointer:!1},yI=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("surface")==="desktop",vI=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}},xI=(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 Ed(){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=bt()||yI(),{isExplicitTablet:c}=vI(i),d=s||o||i>0,f=s||o,u=e>Us.md&&e<=Us.lg,p=e<=Us.md;let m=d&&p,g=d&&!m&&(u||c),b=!d||!g&&e>Us.lg,y="desktop";a?(m=!1,g=!1,b=!0,y="desktop"):nn()?(m=!0,g=!1,b=!1,y="mobile"):m?y="mobile":g?y="tablet":(b=!0,y="desktop"),xI(a,y,d);let S="xs";for(const[v,x]of Object.entries(Us))e>=x&&(S=v);return{isMobile:m,isTablet:g,isDesktop:b,deviceType:y,screenWidth:e,breakpoint:S,hasTouchInput:d,hasTouchOnlyPointer:f}}const bI=(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,Ql=new Set;let Ir=null,co,si=null;const wI=()=>typeof window>"u"?Jx:(Ir||(Ir=Ed()),Ir),SI=()=>{for(const e of Ql)e()},CI=()=>{co=void 0;const e=Ed();Ir&&bI(Ir,e)||(Ir=e,SI())},gl=()=>{typeof window>"u"||co!==void 0||(co=window.requestAnimationFrame(CI))},Oc=(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)):()=>{}:()=>{},kI=()=>{if(typeof window>"u")return()=>{};Ir=Ed(),window.addEventListener("resize",gl);const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null,t=typeof window.matchMedia=="function"?window.matchMedia("(hover: none)"):null,n=Oc(e,gl),r=Oc(t,gl);return()=>{window.removeEventListener("resize",gl),n(),r(),co!==void 0&&(window.cancelAnimationFrame(co),co=void 0)}},MI=e=>typeof window>"u"?()=>{}:(Ql.add(e),si||(si=kI()),()=>{Ql.delete(e),Ql.size===0&&si&&(si(),si=null,Ir=null)}),II=()=>typeof window>"u"?!1:!!(navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)")?.matches||window.matchMedia?.("(display-mode: fullscreen)")?.matches),h2=()=>{if(typeof window>"u"||bt())return!1;const e=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return II()&&e>0&&window.innerWidth>Us.md};function cW(){const[e,t]=h.useState(()=>h2());return h.useEffect(()=>{if(typeof window>"u")return;const n=()=>t(h2()),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 _I=()=>typeof window>"u"?"portrait":window.matchMedia?.("(orientation: landscape)")?.matches?"landscape":"portrait";function dW(){const[e,t]=h.useState(_I);return h.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(orientation: landscape)"),r=()=>t(n.matches?"landscape":"portrait");return r(),Oc(n,r)},[]),e}const EI=600,jI=1e3,rm=()=>{if(typeof window>"u")return{enabled:!1,roomyForPanels:!1};const e=window.innerWidth,t=window.innerHeight,n=p7()||Math.min(e,t)>=EI;return{enabled:n,roomyForPanels:n&&e>t&&e>=jI}},TI=(e,t)=>e.enabled===t.enabled&&e.roomyForPanels===t.roomyForPanels,Qx={enabled:!1,roomyForPanels:!1},ec=new Set;let _r=null,uo,oi=null;const AI=()=>typeof window>"u"?Qx:(_r||(_r=rm()),_r),LI=()=>{for(const e of ec)e()},NI=()=>{uo=void 0;const e=rm();_r&&TI(_r,e)||(_r=e,LI())},Zu=()=>{typeof window>"u"||uo!==void 0||(uo=window.requestAnimationFrame(NI))},RI=()=>{if(typeof window>"u")return()=>{};_r=rm(),window.addEventListener("resize",Zu);const e=typeof window.matchMedia=="function"?window.matchMedia("(orientation: landscape)"):null,t=Oc(e,Zu);return()=>{window.removeEventListener("resize",Zu),t(),uo!==void 0&&(window.cancelAnimationFrame(uo),uo=void 0)}},PI=e=>typeof window>"u"?()=>{}:(ec.add(e),oi||(oi=RI()),()=>{ec.delete(e),ec.size===0&&oi&&(oi(),oi=null,_r=null)});function jd(){return h.useSyncExternalStore(PI,AI,()=>Qx)}function Pr(){return h.useSyncExternalStore(MI,wI,()=>Jx)}const sm=e=>{const t=e;return le(t.directory??null)??le(t.project?.worktree??null)},Wu=(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]?.providerID!==t[n]?.providerID||e[n]?.modelID!==t[n]?.modelID)return!1;return!0},Th=(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)=>{if(e===t)return!0;const n=Object.keys(e);return n.length!==Object.keys(t).length?!1:n.every(r=>Array.isArray(t[r])&&Th(e[r],t[r]))},p2=()=>{const e=ne.getState();return{favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts}},m2=(e,t)=>Wu(e.favoriteModels,t.favoriteModels)&&Wu(e.hiddenModels,t.hiddenModels)&&Th(e.collapsedModelProviders,t.collapsedModelProviders)&&Wu(e.recentModels,t.recentModels)&&Th(e.recentAgents,t.recentAgents)&&DI(e.recentEfforts,t.recentEfforts),g2=e=>({favoriteModels:e.favoriteModels.slice(),hiddenModels:e.hiddenModels.slice(),collapsedModelProviders:e.collapsedModelProviders.slice(),recentModels:e.recentModels.slice(),recentAgents:e.recentAgents.slice(),recentEfforts:Object.fromEntries(Object.entries(e.recentEfforts).map(([t,n])=>[t,n.slice()]))}),uW=()=>{if(typeof window>"u")return()=>{};let e=null,t=g2(p2()),n=null;const r=(a=!1)=>{e=null;const c=n;if(n=null,!c||c!==J())return;const d=p2();t&&m2(t,d)||(t=g2(d),Er(d,{immediate:a}).catch(()=>{}))},s=()=>{e!==null&&window.clearTimeout(e),n=J(),e=window.setTimeout(r,1200)},o=xp(a=>{a.runtimeKey!==a.previousRuntimeKey&&(e!==null&&window.clearTimeout(e),r(!0),t=null)}),i=ne.subscribe((a,c)=>{const d={favoriteModels:a.favoriteModels,hiddenModels:a.hiddenModels,collapsedModelProviders:a.collapsedModelProviders,recentModels:a.recentModels,recentAgents:a.recentAgents,recentEfforts:a.recentEfforts},f={favoriteModels:c.favoriteModels,hiddenModels:c.hiddenModels,collapsedModelProviders:c.collapsedModelProviders,recentModels:c.recentModels,recentAgents:c.recentAgents,recentEfforts:c.recentEfforts};m2(d,f)||s()});return()=>{i(),o(),e!==null&&window.clearTimeout(e),r(!0)}};let Gu=null;const om=()=>(Gu??=ft(()=>import("./MarkdownRendererImpl-SXAK4uOu.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 Gu=null,e}),Gu),fW=()=>{om().catch(()=>{})},e3={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"/>',briefcase:'<path d="M7 5V2C7 1.44772 7.44772 1 8 1H16C16.5523 1 17 1.44772 17 2V5H21C21.5523 5 22 5.44772 22 6V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V6C2 5.44772 2.44772 5 3 5H7ZM4 16V19H20V16H4ZM4 14H20V7H4V14ZM9 3V5H15V3H9ZM11 11H13V13H11V11Z" 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"/>',fingerprint:'<path d="M17.0003 13V14C17.0003 16.7696 16.3364 19.445 15.0853 21.8455L14.8585 22.2663L13.1116 21.2924C14.2716 19.2115 14.9211 16.8817 14.9935 14.4559L15.0003 14V13H17.0003ZM11.0003 10H13.0003V14L12.9948 14.3787C12.9153 17.1495 11.9645 19.7731 10.3038 21.928L10.073 22.2189L8.52406 20.9536C10.0408 19.0969 10.9145 16.8017 10.9943 14.3663L11.0003 14V10ZM12.0003 6C14.7617 6 17.0003 8.23858 17.0003 11H15.0003C15.0003 9.34315 13.6571 8 12.0003 8C10.3434 8 9.00025 9.34315 9.00025 11V14C9.00025 16.2354 8.1806 18.3444 6.72928 19.9768L6.51767 20.2067L5.06955 18.8273C6.23328 17.6056 6.92099 16.0118 6.99381 14.3027L7.00025 14V11C7.00025 8.23858 9.23883 6 12.0003 6ZM12.0003 2C16.9708 2 21.0003 6.02944 21.0003 11V14C21.0003 15.6979 20.7985 17.3699 20.4035 18.9903L20.2647 19.5285L18.3349 19.0032C18.726 17.5662 18.9475 16.0808 18.9919 14.5684L19.0003 14V11C19.0003 7.13401 15.8662 4 12.0003 4C10.4279 4 8.97663 4.51841 7.80805 5.39364L6.38308 3.96769C7.92267 2.73631 9.87547 2 12.0003 2ZM4.96794 5.38282L6.39389 6.8078C5.5635 7.91652 5.0543 9.27971 5.00431 10.7593L4.99961 10.999L5.00378 13C5.00378 14.1195 4.73991 15.2026 4.24263 16.1772L4.08648 16.4663L2.34961 15.4747C2.72889 14.8103 2.95077 14.0681 2.99539 13.2924L3.00378 13L3.00361 11C3.00025 8.87522 3.73656 6.92242 4.96794 5.38282Z" 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"/>',"graduation-cap":'<path d="M4 11.3333L0 9L12 2L24 9V17.5H22V10.1667L20 11.3333V18.0113L19.7774 18.2864C17.9457 20.5499 15.1418 22 12 22C8.85817 22 6.05429 20.5499 4.22263 18.2864L4 18.0113V11.3333ZM6 12.5V17.2917C7.46721 18.954 9.61112 20 12 20C14.3889 20 16.5328 18.954 18 17.2917V12.5L12 16L6 12.5ZM3.96927 9L12 13.6846L20.0307 9L12 4.31541L3.96927 9Z" 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"/>',heart:'<path d="M12.001 4.52853C14.35 2.42 17.98 2.49 20.2426 4.75736C22.5053 7.02472 22.583 10.637 20.4786 12.993L11.9999 21.485L3.52138 12.993C1.41705 10.637 1.49571 7.01901 3.75736 4.75736C6.02157 2.49315 9.64519 2.41687 12.001 4.52853ZM18.827 6.1701C17.3279 4.66794 14.9076 4.60701 13.337 6.01687L12.0019 7.21524L10.6661 6.01781C9.09098 4.60597 6.67506 4.66808 5.17157 6.17157C3.68183 7.66131 3.60704 10.0473 4.97993 11.6232L11.9999 18.6543L19.0201 11.6232C20.3935 10.0467 20.319 7.66525 18.827 6.1701Z" 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"/>',key:'<path d="M12.917 13C12.441 15.8377 9.973 18 7 18C3.68629 18 1 15.3137 1 12C1 8.68629 3.68629 6 7 6C9.973 6 12.441 8.16229 12.917 11H23V13H21V17H19V13H17V17H15V13H12.917ZM7 16C9.20914 16 11 14.2091 11 12C11 9.79086 9.20914 8 7 8C4.79086 8 3 9.79086 3 12C3 14.2091 4.79086 16 7 16Z" 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-2":'<path d="M6 8V7C6 3.68629 8.68629 1 12 1C15.3137 1 18 3.68629 18 7V8H20C20.5523 8 21 8.44772 21 9V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V9C3 8.44772 3.44772 8 4 8H6ZM19 10H5V20H19V10ZM11 15.7324C10.4022 15.3866 10 14.7403 10 14C10 12.8954 10.8954 12 12 12C13.1046 12 14 12.8954 14 14C14 14.7403 13.5978 15.3866 13 15.7324V18H11V15.7324ZM8 8H16V7C16 4.79086 14.2091 3 12 3C9.79086 3 8 4.79086 8 7V8Z" 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"/>',"user-3":'<path d="M20 22H18V20C18 18.3431 16.6569 17 15 17H9C7.34315 17 6 18.3431 6 20V22H4V20C4 17.2386 6.23858 15 9 15H15C17.7614 15 20 17.2386 20 20V22ZM12 13C8.68629 13 6 10.3137 6 7C6 3.68629 8.68629 1 12 1C15.3137 1 18 3.68629 18 7C18 10.3137 15.3137 13 12 13ZM12 11C14.2091 11 16 9.20914 16 7C16 4.79086 14.2091 3 12 3C9.79086 3 8 4.79086 8 7C8 9.20914 9.79086 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"/>'},y2="pichamber-icon-sprite";let Ku=!1;function OI(){if(Ku||typeof document>"u")return;const e=document.body;if(!e)return;if(document.getElementById(y2)){Ku=!0;return}const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.id=y2,n.setAttribute("aria-hidden","true"),n.style.display="none",n.innerHTML=Object.entries(e3).map(([r,s])=>`<symbol id="oc-${r}" viewBox="0 0 24 24">${s}</symbol>`).join(""),e.insertBefore(n,e.firstChild),Ku=!0}const F=h.memo(({name:e,className:t,...n})=>(typeof document<"u"&&OI(),l.jsx("svg",{className:P("remixicon",t),viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",...n,children:l.jsx("use",{href:`#oc-${e}`})})));F.displayName="Icon";let yl=0;function HI(e,t){return e&&U.isValidElement(t)?{render:t}:{children:t}}function Td({...e}){return l.jsx(l9,{...e})}function FI({asChild:e,children:t,...n}){const r=HI(e,t);return l.jsx(m9,{"data-slot":"dialog-trigger",...n,...r})}function VI({...e}){return l.jsx(h9,{...e})}const t3=U.forwardRef(({className:e,...t},n)=>(U.useEffect(()=>(yl+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{yl=Math.max(0,yl-1),yl===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),l.jsx(p9,{ref:n,"data-slot":"dialog-overlay",className:P("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})));t3.displayName="DialogOverlay";function Ad({className:e,children:t,showCloseButton:n=!0,...r}){return l.jsxs(VI,{children:[l.jsx(t3,{className:"rounded-none"}),l.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center pointer-events-none p-4",children:l.jsxs(c9,{"data-slot":"dialog-content","data-state-slot":"dialog",className:P("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&&l.jsxs(d9,{"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:[l.jsx(F,{name:"close"}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})})]})}function Ld({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-header",className:P("flex flex-col gap-2 text-center sm:text-left",e),...t})}function BI({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-footer",className:P("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",e),...t})}function Nd({className:e,...t}){return l.jsx(u9,{"data-slot":"dialog-title",className:P("typography-markdown leading-none font-semibold text-foreground",e),...t})}function im({className:e,...t}){return l.jsx(f9,{"data-slot":"dialog-description",className:P("text-muted-foreground typography-ui-label",e),...t})}function $I(...e){return t=>{for(const n of e)n&&(typeof n=="function"?n(t):n.current=t)}}function zI(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 UI=U.forwardRef(function({children:t,...n},r){if(!U.isValidElement(t))return null;const s=t;return U.cloneElement(s,{...zI(s.props,n),ref:$I(r,s.ref)})}),qI=["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(" "),ZI=["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(" "),WI=["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(" "),GI=rv(["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:qI,destructive:P(ZI,"focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40"),info:WI,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:P("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 Me({className:e,variant:t,size:n,asChild:r=!1,type:s,...o}){const i=r?UI:"button",a=r?s===void 0?{}:{type:s}:{type:s??"button"};return l.jsx(i,{"data-slot":"button",className:P(GI({variant:t,size:n,className:e})),...a,...o})}const am="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",KI="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",YI="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",XI="bg-border -mx-1 my-0.5 h-px",Rd=U.createContext(null),JI=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function n3(e,t){return e&&U.isValidElement(t)?{render:t}:{children:t}}function Pd({...e}){const[t,n]=U.useState(null),r=U.useMemo(()=>({portalContainer:t,setPortalContainer:n}),[t]);return l.jsx(Rd.Provider,{value:r,children:l.jsx(g9,{...e})})}function Dd({asChild:e,children:t,onPointerDownCapture:n,onFocusCapture:r,...s}){const o=U.useContext(Rd),i=U.useCallback(c=>{if(!o)return;const d=c instanceof HTMLElement?c:null;o.setPortalContainer(JI(d))},[o]),a=n3(e,t);return l.jsx(y9,{"data-slot":"dropdown-menu-trigger",onPointerDownCapture:c=>{i(c.currentTarget),n?.(c)},onFocusCapture:c=>{i(c.currentTarget),r?.(c)},...s,...a})}function Od({className:e,sideOffset:t=4,align:n,side:r,alignOffset:s,portalToBody:o=!1,positionerClassName:i,style:a,children:c,onCloseAutoFocus:d,...f}){const u=U.useContext(Rd);return l.jsx(sv,{container:o?void 0:u?.portalContainer||void 0,children:l.jsx(ov,{sideOffset:t,align:n,side:r,alignOffset:s,className:P("app-region-no-drag z-50",i),children:l.jsx(iv,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...a},className:P(am,e),...f,children:c})})})}function Qs({className:e,inset:t,variant:n="default",asChild:r,children:s,onSelect:o,onClick:i,...a}){const c=n3(r,s),d=f=>{i?.(f),f.defaultPrevented||o?.(f)};return l.jsx(v9,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:P(KI,e),...a,onClick:d,...c})}function QI({...e}){return l.jsx(b9,{"data-slot":"dropdown-menu-radio-group",...e})}function e_({className:e,children:t,...n}){return l.jsxs(w9,{"data-slot":"dropdown-menu-radio-item",className:P("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:[l.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:l.jsx(S9,{children:l.jsx(F,{name:"check",className:"size-3"})})}),t]})}function hW({className:e,inset:t,...n}){return l.jsx("div",{"data-slot":"dropdown-menu-label","data-inset":t,className:P("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",e),...n})}function t_({className:e,...t}){return l.jsx(x9,{"data-slot":"dropdown-menu-separator",className:P(XI,e),...t})}function pW({...e}){return l.jsx(C9,{...e})}function mW({className:e,inset:t,children:n,...r}){return l.jsxs(k9,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:P(YI,e),...r,children:[n,l.jsx(F,{name:"arrow-right-s",className:"ml-auto size-3.5"})]})}function gW({className:e,children:t,...n}){const r=U.useContext(Rd);return l.jsx(sv,{container:r?.portalContainer||void 0,children:l.jsx(ov,{className:"z-50",children:l.jsx(iv,{"data-slot":"dropdown-menu-sub-content",style:{color:"var(--surface-elevated-foreground)"},className:P(am,e),...n,children:t})})})}const n_={local:"This computer",lan:"Local network",tailscale:"Tailscale",relay:"PiChamber Relay",tunnel:"Tunnel",direct:"Direct"},lm={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."}},r3=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"}},r_=(e,t)=>e?{status:r3(e.status),latencyMs:Math.max(0,Math.round(e.latencyMs)),refreshing:t}:{status:t?"checking":"unknown",latencyMs:null,refreshing:t},s_=e=>e==="offline"||e==="wrong-service"||e==="incompatible",o_=e=>{try{return new URL(e).hostname.toLowerCase()}catch{return null}},i_=e=>/^10\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^192\.168\./.test(e)||/^169\.254\./.test(e),a_=e=>i_(e)?!0:e.endsWith(".local")||e.endsWith(".lan")||e.endsWith(".home")||e.endsWith(".internal"),l_=e=>{const t=o_(e);return t?t.endsWith(".ts.net")?"tailscale":t.endsWith(".trycloudflare.com")||t.endsWith(".cfargotunnel.com")?"tunnel":a_(t)?"lan":"direct":"direct"},vl=(e,t)=>({kind:e,label:n_[e],address:t}),c_=(e,t)=>e.kind===t.kind&&(e.address||null)===(t.address||null),Yu=(e,t)=>{try{return e?e(t):t}catch{return t}},d_=(e,t)=>{const n=r_(t.probe,t.probing===!0),r=t.redactUrl?Yu(t.redactUrl,e.label):e.label;let s;if(t.isLocal){const a=(t.localOrigin||e.apiUrl||e.url||"").trim();s=[vl("local",a?Yu(t.redactUrl,a):null)]}else if(e.relay&&!e.apiUrl)s=[vl("relay",null)];else{const a=Yu(t.redactUrl,e.apiUrl||e.url),c=vl(l_(e.apiUrl||e.url),a);s=e.relay?[c,vl("relay",null)]:[c]}let o=null;t.probe&&r3(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}},u_=e=>[...e].sort((t,n)=>Number(n.isCurrent)-Number(t.isCurrent)||Number(n.isDefault)-Number(t.isDefault)||t.label.localeCompare(n.label)),f_=e=>e.activeRoute?.address?e.activeRoute.address:e.routes.find(t=>t.address)?.address||null,tc=e=>`${e.kind}::${e.address??""}`,h_=e=>{if(e.routes.length===0)return null;const t=e.activeRoute;if(t){const n=e.routes.find(r=>c_(r,t));if(n)return n}return e.routes[0]??null},p_=(e,t)=>e.routes.find(n=>tc(n)===t)??null,m_=(e,t)=>{const n=lm[e].tone;return P("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")},g_=e=>{const t=lm[e].tone;return P("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")},y_="typography-micro truncate text-muted-foreground";function v_({item:e,onSelectRoute:t}){const n=h_(e);return n?typeof t=="function"&&e.routes.length>1?l.jsx("span",{className:"flex min-w-0 items-center gap-1.5",children:l.jsxs(Pd,{children:[l.jsx(Dd,{asChild:!0,children:l.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:[l.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-muted-foreground/60",children:"·"}),l.jsx("span",{className:"truncate",children:n.label}),l.jsx(F,{name:"arrow-down-s",className:"size-3 shrink-0 opacity-70","aria-hidden":"true"})]})}),l.jsx(Od,{align:"start",portalToBody:!0,children:l.jsx(QI,{value:tc(n),onValueChange:s=>{const o=p_(e,s);o&&t?.(e,o)},children:e.routes.map(s=>l.jsx(e_,{value:tc(s),children:s.label},tc(s)))})})]})}):l.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[l.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-muted-foreground/60",children:"·"}),l.jsx("span",{className:y_,children:n.label})]}):null}const x_=({item:e,layout:t="comfortable",guardDefaultByStatus:n=!1,switchLabel:r="Switch",refreshing:s=!1,pending:o=!1,actionsDisabled:i=!1,onSwitch:a,onSetDefault:c,onOpenInNewWindow:d,onEdit:f,onRemove:u,onSelectRoute:p})=>{const[m,g]=U.useState(!1);U.useEffect(()=>{g(!1)},[e.id]);const b=lm[e.status],y=s_(e.status),S=f_(e),v=t==="touch",x=i||o,k=typeof a=="function",w=e.canOpenInNewWindow&&typeof d=="function",C=e.canEdit&&typeof f=="function",I=e.canRemove&&typeof u=="function",_=k||w||C||I,E=x||n&&!e.isDefault&&y,M=x||e.isCurrent,T=l.jsxs(l.Fragment,{children:[l.jsx("span",{className:m_(e.status,s||e.status==="checking"),"aria-hidden":"true"}),l.jsxs("span",{className:"flex-1 min-w-0 space-y-0.5",children:[l.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0",children:[l.jsx("span",{className:"typography-ui-label font-medium truncate text-foreground min-w-0",children:e.label}),l.jsx(v_,{item:e,onSelectRoute:p}),e.isCurrent&&l.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"})]}),l.jsxs("span",{className:g_(e.status),title:b.description,children:[b.label,typeof e.latencyMs=="number"&&(e.status==="connected"||e.status==="reachable")?` · ${e.latencyMs}ms`:"",s&&e.status!=="checking"?" · checking":""]}),S?l.jsx("span",{className:"typography-micro block truncate font-mono text-muted-foreground/70",children:S}):null]})]});return l.jsxs("div",{className:P("group flex gap-2 overflow-hidden rounded-md px-2.5 py-2",v?"flex-col rounded-xl bg-[var(--surface-muted)] px-3 py-2.5":"items-center",v&&e.isCurrent&&"bg-[var(--interactive-selection)]/25"),children:[l.jsxs("div",{className:P("flex min-w-0 flex-1 gap-2",v?"items-start":"items-center"),children:[k&&!e.isCurrent?l.jsxs("div",{className:P("relative flex items-center gap-2 flex-1 min-w-0",M&&"opacity-70"),children:[l.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:M,"aria-label":`${r} to ${e.label}`}),o?l.jsx(F,{name:"loader-4",className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):null,l.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:T})]}):l.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0","aria-label":e.isCurrent?`Current server ${e.label}`:void 0,children:T}),l.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[typeof c=="function"&&l.jsx("button",{type:"button",className:P("rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",v?"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",E&&"opacity-40 cursor-not-allowed"),onClick:()=>c?.(e),disabled:E,"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:l.jsx(F,{name:e.isDefault?"star-fill":"star",className:"h-4 w-4","aria-hidden":"true"})}),_&&l.jsxs(Pd,{children:[l.jsx(Dd,{asChild:!0,children:l.jsx("button",{type:"button",className:P("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",v?"h-11 w-11":"h-8 w-8"),"aria-label":`Actions for ${e.label}`,disabled:x,children:l.jsx(F,{name:"more",className:"h-4 w-4","aria-hidden":"true"})})}),l.jsxs(Od,{align:"end",portalToBody:!0,children:[k&&l.jsx(Qs,{disabled:M,onSelect:()=>a?.(e),children:e.isCurrent?"Current server":`${r} to this server`}),w&&l.jsx(Qs,{disabled:x||y,onSelect:()=>d?.(e),children:y?"Server unreachable":"Open in new window"}),C&&l.jsx(Qs,{disabled:x,onSelect:()=>f?.(e),children:"Edit"}),I&&(k||w||C)&&l.jsx(t_,{}),I&&l.jsx(Qs,{variant:"destructive",disabled:x,onSelect:()=>g(!0),children:"Remove"})]})]})]})]}),m&&I&&l.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:[l.jsx("span",{className:"typography-ui-label flex-1 min-w-0 text-foreground",children:`Remove ${e.label}?`}),l.jsx(Me,{type:"button",variant:"destructive",size:v?"sm":"xs",className:v?"min-h-[44px]":void 0,disabled:x,onClick:()=>{g(!1),u?.(e)},"aria-label":`Confirm remove ${e.label}`,children:"Remove"}),l.jsx(Me,{type:"button",variant:"outline",size:v?"sm":"xs",className:v?"min-h-[44px]":void 0,onClick:()=>g(!1),"aria-label":`Keep ${e.label}`,children:"Keep"})]})]})},b_=({items:e,emptyMessage:t="No servers yet.",pendingId:n=null,...r})=>e.length===0?l.jsx("p",{className:"typography-meta text-muted-foreground",children:t}):l.jsx("div",{className:"space-y-1",role:"list","aria-label":"Servers",children:e.map(s=>l.jsx("div",{role:"listitem",children:l.jsx(x_,{item:s,pending:n===s.id,...r})},s.id))}),w_=()=>{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}},S_=w_(),C_=(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}),k_=e=>e.trim().toLowerCase()==="authorization",Xu=e=>{const t={};for(const n of e){const r=n.name.trim(),s=n.value.trim();r&&s&&!k_(r)&&(t[r]=s)}return Object.keys(t).length>0?t:void 0},yW=e=>Object.entries(e||{}).map(([t,n])=>C_(t,n)),v2=async e=>{const t=await ir(e);t.ok||console.error("Failed to copy to clipboard:",t.error)},Hc=e=>e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(Hc).join(" ").trim():U.isValidElement(e)?Hc(e.props?.children):"",M_=e=>typeof e=="function"?e():e,x2=(e,t)=>{const n=Hc(M_(t?.description));return n.length>0?n:Hc(e)},ke={...Xo,success:(e,t)=>Xo.success(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),info:(e,t)=>Xo.info(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),error:(e,t)=>Xo.error(e,{...t,action:t?.action||{label:"Copy",onClick:()=>v2(x2(e,t))}}),warning:(e,t)=>Xo.warning(e,{...t,action:t?.action||{label:"Copy",onClick:()=>v2(x2(e,t))}})},nc=new Map,I_=()=>Object.fromEntries(nc),b2={status:"unreachable",latencyMs:0},Ju=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",w2=e=>{const t=wr(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}},S2=async()=>bo()?S7().catch(()=>""):"",Qu=e=>{const t=e.trim();if(t)try{window.location.assign(t)}catch{window.location.href=t}},__="Invalid PiChamber connection link.",Si="Invalid URL (must be http/https)",E_=e=>(e instanceof Error?e.message:String(e))==="invalid-connect-link"?__:Si;function j_(e){const t=e?.autoLoad!==!1,[n,r]=U.useState([]),[s,o]=U.useState(null),[i,a]=U.useState(()=>m7()),[c,d]=U.useState(()=>I_()),[f,u]=U.useState(!1),[p,m]=U.useState(!1),[g,b]=U.useState(!1),[y,S]=U.useState(null),[v,x]=U.useState(null),[k,w]=U.useState(0);U.useEffect(()=>sn(()=>w(B=>B+1)),[]);const C=U.useMemo(()=>{const B=w7(i),Z=n.map(L=>({...L,url:wr(L.url)||L.url}));return[B,...Z]},[n,i]),I=U.useMemo(()=>g7(C),[C,k]),_=U.useMemo(()=>{const B=s||cn;return C.find(Z=>Z.id===B)?.label||"Local"},[C,s]),E=U.useMemo(()=>{const B=C.map(Z=>d_(Z,{isCurrent:Z.id===I.id,isDefault:(s||cn)===Z.id,isLocal:Z.id===cn,probe:c[Z.id]||null,probing:f,localOrigin:i,redactUrl:Rn}));return u_(B)},[C,I,s,c,f,i]),M=U.useCallback(async()=>{if(bt()){m(!0),x(null);try{const B=await wp();B.localOrigin&&a(B.localOrigin),r(B.hosts||[]),o(B.defaultHostId??null)}catch(B){x(B instanceof Error?B.message:"Failed to load"),r([]),o(null)}finally{m(!1)}}},[]);U.useEffect(()=>{t&&M()},[t,M]);const T=U.useCallback(async(B,Z)=>{b(!0),x(null);try{await vc({hosts:B,defaultHostId:Z,initialHostChoiceCompleted:!0}),r(B),o(Z)}catch(L){throw x(L instanceof Error?L.message:"Failed to save"),L}finally{b(!1)}},[]),A=U.useCallback(async(B,Z)=>S_(B.id,async()=>{const L=B.id===cn?Z:B.clientToken||"",$=B.requestHeaders||null,G=async()=>{const X=await O1(B.relay,{clientToken:L,requestHeaders:$}).catch(()=>({status:"unreachable",latencyMs:0}));return{status:X.status,latencyMs:X.latencyMs,...X.status==="ok"?{via:"relay"}:{}}};if(B.relay&&!B.apiUrl)return G();const Q=wr(bo()?Vl(B):B.url);if(!Q)return{...b2};const z=await hu(Q,{clientToken:L||null,requestHeaders:$,expectedServerId:B.serverId??B.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Ju(z.status)&&B.relay){const X=await G();if(X.status==="ok")return X}return{status:z.status,latencyMs:z.latencyMs}}),[]),j=U.useCallback(async B=>{if(!bt())return{};u(!0);try{const Z=await S2(),L=await Promise.all(B.map(async $=>[$.id,await A($,Z)]));for(const[$,G]of L)nc.set($,G);return d($=>({...$,...Object.fromEntries(L)})),Object.fromEntries(L)}finally{u(!1)}},[A]),R=U.useCallback(async B=>{b(!0),x(null);try{const{hosts:Z,hostId:L}=await y7(B,n);return await vc({hosts:Z,defaultHostId:s,initialHostChoiceCompleted:!0}),r(Z),{ok:!0,hostId:L}}catch(Z){const L=E_(Z);return x(L),{ok:!1,error:L}}finally{b(!1)}},[n,s]),O=U.useCallback(async B=>{const Z=D1(B.url);if(!Z)return x(Si),{ok:!1,error:Si};const L=Z.persistedUrl,G={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:B.label.trim()||Rn(L),url:L,apiUrl:L,...B.token.trim()?{clientToken:B.token.trim()}:{},...Xu(B.headers)?{requestHeaders:Xu(B.headers)}:{}};try{await T([G,...n],s)}catch{return{ok:!1,error:"Failed to save"}}return Z.redeemUrl&&Qu(Z.redeemUrl),{ok:!0}},[n,s,T]),N=U.useCallback(async(B,Z)=>{const L=D1(Z.url);if(!L)return x(Si),{ok:!1,error:Si};const $=L.persistedUrl,G=n.map(Q=>Q.id===B?{...v7(Q,$),label:Z.label.trim()||Rn($),clientToken:Z.token.trim()||void 0,requestHeaders:Xu(Z.headers)}:Q);try{await T(G,s)}catch{return{ok:!1,error:"Failed to save"}}return L.redeemUrl&&Qu(L.redeemUrl),{ok:!0}},[n,s,T]),D=U.useCallback(async B=>{const Z=n.filter($=>$.id!==B),L=s===B?cn:s;try{await T(Z,L)}catch{}},[n,s,T]),K=U.useCallback(async B=>{try{await T(n,B)}catch{}},[n,T]),V=U.useCallback(async(B,Z)=>{const L=C.find(X=>X.id===B);if(!L)return;const $=(X,Y)=>{Y&&C7({relayUrl:X.relayUrl,serverId:X.serverId,hostEncPubJwk:X.hostEncPubJwk},Y),Bl({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:L.clientToken||null,runtimeKey:pu(L),relay:X}),k7(L.id)},G=L.id===cn?i:wr(L.url)||"",Q=L.id===cn?i:wr(Vl(L))||"",z=!!L.relay&&!L.apiUrl&&L.id!==cn;if(!(!G&&!z)){if(bo()){if(!Q&&!L.relay)return;S(L.id);try{const X=L.id===cn?await S2():L.clientToken||"",Y=c[L.id];if(Y?.status==="ok"){Y.via==="relay"&&L.relay?$(L.relay):Q?Bl({apiBaseUrl:Q,clientToken:X||null,requestHeaders:L.requestHeaders||null,runtimeKey:pu(L)}):L.relay&&$(L.relay),Z?.onSwitched?.();return}let ce={...b2},se=null;if(Q){const de=await hu(Q,{clientToken:X||null,requestHeaders:L.requestHeaders||null,expectedServerId:L.serverId??L.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0}));ce={status:de.status,latencyMs:de.latencyMs},Ju(de.status)||(se="direct")}let ue;if(!se&&L.relay){const de=await O1(L.relay,{keepTunnel:!0,clientToken:X||null,requestHeaders:L.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));de.status==="ok"&&(ce={status:de.status,latencyMs:de.latencyMs,via:"relay"},se="relay",ue="tunnel"in de?de.tunnel:void 0)}const Ie=ce;if(nc.set(L.id,Ie),d(de=>({...de,[L.id]:Ie})),!se){ke.error(`Server "${Rn(L.label)}" is unreachable`);return}se==="relay"&&L.relay?$(L.relay,ue):Bl({apiBaseUrl:Q,clientToken:X||null,requestHeaders:L.requestHeaders||null,runtimeKey:pu(L)}),Z?.onSwitched?.()}finally{S(null)}return}if(L.id!==cn&&bt()){S(L.id);try{const X=await hu(G,{clientToken:L.clientToken||null,requestHeaders:L.requestHeaders||null,expectedServerId:L.serverId??L.relay?.serverId??null}).catch(()=>({status:"unreachable",latencyMs:0})),Y={status:X.status,latencyMs:X.latencyMs};if(nc.set(L.id,Y),d(ce=>({...ce,[L.id]:Y})),Ju(X.status)){ke.error(`Server "${Rn(L.label)}" is unreachable`);return}}finally{S(null)}}Z?.onSwitched?.(),Qu(w2(G))}},[C,i,c]),W=U.useCallback(B=>{const Z=C.find(G=>G.id===B);if(!Z)return;const L=G=>{ke.error("Failed to open new window",{description:G instanceof Error?G.message:String(G)})};if(Z.relay&&Z.id!==cn){x7(Z.id).catch(L);return}const $=Z.id===cn?i:Vl(Z);$&&b7(w2($),{clientToken:Z.clientToken||null,requestHeaders:Z.requestHeaders||null}).catch(L)},[C,i]);return{remoteHosts:n,allHosts:C,defaultHostId:s,localOrigin:i,current:I,currentDefaultLabel:_,items:E,statusById:c,probing:f,loading:p,saving:g,switchingHostId:y,error:v,setError:x,load:M,probeAll:j,importPairingLink:R,addManualServer:O,updateServer:N,removeServer:D,setDefaultServer:K,switchToHost:V,openInNewWindow:W}}function T_({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){const s=ne(u=>u.setSettingsDialogOpen),o=ne(u=>u.setSettingsPage),i=j_({autoLoad:!1}),a=U.useCallback(()=>{o("servers"),s(!0),t(!1)},[t,s,o]);U.useEffect(()=>{e&&i.load()},[e]);const c=i.allHosts;if(U.useEffect(()=>{e&&i.probeAll(c)},[e,c]),!bt())return null;const d=bt(),f=l.jsxs(l.Fragment,{children:[n?l.jsx("div",{className:"flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2",children:l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"min-w-0 flex items-baseline gap-1.5 typography-ui-label",children:[l.jsx("span",{className:"font-medium text-foreground",children:"Current"}),l.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:Rn(i.current.label)}),l.jsx("span",{className:"text-muted-foreground/50",children:"•"}),l.jsx("span",{className:"font-medium text-foreground",children:"Default"}),l.jsx("span",{className:"max-w-[9rem] truncate text-muted-foreground",children:Rn(i.currentDefaultLabel)})]}),l.jsx("button",{type:"button",className:P("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:l.jsx(F,{name:"refresh",className:P("h-4 w-4",i.probing&&"animate-spin")})})]})}):l.jsxs(Ld,{className:"flex-shrink-0",children:[l.jsxs(Nd,{className:"flex items-center gap-2",children:[l.jsx(F,{name:"server",className:"h-5 w-5"}),"Servers"]}),l.jsx(im,{children:"Switch between this computer and remote PiChamber servers"})]}),!n&&l.jsxs("div",{className:"flex items-center justify-between gap-2 flex-shrink-0",children:[l.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current:"}),l.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Rn(i.current.label)}),l.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current default:"}),l.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Rn(i.currentDefaultLabel)})]}),l.jsx("div",{className:"flex items-center gap-1",children:l.jsxs(Me,{type:"button",size:"sm",variant:"ghost",onClick:()=>{i.probeAll(i.allHosts)},disabled:!d||i.loading||i.probing,children:[l.jsx(F,{name:"refresh",className:P("h-4 w-4",i.probing&&"animate-spin")}),"Refresh"]})})]}),!d&&l.jsx("div",{className:"flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3",children:l.jsx("div",{className:"typography-meta text-muted-foreground",children:"Server switcher is limited on this page. Use Local to recover."})}),l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:l.jsx("div",{className:P(n&&"px-3 py-1"),children:i.loading?l.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading..."}):l.jsx(b_,{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)})})}),l.jsx("div",{className:"flex-shrink-0 border-t border-[var(--interactive-border)]",children:l.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:[l.jsx(F,{name:"add",className:"h-4 w-4"}),l.jsx("span",{className:"typography-ui-label",children:"Add server"})]})}),i.error&&l.jsx("div",{className:"flex-shrink-0 typography-meta text-status-error",children:i.error})]});return n?l.jsx("div",{className:"w-full max-h-[70vh] flex flex-col overflow-hidden gap-2",children:f}):l.jsx(Td,{open:e,onOpenChange:t,children:l.jsx(Ad,{className:"w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3",children:f})})}function s3(){const[e,t]=U.useState(!1);return bt()?l.jsxs(l.Fragment,{children:[l.jsxs(Me,{type:"button",variant:"ghost",size:"sm","data-oc-host-switcher":!0,className:"w-full justify-center",onClick:()=>t(!0),children:[l.jsx(F,{name:"server",className:"h-4 w-4"}),"Switch server"]}),l.jsx(T_,{open:e,onOpenChange:t})]}):null}const C2=U.memo(function({checked:t,onChange:n,disabled:r=!1,indeterminate:s,ariaLabel:o,className:i,iconClassName:a}){const c="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 l.jsx(M9,{checked:t,onCheckedChange:u=>n(!!u),disabled:r,indeterminate:s,"aria-label":o,className:P("group/checkbox relative flex shrink-0 self-center items-center justify-center rounded-[4px] border outline-none",c,"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:l.jsx(I9,{keepMounted:!0,className:P("flex items-center justify-center text-[var(--primary-base)]","data-[unchecked]:hidden",a),children:s?l.jsx(F,{name:"subtract",className:P(d,"text-[var(--primary-base)]")}):l.jsx(F,{name:"check",className:P(d,"text-[var(--primary-base)]")})})})});function Io({className:e,type:t,...n}){return l.jsx("input",{type:t,"data-slot":"input",className:P("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 cm=({className:e="",width:t=70,height:n=70,isAnimated:r=!1})=>{const s=Yx(),i=U.useId().replace(/[^a-zA-Z0-9_-]/g,""),a=`pc-shimmer-mask-${i}`,c=`pc-shimmer-grad-${i}`,d=U.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 l.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?l.jsxs(l.Fragment,{children:[l.jsxs("defs",{children:[l.jsxs("linearGradient",{id:c,gradientUnits:"userSpaceOnUse",x1:"0",y1:"0",x2:"100",y2:"100",children:[l.jsx("stop",{offset:"0%",stopColor:d,stopOpacity:"0"}),l.jsx("stop",{offset:"35%",stopColor:d,stopOpacity:"0"}),l.jsx("stop",{offset:"50%",stopColor:d,stopOpacity:"1"}),l.jsx("stop",{offset:"65%",stopColor:d,stopOpacity:"0"}),l.jsx("stop",{offset:"100%",stopColor:d,stopOpacity:"0"})]}),l.jsx("mask",{id:a,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:"0",y:"0",width:"100",height:"100",children:l.jsxs("g",{fill:"none",children:[l.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:"white",opacity:"0.3"}),l.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:"white",opacity:"0.55"}),l.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:"white",opacity:"0.85"}),l.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:"white",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M28 31H72 M38 31V68 M62 31V55C62 64 67 68 75 68",stroke:"white",strokeWidth:"6",strokeLinecap:"round",strokeLinejoin:"round"})]})})]}),l.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,l.jsx("path",{d:"M50 3 91 27 50 51 9 27Z",fill:d,opacity:r?.04:.08}),l.jsx("path",{d:"M9 27 50 51V97L9 73Z",fill:d,opacity:r?.08:.14}),l.jsx("path",{d:"M50 51 91 27V73L50 97Z",fill:d,opacity:r?.13:.22}),l.jsx("path",{d:"M50 3 91 27V73L50 97 9 73V27Z",stroke:d,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",opacity:r?.6:1}),l.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?l.jsx("g",{mask:`url(#${a})`,children:l.jsx("rect",{x:"-50",y:"-50",width:"200",height:"200",fill:`url(#${c})`,className:"pc-shimmer-sweep"})}):null]})},o3=({children:e})=>{const t=h.useMemo(()=>({height:"var(--oc-wco-titlebar-height, 0px)",right:"var(--oc-wco-right-inset, 0px)"}),[]);return l.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:[l.jsx("div",{className:"app-region-drag fixed left-0 top-0 z-20",style:t,"aria-hidden":!0}),l.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%)"}}),l.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),l.jsx("div",{className:"app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:e})]})},A_=()=>l.jsx("div",{className:"flex h-full min-h-screen w-full items-center justify-center overflow-hidden bg-background text-foreground",children:l.jsx(cm,{width:120,height:120,isAnimated:!0})}),k2=({onRetry:e,errorType:t="network",retryAfter:n,children:r})=>{const s=t==="rate-limit",o=n?Math.ceil(n/60):1;return l.jsx(o3,{children:l.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:s?"Too many attempts":"Unable to reach server"}),l.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."})]}),l.jsx(Me,{type:"button",onClick:e,className:"w-full max-w-xs",children:"Retry"}),r]})})},L_=({isTunnelLocked:e,password:t,setPassword:n,passwordInputRef:r,isSubmitting:s,errorMessage:o,setErrorMessage:i,trustDevice:a,setTrustDevice:c,supportsPasskeys:d,passkeyStatus:f,isPasskeyBusy:u,activePasskeyAction:p,showHostSwitcher:m,onSubmit:g,onPasskeyUnlock:b,onPasskeySetupOnly:y})=>{const S=d&&f.hasPasskeys,v=d&&!f.hasPasskeys;return l.jsx(o3,{children:l.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[l.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[l.jsx("h1",{className:"text-xl font-semibold text-foreground",children:e?"Tunnel access required":"Unlock PiChamber"}),l.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&&l.jsxs("form",{onSubmit:g,className:"w-full space-y-2",children:[S&&l.jsxs(Me,{type:"button",variant:"outline",className:"w-full",onClick:()=>{b()},disabled:s||u&&p!=="auth",children:[u?l.jsx(F,{name:"loader-4",className:"h-4 w-4 animate-spin"}):l.jsx(F,{name:"lock-unlock",className:"h-4 w-4"}),l.jsx("span",{children:u&&p==="auth"?"Cancel passkey":"Use passkey"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"relative flex-1",children:[l.jsx(F,{name:"lock",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),l.jsx(Io,{id:"pichamber-ui-password",ref:r,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:t,onChange:x=>{n(x.target.value),o&&i("")},className:"pl-10","aria-invalid":!!o||void 0,"aria-describedby":o?"oc-ui-auth-error":void 0,disabled:s})]}),l.jsx(Me,{type:"submit",size:"icon",disabled:!t||s,"aria-label":s?"Unlocking":"Unlock",children:s?l.jsx(F,{name:"loader-4",className:"h-4 w-4 animate-spin"}):l.jsx(F,{name:"lock-unlock",className:"h-4 w-4"})})]}),v?l.jsxs("div",{className:"flex items-center justify-between pt-1",children:[l.jsxs("label",{className:"flex items-center gap-2 text-center typography-micro text-muted-foreground",children:[l.jsx(C2,{checked:a,onChange:c,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),l.jsx("span",{children:"Trust this device"})]}),l.jsx(Me,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-foreground",onClick:()=>{y()},disabled:s,children:u&&p==="register"?"Cancel passkey setup":"Add passkey"})]}):l.jsxs("label",{className:"flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground",children:[l.jsx(C2,{checked:a,onChange:c,disabled:s,ariaLabel:"Trust this device",className:"size-4",iconClassName:"size-4"}),l.jsx("span",{children:"Trust this device"})]}),o&&l.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:o})]}),m&&l.jsxs("div",{className:"w-full",children:[l.jsx(s3,{}),l.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})})},N_="/auth/passkey/authenticate/options",R_="/auth/passkey/authenticate/verify",P_="/auth/passkey/register/options",D_="/auth/passkey/register/verify",i3="/api/passkeys",O_="/auth/passkey/status",H_="/api/auth/reset",rc={enabled:!1,hasPasskeys:!1,passkeyCount:0,rpID:null},ua=async(e,t)=>Tt(e,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:t===void 0?void 0:JSON.stringify(t)}),ms=async(e,t)=>{try{const n=await e.json();if(n&&typeof n.error=="string"&&n.error.trim())return n.error}catch{}return t},ef=e=>e instanceof j9&&e.code==="ERROR_CEREMONY_ABORTED",M2=()=>{_9.cancelCeremony()},a3=()=>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."},I2=async()=>{const e=a3();if(!e.supported)throw new Error(e.reason);const t=typeof navigator.userAgent=="string"&&navigator.userAgent.trim()?navigator.userAgent:"This device",n=await ua(P_,{label:t});if(!n.ok)throw new Error(await ms(n,"Could not start passkey setup."));const{requestId:r,optionsJSON:s}=await n.json(),o=await E9({optionsJSON:s}),i=await ua(D_,{requestId:r,response:o});if(!i.ok)throw new Error(await ms(i,"Could not finish passkey setup."));return i.json().catch(()=>null)},F_=async(e,t={})=>{const n=a3();if(!n.supported)throw new Error(n.reason);const r=await ua(N_);if(!r.ok)throw new Error(await ms(r,"Passkey sign-in is not available right now."));const{requestId:s,optionsJSON:o}=await r.json(),i=await T9({optionsJSON:o}),a=await ua(R_,{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 ms(a,"Passkey sign-in failed."));return a.json().catch(()=>null)},V_=async()=>{const e=await Tt(O_,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)return rc;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}},vW=async()=>{const e=await Tt(i3,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(await ms(e,"Could not load passkeys."));const t=await e.json().catch(()=>null);return Array.isArray(t?.passkeys)?t.passkeys:[]},xW=async e=>{const t=await Tt(`${i3}/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(await ms(t,"Could not remove passkey."));return t.json().catch(()=>null)},bW=async()=>{const e=await ua(H_);if(!e.ok)throw new Error(await ms(e,"Could not clear saved authentication."));return e.json().catch(()=>null)},B_=(e,t)=>e.apiBaseUrl===t.apiBaseUrl&&e.runtimeKey===t.runtimeKey,$_=e=>e.shouldUseDesktopShellPasswordLogin?"locked":"error",l3="/auth/session",z_=4,U_=1500,c3="pichamber.uiAuth.trustDevice",q_="desktop-local",Z_="desktop-local",W_=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},G_=(e,t)=>{const n=wr(e),r=wr(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},Ah=()=>bt(),K_=e=>{const t=e.replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"},d3=()=>{if(!bt())return!1;const e=W_();if(!e)return!1;const n=od()||(typeof window<"u"?window.location.origin:"");if(G_(e,n))return!0;try{const r=wr(n);return!!(r&&K_(new URL(r).hostname))}catch{return!1}},dm=()=>d3()?{clientKind:q_,dedupeKey:Z_}:{},Y_=async()=>await Tt(l3,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),X_=()=>typeof window>"u"?!1:window.localStorage.getItem(c3)==="true",J_=async(e,t)=>{const n=Ah();return await Tt(l3,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:"PiChamber Desktop",...dm()})})},Q_=async()=>{if(!bt())return"";const e=await Tt("/api/client-auth/clients",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({label:"PiChamber Desktop",...dm()})}).catch(()=>null);if(!e?.ok)return"";const t=await e.json().catch(()=>null);return typeof t?.token=="string"?t.token.trim():""},tf=()=>bt()&&!d3(),Gr=()=>({apiBaseUrl:od(),runtimeKey:J()}),ut=e=>B_(e,Gr()),nf=async(e,t,n,r)=>{if(!bt()||typeof window>"u")return null;const s=await Qn("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}:{}}},eE=async(e,t)=>{if(!bt()||!t||!ut(e))return!1;const n=await wp().catch(()=>null);if(!n||!ut(e))return!1;const r=M7({runtimeKey:e.runtimeKey,apiBaseUrl:e.apiBaseUrl,hosts:n.hosts,localOrigin:n.localOrigin});return r?r.kind==="local"?(await vc({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>{}),ut(e)):r.host.clientToken===t?!0:ut(e)?(await vc({hosts:n.hosts.map(s=>s.id===r.host.id?{...s,clientToken:t}:s),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{}),ut(e)):!1:!0},xl=async(e,t,n)=>!e||!ut(t)||!await eE(t,e)||!ut(t)?!1:(Bl({apiBaseUrl:t.apiBaseUrl,clientToken:e,requestHeaders:Object.keys(n).length>0?n:null,runtimeKey:t.runtimeKey}),!0);function tE(){const t=h.useMemo(()=>bt(),[]),[n,r]=h.useState(()=>"pending"),[s,o]=h.useState(""),[i,a]=h.useState(!1),[c,d]=h.useState(""),[f,u]=h.useState(void 0),[p,m]=h.useState(!1),[g,b]=h.useState(rc),[y,S]=h.useState(!1),[v,x]=h.useState(!1),[k,w]=h.useState(()=>X_()),[C,I]=h.useState(null),_=h.useRef(null),E=h.useRef(!1);h.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(c3,k?"true":"false")},[k]);const M=h.useCallback(async($=Gr())=>{try{const G=await V_();return ut($)&&b(G),G}catch{return ut($)&&b(rc),rc}},[!1]);h.useEffect(()=>{let $=!1;return(async()=>{try{if(!window.isSecureContext||!A9()){$||S(!1);return}$||S(!0)}catch{$||S(!1)}})(),()=>{$=!0}},[!1]);const T=h.useRef(0),A=h.useRef(null),j=h.useRef(null),R=h.useCallback(()=>{A.current!==null&&(window.clearTimeout(A.current),A.current=null)},[]),O=h.useCallback(()=>{T.current=0,R()},[R]),N=h.useCallback(()=>T.current>=z_?!1:(T.current+=1,R(),A.current=window.setTimeout(()=>{A.current=null,j.current?.()},U_*T.current),!0),[R]);h.useEffect(()=>R,[R]);const D=h.useCallback(async()=>{const $=Gr();r(G=>G==="authenticated"?G:"pending");try{const[G,Q]=await Promise.all([Y_(),M($)]),z=await G.text();if(!ut($))return;if(G.ok){O(),r("authenticated"),m(!1),d(""),u(void 0);return}if(G.status===401){let X={};try{X=JSON.parse(z)}catch{X={}}O(),m(X.tunnelLocked===!0),b(Q),r("locked"),u(void 0);return}if(G.status===429){let X={};try{X=JSON.parse(z)}catch{X={}}O(),u(X.retryAfter),m(!1),r("rate-limited");return}if(N())return;r("error"),m(!1)}catch(G){if(!ut($))return;if(console.warn("Failed to check session status:",G),$_({shouldUseDesktopShellPasswordLogin:tf()})==="locked"){r("locked"),u(void 0),m(!1);return}if(N())return;r("error"),m(!1)}},[M,O,N,!1]);h.useEffect(()=>{j.current=D},[D]),h.useEffect(()=>{D()},[D,!1]),h.useEffect(()=>I7(()=>{O(),D()}),[D,O,!1]),h.useEffect(()=>sn(()=>{M2(),o(""),d(""),u(void 0),m(!1),a(!1),I(null),x(!1),O(),r("pending"),D()}),[D,O,!1]),h.useEffect(()=>{n==="locked"&&(E.current=!1)},[!1,n]),h.useEffect(()=>{n==="locked"&&_.current&&(_.current.focus(),_.current.select())},[n]),h.useEffect(()=>{n==="authenticated"&&(E.current=!0)},[!1,n]);const K=h.useCallback(async()=>{const $=Gr();I("register"),x(!0);try{await I2()}finally{ut($)&&(I(null),x(!1))}ut($)&&await M($)},[M]),V=h.useCallback(()=>{M2(),I(null),x(!1)},[]),W=h.useCallback(async $=>{if(p||!s||i)return;v&&V();const G=Gr(),Q=H1();a(!0),d("");try{if(tf()){const X=await nf(s,k,G,Q);if(!ut(G))return;if(X?.token){if(o(""),m(!1),!await xl(X.token,G,Q))return;r("authenticated");return}if(X?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(X?.status===429){u(void 0),m(!1),r("rate-limited");return}}const z=await J_(s,k);if(!ut(G))return;if(z.ok){const X=await z.json().catch(()=>null);if(!ut(G))return;const Y=Ah();let ce="";if(Y&&(ce=typeof X?.clientToken=="string"&&X.clientToken.trim()?X.clientToken.trim():"",!ce)){const se=await nf(s,k,G,Q);if(!ut(G)||(ce=se?.token||await Q_(),!ut(G)))return}if(o(""),m(!1),ce&&!await xl(ce,G,Q))return;if($&&y)try{if(await K(),!ut(G))return;ke.success("Passkey added"),r("authenticated");return}catch(se){if(ef(se))ke.message("Passkey setup canceled");else{const ue=se instanceof Error?se.message:"Passkey setup failed.";ke.error(ue)}r("authenticated");return}r("authenticated");return}if(z.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(z.status===429){const X=await z.json().catch(()=>({}));u(X.retryAfter),m(!1),r("rate-limited");return}d("Unexpected response from server."),m(!1),r("error")}catch(z){if(!ut(G))return;console.warn("Failed to submit UI password:",z);const X=tf()?await nf(s,k,G,Q):null;if(!ut(G))return;if(X?.token){if(o(""),m(!1),!await xl(X.token,G,Q))return;r("authenticated");return}if(X?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(X?.status===429){u(void 0),m(!1),r("rate-limited");return}d("Network error. Check connection and retry."),m(!1),r("error")}finally{ut(G)&&a(!1)}},[V,v,i,p,s,K,y,k]),B=h.useCallback(async()=>{if(i||!y)return;if(v){V();return}x(!0),I("auth"),d("");const $=Gr(),G=H1();try{const Q=await F_(k,{issueClientToken:Ah(),clientLabel:"PiChamber Desktop",...dm()});if(!ut($))return;if(typeof Q?.clientToken=="string"&&Q.clientToken.trim()){const z=Q.clientToken.trim();if(!await xl(z,$,G))return}m(!1),r("authenticated")}catch(Q){if(!ut($)||ef(Q))return;const z=Q instanceof Error?Q.message:"Passkey sign-in failed.";d(z)}finally{ut($)&&(I(null),x(!1))}},[V,v,i,y,k]),Z=h.useCallback(async()=>{if(i||!y)return;if(v){V();return}const $=Gr();I("register"),x(!0);try{if(await I2(),!ut($))return;ke.success("Passkey added"),await M($)}catch(G){if(!ut($))return;if(ef(G))ke.message("Passkey setup canceled");else{const Q=G instanceof Error?G.message:"Passkey setup failed.";ke.error(Q)}}finally{ut($)&&(I(null),x(!1))}},[V,v,i,M,y]);return{state:n,password:s,setPassword:o,passwordInputRef:_,isSubmitting:i,errorMessage:c,setErrorMessage:d,retryAfter:f,isTunnelLocked:p,passkeyStatus:g,supportsPasskeys:y,isPasskeyBusy:v,trustDevice:k,setTrustDevice:w,activePasskeyAction:C,showHostSwitcher:t,resetTransientRetry:O,checkStatus:D,handleSubmit:async $=>{$.preventDefault(),await W(!1)},handlePasswordUnlock:W,handlePasskeyUnlock:B,handlePasskeySetupOnly:Z}}const wW=({children:e})=>{const{state:t,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,retryAfter:c,isTunnelLocked:d,passkeyStatus:f,supportsPasskeys:u,isPasskeyBusy:p,trustDevice:m,setTrustDevice:g,activePasskeyAction:b,showHostSwitcher:y,resetTransientRetry:S,checkStatus:v,handleSubmit:x,handlePasskeyUnlock:k,handlePasskeySetupOnly:w}=tE();return t==="pending"?l.jsx(A_,{}):t==="error"?l.jsx(k2,{onRetry:()=>{S(),v()},errorType:"network",children:y&&l.jsxs("div",{className:"w-full max-w-xs",children:[l.jsx(s3,{}),l.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})}):t==="rate-limited"?l.jsx(k2,{onRetry:()=>{v()},errorType:"rate-limit",retryAfter:c}):t==="locked"?l.jsx(L_,{isTunnelLocked:d,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,trustDevice:m,setTrustDevice:g,supportsPasskeys:u,passkeyStatus:f,isPasskeyBusy:p,activePasskeyAction:b,showHostSwitcher:y,onSubmit:x,onPasskeyUnlock:k,onPasskeySetupOnly:w}):l.jsx(l.Fragment,{children:e})},Hd=e=>{try{return new URL(e)}catch{return null}},SW=e=>{const t=Hd(e.trim());return t?t.protocol==="http:"||t.protocol==="https:":!1},nE=e=>{const t=Hd(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?null:`https://icons.duckduckgo.com/ip3/${t.hostname.toLowerCase()}.ico`},rE=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),sE=e=>{const t=Hd(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?!1:rE.has(t.hostname.toLowerCase())},oE=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi,iE=e=>{if(!e)return[];const t=e.match(oE);if(!t||t.length===0)return[];const n=new Set,r=[];for(const s of t){const o=s.replace(/[),.;:!?'"`]+$/g,"");!o||!sE(o)||n.has(o)||(n.add(o),r.push(o))}return r},Lh=async e=>{if(typeof window>"u")return!1;const t=e.trim();if(!t)return!1;const n=Hd(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 aE(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=Ed();return e}catch{return"unknown"}}function lE(){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 cE(){const e=j7();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 dE(e){const t=new URLSearchParams;return t.set("deviceClass",aE()),t.set("arch",lE()),t.set("platform",cE()),e==="desktop"?(t.set("appType","desktop-electron"),t.set("instanceMode",ld()?"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 ii(e,t){try{const n=dE(e);t&&n.set("currentVersion",t);const r=await Tt(`/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 uE(){return Jn()?"mobile":bo()?"desktop":Sp()?"web":null}const _2={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,serverInfo:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},fE=Et()((e,t)=>({..._2,checkForUpdates:async()=>{const n=uE();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,s=null;if(n==="desktop"){const o="1.0.5",i=!ld(),[a,c]=await Promise.allSettled([F1(),i?ii("web"):ii("desktop",o)]),d=a.status==="fulfilled"?a.value:null,f=c.status==="fulfilled"?c.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 ii("web"),s=r?.nextSuggestedCheckInSec??null;else if(n==="mobile"){const o="1.0.5",[i,a]=await Promise.all([ii("mobile",o),ii("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 F1();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 E7(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 _7())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(_2)}}));function hE({className:e,...t}){return l.jsx("div",{"data-slot":"card",className:P("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",e),...t})}function pE({className:e,...t}){return l.jsx("div",{"data-slot":"card-header",className:P("@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 mE({className:e,...t}){return l.jsx("div",{"data-slot":"card-title",className:P("leading-none font-semibold",e),...t})}function gE({className:e,...t}){return l.jsx("div",{"data-slot":"card-content",className:P("px-6",e),...t})}class yE extends h.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 ir(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:l.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:l.jsxs(hE,{className:"w-full max-w-md",children:[l.jsx(pE,{className:"text-center",children:l.jsxs(mE,{className:"flex items-center justify-center gap-2 text-destructive",children:[l.jsx(F,{name:"error-warning",className:"h-5 w-5"}),t.title]})}),l.jsxs(gE,{className:"space-y-4",children:[l.jsx("p",{className:"text-sm text-muted-foreground text-center",children:t.description}),this.state.error&&l.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[l.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:t.detailsSummary}),l.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}`:""]})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Me,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[l.jsx(F,{name:"restart",className:"h-4 w-4 mr-2"}),t.tryAgain]}),l.jsx(Me,{onClick:this.handleCopy,variant:"outline",className:"flex-1",children:this.state.copied?t.copied:t.copy})]})]})]})}):this.props.children}}const CW=({children:e,fallback:t})=>{const n=h.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 l.jsx(yE,{fallback:t,strings:n,children:e})},vE=1e3,E2=.5,j2={length:0,offset:0},T2=(e,t)=>Math.abs(e.length-t.length)<E2&&Math.abs(e.offset-t.offset)<E2,u3=({containerRef:e,minThumbSize:t=32,hideDelayMs:n=1e3,className:r,disableHorizontal:s=!1,observeMutations:o=!0,suppressVisibility:i=!1,userIntentOnly:a=!1})=>{const[c,d]=h.useState(!1),[f,u]=h.useState({length:0,offset:0}),[p,m]=h.useState({length:0,offset:0}),g=h.useRef(null),b=h.useRef(null),y=h.useRef(null),S=h.useRef(!1),v=h.useRef(!1),x=h.useRef(0),k=h.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),w=h.useRef(null),C=h.useRef(new Set),I=h.useCallback(()=>{const B=e.current;if(!B)return;const{scrollHeight:Z,clientHeight:L,scrollTop:$,scrollWidth:G,clientWidth:Q,scrollLeft:z}=B,X=8;let Y=j2;if(Z>L){const se=Math.max(L-X*2,0),ue=L/Z*se,Ie=Math.max(t,Math.min(se,ue)),de=Math.max(se-Ie,0),Fe=Math.max(Z-L,1),$e=$/Fe*de;Y={length:Ie,offset:$e}}u(se=>T2(se,Y)?se:Y);let ce=j2;if(!s&&G>Q){const se=Math.max(Q-X*2,0),ue=Q/G*se,Ie=Math.max(t,Math.min(se,ue)),de=Math.max(se-Ie,0),Fe=Math.max(G-Q,1),$e=z/Fe*de;ce={length:Ie,offset:$e}}m(se=>T2(se,ce)?se:ce)},[e,t,s]),_=h.useCallback(()=>{y.current===null&&(y.current=requestAnimationFrame(()=>{y.current=null,I()}))},[I]),E=h.useCallback((B,Z)=>{if(!Z){C.current.clear();return}const L=new Set;L.add(B),Array.from(B.children).forEach($=>{L.add($)}),C.current.forEach($=>{L.has($)||Z.unobserve($)}),L.forEach($=>{C.current.has($)||Z.observe($)}),C.current=L},[]),M=h.useCallback(()=>{g.current&&clearTimeout(g.current),!v.current&&(g.current=setTimeout(()=>d(!1),n))},[n]),T=h.useCallback(()=>{x.current=Date.now()},[]),A=h.useCallback(()=>{b.current&&cancelAnimationFrame(b.current),b.current=requestAnimationFrame(()=>{if(I(),i&&!S.current){d(!1);return}if(a&&!S.current&&!(Date.now()-x.current<=vE)){d(!1);return}d(!0),M()})},[M,i,I,a]);h.useEffect(()=>{const B=e.current;if(!B)return;I(),d(!1);const Z=()=>A(),L=X=>{(X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="PageUp"||X.key==="PageDown"||X.key==="Home"||X.key==="End"||X.key===" ")&&T()};B.addEventListener("scroll",Z,{passive:!0}),a&&(B.addEventListener("wheel",T,{passive:!0}),B.addEventListener("touchstart",T,{passive:!0}),B.addEventListener("touchmove",T,{passive:!0}),B.addEventListener("keydown",L));const $=typeof ResizeObserver<"u"?new ResizeObserver(()=>{_()}):null;E(B,$);const G=o&&typeof MutationObserver<"u"?new MutationObserver(()=>{E(B,$),_()}):null;G?.observe(B,{childList:!0});const Q=()=>_(),z=()=>_();return B.addEventListener("input",Q,!0),B.addEventListener("load",z,!0),()=>{B.removeEventListener("scroll",Z),B.removeEventListener("input",Q,!0),B.removeEventListener("load",z,!0),a&&(B.removeEventListener("wheel",T),B.removeEventListener("touchstart",T),B.removeEventListener("touchmove",T),B.removeEventListener("keydown",L)),$?.disconnect(),G?.disconnect(),C.current.clear(),g.current&&clearTimeout(g.current),b.current&&cancelAnimationFrame(b.current),y.current&&cancelAnimationFrame(y.current)}},[e,A,T,o,_,E,I,a]),h.useEffect(()=>{i&&(S.current||(d(!1),g.current&&(clearTimeout(g.current),g.current=null)))},[i]);const j=(B,Z)=>{const L=e.current;L&&(S.current=!0,k.current={pointerX:B.clientX,pointerY:B.clientY,scrollTop:L.scrollTop,scrollLeft:L.scrollLeft},w.current=Z,T(),d(!0),g.current&&clearTimeout(g.current),B.currentTarget.setPointerCapture(B.pointerId))},R=B=>{if(!S.current)return;const Z=e.current;if(!Z)return;const L=w.current;if(L==="vertical"){const{pointerY:$,scrollTop:G}=k.current,Q=B.clientY-$,z=Z.clientHeight,X=Math.max(z-f.length,1),Y=Math.max(Z.scrollHeight-Z.clientHeight,1),ce=Q/X*Y;Z.scrollTop=G+ce}else if(L==="horizontal"){const{pointerX:$,scrollLeft:G}=k.current,Q=B.clientX-$,z=Z.clientWidth,X=Math.max(z-p.length,1),Y=Math.max(Z.scrollWidth-Z.clientWidth,1),ce=Q/X*Y;Z.scrollLeft=G+ce}},O=B=>{S.current&&(S.current=!1,B.currentTarget.releasePointerCapture(B.pointerId),M())},N=h.useCallback(()=>{v.current=!0,g.current&&(clearTimeout(g.current),g.current=null)},[]),D=h.useCallback(()=>{v.current=!1,M()},[M]),K=f.length>0,V=p.length>0;if(!K&&!V)return null;const W=8;return l.jsxs("div",{className:P("overlay-scrollbar",r),"aria-hidden":"true",style:{opacity:c?1:0},children:[K&&l.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical","data-overlay-scrollbar-thumb":"vertical",style:{height:`${f.length}px`,top:`${W+f.offset}px`,right:`${W/2}px`},onPointerDown:B=>j(B,"vertical"),onPointerMove:R,onPointerUp:O,onPointerCancel:O,onMouseEnter:N,onMouseLeave:D}),V&&l.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal","data-overlay-scrollbar-thumb":"horizontal",style:{width:`${p.length}px`,left:`${W+p.offset}px`,bottom:`${W/2}px`},onPointerDown:B=>j(B,"horizontal"),onPointerMove:R,onPointerUp:O,onPointerCancel:O,onMouseEnter:N,onMouseLeave:D})]})};u3.displayName="OverlayScrollbar";const f3=u3;function xE(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n&&typeof n=="object"&&(n.current=t)})}}const Fd=h.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:c,style:d,className:f,children:u,...p},m)=>{const g=h.useRef(null),b=h.useRef("none"),y=p["data-scroll-shadow"];delete p["data-scroll-shadow"];const S=h.useMemo(()=>{const w={...d};return w["--scroll-shadow-size"]=`${r}px`,w},[r,d]),v=h.useCallback((w,C,I,_,E)=>{const M=`${_}${E.charAt(0).toUpperCase()}${E.slice(1)}Scroll`;C&&I?(w.dataset[M]="true",w.removeAttribute(`data-${_}-scroll`),w.removeAttribute(`data-${E}-scroll`)):(w.dataset[`${_}Scroll`]=String(C),w.dataset[`${E}Scroll`]=String(I),w.removeAttribute(`data-${_}-${E}-scroll`))},[]),x=h.useCallback(w=>{["top","bottom","top-bottom","left","right","left-right"].forEach(C=>{w.removeAttribute(`data-${C}-scroll`)})},[]),k=h.useCallback(()=>{const w=g.current;if(!w)return;if(!s){x(w);return}const C=1,I=t==="vertical"?w.scrollTop>n+C:w.scrollLeft>n+C;let _=t==="vertical"?w.scrollHeight-(w.scrollTop+w.clientHeight)>n+C:w.scrollWidth-(w.scrollLeft+w.clientWidth)>n+C;const E=o&&t==="vertical"?!1:I;i&&t==="vertical"&&(_=!1),v(w,E,_,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const M=E&&_?"both":E?t==="vertical"?"top":"left":_?t==="vertical"?"bottom":"right":"none";M!==b.current&&(b.current=M,c?.(M))},[x,o,i,s,n,c,t,v]);return h.useEffect(()=>{const w=g.current;if(!w)return;let C=null;const I=()=>{C===null&&(C=requestAnimationFrame(()=>{C=null,k()}))},_=()=>k(),E=typeof ResizeObserver<"u"?new ResizeObserver(I):null,M=a&&typeof MutationObserver<"u"?new MutationObserver(I):null;return k(),w.addEventListener("scroll",_,{passive:!0}),E?.observe(w),M?.observe(w,{childList:!0,subtree:!0,characterData:!0}),()=>{C!==null&&cancelAnimationFrame(C),w.removeEventListener("scroll",_),E?.disconnect(),M?.disconnect()}},[k,a]),l.jsx(e,{...p,ref:xE(g,m),className:f,"data-orientation":t,"data-scroll-shadow":y??!0,style:S,children:u})});Fd.displayName="ScrollShadow";const Fn=h.forwardRef(({className:e,outerClassName:t,children:n,style:r,minThumbSize:s,hideDelayMs:o,as:i="div",scrollbarClassName:a,disableHorizontal:c=!1,observeMutations:d=!0,fillContainer:f=!0,preventOverscroll:u=!1,useScrollShadow:p=!1,scrollShadowSize:m,hideTopScrollShadow:g=!1,userIntentOnly:b=!1,...y},S)=>{const v=h.useRef(null);return h.useImperativeHandle(S,()=>v.current,[]),l.jsxs("div",{className:P("relative flex flex-col min-h-0 w-full overflow-hidden",u&&"overscroll-none",t),children:[p?l.jsx(Fd,{as:i,ref:v,size:m,hideTopShadow:g,className:P("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",c?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,observeMutations:d,...y,children:n}):l.jsx(i,{ref:v,className:P("overlay-scrollbar-target overlay-scrollbar-container",u&&"overscroll-none",f?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",c?"overflow-y-auto overflow-x-hidden":"overflow-auto",e),style:r,...y,children:n}),l.jsx(f3,{containerRef:v,minThumbSize:s,hideDelayMs:o,className:a,disableHorizontal:c,observeMutations:d,userIntentOnly:b})]})});Fn.displayName="ScrollableOverlay";const A2="mobile-overlay-root",L2=16,N2=200,bE=()=>{if(typeof document>"u")return null;let e=document.getElementById(A2);return e||(e=document.createElement("div"),e.id=A2,document.body.appendChild(e)),e},fa=({open:e,title:t,onClose:n,children:r,footer:s,className:o,contentMaxHeightClassName:i,renderHeader:a})=>{const c=h.useRef(null),[d,f]=h.useState(!1),[u,p]=h.useState(!1);if(typeof document<"u"&&!c.current&&(c.current=bE()),h.useEffect(()=>{if(!e){f(!1),p(!1);return}const b=window.setTimeout(()=>f(!0),L2),y=window.setTimeout(()=>p(!0),L2+N2+50);return()=>{window.clearTimeout(b),window.clearTimeout(y)}},[e]),h.useLayoutEffect(()=>{if(e)return window.dispatchEvent(new Event("oc:mobile-overlay-opened")),()=>{window.dispatchEvent(new Event("oc:mobile-overlay-closed"))}},[e]),h.useEffect(()=>{if(!e)return;const b=document.body.style.overflow;document.body.style.overflow="hidden";const y=S=>{S.key==="Escape"&&n()};return document.addEventListener("keydown",y),()=>{document.body.style.overflow=b,document.removeEventListener("keydown",y)}},[e,n]),!e||!c.current)return null;const m=i??"max-h-[min(70vh,520px)]",g=l.jsx("div",{className:P("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:l.jsxs("div",{className:P("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 ${N2}ms cubic-bezier(0.32, 0.72, 0, 1)`},onClick:b=>b.stopPropagation(),children:[(()=>{const b=l.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:l.jsx(F,{name:"close",className:"h-4 w-4"})});return a?a(b):l.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[l.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:t}),b]})})(),l.jsx(Fn,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:P("min-h-0 flex-1",m),className:"px-2 py-2 pwa-overlay-scroll",children:r}),s?l.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 na.createPortal(g,c.current)},wE="Awaiting first prompt";function h3(e,t="Untitled Session"){const n=e?.title?.trim();return n||(e?.messageCount===0?wE:t)}const rf=new Set,sf=new Set,of=new Set,af=new Set,Vd={onDeleteRequest(e){return rf.add(e),()=>{rf.delete(e)}},requestDelete(e){e.sessions.length&&rf.forEach(t=>t(e))},onCreateRequest(e){return sf.add(e),()=>{sf.delete(e)}},requestCreate(e){const t=e??{};sf.forEach(n=>n(t))},onDirectoryRequest(e){return of.add(e),()=>{of.delete(e)}},requestDirectoryDialog(){of.forEach(e=>e())},onGitRefreshHint(e){return af.add(e),()=>{af.delete(e)}},requestGitRefresh(e){e.directory.trim()&&af.forEach(t=>t(e))}},wa=h.createContext(null),SE=40,R2=20*1024*1024;function CE(e){const t=new Map;let n=0,r=0,s=!0,o=Promise.resolve();const i=(v,x)=>JSON.stringify([x?.directory??"",v]),a=v=>new TextEncoder().encode(v).byteLength,c=v=>{const x=t.get(v);x&&(n=Math.max(0,n-x.bytes)),t.delete(v)},d=v=>{const x=v.endsWith("/")?v:`${v}/`;for(const[k,w]of t)(w.sourcePath===v||w.sourcePath.startsWith(x))&&c(k)},f=(v,x)=>x.isFile&&x.mtimeMs!==void 0&&v.mtimeMs===x.mtimeMs&&v.size===x.size,u=()=>{t.clear(),n=0},p=(v,x,k,w)=>{if(!s||!w.isFile||w.mtimeMs===void 0)return k;const C=a(k.content);if(C>R2)return k;for(c(v),t.set(v,{...k,sourcePath:x,size:w.size,mtimeMs:w.mtimeMs,bytes:C}),n+=C;t.size>SE||n>R2;){const I=t.keys().next().value;if(!I)break;c(I)}return k},m=async(v,x,k,w)=>{const C=await e.statFile?.(x,k).catch(()=>null),I=await e.readFile(x,k),_=await e.statFile?.(x,k).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return w!==r?g(x,k):C&&_&&C.isFile&&_.isFile&&C.mtimeMs!==void 0&&_.mtimeMs!==void 0&&C.size===_.size&&C.mtimeMs===_.mtimeMs?p(v,x,I,_):I},g=e.readFile?async(v,x)=>{if(await o,!s)throw new Error("File cache owner disposed");const k=r;if(x?.allowOutsideWorkspace)return e.readFile(v,x);const w=i(v,x),C=t.get(w);if(!C)return m(w,v,x,k);const I=await e.statFile?.(v,x).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return k!==r?g(v,x):!I||!f(C,I)?(c(w),m(w,v,x,k)):(t.delete(w),t.set(w,C),{content:C.content,path:C.path,revision:C.revision})}:void 0,b=async(v,x)=>{const k=o;let w;o=new Promise(C=>{w=C}),await k,r+=1,v.forEach(d);try{return await x()}finally{v.forEach(d),r+=1,w()}},y={...e,readFile:g,writeFile:e.writeFile?(v,x,k)=>b([v],()=>e.writeFile(v,x,k)):void 0,delete:e.delete?v=>b([v],()=>e.delete(v)):void 0,rename:e.rename?(v,x)=>b([v,x],()=>e.rename(v,x)):void 0},S=xp(v=>{v.runtimeKey!==v.previousRuntimeKey&&(r+=1,u())});return{files:y,dispose:()=>{s=!1,r+=1,u(),S()}}}function kW({apis:e,children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=CE(e.files);return r(i),()=>{i.dispose(),r(a=>a===i?null:a)}},[e.files]);const s=n?.files??e.files,o=h.useMemo(()=>({...e,files:s}),[e,s]);return l.jsx(wa.Provider,{value:o,children:t})}const kE=600,ME=1600,P2=10,p3=U.createContext(null);class m3 extends U.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function IE({delayDuration:e=0,skipDelayDuration:t,delay:n,closeDelay:r,...s}){return l.jsx(L9,{delay:n??e,closeDelay:r??t,...s})}function pt({delayDuration:e,open:t,onOpenChange:n,...r}){const[s,o]=U.useState(!1),i=U.useRef(null),a=U.useRef(null),c=U.useRef(null),d=U.useRef(!1),f=t!==void 0,u=f?t:s,p=U.useCallback(()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),m=U.useCallback(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[]),g=U.useCallback(v=>{f||o(v)},[f]),b=U.useMemo(()=>({handlePointerDown:v=>{v.pointerType!=="touch"&&v.pointerType!=="pen"||(p(),m(),c.current={x:v.clientX,y:v.clientY},i.current=window.setTimeout(()=>{f||(d.current=!0,g(!0))},kE))},handlePointerMove:v=>{const x=c.current;if(!x)return;const k=Math.abs(v.clientX-x.x),w=Math.abs(v.clientY-x.y);(k>P2||w>P2)&&(p(),c.current=null)},handlePointerEnd:()=>{p(),c.current=null,d.current&&(m(),a.current=window.setTimeout(()=>{d.current=!1,g(!1)},ME))},handleClickCapture:v=>{d.current&&(d.current=!1,v.preventDefault(),v.stopPropagation())},handleContextMenu:v=>{d.current&&v.preventDefault()}}),[m,p,f,g]);U.useEffect(()=>()=>{p(),m()},[m,p]);const y=U.useCallback((v,x)=>{f||o(v),n?.(v,x)},[f,n]),S=l.jsx(p3.Provider,{value:b,children:l.jsx(N9,{open:u,onOpenChange:y,...r})});return e===void 0?S:l.jsx(IE,{delayDuration:e,children:S})}function mt({asChild:e,children:t,onPointerDown:n,onPointerMove:r,onPointerUp:s,onPointerCancel:o,onClickCapture:i,onContextMenu:a,...c}){const d=U.useContext(p3),f=e&&U.isValidElement(t)?{render:t}:{children:t};return l.jsx(m3,{fallback:t,children:l.jsx(R9,{"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)},...c,...f})})}function gt({className:e,sideOffset:t=0,side:n,align:r,children:s,style:o,...i}){return l.jsx(m3,{children:l.jsx(P9,{children:l.jsx(D9,{sideOffset:t,side:n,align:r,className:"z-50",children:l.jsxs(O9,{"data-slot":"tooltip-content",className:P("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,l.jsx(H9,{className:"fill-[var(--surface-elevated)] z-50 size-2"})]})})})})}const _E="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)",EE="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 jE(){const e=()=>typeof document<"u"&&document.documentElement.classList.contains("dark"),[t,n]=U.useState(e);return U.useEffect(()=>{const r=()=>n(e()),s=new MutationObserver(r);return s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r(),()=>s.disconnect()},[]),t}function TE(e){U.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 MW=({...e})=>{const t=jE();return TE(t?_E:EE),l.jsx(F9,{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})},AE="pichamber_session_load_perf",Nh=1e3,LE=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"]),NE=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"]),RE=new Set(["complete","error","stale","deduplicated","canceled"]),g3=()=>{if(Lo())return!0;if(typeof window>"u")return!1;try{return window.localStorage.getItem(AE)==="1"}catch{return!1}};function PE(){return typeof window>"u"?0:window.__pichamberSessionLoadPerformance?.events.length??0}function DE(){typeof window>"u"||window.__pichamberSessionLoadPerformance&&(window.__pichamberSessionLoadPerformance.events=[])}const D2=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),OE=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 HE(e){if(!g3()||!LE.has(e.operation)||e.caller!==void 0&&!NE.has(e.caller))return()=>{};const t=D2();return(n,r)=>{if(typeof window>"u"||!RE.has(n))return;const s=window.__pichamberSessionLoadPerformance??{events:[]},o=OE(e.queuedMs),i=lf(e.requestLimit),a=lf(r?.retryCount??e.retryCount),c=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,D2()-t),...a!==void 0?{retryCount:a}:{},...c!==void 0?{recordCount:c}:{},at:Date.now()}),s.events.length>Nh&&s.events.splice(0,s.events.length-Nh),window.__pichamberSessionLoadPerformance=s}}const O2="pichamber.chat.first_message_visible";function FE(e){const t=e?.enabled??g3,n=e?.requestFrame??(c=>window.requestAnimationFrame(c)),r=e?.cancelFrame??(c=>window.cancelAnimationFrame(c)),s=e?.markVisible??(()=>{performance.mark(O2),performance.clearMarks(O2)}),o=e?.startEvent??HE,i=new Set;let a=null;return{schedule(c,d){if(!t()||i.has(c))return()=>{};a&&(r(a.frame),a=null);const f=o({operation:"session-messages.visible",caller:"selected-session",recordCount:d}),u=n(()=>{a?.key!==c||a.frame!==u||(a=null,i.add(c),i.size>Nh&&i.delete(i.values().next().value),s(),f("complete"))});return a={key:c,frame:u},()=>{a?.key!==c||a.frame!==u||(r(u),a=null)}}}}const VE=1e3,BE=6,$E=16.7,zE=50,UE=(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},qE=(e=VE)=>{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:UE(n,95),samples:n.length}}}},H2=(e,t=BE)=>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})),ai=(e,t=1)=>Number.isFinite(e)?e.toFixed(t):"—",ZE=e=>typeof e!="number"||!Number.isFinite(e)||e<0?null:e/(1024*1024),WE=250,GE=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),KE=()=>{if(typeof performance>"u")return null;const e=performance.memory?.usedJSHeapSize;return typeof e=="number"&&Number.isFinite(e)?e:null},YE=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()=>{}}},XE=(e,t={})=>{const n=(t.getStreamSnapshot??A7)(),r=(t.getSyncSnapshot??px)(),s=(t.getSessionLoadEventCount??PE)(),o=H2(n.entries.map(a=>({metric:a.metric,value:a.count}))),i=H2(Object.entries(r??{}).map(([a,c])=>({metric:`sync.${a}`,value:typeof c=="number"?c:0})));return{...e,capturedAt:Date.now(),stream:o,sync:i,sessionLoadEvents:s}},JE=(e,t={})=>{const n=t.now??GE,r=t.requestFrame??(S=>window.requestAnimationFrame(S)),s=t.cancelFrame??(S=>window.cancelAnimationFrame(S)),o=t.observeLongTasks??YE,i=t.readHeapUsedBytes??KE,a=qE();let c=0,d=0,f=0,u=0,p=0,m=!1;const g=o(S=>{c+=1,d=S,f+=S}),b=S=>{const v=a.snapshot();e(XE({fps:v.fps,frameMs:{last:v.lastMs,p95:v.p95Ms},longTasks:{count:c,lastMs:d,totalMs:f},heapUsedMb:ZE(i())},t)),u=S},y=S=>{if(m)return;const v=typeof S=="number"&&Number.isFinite(S)?S:n();a.sample(v),(u===0||v-u>=WE)&&b(v),p=r(y)};return p=r(y),{stop(){m=!0,s(p),g(),a.reset()},reset(){a.reset(),c=0,d=0,f=0,QE(),b(n())}}},QE=()=>{T7(),hx(),DE()},ej=()=>({capturedAt:0,fps:0,frameMs:{last:0,p95:0},longTasks:{count:0,lastMs:0,totalMs:0},heapUsedMb:null,stream:[],sync:[],sessionLoadEvents:0});let Rh=ej();const tj=()=>h.useSyncExternalStore(N7,Lo,()=>!1),nj=e=>e>=zE?"var(--status-error)":e>=$E?"var(--status-warning)":"var(--surface-foreground)",Hs=(e,t)=>{e&&e.textContent!==t&&(e.textContent=t)},rj=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"},bl=8,cf=(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,c=s?.height||window.innerHeight,d=o+bl,f=i+bl,u=Math.max(d,o+a-n-bl),p=Math.max(f,i+c-r-bl);return{left:Math.round(Math.min(Math.max(e,d),u)),top:Math.round(Math.min(Math.max(t,f),p))}},F2=(e,t)=>{e.style.left=`${t.left}px`,e.style.top=`${t.top}px`,e.style.right="auto",e.style.transform="none"},sj=()=>{const[e,t]=h.useState(!1),[n,r]=h.useState(null),[s,o]=h.useState(!1),i=h.useRef(null),a=h.useRef(null),c=h.useRef(null),d=h.useRef(null),f=h.useRef(null),u=h.useRef(null),p=h.useRef(null),m=h.useRef(null),g=h.useRef(Rh),b=h.useRef(null),y=h.useCallback(C=>{const I=i.current;if(!I||a.current)return;const _=I.getBoundingClientRect(),E=cf(C.left,C.top,_.width,_.height);E.left===C.left&&E.top===C.top||(F2(I,E),r(E))},[]);h.useLayoutEffect(()=>{n&&y(n)},[e,y,n]),h.useEffect(()=>{if(!n||typeof window>"u")return;const C=()=>{y(n)},I=window.visualViewport;return window.addEventListener("resize",C),I?.addEventListener("resize",C),()=>{window.removeEventListener("resize",C),I?.removeEventListener("resize",C)}},[y,n]);const S=h.useCallback(C=>{if(C.button!==0||a.current)return;const I=i.current;if(!I)return;const _=I.getBoundingClientRect();a.current={pointerId:C.pointerId,offsetX:C.clientX-_.left,offsetY:C.clientY-_.top,originLeft:_.left,originTop:_.top,left:_.left,top:_.top,width:_.width,height:_.height};try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}o(!0),C.preventDefault()},[]),v=h.useCallback(C=>{const I=a.current;if(!I||I.pointerId!==C.pointerId)return;const _=cf(C.clientX-I.offsetX,C.clientY-I.offsetY,I.width,I.height);_.left===I.left&&_.top===I.top||(I.left=_.left,I.top=_.top,i.current?.style.setProperty("transform",`translate3d(${_.left-I.originLeft}px, ${_.top-I.originTop}px, 0)`),C.cancelable&&C.preventDefault())},[]),x=h.useCallback((C,I)=>{const _=a.current;if(!_||_.pointerId!==C.pointerId)return;const E=i.current,M=E?.getBoundingClientRect(),T=I?{left:_.originLeft,top:_.originTop}:cf(C.clientX-_.offsetX,C.clientY-_.offsetY,M?.width??_.width,M?.height??_.height);a.current=null,E&&(I?E.style.transform="none":F2(E,T)),o(!1),I||r(T);try{C.currentTarget.hasPointerCapture(C.pointerId)&&C.currentTarget.releasePointerCapture(C.pointerId)}catch{}},[]);h.useEffect(()=>()=>{a.current=null},[]),h.useEffect(()=>{const I=JE(_=>{Rh=_,g.current=_,Hs(c.current,ai(_.fps,0)),Hs(d.current,`${ai(_.frameMs.last)}ms`),Hs(f.current,`${ai(_.frameMs.p95)}ms`),f.current&&(f.current.style.color=nj(_.frameMs.p95)),Hs(u.current,`${_.longTasks.count} / ${ai(_.longTasks.lastMs,0)}ms`),Hs(p.current,_.heapUsedMb==null?"—":`${ai(_.heapUsedMb,0)}MB`),Hs(m.current,rj(_))});return b.current=I,()=>{I.stop(),b.current=null}},[]);const k=h.useCallback(()=>{ir(`${JSON.stringify(g.current,null,2)}
44
- `)},[]),w=h.useCallback(()=>{b.current?.reset()},[]);return l.jsxs("aside",{ref:i,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:[l.jsxs("div",{className:"flex items-center gap-1 px-2 py-1",children:[l.jsxs("div",{className:P("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:S,onPointerMove:v,onPointerUp:C=>x(C,!1),onPointerCancel:C=>x(C,!0),onLostPointerCapture:C=>x(C,!0),children:[l.jsx(F,{name:"draggable",className:"size-3.5 text-muted-foreground"}),l.jsx("p",{className:"min-w-0 flex-1 typography-micro font-medium",children:"Performance"})]}),l.jsx(Me,{variant:"ghost",size:"xs","aria-label":"Copy performance snapshot",onClick:k,children:l.jsx(F,{name:"file-copy",className:"size-3.5"})}),l.jsx(Me,{variant:"ghost",size:"xs","aria-label":"Reset performance counters",onClick:w,children:l.jsx(F,{name:"refresh",className:"size-3.5"})}),l.jsx(Me,{variant:"ghost",size:"xs","aria-label":e?"Expand performance overlay":"Collapse performance overlay","aria-expanded":!e,onClick:()=>t(C=>!C),children:l.jsx(F,{name:e?"arrow-down-s":"arrow-up-s",className:"size-3.5"})}),l.jsx(Me,{variant:"ghost",size:"xs","aria-label":"Turn off performance overlay",onClick:()=>xc(!1),children:l.jsx(F,{name:"close",className:"size-3.5"})})]}),l.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:[l.jsx("span",{children:"FPS"}),l.jsx("span",{ref:c,className:"text-right text-foreground",children:"0"}),l.jsx("span",{children:"Frame"}),l.jsx("span",{ref:d,className:"text-right text-foreground",children:"0.0ms"}),l.jsx("span",{children:"p95"}),l.jsx("span",{ref:f,className:"text-right",children:"0.0ms"}),l.jsx("span",{children:"Long"}),l.jsx("span",{ref:u,className:"text-right text-foreground",children:"0 / 0ms"}),l.jsx("span",{children:"Heap"}),l.jsx("span",{ref:p,className:"text-right text-foreground",children:"—"})]}),e?null:l.jsx("pre",{ref:m,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"})]})},IW=()=>{const e=tj();return h.useLayoutEffect(()=>{L7()},[]),h.useEffect(()=>{if(!(typeof window>"u"))return window.__pichamberPerfHud={setEnabled:xc,isEnabled:Lo,getSnapshot:()=>Rh},()=>{delete window.__pichamberPerfHud}},[]),!e||typeof document>"u"||!document.body?null:na.createPortal(l.jsx(sj,{}),document.body)},um=48,oj=e=>e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,um).replace(/-$/g,""),ij=e=>{const t=e.trim();return t.length===0||t.length>um?null:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)?t:null},V2=e=>{const t=oj(e.trim());return t&&t.split("-").filter(Boolean).slice(0,7).join("-").slice(0,um).replace(/-$/g,"")||null},aj=async(e,t)=>{const n=e.trim();if(!n||!t)return V2(n);try{const r=await Tt("/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=ij(s.text);if(o)return o}}}catch{}return V2(n)},lj=500,sc="Worktree creation superseded.",Ph=e=>{const t=le(e.projectRoot)??e.projectRoot,n=le(e.sourceDirectory)??e.sourceDirectory;return JSON.stringify([e.runtimeKey,t,n,e.startRef])},y3=e=>e?Ph(e):null,cj=e=>new Promise(t=>{setTimeout(t,e)}),dj=(e,t)=>!!(e&&t&&e.runtimeKey===t.runtimeKey&&le(e.projectRoot)===le(t.projectRoot)&&le(e.sourceDirectory)===le(t.sourceDirectory)&&e.startRef===t.startRef),uj=(e,t)=>({...e,path:t.path,branch:t.branch}),fr=new Map,li=new Map,fj=e=>({prompt:e.prompt,confirmedMentions:Array.from(new Set(Array.isArray(e.confirmedMentions)?e.confirmedMentions:[...e.confirmedMentions])),attachments:e.attachments.map(xd)}),ci=(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}})},en=Et()((e,t)=>{const n=(a,c,d)=>{ci(e,a,(f,u)=>f?{...f,state:d,failedSend:null,updatedAt:u}:{key:a,intent:c,state:d,receipt:null,failedSend:null,notificationSent:!1,startedAt:u,updatedAt:u})},r=(a,c,d,f)=>{ci(e,a,(u,p)=>({key:a,intent:c,state:d,receipt:null,failedSend:f,notificationSent:u?.notificationSent??!1,path:u?.path??null,branch:u?.branch??null,startedAt:u?.startedAt??p,updatedAt:p}))},s=(a,c,d,f,u,p)=>{ci(e,a,(m,g)=>({key:a,intent:c,state:null,receipt:d,failedSend:f,notificationSent:m?.notificationSent??!1,path:u??d.path,branch:p??d.branch,startedAt:m?.startedAt??g,updatedAt:g}))},o=(a,c,d)=>{ci(e,a,(f,u)=>f?{...f,path:c,branch:d,updatedAt:u}:null)},i=async a=>{const{intent:c,prompt:d,git:f,refreshProject:u}=a,p=a.failedSend?fj(a.failedSend):null,m=a.pollIntervalMs??lj,g=a.taskId??Ph(c),b=(fr.get(g)??0)+1;fr.set(g,b);const y=()=>fr.get(g)!==b||c.runtimeKey!==J(),S=()=>{!f||c.runtimeKey!==J()||u(c.projectRoot,f,{force:!0}).catch(()=>{})};if(n(g,c,{phase:"naming",label:"Naming worktree..."}),!f?.createGitWorktree||!f.getGitWorktreeBootstrapStatus){const v="Git worktrees are unavailable for this runtime.";throw r(g,c,{phase:"failed",label:"Worktree creation failed",error:v},p),new Error(v)}if(c.runtimeKey!==J()){const v="The runtime changed. Select New worktree again.";throw r(g,c,{phase:"failed",label:"Worktree creation stopped",error:v},p),new Error(v)}try{const v=await aj(d,c.sourceDirectory);if(y())throw new Error(sc);const x={mode:"new",startRef:c.startRef,...v?{worktreeName:v}:{},returnAfterDirectoryCreated:!0};if(f.validateGitWorktree){const I=await f.validateGitWorktree(c.sourceDirectory,x);if(!I.ok)throw new Error(I.errors.map(_=>_.message).filter(Boolean).join(`
45
- `)||"The worktree request is invalid.")}if(y())throw new Error(sc);n(g,c,{phase:"creating",label:"Creating worktree..."});const k=await f.createGitWorktree(c.sourceDirectory,x),w=uj(c,k);if(y())return w;o(g,k.path,k.branch);let C=k.bootstrapStatus;for(;C.status==="pending";){if(y()||(n(g,c,C.phase==="directory-created"?{phase:"checking-out",label:"Checking out files..."}:{phase:"setting-up",label:"Setting up project..."}),await cj(m),y()))return w;C=await f.getGitWorktreeBootstrapStatus(k.path)}if(C.status==="failed"||C.phase!=="setup-ready")throw new Error(C.error||"Worktree setup failed.");try{await u(c.projectRoot,f,{force:!0})}catch{}return y()||s(g,c,w,p,k.path,k.branch),w}catch(v){if(y())throw v;const x=v instanceof Error?v.message:"Failed to create the worktree.";throw x===sc||(S(),r(g,c,{phase:"failed",label:"Worktree creation failed",error:x},p)),v}};return{runtimeKey:J(),entries:new Map,getEntry:a=>{const c=y3(a);return c?t().entries.get(c)??null:null},getEntryByKey:a=>t().entries.get(a)??null,getActiveEntries:()=>{const a=[];for(const c of t().entries.values())c.state&&c.state.phase!=="failed"&&a.push(c);return a},clearEntry:a=>{e(c=>{if(!c.entries.has(a))return c;const d=new Map(c.entries);return d.delete(a),fr.delete(a),{entries:d}})},consumeFailedSend:(a,c)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||u.state?.phase!=="failed"||u.failedSend!==c)return f;const p=new Map(f.entries);return p.delete(a),fr.delete(a),d=!0,{entries:p}}),d},markWorktreePromptSucceeded:(a,c)=>{let d=!1;return e(f=>{const u=f.entries.get(a);if(!u||!u.receipt||u.failedSend!==c)return f;const p=new Map(f.entries);return p.delete(a),fr.delete(a),d=!0,{entries:p}}),d},markWorktreePromptFailed:(a,c,d)=>{let f=!1;return e(u=>{const p=u.entries.get(a);if(!p||!p.receipt||p.failedSend!==c)return u;const m=new Map(u.entries);return m.set(a,{...p,state:{phase:"failed",label:"Prompt failed to send",error:d},updatedAt:Date.now()}),f=!0,{entries:m}}),f},markNotificationSent:a=>{ci(e,a,(c,d)=>!c||c.notificationSent?c??null:{...c,notificationSent:!0,updatedAt:d})},dismissFailed:a=>{e(c=>{if(c.entries.get(a)?.state?.phase!=="failed")return c;const f=new Map(c.entries);return f.delete(a),fr.delete(a),{entries:f}})},resetForRuntimeSwitch:a=>{fr.clear(),li.clear(),e({runtimeKey:a,entries:new Map})},request:a=>{const c=a.taskId??Ph(a.intent),d=li.get(c);if(d)return d;const f=i(a).finally(()=>{li.get(c)===f&&li.delete(c)});return li.set(c,f),f}}}),v3=e=>y3(e),hj=dj,pj=async e=>(await vx([...e])).map(xd),mj=(e,t)=>e??t,x3=(e,t)=>(e??t).map(n=>n.id),Dh=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.`}},gj=(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"?Dh(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."},b3=()=>{try{const e=pe.getState(),t=e.newSessionDraft?.open?e.newSessionDraft.directoryOverride:null,n=e.currentSessionId,r=n?e.getDirectoryForSession(n)??e.currentSessionDirectory:t??tt.getState().currentDirectory,s=No(J(),r,n);return s?Wt(s):null}catch{return null}},_W=e=>{const t=en.getState(),n=t.getEntryByKey(e),r=n?.failedSend;if(!n||!r)return{ok:!1,reason:"missing"};if(n.intent.runtimeKey!==J())return{ok:!1,reason:"runtime-mismatch"};const s=No(J(),n.intent.sourceDirectory,null);if(!s)return{ok:!1,reason:"invalid-target"};const o=Wt(s);try{const d=vd(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=b3();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(xd),expectedFailedSend:r};try{Ke.getState().requestWorktreeRestore(d)}catch{return{ok:!1,reason:"open-failed"}}return{ok:!0,reason:"pending"}}const c=t.getEntryByKey(e);if(!c||c.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{hs(s,r.prompt,r.confirmedMentions)}catch{return{ok:!1,reason:"invalid-target"}}try{Ke.getState().activateAttachmentsDraft(o);const d=Ke.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}},yj=(e,t)=>{const n=en.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!==J())return{ok:!1,reason:"runtime-mismatch"};const o=No(J(),r.intent.sourceDirectory,null);if(!o)return{ok:!1,reason:"invalid-target"};const i=Wt(o);if(i!==e.targetKey)return{ok:!1,reason:"invalid-target"};const a=b3();if(a!==null&&a!==i)return{ok:!1,reason:"navigated-away"};const c=t??"";if(c.trim().length>0&&c!==e.prompt)return{ok:!1,reason:"target-occupied"};try{const u=vd(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=le(r.intent.sourceDirectory),f=le(o.directory);if(!d||d!==f)return{ok:!1,reason:"invalid-target"};try{hs(o,e.prompt,e.confirmedMentions),Ke.getState().activateAttachmentsDraft(i);const u=Ke.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}},EW=e=>!!(e?.receipt&&e?.failedSend&&!e?.state),vj=e=>!!(e?.receipt&&!e?.state&&!e?.failedSend),jW=e=>vj(e),TW=e=>!!(e?.receipt&&!e?.notificationSent&&!e?.state&&!e?.failedSend),xj=(e,t,n)=>{if(!e||!t)return!1;try{return en.getState().markWorktreePromptFailed(e,t,n)}catch{return!1}},bj=(e,t,n,r)=>{if(!e||!t)return!1;let s=!1;try{s=en.getState().markWorktreePromptSucceeded(e,t)}catch{return!1}if(!s)return!1;if(!n||n.length===0)return!0;try{const o=x3(n,r);o.length>0&&Ke.getState().detachAttachedFiles(o)}catch{}return!0},wj=600*1e3,Oh="pending-input:",Sj=e=>!Number.isFinite(e.ageMs)||Math.max(0,e.ageMs)>wj||e.isCurrent&&e.visible&&e.focused?"none":!e.visible||!e.focused||e.mode==="always"&&!e.isCurrent?"toast-and-notify":"toast",Fc=e=>`${Oh}${e}`,Cj=e=>e==="approval"?"Approval needed":"Input needed",B2=e=>{const t=Ge().getState().catalog.byId.get(e);return t?h3(Mr(t),"Untitled session"):"Untitled session"},kj=(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=ne.getState().notificationMode,a=Date.now(),c=wo(t.since,n,a)??t.since;return{isCurrent:r,visible:s,focused:o,mode:i==="always"?"always":"hidden-only",ageMs:a-c}},w3=(e,t)=>{pe.getState().setCurrentSession(e,t)},$2=(e,t,n,r,s)=>{ke.warning(Cj(n.kind),{id:Fc(e),description:r,duration:1/0,onDismiss:s,onAutoClose:s,action:{label:"Open session",onClick:()=>w3(e,t||null)}})},Mj=(e,t)=>{const n=[];for(const[r,s]of e){const o=t(r);o!==s.label&&n.push([r,o])}return n},Ij=(e,t,n,r)=>{e.get(n)?.raise===r&&(e.delete(n),t.delete(Fc(n)))},_j=(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},AW=()=>{const e=pe(d=>d.currentSessionId),t=h.useRef(new Map),n=h.useRef(new Set),r=h.useRef(new Map),s=h.useRef(0),o=h.useCallback((d,f)=>{Ij(r.current,n.current,d,f)},[]),i=h.useCallback(d=>{const f=Fc(d);n.current.delete(f),r.current.delete(d),ke.dismiss(f);const u=t.current.get(d);if(u!==void 0){t.current.delete(d);const p=jr()?.notifications?.close;p&&p(u).catch(()=>{})}},[]),a=h.useCallback(()=>{for(const f of n.current)ke.dismiss(f);n.current.clear(),r.current.clear();const d=jr()?.notifications?.close;if(d)for(const f of t.current.values())d(f).catch(()=>{});t.current.clear()},[]);h.useEffect(()=>Vk(d=>{if(d.type==="cleared"||!d.pending){i(d.sessionId);return}const f=d.pending,u=Sj(kj(d.sessionId,f,d.serverNow));if(u==="none")return;const p=B2(d.sessionId),m=++s.current,g=d.sessionId;if(n.current.add(Fc(g)),r.current.set(g,{directory:d.directory,pending:f,label:p,raise:m}),$2(g,d.directory,f,p,()=>o(g,m)),u==="toast-and-notify"){const b=Hp(d.sessionId,f.since);t.current.set(d.sessionId,b),ux({sessionId:d.sessionId,directory:d.directory,since:f.since,kind:f.kind,title:p})}}),[i,o]),h.useEffect(()=>Ge().subscribe(()=>{if(r.current.size!==0)for(const[d,f]of Mj(r.current,B2)){const u=r.current.get(d);u&&(r.current.set(d,{...u,label:f}),$2(d,u.directory,u.pending,f,()=>o(d,u.raise)))}},xt),[o]),h.useEffect(()=>{e&&i(e)},[e,i]);const c=Vx();return h.useEffect(()=>{const d=new Set(c.map(m=>m.sessionId)),f=new Set(t.current.keys());for(const m of n.current)m.startsWith(Oh)&&f.add(m.slice(Oh.length));if(f.size===0)return;const u=Ge().getState().catalog,p=_j([...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 p)i(m)},[c,i]),h.useEffect(()=>sn(()=>{a()}),[a]),h.useEffect(()=>()=>{a()},[a]),null},LW=()=>{const t=Vx().length,n=ne(r=>r.dockBadgeEnabled);return h.useEffect(()=>{const r=bt()&&!n?0:t;try{jr()?.notifications?.setAttentionCount?.(r)}catch{}},[t,n]),h.useEffect(()=>()=>{try{jr()?.notifications?.setAttentionCount?.(0)}catch{}},[]),null},Ej=()=>{const e=qe(t=>Gp(t.catalog).length,Object.is,"catalog");return e<=0||bt()||Jn()?"":`(${e}) `},NW=()=>(h.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;w3(r,s)};return window.addEventListener("pichamber:open-session",e),()=>window.removeEventListener("pichamber:open-session",e)},[]),null),jj="PiChamber",z2=e=>e.replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase()),Tj=e=>{const n=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??""},Aj=(e,t)=>[e,t,jj].filter(r=>typeof r=="string"&&r.trim().length>0).join(" | "),Lj=()=>{const e=pe(c=>c.currentSessionId),t=qe(c=>e?c.reducer.bySession.get(e)?.extensionTitle??null:null,Object.is,e?`session:${e}`:"chrome"),n=it(c=>c.activeProjectId?c.projects.find(d=>d.id===c.activeProjectId)??null:null),r=h.useMemo(()=>{if(!n)return null;const c=n.label?.trim();if(c)return z2(c);const d=Tj(n.path);return d?z2(d):null},[n]),[s,o]=h.useState(null),i=Ej();h.useEffect(()=>{if(typeof window>"u"||!bt()){o(null);return}let c=!1;const d=async()=>{try{if(ld()){c||o(null);return}const u=window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,p=od();if(p&&V1(p,u)){c||o(null);return}const g=(await wp()).hosts.find(y=>p?V1(p,Vl(y)):!1),b=g?.label?.trim()?Rn(g.label.trim()):"Instance";c||o(b)}catch{c||o("Instance")}};d();const f=()=>{d()};return window.addEventListener("focus",f),()=>{c=!0,window.removeEventListener("focus",f)}},[]);const a=h.useMemo(()=>`${i}${Aj(t?.trim()||r,s)}`,[t,s,r,i]);h.useEffect(()=>{if(typeof document<"u"&&(document.title=a),!bt())return;(async()=>{try{if(typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await aI(a)}catch{return}})()},[a])},RW=()=>(Lj(),null),U2=(e,t)=>{const n=le(t??null);if(!n)return;const r=n.toLowerCase();e.has(r)||e.set(r,n)},S3=(e,t,n)=>{const r=new Map;for(const s of e)U2(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)U2(r,o?.path);return new Set(r.values())},wl=new Map,Nj=e=>{const t=new Set;for(const n of e){const r=le(n);r&&t.add(r)}return t},Rj=()=>{const e=new Set,t=it.getState().projects,n=S3(t,Hn(t,rn.getState()),{includeWorktrees:!0});for(const o of n){const i=le(o);i&&i!=="~"&&e.add(i)}const r=le(Ge().getState().directory);r&&e.add(r);const s=tt.getState().homeDirectory??null;for(const o of Wp(s)){const i=le(o);i&&i!=="~"&&e.add(i)}return e},Pj=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=Ge(),c=a!==e||J()!==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 p=!c&&u.size===0&&f.size===r.length&&(s||r.length>0);return{runtimeKey:t,catalog:d,readyDirectories:f,failedDirectories:u,complete:p,stale:c}},Dj=e=>{const t=Ge(),n=J(),r=t.getRuntimeGeneration(),s=e!==void 0,i=[...e===void 0?Rj():Nj(e)].sort(),a=`${n}::${i.join("|")}`,c=wl.get(a);if(c&&c.store===t&&c.runtimeKey===n&&c.generation===r)return c.promise;const d=Pj(t,n,r,i,s);wl.set(a,{store:t,runtimeKey:n,generation:r,promise:d});const f=()=>{wl.get(a)?.promise===d&&wl.delete(a)};return d.then(f,f),d},Oj=e=>{if(typeof Element>"u"||!(e instanceof Element))return null;const t=e.closest("[data-terminal-owner]");return t?.isConnected&&t.dataset.terminalOwner||null},df=e=>Oj(e)!==null,Hj=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},Fj=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(!Hj(n[r]))return n[r].info.id;return null},Vj=e=>e.connection==="ready"&&(e.authoritativeWorking||e.hasPendingAssistant),Bj=e=>{const t=e.connection==="ready"&&!e.transportUncertain,n=e.authoritativeWorking||e.hasPendingAssistant;return{isWorking:t&&n,isAwaitingRecovery:!t&&(n||e.hasRetainedStream)}},$j=e=>e.turnIsInActiveStream||e.isLastTurn&&e.sessionIsWorking&&e.awaitingPromptEcho!==!0&&(e.isSteering===!0||!e.activeStreamingMessageId),zj=e=>e.isRetrying===!0||e.isAwaitingRecovery===!0||!!e.activeStreamingMessageId&&e.messageId===e.activeStreamingMessageId,uf={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Uj(e,t){const n=Bx(),r=Md(e??""),s=tm(e??"");return h.useMemo(()=>{if(!e)return uf;const o=r?.type??"idle",i=s[s.length-1],a=!!(i&&i.role==="assistant"&&typeof i.time?.completed!="number"),c=r!==void 0,d=c&&o!=="idle",f=Vj({connection:n,authoritativeWorking:d,hasPendingAssistant:a});return c&&!d||!f?uf:{phase:d?o:"busy",isWorking:!0,isBusy:o==="busy"||!d&&a,isCooldown:!1}},[n,e,r,s])}function fm(){const e=pe(t=>t.currentSessionId);return pe(t=>t.currentSessionDirectory),Uj(e)}const PW=.45,hm=[{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"}],C3=new Map(hm.map(e=>[e.id,e])),ff=hm.find(e=>e.id==="git"),DW=e=>e===!1?{icon:"arrow-left-right",label:"Changes",description:"Review working and last-turn changes"}:{icon:ff?.icon??"git-branch",label:ff?.label??"Git",description:ff?.description??"Review diffs, commit, and push"},qj=e=>typeof e=="string"&&C3.has(e),Zj=e=>{const t=[],n=new Set;for(const r of e){if(!qj(r)||n.has(r))continue;const s=C3.get(r);s&&(n.add(r),t.push(s))}for(const r of hm)n.has(r.id)||t.push(r);return t},OW=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)}},Wj=e=>!e||e.isLoading&&!e.hasResult?!1:e.hasError?!0:e.hasGitHubRepo,Gj=e=>Zj(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:Wj(e.githubScope):t.availability==="extensions"?e.tabs.some(n=>n.mode===t.mode)?!0:!!e.hasExtensionContent:!0),k3=3e4,Kr=()=>({scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),di=new Map,Kj=(e,t)=>`${e}
46
- ${t}`,Yj=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub scope check failed"}},oc=e=>!e.host||!e.owner||!e.repo?null:J5(`${e.host}/${e.owner}/${e.repo}`),ic=e=>!!(e.host&&e.owner&&e.repo&&!e.disabledReason),pm=(e,t)=>{if(!e)return t;const n=new Set(e.repositories.filter(ic).map(i=>oc(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"&&ic(i)),s=r?oc(r):null;if(s&&n.has(s))return s;const o=e.repositories.find(ic);return o?oc(o):null},Sa=Et()(or((e,t)=>({runtimeKey:J(),entriesByDirectory:{},resetForRuntimeSwitch:n=>{const r=n??J();di.clear(),e({runtimeKey:r,entriesByDirectory:{}})},ensureScope:async(n,r)=>{const s=Qr(n.trim());if(!s)return Kr();const o=J();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t().entriesByDirectory[s],a=Date.now();return i?.scope&&i.fetchedAt&&a-i.fetchedAt<k3&&!i.isLoading?i:t().refreshScope(s,r)},refreshScope:async(n,r,s)=>{const o=Qr(n.trim());if(!o)return Kr();const i=J();t().runtimeKey!==i&&t().resetForRuntimeSwitch(i);const a=Kj(i,o),c=di.get(a);if(c&&!s?.force)return c;const d=r??null;if(!d)return t().entriesByDirectory[o]??Kr();const f=t().entriesByDirectory[o]??Kr();f.isLoading||e(p=>({entriesByDirectory:{...p.entriesByDirectory,[o]:{...f,isLoading:!0}}}));const u=(async()=>{try{const p=await d.scope(o);if(J()!==i)return t().entriesByDirectory[o]??Kr();const m={scope:p,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null};e(y=>({entriesByDirectory:{...y.entriesByDirectory,[o]:m}}));const g=ne.getState().githubSelectedRepoByDirectory[o]??null,b=pm(p,g);return b!==g&&ne.getState().setGitHubSelectedRepo(o,b),m}catch(p){if(J()!==i)return t().entriesByDirectory[o]??Kr();const m=Yj(p),g=f.scope?{...f,isLoading:!1,stale:!0,error:m}:{scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:m};return e(b=>({entriesByDirectory:{...b.entriesByDirectory,[o]:g}})),g}})();di.set(a,u);try{return await u}finally{di.get(a)===u&&di.delete(a)}},setSelectedRepo:(n,r)=>{const s=Qr(n.trim());if(!s)return;const o=t().entriesByDirectory[s]?.scope??null;if(r!=null){const i=J5(r);if(!i||o&&!new Set(o.repositories.filter(ic).map(c=>oc(c)).filter(c=>!!c)).has(i))return;ne.getState().setGitHubSelectedRepo(s,i);return}ne.getState().setGitHubSelectedRepo(s,null)},invalidate:async(n,r)=>{const s=Qr(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"&&sn(e=>{Sa.getState().resetForRuntimeSwitch(e.runtimeKey)});const q2=Object.freeze(Kr()),Xj=e=>Sa(t=>e?t.entriesByDirectory[Qr(e)]??q2:q2),Jj=e=>{const t=Sa(r=>e?r.entriesByDirectory[Qr(e)]?.scope??null:null),n=ne(r=>e?r.githubSelectedRepoByDirectory[Qr(e)]??null:null);return h.useMemo(()=>e?pm(t,n):null,[e,t,n])},HW=Object.freeze(Object.defineProperty({__proto__:null,GITHUB_SCOPE_STALE_MS:k3,resolveGitHubSelectedRepo:pm,useGitHubScope:Xj,useGitHubScopeStore:Sa,useGitHubSelectedRepo:Jj},Symbol.toStringTag,{value:"Module"})),Bn=()=>{const e=pe(s=>s.currentSessionId),t=pe(s=>s.newSessionDraft),n=MM(e),r=tt(s=>s.currentDirectory);return e&&n?n:t?.open&&t.directoryOverride?t.directoryOverride:r??void 0},Qj=()=>({setCurrentVariant:e=>Ze.getState().setCurrentVariant(e)}),Ci=(e,t=Qj())=>(t.setCurrentVariant(e),"applied"),eT=async(e=1)=>{const t=Ze.getState(),n=Lp(t.getCurrentModelVariants(),t.currentVariant,e);return Ci(n),n},tT='[data-chat-input="true"] .cm-content';function fo(){document.querySelector(tT)?.focus()}const nT=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"]),mm=e=>e.replace(/\r\n?/g,`
47
- `),pn=e=>mm(e).trim(),rT=e=>e.replace(/\s+/g," ").trim(),M3=e=>(e.match(/language-([\w+#.-]+)/)?.[1]||"").trim(),sT=e=>e.closest("pre")?.getAttribute("data-md-lang")||M3(e.className),I3=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=>I3(n)).filter(n=>n!==null)}},gm=e=>e.filter(t=>t.type==="text"||!t.isCodeLineNumber).map(t=>t.type==="text"?t:{...t,children:gm(t.children)}),oT=e=>Array.from(e.childNodes).map(t=>I3(t)).filter(t=>t!==null),Wi=e=>e.type==="text"?e.value:e.children.map(t=>Wi(t)).join(""),Hh=(e,t)=>{if(e.type==="text")return null;if(t(e))return e;for(const n of e.children){const r=Hh(n,t);if(r)return r}return null},ym=(e,t="")=>{const n=mm(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}`},ho=e=>{if(e.type==="text")return rT(e.value);const t=e.children.map(n=>ho(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},Z2=(e,t)=>e.children.filter(n=>n.type==="element"&&n.tag==="li").map((n,r)=>{const s=n.children.map(o=>ho(o)).join("").replace(/\s+/g," ").trim();return s?`${t?`${r+1}.`:"-"} ${s}`:""}).filter(Boolean).join(`
51
- `),ki=e=>{if(e.type==="text")return pn(e.value);if(e.isMarkdownBlock)return e.children.map(n=>ki(n)).filter(n=>n.length>0).join(`
52
-
53
- `);if(e.component==="markdown-code"){const n=Hh(e,r=>r.tag==="pre");return n?ki(n):""}if(e.tag==="pre"||e.tag==="code"&&e.isCodeLines){const n=e.tag==="code"?e:Hh(e,r=>r.tag==="code");return ym(Wi(n||e),e.markdownLanguage||M3(n?.className||""))}if(e.tag==="code"){const n=mm(Wi(e)).trim();return n?`\`${n.replace(/`/g,"\\`")}\``:""}if(e.tag==="ul")return Z2(e,!1);if(e.tag==="ol")return Z2(e,!0);if(e.tag==="blockquote")return pn(e.children.map(r=>ki(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=pn(e.children.map(s=>ho(s)).join(""));return r?`${"#".repeat(n)} ${r}`:""}if(e.tag==="p"||e.tag==="div"||e.tag==="li")return pn(e.children.map(n=>ho(n)).join(""));const t=e.children.map(n=>ki(n)).filter(n=>n.length>0);return t.length>0?t.join(`
57
-
58
- `):pn(e.children.map(n=>ho(n)).join(""))},iT=e=>e.type==="text"?!0:!e.isMarkdownBlock&&!e.isCodeLines&&e.component!=="markdown-code"&&!nT.has(e.tag),aT=(e,t)=>{const n=gm(e);if(n.every(s=>iT(s))){const s=pn(n.map(o=>ho(o)).join(""));if(s)return s}return n.map(s=>ki(s)).filter(s=>s.length>0).join(`
59
-
60
- `).trim()||pn(t)},W2=e=>(e.nodeType===1?e:e.parentElement)?.closest("pre code")??null,_3=(e,t)=>{const n=W2(e.startContainer),r=W2(e.endContainer),s=gm(oT(e.cloneContents()));return n&&n===r?ym(s.map(o=>Wi(o)).join(""),sT(n)):aT(s,t)},vm=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}`},lT='[data-chat-input="true"]',xm=e=>{if(!e)return!1;const t=e;return!!(typeof t.closest=="function"?t:e.parentElement)?.closest(lT)},cT=e=>{if(xm(e))return null;const t=e.tagName?.toLowerCase();if(t==="textarea"){const n=e,r=n.selectionStart??0,s=n.selectionEnd??0,o=pn(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=pn(n.value.slice(s,o));return i?(n.selectionStart=o,n.selectionEnd=o,i):null}return null},dT=()=>{if(typeof document>"u")return null;const e=document.activeElement;if(!e||typeof e.tagName!="string")return null;const t=cT(e);return t?vm(t):null},uT=()=>{if(typeof document>"u")return null;const e=document.querySelector(".cm-editor.cm-focused");if(!e||xm(e))return null;const t=hn.findFromDOM(e);if(!t)return null;const{from:n,to:r}=t.state.selection.main;if(n===r)return null;const s=pn(t.state.sliceDoc(n,r));return s?(t.dispatch({selection:{anchor:r}}),ym(s)):null},fT=()=>{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(xm(t.commonAncestorContainer))return null;const n=pn(e.toString());if(!n)return null;const r=_3(t,n);return e.removeAllRanges(),vm(r)},hT=()=>uT()??dT()??fT(),E3=()=>{const e=hT();return ne.getState().setActiveMainTab("chat"),ne.getState().setSessionSwitcherOpen(!1),e&&Ke.getState().setPendingInputText(e,"append"),queueMicrotask(()=>{fo()}),e!==null},j3="file://";function pT(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 mT(e){const t=e.replace(/\\/g,"/").trim();return t.toLowerCase().startsWith(j3)?t:`file://${pT(t)}`}function gT(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function G2(e){const t=e.trim().replace(/^['"]+|['"]+$/g,"");return!t||/[\r\n]/.test(t)?null:t.toLowerCase().startsWith(j3)||gT(t)?t:null}function Fh(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)Fh(r,t,n+1);return}if(typeof e=="object")for(const r of Object.values(e))Fh(r,t,n+1)}}function yT(e){const t=new Set,n=r=>{const s=G2(r);if(s){t.add(s);return}for(const o of r.split(/\r?\n/)){const i=G2(o);i&&t.add(i)}};n(e);try{const r=JSON.parse(e),s=new Set;Fh(r,s);for(const o of s)n(o)}catch{}return Array.from(t)}function qt(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 vT(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 xT=["CodeFiles","codefiles","application/vnd.code.tree","application/vnd.code.tree.explorer","text/uri-list","text/plain"],tr="__home__",bT="Don't work in a folder",wT=()=>"~",ST=e=>e.enabled&&e.isDraftOpen&&!!e.activeProjectId&&e.selectedProjectId!==tr&&e.selectedProjectId!==e.activeProjectId,CT=e=>{if(e.selectedProjectId===tr)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()||Q5(n.path):null};function T3(e,t){const n=e.flatMap(o=>{const i={...o,id:o.id,ownerProjectId:o.id,kind:"project"},a=t.get(qt(o.path)??o.path)??[];return[i,...a.map(c=>({id:`worktree:${o.id}:${c.path}`,ownerProjectId:o.id,kind:"worktree",path:c.path,branch:c.branch,label:c.branch||(c.detached?"Detached HEAD":c.name)}))]}),r=wT();return[{id:tr,ownerProjectId:tr,kind:"project",path:r,label:bT},...n]}const A3=Et()(or(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 L3(e,t){if(e.length<=1)return null;const n=t?e.indexOf(t):-1;return e[(n+1)%e.length]??null}function Vh(e=1){const t=it.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=le(tt.getState().currentDirectory??null);s=er(n,Hn(n,rn.getState()),f)?.id??null}const o=e===1?L3(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=le(i?.path??null);if(!i||!a)return!1;t.setActiveProjectIdOnly(o),A3.getState().selectSpace(o),ne.getState().closeMainSurfaces();const c=Hn(n,rn.getState()),d=Ax().find(f=>{const u=le(f.directory??null);return u?er(n,c,u)?.id===o:!1});if(d){const f=le(d.directory??null);return pe.getState().setCurrentSession(d.id,f),!0}return pe.getState().openNewSessionDraft({selectedProjectId:o,directoryOverride:a}),!0}function kT(){const e=pe.getState(),t=e.newSessionDraft;if(!t?.open)return!1;const n=it.getState(),r=n.projects,s=T3(r,Hn(r,rn.getState()));if(s.length<=1)return!1;const o=le(t.directoryOverride??null),i=t.selectedProjectId?s.find(f=>f.ownerProjectId===t.selectedProjectId&&(!o||le(f.path)===o))??s.find(f=>f.id===t.selectedProjectId)??(o?s.find(f=>le(f.path)===o)??null:null):o?s.find(f=>le(f.path)===o)??null:null,a=L3(s.map(f=>f.id),i?.id??null),c=s.find(f=>f.id===a),d=le(c?.path??null);return!c||!d?!1:c.ownerProjectId===tr?(e.setNewSessionDraftTarget({projectId:tr,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0):(n.activeProjectId!==c.ownerProjectId&&(n.setActiveProjectIdOnly(c.ownerProjectId),A3.getState().selectSpace(c.ownerProjectId)),e.setNewSessionDraftTarget({projectId:c.ownerProjectId,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0)}const MT=['[data-slot="dropdown-menu-content"][data-open]','[data-slot="select-content"][data-open]'].join(",");function IT(e=document){return!!e.querySelector(MT)}const _T=(e,t)=>!e.repeat&&kt(e,t),ET=e=>{const t=pe.getState().currentSessionId;t&&Ge().prompt(t,H7(e),"prompt").catch(()=>{})},jT=()=>{const e=pe(j=>j.openNewSessionDraft),t=pe(j=>j.armAbortPrompt),n=pe(j=>j.clearAbortPrompt),r=pe(j=>j.currentSessionId),s=Ux,o=ne(j=>j.toggleCommandPalette),i=ne(j=>j.toggleHelpDialog),a=ne(j=>j.toggleSidebar),c=tt(j=>j.currentDirectory),d=Bn(),f=h.useCallback(()=>{c&&ne.getState().openContextSurface(Ri(c),"terminal")},[c]),u=ne(j=>j.isMobile),p=ne(j=>j.setSessionSwitcherOpen),m=ne(j=>j.setActiveMainTab),g=ne(j=>j.setSettingsDialogOpen),b=ne(j=>j.setModelSelectorOpen),y=ne(j=>j.setTimelineDialogOpen),S=ne(j=>j.setPromptNavigatorPanelOpen),v=ne(j=>j.shortcutOverrides),x=tt(j=>j.currentDirectory),k=it(j=>j.getActiveProject()),{themeMode:w,setThemeMode:C}=Vn(),{phase:I}=fm(),_=h.useRef(null),E=h.useRef(null),M=h.useRef(w),T=h.useRef(new Set);h.useEffect(()=>{M.current=w},[w]);const A=h.useCallback(()=>{E.current&&(clearTimeout(E.current),E.current=null),_.current=null,n()},[n]);h.useEffect(()=>{const j=L=>O7(L,v),R=R7("switch_context_surface",v),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(","),N=L=>L instanceof Element&&!!L.closest(O),D=L=>{if(df(L.target)&&kt(L,j("toggle_terminal"))){const{isMobile:$}=ne.getState();if($)return;L.preventDefault(),L.stopPropagation(),f();return}},K=L=>{if(L.key!=="Escape")return;const $=L.target,G=!!$?.closest('[role="dialog"]'),Q=!!document.querySelector('[data-settings-view="true"]'),z=df($),X=N($)||IT(),{isSettingsDialogOpen:Y,isCommandPaletteOpen:ce,isHelpDialogOpen:se,isSessionSwitcherOpen:ue,isImagePreviewOpen:Ie,activeMainTab:de,isPromptNavigatorPanelOpen:Fe}=ne.getState();if(G||z||X){A();return}if(Fe){L.preventDefault(),S(!1),A();return}if(Y){L.preventDefault(),g(!1),A();return}if(Q){A();return}if(ce||se||ue||Ie||!(de==="chat")){A();return}const We=r;if(I==="idle"||!We){A();return}const Ae=Date.now(),be=_.current;if(be&&Ae<be){L.preventDefault(),A(),s(We);return}L.preventDefault();const te=t(3e3)??Ae+3e3;_.current=te,E.current&&clearTimeout(E.current);const ve=Math.max(te-Ae,0);E.current=setTimeout(()=>{_.current&&Date.now()>=_.current&&A()},ve||0)},V=L=>{if(L.key==="Escape"||df(L.target))return;if(kt(L,j("open_command_palette"))){L.preventDefault(),o();return}if(kt(L,j("open_timeline_dialog"))){L.preventDefault(),y(!0);return}if(kt(L,j("open_help"))){L.preventDefault(),i();return}if(P7()&&kt(L,j("new_mini_chat"))){L.preventDefault(),Qn("desktop_open_draft_mini_chat_window",{directory:x||k?.path||"",projectId:k?.id??null}).catch(z=>{console.warn("[keyboard-shortcuts] failed to open draft mini chat window",z)});return}if(kt(L,j("new_chat"))){L.preventDefault(),m("chat"),p(!1),e();return}if(kt(L,j("cycle_theme"))){L.preventDefault();const z=["light","dark","system"],X=document.activeElement,ce=(z.indexOf(M.current)+1)%z.length;C(z[ce]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),X&&document.contains(X)&&X.focus({preventScroll:!0}))});return}if(kt(L,j("open_settings"))){L.preventDefault();const{isSettingsDialogOpen:z}=ne.getState();g(!z);return}if(kt(L,j("add_selection_to_chat"))){L.preventDefault(),E3();return}if(kt(L,j("toggle_sidebar"))){L.preventDefault();const{isMobile:z,isSessionSwitcherOpen:X}=ne.getState();z?p(!X):a();return}if(kt(L,j("focus_input"))){L.preventDefault(),fo();return}if(kt(L,j("cycle_session_folder"))){if(!Vh())return;L.preventDefault();return}if(kt(L,j("cycle_draft_folder"))){if(!kT())return;L.preventDefault();return}if(kt(L,j("open_right_sidebar"))){const z=ne.getState();if(z.isMobile||!x)return;L.preventDefault();const X=Ri(x),Y=z.contextPanelByDirectory[X];if(Y?.isOpen)return;Y?.activeTabId?z.setActiveContextPanelTab(X,Y.activeTabId):z.openContextSurface(X,"git");return}if(kt(L,j("toggle_terminal"))){const{isMobile:z}=ne.getState();if(z)return;L.preventDefault(),f();return}const G=L.key.length===1&&L.key>="0"&&L.key<="9"?L.key==="0"?10:Number(L.key):null;if(G!==null&&!L.repeat&&D7(L,R,T.current)){const z=ne.getState();if(z.isMobile||!d)return;const X=Ri(d),Y=z.contextPanelByDirectory[X];let ce;const se=Sa.getState().entriesByDirectory[X]??null;if(se){const de=se.scope?.repositories??[];ce={isLoading:se.isLoading,hasResult:!!(se.scope||se.error),hasGitHubRepo:de.some(Fe=>!!(Fe.host&&Fe.owner&&Fe.repo&&!Fe.disabledReason)),hasError:!!(se.error&&!se.scope)}}const Ie=Gj({railOrder:z.contextRailOrder,tabs:Y?.tabs??[],githubScope:ce})[G-1];if(!Ie)return;L.preventDefault(),z.openContextSurface(X,Ie.mode);return}if(_T(L,j("open_model_selector"))){const{isSettingsDialogOpen:z,isCommandPaletteOpen:X,isHelpDialogOpen:Y,isSessionSwitcherOpen:ce,activeMainTab:se,isModelSelectorOpen:ue}=ne.getState();if(z||X||Y||ce||!(se==="chat"))return;L.preventDefault(),b(!ue);return}if(kt(L,j("cycle_thinking_variant"))){const{isSettingsDialogOpen:z,isCommandPaletteOpen:X,isHelpDialogOpen:Y,isSessionSwitcherOpen:ce,activeMainTab:se}=ne.getState();if(z||X||Y||ce||!(se==="chat")||Ze.getState().getCurrentModelVariants().length===0)return;L.preventDefault(),eT(1).catch(()=>{ke.error("Couldn't update thinking")});return}if(kt(L,j("cycle_favorite_model_forward"))||kt(L,j("cycle_favorite_model_backward"))){const{isSettingsDialogOpen:z,isCommandPaletteOpen:X,isHelpDialogOpen:Y,isSessionSwitcherOpen:ce,activeMainTab:se,favoriteModels:ue,addRecentModel:Ie}=ne.getState();if(z||X||Y||ce||!(se==="chat")||ue.length===0)return;L.preventDefault();const{currentProviderId:$e,currentModelId:Xe,setProvider:We,setModel:Ae}=Ze.getState(),be=ue.length,te=ue.findIndex(je=>je.providerID===$e&&je.modelID===Xe),ve=kt(L,j("cycle_favorite_model_forward"))?1:-1,we=ue[(te+ve+be)%be];We(we.providerID),Ae(we.modelID),Ie(we.providerID,we.modelID);return}const Q=ne.getState().commandTriggers;if(Q.length>0&&!N(L.target)){for(const z of Q)if(!(!z.combo||!kt(L,z.combo))){L.preventDefault(),L.stopPropagation(),ET(z);return}}},W=L=>{T.current.add(L.key.toLowerCase())},B=L=>{T.current.delete(L.key.toLowerCase())},Z=()=>{T.current.clear()};return window.addEventListener("keydown",W,!0),window.addEventListener("keyup",B,!0),window.addEventListener("blur",Z),window.addEventListener("keydown",D,!0),window.addEventListener("keydown",K,!0),window.addEventListener("keydown",V),()=>{window.removeEventListener("keydown",W,!0),window.removeEventListener("keyup",B,!0),window.removeEventListener("blur",Z),window.removeEventListener("keydown",D,!0),window.removeEventListener("keydown",K,!0),window.removeEventListener("keydown",V)}},[e,s,o,i,a,f,u,p,m,g,b,y,S,C,I,t,A,r,x,d,k?.id,k?.path,v]),h.useEffect(()=>()=>{A()},[A])},TT=3,AT=(e,t)=>{if(typeof e!="string")return t;const n=e.trim().replace(/\s+/g," ");return n?n.slice(0,48):t},LT=(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:AT(o.title,`Session ${r.length+1}`)}),r.length>=TT))break}return r},NT=()=>{const e=$x(),t=pe(o=>o.currentSessionId),n=h.useMemo(()=>LT(e,t),[t,e]),r=h.useMemo(()=>JSON.stringify(n),[n]),s=n.length>0;h.useEffect(()=>{if(typeof window>"u"||!Sp())return;try{s?localStorage.setItem(B1,r):localStorage.removeItem(B1)}catch{return}window.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[s,r])},RT=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")},PT=async(e,t)=>{try{const n=V7(e.runtimeKey);if(!t.streamEpoch||t.streamEpoch!==n)return"unknown";const r=await Ne.getSendReceipt({sessionId:e.sessionId,kind:t.kind,operationId:t.operationId,streamEpoch:t.streamEpoch},{directory:e.directory,runtimeKey:e.runtimeKey});return RT(r)}catch{return"unknown"}},N3=e=>e instanceof F7,DT=2e3,hr="hydrate-demand",R3=2e3,OT=6e4,HT=e=>Math.min(R3*2**Math.max(e-1,0),OT),K2=(e,t,n)=>e!==void 0&&e.messageId===t&&n<e.nextAttemptAt,FT=(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}}},VT=e=>{const t=pe.getState().sessionAbortFlags.get(e);if(!t)return null;const n=t.timestamp+DT;return Date.now()<n?n:null},BT=e=>{const t=e[0];return t?{queuedMessageId:t.id,primaryText:t.content,primaryAttachments:t.attachments??[],agentMentionName:void 0,sendConfig:t.sendConfig}:null},$T=(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}:{}}),zT=e=>{const t=Ze.getState(),n=_t.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,c=r&&i&&a?n.getAgentModelVariantForSession(e,r,i,a):void 0;return{providerID:i,modelID:a,agent:r,variant:c}},UT=(e,t)=>{if(e.connection!=="ready")return"unknown";const n=e.catalog.byId.get(t.sessionId);return!n||le(n.directory)!==le(t.directory)||n.archived?"unknown":n.lifecycle==="busy"||n.lifecycle==="retry"?"busy":n.hydrated?"ready":"unknown"};function qT(e){const t=typeof e=="boolean"?e:e?.enabled??!0,n=ct(p=>p.queuedMessages),r=tt(p=>p.currentDirectory),s=ba(),o=qe(p=>p.catalog,void 0,xt),i=qe(p=>p.connection,void 0,jt),a=h.useRef(new Set),c=h.useRef(new Map),[d,f]=h.useState(0),u=h.useMemo(()=>FT(()=>f(p=>p+1)),[]);h.useEffect(()=>()=>u.dispose(),[u]),h.useEffect(()=>{if(!t)return;const p=ct.getState().queuedMessages;for(const[S,v]of c.current)v.messageId===hr&&!(S in p)&&c.current.delete(S);const m=S=>{c.current.get(S)?.messageId===hr&&c.current.delete(S)},g=async(S,v,x)=>{const k=s.getState();if(k.connection!=="ready")return;const w=k.catalog.byId.get(v);if(!w||w.archived||le(w.directory)!==le(S.directory))return;const C=c.current.get(x);if(C?.messageId===hr&&K2(C,hr,Date.now())){u.schedule(C.nextAttemptAt);return}if(a.current.has(x))return;a.current.add(x);try{await s.ensureHydrated(v)}finally{a.current.delete(x),f(A=>A+1)}const I=s.getState();if(s.isDeleted(v)||!I.catalog.byId.has(v)){m(x);return}if(I.catalog.byId.get(v)?.hydrated){m(x);return}const M=(C?.messageId===hr?C.failures:0)+1,T=Date.now()+HT(M);c.current.set(x,{messageId:hr,failures:M,nextAttemptAt:T}),u.schedule(T)},b=async(S,v)=>{const{sessionId:x}=S,k=ev(S);if(v.length===0||S.runtimeKey!==J()||a.current.has(k))return;const w=VT(x);if(w!==null){u.schedule(w);return}const C=s.getState(),I=UT(C,S);if(I==="busy")return;if(I==="unknown"){await g(S,x,k);return}const _=ct.getState().getAutoSendCandidate(S);if(!_)return;const E=c.current.get(k);if(E&&E.messageId!==_.id&&E.messageId!==hr)c.current.delete(k);else if(E&&E.messageId!==hr&&K2(E,_.id,Date.now())){Number.isFinite(E.nextAttemptAt)&&u.schedule(E.nextAttemptAt);return}const M=ct.getState().claimQueuedMessage(S,_.id);if(!M)return;const T=BT([M]);if(!T){ct.getState().clearSending(S,M.id);return}const A=T.sendConfig,j=A?.providerID&&A?.modelID?A:zT(x);if(!j.providerID||!j.modelID){ct.getState().clearSending(S,M.id),u.schedule(Date.now()+R3);return}a.current.add(k);const R=ct.getState().markDeliveryAttempt(S,M.id,"followUp");if(!R?.streamEpoch){a.current.delete(k),ct.getState().clearSending(S,M.id);return}try{await $T(S,T,{providerID:j.providerID,modelID:j.modelID,agent:j.agent,variant:j.variant},R.streamEpoch),ct.getState().completeQueuedSend(S,T.queuedMessageId),c.current.delete(k)}catch(O){console.warn("[follow-up] auto-send failed:",O);const N=E?.messageId===T.queuedMessageId?E.failures:0;c.current.set(k,{messageId:T.queuedMessageId,failures:N+1,nextAttemptAt:Number.POSITIVE_INFINITY}),N3(O)?(ct.getState().markSendUnconfirmed(S,T.queuedMessageId,"followUp"),ke.error("Follow-up status uncertain. Check status before retrying.",{id:`follow-up-unconfirmed:${k}:${T.queuedMessageId}`})):(ct.getState().markSendFailed(S,T.queuedMessageId),ke.error("Follow-up message failed to send. Use Send now to retry.",{id:`follow-up-failed:${k}:${T.queuedMessageId}`}))}finally{a.current.delete(k),ct.getState().clearSending(S,T.queuedMessageId)}};Object.entries(n).forEach(([S,v])=>{const x=B7(S);!x||x.runtimeKey!==J()||x.directory!==r||v.length!==0&&b(x,v)})},[t,n,r,o,i,d,u,s])}const ZT=1440*60*1e3,P3=5,D3=1440*60*1e3,WT=[],hf=e=>e.time?.updated??e.time?.created??0,Bh=({sessions:e,currentSessionId:t,cutoffDays:n,keepRecent:r=P3,now:s=Date.now()})=>{if(!Array.isArray(e)||n<=0)return[];const o=s-n*ZT,i=[...e].sort((c,d)=>hf(d)-hf(c)),a=new Set(i.slice(0,r).map(c=>c.id));return i.filter(c=>{if(!c?.id||a.has(c.id)||c.id===t||c.share)return!1;const d=hf(c);return d?d<o:!1}).map(c=>c.id)},GT=(e,t,n)=>{const r=[],s=[];for(const o of e){const i=t.get(o),a=i?sm(i):null;a&&n.has(a)?r.push(o):s.push(o)}return{actionable:r,unready:s}},KT=()=>{try{const e=Ge();return{store:e,runtimeKey:J(),generation:e.getRuntimeGeneration()}}catch{return null}},pf=e=>{try{const t=Ge();return t!==e.store||J()!==e.runtimeKey?!1:t.getRuntimeGeneration()===e.generation}catch{return!1}};let ac=!1;const YT=()=>ac,XT=async({force:e=!1,now:t}={})=>{const n=()=>{try{return ne.getState().sessionRetentionAction??"archive"}catch{return"archive"}};if(ac)return{completedIds:[],failedIds:[],action:n(),skippedReason:"running"};let r;try{const i=ne.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<D3)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"cooldown"};const o=KT();if(!o)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"stale"};ac=!0;try{try{let i;try{i=await Dj()}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}if(i.stale||!pf(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(Mr(w));if(a.length===0){if(i.failedDirectories.size>0)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"};try{ne.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:[],failedIds:[],action:r.action,skippedReason:"no-candidates"}}let c,d,f;try{c=pe.getState().currentSessionId??null;const w=ne.getState();d=w.sessionRetentionAction??r.action,f=w.autoDeleteAfterDays??r.days}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}const u=Bh({sessions:a,currentSessionId:c,cutoffDays:f,now:s});if(u.length===0){if(i.failedDirectories.size>0)return{completedIds:[],failedIds:[],action:d,skippedReason:"partial"};try{ne.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:[],failedIds:[],action:d,skippedReason:"no-candidates"}}const p=new Map(a.map(w=>[w.id,w])),{actionable:m,unready:g}=GT(u,p,i.readyDirectories);if(m.length===0)return{completedIds:[],failedIds:[...g],action:d,skippedReason:"partial"};const b=[],y=new Set(g),S=[...g],v=w=>{y.has(w)||(y.add(w),S.push(w))};let x=!1,k=d;for(let w=0;w<m.length;w+=1){const C=m[w];if(!pf(o)){for(let R=w;R<m.length;R+=1)v(m[R]);x=!0;break}let I,_,E,M;try{I=pe.getState().currentSessionId??null;const R=ne.getState();_=R.sessionRetentionAction??d,E=R.autoDeleteAfterDays??f,M=Ge().getState().catalog}catch{v(C);continue}k=_;let T=!1,A=null;try{const R=[];for(const N of M.byId.values())N.archived||R.push(Mr(N));if(T=new Set(Bh({sessions:R,currentSessionId:I,cutoffDays:E,now:s})).has(C),T){const N=M.byId.get(C);A=N?sm(Mr(N)):null}}catch{v(C);continue}if(!T||!A){v(C);continue}let j;try{j=M.listStatusByDirectory.get(A)}catch{v(C);continue}if(j!=="ready"){v(C);continue}try{const R=Ge();_==="archive"?await R.archive(C,!0,A):await R.remove(C,A)}catch{v(C);continue}if(!pf(o)){v(C);for(let R=w+1;R<m.length;R+=1)v(m[R]);x=!0;break}b.push(C)}if(x)return{completedIds:b,failedIds:S,action:k,skippedReason:"stale"};if(i.failedDirectories.size>0||S.length>0)return{completedIds:b,failedIds:S,action:k,skippedReason:"partial"};try{ne.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:b,failedIds:S,action:k}}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}}finally{ac=!1}},JT=e=>{const t=typeof e=="object"?e:void 0,n=t?.autoRun!==!1,r=typeof e=="boolean"?e:t?.enabled??!0,s=pe(y=>y.currentSessionId),o=ne(y=>y.autoDeleteEnabled),i=ne(y=>y.autoDeleteAfterDays),a=ne(y=>y.sessionRetentionAction),c=ne(y=>y.autoDeleteLastRunAt),d=r&&(!n||o),f=qe(y=>da(y.catalog,{archived:!1}),jx,"catalog"),u=d?f:WT,[p,m]=h.useState(!1),g=h.useMemo(()=>i<=0?[]:Bh({sessions:u,currentSessionId:s,cutoffDays:i}),[i,s,u]),b=h.useCallback(async({force:y=!1}={})=>{m(!0);try{return await XT({force:y})}finally{m(!1)}},[]);return h.useEffect(()=>{if(!r||!n||!o||i<=0||g.length===0)return;const y=Date.now();c&&y-c<D3||YT()||b()},[i,o,c,n,g.length,r,b]),{candidates:g,isRunning:p,runCleanup:b,keepRecentCount:P3,action:a}},mf=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:"0px",gf=(e,t,n)=>{const r=e.style.getPropertyValue(t);r===n||!r&&n==="0px"||e.style.setProperty(t,n)},yf=(e,t,n,r)=>{gf(e,"--oc-wco-left-inset",mf(t)),gf(e,"--oc-wco-right-inset",mf(n)),gf(e,"--oc-wco-titlebar-height",mf(r))},QT=()=>{h.useEffect(()=>{if(typeof window>"u"||!Sp())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){yf(e,0,0,0);return}const i=r.getTitlebarAreaRect(),a=Math.max(0,Number(i.x)||0),c=Math.max(0,Number(i.width)||0),d=Math.max(0,Number(i.height)||0),f=Math.max(0,window.innerWidth-(a+c));yf(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),yf(e,0,0,0)}},[])},eA=()=>{};async function tA(e,t){if(!e?.listen)return eA;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 Sl=e=>{const t=ne.getState();e&&t.setSettingsPage(e),t.setSettingsDialogOpen(!0)},Y2=e=>{const t=Ax();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,sm(o))};function nA(){const{setThemeMode:e}=Vn(),t=h.useCallback(s=>{const o=ne.getState();switch(s){case"about":Sl("about");return;case"settings":Sl();return;case"command-palette":o.setCommandPaletteOpen(!0);return;case"new-session":o.setActiveMainTab("chat"),o.setSessionSwitcherOpen(!1),pe.getState().openNewSessionDraft();return;case"change-workspace":Vd.requestDirectoryDialog();return;case"add-selection-to-chat":E3();return;case"open-right-sidebar":{const i=tt.getState().currentDirectory;if(!i)return;const a=Ri(i),c=o.contextPanelByDirectory[a];if(c?.isOpen)return;c?.activeTabId?o.setActiveContextPanelTab(a,c.activeTabId):o.openContextSurface(a,"git");return}case"toggle-terminal":{const i=tt.getState().currentDirectory;i&&o.openContextSurface(Ri(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":xc(!Lo());return;case"go-back":window.history.back();return;case"go-forward":window.history.forward();return;case"previous-session":Y2(-1);return;case"next-session":Y2(1);return;case"previous-project":Vh(-1);return;case"next-project":Vh(1);return;case"help-dialog":o.setHelpDialogOpen(!0);return;case"download-logs":Sl("general"),xc(!0);return;case"copy":return;default:return}},[e]),n=h.useCallback(()=>{Sl("about"),fE.getState().checkForUpdates()},[]),r=h.useCallback(()=>{const s=it.getState().getActiveProject();Qn("desktop_open_draft_mini_chat_window",{directory:tt.getState().currentDirectory||s?.path||"",projectId:s?.id??null}).catch(o=>{console.warn("[desktop-menu] failed to open draft mini chat window",o)})},[]);h.useEffect(()=>{if(!bo())return;let s=!1,o=()=>{};return tA($7(),{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 rA=()=>{const e=it.getState().projects,t=Hn(e,rn.getState()),n=[...S3(e,t,{includeWorktrees:!0})];try{const r=[tt.getState().homeDirectory,$t().getItem("homeDirectory"),typeof window<"u"?window.__PICHAMBER_HOME__:null],s=new Set(n.map(o=>le(o)?.toLowerCase()??o));for(const o of r){if(!o)continue;const i=le(o);if(!i)continue;const a=i.toLowerCase();s.has(a)||(s.add(a),n.push(i))}}catch{}return n},sA=e=>e.length===0?"":[...e].sort().join("|"),oA=()=>(U.useEffect(()=>{let e=!1,t="";const n=Ge(),r=()=>{if(e)return;const a=rA();if(a.length===0)return;const c=sA(a);if(c===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 p=n.getState().catalog.listStatusByDirectory.get(u);return p!=="ready"&&p!=="loading"});if(f.length===0){t=c;return}t=c,n.refreshAllDirectoryCatalogs(f)};r();const s=it.subscribe(r),o=rn.subscribe(r),i=n.subscribe(r,"chrome");return()=>{e=!0,s(),o(),i()}},[]),null),Ca=()=>{const e=h.useContext(wa);if(!e)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return e},iA=6e4,aA=2,lA=()=>{const e=it(c=>c.projects),t=rn(c=>c.refreshProject),{git:n}=Ca(),r=h.useMemo(()=>e.map(c=>c.path).filter(c=>!!c),[e]),s=h.useMemo(()=>[...r].sort().join("\0"),[r]),o=J(),i=h.useCallback(async()=>{if(!n||r.length===0)return;let c=0;const d=async()=>{for(;c<r.length;){const f=r[c];c+=1,await t(f,n)}};await Promise.all(Array.from({length:Math.min(aA,r.length)},()=>d()))},[n,r,t]),a=h.useRef(null);return h.useEffect(()=>{const c=`${o}\0${s}`;a.current!==c&&(a.current=c,i())},[o,s,i]),h.useEffect(()=>{const c=()=>{i()},d=()=>{document.visibilityState==="visible"&&i()};window.addEventListener("focus",c),document.addEventListener("visibilitychange",d);const f=window.setInterval(()=>{document.visibilityState==="visible"&&i()},iA);return()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",d),window.clearInterval(f)}},[i]),null},X2=2e3,cA=3e4,dA=2;class uA{constructor(t){this.options=t}timer=null;currentDelayMs=X2;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=X2}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,br("config-reconcile",{code:"attempt"});try{await this.options.initializeApp()}catch{}finally{this.inFlight=!1}if(this.disposed)return;if(!this.isMismatched()){br("config-reconcile",{code:"success"}),this.resetDelay();return}if(br("config-reconcile",{code:"failure"}),this.isHidden())return;const t=this.currentDelayMs;this.currentDelayMs=Math.min(t*dA,cA),this.timer=setTimeout(()=>{this.timer=null,this.executeAttempt()},t)}}function fA({connection:e,isInitialized:t,isConnected:n,initializeApp:r}){const s=h.useRef({connection:e,isInitialized:t,isConnected:n,initializeApp:r});s.current={connection:e,isInitialized:t,isConnected:n,initializeApp:r};const o=h.useRef(null);h.useEffect(()=>{o.current?.reconcile()},[e,t,n]),h.useEffect(()=>{const i=new uA({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()},c=()=>{i.wake()};typeof document<"u"&&document.addEventListener("visibilitychange",a),typeof window<"u"&&window.addEventListener("online",c);const d=sn(()=>{i.resetForRuntimeSwitch(),i.reconcile()});return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",a),typeof window<"u"&&window.removeEventListener("online",c),d(),i.dispose(),o.current===i&&(o.current=null)}},[])}const hA="pichamber:mini-chat-presence",pA=()=>(h.useEffect(()=>{if(typeof BroadcastChannel>"u")return;const e=new BroadcastChannel(hA);return e.onmessage=t=>{const n=t.data;if(n?.type!=="mini-chat-session-presence"||!n.sessionId||!n.directory)return;n.viewed!==!1&&yd(n.sessionId)},()=>e.close()},[]),null);function mA({embeddedBackgroundWorkEnabled:e}){return JT(e),qT(e),l.jsx(oA,{})}const gA=()=>{const e=h.useMemo(()=>Ge(),[]),t=h.useMemo(()=>a=>e.subscribe(a,"chrome"),[e]),n=h.useSyncExternalStore(t,e.getState,e.getState),{selectedSessionId:r,directory:s,connection:o,focusPending:i}=n;return h.useEffect(()=>{if(!s)return;const a=tt.getState().currentDirectory;le(a)!==le(s)&&tt.getState().setDirectory(s,{showOverlay:!1}),Ze.getState().activateDirectory(s)},[s]),h.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&&!Qp(a.newSessionDraft,a.currentSessionId)&&(a.currentSessionId!==r||a.currentSessionDirectory!==s)){const c=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,...c}),yd(r)}},[r,s,o,i]),null},yA=()=>{const e=h.useMemo(()=>Ge(),[]),t=h.useMemo(()=>c=>e.subscribe(c,"chrome"),[e]),n=h.useSyncExternalStore(t,e.getState,e.getState),r=Ze(c=>c.initializeApp),s=Ze(c=>c.isInitialized),o=Ze(c=>c.isConnected),i=Ze(c=>c.loadProviders),a=Ze(c=>c.providers.length);return fA({connection:n.connection,isInitialized:s,isConnected:o,initializeApp:r}),h.useEffect(()=>{!n.directory||n.connection!=="ready"||!o||a===0&&i({source:"webApp:recovery"})},[o,i,n.connection,n.directory,a]),null};function FW({embeddedBackgroundWorkEnabled:e}){return NT(),QT(),jT(),nA(),l.jsxs(l.Fragment,{children:[l.jsx(yA,{}),l.jsx(mA,{embeddedBackgroundWorkEnabled:e}),l.jsx(gA,{}),l.jsx(pA,{}),l.jsx(lA,{})]})}const O3=({text:e})=>l.jsx("span",{"aria-hidden":"true",className:"oc-shimmer-clip",children:l.jsx("span",{className:"oc-shimmer-band","data-shimmer-text":e})}),vA=Array.from({length:9},(e,t)=>{const n=Math.floor(t/3);return(t%3+Math.abs(n-1))*90}),xA=650;function vf({compact:e=!1}){return l.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:vA.map((t,n)=>l.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 ${xA}ms ease-in-out ${t}ms infinite`}},n))})}function bA(e,t){const[n,r]=h.useState(0),[s]=h.useState(()=>Date.now());if(h.useEffect(()=>{if(!e||t===null)return;const a=setInterval(()=>r(c=>c+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 J2=({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!=="",c=bA(a&&s,i),d=a?l.jsxs("span",{className:P("pixel-loader-label min-w-0 truncate whitespace-nowrap typography-markdown font-medium",o&&"agent-thinking-label-enter"),children:[e,l.jsx(O3,{text:e})]},o?e:void 0):null,f=a&&s&&c!==null?l.jsx("span",{className:"shrink-0 whitespace-nowrap font-mono typography-code text-muted-foreground tabular-nums",children:c}):null;return n==="badge"?l.jsxs("span",{className:P("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:[l.jsx(vf,{compact:!a}),d,f]}):n==="full"?l.jsxs("div",{className:P("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:[l.jsx(vf,{compact:!a}),d,f]}):l.jsxs("span",{className:P("inline-flex min-w-0 items-center gap-2.5",t),role:"status","aria-live":"polite",children:[l.jsx(vf,{compact:!a}),d,f]})},Q2="pichamber:chunk-import-reload",wA=250,SA=3e4,CA=[/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 H3(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 e0(e){const t=H3(e);return CA.some(n=>n.test(t))}function kA(e){return`1.0.5:${H3(e).slice(0,500)}`}function MA(e){if(typeof window>"u")return;const t=Date.now(),n=kA(e);let r=null;try{const o=window.sessionStorage.getItem(Q2);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<SA)){try{window.sessionStorage.setItem(Q2,JSON.stringify({signature:n,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function IA(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,!e0(o)||s>=n)break;await new Promise(i=>setTimeout(i,wA*(s+1)))}throw e0(r)&&MA(r),r}const xs=e=>U.lazy(()=>IA(e)),_A=xs(()=>om().then(e=>({default:e.MarkdownRenderer}))),EA=xs(()=>om().then(e=>({default:e.SimpleMarkdownRenderer}))),jA=l.jsx("div",{className:"break-words w-full min-w-0"}),TA=e=>e==="tool"?"markdown-content markdown-tool":e==="reasoning"?"markdown-content markdown-reasoning":"markdown-content leading-relaxed",F3=e=>!nn()||typeof e.content!="string"||e.content.length===0?jA:l.jsx("div",{className:P("break-words w-full min-w-0 whitespace-pre-wrap",TA(e.variant),typeof e.className=="string"?e.className:void 0),children:e.content}),_o=e=>l.jsx(h.Suspense,{fallback:l.jsx(F3,{...e}),children:l.jsx(_A,{...e})}),ka=e=>l.jsx(h.Suspense,{fallback:l.jsx(F3,{...e}),children:l.jsx(EA,{...e})}),AA=rv(["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"}}),bm=U.createContext(null),LA=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function t0({onValueChange:e,modal:t=!1,...n}){const[r,s]=U.useState(null),o=U.useMemo(()=>({portalContainer:r,setPortalContainer:s}),[r]),i=U.useCallback((a,c)=>{typeof a=="string"&&e?.(a,c)},[e]);return l.jsx(bm.Provider,{value:o,children:l.jsx(V9,{...n,modal:t,onValueChange:i})})}function NA({...e}){return l.jsx(Y9,{"data-slot":"select-group",...e})}function n0({placeholder:e,children:t,...n}){return l.jsx(z9,{"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 r0({className:e,size:t="default",children:n,asChild:r,onPointerDownCapture:s,onFocusCapture:o,...i}){const a=U.useContext(bm),c=U.useCallback(f=>{if(!a)return;const u=f instanceof HTMLElement?f:null;a.setPortalContainer(LA(u))},[a]),d=r&&U.isValidElement(n)?{render:n}:null;return l.jsx(B9,{"data-slot":"select-trigger","data-size":t,className:P(AA({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=>{c(f.currentTarget),s?.(f)},onFocusCapture:f=>{c(f.currentTarget),o?.(f)},...i,...d??{},children:d?void 0:l.jsxs(l.Fragment,{children:[n,l.jsx($9,{children:l.jsx(F,{name:"arrow-down-s",className:"size-4 opacity-50"})})]})})}function s0({className:e,children:t,position:n="popper",fitContent:r=!1,portalToBody:s=!1,sideOffset:o,side:i,align:a,...c}){const d=U.useContext(bm),f=n==="item-aligned",u=d?.portalContainer??null;return l.jsx(U9,{container:s?void 0:u||void 0,children:l.jsx(q9,{alignItemWithTrigger:f,sideOffset:o,side:i,align:a,className:"absolute z-[120] pointer-events-auto",children:l.jsx(Z9,{"data-slot":"select-content",style:{color:"var(--surface-elevated-foreground)"},className:P("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),...c,children:l.jsx(Fn,{outerClassName:P("max-h-[var(--oc-select-max-height,var(--available-height))]",r?"w-max":"w-full"),className:P("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 RA({className:e,...t}){return l.jsx(X9,{"data-slot":"select-label",className:P("text-muted-foreground px-2 py-1.5 typography-meta",e),...t})}function o0({className:e,children:t,...n}){return l.jsxs(W9,{"data-slot":"select-item",className:P("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:[l.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:l.jsx(G9,{children:l.jsx(F,{name:"check",className:"size-4"})})}),l.jsx(K9,{children:t})]})}const i0=e=>e.some(t=>t.source==="local"&&(t.uploadState?.status==="preparing"||t.uploadState?.status==="uploading")),PA=e=>e.some(t=>t.source==="local"&&t.uploadState?.status==="failed"),xf=(e,t=Date.now())=>e.every(n=>n.source==="server"||n.uploadState?.status==="ready"&&n.uploadState.expiresAt>t),lc=200,a0={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:600*1e3},V3=()=>lc,DA=()=>Math.round(V3()*.6),OA={MAX_SESSIONS:a0.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(lc*.6),HISTORICAL_MESSAGES:lc,FETCH_BUFFER:20,HISTORY_CHUNK:lc,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:a0.ZOMBIE_TIMEOUT},l0=()=>{const e=V3(),t=DA();return{...OA,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},HA=5e3,bn=new Map,yr=new Map,Xn=new Map,Gi=new Map,qs=(e,t)=>`${e}
65
- ${t?.trim()??""}`,po=e=>{Gi.set(e,(Gi.get(e)??0)+1),yr.delete(e)},FA=e=>{const t=J();if(typeof e=="string"&&e.trim().length>0){const r=qs(t,e);bn.delete(r),po(r);return}const n=new Set([...bn.keys(),...yr.keys(),...Xn.keys()]);for(const r of n)r.startsWith(`${t}
66
- `)&&(bn.delete(r),po(r))},bf=e=>{const t=new Set([...bn.keys(),...yr.keys(),...Xn.keys()]);for(const n of t)n.startsWith(`${e}
67
- `)&&(bn.delete(n),po(n))},Cl=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}:{}})),Cr=Et()(or((e,t)=>({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null,setSelectedSnippet:n=>e({selectedSnippetId:n}),setSnippetDraft:n=>e({snippetDraft:n}),resetForRuntimeSwitch:()=>{bn.clear(),yr.clear(),Xn.clear(),Gi.clear(),e({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null})},loadSnippets:async n=>{const r=J(),s=qs(r,n),o=Date.now(),i=Xn.get(s);e({activeCacheKey:s,snippets:i??[],isLoading:!0});const a=bn.get(s)??0;if(a>0&&o-a<HA)return e({isLoading:!1}),!0;const c=yr.get(s);if(c)return c;const d=Gi.get(s)??0,f=(async()=>{try{const u=await Ne.listSnippets(n,{runtimeKey:r});if(J()!==r)return!1;if((Gi.get(s)??0)!==d)return e(m=>m.activeCacheKey===s?{isLoading:!1}:m),!0;const p=Cl(u);return Xn.set(s,p),bn.set(s,Date.now()),e(m=>m.activeCacheKey===s?{snippets:p,isLoading:!1,...m.selectedSnippetId&&!p.some(g=>g.id===m.selectedSnippetId)?{selectedSnippetId:null}:{}}:m),!0}catch{return e(u=>u.activeCacheKey===s?{isLoading:!1}:u),!1}})();yr.set(s,f);try{return await f}finally{yr.get(s)===f&&yr.delete(s)}},createSnippet:async(n,r,s={})=>{const o=J(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ne.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(J()!==o)return!1;const c=qs(o,i),d=Cl(a);po(c),Xn.set(c,d),bf(o),bn.set(c,Date.now());const f=d.find(u=>u.name===n&&u.source===(s.scope??"global"));return e(u=>u.activeCacheKey===c?{snippets:d,snippetDraft:null,selectedSnippetId:f?.id??null,isLoading:!1}:u),!0}catch{return!1}},updateSnippet:async(n,r,s)=>{const o=J(),i=t().snippets.find(c=>c.id===n);if(!i)return!1;const a=s?.trim()?s.trim():i.source==="project"&&i.directory?i.directory:void 0;try{const c=await Ne.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(J()!==o)return!1;const d=qs(o,a),f=Cl(c);return po(d),Xn.set(d,f),bf(o),bn.set(d,Date.now()),e(u=>u.activeCacheKey===d?{snippets:f,isLoading:!1}:u),!0}catch{return!1}},deleteSnippet:async(n,r)=>{const s=J(),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 Ne.deleteSnippet(o.id,i,{runtimeKey:s});if(J()!==s)return!1;const c=qs(s,i),d=Cl(a);return po(c),Xn.set(c,d),bf(s),bn.set(c,Date.now()),e(f=>f.activeCacheKey===c?{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=qs(J(),r),o=Xn.get(s)??(t().activeCacheKey===s?t().snippets:[]),i=new Map,a=[...o].sort((c,d)=>+(d.source==="project")-+(c.source==="project"));for(const c of a){const d=c.name.toLowerCase();i.has(d)||i.set(d,c.content);for(const f of c.aliases??[]){const u=f.toLowerCase();i.has(u)||i.set(u,c.content)}}return i.size===0?n:n.replace(/(^|\s)#([A-Za-z0-9][A-Za-z0-9_-]*)/g,(c,d,f)=>{const u=i.get(f.toLowerCase());return u!==void 0?`${d}${u}`:c})},getSnippetByName:n=>t().snippets.find(r=>r.name===n)}),{name:"snippets-store"})),VW=Object.freeze(Object.defineProperty({__proto__:null,invalidateSnippetsLoadCache:FA,useSnippetsStore:Cr},Symbol.toStringTag,{value:"Module"}));function B3(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 VA=["drawio","dio"];function $3(e){const t=e.split(".").pop()?.toLowerCase();return VA.includes(t||"")}const z3=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function BW(e){const t=e.split(".").pop()?.toLowerCase();return z3.includes(t||"")}function $W(e){return e.split(".").pop()?.toLowerCase()==="pdf"}function BA(e){return e.toLowerCase().endsWith(".svg")}const $A=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",...z3.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 zA(e){const t=e.split(/[/\\]/).pop()??e,n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n+1).toLowerCase()}function zW(e){if(BA(e))return!1;const t=zA(e);return $A.has(t)}function UW(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 qW(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 UA={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 qA(e){return e.trim().replace(/[_-]+/g," ").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function Ma(e){return UA[e]||{displayName:qA(e),category:"system",outputLanguage:"text",inputFields:[]}}function ZA(e,t,n){const r=Ma(e);if(r.outputLanguage==="auto"){if(n?.filePath||n?.file_path||n?.sourcePath){const s=n.filePath||n.file_path||n.sourcePath,o=B3(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 WA(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"),c=o&&i?` (Line: ${o}; Character: ${i})`:"";if(r==="workspaceSymbol")return a?`Operation: ${r} (Query: "${a}")`:`Operation: ${r}`;const d=`Operation: ${r}${c}`;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(/^./,c=>c.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 U3="p-1.5 max-w-[260px] overflow-hidden rounded-xl bg-popover/95 border border-border shadow-lg";function q3({imageUrl:e,filename:t,metaLine:n}){return e?l.jsxs("div",{children:[l.jsx("img",{src:e,alt:t,loading:"lazy",decoding:"async",className:"max-h-48 w-auto rounded-lg object-contain mx-auto"}),l.jsxs("div",{className:"mt-1 px-1 py-0.5",children:[l.jsx("p",{className:"truncate text-xs font-medium text-foreground",children:t}),n?l.jsx("p",{className:"text-[11px] text-muted-foreground",children:n}):null]})]}):l.jsxs("p",{children:[t,n?` (${n})`:""]})}const wm=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"]),$h="oc-file-type-icon-sprite-root",c0="http://www.w3.org/2000/svg";let Sm=null,ui=null,Ki=null;const Vc=new Set,Yi=new Set;let Z3=0;const zh=new Set,d0=()=>Z3,GA=e=>(zh.add(e),()=>{zh.delete(e)}),KA=()=>{Z3+=1;for(const e of Array.from(zh))e()},YA=()=>ft(()=>import("./sprite-HGQGInUp.js"),[]);let XA=YA;const JA=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},W3=()=>{if(typeof document>"u"||!document.body)return null;const e=document.getElementById($h),t=e?.querySelector("defs");if(t)return t;e?.remove(),Vc.clear();const n=document.createElement("div");n.id=$h,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(c0,"svg");r.setAttribute("width","0"),r.setAttribute("height","0");const s=document.createElementNS(c0,"defs");return r.appendChild(s),n.appendChild(r),document.body.appendChild(n),s},QA=()=>typeof document>"u"||!document.body?!1:!!document.getElementById($h)?.querySelector("defs"),Cm=e=>{const t=W3();if(!t||Vc.has(e)||!Ki)return;const n=Ki.get(e);if(n){Vc.add(e),t.insertAdjacentHTML("beforeend",n);for(const r of n.matchAll(/href="#([^"]+)"/g))Ki.has(r[1])&&Cm(r[1])}},eL=e=>{if(!(Vc.has(e)&&QA())){if(Sm===null||Ki===null){Yi.add(e),G3().catch(()=>{});return}Yi.delete(e),Cm(e)}},tL=e=>{if(Sm=e,Ki=JA(e),Yi.size>0&&W3()!==null){const t=Array.from(Yi);Yi.clear();for(const n of t)Cm(n)}KA()},G3=()=>Sm!==null?Promise.resolve():(ui||(ui=XA().then(e=>{ui=null,tL(typeof e=="string"?e:e.default)},()=>{throw ui=null,new Error("file-type sprite failed to load")})),ui),nL=()=>{if(typeof window>"u"||typeof document>"u")return;const e=()=>{G3().catch(()=>{})};if(typeof window.requestIdleCallback=="function"){window.requestIdleCallback(()=>e());return}window.setTimeout(e,0)};nL();const u0={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"},f0={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"},h0={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"},Bc="document",rL=(e,t)=>{if(!e)return t==="light"?`${Bc}_light`:Bc;if(t==="light"){const n=e.endsWith("_light")?e:`${e}_light`;return wm.has(n)?n:e}return e},sL=e=>typeof e=="string"&&e.trim().length>0,oL=(e,t)=>{const r=e.replace(/\\/g,"/").split("/").pop()?.toLowerCase()||"";if(u0[r])return u0[r];if(r.startsWith(".env"))return"settings";const s=B3(e);if(s&&f0[s])return f0[s];const o=sL(t)?t.toLowerCase():r.includes(".")&&r.split(".").pop()?.toLowerCase()||"";return o&&h0[o]?h0[o]:o&&wm.has(o)?o:Bc},iL=(e,t)=>{const n=oL(e,t?.extension),r=wm.has(n)?n:Bc,s=rL(r,t?.themeVariant);return eL(s),`#${s}`},rr=({filePath:e,extension:t,className:n})=>{const r=Yx(),s=U.useSyncExternalStore(GA,d0,d0),o=r?.currentTheme.metadata.variant==="light"?"light":"dark",i=iL(e,{extension:t,themeVariant:o});return l.jsx("svg",{className:P("block h-4 w-4 flex-shrink-0",n),"aria-hidden":"true",focusable:"false",children:l.jsx("use",{href:i,xlinkHref:i},s)})},aL=e=>e===null?null:Math.min(100,Math.max(0,e));function lL({filename:e,progress:t}){const n=aL(t);return l.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:l.jsx("span",{className:"block size-6",style:n===null?void 0:{opacity:.35+.65*n/100,filter:`saturate(${n/100})`},children:l.jsx(rr,{filePath:e,className:"size-6 shrink-0"})})})}const cL=U.memo(()=>{const e=U.useRef(null),t=Ke(a=>a.addAttachedFile),n=ne(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 c=>{try{await t(c)}catch(d){console.error("File attach failed",d),ke.error(d instanceof Error?d.message:"Failed to attach file")}}))},i=async a=>{const c=a.target.files;c&&(await o(c),e.current&&(e.current.value=""))};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:e,type:"file",multiple:!0,className:"hidden",onChange:i}),l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx("button",{type:"button",onClick:()=>e.current?.click(),className:P("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:l.jsx(F,{name:"attachment-2",className:s})})}),l.jsx(gt,{side:"top",children:l.jsx("p",{children:"Attach files"})})]})]})});cL.displayName="FileAttachmentButton";const dL=e=>!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,uL=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},K3=U.memo(({file:e,onRemove:t,onRetry:n,onShowPopup:r,gallery:s,galleryIndex:o})=>{const{isMobile:i,isTablet:a}=Pr(),c=i||a,d=e.uploadState,f=d?.status==="ready"&&d.expiresAt<=Date.now(),u=e.mimeType.startsWith("image/"),p=u&&e.previewUrl?e.previewUrl:u&&e.dataUrl.startsWith("data:image/")?e.dataUrl:u&&e.serverPath||"",m=uL(e.filename),g=dL(e.size),b=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",y=d?.status==="uploading"?d.progress:null,S=d?.status==="uploading"||d?.status==="preparing",v=d?.status==="failed"?d.error:f?"Upload expired.":null,x=()=>{!r||!p||r({open:!0,title:e.filename||"Image",content:"",metadata:{tool:"image-preview",filename:e.filename,mime:e.mimeType,size:e.size},image:{url:p,mimeType:e.mimeType,filename:e.filename,size:e.size,gallery:s,index:o}})};return l.jsxs("article",{className:P("group relative min-w-0 overflow-hidden rounded-xl border w-full",v?"border-[var(--status-error)]/50 bg-[var(--status-error-background)]/40":"border-border/60 bg-[var(--surface-elevated)]"),children:[l.jsx("span",{className:"sr-only","aria-live":"polite",children:b}),l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("div",{role:p&&r?"button":void 0,tabIndex:p&&r?0:void 0,onClick:x,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),x())},className:P("flex min-h-14 items-center gap-2.5 px-3 py-2",v?"pr-14":"pr-8",p&&r&&"cursor-pointer select-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"),"aria-label":p?`Preview ${e.filename}`:void 0,children:[S?l.jsx(lL,{filename:e.filename,progress:y}):l.jsx(rr,{filePath:e.filename,extension:m,className:"size-6 shrink-0"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"truncate typography-ui-label text-foreground",title:e.filename,children:e.filename}),l.jsx("p",{className:"typography-meta text-muted-foreground",children:[m.toUpperCase(),g].filter(Boolean).join(" · ")})]})]})}),l.jsx(gt,{side:"top",className:P(p&&!v?U3:void 0),children:v?l.jsx("p",{children:v}):l.jsx(q3,{imageUrl:p||void 0,filename:e.filename,metaLine:p?[m.toUpperCase(),g].filter(Boolean).join(" · "):g})})]}),S?l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 overflow-hidden rounded-xl",children:l.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,l.jsx(Me,{variant:"ghost",size:"xs",onClick:k=>{k.stopPropagation(),t()},className:P("absolute right-1 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",c?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Remove ${e.filename}`,title:`Remove ${e.filename}`,children:l.jsx(F,{name:"close",className:"size-3.5"})}),v?l.jsx(Me,{variant:"ghost",size:"xs",onClick:k=>{k.stopPropagation(),n()},className:P("absolute right-8 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",c?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100"),"aria-label":`Retry upload of ${e.filename}`,title:"Retry upload",children:l.jsx(F,{name:"refresh",className:"size-3.5"})}):null]})});K3.displayName="DraftAttachmentCard";const Y3=U.memo(({onShowPopup:e,className:t,isInline:n=!1,isMobile:r=!1})=>{const s=Ke(p=>p.attachedFiles),o=Ke(p=>p.removeAttachedFile),i=Ke(p=>p.retryAttachmentUpload),[,a]=h.useState(0);if(h.useEffect(()=>{const p=s.reduce((g,b)=>b.uploadState?.status!=="ready"||b.uploadState.expiresAt<=Date.now()?g:g===null?b.uploadState.expiresAt:Math.min(g,b.uploadState.expiresAt),null);if(p===null)return;const m=setTimeout(()=>a(g=>g+1),Math.max(0,p-Date.now()+1));return()=>clearTimeout(m)},[s]),s.length===0)return null;const d=s.filter(p=>p.mimeType.startsWith("image/")).flatMap(p=>{const m=p.previewUrl||p.dataUrl||p.serverPath||"";return m?[{file:p,image:{url:m,mimeType:p.mimeType,filename:p.filename,size:p.size}}]:[]}),f=d.map(p=>p.image),u=new Map(d.map((p,m)=>[p.file.id,m]));return l.jsx("div",{className:P("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(p=>l.jsx(K3,{file:p,onRemove:()=>o(p.id),onRetry:()=>i(p.id),onShowPopup:e,gallery:f,galleryIndex:u.get(p.id)??0},p.id))})});Y3.displayName="AttachedFilesList";const fL="application/vnd.github.issue-link",hL="application/vnd.github.pull-request-link",wf=e=>e.mime===fL?"issue":e.mime===hL?"pr":null,km=U.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=h.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),c=r.filter(u=>!u.mime?.startsWith("image/")),d=h.useMemo(()=>a.flatMap(u=>{if(!u.url)return[];const p=o(u)||"Image";return[{url:u.url,mimeType:u.mime,filename:p,size:u.size}]}),[a,o]),f=h.useCallback(u=>{if(!t)return;const p=d[u];if(!p?.url)return;const m=p.filename||"Image";t({open:!0,title:m,content:"",metadata:{tool:"image-preview",filename:m,mime:p.mimeType,size:p.size},image:{url:p.url,mimeType:p.mimeType,filename:m,size:p.size,gallery:d,index:u}})},[d,t]);return r.length===0?null:n?l.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[c.length>0&&l.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map((u,p)=>{const m=o(u),g=m.split(".").pop()||"",b=i(u.size),y=wf(u);return l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:y&&u.url?l.jsxs("button",{type:"button",onClick:()=>{Lh(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:[y==="pr"?l.jsx(F,{name:"git-pull-request",className:"text-muted-foreground h-3.5 w-3.5"}):l.jsx(F,{name:"github",className:"text-muted-foreground h-3.5 w-3.5"}),l.jsx("div",{className:"overflow-hidden max-w-[220px]",children:l.jsx("span",{className:"truncate block",title:m,children:m})})]}):l.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")?l.jsx(F,{name:"file-pdf",className:"text-muted-foreground h-3.5 w-3.5"}):l.jsx(rr,{filePath:m,extension:g,className:"text-muted-foreground h-3.5 w-3.5"}),l.jsx("div",{className:"overflow-hidden max-w-[140px]",children:l.jsx("span",{className:"truncate block",title:m,children:m})})]})}),l.jsx(gt,{children:l.jsxs("p",{children:[m,b?` (${b})`:""]})})]},`file-${u.url||u.filename||p}`)})}),a.length>0&&l.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-0.5 scrollbar-thin","data-no-drawer-swipe":"true",children:l.jsx("div",{className:"flex snap-x snap-mandatory gap-2",children:a.map((u,p)=>{const m=o(u)||"Image";return l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>f(p),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?l.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:g=>{const b=g.target;b.style.visibility="hidden"}}):l.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:l.jsx(F,{name:"file-image",className:"h-6 w-6"})}),l.jsx("span",{className:"sr-only",children:m})]})}),l.jsx(gt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u.url||u.filename||p}`)})})})]}):l.jsx("div",{className:P("grid gap-2",n?"grid-cols-1":"grid-cols-1 sm:grid-cols-2"),children:r.map((u,p)=>{const m=o(u),g=u.mime?.startsWith("image/"),b=i(u.size),y=wf(u);if(g&&u.url)return l.jsxs("div",{className:"relative aspect-video rounded-lg border border-border/40 bg-muted/10 overflow-hidden group",children:[l.jsx("img",{src:u.url,alt:m,className:"h-full w-full object-cover",loading:"lazy"}),l.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"}),l.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-2 text-white opacity-0 group-hover:opacity-100 transition-opacity",children:[l.jsx("p",{className:"text-xs font-medium truncate",children:m}),b&&l.jsx("p",{className:"text-xs opacity-80",children:b})]})]},u.url||`${m}-${p}`);if(y&&u.url)return l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>{Lh(u.url||"")},className:P("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:[l.jsx("div",{className:"flex-shrink-0",children:y==="pr"?l.jsx(F,{name:"git-pull-request",className:P("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):l.jsx(F,{name:"github",className:P("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"font-medium truncate",children:m}),b&&l.jsx("p",{className:"text-xs text-muted-foreground",children:b})]})]})}),l.jsx(gt,{children:l.jsxs("p",{children:[m,b?` (${b})`:""]})})]},u.url||`${m}-${p}`);const S=u.source,v=typeof S?.type=="string"?S.type:void 0,x=S&&typeof S.path=="string"?S.path:void 0,k=v==="file"&&x?x:u.url||"";return k&&$3(k)?l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>{ne.getState().navigateToDiagram(k)},className:P("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:[l.jsx(F,{name:"file",className:P("text-muted-foreground shrink-0",n?"h-3.5 w-3.5":"h-4 w-4")}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"font-medium truncate",children:m}),l.jsx("p",{className:"text-xs text-status-info",children:"Open in diagram view"})]}),l.jsx(F,{name:"external-link",className:P("text-muted-foreground shrink-0",n?"h-3 w-3":"h-3.5 w-3.5")})]})}),l.jsx(gt,{children:l.jsx("p",{children:"Open in diagram view"})})]},u.url||`${m}-${p}`):l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>{t&&u.url&&t({open:!0,title:m,content:"",image:{url:u.url,mimeType:u.mime,filename:m}})},className:P("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:[l.jsx("div",{className:"flex-shrink-0",children:u.mime?.startsWith("image/")?l.jsx(F,{name:"file-image",className:P("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):u.mime?.includes("pdf")?l.jsx(F,{name:"file-pdf",className:P("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):l.jsx(F,{name:"file",className:P("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"font-medium truncate",children:m}),b&&l.jsx("p",{className:"text-xs text-muted-foreground",children:b})]})]})}),l.jsx(gt,{children:l.jsxs("p",{children:[m,b?` (${b})`:""]})})]},u.url||`${m}-${p}`)})})});km.displayName="MessageFilesDisplay";const pL=U.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 l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:P("grid gap-2",r()),children:e.map((s,o)=>l.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:[l.jsx("img",{src:s,alt:t||`Image ${o+1}`,className:"h-full w-full object-cover transition-transform group-hover:scale-105",loading:"lazy"}),l.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors"})]},s))}),t&&l.jsx("p",{className:"text-sm text-muted-foreground italic",children:t})]})});pL.displayName="ImageGallery";const X3=U.memo(({message:e,target:t,sending:n,checking:r,onEdit:s,onSend:o,onCheck:i})=>{const a=ct(x=>x.removeFromQueue),{attributes:c,listeners:d,setNodeRef:f,transform:u,transition:p,isDragging:m}=_p({id:e.id}),g=h.useMemo(()=>{const x=e.content.split(`
70
- `),k=x[0]||"",w=100;return k.length>w?k.substring(0,w)+"...":k+(x.length>1?"...":"")},[e.content]),b=e.attachments?.length??0,y=e.deliveryAttempt!==void 0,S=e.sendFailed===!0,v=n||r;return l.jsxs("div",{ref:f,style:{transform:Ep.Translate.toString(u),transition:p},className:P("flex min-w-0 flex-col gap-1 py-1",m&&"z-10 opacity-60"),children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx("button",{type:"button",...c,...d,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:l.jsx(F,{name:"draggable",className:"h-4 w-4","aria-hidden":"true"})}),l.jsxs("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:[g||"(empty)",b>0&&l.jsx("span",{className:"ml-1 text-muted-foreground",children:b===1?"+1 file":`+${b} files`})]}),l.jsxs(Me,{type:"button",variant:"secondary",size:"xs",onClick:()=>s(e),disabled:v,children:[l.jsx(F,{name:"edit",className:"h-3 w-3","aria-hidden":"true"}),"Edit"]}),y?l.jsxs(Me,{type:"button",variant:"secondary",size:"xs",onClick:()=>i(e),disabled:v,"aria-label":"Check delivery status",title:"Check delivery status",children:[l.jsx(F,{name:"refresh",className:"h-3 w-3","aria-hidden":"true"}),"Check status"]}):l.jsxs(Me,{type:"button",variant:"secondary",size:"xs",onClick:()=>o(e),disabled:v,"aria-label":"Send now with Steering",title:"Send now with Steering",children:[l.jsx(F,{name:"send-plane",className:"h-3 w-3","aria-hidden":"true"}),"Steer"]}),l.jsx("button",{type:"button",onClick:()=>a(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:l.jsx(F,{name:"close",className:"h-4 w-4 text-muted-foreground"})})]}),(n||r||S||y)&&l.jsx("p",{className:P("typography-micro pl-6",S&&!n&&!r?"text-[var(--status-error)]":y&&!n&&!r?"text-[var(--status-warning)]":"text-muted-foreground"),role:S||y?"status":void 0,children:n?"Sending…":r?"Checking status…":S?"Send failed. Retry with Steer or remove.":"Delivery uncertain. Check status before retrying."})]})});X3.displayName="QueuedMessageChip";const p0=[],m0=[],J3=U.memo(({onEditMessage:e,onSendMessage:t})=>{const n=pe(M=>M.currentSessionId),r=pe(h.useCallback(M=>n?M.getDirectoryForSession(n):null,[n])),s=n?bp(n,r):null,o=s?ev(s):null,i=ct(h.useCallback(M=>o?M.queuedMessages[o]??p0:p0,[o])),a=ct(h.useCallback(M=>o?M.sendingIds[o]??m0:m0,[o])),c=ct(M=>M.popToInput),d=ct(M=>M.reorderQueue),[f,u]=h.useState([]),p=n?`session:${n}`:"*",m=qe(M=>M.reducer.bySession,(M,T)=>{if(Object.is(M,T)||!n)return!0;const A=M.get(n)?.queue,j=T.get(n)?.queue;return!A&&!j?!0:!A||!j?!1:A.steering===j.steering&&A.followUp===j.followUp},p),g=n?m.get(n)?.queue:void 0,b=g?.steering??0,y=g?.followUp??0,S=b>0||y>0,v=!!s&&i.length>0,x=b===1?"1 steering message waiting":`${b} steering messages waiting`,k=y===1?"1 follow-up message waiting":`${y} follow-up messages waiting`,w=Cp(ra(lv,{activationConstraint:{distance:8}}),ra(av,{activationConstraint:{delay:200,tolerance:6}})),C=h.useCallback(M=>{const{active:T,over:A}=M;!A||T.id===A.id||!s||d(s,String(T.id),String(A.id))},[s,d]),I=h.useCallback(M=>{if(!s)return;const T=c(s,M.id);if(T){if(T.attachments&&T.attachments.length>0){const A=Ke.getState().attachedFiles;Ke.getState().setAttachedFiles([...A,...T.attachments])}e(T.content,T.attachments)}},[s,c,e]),_=h.useCallback(M=>{t(M.id)},[t]),E=h.useCallback(async M=>{if(!s||!o||f.includes(M.id)||a.includes(M.id))return;const A=ct.getState().queuedMessages[o]?.find(j=>j.id===M.id)?.deliveryAttempt??M.deliveryAttempt;if(A){u(j=>j.includes(M.id)?j:[...j,M.id]);try{const j=await PT(s,A);j==="accepted"?ct.getState().completeQueuedSend(s,M.id):j==="pending"?ke.info("Delivery still pending. Follow-ups are on hold. Check again later."):ke.warning("Delivery status unknown. The message stays on hold. No resend attempted.")}finally{u(j=>j.filter(R=>R!==M.id))}}},[s,o,f,a]);return!v&&!S?null:l.jsx("div",{className:"pb-2 w-full px-1",children:l.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[v&&s&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex w-full items-center gap-2 px-3 py-2 text-left",children:[l.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Follow-up messages"," ",i.length]}),l.jsx(F,{name:"time",className:"ml-auto h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}),l.jsx(kp,{sensors:w,collisionDetection:Mp,onDragEnd:C,children:l.jsx(Ip,{items:i.map(M=>M.id),strategy:cv,children:l.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:i.map(M=>l.jsx(X3,{message:M,target:s,sending:a.includes(M.id),checking:f.includes(M.id),onEdit:I,onSend:_,onCheck:E},M.id))})})})]}),S&&l.jsxs("div",{className:P("px-3 typography-micro text-muted-foreground",v?"pb-3 pt-1":"py-2"),children:[b>0&&l.jsx("p",{role:"status",children:x}),y>0&&l.jsx("p",{role:"status",children:k})]})]})})});J3.displayName="QueuedMessageChips";let Sf=Date.now();const mL=()=>(Sf=Math.max(Sf+1,Date.now()),Sf),g0=()=>!(typeof document>"u"||document.visibilityState!=="visible"||typeof document.hasFocus=="function"&&!document.hasFocus());function gL({sessionId:e,directory:t,text:n,debounceMs:r=250}){const s=qe(m=>e?m.reducer.bySession.get(e)?.extensionDraftTracked===!0:!1,Object.is,e?`session:${e}`:"chrome"),o=s?n:null,i=U.useRef(n);i.current=n;const a=U.useRef(t);a.current=t;const c=U.useRef(e);c.current=e;const d=U.useRef(new Map),f=U.useRef(null),u=U.useRef(new Set);U.useEffect(()=>{if(!e)return;const m=u.current,g=d.current;return()=>{m.delete(e),g.delete(e)}},[e]);const p=U.useCallback((m,g)=>{if(!g0())return;d.current.set(m,g);const b=mL(),y=a.current;Ne.updateExtensionDraft({sessionId:m,text:g,revision:b,...y?{directory:y}:{}}).catch(()=>{d.current.get(m)===g&&d.current.delete(m)})},[]);U.useEffect(()=>{if(!e||!s)return;const m=()=>{if(!g0())return;const g=i.current,b=d.current.get(e);g!==b&&(f.current!==null&&(clearTimeout(f.current),f.current=null),p(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,p]),U.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),p(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 b=i.current,y=c.current;!y||b===d.current.get(y)||p(y,b)},r),()=>{f.current!==null&&(clearTimeout(f.current),f.current=null)}},[e,o,r,p])}const yL="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",vL="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",xL="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",bL="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",wL="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",SL="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",CL="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",kL="/assets/kimi-for-coding-eVEHug_h.svg",ML="/assets/llmapi-detailed-Pup_107f.svg",IL="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",_L="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",EL="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",jL="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",TL="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",AL="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",LL="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",NL="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",RL="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",PL="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",DL="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",OL=Object.assign({"../assets/provider-logos/anthropic.svg":yL,"../assets/provider-logos/bailian-coding-plan.svg":vL,"../assets/provider-logos/cursor.svg":xL,"../assets/provider-logos/evroc.svg":bL,"../assets/provider-logos/github-copilot.svg":wL,"../assets/provider-logos/gocode.svg":SL,"../assets/provider-logos/google.svg":CL,"../assets/provider-logos/kimi-for-coding.svg":kL,"../assets/provider-logos/llmapi-detailed.svg":ML,"../assets/provider-logos/llmapi.svg":IL,"../assets/provider-logos/lmstudio.svg":_L,"../assets/provider-logos/minimax-cn-coding-plan.svg":EL,"../assets/provider-logos/minimax-coding-plan.svg":jL,"../assets/provider-logos/nano-gpt.svg":TL,"../assets/provider-logos/ollama.svg":AL,"../assets/provider-logos/openai.svg":LL,"../assets/provider-logos/openrouter.svg":NL,"../assets/provider-logos/wafer.ai.svg":RL,"../assets/provider-logos/zai-coding-plan.svg":PL,"../assets/provider-logos/zhipuai-coding-plan.svg":DL}),Uh=new Map,Cf=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"]]),HL=e=>(e??"").toLowerCase().trim().replace(/^models\./,"").replace(/^provider\./,"").replace(/\s+/g,"-"),FL=e=>{const t=HL(e);if(!t)return[];const n=t.replace(/[^a-z0-9_\-./:]/g,""),r=n.split(/[/:]/)[0]||n,s=r.split(/[-_.]/)[0]||r,o=[Cf.get(n),Cf.get(r),Cf.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(OL)){const n=e.match(/provider-logos\/([^/]+)\.svg$/i);n?.[1]&&t&&Uh.set(n[1].toLowerCase(),t)}function Mm(e){const t=FL(e),n=t.find(d=>Uh.has(d))??null,r=t[0]??null,s=!!n,o=n?Uh.get(n)??null:null,[i,a]=U.useState(s?"local":"remote");U.useEffect(()=>{a(s?"local":"remote")},[s,n,r]);const c=U.useCallback(()=>{a(d=>d==="local"&&s?"remote":"none")},[s]);return!n&&!r?{src:null,onError:c,hasLogo:!1}:i==="local"&&o?{src:o,onError:c,hasLogo:!0}:i==="remote"&&r?{src:`https://models.dev/logos/${r}.svg`,onError:c,hasLogo:!0}:{src:null,onError:c,hasLogo:!1}}const Eo=({providerId:e,alt:t,className:n,onError:r})=>{const{src:s,onError:o,hasLogo:i}=Mm(e),a=h.useCallback(()=>{o(),r?.()},[o,r]);return!i||!s?null:l.jsx("img",{src:s,alt:t||`${e} logo`,className:P("dark:invert object-contain",n),loading:"eager",decoding:"async",fetchPriority:"high",draggable:!1,onError:a})},y0=Et()(cd(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})),v0=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Im=(e,t,n)=>{const r=v0(t.limit,"context"),s=v0(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}:{}}}},ds=e=>typeof e=="string"?e.trim():"",x0=(e,t)=>!t||t<=0||e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`,VL={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"},b0=e=>e?e[0].toUpperCase()+e.slice(1).toLowerCase():"",BL=e=>{const t=e.startsWith("~")?e.slice(1):e,n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t},$L=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)}},zL=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},UL=e=>{const t=e.toLowerCase(),n=VL[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)?b0(t).replace(/([a-z])(\d)/i,"$1$2"):b0(e)},qL=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},ZL=e=>{const t=ds(e).toLowerCase();return t?t==="free"||t==="thinking"?t:Q3(t):""},Q3=e=>{const t=ds(e);if(!t)return"";const{base:n,suffix:r}=$L(BL(t)),s=qL(zL(n).map(UL));if(s.length>=2){const c=s[s.length-1],d=s[s.length-2];c==="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=ZL(r);return a?`${i} (${a})`:i},_m=(e,t,n={})=>{const r=ds(e?.name);if(r)return x0(r,n.maxLength);const s=ds(e?.id)||ds(t);return s?x0(Q3(s),n.maxLength):n.fallbackLabel??""},WL=(e,t)=>{const n=e?.models;if(!(!n||!t))return Array.isArray(n)?n.find(r=>ds(r.id)===t):n[t]},Em=(e,t,n={})=>{const r=ds(t),s=WL(e,r);return _m(s,r,n)},GL=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),KL=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),cc=e=>_m(e,void 0,{maxLength:40}),YL=e=>{if(typeof e!="number"||Number.isNaN(e))return"";if(e===0)return"0";const t=GL(e);return t.endsWith(".0")?t.slice(0,-2):t},w0=e=>typeof e!="number"||!Number.isFinite(e)?"—":KL(e),XL=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,JL=({metadata:e,active:t,labels:n,children:r})=>{const[s,o]=h.useState(!1);if(h.useEffect(()=>{if(!t){o(!1);return}const d=window.setTimeout(()=>o(!0),450);return()=>window.clearTimeout(d)},[t]),!XL(e))return r;const i=e?.modalities?.input??[],a=e?.modalities?.output??[],c=[e?.tool_call?n.capabilityToolCalling:null,e?.reasoning?n.capabilityReasoning:null].filter(Boolean);return l.jsxs(pt,{delayDuration:0,open:t&&s,onOpenChange:()=>{},children:[l.jsx(mt,{asChild:!0,children:r}),t&&s?l.jsxs(gt,{side:"right",align:"center",sideOffset:8,className:"z-[999] p-2 typography-micro space-y-1.5 shadow-md border pointer-events-none",children:[c.length>0?l.jsxs("div",{children:[l.jsxs("span",{className:"text-muted-foreground",children:[n.capabilities||"Capabilities",": "]}),l.jsx("span",{className:"font-medium",children:c.join(", ")})]}):null,i.length>0||a.length>0?l.jsxs("div",{className:"space-y-0.5",children:[i.length>0?l.jsxs("div",{children:[l.jsxs("span",{className:"text-muted-foreground",children:[n.input||"Input",": "]}),l.jsx("span",{className:"font-medium",children:i.join(", ")})]}):null,a.length>0?l.jsxs("div",{children:[l.jsxs("span",{className:"text-muted-foreground",children:[n.output||"Output",": "]}),l.jsx("span",{className:"font-medium",children:a.join(", ")})]}):null]}):null,e?.cost?.input!==void 0||e?.cost?.output!==void 0?l.jsxs("div",{children:[l.jsxs("span",{className:"text-muted-foreground",children:[n.costPerMillion||"Cost / 1M tokens",": "]}),l.jsxs("span",{className:"font-medium",children:[w0(e?.cost?.input)," / ",w0(e?.cost?.output)]})]}):null]}):null]})},QL=h.memo(({store:e,index:t,children:n})=>{const[r,s]=h.useState(()=>e.getSnapshot()===t);return h.useEffect(()=>{const o=()=>s(e.getSnapshot()===t);return o(),e.subscribeIndex(t,o)},[t,e]),l.jsx(l.Fragment,{children:n(r)})}),eN=({id:e,disabled:t=!1,children:n})=>{const{attributes:r,listeners:s,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:c,isDragging:d}=_p({id:e,disabled:t});return l.jsx("div",{ref:o,style:{transform:Ep.Transform.toString(a),transition:c},className:P(d&&"opacity-60"),children:n({attributes:r,listeners:s,setActivatorNodeRef:i,isDragging:d})})},tN=({entry:e,keyPrefix:t,showProviderLogo:n,rowIndex:r,dragHandleProps:s,selectionStore:o,modelsMetadata:i,selectedModel:a,disabled:c=!1,rowClassName:d,renderVersion:f,tooltipsEnabled:u=!0,labels:p,selectionCount:m,isFavorite:g,onToggleFavorite:b,onSelect:y,selectIndex:S,itemRefs:v,lastMousePositionRef:x,keyboardOwnsSelectionRef:k,reorderFavoriteAriaLabel:w,reorderFavoriteTitle:C,renderRowEnd:I})=>{const _=Im(e.providerID,e.model,i.get(`${e.providerID}/${e.modelID}`)),E=YL(_?.limit?.context),M=m?.(e)??0,T=a?.providerID===e.providerID&&a.modelID===e.modelID,A=g?.(e)??!1,j=R=>{const O={x:R.clientX,y:R.clientY},N=x.current,D=!N||N.x!==O.x||N.y!==O.y;x.current=O,!(k.current&&!N)&&(k.current&&!D||(k.current&&D&&(k.current=!1),S(r)))};return l.jsx(QL,{store:o,index:r,renderVersion:f,children:R=>{const O=l.jsxs("div",{ref:N=>{v.current[r]=N},role:"option","aria-selected":T,"aria-disabled":c||void 0,tabIndex:-1,onClick:()=>{c||y(e)},onKeyDown:N=>{c||(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),y(e))},onMouseEnter:j,onMouseMove:j,className:P("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!c&&(R?"bg-interactive-selection":"hover:bg-interactive-hover/50"),c&&"cursor-not-allowed opacity-60",d),children:[l.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[s?l.jsx("button",{type:"button",ref:s.setActivatorNodeRef,...s.attributes,...s.listeners,disabled:c,onClick:N=>{N.preventDefault(),N.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:C,children:l.jsx(F,{name:"draggable",className:"size-3.5"})}):null,n?l.jsx(Eo,{providerId:e.providerID,className:"h-3.5 w-3.5 flex-shrink-0"}):null,l.jsx("span",{className:"font-medium truncate",children:cc(e.model)}),E?l.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:E}):null]}),M>0?l.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["x",M]}):null,I?.(e,{isHighlighted:R,isSelected:T}),T?l.jsx(F,{name:"check",className:"h-4 w-4 text-primary flex-shrink-0"}):null,b?l.jsx("button",{type:"button",disabled:c,onClick:N=>{N.preventDefault(),N.stopPropagation(),b(e)},className:P("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-primary/80 flex-shrink-0 disabled:pointer-events-none",A?"text-primary":"text-muted-foreground"),"aria-label":A?p.unfavorite:p.favorite,title:A?p.unfavorite:p.favorite,children:l.jsx(F,{name:A?"star-fill":"star",className:"h-3.5 w-3.5"})}):null]});return l.jsx(JL,{metadata:_,active:u&&R,labels:p,children:O})}},`${t}-${e.providerID}-${e.modelID}`)},nN=(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()}}},rN=48,sN=32,oN=24;function iN({providers:e,favoriteModels:t,recentModels:n,searchQuery:r,hiddenModels:s=[],allowedProviderIds:o,isModelAllowed:i,stickyHeaders:a=!0,scrollRef:c,collapsedSections:d}){const f=h.useRef(0),u=h.useMemo(()=>o?new Set(o):null,[o]),p=h.useMemo(()=>new Map(e.map(I=>[I.id,I])),[e]),m=h.useCallback((I,_)=>s.some(E=>E.providerID===I&&E.modelID===_),[s]),g=h.useCallback((I,_)=>{const E=r.trim().toLowerCase();return E?I.toLowerCase().includes(E)||_.toLowerCase().includes(E):!0},[r]),b=h.useMemo(()=>t.filter(({model:I,providerID:_,modelID:E})=>{if(u&&!u.has(_)||i&&!i(_,E)||m(_,E))return!1;const M=p.get(_)?.name||_;return g(cc(I),M)}),[u,t,m,i,g,p]),y=h.useMemo(()=>n.filter(({model:I,providerID:_,modelID:E})=>{if(u&&!u.has(_)||i&&!i(_,E)||m(_,E))return!1;const M=p.get(_)?.name||_;return g(cc(I),M)}),[u,m,i,g,p,n]),S=h.useMemo(()=>e.filter(I=>!u||u.has(I.id)).map(I=>{const E=(Array.isArray(I.models)?I.models:[]).filter(M=>{const T=typeof M.id=="string"?M.id:"";return!T||m(I.id,T)||i&&!i(I.id,T)?!1:g(cc(M),I.name||I.id)});return{...I,models:E}}).filter(I=>I.models.length>0),[u,m,i,g,e]),v=h.useMemo(()=>[...b.length>0?["favorites"]:[],...y.length>0?["recent"]:[],...S.map(I=>`provider:${I.id}`)],[b.length,S,y.length]),x=h.useCallback(I=>{const E=I.scrollTop>1?Math.min(sN+I.scrollTop,rN):0;f.current=E,I.style.setProperty("--scroll-shadow-top-size",`${E}px`),I.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(E-8,0),oN)}px`)},[]),k=h.useCallback(I=>{I.target.closest("[data-overlay-scrollbar-thumb], [data-model-picker-sticky-header]")||I.clientY-I.currentTarget.getBoundingClientRect().top>=f.current||(I.preventDefault(),I.stopPropagation())},[]);h.useLayoutEffect(()=>{a&&c.current&&x(c.current)},[c,a,x,v]);const w=h.useMemo(()=>{const I=[];return d.has("favorites")||b.forEach(_=>I.push(_)),d.has("recent")||y.forEach(_=>I.push(_)),S.forEach(_=>{d.has(`provider:${_.id}`)||_.models.forEach(E=>I.push({model:E,providerID:_.id,modelID:E.id}))}),I},[d,b,S,y]),C=h.useMemo(()=>new Map(b.map(I=>[`${I.providerID}:${I.modelID}`,I])),[b]);return{allowedProviderSet:u,providerById:p,filteredFavorites:b,filteredRecents:y,filteredProviders:S,visibleSectionKeys:v,flatModelList:w,favoriteLookup:C,syncStickyFade:x,blockStickyFadeInteraction:k}}const S0=32,aN=(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,c=i+S0,d=s<c?s-S0:o>a?o-e.clientHeight:i,f=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.max(0,Math.min(d,f))},lN=({providers:e,favoriteModels:t,recentModels:n,modelsMetadata:r,searchQuery:s,onSearchQueryChange:o,onSelect:i,labels:a,selectedModel:c,hiddenModels:d=[],allowedProviderIds:f,isModelAllowed:u,includeNotSelected:p=!1,onSelectNone:m,selectionCount:g,disabled:b=!1,maxHeightClassName:y="max-h-[min(400px,calc(100dvh-12rem))] flex-1",maxHeightStyle:S,sectionHeaderClassName:v,rowClassName:x,stickyHeaders:k=!0,autoFocus:w=!0,onEscape:C,isFavorite:I,onToggleFavorite:_,renderRowEnd:E,onActiveKeyDown:M,onActiveEntryChange:T,onVariantKey:A,onReorderFavorite:j,reorderFavoriteAriaLabel:R,reorderFavoriteTitle:O,renderVersion:N,tooltipsEnabled:D=!0})=>{const K=h.useRef(null);K.current||(K.current=nN());const V=K.current,W=h.useRef([]),B=h.useRef(null),Z=h.useRef(!1),L=h.useRef(null),$=y0(xe=>xe.collapsedSections),G=y0(xe=>xe.toggleSection),Q=h.useMemo(()=>new Set(Object.keys($).filter(xe=>$[xe])),[$]),z=Cp(ra(J9,{activationConstraint:{distance:8}})),{filteredFavorites:X,filteredRecents:Y,filteredProviders:ce,flatModelList:se,favoriteLookup:ue,syncStickyFade:Ie,blockStickyFadeInteraction:de}=iN({providers:e,favoriteModels:t,recentModels:n,searchQuery:s,hiddenModels:d,allowedProviderIds:f,isModelAllowed:u,stickyHeaders:k,scrollRef:B,collapsedSections:Q}),Fe=se.length>0,$e=!!j&&s.trim().length===0&&X.length>1;h.useEffect(()=>{V.set(0)},[s,V]);const Xe=h.useCallback(xe=>{V.set(xe),T?.(se[xe])},[se,T,V]),We=h.useCallback(xe=>{const re=se.length;if(re===0)return;Z.current=!0,L.current=null;const fe=(V.getSnapshot()+xe+re)%re;V.set(fe),T?.(se[fe]),requestAnimationFrame(()=>aN(B.current,W.current[fe]))},[se,T,V]);h.useEffect(()=>{T?.(se[V.getSnapshot()])},[se,T,V]);const Ae=h.useCallback(xe=>{if(!xe.defaultPrevented){if(xe.stopPropagation(),xe.key==="ArrowLeft"||xe.key==="ArrowRight"){const re=se[V.getSnapshot()];if(re&&A?.(xe,re))return}if(M?.(xe,se[V.getSnapshot()]),!xe.defaultPrevented){if(xe.key==="ArrowDown"){xe.preventDefault(),We(1);return}if(xe.key==="ArrowUp"){xe.preventDefault(),We(-1);return}if(xe.key==="Enter"){xe.preventDefault();const re=se[V.getSnapshot()];re&&!b&&i(re);return}xe.key==="Escape"&&(xe.preventDefault(),C?.())}}},[b,se,We,M,C,i,A,V]),be=P("typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 px-2 py-1.5",k&&"sticky top-0 z-20",v);let te=0;const ve=(xe,re,me,fe,Se)=>l.jsx(tN,{entry:xe,keyPrefix:re,showProviderLogo:me,rowIndex:fe,dragHandleProps:Se,selectionStore:V,modelsMetadata:r,selectedModel:c,disabled:b,rowClassName:x,renderVersion:N,tooltipsEnabled:D,labels:a,selectionCount:g,isFavorite:I,onToggleFavorite:_,onSelect:i,selectIndex:Xe,itemRefs:W,lastMousePositionRef:L,keyboardOwnsSelectionRef:Z,reorderFavoriteAriaLabel:R,reorderFavoriteTitle:O,renderRowEnd:E},`${re}-${xe.providerID}-${xe.modelID}`),we=xe=>{if(!j)return;const{active:re,over:me}=xe;if(!me||re.id===me.id)return;const fe=ue.get(String(re.id)),Se=ue.get(String(me.id));!fe||!Se||j(fe,Se)},je=xe=>Q.has(xe),Ce=xe=>G(xe),ze=(xe,re,me)=>{const fe=je(xe),Se=_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),Ce(xe))};return l.jsxs("button",{type:"button","aria-expanded":!fe,"data-model-picker-sticky-header":k?"true":void 0,className:P(be,"w-full text-left"),onClick:()=>Ce(xe),onKeyDown:Se,children:[re,l.jsx("span",{className:"min-w-0 truncate",children:me}),l.jsx("span",{className:"ml-auto flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",children:l.jsx(F,{name:fe?"arrow-right-s":"arrow-down-s",className:"size-4"})})]})},ht=()=>ce.map(xe=>{const re=je(`provider:${xe.id}`);return l.jsxs("div",{className:"relative overflow-hidden",children:[ze(`provider:${xe.id}`,l.jsx(Eo,{providerId:xe.id,className:"h-3.5 w-3.5 flex-shrink-0"}),xe.name||xe.id),re?null:l.jsx("div",{className:"space-y-0.5 mt-0.5",children:xe.models.map(me=>{const fe={model:me,providerID:xe.id,modelID:me.id},Se=te;return te+=1,ve(fe,xe.id,!1,Se)})})]},xe.id)});return l.jsxs("div",{className:"flex flex-col min-h-0",children:[l.jsx("div",{className:"p-2 border-b",children:l.jsx(Io,{placeholder:a.searchPlaceholder,value:s,onChange:xe=>o(xe.target.value),onKeyDown:Ae,autoFocus:w,className:"h-8 typography-meta"})}),l.jsx("div",{className:"relative flex flex-col min-h-0",onMouseDown:de,onPointerDown:de,children:l.jsxs(Fn,{ref:B,className:P(y,"p-2 space-y-3 min-h-0"),style:S,onScroll:xe=>{k&&Ie(xe.currentTarget)},children:[p&&m?l.jsx("div",{className:"pb-1 border-b mb-1",children:l.jsxs("button",{type:"button",disabled:b,onClick:m,className:P("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!b&&"hover:bg-interactive-hover/50",b&&"cursor-not-allowed opacity-60",x),children:[l.jsx("span",{className:"font-medium text-muted-foreground",children:a.notSelected||"Not Selected"}),c?null:l.jsx(F,{name:"check",className:"h-4 w-4 text-primary ml-auto flex-shrink-0"})]})}):null,X.length>0?l.jsxs("div",{className:"relative overflow-hidden",children:[ze("favorites",l.jsx(F,{name:"star-fill",className:"h-3.5 w-3.5 text-primary flex-shrink-0"}),a.favorites),je("favorites")?null:$e?l.jsx(kp,{sensors:z,collisionDetection:Mp,onDragEnd:we,children:l.jsx(Ip,{items:X.map(xe=>`${xe.providerID}:${xe.modelID}`),strategy:cv,children:l.jsx("div",{className:"space-y-0.5 mt-0.5",children:X.map(xe=>{const re=`${xe.providerID}:${xe.modelID}`,me=te;return te+=1,l.jsx(eN,{id:re,disabled:b,children:fe=>ve(xe,"favorite",!0,me,fe)},`favorite-${re}`)})})})}):l.jsx("div",{className:"space-y-0.5 mt-0.5",children:X.map(xe=>{const re=te;return te+=1,ve(xe,"favorite",!0,re)})})]}):null,Y.length>0?l.jsxs("div",{className:"relative overflow-hidden",children:[ze("recent",l.jsx(F,{name:"history",className:"h-3.5 w-3.5 flex-shrink-0"}),a.recent),je("recent")?null:l.jsx("div",{className:"space-y-0.5 mt-0.5",children:Y.map(xe=>{const re=te;return te+=1,ve(xe,"recent",!0,re)})})]}):null,ht(),Fe?null:l.jsx("div",{className:"p-4 text-center typography-meta text-muted-foreground",children:a.noResults})]})})]})};function eb(){const e=Ge();return U.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 cN=()=>{const e=Ze(a=>a.providers),t=ne(a=>a.favoriteModels),n=ne(a=>a.recentModels),r=ne(a=>a.hiddenModels),s=h.useCallback((a,c)=>r.some(d=>d.providerID===a&&d.modelID===c),[r]),o=h.useMemo(()=>t.map(({providerID:a,modelID:c})=>{const d=e.find(p=>p.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(p=>p.id===c);return!u||s(a,c)?null:{provider:d,model:u,providerID:a,modelID:c}}).filter(a=>a!==null),[t,e,s]),i=h.useMemo(()=>n.map(({providerID:a,modelID:c})=>{const d=e.find(p=>p.id===a);if(!d)return null;const u=(Array.isArray(d.models)?d.models:[]).find(p=>p.id===c);return!u||s(a,c)?null:{provider:d,model:u,providerID:a,modelID:c}}).filter(a=>a!==null).filter(({providerID:a,modelID:c})=>!t.some(d=>d.providerID===a&&d.modelID===c)),[n,e,t,s]);return{favoriteModelsList:o,recentModelsList:i}},dN=typeof window<"u"?h.useLayoutEffect:h.useEffect,uN=(e,t=[])=>{const[n,r]=h.useState(!1),s=h.useCallback(()=>{const o=e.current;if(!o)return;const i=o.scrollWidth>o.clientWidth+1;r(i)},[e]);return dN(()=>{s()},[s,...t]),h.useEffect(()=>{const o=e.current;if(!o||typeof ResizeObserver>"u")return;const i=new ResizeObserver(()=>{s()});return i.observe(o),()=>i.disconnect()},[s,e]),h.useEffect(()=>{if(typeof window>"u")return;const o=()=>s();return window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[s]),n},jm=(e,t)=>t?[void 0,...e]:[...e],tb=e=>e??"default",fN=(e,t)=>t===0?50:e/t*100,kl=10,hN={side:"none",align:"none",fallbackAxisSide:"none"};function C0({options:e,value:t,prefix:n="",className:r,truncateAt:s}){const o=i=>s==null||i.length<=s?i:`${i.slice(0,s)}...`;return l.jsxs("span",{className:P("grid min-w-0 justify-items-start",r),children:[e.map(i=>l.jsxs("span",{className:"invisible col-start-1 row-start-1 overflow-hidden whitespace-nowrap","aria-hidden":"true",children:[n,o(Tr(i))]},tb(i))),l.jsxs("span",{className:"col-start-1 row-start-1 truncate",children:[n,o(t)]})]})}function pN({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=h.useRef(null),i=jm(e,s),[a,c]=h.useState(null),[d,f]=h.useState(null),u=a!==null?a:t,p=Math.max(0,i.findIndex(j=>j===u)),m=Math.max(0,i.length-1),g=m===0?0:p/m,b=d!==null?d:g,y=Tr(i[p]),S=h.useRef(null),v=h.useRef(t),x=h.useRef(i),k=h.useRef(n),w=h.useRef(r),C=h.useRef(null);h.useEffect(()=>{v.current=t},[t]),h.useEffect(()=>{x.current=i},[i]),h.useEffect(()=>{k.current=n},[n]),h.useEffect(()=>{w.current=r},[r]),h.useEffect(()=>{C.current=a},[a]),h.useEffect(()=>{a!==null&&a===t&&(c(null),f(null))},[t,a]);const I=h.useCallback(j=>{const R=o.current?.getBoundingClientRect(),O=x.current;if(!R||R.width<=0||O.length===0)return{next:O[0],clamped:0};const N=Math.min(Math.max((j-R.left)/R.width,0),1),D=o8(N,O.length);return{next:O[D],clamped:N}},[]),_=j=>{j.preventDefault();const{next:R,clamped:O}=I(j.clientX);c(R),f(O),C.current=R,S.current=j.pointerId;try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}!w.current&&R!==v.current&&k.current(R)},E=j=>{if(S.current!==j.pointerId)return;j.preventDefault();const{next:R,clamped:O}=I(j.clientX);f(O),R!==C.current&&(c(R),C.current=R,!w.current&&R!==v.current&&k.current(R))},M=j=>{if(S.current!==j.pointerId)return;const{next:R,clamped:O}=I(j.clientX),N=C.current??R,D=d??O;S.current=null;try{j.currentTarget.hasPointerCapture(j.pointerId)&&j.currentTarget.releasePointerCapture(j.pointerId)}catch{}w.current?(w.current(N),f(D)):N!==v.current&&k.current(N),w.current||(c(null),f(null))},T=j=>{S.current===j.pointerId&&(S.current=null,c(null),f(null))},A=j=>{let R=null;if((j.key==="ArrowRight"||j.key==="ArrowUp")&&(R=Math.min(m,p+1)),(j.key==="ArrowLeft"||j.key==="ArrowDown")&&(R=Math.max(0,p-1)),j.key==="Home"&&(R=0),j.key==="End"&&(R=m),R===null||R===p)return;j.preventDefault();const O=i[R];w.current?w.current(O):n(O)};return l.jsx("div",{role:"slider",tabIndex:0,"aria-label":"Thinking","aria-orientation":"horizontal","aria-valuemin":0,"aria-valuemax":m,"aria-valuenow":p,"aria-valuetext":y,"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:_,onPointerMove:E,onPointerUp:M,onPointerCancel:T,onLostPointerCapture:T,onKeyDown:A,children:l.jsxs("div",{className:"relative h-8",children:[l.jsx("div",{className:"absolute inset-x-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-muted"}),l.jsx("div",{className:"absolute left-0 top-1/2 h-5 -translate-y-1/2 rounded-full bg-primary",style:{width:`calc(${kl}px + (100% - ${kl*2}px) * ${b})`}}),l.jsxs("div",{ref:o,className:"absolute inset-y-0",style:{left:kl,right:kl},children:[i.map((j,R)=>{const O=fN(R,m),N=R<=p;return l.jsx("div",{"aria-hidden":"true",className:P("pointer-events-none absolute top-1/2 size-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full",N?"bg-primary-foreground/50":"bg-foreground/35"),style:{left:`${O}%`}},tb(j))}),l.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-1/2 h-0",children:l.jsx("div",{className:"w-full",style:{transform:`translateX(${b*100}%)`},children:l.jsx("div",{className:"absolute left-0 top-0 size-8 -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground"})})})]})]})})}function Tm({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=jm(e,s);return l.jsxs("div",{className:"w-full px-4 pt-3.5 pb-2","data-no-drawer-swipe":"true",children:[l.jsx(pN,{levels:e,value:t,onChange:n,onCommit:r,allowUnset:s}),l.jsxs("div",{className:"mt-1.5 flex justify-between px-4 typography-micro text-muted-foreground",children:[l.jsx("span",{children:Tr(o[0])}),l.jsx("span",{className:"text-right",children:Tr(o[o.length-1])})]})]})}function mN({levels:e,value:t,onChange:n,compact:r,keepLabel:s=!1,onCompactOpen:o,buttonHeight:i,iconSize:a,textSize:c,isMobile:d,isDesktop:f}){const[u,p]=h.useState(!1),m=Tr(t),b=!t?"text-muted-foreground":"text-foreground",y=jm(e,!0),S=d?10:void 0,v=l.jsxs("button",{type:"button",onClick:r?o:void 0,className:P("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:[l.jsx(F,{name:"brain-ai-3",className:P(a,"flex-shrink-0",b)}),l.jsx(C0,{options:y,value:m,truncateAt:S,className:P("model-controls__variant-label",c,"font-normal",s?"min-w-max whitespace-nowrap":null,r&&d&&!s&&"max-w-[60px]",!r&&f&&"max-w-[180px]",b)})]});return r?v:l.jsxs(dv,{open:u,onOpenChange:p,children:[l.jsxs(pt,{delayDuration:600,...u?{open:!1}:{},children:[l.jsx(mt,{asChild:!0,children:l.jsx(uv,{render:v})}),l.jsx(gt,{side:"top",align:"center",children:l.jsx(C0,{options:y,value:m,prefix:"Thinking: ",className:"typography-meta"})})]}),l.jsx(fv,{children:l.jsx(hv,{className:"app-region-no-drag z-50",side:"top",align:"center",sideOffset:8,collisionPadding:8,collisionAvoidance:hN,children:l.jsx(pv,{className:P(am,"w-[min(17.5rem,calc(100vw-2rem))] p-0 max-h-none"),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},children:l.jsx(Tm,{levels:e,value:t,onChange:n})})})})]})}function gN(){const e=Ze(i=>i.isInitialized),t=Ze(i=>i.connectionPhase),n=Ze(i=>i.lastDisconnectReason),r=Ze(i=>i.providers.length>0),s=e||r,o=!s&&n==="init_error";return{isReady:s,isLoading:!s&&!o,isUnavailable:o,connectionPhase:t}}const yN=({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"},vN=[{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}],xN={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"}},bN=e=>e.trim().toLowerCase(),$c=(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=>bN(o)))),s=[];for(const o of r){const i=xN[o];i&&s.push({key:o,icon:i.icon,label:i.label})}return s},wN=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),SN=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),CN=e=>new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(e),kN=e=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e),ha=e=>{if(typeof e!="number"||Number.isNaN(e))return"—";if(e===0)return"0";const t=wN(e);return t.endsWith(".0")?t.slice(0,-2):t},Ml=e=>typeof e!="number"||!Number.isFinite(e)?"—":SN(e),nb=e=>{const t=[];for(const n of vN)n.isActive(e)&&t.push({key:n.key,icon:n.icon,label:n.label});return t},rb=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 CN(s)}return e},sb=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:kN(t)},mo=({iconName:e,label:t})=>l.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:l.jsx(F,{name:e,className:"size-3.5"})}),MN=({currentMetadata:e,modelDisplayName:t,providerDisplayName:n,currentCapabilityIcons:r,inputModalityIcons:s,outputModalityIcons:o,costRows:i,limitRows:a})=>l.jsx(gt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e?l.jsxs("div",{className:"flex min-w-[240px] flex-col gap-3",children:[l.jsxs("div",{className:"flex flex-col gap-0.5",children:[l.jsx("span",{className:"typography-micro font-semibold text-foreground",children:e.name||t}),l.jsx("span",{className:"typography-meta text-muted-foreground",children:n})]}),l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Capabilities"}),l.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:r.length>0?r.map(({key:c,icon:d,label:f})=>l.jsx(mo,{iconName:d,label:f},`cap-${c}`)):l.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),l.jsxs("div",{className:"flex flex-col gap-1",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),l.jsx("div",{className:"flex items-center gap-1.5",children:s.length>0?s.map(({key:c,icon:d,label:f})=>l.jsx(mo,{iconName:d,label:`${f} input`},`input-${c}`)):l.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),l.jsx("div",{className:"flex items-center gap-1.5",children:o.length>0?o.map(({key:c,icon:d,label:f})=>l.jsx(mo,{iconName:d,label:`${f} output`},`output-${c}`)):l.jsx("span",{className:"typography-meta text-muted-foreground",children:"-"})})]})]})]}),l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),i.map(c=>l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:c.label}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:c.value})]},c.label))]}),l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),a.map(c=>l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:c.label}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:c.value})]},c.label))]}),l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:rb(e.knowledge)})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Release"}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:sb(e.release_date)})]})]})]}):l.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),IN=({open:e,onClose:t,title:n,providerDisplayName:r,currentCapabilityIcons:s,inputModalityIcons:o,outputModalityIcons:i,currentMetadata:a})=>e?l.jsx(fa,{open:!0,onClose:t,title:n,children:l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[l.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),l.jsx("div",{className:"typography-meta text-foreground font-medium",children:r})]}),s.length>0&&l.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[l.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(({key:c,icon:d,label:f})=>l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(mo,{iconName:d,label:f},`cap-${c}`),l.jsx("span",{className:"typography-meta text-foreground",children:f})]},c))})]}),(o.length>0||i.length>0)&&l.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[l.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),l.jsxs("div",{className:"flex flex-col gap-1",children:[o.length>0&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Input"}),l.jsx("div",{className:"flex gap-1",children:o.map(({key:c,icon:d,label:f})=>l.jsx(mo,{iconName:d,label:`${f} input`},`input-${c}`))})]}),i.length>0&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Output"}),l.jsx("div",{className:"flex gap-1",children:i.map(({key:c,icon:d,label:f})=>l.jsx(mo,{iconName:d,label:`${f} output`},`output-${c}`))})]})]})]}),l.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[l.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),l.jsxs("div",{className:"flex flex-col gap-0.5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:ha(a?.limit?.context)})]}),l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Output"}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:ha(a?.limit?.output)})]})]})]}),l.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[l.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Metadata"}),l.jsxs("div",{className:"flex flex-col gap-0.5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Knowledge"}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:rb(a?.knowledge)})]}),l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Release"}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:sb(a?.release_date)})]})]})]})]})}):null,_N=({open:e,onClose:t,targetVariants:n,selectedVariant:r,onVariantLiveChange:s,onVariantCommit:o})=>!e||n.length===0?null:l.jsx(fa,{open:!0,onClose:t,title:"Thinking",children:l.jsx(Tm,{levels:n,value:tn(r)??void 0,onChange:s,onCommit:o})}),EN=e=>{if(!e||e.trim().length===0)return Tr(void 0);const t=e.trim();return/^\d+(\.\d+)?$/.test(t)?t:Tr(t)},jN=(e,t)=>`${e}:${t}`,TN=({open:e,onClose:t,mobileModelQuery:n,onMobileModelQueryChange:r,filteredFavorites:s,filteredRecents:o,filteredProviders:i,expandedMobileProviders:a,onToggleMobileProviderExpansion:c,expandedMobileModelKey:d,onToggleExpandedMobileModelKey:f,currentProviderId:u,currentModelId:p,getModelDisplayName:m,getModelMetadata:g,getModelVariantOptions:b,resolveModelVariantSelection:y,pendingThinkingVariants:S,onUpdatePendingThinkingVariant:v,isFavoriteModel:x,onToggleFavoriteModel:k,onApplyModel:w})=>{if(!e)return null;const C=n.trim(),I=s.length>0||o.length>0||i.length>0,_=({model:E,providerId:M,modelId:T,showProviderLogo:A})=>{const j=jN(M,T),R=M===u&&T===p,O=Im(M,E,g(M,T)),N=b(M,T),D=N.length>0,K=y(M,T),V=S.get(j),B=S.has(j)?V:K,Z=D?EN(B):null,L=d===j,$=nb(O),G=[...$c(O,"input"),...$c(O,"output")],Q=Array.from(new Map([...$,...G].map(X=>[X.key,X])).values()),z=O?.limit?.context?`${ha(O.limit.context)} ctx`:null;return l.jsxs("div",{className:P("border-b border-border/30 last:border-b-0",R&&"bg-interactive-selection/15 text-interactive-selection-foreground"),children:[l.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5",children:[l.jsx("button",{type:"button",onClick:()=>w(M,T,B),className:P("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:l.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[A?l.jsx(Eo,{providerId:M,className:"size-3.5 flex-shrink-0"}):null,l.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:m(E)}),R?l.jsx(F,{name:"check",className:"size-4 flex-shrink-0 text-primary"}):null]}),z||Q.length>0?l.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden typography-micro text-muted-foreground",children:[z?l.jsx("span",{className:"whitespace-nowrap flex-shrink-0",children:z}):null,z&&Q.length>0?l.jsx("span",{"aria-hidden":"true",className:"h-3 w-px flex-shrink-0 bg-border/50"}):null,Q.length>0?l.jsx("div",{className:"flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap pl-0.5",children:Q.map(({key:X,icon:Y,label:ce})=>l.jsx("span",{className:"flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",title:ce,"aria-label":ce,children:l.jsx(F,{name:Y,className:"size-3"})},`meta-${M}-${T}-${X}`))}):null]}):null]})}),D?l.jsxs("button",{type:"button",onClick:()=>f(d===j?null:j),className:"flex items-center gap-0.5 typography-micro font-medium text-muted-foreground hover:text-foreground flex-shrink-0","aria-expanded":L,"aria-label":L?"Hide thinking modes":"Show thinking modes",children:[l.jsx("span",{className:"whitespace-nowrap",children:Z}),L?l.jsx(F,{name:"arrow-down-s",className:"size-3.5"}):l.jsx(F,{name:"arrow-right-s",className:"size-3.5"})]}):null,l.jsx("div",{className:"flex flex-shrink-0 items-center gap-1.5",children:l.jsx("button",{type:"button",onClick:X=>{X.preventDefault(),X.stopPropagation(),k(M,T)},className:P("model-favorite-button flex size-5 items-center justify-center hover:text-primary/80 flex-shrink-0",x(M,T)?"text-primary":"text-muted-foreground"),"aria-label":x(M,T)?"Unfavorite":"Favorite",title:x(M,T)?"Remove from favorites":"Add to favorites",children:x(M,T)?l.jsx(F,{name:"star-fill",className:"size-4"}):l.jsx(F,{name:"star",className:"size-4"})})})]}),L&&D?l.jsx("div",{className:"border-t border-border/30 px-1 py-1","data-no-drawer-swipe":"true",children:l.jsx(Tm,{levels:N,value:tn(B)??void 0,onChange:()=>{},onCommit:X=>v(j,X)})}):null]},`mobile-model-${M}-${T}`)};return l.jsx(fa,{open:!0,onClose:t,title:"Select model",children:l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("div",{children:l.jsxs("div",{className:"relative",children:[l.jsx(F,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground"}),l.jsx(Io,{value:n,onChange:E=>{r(E.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&&l.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:l.jsx(F,{name:"close-circle",className:"size-4"})})]})}),!I&&l.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&&l.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[l.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[l.jsx(F,{name:"star-fill",className:"size-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),l.jsx("div",{className:"flex flex-col border-t border-border/30",children:s.map(({model:E,providerID:M,modelID:T})=>_({model:E,providerId:M,modelId:T,showProviderLogo:!0}))})]}),o.length>0&&l.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[l.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[l.jsx(F,{name:"time",className:"size-3 inline-block mr-1.5"}),"Recent"]}),l.jsx("div",{className:"flex flex-col border-t border-border/30",children:o.map(({model:E,providerID:M,modelID:T})=>_({model:E,providerId:M,modelId:T,showProviderLogo:!0}))})]}),i.map(({provider:E,providerModels:M})=>{if(M.length===0)return null;const T=String(E.id||""),A=String(E.name||T),j=T===u,R=a.has(T)||C.length>0;return l.jsxs("div",{className:"rounded-xl border border-border/40 bg-[var(--surface-elevated)] overflow-hidden",children:[l.jsxs("button",{type:"button",onClick:()=>{C.length>0||c(T)},className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":R,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Eo,{providerId:T,className:"size-3.5"}),l.jsx("span",{className:"typography-meta font-medium text-foreground",children:A}),j&&l.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),R?l.jsx(F,{name:"arrow-down-s",className:"size-3 text-muted-foreground"}):l.jsx(F,{name:"arrow-right-s",className:"size-3 text-muted-foreground"})]}),R&&M.length>0&&l.jsx("div",{className:"flex flex-col border-t border-border/30",children:M.map(O=>_({model:O,providerId:String(E.id||""),modelId:String(O.id||""),showProviderLogo:!1}))})]},T)})]})})},kf=(e,t)=>`${e}:${t}`,AN="__add_provider__",LN=({className:e,keepLabels:t=!1,mobilePanel:n,onMobilePanelChange:r})=>{const{isReady:s,isUnavailable:o}=gN(),i=o?"Unavailable":"Loading...",a=Ze(q=>q.providers),c=Ze(q=>q.currentProviderId),d=Ze(q=>q.currentModelId),f=Ze(q=>q.currentVariant),u=Ze(q=>q.settingsDefaultThinking),p=Ze(q=>q.settingsDefaultThinkingByModel),m=Ze(q=>q.setProvider),g=Ze(q=>q.setSelectedProvider),b=Ze(q=>q.setModel),y=Ze(q=>q.setCurrentVariant),S=Ze(q=>q.getCurrentModelVariants),v=Ze(q=>q.getCurrentProvider),x=Ze(q=>q.getModelMetadata),k=h.useRef(!1);h.useEffect(()=>{k.current||!s||(k.current=!0,st("ModelControls:ready",{providers:a.length,currentProviderId:c,currentModelId:d}))},[d,c,s,a.length]);const w=pe(q=>q.currentSessionId),C=pe(q=>q.newSessionDraft.open),I=pe(q=>q.getDirectoryForSession),_=eb(),E=_t(q=>q.getSessionModelSelection),M=_t(q=>q.saveSessionModelSelection),T=_t(q=>q.hasHydrated),A=ne(q=>q.toggleFavoriteModel),j=ne(q=>q.reorderFavoriteModel),R=ne(q=>q.isFavoriteModel),O=ne(q=>q.addRecentModel),N=ne(q=>q.addRecentEffort),D=ne(q=>q.isModelSelectorOpen),K=ne(q=>q.setModelSelectorOpen),V=ne(q=>q.setSettingsDialogOpen),W=ne(q=>q.setSettingsPage),B=ne(q=>q.hiddenModels),{favoriteModelsList:Z,recentModelsList:L}=cN(),{isMobile:$}=Pr(),{enabled:G}=jd(),Q=ne(q=>q.isMobile),z=($||Q)&&!G,X=h.useMemo(()=>bt(),[]),Y=z,[ce,se]=h.useState(null),ue=n!==void 0&&typeof r=="function",Ie=ue?n:ce,de=ue?r:se,[Fe,$e]=h.useState(null),[Xe,We]=h.useState(""),[Ae,be]=h.useState(null),te=h.useRef(!1),ve=h.useCallback(()=>de(null),[de]),we=h.useCallback(()=>$e(null),[]),je=h.useRef(void 0),[Ce,ze]=h.useState(()=>{const q=new Set;return c&&q.add(c),q}),ht=h.useCallback(()=>{g(AN),W("providers"),V(!0),K(!1),ve()},[g,W,V,K,ve]),[xe,re]=h.useState(""),me=h.useRef(!1),fe=h.useRef(null),Se=h.useRef(void 0),_e=h.useRef(null),[Ee,ye]=h.useState(new Map),[ie,ee]=h.useState(new Set),[oe,he]=h.useState(0);h.useEffect(()=>{Ie==="model"&&(Ze.getState().ensureModelMetadata(),ze(()=>{const q=new Set;return c&&q.add(c),q}))},[Ie,c]),h.useEffect(()=>{Ie===null&&be(null)},[Ie]),h.useEffect(()=>{Ie!=="model"&&(We(""),be(null),ye(new Map),ee(new Set))},[Ie]);const Le=h.useRef(D);h.useEffect(()=>{const q=Le.current;Le.current=D,D&&Ze.getState().ensureModelMetadata(),D||(re(""),me.current=!1,fe.current=null,ye(new Map),ee(new Set),q&&!Y&&requestAnimationFrame(fo))},[D,Y]);const Ue=z?"mobile":"default",dt=Ue==="mobile"?"h-9":"h-7",Lt="size-3.5",zt="typography-micro",ws=Ue==="mobile"?"gap-x-1":"gap-x-3",Ta=v(),Aa=Array.isArray(Ta?.models)?Ta.models:[],Kd=h.useMemo(()=>{const q=[];for(const ge of a){const He=(Array.isArray(ge.models)?ge.models:[]).filter(rt=>{const nt=typeof rt?.id=="string"?rt.id:"";return!B.some(ot=>ot.providerID===String(ge.id)&&ot.modelID===nt)});He.length>0&&q.push({...ge,models:He})}return q},[a,B]),En=h.useCallback(q=>{const ge=q.toLowerCase().trim(),Re=ge.replace(/[^a-z0-9]/g,""),He=ge.split(/[^a-z0-9]+/).filter(Boolean);return{lower:ge,compact:Re,tokens:He}},[]),Kt=h.useCallback((q,ge)=>{const Re=En(ge);if(!Re.lower)return!0;const He=En(q);return He.lower.includes(Re.lower)||Re.compact.length>=2&&He.compact.includes(Re.compact)?!0:Re.tokens.length===0?!1:Re.tokens.every(rt=>He.tokens.some(nt=>nt.startsWith(rt)||nt.includes(rt)))},[En]),Do=d?Aa.find(q=>q.id===d):void 0,Nt=c&&d&&Do?Im(c,Do,x(c,d)):c&&d?x(c,d):void 0,on=h.useCallback(q=>q==="Tool calling"?"Tool calling":q==="Reasoning"?"Reasoning":q==="Text"?"Text":q==="Image"?"Image":q==="Video"?"Video":q==="Audio"?"Audio":q==="PDF"?"PDF":q,[]),Oo=h.useMemo(()=>nb(Nt).map(q=>({...q,label:on(q.label)})),[Nt,on]),Ho=h.useMemo(()=>$c(Nt,"input").map(q=>({...q,label:on(q.label)})),[Nt,on]),Fo=h.useMemo(()=>$c(Nt,"output").map(q=>({...q,label:on(q.label)})),[Nt,on]),Ss=S().filter(Pt),La=Ss.length>0,Dr=[{label:"Input",value:Ml(Nt?.cost?.input)},{label:"Output",value:Ml(Nt?.cost?.output)},{label:"Cache read",value:Ml(Nt?.cost?.cache_read)},{label:"Cache write",value:Ml(Nt?.cost?.cache_write)}],jn=[{label:"Context",value:ha(Nt?.limit?.context)},{label:"Output",value:ha(Nt?.limit?.output)}],mn=h.useRef(null),Cs=h.useRef(null);w&&I(w);const ks=zx(w??""),Vt=qe(q=>{if(!w)return null;const ge=q.reducer.bySession.get(w);return ge?{model:ge.model,thinking:ge.thinking}:null},(q,ge)=>q===ge?!0:!q||!ge?!1:q.model?.providerId===ge.model?.providerId&&q.model?.modelId===ge.model?.modelId&&q.thinking===ge.thinking,w?`session:${w}`:"*"),Ms=h.useCallback((q,ge)=>{if(!q||!ge)return"model-missing";const Re=a.find(Je=>Je.id===q);if(!Re)return"provider-missing";const rt=(Array.isArray(Re.models)?Re.models:[]).find(Je=>Je.id===ge);if(!rt)return"model-missing";if(c===q&&d===ge)return"applied";m(q),b(ge);const Oe=tl({providerId:q,modelId:ge,thinkingLevels:rt.thinkingLevels,reasoning:rt.reasoning,supportsThinking:rt.supportsThinking,defaultThinkingByModel:p,defaultThinking:u,previousThinking:f});return y(Oe),w&&M(w,q,ge),"applied"},[a,c,d,f,m,b,y,w,M,u,p]),Ot=h.useCallback((q,ge)=>{const Re=a.find(rt=>rt.id===q),He=(Array.isArray(Re?.models)?Re.models:[]).find(rt=>rt.id===ge);return Ap(He)},[a]),Or=h.useCallback((q,ge,Re)=>{if(!q||!ge)return"model-missing";const He=a.find(ot=>ot.id===q);if(!He)return"provider-missing";if(!(Array.isArray(He.models)?He.models:[]).some(ot=>ot.id===ge))return"model-missing";c!==q&&m(q),(c!==q||d!==ge)&&b(ge),w&&M(w,q,ge);const nt=Ot(q,ge);return y(Re&&nt.includes(Re)?Re:void 0),Cs.current={...q?{providerId:q}:{},...ge?{modelId:ge}:{},...Re?{thinking:Re}:{}},"applied"},[d,c,w,Ot,a,M,y,b,m]),Na=h.useCallback((q,ge)=>{const Re=Ot(q,ge);if(Re.length!==0){if(c===q&&d===ge&&Pt(f)&&Re.includes(f))return f;if(!w){const He=a.find(nt=>nt.id===q),rt=(Array.isArray(He?.models)?He.models:[]).find(nt=>nt.id===ge);return tl({providerId:q,modelId:ge,thinkingLevels:rt?.thinkingLevels,reasoning:rt?.reasoning,supportsThinking:rt?.supportsThinking,defaultThinkingByModel:p,defaultThinking:u})}}},[d,c,w,f,Ot,a,u,p]),Is=h.useCallback((q,ge,Re)=>{const He=Ot(q,ge);if(He.length===0){te.current=!1,Ci(void 0);return}const rt=Pt(Re)&&He.includes(Re)?Re:void 0;te.current=!0,Ci(rt),N(q,ge,Re)},[N,Ot]),Ra=h.useCallback((q,ge,Re)=>{const He=Ms(q,ge);return He!=="applied"?He:(O(q,ge),Is(q,ge,Re),"applied")},[O,Is,Ms]);h.useEffect(()=>{if(!w){mn.current=null;return}if(!T||a.length===0)return;if(!ks){_.ensureSessionRenderable(w);return}if(mn.current===w)return;const q=He=>{if(He&&c&&d){const rt=Ot(c,d);y(rt.includes(He)?He:void 0);return}y(void 0)},ge=Vt?.model;if(ge){if(Or(ge.providerId,ge.modelId,Vt?.thinking)==="provider-missing")return;mn.current=w;return}if(Vt?.thinking){q(Vt.thinking),mn.current=w;return}const Re=E(w);Re&&Or(Re.providerId,Re.modelId,Vt?.thinking)==="provider-missing"||(mn.current=w)},[Or,T,d,c,w,Vt,Ot,E,ks,a.length,y,_]),h.useEffect(()=>{if(!w||!T||a.length===0||!ks||mn.current!==w)return;const q=Vt?.model,ge=Vt?.thinking??void 0;if(!q?.providerId||!q?.modelId){Cs.current=null;return}const Re=yN({authoritative:{providerId:q.providerId,modelId:q.modelId,thinking:ge},observed:Cs.current,composer:{providerId:c,modelId:d,thinking:tn(f)??void 0}});if(Re!=="ignore"){if(Re==="apply"){Or(q.providerId,q.modelId,ge);return}Cs.current={providerId:q.providerId,modelId:q.modelId,...ge?{thinking:ge}:{}}}},[Or,T,d,c,w,f,Vt,ks,a.length]),h.useEffect(()=>{if(!T){te.current=!1,y(void 0);return}if(!c||!d){te.current=!1,y(void 0);return}const q=a.find(He=>He.id===c),ge=(Array.isArray(q?.models)?q.models:[]).find(He=>He.id===d),Re=Tp(ge);if(!fd(Re)){f&&Pt(f)&&y(void 0);return}if(!w&&!f&&!te.current){const He=tl({providerId:c,modelId:d,thinkingLevels:ge?.thinkingLevels,reasoning:ge?.reasoning,supportsThinking:ge?.supportsThinking,defaultThinkingByModel:p,defaultThinking:u});He&&y(He);return}if(f&&Pt(f)&&!Re.includes(f)){y(tl({providerId:c,modelId:d,thinkingLevels:ge?.thinkingLevels,reasoning:ge?.reasoning,supportsThinking:ge?.supportsThinking,defaultThinkingByModel:p,defaultThinking:u,previousThinking:f}));return}if(w&&!f&&!te.current){const He=tn(Vt?.thinking);He&&Re.includes(He)&&y(He)}},[T,w,c,d,f,Vt,a,y,u,p]),h.useEffect(()=>{te.current=!1},[c,d]);const Vo=h.useCallback(q=>{c&&d&&Is(c,d,q)},[Is,d,c]),ar=h.useCallback(q=>{if(!c||!d)return;const ge=Ot(c,d);if(ge.length===0){te.current=!1,Ci(void 0);return}const Re=Pt(q)&&ge.includes(q)?q:void 0;te.current=!0,Ci(Re)},[c,d,Ot]),gn=h.useCallback(q=>{q!==f&&ar(q),c&&d&&N(c,d,q)},[ar,c,d,f,N]),Yd=(q,ge,Re)=>{try{const He=Re?.applyVariant?Ra(q,ge,Re.variant):Ms(q,ge);if(He!=="applied"){He==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",q):He==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:q,modelId:ge});return}Re?.applyVariant||O(q,ge),K(!1),Y&&ve(),requestAnimationFrame(fo)}catch(He){console.error("[ModelControls] Handle model change error:",He)}},Hr=(q,ge)=>_m(q,ge,{maxLength:40}),$n=()=>a.find(ge=>ge.id===c)?.name||c||"",Bo=()=>{if(!d)return"Select model";const q=Aa.find(ge=>ge.id===d);return Hr(q,d)||"Select model"},lr=h.useCallback((q,ge)=>!z||q.length<=ge?q:`${q.slice(0,ge)}...`,[z])(Bo(),16),$o=h.useRef(null),zo=uN($o,[lr,Y]),Pa=h.useCallback(q=>{ze(ge=>{const Re=new Set(ge);return Re.has(q)?Re.delete(q):Re.add(q),Re})},[]),Da=h.useCallback(q=>{je.current&&clearTimeout(je.current),je.current=setTimeout(()=>{$e(q)},500)},[]),Uo=h.useCallback(()=>{je.current&&clearTimeout(je.current)},[]);h.useEffect(()=>()=>{je.current&&clearTimeout(je.current)},[]);const Oa=()=>!Y||Fe!=="model"?null:l.jsx(IN,{open:!0,onClose:we,title:Nt?.name||Bo(),providerDisplayName:$n(),currentCapabilityIcons:Oo,inputModalityIcons:Ho,outputModalityIcons:Fo,currentMetadata:Nt}),Ha=()=>{if(!Y)return null;const q=Xe.trim(),ge=Z.filter(({model:nt,providerID:ot})=>{const Je=a.find(Rt=>Rt.id===ot)?.name||ot,Ct=Hr(nt);return q.length===0||Kt(String(Ct||""),q)||Kt(String(Je||""),q)}),Re=L.filter(({model:nt,providerID:ot})=>{const Je=a.find(Rt=>Rt.id===ot)?.name||ot,Ct=Hr(nt);return q.length===0||Kt(String(Ct||""),q)||Kt(String(Je||""),q)}),He=[];for(const nt of Kd){const ot=Array.isArray(nt.models)?nt.models:[],Oe=q.length===0?!0:Kt(String(nt.name||""),q)||Kt(String(nt.id||""),q),Je=q.length===0?ot:ot.filter(Rt=>{const an=Hr(Rt),An=typeof Rt.id=="string"?Rt.id:"";return Kt(String(an||""),q)||Kt(String(An||""),q)}),Ct=Oe&&q.length>0?ot:Je;(Oe||Ct.length>0)&&He.push({provider:nt,providerModels:Ct,matchesProvider:Oe})}const rt=(nt,ot,Oe)=>{const Je=Ra(nt,ot,Oe);if(Je!=="applied"){Je==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",nt):Je==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:nt,modelId:ot});return}be(null),ve(),requestAnimationFrame(fo)};return l.jsx(TN,{open:Ie==="model",onClose:ve,mobileModelQuery:Xe,onMobileModelQueryChange:We,filteredFavorites:ge,filteredRecents:Re,filteredProviders:He,expandedMobileProviders:Ce,onToggleMobileProviderExpansion:Pa,expandedMobileModelKey:Ae,onToggleExpandedMobileModelKey:be,currentProviderId:c,currentModelId:d,getModelDisplayName:Hr,getModelMetadata:x,getModelVariantOptions:Ot,resolveModelVariantSelection:Na,pendingThinkingVariants:Ee,onUpdatePendingThinkingVariant:(nt,ot)=>{ye(Oe=>{const Je=new Map(Oe);return Je.set(nt,ot),Je}),ee(Oe=>{const Je=new Set(Oe);return Je.add(nt),Je}),he(Oe=>Oe+1)},isFavoriteModel:R,onToggleFavoriteModel:A,onApplyModel:rt})},Fa=()=>{if(!Y||!c||!d)return null;const q=Ot(c,d);return l.jsx(_N,{open:Ie==="variant",onClose:ve,targetVariants:q,selectedVariant:f,onVariantLiveChange:ar,onVariantCommit:gn})},Xd=()=>l.jsx(MN,{currentMetadata:Nt,modelDisplayName:Bo(),providerDisplayName:$n(),currentCapabilityIcons:Oo,inputModalityIcons:Ho,outputModalityIcons:Fo,costRows:Dr,limitRows:jn}),qo=()=>{const q=(Oe,Je)=>{if(me.current=!0,Oe.key!=="ArrowLeft"&&Oe.key!=="ArrowRight")return!1;const{providerID:Ct,modelID:Rt}=Je,an=Ot(Ct,Rt);if(an.length===0)return!1;Oe.preventDefault(),Oe.stopPropagation();const An=kf(Ct,Rt),Es=Ee.has(An),js=Ee.get(An),Ts=Es?js:c===Ct&&d===Rt?f:void 0,Zo=Lp(an,Pt(Ts)?Ts:void 0,Oe.key==="ArrowRight"?1:-1);return ye(Fr=>{const As=new Map(Fr);return As.set(An,Zo),As}),ee(Fr=>{const As=new Set(Fr);return As.add(An),As}),he(Fr=>Fr+1),!0},ge=(Oe,Je)=>{Je&&q(Oe,Je)},Re=Oe=>{const Je=kf(Oe.providerID,Oe.modelID),Ct=Ee.get(Je),Rt=ie.has(Je);Yd(Oe.providerID,Oe.modelID,Rt?{applyVariant:!0,variant:Ct}:void 0)},He=Oe=>{_e.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}},rt=(Oe,Je)=>{if(!Oe){const Ct=document.activeElement;console.info("[DEBUG-model-picker-close]",{reason:Je.reason??"unknown",eventType:Je.event?.type??"none",draftOpen:C,focusInsidePicker:Ct instanceof Element&&!!Ct.closest('[data-model-picker-popup="true"]'),precedingKey:_e.current})}K(Oe)},nt={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)"},ot=(Oe,{isHighlighted:Je,isSelected:Ct})=>{const Rt=Ot(Oe.providerID,Oe.modelID).length>0,an=kf(Oe.providerID,Oe.modelID),An=ie.has(an);if(!Rt||!Je&&!Ct)return null;const Es=Ee.has(an),js=Ee.get(an),Ts=Es?js:Ct?f:void 0,Zo=Tr(Pt(Ts)?Ts:void 0);return l.jsxs("span",{className:P("typography-micro whitespace-nowrap",An?"text-foreground":"text-muted-foreground"),children:["Thinking: ",Zo]})};return l.jsxs(pt,{delayDuration:600,children:[Y?l.jsx("button",{type:"button",onClick:s?()=>de("model"):void 0,onTouchStart:s?()=>Da("model"):void 0,onTouchEnd:s?Uo:void 0,onTouchCancel:s?Uo:void 0,disabled:!s,className:P("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",dt),children:s?l.jsxs(l.Fragment,{children:[c?l.jsx(Eo,{providerId:c,className:P(Lt,"flex-shrink-0")}):l.jsx(F,{name:"pencil-ai",className:P(Lt,"text-muted-foreground")}),l.jsx("span",{ref:$o,className:P("model-controls__model-label typography-micro font-normal overflow-hidden",t?"whitespace-nowrap":"min-w-0",!t&&(z?"max-w-[120px]":"max-w-[220px]")),children:l.jsx("span",{className:P("marquee-text",zo&&"marquee-text--active"),children:lr})}),l.jsx(F,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"})]}):l.jsxs(l.Fragment,{children:[l.jsx(F,{name:"loader-4",className:P(Lt,"animate-spin text-muted-foreground flex-shrink-0")}),l.jsx("span",{className:"typography-micro font-normal text-muted-foreground min-w-0",children:i})]})}):l.jsxs(Pd,{open:s&&D,onOpenChange:s?rt:void 0,children:[l.jsx(mt,{asChild:!0,children:l.jsx(Dd,{asChild:!0,children:l.jsxs("button",{type:"button",className:P("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",dt),children:[s?c?l.jsxs(l.Fragment,{children:[l.jsx(Eo,{providerId:c,className:P(Lt,"flex-shrink-0")}),l.jsx(F,{name:"pencil-ai",className:P(Lt,"text-primary/60 hidden")})]}):l.jsx(F,{name:"pencil-ai",className:P(Lt,"text-muted-foreground")}):l.jsxs(l.Fragment,{children:[l.jsx(F,{name:"loader-4",className:P(Lt,"animate-spin text-muted-foreground flex-shrink-0")}),l.jsx("span",{className:P("model-controls__model-label",zt,"font-normal whitespace-nowrap text-muted-foreground min-w-0"),children:i})]}),s&&l.jsx("span",{ref:$o,className:P("model-controls__model-label overflow-hidden",zt,"font-normal whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:l.jsx("span",{className:P("marquee-text",zo&&"marquee-text--active"),children:lr})},`${c}-${d}`),s?l.jsx(F,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"}):null]})})}),l.jsxs(Od,{"data-model-picker-popup":"true",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,onKeyDownCapture:He,children:[l.jsx("div",{className:"p-1 border-b border-border/40",children:l.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:[l.jsx("span",{className:"flex size-4 items-center justify-center text-muted-foreground",children:l.jsx(F,{name:"add",className:"size-4 -mr-0.5"})}),l.jsx("span",{className:"font-medium text-foreground",children:"Add new provider"})]})}),l.jsx(lN,{providers:a,favoriteModels:Z,recentModels:L,modelsMetadata:Ze.getState().modelsMetadata,searchQuery:xe,onSearchQueryChange:re,onSelect:Re,labels:nt,selectedModel:c&&d?{providerID:c,modelID:d}:null,hiddenModels:B,onActiveKeyDown:ge,onActiveEntryChange:Oe=>{Se.current=Oe},onVariantKey:q,isFavorite:Oe=>R(Oe.providerID,Oe.modelID),onToggleFavorite:Oe=>A(Oe.providerID,Oe.modelID),renderRowEnd:ot,renderVersion:oe,onReorderFavorite:(Oe,Je)=>j(Oe.providerID,Oe.modelID,Je.providerID,Je.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",tooltipsEnabled:D,onEscape:()=>K(!1)})]})]}),Xd()]})},Jd=()=>!s||!La?null:l.jsx(mN,{levels:Ss,value:tn(f)??void 0,onChange:Vo,compact:Y,keepLabel:t,onCompactOpen:()=>de("variant"),buttonHeight:dt,iconSize:Lt,textSize:zt,isMobile:z,isDesktop:X}),Tn=P(!t&&"@container/model-controls","flex items-center",t?"w-max shrink-0":"min-w-0",z&&!t&&"w-full",e);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:Tn,children:l.jsxs("div",{className:P("flex items-center justify-start",ws,t?"w-max shrink-0":"min-w-0",z&&!t&&"overflow-hidden"),children:[qo(),Jd()]})}),Ha(),Fa(),Oa()]})},NN=1e9,RN=1e12,Mf="thinking",PN=e=>e>=RN?e:e>=NN?e*1e3:Date.now()+e,DN=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 ob({isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:s,modelName:o,providerId:i,startedAt:a=null}){const{src:c,onError:d,hasLogo:f}=Mm(i??null),{currentTheme:u}=Vn(),p=u?.metadata.variant==="dark",m=h.useRef(null),[g,b]=h.useState(null);if(h.useEffect(()=>{const C=s?.next;if(!C||C<=0){b(null);return}const I=PN(C),_=()=>{const M=Math.max(0,I-Date.now());b(Math.ceil(M/1e3))};_();const E=setInterval(_,500);return()=>clearInterval(E)},[s?.next,s?.attempt]),!e)return m.current=null,null;if(s){m.current=null;const C=s.attempt&&s.attempt>1?` (attempt ${s.attempt})`:"",_=`Retrying${g!==null&&g>0?` in ${DN(g)}`:""}${C}`;return l.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":"polite","aria-label":`${_}...`,"data-agent-thinking-row":"true",children:l.jsx(J2,{text:_,variant:"inline",showElapsed:!1,className:"min-w-0"})})}const y=r?"waiting for permission":t,S=!!r,v=!!n&&!S;m.current===null?m.current={text:v?Mf:y??Mf,permission:S}:y&&(!v||S)?m.current={text:y,permission:S}:v&&m.current.permission&&(m.current={text:Mf,permission:!1});const x=m.current;if(!x)return null;const k=typeof o=="string"?o.trim():"",w=k.length>0?`${k} is ${x.text}`:x.text.charAt(0).toUpperCase()+x.text.slice(1);return l.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":x.permission?"assertive":"polite","aria-label":w,"data-agent-thinking-row":"true","data-waiting":x.permission?"true":void 0,children:l.jsxs("span",{className:"typography-markdown inline-flex min-w-0 items-center gap-1.5 leading-5",children:[f&&c?l.jsx("img",{src:c,alt:"","aria-hidden":"true",className:"inline-block h-3.5 w-3.5 mr-0.5 align-[-2px]",style:{filter:p?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:d}):null,l.jsx(J2,{text:w,variant:"inline",animationType:"spinner",animateText:!0,startedAt:a,className:"min-w-0"})]})})}const ON={containerType:"inline-size",containerName:"status-row"},k0={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},M0={high:"text-[var(--status-warning)]",medium:"text-muted-foreground",low:"text-muted-foreground/70"},I0={high:l.jsx(F,{name:"arrow-up-double",className:"h-3.5 w-3.5","aria-hidden":"true"}),medium:l.jsx(F,{name:"arrow-up-s",className:"h-3.5 w-3.5","aria-hidden":"true"}),low:l.jsx(F,{name:"arrow-down-s",className:"h-3.5 w-3.5","aria-hidden":"true"})},_0={in_progress:"In progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},E0={high:"High priority",medium:"Medium priority",low:"Low priority"},HN=({todo:e})=>{const t=String(e.status||"pending"),n=String(e.priority||"medium"),r=k0[t]||k0.pending,s=_0[t]??_0.pending,o=E0[n]??E0.medium,i=t==="in_progress"?l.jsx(F,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]","aria-hidden":"true"}):t==="completed"?l.jsx(F,{name:"checkbox-circle",className:"h-3.5 w-3.5 text-[var(--status-success)]","aria-hidden":"true"}):l.jsx(F,{name:"time",className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":"true"});return l.jsxs("div",{className:"flex items-center min-w-0 py-0.5 gap-2",children:[l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx("span",{className:"flex-shrink-0",children:i})}),l.jsx(gt,{side:"left",sideOffset:6,children:s})]}),l.jsx("span",{className:P("flex-1 typography-ui-label",r.textClassName),children:e.content}),l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx("span",{className:P("typography-meta flex items-center justify-center flex-shrink-0 leading-none",M0[n]??M0.medium),children:I0[n]??I0.medium})}),l.jsx(gt,{side:"right",sideOffset:6,children:o})]})]})},FN=[],ib=({isWorking:e=!1,statusText:t=null,isGenericStatus:n,isWaitingForPermission:r,wasAborted:s,abortActive:o,retryInfo:i,showAbort:a,onAbort:c,showAbortStatus:d,showAssistantStatus:f=!0,showTodos:u=!0,agentName:p,modelName:m,providerId:g,leftAccessory:b,turnStartedAt:y=null})=>{const[S,v]=h.useState(!1),x=pe(L=>L.currentSessionId),k=FN,w=ne(L=>L.isMobile),{enabled:C}=jd(),I=w&&!C,_=I,E=h.useMemo(()=>k.filter(L=>L.status!=="cancelled"),[k]),M=h.useMemo(()=>E.find(L=>L.status==="in_progress")||E.find(L=>L.status==="pending")||null,[E]),T=h.useMemo(()=>{const L=k.filter(G=>G.status!=="cancelled").length;return{completed:k.filter(G=>G.status==="completed").length,total:L}},[k]),A=h.useMemo(()=>{const L=E.filter(G=>G.status==="in_progress").length,$=E.filter(G=>G.status==="in_progress"||G.status==="pending").length;return{active:L,left:$}},[E]),j=u&&A.left>0,R=f&&(e||!!s||!!d),O=!!b,N=!d&&(s||!o),D=R||j||O,K=h.useRef(null);h.useEffect(()=>{if(!S)return;const L=$=>{K.current&&!K.current.contains($.target)&&v(!1)};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[S]);const V=()=>v(L=>!L),W=`${A.active} active · ${A.left} left`,B=a&&c?l.jsx("button",{type:"button",onClick:c,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:l.jsx(F,{name:"close-circle","aria-hidden":"true"})}):null,Z=j?l.jsxs("button",{type:"button",onClick:V,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground","aria-label":W,title:W,children:[!_&&M?l.jsx("span",{className:"status-row__active-todo typography-ui-label text-foreground truncate max-w-[200px]",children:M.content}):l.jsx("span",{className:"typography-ui-label",children:"Tasks"}),l.jsxs("span",{className:"typography-meta flex items-center gap-1 tabular-nums","aria-hidden":"true",children:[l.jsxs("span",{className:"flex items-center gap-0.5",children:[l.jsx(F,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]"}),A.active]}),l.jsx("span",{children:"·"}),l.jsxs("span",{className:"flex items-center gap-0.5",children:[l.jsx(F,{name:"time",className:"h-3.5 w-3.5"}),A.left]})]}),S?l.jsx(F,{name:"arrow-up-s",className:"h-3.5 w-3.5"}):l.jsx(F,{name:"arrow-down-s",className:"h-3.5 w-3.5"})]}):null;return D?l.jsx("div",{className:P("mb-1",I&&"mt-2",!O&&"chat-column"),style:ON,children:l.jsxs("div",{className:P("flex min-h-5 items-center justify-between gap-2 py-0.5",O&&"px-0.5"),children:[l.jsx("div",{className:P("flex min-w-0 flex-1 items-center gap-2",O?"pl-1.5":"overflow-x-hidden"),children:f&&d?l.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-0.5",children:l.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[l.jsx(F,{name:"close-circle","aria-hidden":"true"}),"Aborted"]})}):f&&N?l.jsx(ob,{isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:i,agentName:p,modelName:m,providerId:g,startedAt:y},`${x??"no-session"}:${y??"no-start"}`):b||null}),l.jsxs("div",{className:P("relative flex items-center gap-2 flex-shrink-0",O?"pr-1.5":"-mr-3"),ref:K,children:[B,Z,S&&j&&l.jsxs("div",{style:{maxWidth:"min(28rem, calc(100cqw - 4ch))",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:P("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:[l.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[l.jsx("span",{children:"Tasks"}),l.jsxs("span",{className:"typography-meta tabular-nums",children:[T.completed,"/",T.total]})]}),l.jsx("div",{className:"px-1 max-h-[200px] overflow-y-auto",children:E.map((L,$)=>l.jsx(HN,{todo:L},L.id??`todo-${$}`))})]})]})]})}):null},VN=1e4,BN=6e4,$N=5e3,zN=15e3,UN=3e4,qN=6e4,j0=5*6e4,ZN=3e4,WN=10,T0=25,GN=40,KN=2,A0=15e3,YN=500,XN=30,zc=20*1024*1024,L0=200,N0=e=>JSON.stringify({from:e.from??null,to:e.to??null,all:e.all??!1,file:e.file??null,maxCount:e.maxCount??null}),Mt=()=>({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}),R0="oc.gitBranchCache",dc="oc.gitBranchCache.v2",JN=8,QN=50,If=()=>({version:2,legacyClaimed:!1,runtimes:{}}),ab=e=>{try{const t=$t(),n=t.getItem(dc),r=n?JSON.parse(n):If(),s=r?.version===2&&r.runtimes&&typeof r.runtimes=="object"?{version:2,legacyClaimed:!!r.legacyClaimed,runtimes:r.runtimes}:If();if(!s.legacyClaimed){const o=t.getItem(R0);if(o){const a=JSON.parse(o),c={};for(const[d,f]of Object.entries(a??{}))d&&f&&Array.isArray(f.all)&&(c[d]={branches:f,updatedAt:0});Object.keys(c).length>0&&(s.runtimes[e]={updatedAt:0,directories:c})}s.legacyClaimed=!0;const i=JSON.stringify(s);t.setItem(dc,i),t.getItem(dc)===i&&t.removeItem(R0)}return s}catch{return If()}},eR=(e,t,n)=>{if(!(!t||!n))try{const r=ab(e),s=Date.now(),i={...r.runtimes[e]?.directories??{},[t]:{branches:n,updatedAt:s}},a=Object.fromEntries(Object.entries(i).sort(([,c],[,d])=>d.updatedAt-c.updatedAt).slice(0,QN));r.runtimes[e]={updatedAt:s,directories:a},r.runtimes=Object.fromEntries(Object.entries(r.runtimes).sort(([,c],[,d])=>d.updatedAt-c.updatedAt).slice(0,JN)),$t().setItem(dc,JSON.stringify(r))}catch{}},P0=e=>{const t=new Map,n=ab(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,{...Mt(),isGitRepo:!0,branches:o})}return t},lb=e=>{const t=new TextEncoder;return t.encode(e.original??"").byteLength+t.encode(e.modified??"").byteLength},D0=(e,t=XN,n=zc)=>{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,c)=>a[1].fetchedAt-c[1].fetchedAt),o=new Map;let i=0;for(let a=s.length-1;a>=0;a--){const[c,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(c,d),i+=f)}return o},O0=e=>{const t=[];let n=0;for(const[o,i]of e)for(const[a,c]of i.diffCache){const d=lb(c);t.push({directory:o,path:a,fetchedAt:c.fetchedAt,size:d}),n+=d}if(t.length<=L0&&n<=zc)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<=L0&&n<=zc)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},tR=(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},nR=(e,t)=>!e&&!t?!1:!e||!t?!0:e.remote!==t.remote||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind,rR=(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&&nR(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&&tR(e.diffStats,t.diffStats))},sR=(e,t)=>{const n=new Set;if(!t)return n;const r=e?.files??[],s=t.files??[],o=new Map(r.map(c=>[c.path,c])),i=new Map(s.map(c=>[c.path,c])),a=new Set([...o.keys(),...i.keys()]);for(const c of a){const d=o.get(c),f=i.get(c);if(!d||!f){n.add(c);continue}if(d.index!==f.index||d.working_dir!==f.working_dir){n.add(c);continue}}if(t.diffStats!==void 0){const c=e?.diffStats??{},d=t.diffStats??{},f=new Set([...Object.keys(c),...Object.keys(d)]);for(const u of f){const p=c[u],m=d[u];if(!p||!m){n.add(u);continue}(p.insertions!==m.insertions||p.deletions!==m.deletions)&&n.add(u)}}return n},oR=(e,t)=>{if(!e&&!t)return!1;if(!e||!t)return!0;const n=e.files??[],r=t.files??[],s=c=>{const d=c?.trim()??"";return d==="?"?"":d},o=new Map(n.map(c=>[c.path,s(c.index)])),i=new Map(r.map(c=>[c.path,s(c.index)])),a=new Set([...o.keys(),...i.keys()]);for(const c of a)if((o.get(c)??"")!==(i.get(c)??""))return!0;return!1},H0=e=>!e||e.trim().length===0,Uc=e=>(e||"").trim()==="U",iR=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Uc(t)||Uc(n)?e:{...e,index:t==="?"||n==="?"?"A":t||n||" ",working_dir:" "}},aR=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Uc(t)||Uc(n)?e:{...e,index:" ",working_dir:n||(t==="A"||t==="?"?"?":t)||" "}},lR=e=>H0(e.index)&&H0(e.working_dir),qh=new Map,Am=new Map,Zs=new Map,Mi=new Map,Ii=new Map,_i=new Map,Ei=new Map,ji=new Map,qc=new Map,pa=new Map;let Lm=0,Nm=J();const cR=()=>Nm,dR=e=>{Lm+=1,Nm=e,qc.clear(),pa.clear(),Zs.clear(),Mi.clear(),Ii.clear(),_i.clear(),Ei.clear(),ji.clear(),qh.clear(),Am.clear()},nr=(e,t)=>JSON.stringify([e,t]),F0=(e,t,n)=>JSON.stringify([e,t,n]),uR=(e,t,n)=>JSON.stringify([e,t,n]),fR=(e,t,n)=>JSON.stringify([e,t,n]),hR=(e,t,n)=>JSON.stringify([e,t,n]),Zr=(e,t,n=!1)=>{const r=J(),s=hR(r,e,t),o=(qc.get(s)??0)+1;return qc.set(s,o),{runtimeKey:r,runtimeGeneration:Lm,channelKey:s,requestGeneration:o,...n?{statusMutationRevision:pa.get(nr(r,e))??0}:{}}},dn=(e,t)=>e.runtimeKey===J()&&e.runtimeKey===Nm&&e.runtimeGeneration===Lm&&qc.get(e.channelKey)===e.requestGeneration&&(e.statusMutationRevision===void 0||e.statusMutationRevision===(pa.get(nr(e.runtimeKey,t))??0)),_f=(e,t)=>{const n=nr(e,t);pa.set(n,(pa.get(n)??0)+1)},uc=e=>Am.get(nr(J(),e))??0,Il=e=>{const t=uc(e)+1;return Am.set(nr(J(),e),t),t},pR=e=>{const t=nr(J(),e),n=qh.get(t);if(n)return n;const r=new Set;return qh.set(t,r),r},V0=cR(),yt=Et()(or((e,t)=>({runtimeKey:V0,directories:P0(V0),activeDirectory:null,resetForRuntimeSwitch:n=>{dR(n),e({runtimeKey:n,directories:P0(n),activeDirectory:null})},setActiveDirectory:n=>{const{activeDirectory:r,directories:s}=t();if(r!==n)if(r&&Il(r),n&&Il(n),n&&!s.has(n)){const o=new Map(s);o.set(n,Mt()),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=J(),a=F0(i,n,o),c=Zs.get(a)??(o==="light"?Zs.get(F0(i,n,"full")):void 0);if(c)return c;const d=Zr(n,"status",!0),f=(async()=>{const{silent:u=!1}=s,{directories:p}=t();let m=p.get(n);if(m||(m=Mt()),!u){const b=new Map(t().directories),y=b.get(n)??Mt();b.set(n,{...y,isLoadingStatus:!0}),e({directories:b})}let g=!1;try{const b=Date.now(),y=m.isGitRepo!==!0||b-(m.lastRepoCheckAt||0)>BN;let S=m.isGitRepo===!0;if(y&&(S=await r.checkIsGitRepository(n),!dn(d,n)))return!1;if(!S){const k=new Map(t().directories),w=k.get(n)??m;return k.set(n,{...w,isGitRepo:!1,status:null,isLoadingStatus:!1,lastRepoCheckAt:b,lastStatusFetch:b}),e({directories:k}),!1}const v=await r.getGitStatus(n,s.mode?{mode:s.mode}:void 0);if(!dn(d,n))return!1;const x=t().directories.get(n)??Mt();if(rR(x.status,v)){g=!0;const k=new Map(t().directories),w=k.get(n)??Mt(),C=sR(w.status,v),I=oR(w.status,v),_=new Set((w.status?.files??[]).map(j=>j.path)),E=new Set((v.files??[]).map(j=>j.path)),M=new Map(w.diffCache);for(const j of _)E.has(j)||M.delete(j);for(const j of C)M.delete(j);const T=C.size>0;T&&Il(n);const A={...v,diffStats:v.diffStats===void 0&&w.status?.diffStats!==void 0?w.status.diffStats:v.diffStats,upstreamComparison:v.upstreamComparison===void 0?w.status?.upstreamComparison:v.upstreamComparison};k.set(n,{...w,isGitRepo:!0,status:A,diffCache:M,indexRevision:I?w.indexRevision+1:w.indexRevision,lastRepoCheckAt:y?b:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:T?Date.now():w.lastStatusChange}),e({directories:k})}else{const k=new Map(t().directories),w=k.get(n)??Mt();k.set(n,{...w,isGitRepo:!0,lastRepoCheckAt:y?b:w.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:w.lastStatusChange}),e({directories:k})}}catch(b){console.error("Failed to fetch git status:",b)}finally{if(!u&&dn(d,n)){const b=new Map(t().directories),y=b.get(n)??Mt();b.set(n,{...y,isLoadingStatus:!1}),e({directories:b})}}return g})();Zs.set(a,f);try{return await f}finally{Zs.get(a)===f&&Zs.delete(a)}},moveStatusPathsOptimistically:(n,r,s)=>{const o=new Set(r.map(p=>p.trim()).filter(Boolean));if(o.size===0)return null;const{directories:i}=t(),a=i.get(n),c=a?.status??null;if(!a||!c)return c;let d=!1;const f=[];for(const p of c.files){if(!o.has(p.path)){f.push(p);continue}const m=s==="stage"?iR(p):aR(p);m!==p&&(d=!0),lR(m)?d=!0:f.push(m)}if(!d)return c;_f(t().runtimeKey,n);const u=new Map(i);return u.set(n,{...a,status:{...c,files:f,isClean:f.length===0},indexRevision:a.indexRevision+1,lastStatusChange:Date.now()}),e({directories:u}),c},restoreStatus:(n,r)=>{const{directories:s}=t(),o=s.get(n);if(!o)return;_f(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;_f(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=J(),i=nr(o,n),a=Mi.get(i);if(a)return a;const c=Zr(n,"branches"),{silent:d=!1}=s,f=(async()=>{if(!d){const u=new Map(t().directories),p=u.get(n)??Mt();u.set(n,{...p,isLoadingBranches:!0}),e({directories:u})}try{const u=await r.getGitBranches(n);if(!dn(c,n))return;const p=new Map(t().directories),m=p.get(n)??Mt();p.set(n,{...m,branches:u,isLoadingBranches:!1,lastBranchesFetch:Date.now()}),e({directories:p}),eR(c.runtimeKey,n,u)}catch(u){if(console.error("Failed to fetch git branches:",u),!dn(c,n))return;const p=new Map(t().directories),m=p.get(n)??Mt();p.set(n,{...m,isLoadingBranches:!1}),e({directories:p})}})().finally(()=>{Mi.get(i)===f&&Mi.delete(i)});return Mi.set(i,f),f},fetchLog:async(n,r,s,o={})=>{const{directories:i}=t(),a=i.get(n),c=s??a?.logMaxCount??25,d=J(),f=uR(d,n,c),u=Ii.get(f);if(u)return u;const p=Zr(n,"log"),{silent:m=!1}=o,g=(async()=>{if(!m){const b=new Map(t().directories),y=b.get(n)??Mt();b.set(n,{...y,isLoadingLog:!0}),e({directories:b})}try{const b=await r.getGitLog(n,{maxCount:c});if(!dn(p,n))return;const y=new Map(t().directories),S=y.get(n)??Mt();y.set(n,{...S,log:b,isLoadingLog:!1,lastLogFetch:Date.now(),logMaxCount:c}),e({directories:y})}catch(b){if(console.error("Failed to fetch git log:",b),!dn(p,n))return;const y=new Map(t().directories),S=y.get(n)??Mt();y.set(n,{...S,isLoadingLog:!1}),e({directories:y})}})().finally(()=>{Ii.get(f)===g&&Ii.delete(f)});return Ii.set(f,g),g},fetchRemotes:async(n,r,s={})=>{const o=r.getRemotes;if(typeof o!="function")return;const i=r.getRemoteUrl,a=J(),c=nr(a,n),d=_i.get(c);if(d)return d;const f=Zr(n,"remotes"),{silent:u=!1}=s,p=(async()=>{if(!u){const m=new Map(t().directories),g=m.get(n)??Mt();m.set(n,{...g,isLoadingRemotes:!0}),e({directories:m})}try{const m=o(n),g=typeof i=="function"?i(n).then(x=>({ok:!0,value:x}),()=>({ok:!1,value:null})):Promise.resolve({ok:!0,value:null}),[b,y]=await Promise.all([m,g]);if(!dn(f,n))return;const S=new Map(t().directories),v=S.get(n)??Mt();S.set(n,{...v,remotes:b,remoteUrl:y.ok?y.value:v.remoteUrl,lastRemotesFetch:Date.now(),isLoadingRemotes:!1}),e({directories:S})}catch(m){if(console.error("Failed to fetch git remotes:",m),!dn(f,n))return;const g=new Map(t().directories),b=g.get(n)??Mt();g.set(n,{...b,isLoadingRemotes:!1}),e({directories:g})}})().finally(()=>{_i.get(c)===p&&_i.delete(c)});return _i.set(c,p),p},ensureRemotes:async(n,r)=>{const s=t().directories.get(n),o=Date.now();s?.remotes!==null&&s?.remotes!==void 0&&o-(s?.lastRemotesFetch??0)<j0||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=N0(s),c=J(),d=fR(c,n,a),f=Date.now(),u=t().directories.get(n)?.logQueryCache.get(a);if(!i&&u&&f-u.fetchedAt<ZN)return u.log;const p=Ei.get(d);if(p)return p;const m=Zr(n,`log-query:${a}`),g=(async()=>{try{const b=await r.getGitLog(n,{maxCount:s.maxCount,from:s.from,to:s.to,all:s.all,file:s.file});if(!dn(m,n))return u?.log??null;const y=new Map(t().directories),S=y.get(n)??Mt(),v=new Map(S.logQueryCache);if(v.set(a,{log:b,fetchedAt:Date.now()}),v.size>WN){let x=null,k=Number.POSITIVE_INFINITY;for(const[w,C]of v)C.fetchedAt<k&&(k=C.fetchedAt,x=w);x!==null&&v.delete(x)}return y.set(n,{...S,logQueryCache:v}),e({directories:y}),b}catch(b){return console.error("Failed to fetch git log query:",b),u?.log??t().directories.get(n)?.logQueryCache.get(a)?.log??null}})().finally(()=>{Ei.get(d)===g&&Ei.delete(d)});return Ei.set(d,g),g},getCachedLogQuery:(n,r)=>{const s=N0(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=Mt();const p=new Map(o);p.set(n,i),e({directories:p})}const{force:a=!1,silentIfCached:c=!1}=s,d=Date.now();await t().fetchStatus(n,r,{silent:c&&!!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>VN||!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||lb(s)>zc)return;const i=new Map(t().directories),a=i.get(n)??Mt(),c=new Map(a.diffCache);c.set(r,{...s,fetchedAt:Date.now()});const d=D0(c);i.set(n,{...a,diffCache:d}),e({directories:O0(i)})},clearDiffCache:(n,r)=>{Il(n),Zr(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,T0);await t().prefetchDiffs(n,r,o,{maxFiles:T0})},prefetchDiffs:async(n,r,s,o={})=>{const i=Zr(n,"diff"),a=t().directories.get(n);if(!a?.status?.files||a.status.files.length===0||s.length===0)return;const{maxFiles:c=GN}=o,d=new Set(a.status.files.map(T=>T.path)),f=a.status.diffStats,u=pR(n),p=[],m=new Set;for(const T of s){if(!T||m.has(T)||(m.add(T),!d.has(T))||a.diffCache.has(T)||u.has(T))continue;const A=f?.[T];A&&A.insertions+A.deletions>YN||p.push(T)}const g=p.slice(0,Math.max(1,c));if(g.length===0)return;const b=uc(n);if(typeof document<"u"&&document.hidden)return;g.forEach(T=>u.add(T));let y=0;const S=[],v=()=>{const T=y;return y+=1,T<g.length?g[T]:null},x=async T=>{const A=r.getGitFileDiff(n,{path:T}),j=new Promise((O,N)=>{setTimeout(()=>N(new Error(`Timed out after ${A0}ms`)),A0)}),R=await Promise.race([A,j]);return{path:T,diff:{original:R.original??"",modified:R.modified??"",isBinary:R.isBinary}}},k=async()=>{for(;;){if(b!==uc(n)||!dn(i,n))return;const T=v();if(!T)return;try{S.push(await x(T))}catch{}finally{u.delete(T)}}},w=Math.min(KN,g.length);if(await Promise.allSettled(Array.from({length:w},()=>k())),g.forEach(T=>u.delete(T)),b!==uc(n)||!dn(i,n))return;const C=new Map(t().directories),I=C.get(n);if(!I)return;const _=new Map(I.diffCache),E=Date.now();S.forEach(T=>{_.set(T.path,{...T.diff,fetchedAt:E})});const M=D0(_);C.set(n,{...I,diffCache:M}),e({directories:O0(C)})},setLogMaxCount:(n,r)=>{const s=new Map(t().directories),o=s.get(n)??Mt();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<$N||await t().fetchStatus(n,r,{silent:!!s?.status})},ensureAll:(n,r)=>{const s=nr(J(),n),o=ji.get(s);if(o)return o;const i=(async()=>{const a=t().directories.get(n),c=Date.now();(!a?.status||a.status.diffStats===void 0||c-(a?.lastStatusFetch??0)>=zN)&&await t().fetchStatus(n,r,{silent:!!a?.status});const f=t().directories.get(n);if(!f?.isGitRepo)return;const u=[];(!f.branches||c-f.lastBranchesFetch>=qN)&&u.push(t().fetchBranches(n,r,{silent:!!f.branches})),(!f.log||c-f.lastLogFetch>=UN)&&u.push(t().fetchLog(n,r,void 0,{silent:!!f.log})),(f.remotes==null||c-(f.lastRemotesFetch??0)>=j0)&&u.push(t().fetchRemotes(n,r,{silent:f.remotes!=null})),u.length>0&&await Promise.all(u)})();return ji.set(s,i),i.finally(()=>{ji.get(s)===i&&ji.delete(s)}),i},refresh:async(n,r={})=>{const{activeDirectory:s}=t();s&&await t().fetchAll(s,n,r)}}),{name:"git-store"})),mR=e=>yt(t=>e?t.directories.get(e)?.status??null:null),cb=e=>yt(t=>e?t.directories.get(e)?.branches??null:null),gR=e=>yt(t=>e?t.directories.get(e)?.log??null:null),yR=e=>yt(t=>e?t.directories.get(e)?.remotes??null:null),vR=e=>yt(t=>e?t.directories.get(e)?.remoteUrl??null:null),xR=e=>yt(t=>e?t.directories.get(e)?.isLoadingRemotes??!1:!1),Bd=e=>yt(t=>e?t.directories.get(e)?.isGitRepo??null:null),bR=e=>yt(t=>e?t.directories.get(e)?.status?.current?.trim()??null:null),B0={current:new Map},wR=new Map,SR=(e=!0)=>yt(t=>{if(!e)return wR;const n=B0.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 B0.current=s,s}),CR=e=>{const t=h.useRef(new Map);return yt(n=>{const r=t.current;let s=r.size===e.length;if(s)for(const i of e){const a=n.directories.get(i),c=r.get(i);if(!c||(a?.isGitRepo??null)!==c.isGitRepo||(a?.status?.current??null)!==c.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})},kR=e=>yt(t=>e?t.directories.get(e)?.isLoadingStatus??!1:!1),MR=e=>yt(t=>e?t.directories.get(e)?.isLoadingLog??!1:!1),IR=e=>yt(t=>e?t.directories.get(e)?.isLoadingBranches??!1:!1),ZW=Object.freeze(Object.defineProperty({__proto__:null,useGitAllBranches:SR,useGitBranchLabel:bR,useGitBranches:cb,useGitLoadingBranches:IR,useGitLoadingLog:MR,useGitLoadingRemotes:xR,useGitLoadingStatus:kR,useGitLog:gR,useGitRemoteUrl:vR,useGitRemotes:yR,useGitRepoStatusMap:CR,useGitStatus:mR,useGitStore:yt,useIsGitRepo:Bd},Symbol.toStringTag,{value:"Module"})),db=h.createContext(null),WW=({actions:e,children:t})=>l.jsx(db.Provider,{value:e,children:t}),Ia=()=>h.useContext(db),_R=/^[A-Za-z]:\/$/,Rm=/^[A-Za-z]:\//,Bt=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=_R.test(s);return!o&&!i&&(s=s.replace(/\/+$/,"")),s},ER=e=>{const t=Bt(e);return t.startsWith("/")||Rm.test(t)},Zc=e=>{const t=Bt(e);return Rm.test(t)||t.startsWith("//")?t.toLowerCase():t},ub=e=>e.split("/").filter(Boolean),jR=(e,t)=>{const n=[...e];for(const r of ub(t))if(r!=="."){if(r===".."){n.length>0&&n.pop();continue}n.push(r)}return n},_a=(e,t)=>{const n=Bt(t);if(!n)return Bt(e);if(ER(n))return n;const r=Bt(e);if(!r)return n;const s=Rm.test(r)?r.slice(0,2):"",o=r.startsWith("//"),i=r.startsWith("/")&&!o,a=s?r.slice(2):r,d=jR(ub(a),n).join("/");return s?d?`${s}/${d}`:`${s}/`:o?`//${d}`:i?`/${d}`:d},$d=(e,t)=>{const n=Bt(e),r=Bt(t);if(!n||!r)return!1;const s=Zc(n),o=Zc(r);return s===o||s.startsWith(`${o}/`)},fb=(e,t)=>{const n=Bt(e),r=Bt(t);return n?r?Zc(n)===Zc(r)?".":$d(n,r)?n.slice(r.length+1):n:n:""},Ef=(e,t)=>{const n=Bt(e),r=Bt(t);if(n&&(!r||$d(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)},TR=new Set(["edit","multiedit","write","apply_patch","create","file_write"]),Pm=e=>"insertions"in e,Fs=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e))},AR=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}},GW=e=>{const t=[],n=new Set;for(const r of e){if(r.type!=="tool"||!r.tool||!TR.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,c=i?.metadata,d=Array.isArray(c?.files)?c.files:[];for(const f of d){if(!f||typeof f!="object")continue;const u=f,p=u.relativePath||u.filePath||"";!p||n.has(p)||(n.add(p),t.push({path:p,tool:s,partId:r.id,messageID:o,additions:Fs(u.additions)??void 0,deletions:Fs(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(d.length===0&&c?.filediff&&typeof c.filediff=="object"){const f=c.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:Fs(f.additions)??void 0,deletions:Fs(f.deletions)??void 0,patch:typeof f.patch=="string"?f.patch:void 0}))}if(d.length===0&&Array.isArray(c?.results))for(const f of c.results){if(!f||typeof f!="object")continue;const u=f.filediff;if(!u||typeof u!="object")continue;const p=typeof u.file=="string"?u.file:"";!p||n.has(p)||(n.add(p),t.push({path:p,tool:s,partId:r.id,messageID:o,additions:Fs(u.additions)??void 0,deletions:Fs(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 c?.patch=="string"?c.patch.trim():typeof c?.diff=="string"?c.diff.trim():"";if(f&&!n.has("Diff")){n.add("Diff");const u=AR(f);t.push({path:"Diff",tool:s,partId:r.id,messageID:o,additions:u.added,deletions:u.removed})}}}return t},hb=(e,t,n)=>{const r=[];for(const s of e){const o=s.index?.trim()??"",i=s.working_dir?.trim()??"",a=!!(o&&o!=="?"),c=!!(i||o==="?"),d=i||o;if(!d||d==="!")continue;const f=t?.[s.path];r.push({path:_a(n,s.path),relativePath:s.path,insertions:f?.insertions??0,deletions:f?.deletions??0,status:d,hasStagedChanges:a,hasWorkingChanges:c})}return r},LR=(e,t)=>fb(e,t),NR=(e,t)=>{const n=Pm(e)&&e.relativePath?e.relativePath:LR(e.path,t),r=n.split("/").pop()??n,s=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";return{fileName:r,dirPart:s}},RR=e=>Pm(e)?{additions:e.insertions,deletions:e.deletions}:{additions:e.additions??0,deletions:e.deletions??0},PR=({files:e,currentDirectory:t,onOpenFile:n})=>l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 typography-ui-label font-medium text-muted-foreground",children:[l.jsx("span",{children:"Changed files"}),l.jsx("span",{className:"typography-meta tabular-nums",children:e.length})]}),l.jsx("div",{className:"max-h-[260px] overflow-y-auto",children:e.map((r,s)=>{const{fileName:o,dirPart:i}=NR(r,t),a=RR(r);return l.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:[l.jsx(rr,{filePath:r.path,className:"h-3.5 w-3.5 flex-shrink-0"}),l.jsx("span",{className:"min-w-0 flex-1 flex items-baseline overflow-hidden",title:r.path,children:i?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),l.jsxs("span",{className:"flex-shrink-0",children:[l.jsx("span",{className:"text-muted-foreground",children:"/"}),l.jsx("span",{className:"text-foreground",children:o})]})]}):l.jsx("span",{className:"truncate text-foreground",children:o})}),a.additions>0||a.deletions>0?l.jsxs("span",{className:"flex-shrink-0 inline-flex items-baseline gap-1 text-[0.75rem] tabular-nums",children:[a.additions>0?l.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.additions]}):null,a.deletions>0?l.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.deletions]}):null]}):null]},`${r.path}:${s}`)})})]}),pb="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)]",mb={maxWidth:"calc(100cqw - 4ch)",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},gb=h.memo(({align:e="start"})=>{const[t,n]=h.useState(!1),r=h.useRef(null),s=Bn()??null,o=h.useContext(wa),i=Bd(s),a=yt(k=>s?k.directories.get(s)?.status??null:null),c=Ia(),d=ne(k=>k.isMobile),{enabled:f}=jd(),u=d&&!f;h.useEffect(()=>{if(!t)return;const k=w=>{r.current&&!r.current.contains(w.target)&&n(!1)};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const p=h.useMemo(()=>!s||i!==!0||!a||a.isClean?[]:hb(a.files,a.diffStats,s),[i,a,s]),{totalAdded:m,totalRemoved:g}=h.useMemo(()=>{let k=0,w=0;for(const C of p)k+=C.insertions,w+=C.deletions;return{totalAdded:k,totalRemoved:w}},[p]);if(!s||i!==!0||p.length===0)return null;const b=k=>{if(!s||!Pm(k))return;n(!1);const w=k.path;if(c){c.openChanges({diffPath:k.relativePath,staged:k.hasStagedChanges&&!k.hasWorkingChanges});return}const C=o?.editor;if(C){C.openFile(w);return}const I=ne.getState(),_=k.hasStagedChanges&&!k.hasWorkingChanges;if(!I.isMobile){I.openContextDiff(s,k.relativePath,_);return}I.navigateToDiff(k.relativePath,_)},y=p.length,S=y===1?`${y} file`:`${y} files`,v=y===1?"1 change":`${y} changes`,x=l.jsxs(l.Fragment,{children:[l.jsx(F,{name:"git-branch",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),u?l.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-ui-label",children:v}):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"min-w-0 shrink-0 text-foreground typography-ui-label",children:S}),l.jsx("span",{className:"status-row__changed-label min-w-0 typography-ui-label text-foreground truncate",children:"changed"})]}),l.jsxs("span",{className:"inline-flex shrink-0 items-baseline gap-1 text-[0.75rem] tabular-nums",children:[m>0?l.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}):null,g>0?l.jsxs("span",{style:{color:"var(--status-error)"},children:["-",g]}):null]}),t?l.jsx(F,{name:"arrow-up-s",className:"h-3.5 w-3.5 shrink-0"}):l.jsx(F,{name:"arrow-down-s",className:"h-3.5 w-3.5 shrink-0"})]});return l.jsxs("div",{className:"relative",ref:r,children:[l.jsx("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 text-left text-muted-foreground",onClick:()=>n(k=>!k),"aria-expanded":t,children:x}),t&&l.jsx("div",{style:{...mb,maxWidth:"min(28rem, calc(100cqw - 4ch))"},className:P(pb,"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:l.jsx(PR,{files:p,currentDirectory:s,onOpenFile:b})})]})});gb.displayName="PendingChangesBar";const DR=h.createContext("default"),zd=()=>h.useContext(DR);let Zh=!1;const Wh=new Set,Wc=()=>Zh,KW=e=>{if(Zh!==e){Zh=e;for(const t of[...Wh])try{t()}catch{}}},OR=e=>(Wh.add(e),()=>{Wh.delete(e)}),yb=()=>h.useSyncExternalStore(OR,Wc,Wc);function HR({className:e,style:t,...n}){return l.jsx(vs,{"data-slot":"command",style:{color:"var(--surface-elevated-foreground)",...t},className:P("flex h-full w-full flex-col overflow-hidden rounded-xl",e),...n})}const vb=U.forwardRef(({className:e,...t},n)=>l.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[l.jsx(F,{name:"search",className:"size-4 shrink-0 opacity-50"}),l.jsx(vs.Input,{ref:n,"data-slot":"command-input",className:P("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})]}));vb.displayName="CommandInput";function FR({className:e,children:t,scrollbarClassName:n,disableHorizontal:r,...s}){return l.jsx(Fn,{as:vs.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:P("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 VR({...e}){return l.jsx(vs.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...e})}function BR({className:e,...t}){return l.jsx(vs.Group,{"data-slot":"command-group",className:P("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 YW({className:e,...t}){return l.jsx(vs.Separator,{"data-slot":"command-separator",className:P("bg-border -mx-1 h-px",e),...t})}function $R({className:e,...t}){return l.jsx(vs.Item,{"data-slot":"command-item",className:P("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 XW({className:e,...t}){const n=o=>{const i=o.trim().toLowerCase();return i==="ctrl"||i==="control"?l.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?l.jsx(F,{name:"command",className:"size-3.5"}):i==="shift"||i==="⇧"?l.jsx(F,{name:"arrow-up",className:"size-3.5"}):l.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 l.jsx("span",{"data-slot":"command-shortcut",className:P("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",e),...t,children:s.length>0?s.map((o,i)=>l.jsxs(U.Fragment,{children:[i>0&&l.jsx("span",{className:"opacity-60 text-xs",children:"+"}),n(o)]},`${o}-${i}`)):t.children})}const jf=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")},JW=e=>!!(e&&typeof e=="object"&&e.deferred===!0),QW=e=>`${e} saved. It will apply when active sessions are idle.`,eG=e=>`${e} could not be changed while a session is running. Try again when it finishes.`,zR=5e3,wn=new Map,vr=new Map,gr=new Map,Xi=new Map,eo=(e,t)=>`${e}
72
- ${t?.trim()??""}`,go=e=>{Xi.set(e,(Xi.get(e)??0)+1),vr.delete(e)},tG=e=>{const t=J();if(typeof e=="string"&&e.trim().length>0){const r=eo(t,e);wn.delete(r),go(r);return}const n=new Set([...wn.keys(),...vr.keys(),...gr.keys()]);for(const r of n)r.startsWith(`${t}
73
- `)&&(wn.delete(r),go(r))},Tf=e=>{const t=new Set([...wn.keys(),...vr.keys(),...gr.keys()]);for(const n of t)n.startsWith(`${e}
74
- `)&&(wn.delete(n),go(n))},_l=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})),fc=Et()(or((e,t)=>({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null,setSelectedPrompt:n=>e({selectedPromptId:n}),setPromptDraft:n=>e({promptDraft:n}),resetForRuntimeSwitch:()=>{wn.clear(),vr.clear(),gr.clear(),Xi.clear(),e({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null})},loadPrompts:async n=>{const r=J(),s=typeof n=="string"&&n.trim().length>0?n.trim():void 0,o=eo(r,s),i=Date.now(),a=gr.get(o);e({activeCacheKey:o,prompts:a??[],isLoading:!0});const c=wn.get(o)??0;if(c>0&&i-c<zR)return e({isLoading:!1}),!0;const d=vr.get(o);if(d)return d;const f=Xi.get(o)??0,u=(async()=>{try{const p=s?await Ne.listResources(s,{runtimeKey:r}):await Ne.listResources({runtimeKey:r});if(J()!==r)return!1;if((Xi.get(o)??0)!==f)return e(g=>g.activeCacheKey===o?{isLoading:!1}:g),!0;const m=_l(p);return gr.set(o,m),wn.set(o,Date.now()),e(g=>g.activeCacheKey===o?{prompts:m,isLoading:!1,...g.selectedPromptId&&!m.some(b=>b.id===g.selectedPromptId)?{selectedPromptId:null}:{}}:g),!0}catch{return e(p=>p.activeCacheKey===o?{isLoading:!1}:p),!1}})();vr.set(o,u);try{return await u}finally{vr.get(o)===u&&vr.delete(o)}},createPrompt:async(n,r,s)=>{const o=J(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await Ne.createPromptTemplate({name:n,description:s.description,content:r,location:s.location},i,{runtimeKey:o});if(J()!==o)return a.deferred===!0?"deferred":!0;const c=eo(o,i),d=_l(a);go(c),gr.set(c,d),Tf(o),wn.set(c,Date.now());const f=d.find(u=>u.name===n&&u.location===s.location);return e(u=>u.activeCacheKey===c?{prompts:d,promptDraft:null,selectedPromptId:f?.id??null,isLoading:!1}:u),zl(s.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return jf(a)?"busy":!1}},updatePrompt:async(n,r,s)=>{const o=J(),i=t().prompts.find(c=>c.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 c=await Ne.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(J()!==o)return c.deferred===!0?"deferred":!0;const d=eo(o,a),f=_l(c);go(d),gr.set(d,f),Tf(o),wn.set(d,Date.now());const u=f.find(p=>p.name===(r.name??i.name)&&p.location===(r.location??i.location));return e(p=>p.activeCacheKey===d?{prompts:f,selectedPromptId:u?.id??null,isLoading:!1}:p),zl(i.location==="global"||r.location==="global"?null:a),c.deferred===!0?"deferred":!0}catch(c){return jf(c)?"busy":!1}},deletePrompt:async(n,r)=>{const s=J(),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 Ne.deletePromptTemplate(o.id,i,{runtimeKey:s});if(J()!==s)return a.deferred===!0?"deferred":!0;const c=eo(s,i),d=_l(a);return go(c),gr.set(c,d),Tf(s),wn.set(c,Date.now()),e(f=>f.activeCacheKey===c?{prompts:d,...f.selectedPromptId===n?{selectedPromptId:null}:{},isLoading:!1}:f),zl(o.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return jf(a)?"busy":!1}},getPromptById:n=>t().prompts.find(r=>r.id===n)}),{name:"prompt-templates-store"})),UR="pichamber.json",qR=".pichamber",ZR=[".config","pichamber","projects"];function Dm(){const e=jr();return e?.files?e.files:null}const WR=80,GR=4e3,KR=2e3,YR=300,XR=new Set(["macos","linux","windows"]),yo=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},ma=(e,t)=>{const n=yo(e),r=t.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},xb=e=>ma(ma(e,qR),UR),Ud=()=>{const e="/api";return e.startsWith("/"),e},Om=async(e,t)=>{try{const n=await Tt(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}}},JR=async e=>{const t=Dm();if(t?.createDirectory)try{if((await t.createDirectory(e))?.success)return!0}catch{}return!!(await Om(`${Ud()}/fs/mkdir`,{path:e})).ok},bb=async(e,t)=>{try{const n=await Tt(`${Ud()}/fs/read`,{query:{path:e,optional:"true",...t?{directory:t}:{}},cache:"no-store"});return n.ok?await n.text():null}catch{return null}},QR=async(e,t)=>{const n=Dm();if(n?.writeFile)try{if((await n.writeFile(e,t))?.success)return!0}catch{}return!!(await Om(`${Ud()}/fs/write`,{path:e,content:t})).ok},wb=async()=>{const e=await z7();let t=e.home?yo(e.home):null;const n=e.pichamberDataDir?yo(e.pichamberDataDir):null;if(!t)try{const r=await U7();r&&r.trim().length>0&&(t=yo(r))}catch{}return{home:t,pichamberDataDir:n}},eP=async()=>(await wb()).home,tP=async()=>(await wb()).pichamberDataDir,Sb=async()=>{const e=await tP();if(e)return ma(e,"projects");const t=await eP();return t?ZR.reduce((n,r)=>ma(n,r),t):null},nP=e=>{const t=typeof e?.path=="string"?e.path.trim():"",n=t?yo(t):"";return n&&yp(n)||null},Cb=async e=>{const t=await Sb();if(!t)return null;const n=nP(e);return n?ma(t,`${n}.json`):null},El=(e,t)=>e.length<=t?e:e.slice(0,t),rP=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();!XR.has(s)||n.has(s)||(n.add(s),t.push(s))}return t},sP=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=El(typeof s.name=="string"?s.name.trim():"",WR),a=El(typeof s.command=="string"?s.command.trim():"",GR);if(!o||!i||!a||n.has(o))continue;n.add(o);const c=typeof s.icon=="string"?s.icon.trim():"",d=rP(s.platforms),f=s.autoOpenUrl===!0,u=typeof s.openUrl=="string"?s.openUrl.trim():"",p=El(u,KR),m=typeof s.desktopOpenSshForward=="string"?s.desktopOpenSshForward.trim():"",g=El(m,YR);t.push({id:o,name:i,command:a,icon:c||null,...f?{autoOpenUrl:!0}:{},...p?{openUrl:p}:{},...g?{desktopOpenSshForward:g}:{},...d.length>0?{platforms:d}:{}})}return t},kb=e=>{const t=sP(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 Hm(e){const t=typeof e?.path=="string"?e.path.trim():"";if(!t)return null;const n=await Cb(e),r=async(a,c)=>{const d=await bb(a,c);return d===null?null:d},s=a=>{if(typeof a!="string")return null;const c=a.trim();if(!c)return null;try{const d=JSON.parse(c);return!d||typeof d!="object"?null:d}catch{return null}};if(n){const a=s(await r(n));if(a)return a}const o=xb(t),i=s(await r(o,t));if(!i)return null;try{await Mb(e,i)&&await aP(t)}catch{}return i}async function Mb(e,t){const n=typeof e?.path=="string"?e.path.trim():"";if(!n)return!1;const r=await Sb(),s=await Cb(e);if(!r||!s)return!1;try{if(!await JR(r))return!1;const i=await bb(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 c={};a.version!==void 0&&(c.version=a.version);const d=JSON.stringify({...a,...t,...c,projectPath:yo(n)},null,2);return await QR(s,d)}catch(o){return console.error("Failed to write pichamber config:",o),!1}}async function Ib(e,t){const r={...await Hm(e)||{},...t};return Mb(e,r)}async function oP(e){const t=await Hm(e);return tv(t?.draftStarters)}async function iP(e,t){return Ib(e,{draftStarters:tv(t)})}async function nG(e){const t=await Hm(e);return kb({actions:t?.projectActions,primaryActionId:t?.projectActionsPrimaryId})}async function rG(e,t){const n=kb({actions:t.actions,primaryActionId:t.primaryActionId});return Ib(e,{projectActions:n.actions,projectActionsPrimaryId:n.primaryActionId??void 0})}async function aP(e){const t=xb(e),n=Dm();if(n?.delete)try{await n.delete(t);return}catch{}try{await Om(`${Ud()}/fs/delete`,{path:t})}catch{}}const lP=[],fi=(e,t)=>`${e}:${Kf(t)}`;function cP(){const e=ne(N=>N.globalDraftStarters),t=fc(N=>N.prompts),n=fc(N=>N.activeCacheKey),r=fc(N=>N.loadPrompts),s=it(N=>N.activeProjectId),o=it(N=>N.projects),i=Bn(),a=h.useMemo(()=>{if(!s)return null;const N=o.find(D=>D.id===s);return N?.path?{id:N.id,path:N.path}:null},[s,o]),[c,d]=h.useState([]),f=h.useRef(new Set),[u,p]=h.useState(0);h.useEffect(()=>{let N=!1;if(!a){d([]);return}return oP(a).then(D=>{N||d(D)}).catch(()=>{N||d([])}),()=>{N=!0}},[a]),h.useEffect(()=>sn(()=>{f.current.clear(),p(D=>D+1),d([])}),[]);const m=h.useCallback(()=>{i&&r(i)},[i,r]);h.useEffect(()=>{if(!i)return;let N=!1;const D=J();return r(i).then(K=>{N||J()===D&&K&&(f.current.add(i),p(V=>V+1))}),()=>{N=!0}},[i,r]);const g=eo(J(),i),b=n===g,y=b?t:lP,S=h.useMemo(()=>q7(y),[y]),v=i?b&&f.current.has(i):!1,x=h.useCallback((N,D)=>{if(N.type==="text"){const V=Z7[N.key];return V?{id:fi(D,N),ref:N,group:D,label:V.label,icon:V.icon,insertText:V.text,promptName:""}:null}return S.get(N.name)?{id:fi(D,N),ref:N,group:D,label:gu(N.name),icon:mu,insertText:`/${N.name} `,promptName:N.name}:v?null:{id:fi(D,N),ref:N,group:D,label:gu(N.name),icon:mu,insertText:`/${N.name} `,promptName:N.name}},[S,v]),k=h.useMemo(()=>e??Ja,[e]),w=h.useMemo(()=>k.map(N=>x(N,"global")).filter(N=>N!==null),[k,x]),C=h.useMemo(()=>c.map(N=>x(N,"project")).filter(N=>N!==null),[c,x]),{global:I,project:_}=h.useMemo(()=>W7(C,w),[C,w]),E=h.useMemo(()=>{const N=new Set;for(const D of k)N.add(Kf(D));for(const D of c)N.add(Kf(D));return N},[k,c]),M=h.useMemo(()=>{const N=new Map;for(const D of y){if(D.editable!==!0||D.location!=="global"&&D.location!=="project")continue;const K=N.get(D.name),V=D.location==="project"?"project":"user",W={type:"prompt",name:D.name,label:gu(D.name),icon:mu,section:"prompt",scope:V};if(!K){N.set(D.name,W);continue}V==="project"&&K.scope!=="project"&&N.set(D.name,W)}return[...N.values()].filter(D=>!E.has(`${D.type}:${D.name}`))},[y,E]),T=h.useCallback(N=>{ne.getState().setGlobalDraftStarters(N),Er({draftStarters:N})},[]),A=h.useCallback(N=>{d(N),a&&iP(a,N)},[a]),j=h.useCallback(N=>{if(N.type!=="prompt")return;const D={type:"prompt",name:N.name};if(N.scope==="project"){if(!a||c.some(K=>Qa(K,D)))return;A([...c,D])}else{const K=e??Ja;if(K.some(V=>Qa(V,D)))return;T([...K,D])}},[a,c,e,A,T]),R=h.useCallback((N,D)=>{N==="project"?A(c.filter(K=>!Qa(K,D))):T((e??Ja).filter(V=>!Qa(V,D)))},[c,e,A,T]),O=h.useCallback((N,D,K)=>{const V=N==="project"?c:e??Ja,W=V.findIndex(L=>fi(N,L)===D),B=V.findIndex(L=>fi(N,L)===K);if(W<0||B<0||W===B)return;const Z=Q9([...V],W,B);N==="project"?A(Z):T(Z)},[c,e,A,T]);return{global:I,project:_,pinnable:M,hasProject:!!a,ensureLoaded:m,addStarter:j,removeStarter:R,reorder:O}}const _b="__draft-starter-trash__",Eb="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors",dP=[{key:"prompt",headingKey:"Prompts"}],uP=({item:e,onInsert:t,onRemove:n,hideRemove:r})=>{const{currentTheme:s}=Vn(),{attributes:o,listeners:i,setNodeRef:a,transform:c,transition:d,isDragging:f}=_p({id:e.id}),u={backgroundColor:s?.colors?.surface?.elevated,borderColor:s?.colors?.interactive?.border};return l.jsxs("div",{ref:a,style:{transform:Ep.Translate.toString(c),transition:d},className:P("group/chip relative",f&&"z-10 opacity-60"),children:[l.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:[l.jsx(F,{name:e.icon,className:"h-3.5 w-3.5 shrink-0 opacity-70 transition-opacity group-hover:opacity-100"}),l.jsx("span",{className:"whitespace-nowrap",children:e.label})]}),r?null:l.jsx("button",{type:"button",onClick:p=>{p.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:l.jsx(F,{name:"close",className:"h-2.5 w-2.5"})})]})},$0=({items:e,onInsert:t,onRemove:n,hideRemove:r})=>l.jsx(Ip,{items:e.map(s=>s.id),strategy:tS,children:e.map(s=>l.jsx(uP,{item:s,onInsert:t,onRemove:()=>n(s),hideRemove:r},s.id))}),fP=()=>{const{currentTheme:e}=Vn(),{setNodeRef:t,isOver:n}=nS({id:_b});return l.jsx("button",{type:"button",ref:t,"aria-label":"Remove",title:"Remove",className:P(Eb,n?"border-destructive text-destructive":"text-muted-foreground"),style:{backgroundColor:e?.colors?.surface?.elevated,borderColor:n?void 0:e?.colors?.interactive?.border},children:l.jsx(F,{name:"delete-bin",className:"h-4 w-4"})})},hP=({pinnable:e,onPick:t,className:n})=>l.jsxs(HR,{className:P("min-h-0",n),children:[l.jsx(vb,{placeholder:"Search prompts…"}),l.jsxs(FR,{children:[l.jsx(VR,{children:"Nothing to add"}),dP.map(r=>{const s=e.filter(o=>o.section===r.key);return s.length===0?null:l.jsx(BR,{heading:r.headingKey,children:s.map(o=>l.jsx($R,{value:`${o.section} ${o.label} ${o.name}`,onSelect:()=>t(o),children:l.jsx("span",{className:"truncate",children:o.label})},`${o.type}:${o.name}`))},r.key)})]})]}),pP=({pinnable:e,onOpen:t,onAdd:n})=>{const{currentTheme:r}=Vn(),[s,o]=h.useState(!1);return l.jsxs(Td,{open:s,onOpenChange:i=>{o(i),i&&t()},children:[l.jsx(FI,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Add a starter",title:"Add a starter",className:P(Eb,"text-muted-foreground hover:bg-[var(--interactive-hover)] hover:text-foreground"),style:{backgroundColor:r?.colors?.surface?.elevated,borderColor:r?.colors?.interactive?.border},children:l.jsx(F,{name:"add",className:"h-4 w-4"})})}),l.jsxs(Ad,{className:"gap-0 overflow-hidden p-0 sm:max-w-sm",children:[l.jsx(Ld,{className:"px-4 pb-2 pt-4 text-left",children:l.jsx(Nd,{children:"Add a starter"})}),l.jsx(hP,{pinnable:e,onPick:i=>{n(i),o(!1)},className:"flex max-h-[60vh] flex-col"})]})]})},mP=({onInsert:e,className:t})=>{const{global:n,project:r,pinnable:s,ensureLoaded:o,addStarter:i,removeStarter:a,reorder:c}=cP(),{isMobile:d}=Pr(),[f,u]=h.useState(!1),p=Cp(ra(lv,{activationConstraint:{distance:8}}),ra(av,{activationConstraint:{delay:200,tolerance:6}})),m=h.useCallback(S=>n.find(v=>v.id===S)??r.find(v=>v.id===S),[n,r]),g=()=>u(!0),b=()=>u(!1),y=S=>{u(!1);const{active:v,over:x}=S;if(!x)return;const k=String(v.id),w=m(k);if(!w)return;if(String(x.id)===_b){a(w.group,w.ref);return}const C=String(x.id);if(k===C)return;const I=m(C);I&&I.group===w.group&&c(w.group,k,C)};return l.jsx(kp,{sensors:p,collisionDetection:Mp,measuring:{droppable:{strategy:eS.Always}},onDragStart:g,onDragCancel:b,onDragEnd:y,children:l.jsxs("div",{className:P("flex flex-wrap items-center justify-center gap-2",t),children:[n.length>0?l.jsx($0,{items:n,onInsert:e,onRemove:S=>a("global",S.ref),hideRemove:d}):null,r.length>0?l.jsx($0,{items:r,onInsert:e,onRemove:S=>a("project",S.ref),hideRemove:d}):null,d&&f?l.jsx(fP,{}):l.jsx(pP,{pinnable:s,onOpen:o,onAdd:i})]})})},jb=e=>ne(n=>n.draftStartersVisible)?l.jsx(mP,{...e}):null,Tb=()=>{const e=pe(i=>i.currentSessionId),t=$x(),n=pe(i=>i.newSessionDraft),r=it(i=>i.activeProjectId),s=it(i=>i.projects),o=tt(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},hi=new Map,gP=(e,t)=>`${e}
75
- ${t?.trim()??""}`;function Ab(e){const t=e?.trim()?e.trim():void 0,n=h.useSyncExternalStore(_8,wu,wu),r=fc(m=>m.prompts.map(g=>`${g.id}:${g.name}:${g.location}`).join("|")),s=kr(m=>m.skills.map(g=>`${g.id}:${g.name}:${g.scope}`).join("|")),[o,i]=h.useState(()=>{if(!t)return ur();const m=rg(J(),t);return m?[...ur(),...m]:ur()}),[a,c]=h.useState(!1),[d,f]=h.useState(0),u=h.useRef(void 0),p=h.useRef({promptSignature:"",skillSignature:""});return h.useEffect(()=>{p.current={promptSignature:r,skillSignature:s}},[r,s]),h.useEffect(()=>sn(()=>{N8(),hi.clear(),u.current=void 0,i(ur()),f(g=>g+1)}),[]),h.useEffect(()=>{const m=J(),g=gP(m,t),b=`${g}
76
- ${n}`;if(!t){u.current=g,i(ur());return}if(u.current!==g){u.current=g;const x=rg(m,t);i(x?[...ur(),...x]:ur())}const y=j8(m,t);if(y&&T8(y)){const x=y.promptSignature!==""&&y.promptSignature!==r,k=y.skillSignature!==""&&y.skillSignature!==s;if(!x&&!k){(y.promptSignature!==r||y.skillSignature!==s)&&L8(m,t,r,s),c(!1);return}}let S=!1;c(!0);const v=()=>{const x=hi.get(b);let k;if(x)k=x;else{const w=n,C=p.current.promptSignature,I=p.current.skillSignature,_={},E=(async()=>{try{const M=await Ne.listCommands(t,{runtimeKey:m});if(J()!==m||wu()!==w)return null;const T=M8(M.commands);return A8(m,t,T,{promptSignature:C,skillSignature:I}),T}catch{return null}finally{hi.get(b)?.promise===_.promise&&hi.delete(b)}})();_.promise=E,k={promise:E,promptSignature:C,skillSignature:I},hi.set(b,k)}k.promise.then(w=>{if(!S&&J()===m){if(w){i([...ur(),...w]);const C=p.current,I=k.promptSignature!==""&&k.promptSignature!==C.promptSignature,_=k.skillSignature!==""&&k.skillSignature!==C.skillSignature;if(I||_){v();return}}c(!1)}}).catch(()=>{S||c(!1)})};return v(),()=>{S=!0}},[t,r,s,d,n]),{commands:o,isLoading:a}}const yP=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer"],vP=e=>typeof e=="string"&&yP.includes(e),xP=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."}},bP=({enabled:e,preset:t,customInstructions:n})=>e?t==="custom"?(typeof n=="string"?n.trim():"")||null:vP(t)?xP(t):null:null,Lb=(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")},wP=e=>e.newSessionDraftOpen||(e.sessionId!==null?Lb(e.storeState,e.sessionId):!1),Nb=e=>bP({enabled:e.responseStyleEnabled===!0,preset:e.responseStylePreset,customInstructions:e.responseStyleCustomInstructions});let Ji=null,Ws=null;const SP=e=>{Ji={runtimeKey:J(),value:Nb(e)}};typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{SP(e.detail??{})});sn(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Ji=null,Ws=null)});const CP=async()=>{const e=J();if(Ji?.runtimeKey===e)return Ji.value;if(Ws?.runtimeKey===e)return Ws.promise;const t=(async()=>{const n=await Tt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return null;const r=await n.json().catch(()=>null);if(!r||J()!==e)return null;const s=Nb(r);return Ji={runtimeKey:e,value:s},s})();Ws={runtimeKey:e,promise:t};try{return await t}finally{Ws?.promise===t&&(Ws=null)}},kP=async e=>{if(!wP({newSessionDraftOpen:e.newSessionDraftOpen,sessionId:e.sessionId,storeState:e.getStoreState()}))return null;const t=await CP().catch(()=>null);return!t||!e.newSessionDraftOpen&&e.sessionId!==null&&!Lb(e.getStoreState(),e.sessionId)?null:t},z0="<system-reminder>",U0="</system-reminder>",MP=e=>{const t=e.trim();return t?t.startsWith(z0)&&t.endsWith(U0)?t:`${z0}
77
- ${t}
78
- ${U0}`:""},q0=e=>e.includes("@")?"paste":"manual",IP=({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},_P=/[\s()[\]{}<>"'`,.;:]/,EP=/^[`"'<([{]+/,jP=/[)\]},.;:!?`"'>]+$/,Z0=/@([^\s]+)/g;function TP(e,t){return t<=0?!0:_P.test(e[t-1])}function AP(e){return e.trim().replace(EP,"").replace(jP,"")}function LP(e){if(!e||!e.includes("@"))return[];const t=[];Z0.lastIndex=0;let n;for(;(n=Z0.exec(e))!==null;){const r=n.index;if(!TP(e,r))continue;const s=n[1]??"",o=AP(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 NP(e,t){return!e||e.includes("<")||e.includes(">")?null:t.knownAgentNames.has(e.toLowerCase())?"agent":RP(e,t.confirmedMentions)?"file":null}function RP(e,t){return e.includes("/")||e.includes("\\")||e.includes(".")||t.has(e)}const PP=(e,t)=>t<=0||/\s/.test(e[t-1]);function DP(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 OP(e,t,n,r){const s=e.substring(0,t),o=s.lastIndexOf(n);if(o===-1||!PP(s,o))return null;const i=s.substring(o+1);return i.includes(" ")||i.includes(`
81
- `)?null:{kind:r,query:i}}function HP(e,t,n){return n.inputMode==="shell"?null:DP(e,t)??OP(e,t,"#","snippet")??FP(e,t,n)}function FP(e,t,n){const r=IP({value:e,cursorPosition:t,inputSource:n.inputSource,insertedText:n.insertedText});return r===null?null:{kind:"mention",query:r}}const VP=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),W0=new Set(["image","screenshot","screen-shot","clipboard","pasted-image","pastedimage","untitled","unknown","file","blob"]),BP={"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"},gs=e=>e.trim().toLowerCase(),$P=e=>e.charCodeAt(0)<32||'<>:"/\\|?*[]'.includes(e),zP=e=>{const t=e.replace(/\\/g,"/").split("/").pop()??"";return Array.from(t).map(n=>$P(n)?"-":n).join("").replace(/\s+/g," ").replace(/-+/g,"-").trim()},UP=e=>{const t=e?.trim().toLowerCase()??"";return BP[t]??"png"},Rb=e=>{const t=zP(e.name),n=UP(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}},qP=e=>{const{base:t}=Rb({name:e}),n=t.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(W0.has(n))return!0;const r=n.replace(/-\(\d+\)$/g,"");return r!==n&&W0.has(r)?!0:/^(image|file|unknown|untitled|blob)-\d+$/.test(n)},vo=(e,t)=>`${e}.${t}`,ZP=(e,t,n)=>{const r=vo(e,t);if(!n.has(gs(r)))return r;for(let s=2;s<Number.MAX_SAFE_INTEGER;s+=1){const o=vo(`${e}-${s}`,t);if(!n.has(gs(o)))return o}return vo(`${e}-${Date.now()}`,t)},WP=(e,t)=>{for(let n=1;n<Number.MAX_SAFE_INTEGER;n+=1){const r=vo(`image-${n}`,e);if(!Array.from(t).some(o=>o.startsWith(`image-${n}.`))&&!t.has(gs(r)))return r}return vo(`image-${Date.now()}`,e)},GP=(e,t)=>{const n=new Set(t.map(gs));return e.map(r=>{const{base:s,ext:o}=Rb(r),i=qP(vo(s,o))?WP(o,n):ZP(s,o,n);return n.add(gs(i)),i})},KP=e=>e.map(t=>`[${t}]`).join(" "),YP=(e,t)=>{if(!e||!e.includes("[")||t.length===0)return[];const n=new Set(t.map(gs)),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(gs(a))&&r.push({start:o,end:i+1})}s=i+1}return r},XP=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}},Pb=e=>e.trim().toLowerCase(),Gh=new Map,jl=new Map;let Tl=null;const JP=async(e,t)=>{switch(e){case"javascript":{const{javascript:n}=await ft(async()=>{const{javascript:r}=await import("./vendor-codemirror-lang-javascript-Dw4kFO4e.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 ft(async()=>{const{json:r}=await import("./vendor-codemirror-lang-json-B-b1vAv-.js");return{json:r}},__vite__mapDeps([48,49,46,5,1,6]));return n().language}case"css":{const{css:n}=await ft(async()=>{const{css:r}=await import("./vendor-codemirror-lang-css-RM2HqXZ0.js");return{css:r}},__vite__mapDeps([50,51,46,5,1,6]));return n().language}case"html":{const{html:n}=await ft(async()=>{const{html:r}=await import("./vendor-codemirror-lang-html-CHSHUpwq.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 ft(async()=>{const{markdown:r}=await import("./vendor-codemirror-lang-markdown-BTht2ATe.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 ft(async()=>{const{python:r}=await import("./vendor-codemirror-lang-python-CH6_em9L.js");return{python:r}},__vite__mapDeps([56,57,46,5,1,6,47]));return n().language}case"shell":{if(Tl)return Tl;const{shell:n}=await ft(async()=>{const{shell:r}=await import("./shell-CjFT_Tl9.js");return{shell:r}},[]);return Tl=rS.define(n),Tl}}},Db=e=>e?Gh.get(Pb(e))??null:null,QP=e=>{const t=Pb(e);if(!t)return Promise.resolve(null);const n=Gh.get(t);if(n)return Promise.resolve(n);const r=jl.get(t);if(r)return r;const s=XP(t);if(!s)return Promise.resolve(null);const o=JP(s,t).then(i=>(i&&Gh.set(t,i),jl.delete(t),i)).catch(()=>(jl.delete(t),null));return jl.set(t,o),o},eD={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},G0={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"},tD=new Set(["strong","emphasis"]),Ob="text-foreground";function nD(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 rD(e,t,n){const r=e[t-1],s=e[t+n];return!(!r||/\s/.test(r)||e[t]==="_"&&s&&/[\w]/.test(s))}function sD(e,t){const n=e[t],r=/^(\*{1,3}|_{1,3})/.exec(e.slice(t))?.[1]??"";if(!r||!nD(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(rD(e,o,r.length))return{end:o+r.length,runLength:r.length};s=o+r.length}return null}function Gs(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 c=a+i.length;n.push({start:t+r,end:t+c,style:"code"}),r=c;continue}}if(o==="["){const i=/^\[([^\]\n]*)\]\(([^)\n]*)\)/.exec(e.slice(r));if(i){const a=t+r,c=i[1].length,d=i[2].length,f=a+1,u=f+c,p=u+2,m=p+d,g=m+1;n.push({start:a,end:f,style:"marker"}),c>0&&n.push({start:f,end:u,style:"link"}),n.push({start:u,end:p,style:"marker"}),d>0&&n.push({start:p,end:m,style:"linkUrl"}),n.push({start:m,end:g,style:"marker"}),r+=i[0].length;continue}}if(o==="*"||o==="_"){const i=sD(e,r);if(i){const a=t+r+i.runLength,c=t+i.end-i.runLength;n.push({start:t+r,end:a,style:"marker"}),i.runLength>=2&&n.push({start:a,end:c,style:"strong"}),i.runLength!==2&&n.push({start:a,end:c,style:"emphasis"}),n.push({start:c,end:t+i.end,style:"marker"}),Gs(e.slice(r+i.runLength,i.end-i.runLength),a,n),r=i.end;continue}}r+=1}}const oD=/^(\s*)(`{3,}|~{3,})\s*(\S*)/;function Fm(e){const t=oD.exec(e);return t?{marker:t[2],lang:t[3]||""}:null}function Hb(e,t){return new RegExp(`^\\s*\\${t[0]}{${t.length},}\\s*$`).test(e)}function iD(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],c=n,d=c+a.length;if(n=d+1,r){t.push({start:c,end:d,style:"codeFence"}),Hb(a,s)&&(r=!1);continue}const f=Fm(a);if(f){r=!0,s=f.marker,t.push({start:c,end:d,style:"codeFence"});continue}const u=/^(\s*)(!!!)(\s+)/.exec(a);if(u){const b=c+u[1].length,y=b+u[2].length;t.push({start:b,end:y,style:"marker"});const S=y+u[3].length;d>S&&(t.push({start:S,end:d,style:"attention"}),Gs(a.slice(S-c),S,t));continue}const p=/^(\s*)(#{1,6})(\s+)/.exec(a);if(p){const b=c+p[1].length,y=b+p[2].length;t.push({start:b,end:y,style:"marker"});const S=y+p[3].length;d>S&&(t.push({start:S,end:d,style:"heading"}),Gs(a.slice(S-c),S,t));continue}const m=/^(\s*)(>+)(\s?)/.exec(a);if(m){const b=c+m[1].length,y=b+m[2].length;t.push({start:b,end:y,style:"marker"});const S=y+m[3].length;d>S&&(t.push({start:S,end:d,style:"blockquote"}),Gs(a.slice(S-c),S,t));continue}const g=/^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(a);if(g){const b=c+g[1].length,y=b+g[2].length;t.push({start:b,end:y,style:"listMarker"});const S=y+g[3].length;Gs(a.slice(S-c),S,t);continue}Gs(a,c,t)}return t}function aD(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 c=0;for(let d=0;d<s.length-1;d+=1){const f=s[d],u=s[d+1];if(u<=f)continue;for(;c<o.length&&o[c].range.start<=f;)a.push(o[c]),c+=1;for(let x=a.length-1;x>=0;x-=1)a[x].range.end<=f&&a.splice(x,1);let p=null,m=-1,g=1/0;const b=[];for(const{range:x,index:k}of a){if(tD.has(x.style)){const C=x.className??G0[x.style];b.includes(C)||b.push(C);continue}const w=x.priority??eD[x.style];(w>m||w===m&&k<g)&&(m=w,g=k,p=x)}const y=p?p.className??G0[p.style]:Ob,S=b.length>0?[y,...b].join(" "):y,v=i[i.length-1];v&&v.className===S&&v.end===f?v.end=u:i.push({start:f,end:u,className:S})}return i}const lD=Ob;function cD(e){return e.map(t=>({start:t.start,end:t.end,style:t.kind==="file"?"mentionFile":"mentionAgent"}))}const Kn="bg-[var(--surface-subtle)]",dD=91,uD=94,Af={keyword:8,function:7,type:6,string:5,number:5,variable:4,operator:3,comment:2},fD={keyword:`${Kn} text-[var(--syntax-keyword)]`,string:`${Kn} text-[var(--syntax-string)]`,number:`${Kn} text-[var(--syntax-number)]`,comment:`${Kn} text-[var(--syntax-comment)]`,function:`${Kn} text-[var(--syntax-function)]`,type:`${Kn} text-[var(--syntax-type)]`,variable:`${Kn} text-[var(--syntax-variable)]`,operator:`${Kn} text-[var(--syntax-operator)]`},hD=oS([{tag:[De.comment,De.lineComment,De.blockComment,De.docComment,De.meta],class:"comment"},{tag:[De.keyword,De.modifier,De.controlKeyword,De.operatorKeyword,De.definitionKeyword,De.moduleKeyword,De.self,De.null],class:"keyword"},{tag:[De.string,De.special(De.string),De.docString,De.character,De.regexp],class:"string"},{tag:[De.number,De.integer,De.float,De.bool,De.atom],class:"number"},{tag:[De.function(De.variableName),De.function(De.propertyName),De.macroName,De.standard(De.variableName)],class:"function"},{tag:[De.typeName,De.className,De.namespace,De.tagName],class:"type"},{tag:[De.variableName,De.propertyName,De.attributeName,De.labelName,De.definition(De.variableName)],class:"variable"},{tag:[De.operator,De.punctuation,De.bracket,De.derefOperator,De.separator],class:"operator"},{tag:[De.heading,De.heading1,De.heading2,De.heading3,De.heading4,De.heading5,De.heading6,De.strong],class:"keyword"},{tag:[De.emphasis,De.quote],class:"type"},{tag:[De.link,De.url],class:"function"},{tag:[De.monospace],class:"string"},{tag:[De.strikethrough],class:"comment"}]),pD=e=>{let t=null;for(const n of e.split(" ")){const r=n;Af[r]!==void 0&&(t===null||Af[r]>Af[t])&&(t=r)}return t?fD[t]:null},mD=2e4,gD=e=>e?Db(e):null;async function yD(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return!1;const t=new Set;for(const r of e.split(`
83
- `)){const s=Fm(r);s?.lang&&(Db(s.lang)||t.add(s.lang))}return t.size===0?!1:(await Promise.all([...t].map(r=>QP(r)))).some(r=>r!==null)}function vD(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=Fm(o);if(!i)continue;const a=gD(i.lang),c=r,d=[];let f=s+1,u=r;for(;f<n.length;f+=1){const m=n[f];if(Hb(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 p=d.join(`
85
- `);if(p.trim()&&(t.push({start:c,end:c+p.length,style:"codeFence",className:`${Kn} text-[var(--syntax-foreground)]`,priority:dD}),!(p.length>mD)))try{const m=a.parser.parse(p);sS(m,hD,(g,b,y)=>{const S=pD(y);S&&t.push({start:c+g,end:c+b,style:"codeFence",className:S,priority:uD})})}catch{}}return t}const K0=/~([^\s~]+)/g,xD=/[)\]},.;:!?`"'>]+$/,bD=/[\s()[\]{}<>"'`,;:]/;function wD(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z]/.test(e)}function SD(e){if(!e||!e.includes("~"))return[];const t=[];K0.lastIndex=0;let n;for(;(n=K0.exec(e))!==null;){const r=n.index,s=r>0?e[r-1]:"";if(s&&!bD.test(s))continue;const o=(n[1]??"").replace(xD,"");!o||!wD(o)||t.push({start:r,end:r+1+o.length,path:o})}return t}function CD(e){return SD(e).map(t=>({start:t.start,end:t.end,style:"path"}))}const kD="[A-Za-z0-9][A-Za-z0-9_-]*",MD="[A-Za-z0-9][^\\s/]*",ID={"/":new RegExp(`(^|\\s)\\/(${MD})`,"g"),"#":new RegExp(`(^|\\s)#(${kD})`,"g")};function Kh(e,t){if(!e||!e.includes(t))return[];const n=ID[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 Yh(e,t,n="case-insensitive"){return t.size===0?[]:e.filter(r=>t.has(n==="exact"?r.name:r.name.toLowerCase()))}function _D(e,t,n,r="case-insensitive"){const s=new Set,o=[];for(const i of Yh(Kh(e,t),n,r))s.has(i.name)||(s.add(i.name),o.push(i.name));return o}function ED(e,t){const n=[];for(const r of LP(e)){const s=NP(r.name,t);s&&n.push({start:r.start,end:r.end,kind:s})}return n}function jD(e,t){if(!e||t.inputMode==="shell")return[];const n=[...iD(e),...vD(e),...cD(ED(e,t)),...CD(e)];for(const r of Yh(Kh(e,"/"),t.knownSlashNames))n.push({start:r.start,end:r.end,style:"mentionCommand"});for(const r of Yh(Kh(e,"#"),t.knownSnippetTriggers))n.push({start:r.start,end:r.end,style:"mentionSnippet"});if(t.attachmentFilenames.length>0&&e.includes("["))for(const r of YP(e,[...t.attachmentFilenames]))n.push({...r,style:"mentionFile"});return n}const Vm=mv.define(),Fb=mv.define(),Xh=gv.define({create:()=>Vb,update(e,t){for(const n of t.effects)if(n.is(Vm))return n.value;return e}}),Vb={inputMode:"normal",knownAgentNames:new Set,confirmedMentions:new Set,knownSlashNames:new Set,knownSnippetTriggers:new Set,attachmentFilenames:[]};function Y0(e,t){const n=new aS;for(const r of aD(e,jD(e,t)))r.className!==lD&&n.add(r.start,r.end,lS.mark({class:r.className}));return n.finish()}const TD=gv.define({create:e=>Y0(e.doc.toString(),e.field(Xh)),update(e,t){const n=t.effects.some(s=>s.is(Vm)),r=t.effects.some(s=>s.is(Fb));return!t.docChanged&&!n&&!r?e:Y0(t.state.doc.toString(),t.state.field(Xh))},provide:e=>hn.decorations.from(e)}),AD=iS.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 yD(n)}catch{return}t===this.generation&&r&&e.state.doc.toString()===n&&e.dispatch({effects:Fb.of(void 0)})}});function LD(e=Vb){return[Xh.init(()=>e),TD,AD]}const ND={"&":{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)"}},RD=hn.theme(ND),PD={"& .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"}},DD=hn.theme(PD),OD=[DD,hn.editorAttributes.of(e=>e.state.selection.main.empty?null:{class:"oc-native-range"})];function HD(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 FD(e){let t="";return e.changes.iterChanges((n,r,s,o,i)=>{t+=i.toString()}),t}function X0(e){return!!e.synthetic}const J0=new yv,Q0=new yv,VD=h.forwardRef(function(t,n){const{value:r,languageContext:s,placeholder:o,editable:i=!0,spellCheck:a=!1,autoCorrect:c=!1,autoCapitalize:d="none",fillContainer:f=!1,maxLines:u=8,boundSelector:p,boundGapPx:m=0,className:g,contentClassName:b,commandComboboxExpanded:y,commandComboboxListboxId:S,commandComboboxActiveOptionId:v}=t,x=h.useRef(null),k=h.useRef(null),w=h.useRef(!1),C=h.useRef({element:null,role:null}),I=h.useRef(t),_=t.viewStore??null;_&&!_.handlers&&(_.handlers={current:t});const E=_?.handlers??I;E.current=t,h.useLayoutEffect(()=>{const T=x.current;if(!T)return;const A=_?.view;if(A){T.appendChild(A.dom),A.requestMeasure();const{anchor:N,head:D}=A.state.selection.main;return A.dispatch({selection:{anchor:N,head:D}}),k.current=A,()=>{A.dom.remove(),k.current=null}}const j=[{any:(N,D)=>(D.key==="Enter"&&X0(D)&&w.current&&Object.defineProperty(D,"shiftKey",{value:!0}),E.current.onKeyDown?.(D)??!1)}],R=new hn({state:cS.create({doc:E.current.value,extensions:[dS(),uS(),OD,hn.lineWrapping,fS.highest(z1.of(j)),z1.of([...hS,...pS]),LD(E.current.languageContext),J0.of(hn.editable.of(E.current.editable??!0)),Q0.of(U1(E.current.placeholder??"")),RD,hn.updateListener.of(N=>{const D=E.current,K=ty(N.state);if(N.docChanged){const V=N.transactions.some(B=>B.isUserEvent("input.paste"));let W="";for(const B of N.transactions)W+=FD(B);D.onChange({value:N.state.doc.toString(),selection:K,fromPaste:V,insertedText:W})}else N.selectionSet&&D.onSelectionChange?.(K);(N.docChanged||N.heightChanged||N.geometryChanged)&&D.onVisualLineCount?.(ey(N.view))}),hn.domEventHandlers({focus:()=>(E.current.onFocus?.(),!1),blur:()=>(E.current.onBlur?.(),!1),paste:N=>(E.current.onPaste?.(N),!1)}),hn.contentAttributes.of({spellcheck:String(E.current.spellCheck??!1),autocorrect:E.current.autoCorrect?"on":"off",autocapitalize:E.current.autoCapitalize??"none",...E.current["aria-label"]?{"aria-label":E.current["aria-label"]}:{}})]}),parent:T});k.current=R,_&&(_.view=R);const O=N=>{N.key!=="Enter"||X0(N)||(w.current=N.shiftKey)};return R.contentDOM.addEventListener("keydown",O),()=>{if(k.current=null,_){R.dom.remove();return}R.destroy()}},[]),h.useEffect(()=>{const T=k.current;if(!T)return;const A=T.state.doc.toString();A!==r&&(T.dispatch({changes:{from:0,to:A.length,insert:r},selection:{anchor:r.length}}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{k.current===T&&(T.scrollDOM.scrollTop=T.scrollDOM.scrollHeight)})}))},[r]),h.useEffect(()=>{k.current?.dispatch({effects:Vm.of(s)})},[s]),h.useEffect(()=>{k.current?.dispatch({effects:J0.reconfigure(hn.editable.of(i))})},[i]),h.useEffect(()=>{k.current?.dispatch({effects:Q0.reconfigure(U1(o??""))})},[o]),h.useEffect(()=>{const T=k.current,A=x.current;if(!T||!A)return;if(f){T.scrollDOM.style.maxHeight="";return}const j=p?A.closest(p):null;let R=null;if(j)for(R=A;R.parentElement&&R.parentElement!==j;)R=R.parentElement;const O=()=>{const D=parseFloat(getComputedStyle(T.contentDOM).lineHeight||"");if(!Number.isFinite(D)||D<=0)return;let K=D*u;if(j&&R){const W=R.offsetHeight-T.scrollDOM.offsetHeight,B=j.clientHeight-W-m;B>0&&(K=Math.min(K,B))}const V=`${K}px`;T.scrollDOM.style.maxHeight!==V&&(T.scrollDOM.style.maxHeight=V)};if(O(),E.current.onVisualLineCount?.(ey(T)),typeof ResizeObserver>"u")return;const N=new ResizeObserver(O);return N.observe(A),R&&N.observe(R),j&&N.observe(j),()=>N.disconnect()},[m,p,f,u]),h.useEffect(()=>{const T=k.current;if(!T)return;const A=T.contentDOM;A.setAttribute("spellcheck",String(a)),A.setAttribute("autocorrect",c?"on":"off"),A.setAttribute("autocapitalize",d)},[d,c,a]),h.useLayoutEffect(()=>{const T=k.current;if(!T)return;const A=T.contentDOM;if(C.current.element!==A){const D=C.current;D.element&&D.element!==A&&(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")),C.current={element:A,role:A.getAttribute("role")}}const j=C.current.role,R=()=>{j===null?A.getAttribute("role")==="combobox"&&A.removeAttribute("role"):A.getAttribute("role")!==j&&A.setAttribute("role",j)},O=()=>{A.removeAttribute("aria-expanded"),A.removeAttribute("aria-controls"),A.removeAttribute("aria-activedescendant"),R()};return!!(y&&S)&&S?(A.setAttribute("role","combobox"),A.setAttribute("aria-expanded","true"),A.setAttribute("aria-controls",S),v?A.setAttribute("aria-activedescendant",v):A.removeAttribute("aria-activedescendant"),O):(O(),O)},[y,S,v]);const M=h.useCallback(T=>{HD(k.current,T)},[]);return h.useImperativeHandle(n,()=>({focus(T){const A=k.current;A&&A.contentDOM.focus({preventScroll:T?.preventScroll})},blur(){k.current?.contentDOM.blur()},isFocused(){return k.current?.hasFocus??!1},getValue(){return k.current?.state.doc.toString()??""},getSelection(){const T=k.current;return T?ty(T.state):{start:0,end:0}},setSelection(T,A=T){const j=k.current;if(!j)return;const R=j.state.doc.length;j.dispatch({selection:{anchor:Math.min(Math.max(T,0),R),head:Math.min(Math.max(A,0),R)}})},selectAll(){const T=k.current;T&&T.dispatch({selection:{anchor:0,head:T.state.doc.length}})},insertText(T){const A=k.current;if(!A||!T)return;const{from:j,to:R}=A.state.selection.main;A.dispatch({changes:{from:j,to:R,insert:T},selection:{anchor:j+T.length},userEvent:"input.type"})},replaceRange(T,A,j,R){const O=k.current;O&&O.dispatch({changes:{from:T,to:A,insert:j},selection:{anchor:R??T+j.length},userEvent:"input.type"})},caretCoords(T){const A=k.current;if(!A)return null;const j=T??A.state.selection.main.head,R=A.coordsAtPos(j);return R?{top:R.top,bottom:R.bottom,left:R.left}:null},getScrollDOM(){return k.current?.scrollDOM??null}}),[]),l.jsx("div",{ref:x,"data-testid":t["data-testid"],"data-chat-input":"true",onMouseDown:M,className:P("composer-editor w-full","[&_.cm-editor]:h-full",f&&"flex min-h-0 flex-1 flex-col",g,b)})});function ey(e){const t=e.defaultLineHeight;return!Number.isFinite(t)||t<=0?1:Math.max(1,Math.round(e.contentHeight/t))}function ty(e){const t=e.selection.main;return{start:t.from,end:t.to}}function BD(){return{view:null,handlers:null}}function $D(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 Bb(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 $b(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 zD(e,t){return e?`${e}${/\s$/.test(e)?"":" "}${t}`:t}const UD=/^(https?:\/\/|mailto:)\S+$/i;function qD(e,t){return UD.test(e)&&!/\s/.test(e)&&t.trim().length>0&&!t.includes("](")}const ZD="application/x-pichamber-file-path",WD=["files","text/uri-list","codefiles",ZD];function GD(e,t){try{return e.getData(t)}catch{return""}}function Al(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(WD.some(n=>t.includes(n))||t.some(n=>n.includes("vnd.code.tree")))return!0}for(const t of xT){const n=GD(e,t);if(n&&yT(n).length>0)return!0}return!1}function KD(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 YD({enabled:e,composerRef:t,messageRef:n,cursorPosRef:r,confirmedMentionsRef:s,setMessage:o,addAttachedFile:i}){const[a,c]=h.useState(!1),[d,f]=h.useState(!1),u=h.useRef(0),p=h.useCallback(v=>{if(!Al(v.dataTransfer))return;v.preventDefault(),v.stopPropagation(),u.current++;const x=v.dataTransfer.types?.includes("application/x-pichamber-file-path")??!1;x!==d&&f(x),e&&!a&&c(!0)},[e,a,d]),m=h.useCallback(v=>{Al(v.dataTransfer)&&(v.preventDefault(),v.stopPropagation(),v.dataTransfer.dropEffect="copy",e&&!a&&c(!0))},[e,a]),g=h.useCallback(v=>{v.preventDefault(),v.stopPropagation(),u.current--,u.current<=0&&(u.current=0,c(!1),f(!1))},[]),b=h.useCallback(()=>{u.current=0,c(!1),f(!1)},[]),y=h.useCallback(async v=>{if(u.current=0,!Al(v.dataTransfer)||(v.preventDefault(),v.stopPropagation(),c(!1),!e))return;const k=v.dataTransfer.getData("application/x-pichamber-file-path");if(k&&k!=="."){s.current.add(k);const C=`@${k}`,I=t.current,_=n.current;if(I){const{start:E,end:M}=I.getSelection(),T=_.slice(0,E),A=_.slice(M),j=T.length>0&&!/\s$/.test(T),R=A.length>0&&!/^\s/.test(A),O=`${j?" ":""}${C}${R?" ":""}`;I.replaceRange(E,M,O),r.current=E+O.length,I.focus()}else o(E=>Bb(E,C));return}const w=KD(v.dataTransfer);w.length>0&&((await Promise.all(w.map(async I=>{try{return await i(I)}catch(_){return console.error("File attach failed",_),!1}}))).some(Boolean)||ke.error("Failed to attach file"))},[i,t,s,r,e,n,o]),S=h.useCallback(v=>{Al(v.dataTransfer)&&v.preventDefault()},[]);return{isDragging:a,isInternalDrag:d,handleDragEnter:p,handleDragOver:m,handleDragLeave:g,handleDragEnd:b,handleDrop:y,handleDropCapture:S}}const XD=16e3,JD="pasted-text.txt";function QD(e){return e.length>XD}function ny(e){return new File([e],JD,{type:"text/plain"})}function eO({inputMode:e,enabled:t,composerRef:n,message:r,setMessage:s,insertTextAtSelection:o,updateAutocompleteState:i,markFileMentionPasteSuppression:a,attachedFiles:c,addAttachedFile:d}){const f=h.useRef(new Set);return h.useCallback(async u=>{const p=u.clipboardData;if(!p)return;const m={...u,clipboardData:p,preventDefault:()=>u.preventDefault()},g=m.clipboardData.getData("text"),b=QD(g);if(e==="normal"&&t&&!b){const M=n.current,T=M?.getSelection().start??-1,A=M?.getSelection().end??-1;if(M&&A>T){const j=g.trim(),R=r.slice(T,A);if(qD(j,R)){m.preventDefault();const O=`${r.slice(0,T)}[${R}](${j})${r.slice(A)}`,N=T+1+R.length+2+j.length+1;s(O),n.current?.setSelection(N,N),i(O,N,q0(j),j);return}}}const y=new Map;Array.from(m.clipboardData.files||[]).forEach(M=>{M.type.startsWith("image/")&&y.set(`${M.name}-${M.size}`,M)}),Array.from(m.clipboardData.items||[]).forEach(M=>{if(M.kind==="file"&&M.type.startsWith("image/")){const T=M.getAsFile();T&&y.set(`${T.name}-${T.size}`,T)}});const S=Array.from(y.values());if(b){if(!t){g.includes("@")&&a();return}if(m.preventDefault(),S.length===0){const M=ny(g);try{await d(M)||ke.error("Failed to attach pasted text as file")}catch{ke.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 v=GP(S,[...c.map(M=>M.filename),...f.current]),x=KP(v),k=n.current,w=k?.getSelection().start??r.length,C=k?.getSelection().end??r.length,I=$b(zD(b?"":g,x),r.slice(0,w),r.slice(C));o(I,q0(I));const _=b?(async()=>{try{await d(ny(g))||ke.error("Failed to attach pasted text as file")}catch{ke.error("Failed to attach pasted text as file")}})():null,E=S.map(async(M,T)=>{const A=v[T],j=VP(M,A);f.current.add(A);try{await d(j)}catch(R){console.error("Clipboard image attach failed",R),ke.error(R instanceof Error?R.message:"Failed to attach image from clipboard")}finally{f.current.delete(A)}});await Promise.all(_?[_,...E]:E)},[d,c,n,t,e,o,a,r,s,i])}const tO=(e,t)=>{if(t.size===0)return[];const n=new Map;for(const a of t){const c=a.toLowerCase();n.has(c)||n.set(c,a)}const r=new Set;for(const a of n.keys())r.add(`skill:${a}`);const s=_D(e,"/",r,"case-insensitive"),o=new Set,i=[];for(const a of s){const c=a.slice(6),d=n.get(c.toLowerCase())??c,f=d.toLowerCase();o.has(f)||(o.add(f),i.push(d))}return i},nO=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 rO(e,t){let n="",r=[],s;const o=[],i=[],a=u=>{for(const p of t.collectSkillNames(u))i.includes(p)||i.push(p)},c=u=>{!s&&u&&(s=u)},d=u=>{const p=t.parseAgentMention(u);c(p.agentName);const m=t.extractFileMentions(p.text);return a(m.text),m};if(e.queued.forEach((u,p)=>{const m=d(u.content),g=[...t.sanitizeAttachments(u.attachments),...m.attachments];if(p===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,"")),p=[...t.sanitizeAttachments(e.composerAttachments),...u.attachments];e.queued.length===0?(n=u.text,r=p):o.push({text:u.text,attachments:p})}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 ry(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 sO=["undo","redo","timeline","compact"];function zb(e){return sO.includes(e)}async function oO({command:e,currentSessionId:t,scrollToBottom:n,setTimelineDialogOpen:r,onCompactSession:s,onUndoSession:o,onRedoSession:i}){const{name:a,argument:c}=e;return zb(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,c.trim()||void 0),!0):(ke.error("Open a session before compacting."),!0):!1:!1}function iO(e){const{enabled:t,openAutocomplete:n,message:r,editorRef:s,containerRef:o}=e,[i,a]=h.useState(null),c=h.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 p=f.getBoundingClientRect(),m=u.top-p.top,g=u.left-p.left,b=8,y=260,S=m-b,v=p.height-m-b,x=v>=y||v>=S?"below":"above",k=n==="mention"?520:450,w=Math.max(b,Math.min(g-24,p.width-k-b)),C=Math.max(120,Math.min(y,x==="below"?v:S));a({top:x==="below"?m+22:m-6,left:w,place:x,maxHeight:C})},[o,s,t,n]);return h.useLayoutEffect(()=>{c()},[c,r,n,t]),h.useEffect(()=>{if(!t)return;const d=()=>c();return window.addEventListener("resize",d),()=>{window.removeEventListener("resize",d)}},[t,c]),{position:i,update:c}}const qd=-1,Jh={index:qd,stashedDraft:""},Qh=e=>({state:e,text:null});function aO(e,t,n){if(t.length===0)return Qh(e);if(e.index===qd)return{state:{index:0,stashedDraft:n},text:t[0]};if(e.index>=t.length-1)return Qh(e);const r=e.index+1;return{state:{...e,index:r},text:t[r]}}function lO(e,t){if(e.index===qd)return Qh(e);if(e.index===0)return{state:Jh,text:e.stashedDraft};const n=e.index-1;return{state:{...e,index:n},text:t[n]}}function cO(e){const[t,n]=h.useState(Jh),r=h.useCallback(i=>{const a=aO(t,e,i);return a.text===null?null:(n(a.state),a.text)},[e,t]),s=h.useCallback(()=>{const i=lO(t,e);return i.text===null?null:(n(i.state),i.text)},[e,t]),o=h.useCallback(()=>n(Jh),[]);return{isBrowsing:t.index!==qd,older:r,newer:s,reset:o}}const dO=500;function sy(e,t){return`${e}\0${[...t].sort().join("\0")}`}function uO(e){const{message:t,messageRef:n,setMessage:r,confirmedMentionsRef:s,identity:o,persistEnabled:i,initialDraft:a,onIdentityChange:c,onDraftRestored:d}=e,f=h.useRef(null),u=h.useRef(!1),p=h.useRef(new Map),m=h.useRef(a.identity),g=h.useRef({onIdentityChange:c,onDraftRestored:d});g.current={onIdentityChange:c,onDraftRestored:d},h.useEffect(()=>{m.current=o},[o]);const b=h.useCallback((x,k)=>{if(!x)return;const w=Wt(x),C=new Set;for(const _ of s.current)k.includes(`@${_}`)&&C.add(_);s.current=C;const I=sy(k,C);p.current.get(w)!==I&&(hs(x,k,C),p.current.set(w,I))},[s]),y=h.useCallback(()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]),S=h.useRef(!1);h.useEffect(()=>{if(!S.current&&(S.current=!0,!!a.text)){if(!i){r(""),hs(a.identity,"",[]);return}requestAnimationFrame(()=>g.current.onDraftRestored?.())}},[i]);const v=h.useRef(a.identity);return h.useEffect(()=>{const x=v.current,k=x?Wt(x):null,w=o?Wt(o):null;if(k===w)return;if(v.current=o,g.current.onIdentityChange?.(),y(),u.current=!0,!i){r(""),s.current=new Set;return}b(x,n.current);const C=vd(o);r(C.text),s.current=C.confirmedMentions,C.text&&requestAnimationFrame(()=>g.current.onDraftRestored?.())},[y,s,o,n,i,b,r]),h.useEffect(()=>vC(x=>{const k=Wt(x);p.current.set(k,sy("",[]));const w=m.current;!w||Wt(w)!==k||(y(),u.current=!0,n.current="",s.current=new Set,r(""))}),[y,s,n,r]),h.useEffect(()=>{if(!i){y(),b(o,"");return}if(u.current){u.current=!1;return}y();const x=t,k=o;return f.current=setTimeout(()=>{f.current=null,b(k,x)},dO),y},[y,o,t,i,b]),h.useEffect(()=>{const x=()=>{y(),i&&b(m.current,n.current)},k=()=>{document.visibilityState==="hidden"&&x()};return document.addEventListener("visibilitychange",k),document.addEventListener("freeze",x),window.addEventListener("pagehide",x),()=>{document.removeEventListener("visibilitychange",k),document.removeEventListener("freeze",x),window.removeEventListener("pagehide",x),x()}},[y,n,i,b]),{persistNow:b}}function fO(e,t,n){const s=e.substring(0,t).lastIndexOf("@");if(s!==-1){const a=e.substring(0,s)+`@${n} `+e.substring(t),c=s+n.length+2;return{newMessage:a,nextCursor:c}}const o=e.substring(0,t)+`@${n} `+e.substring(t),i=t+n.length+2;return{newMessage:o,nextCursor:i}}function oy(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)}`,c=i+r.length+2;return{newMessage:a,nextCursor:c}}function hO({composerRef:e,message:t,setMessage:n,updateAutocompleteState:r,closeAutocomplete:s,confirmedMentionsRef:o,toMentionPath:i}){const a=h.useCallback(u=>{const p=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:b}=fO(t,p,m);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(b),r(g,b)}),s(),e.current?.focus()},[s,e,o,t,n,i,r]),c=h.useCallback(u=>{const p=e.current?.getSelection().start??t.length,{newMessage:m,nextCursor:g}=oy(t,p,"@",u);n(m),requestAnimationFrame(()=>{e.current&&e.current.setSelection(g),r(m,g)}),s(),e.current?.focus()},[s,e,t,n,r]),d=h.useCallback((u,p)=>{const m=e.current?.getSelection().start??t.length,{newMessage:g,nextCursor:b}=oy(t,m,"#",p);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(b),r(g,b)}),s(),e.current?.focus()},[s,e,t,n,r]),f=h.useCallback(u=>{const p=u.invocationName??u.name;n(`/${p} `),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:c,handleSnippetSelect:d,handleCommandSelect:f}}const pO=e=>{const t="nativeEvent"in e?e.nativeEvent:e;return t.isComposing||t.keyCode===229},mO={"`":["`","`"],"*":["*","*"],_:["_","_"],"~":["~","~"],"(":["(",")"],"[":["[","]"],"{":["{","}"],'"':['"','"'],"'":["'","'"]};function gO(e,t,n,r){if(n<=t)return null;const s=mO[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 yO(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 vO({inputMode:e,setInputMode:t,message:n,setMessage:r,openAutocomplete:s,commandRef:o,snippetRef:i,mentionRef:a,composerRef:c,messageHistory:d,updateAutocompleteState:f,isMobile:u,hasContent:p,currentSessionId:m,sessionPhase:g,followUpBehavior:b,handleSubmit:y,handleQueueMessage:S}){return h.useCallback(v=>{if(pO(v))return;if(e==="shell"&&v.key==="Escape"){v.preventDefault(),t("normal");return}if(e==="shell"&&v.key==="Backspace"&&n.length===0){v.preventDefault(),t("normal");return}if(s==="command"&&o.current&&(v.key==="Enter"||v.key==="ArrowUp"||v.key==="ArrowDown"||v.key==="Escape"||v.key==="Tab")){v.preventDefault(),v.stopPropagation(),o.current.handleKeyDown(v.key);return}if(s==="snippet"&&i.current&&(v.key==="Enter"||v.key==="ArrowUp"||v.key==="ArrowDown"||v.key==="Escape"||v.key==="Tab")){v.preventDefault(),v.stopPropagation(),i.current.handleKeyDown(v.key);return}if(s==="mention"&&a.current&&(v.key==="Enter"||v.key==="ArrowUp"||v.key==="ArrowDown"||v.key==="Escape"||v.key==="Tab")){v.preventDefault(),v.stopPropagation(),a.current.handleKeyDown(v.key);return}const x=s!==null,k=c.current?.getSelection().start===0&&c.current?.getSelection().end===0,w=c.current?.getSelection().start===n.length&&c.current?.getSelection().end===n.length,C=!x&&(n.length===0||k),I=!x&&(n.length===0||w);if(e==="normal"&&!x&&!v.metaKey&&!v.ctrlKey&&!v.altKey){const _=c.current,E=_?.getSelection().start??-1,M=_?.getSelection().end??-1;if(_&&E>=0){const T=(R,O,N)=>{v.preventDefault(),r(R),c.current?.setSelection(O,N),f(R,N)},A=gO(n,E,M,v.key);if(A){T(A.next,A.caretStart,A.caretEnd);return}const j=yO(n,E,M,v.key);if(j){T(j.next,j.caret,j.caret);return}}}if(v.key==="ArrowUp"&&C){v.preventDefault();const _=d.older(n);_!==null&&(r(_),requestAnimationFrame(()=>c.current?.setSelection(0,0)));return}if(v.key==="ArrowDown"&&I){v.preventDefault();const _=d.newer();_!==null&&r(_);return}if(v.key==="Enter"&&!v.shiftKey&&(!u||v.ctrlKey||v.metaKey)){v.preventDefault();const _=v.ctrlKey||v.metaKey,E=e==="normal"&&p&&m&&g!=="idle";b==="queue"?_||!E?y():S():_||!E?y():y({delivery:"steer"})}},[o,c,m,b,S,y,p,e,u,a,n,d,s,g,t,r,i,f])}const xO=e=>e.enabled&&e.draftOpen&&!!e.directory&&e.gitAvailable&&e.isGitRepository,bO=(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 Bm(e){return e.label?.trim()||Q5(e.path)}function wO(e){const t=it(V=>V.projects),n=rn(V=>V.projects),r=h.useMemo(()=>Hn(t,{projects:n}),[t,n]),s=tt(V=>V.homeDirectory),o=h.useMemo(()=>T3(t,r),[r,t]),i=it(V=>V.activeProjectId),a=it(V=>V.setActiveProjectIdOnly),c=pe(V=>V.newSessionDraft),d=pe(V=>V.currentSessionId),f=pe(V=>V.currentSessionDirectory),u=pe(V=>V.setNewSessionDraftTarget),p=!!c?.open,m=yt(V=>V.fetchBranches),{git:g}=Ca(),b=h.useMemo(()=>{if(p){const W=qt(c?.directoryOverride??null),B=c?.selectedProjectId?o.find(Z=>Z.ownerProjectId===c.selectedProjectId&&(!W||qt(Z.path)===W))??o.find(Z=>Z.id===c.selectedProjectId)??null:null;if(B)return B;if(W){const Z=o.find(L=>qt(L.path)===W)??null;if(Z)return Z}}else if(d){const W=qt(f??null);if(W&&vk(W,s)){const Z=o.find(L=>L.ownerProjectId===tr)??null;if(Z)return Z}const B=er(t,r,f);if(B){const Z=qt(f??null);return o.find(L=>L.ownerProjectId===B.id&&qt(L.path)===Z)??o.find(L=>L.id===B.id)??null}}return(i?o.find(W=>W.id===i)??null:null)??o[0]??null},[i,r,f,d,s,p,c?.directoryOverride,c?.selectedProjectId,o,t]),y=h.useMemo(()=>qt(b?.path??null),[b?.path]),S=h.useMemo(()=>p?qt(c?.directoryOverride??null)??y:qt(f??null)??y,[f,p,c?.directoryOverride,y]),v=b?t.find(V=>V.id===b.ownerProjectId)??null:null,x=qt(v?.path??null),k=b?Bm(b):null;h.useEffect(()=>{if(!ST({enabled:e,isDraftOpen:p,activeProjectId:i,selectedProjectId:c?.selectedProjectId}))return;const V=o.find(W=>W.id===i);V&&u({projectId:V.id,directoryOverride:V.path,branchIntent:null,worktreeIntent:null})},[i,e,p,c?.selectedProjectId,o,u]);const w=Bd(S),C=yt(V=>S&&V.directories.get(S)?.status?.current?.trim()||null),I=cb(p?S:null),[_,E]=h.useState(!1);h.useEffect(()=>{const V=S?yt.getState().directories.get(S)?.branches??null:null;if(!xO({enabled:e,draftOpen:p,directory:S,gitAvailable:!!g,isGitRepository:w===!0})){E(!1);return}if(!S||!g)return;let W=!1;return E(V===null),m(S,g).finally(()=>{W||E(!1)}),()=>{W=!0}},[e,m,p,g,w,S]);const M=I?.current?.trim()||C,T=p&&(c?.worktreeIntent?.startRef?.trim()||c?.branchIntent?.branch?.trim())||null,A=T??M,j=h.useMemo(()=>p?bO(I?.all,T):[],[T,p,I?.all]),R=A??(w===!0?"Detached HEAD":null),O=w===!0&&!!(R||j.length>0||_),N=h.useCallback(V=>{if(!p)return;const W=o.find(Z=>Z.id===V),B=qt(W?.path??null);if(!(!W||!B)){if(W.ownerProjectId===tr){u({projectId:tr,directoryOverride:B,branchIntent:null,worktreeIntent:null});return}i!==W.ownerProjectId&&a(W.ownerProjectId),u({projectId:W.ownerProjectId,directoryOverride:B,branchIntent:null,worktreeIntent:null})}},[i,p,o,a,u]),D=h.useCallback(V=>{if(!p||!S)return;const W=V.trim();if(!(!W||W.startsWith("remotes/"))){if(c?.worktreeIntent&&x){u({branchIntent:null,worktreeIntent:{runtimeKey:J(),projectRoot:x,sourceDirectory:S,startRef:W}});return}u({worktreeIntent:null,branchIntent:{runtimeKey:J(),directory:S,branch:W}})}},[p,c?.worktreeIntent,S,x,u]),K=h.useCallback(V=>{if(!(!p||!S||!x||!A)){if(V){u({branchIntent:null,worktreeIntent:{runtimeKey:J(),projectRoot:x,sourceDirectory:S,startRef:A}});return}u({worktreeIntent:null,branchIntent:A===M?null:{runtimeKey:J(),directory:S,branch:A}})}},[M,p,A,S,x,u]);return{projects:o,selectedDraftProject:b,selectedDraftProjectPath:y,selectedDraftProjectRoot:x,draftProjectLabel:k,selectedDraftDirectory:S,selectedDraftBranchLabel:R,selectedBranchName:A,currentBranch:M,draftBranchItems:j,isDiscoveringDraftBranches:_,shouldShowDraftBranchSelector:O,worktreeMode:!!(p&&c?.worktreeIntent),handleDraftProjectChange:N,handleDraftBranchChange:D,handleWorktreeModeChange:K}}const SO=e=>{const t=le(e.targetDirectory)??e.targetDirectory,r=(e.projectId?e.projects.find(i=>i.id===e.projectId)??null:null)??e.projects.reduce((i,a)=>{const c=le(a.path);if(!c||t!==c&&!t.startsWith(`${c}/`))return i;const d=le(i?.path??null);return!d||c.length>d.length?a:i},null),s=le(r?.path??null),o=new Set([t]);if(!s)return o;o.add(s);for(const[i,a]of e.availableWorktreesByProject)if(le(i)===s)for(const c of a??[]){const d=le(c?.path??null);d&&o.add(d)}return o},CO=(e,t)=>{const n=new Set(e.map(r=>r.id));return t.some(r=>!n.has(r.id))},iy=(e,t)=>{const n=it.getState(),r=Hn(n.projects,rn.getState()),s=SO({targetDirectory:e,projectId:t,projects:n.projects,availableWorktreesByProject:r});return Uk().filter(o=>s.has(o.directory)).sort((o,i)=>(o.title??"").localeCompare(i.title??"")||o.id.localeCompare(i.id))};function kO(e){const{activeRuntimeKey:t,intent:n,onReady:r}=e,{git:s}=Ca(),o=yt(C=>C.fetchStatus),i=yt(C=>C.fetchBranches),a=yt(C=>C.clearDiffCache),[c,d]=h.useState(null),f=h.useRef(!1),u=h.useRef(0),p=h.useRef(null),m=h.useRef(r);m.current=r;const g=n?.runtimeKey??"",b=n?.directory??"",y=n?.branch??"";h.useEffect(()=>{u.current+=1,p.current=null,d(null)},[t,y,b,g]);const S=h.useCallback(C=>{s&&(a(C),Vd.requestGitRefresh({directory:C}),Promise.all([o(C,s,{silent:!0}),i(C,s)]))},[a,i,o,s]),v=h.useCallback((C,I)=>{const _={runtimeKey:I.runtimeKey,directory:I.directory,branch:I.branch};p.current=_,m.current(C,_)},[]),x=h.useCallback(async C=>{const I=C.intent;if(!(f.current||c)){if(!s){ke.error("Git is not available for the selected runtime.");return}if(I.runtimeKey!==J()){ke.error("The runtime changed. Select the branch again before sending.");return}f.current=!0;try{const[_,E]=await Promise.all([s.getGitBranches(I.directory),s.getGitStatus(I.directory,{mode:"light"})]),M=pe.getState().newSessionDraft.branchIntent;if(!Zi(I,M))return;if(!_.all.includes(I.branch)||I.branch.startsWith("remotes/")){ke.error(`Local branch ${I.branch} no longer exists.`),i(I.directory,s);return}if(E.mergeInProgress||E.rebaseInProgress||E.attentionReason){const R=E.attentionReason??(E.rebaseInProgress?"rebase":"merge");ke.error(`Finish or abort the ${R} before switching branches.`);return}const T=E.current?.trim()||_.current?.trim()||null;if(T===I.branch){v(C.continuation,I);return}const A=C.projectId?it.getState().projects.find(R=>R.id===C.projectId)?.label?.trim():null,j=I.directory.split(/[\\/]/).filter(Boolean).pop()||I.directory;d({runtimeKey:I.runtimeKey,projectId:C.projectId??null,directory:I.directory,branch:I.branch,currentBranch:T,projectLabel:A||j,changedFileCount:E.files.length,activeSessions:iy(I.directory,C.projectId),phase:"ready",continuation:C.continuation})}catch(_){ke.error(_ instanceof Error?_.message:"Failed to inspect the selected branch.")}finally{f.current=!1}}},[i,s,c,v]),k=h.useCallback(()=>{u.current+=1,p.current=null,d(null)},[]),w=h.useCallback(async()=>{const C=c;if(!C||C.phase==="checking"||C.phase==="terminal-error"||!s)return;const I=u.current+1;u.current=I,d({...C,phase:"checking",activeSessionsChanged:!1,error:void 0});try{const _=pe.getState().newSessionDraft;if(!_.open||!Zi(_.branchIntent,C))throw Object.assign(new Error("The draft target changed. Press Send again to review the branch."),{terminal:!0});if(C.runtimeKey!==J())throw Object.assign(new Error("The runtime changed. Select the branch again before sending."),{terminal:!0});const E=iy(C.directory,C.projectId);if(CO(C.activeSessions,E)){d({...C,activeSessions:E,phase:"ready",activeSessionsChanged:!0,error:void 0});return}const M=await s.getGitBranches(C.directory);if(u.current!==I)return;const T=M.current?.trim()||null;if(T!==C.currentBranch&&T!==C.branch)throw Object.assign(new Error(`The current branch changed to ${T??"detached HEAD"}. Press Send again to review it.`),{terminal:!0});if(!M.all.includes(C.branch)||C.branch.startsWith("remotes/"))throw Object.assign(new Error(`Local branch ${C.branch} no longer exists.`),{terminal:!0});if(T!==C.branch&&(await s.checkoutBranch(C.directory,C.branch,{expectedCurrent:T,localOnly:!0})).currentBranch!==C.branch)throw Object.assign(new Error(`Git did not confirm checkout of ${C.branch}.`),{terminal:!0});if(u.current!==I)return;if(C.runtimeKey!==J()){ke.warning("The branch may have changed on the previous runtime. The message was not sent.");return}S(C.directory),d(null),v(C.continuation,C)}catch(_){if(u.current!==I)return;const E=_ instanceof Error?_.message:"Failed to check out the selected branch.";let M;try{M=(await s.getGitBranches(C.directory)).current?.trim()||null}catch{M=void 0}if(u.current!==I)return;S(C.directory);const T=!!(_&&typeof _=="object"&&"terminal"in _)||_&&typeof _=="object"&&"code"in _&&_.code==="BRANCH_CHANGED"||M===C.branch||M===void 0,A=M===C.branch?`Git switched to ${C.branch}, but reported an error: ${E} Review the repository, then press Send again.`:E;d({...C,phase:T?"terminal-error":"retryable-error",error:A})}},[s,c,S,v]);return{dialogState:c,request:x,confirm:w,cancel:k,getReceipt:C=>Zi(C,p.current)?p.current:null,clearReceipt:()=>{p.current=null}}}function MO(e){const{taskId:t,intent:n}=e,{git:r}=Ca(),s=rn(f=>f.refreshProject),o=t??v3(n),a=en(h.useCallback(f=>o?f.entries.get(o)??null:null,[o]))?.state??null,c=h.useCallback(async f=>{try{const u=await en.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!==J()?null:u}catch(u){return u instanceof Error&&u.message===sc,null}},[r,s,t]),d=h.useCallback(f=>{const u=o?en.getState().getEntryByKey(o):en.getState().getEntry(f);return!u?.receipt||!f?null:hj(f,u.receipt)?u.receipt:null},[o]);return{state:a,request:c,getReceipt:d}}function IO(e){const{isMobile:t,editorRef:n,formRef:r,controlsPanelOpen:s,attachMenuOpen:o}=e,[i,a]=h.useState(!1),[c,d]=h.useState(!1),f=h.useRef(0),u=h.useRef(!1),p=h.useRef(null);h.useEffect(()=>()=>{p.current!==null&&window.clearTimeout(p.current)},[]),h.useEffect(()=>{if(!t||typeof document>"u")return;let x=document.getElementById("mobile-overlay-root");x||(x=document.createElement("div"),x.id="mobile-overlay-root",document.body.appendChild(x));const k=x,w=()=>d(k.childElementCount>0);w();const C=new MutationObserver(w);return C.observe(k,{childList:!0}),()=>C.disconnect()},[t]);const m=c||s||o,g=h.useRef(0),b=h.useRef(0);h.useEffect(()=>{if(!t||Jn()||typeof window>"u"||!window.matchMedia?.("(display-mode: standalone)")?.matches)return;const x=()=>{g.current+=1},k=()=>{if(g.current=Math.max(0,g.current-1),!u.current||g.current>0)return;u.current=!1,b.current=Date.now()+600,n.current?.focus(),n.current?.isFocused()&&a(!0);const w=()=>{const C=n.current;C?.isFocused()&&(r.current??C.getScrollDOM())?.scrollIntoView({block:"end"})};window.setTimeout(w,300),window.setTimeout(w,650)};return window.addEventListener("oc:mobile-overlay-opened",x),window.addEventListener("oc:mobile-overlay-closed",k),()=>{window.removeEventListener("oc:mobile-overlay-opened",x),window.removeEventListener("oc:mobile-overlay-closed",k)}},[n,r,t]),h.useEffect(()=>{if(!t)return;if(m){(i||Date.now()-f.current<800)&&(u.current=!0);return}if(!u.current)return;const x=window.setTimeout(()=>{u.current=!1,n.current?.focus({preventScroll:Jn()})},180);return()=>window.clearTimeout(x)},[n,i,t,m]),h.useEffect(()=>{if(!t||Jn()||typeof document>"u")return;const x=document.documentElement;return i?x.classList.add("oc-browser-keyboard-open"):(x.classList.remove("oc-browser-keyboard-open"),window.matchMedia?.("(display-mode: standalone)")?.matches&&window.setTimeout(()=>{x.classList.contains("oc-browser-keyboard-open")||(window.scrollTo(0,0),document.body.scrollTop=0,x.scrollTop=0)},350)),()=>x.classList.remove("oc-browser-keyboard-open")},[i,t]);const y=h.useCallback(()=>{t&&(Jn()&&dM(),p.current!==null&&(window.clearTimeout(p.current),p.current=null),a(!0))},[t]),S=h.useCallback(()=>{if(t){if(Date.now()<b.current){const x=n.current;if(x){x.focus(),window.setTimeout(()=>{Date.now()<b.current&&!x.isFocused()&&x.focus()},50);return}}if(f.current=Date.now(),Jn()){na.flushSync(()=>a(!1));return}p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{p.current=null,a(!1)},120)}},[n,t]),v=h.useCallback(()=>{u.current=!1},[]);return{focused:i,onEditorFocus:y,onEditorBlur:S,cancelOverlayCloseRestore:v}}function ay(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 _O(e){const{isMobile:t,isFullscreen:n,isDraftScreen:r,isFocused:s,formRef:o,editorRef:i}=e;h.useLayoutEffect(()=>{if(!t||!n||Jn())return;const a=window.visualViewport,c=o.current,d=i.current;if(!a||!c)return;document.documentElement.classList.add("oc-browser-kb-fullscreen");const f=()=>{const u=Math.max(0,Math.floor(a.offsetTop)),p=document.documentElement.clientHeight;c.style.position="fixed",c.style.left="0",c.style.right="0",c.style.top=`${u}px`,c.style.height=`${Math.floor(Math.min(a.height,p-u))}px`,c.style.zIndex="40",c.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"),ay(c),requestAnimationFrame(()=>{d?.isFocused()&&d.getScrollDOM()?.scrollIntoView({block:"nearest"})})}},[i,o,n,t]),h.useLayoutEffect(()=>{if(!t||Jn()||!r||n||!s)return;const a=window.visualViewport,c=o.current;if(!a||!c)return;const d=c.getBoundingClientRect();c.style.position="fixed",c.style.left=`${Math.floor(d.left)}px`,c.style.width=`${Math.floor(d.width)}px`,c.style.zIndex="40",c.style.background="var(--background)";let f=Number.NaN,u=0;const p=()=>{const m=document.documentElement.clientHeight,g=a.offsetTop+a.height,b=Math.max(0,Math.floor(Math.min(g,m)-c.offsetHeight));b!==f&&(f=b,c.style.top=`${b}px`),u=requestAnimationFrame(p)};return p(),()=>{cancelAnimationFrame(u),ay(c)}},[o,r,s,n,t])}const $m=(e,t)=>{const[n,r]=h.useState(e),s=h.useRef(null),o=h.useCallback(()=>{s.current!==null&&typeof window<"u"&&(window.clearTimeout(s.current),s.current=null)},[]);h.useEffect(()=>o,[o]);const i=h.useCallback(()=>{o(),r(e)},[o,e]),a=h.useCallback(c=>{o(),r(c),!(typeof window>"u")&&(s.current=window.setTimeout(()=>{r(e),s.current=null},t))},[o,t,e]);return{value:n,show:a,clear:i}},Ub=20,EO=24,qb=(e,t)=>e.length<=t?e:`${e.slice(0,t-1)}…`;function Gc({project:e,maxCharacters:t}){const n=Bm(e),r=t?qb(n,t):n,s=e.id==="__home__"||e.ownerProjectId==="__home__";return l.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:n,children:[l.jsx(F,{name:e.kind==="worktree"?"git-branch":s?"home":"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-muted-foreground",children:r})]})}const ly="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",Zb=({checked:e,onChange:t,showCheck:n=!0,chromeLess:r=!1})=>l.jsxs(pt,{delayDuration:300,children:[l.jsx(mt,{asChild:!0,children:l.jsxs(Me,{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:[l.jsx(F,{name:"git-branch",className:"size-3.5"}),l.jsx("span",{className:"truncate",children:"New worktree"}),e&&n?l.jsx(F,{name:"check",className:"size-3.5"}):null]})}),l.jsx(gt,{side:"top",sideOffset:6,className:"max-w-72",children:"Starts from the selected branch's latest commit. Uncommitted changes are not copied."})]}),cy=({label:e,startFrom:t=!1})=>{const n=e??"Branch";return l.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",title:e??void 0,children:[l.jsx(F,{name:"git-branch",className:"size-3.5 shrink-0 text-muted-foreground"}),t&&e?l.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:"from"}):null,l.jsx("span",{className:"truncate",children:n})]})};function Wb({branchName:e}){const{value:t,show:n}=$m(!1,2e3),r=h.useCallback(async s=>{if(s.stopPropagation(),s.preventDefault(),!e)return;(await ir(e)).ok?n(!0):ke.error("Failed to copy")},[e,n]);return e?l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(Me,{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?l.jsx(F,{name:"check",className:"size-3.5 text-[color:var(--status-success)]"}):l.jsx(F,{name:"file-copy",className:"size-3.5"})})}),l.jsx(gt,{sideOffset:6,children:t?"Copied":"Copy branch name"})]}):null}function jO(e){const{projects:t,selectedProject:n,selectedBranchName:r,selectedBranchLabel:s,branchOptions:o,branchInteractive:i,branchLoading:a,showBranchSelector:c,showProjectSelector:d=!0,showWorktreeSelector:f=!1,worktreeMode:u=!1,endAccessory:p,onProjectChange:m,onBranchChange:g,onWorktreeModeChange:b,theme:y}=e;return l.jsxs("div",{className:"mb-3 flex min-w-0 w-full items-center justify-between gap-2 pl-2 pr-1",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[d?l.jsxs(t0,{value:n.id,onValueChange:m,children:[l.jsx(r0,{size:"sm",className:ly,children:l.jsx(n0,{children:l.jsx(Gc,{project:n,theme:y,maxCharacters:Ub})})}),l.jsx(s0,{className:"w-max min-w-48",children:t.map(S=>l.jsx(o0,{value:S.id,className:S.kind==="worktree"?"max-w-[24rem] truncate pl-7":"max-w-[24rem] truncate",children:l.jsx(Gc,{project:S,theme:y})},S.id))})]}):null,c&&i?l.jsxs(t0,{value:r??void 0,onValueChange:g,disabled:!!(a&&o.length===0),children:[l.jsx(r0,{size:"sm",className:ly,children:l.jsx(n0,{children:l.jsx(cy,{label:s,startFrom:u})})}),l.jsx(s0,{className:"w-max min-w-56",children:l.jsxs(NA,{children:[l.jsx(RA,{children:a?"Loading branches...":"Local branches"}),o.map(S=>l.jsx(o0,{value:S.value,className:"max-w-[28rem] truncate",children:S.label},S.value))]})})]}):c?l.jsxs("div",{className:"inline-flex h-7 min-w-0 items-center gap-0.5 px-1.5 typography-micro text-muted-foreground",children:[l.jsx(cy,{label:s,startFrom:u}),l.jsx(Wb,{branchName:r})]}):null,f?l.jsx(Zb,{checked:u,onChange:b}):null]}),p?l.jsx("div",{className:"min-w-0 shrink-0",children:p}):null]})}function TO(e){const{selectedProject:t,selectedBranchName:n,selectedBranchLabel:r,branchInteractive:s,showBranchSelector:o,showProjectSelector:i=!0,showWorktreeSelector:a=!1,worktreeMode:c=!1,onWorktreeModeChange:d,endAccessory:f,theme:u,onOpenPicker:p}=e,m=r?qb(r,EO):null;return l.jsxs("div",{className:"mb-1.5 flex min-w-0 w-full flex-col gap-0.5 pl-2 pr-1",children:[a?l.jsx("div",{className:"flex w-full justify-end",children:l.jsx(Zb,{checked:c,onChange:d,showCheck:!1,chromeLess:!0})}):null,l.jsxs("div",{className:"flex min-w-0 w-full items-center gap-x-1",children:[i?l.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:()=>p("project"),children:[l.jsx(Gc,{project:t,theme:u,maxCharacters:Ub}),l.jsx(F,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):null,o&&s?l.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:()=>p("branch"),title:r??void 0,children:[l.jsx(F,{name:"git-branch",className:"h-3 w-3 shrink-0 text-muted-foreground"}),c&&m?l.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:"from"}):null,l.jsx("span",{className:"truncate",children:m??"Branch"}),l.jsx(F,{name:"arrow-down-s",className:"h-3 w-3 shrink-0 text-muted-foreground"})]}):o?l.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:[l.jsx(F,{name:"git-branch",className:"h-3 w-3 shrink-0"}),c&&m?l.jsx("span",{className:"shrink-0 text-muted-foreground/70",children:"from"}):null,l.jsx("span",{className:"truncate",children:m??"Branch"}),l.jsx(Wb,{branchName:n})]}):null,!i&&f?l.jsx("div",{className:`min-w-0 shrink-0 ${o?"":"ml-auto"}`,children:f}):null]})]})}function AO(e){const{projects:t,selectedProject:n,selectedBranchName:r,branchOptions:s,branchInteractive:o,onProjectChange:i,onBranchChange:a,theme:c,openPicker:d,onOpenPickerChange:f,showProjectSelector:u=!0,showBranchSelector:p,query:m="",onQueryChange:g}=e,[b,y]=h.useState("");h.useEffect(()=>{d!=="project"&&y(""),d!=="branch"&&g?.("")},[g,d]);const S=h.useMemo(()=>{const x=b.trim().toLowerCase();return x?t.filter(k=>Bm(k).toLowerCase().includes(x)||k.path.toLowerCase().includes(x)):t},[b,t]),v=h.useMemo(()=>{const x=m.trim().toLowerCase();return x?s.filter(k=>k.label.toLowerCase().includes(x)):s},[s,m]);return l.jsxs(l.Fragment,{children:[l.jsx(fa,{open:u&&d==="project",onClose:()=>f(null),title:"Project",children:l.jsxs("div",{className:"flex flex-col py-1",children:[t.length>5?l.jsx("div",{className:"px-3 pb-2 pt-1",children:l.jsx(Io,{value:b,onChange:x=>y(x.target.value),placeholder:"Search projects...",className:"h-8 typography-meta",autoFocus:!0})}):null,l.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:S.map(x=>{const k=x.id===n.id;return l.jsxs("button",{type:"button",onClick:()=>{i(x.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)] ${x.kind==="worktree"?"pl-7 ":""}${k?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[l.jsx(Gc,{project:x,theme:c}),k?l.jsx(F,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},x.id)})})]})}),l.jsx(fa,{open:o&&p&&d==="branch",onClose:()=>f(null),title:"Branch",children:l.jsxs("div",{className:"flex flex-col py-1",children:[s.length>5?l.jsx("div",{className:"px-3 pb-2 pt-1",children:l.jsx(Io,{value:m,onChange:x=>g?.(x.target.value),placeholder:"Search branches...",className:"h-8 typography-meta",autoFocus:!0})}):null,l.jsx("div",{className:"max-h-[60vh] overflow-y-auto px-2",children:v.map(x=>{const k=x.value===r;return l.jsxs("button",{type:"button",onClick:()=>{a(x.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)] ${k?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[l.jsx("span",{className:"truncate",children:x.label}),k?l.jsx(F,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},x.value)})})]})})]})}function LO(e){const{state:t,onCancel:n,onConfirm:r}=e,s=t?.phase==="checking",o=t?.phase==="terminal-error";return l.jsx(Td,{open:t!==null,onOpenChange:i=>{!i&&!s&&n()},children:l.jsxs(Ad,{showCloseButton:!1,className:"max-w-md gap-5",children:[l.jsxs(Ld,{children:[l.jsx(Nd,{children:o?"Branch checkout needs attention":"Check out branch?"}),l.jsx(im,{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?l.jsxs("section",{"aria-live":"polite",className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[l.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`}),l.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."}),l.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=>l.jsx("li",{children:i.title??"Untitled session"},i.id))}),t.activeSessionsChanged?l.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?l.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?l.jsx("p",{role:"alert",className:"typography-ui-label text-status-error",children:t.error}):null,l.jsxs(BI,{children:[l.jsx(Me,{variant:"outline",onClick:n,disabled:s,children:o?"Close":"Cancel"}),o?null:l.jsx(Me,{onClick:r,disabled:s,children:s?"Checking out...":t?.phase==="retryable-error"?"Try Again":"Check Out and Send"})]})]})})}const zm=(e,t)=>{const[n,r]=h.useState(void 0);return h.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,c=Math.max(i.getBoundingClientRect().top,a),d=o.getBoundingClientRect().bottom-c-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},Nr=e=>e.invocationName??e.name;function dy(e,t){const n=Nr(e),r=Nr(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,c,d)=>a!==e.description&&d.indexOf(a)===c);return o.length===s.length&&o.every((a,c)=>a===s[c])?e:{...e,searchAliases:o}}function NO(e,t,n,r=[]){const s=[],o=new Map,i=(a,c)=>{for(const d of a){const f=c(d),u=Nr(d),p=o.get(u);if(!p){o.set(u,{index:s.length,item:d,precedence:f}),s.push(d);continue}const m=f>p.precedence?dy(d,p.item):dy(p.item,d);s[p.index]=m,o.set(u,{index:p.index,item:m,precedence:Math.max(p.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 uy(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 RO(e,t){return Js(e.name,t)||Js(Nr(e),t)||!!(e.description&&Js(e.description,t))||!!e.searchAliases?.some(n=>Js(n,t))}function PO(e,t,n){const r=t.trim(),s=r.toLowerCase(),i=[...r?e.filter(a=>uy(a,n)&&RO(a,r)):e.filter(a=>uy(a,n))];return i.sort((a,c)=>{const d=Nr(a).toLowerCase(),f=Nr(c).toLowerCase(),u=s.length>0&&d.startsWith(s),p=s.length>0&&f.startsWith(s);return u&&!p?-1:!u&&p?1:d.localeCompare(f)}),i}function DO(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function OO(e){return`command-listbox-${e.length>0?e:"commands"}`}function ep(e,t){return`${e}-option-${t}`}function HO(e){if(!e.loading&&e.hasSelectedCommand)return ep(e.listboxId,e.selectedIndex)}const fy=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},FO=[{value:"all",label:"All"},{value:"system",label:"System"},{value:"prompts",label:"Prompts"},{value:"skills",label:"Skills"},{value:"extensions",label:"Extensions"}],Gb=h.forwardRef(({searchQuery:e,onCommandSelect:t,onClose:n,style:r,onComboboxStateChange:s},o)=>{const i=pe(N=>N.currentSessionId),c=tm(i??"").length>0,d=!!i,f=ne(N=>N.isMobile),[u,p]=h.useState("all"),m=Bn(),{commands:g,isLoading:b}=Ab(m),[y,S]=h.useState([]),[v,x]=h.useState(!1),[k,w]=h.useState(0),C=h.useRef(0),I=h.useRef(!1),_=h.useRef([]),E=h.useRef(null),M=zm(E,f),T=h.useRef(!1),A=h.useRef(null),j=h.useRef(!1),R=h.useId(),O=h.useMemo(()=>OO(DO(R)),[R]);return h.useEffect(()=>{const N=D=>{const K=D.target;!K||!E.current||E.current.contains(K)||n()};return document.addEventListener("pointerdown",N,!0),()=>{document.removeEventListener("pointerdown",N,!0)}},[n]),h.useEffect(()=>{x(b);const N=g.filter(W=>W.source==="system").filter(W=>W.invocationName==="compact"?!0:d).map(W=>({id:W.id,name:W.name,invocationName:W.invocationName,source:"system",description:W.description,isBuiltIn:!0,...W.scope?{scope:W.scope}:{}})),D=g.filter(W=>W.source!=="system").map(W=>({id:W.id,name:W.name,invocationName:W.invocationName,source:W.source,description:W.description,...W.source==="skill"?{isSkill:!0}:{},...W.scope?{scope:W.scope}:{}})),K=NO(N,D.filter(W=>W.source==="extension"),D.filter(W=>W.source==="skill"),D.filter(W=>W.source==="prompt"));S(PO(K,e,f?"all":u))},[e,d,c,g,b,u,f]),h.useEffect(()=>{w(0)},[y]),h.useEffect(()=>{C.current=k},[k]),h.useEffect(()=>{s?.({listboxId:O,activeOptionId:HO({loading:v,hasSelectedCommand:!!y[k],selectedIndex:k,listboxId:O})})},[y,O,v,s,k]),h.useEffect(()=>{_.current[k]?.scrollIntoView({block:"nearest"})},[k]),h.useImperativeHandle(o,()=>({handleKeyDown:N=>{const D=y.length;if(N==="Escape"){n();return}if(D!==0){if(N==="ArrowDown"){I.current=!0,w(K=>(K+1)%D);return}if(N==="ArrowUp"){I.current=!0,w(K=>(K-1+D)%D);return}if(N==="Enter"||N==="Tab"){const K=(C.current%D+D)%D,V=y[K];V&&t(V)}}}}),[y,n,t]),f?l.jsx("div",{ref:E,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:M!==void 0?{...r,maxHeight:M}:r,children:l.jsx(Fn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:v?l.jsx("div",{className:"flex items-center justify-center py-8",children:l.jsx(F,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):l.jsxs("div",{children:[y.map((N,D)=>{const K=D===k,V=fy(N),W=Nr(N);return l.jsx("div",{id:ep(O,D),ref:B=>{_.current[D]=B},role:"option","aria-selected":K,className:P("flex cursor-pointer items-center gap-2 rounded-lg px-3 py-1.5 typography-ui-label",K?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:B=>B.preventDefault(),onPointerDown:B=>{B.pointerType==="touch"&&(A.current={x:B.clientX,y:B.clientY},j.current=!1)},onPointerMove:B=>{if(B.pointerType!=="touch"||!A.current)return;const Z=B.clientX-A.current.x,L=B.clientY-A.current.y;Math.hypot(Z,L)>6&&(j.current=!0)},onPointerUp:B=>{if(B.pointerType!=="touch")return;const Z=j.current;A.current=null,j.current=!1,!Z&&(B.preventDefault(),B.stopPropagation(),T.current=!0,t(N))},onPointerCancel:()=>{A.current=null,j.current=!1},onClick:()=>{if(T.current){T.current=!1;return}t(N)},onMouseMove:()=>{I.current=!1,w(D)},children:l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[l.jsxs("span",{className:"min-w-0 truncate font-mono font-semibold",children:["/",W]}),V&&l.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:V})]})},N.id)}),y.length===0&&l.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})})}):l.jsxs("div",{ref:E,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:M!==void 0?{...r,maxHeight:M}:r,children:[l.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:FO.map(N=>l.jsx(Me,{variant:"chip",size:"xs","aria-pressed":u===N.value,onMouseDown:D=>D.preventDefault(),onClick:()=>p(N.value),children:N.label},N.value))}),l.jsx(Fn,{role:"listbox",id:O,"aria-label":"Commands",preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:v?l.jsx("div",{className:"flex items-center justify-center py-8",children:l.jsx(F,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):l.jsxs("div",{children:[y.map((N,D)=>{const K=D===k,V=fy(N),W=Nr(N);return l.jsx("div",{id:ep(O,D),ref:B=>{_.current[D]=B},role:"option","aria-selected":K,className:P("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",K?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:B=>B.preventDefault(),onPointerDown:B=>{B.pointerType==="touch"&&(A.current={x:B.clientX,y:B.clientY},j.current=!1)},onPointerMove:B=>{if(B.pointerType!=="touch"||!A.current)return;const Z=B.clientX-A.current.x,L=B.clientY-A.current.y;Math.hypot(Z,L)>6&&(j.current=!0)},onPointerUp:B=>{if(B.pointerType!=="touch")return;const Z=j.current;A.current=null,j.current=!1,!Z&&(B.preventDefault(),B.stopPropagation(),T.current=!0,t(N))},onPointerCancel:()=>{A.current=null,j.current=!1},onClick:()=>{if(T.current){T.current=!1;return}t(N)},onMouseMove:()=>{I.current=!1,w(D)},children:l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["/",W]}),V&&l.jsx("span",{className:P("ml-auto max-w-[45%] shrink-0 truncate text-xs leading-4",K?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:V})]}),N.description&&l.jsx("div",{className:P("mt-1 truncate text-xs leading-5",K?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:N.description}),N.source==="skill"&&N.name!==W&&l.jsx("div",{className:P("mt-0.5 truncate text-xs leading-4",K?"text-interactive-selection-foreground/60":"text-muted-foreground/80"),children:N.name})]})},N.id)}),y.length===0&&l.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),!f&&l.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"})]})});Gb.displayName="CommandAutocomplete";const VO=(e,t=200)=>{const[n,r]=U.useState(e);return U.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},BO=h.forwardRef(({searchQuery:e,onFileSelect:t,onClose:n,style:r},s)=>{const o=Tb()??"",i=it(z=>z.activeProjectId),a=it(h.useCallback(z=>z.projects.find(X=>X.id===i)?.path??null,[i])),c=h.useMemo(()=>{const z=a||o;return z?z.replace(/\\/g,"/").replace(/\/+$/,""):null},[a,o]),d=G7(h.useCallback(z=>c?z.byRoot[c]:void 0,[c])),f=K7(z=>z.searchFiles),u=VO(e,180),p=Y7(),[m,g]=h.useState([]),[b,y]=h.useState([]),[S,v]=h.useState(!1),x=h.useRef(0),[k,w]=h.useState(0),C=h.useRef(0),[I,_]=h.useState(360),[E,M]=h.useState({}),[T,A]=h.useState({}),j=h.useRef([]),R=h.useRef([]),O=h.useRef([]),N=h.useRef(null),D=ne(z=>z.isMobile),K=zm(N,D),V=(e??"").trim(),W=h.useMemo(()=>{if(!c||!d)return[];const z=[d.selectedPath,...d.openPaths.slice().reverse()].filter(se=>typeof se=="string"&&se.length>0),X=new Set,Y=V.toLowerCase();return z.filter(se=>{if(X.has(se))return!1;X.add(se);const ue=se.startsWith(`${c}/`)?se.slice(c.length+1):se;return Y?ue.toLowerCase().includes(Y):!0}).slice(0,6).map(se=>{const ue=se.replace(/\\/g,"/"),Ie=ue.split("/").filter(Boolean).pop()||ue,de=ue.startsWith(`${c}/`)?ue.slice(c.length+1):ue;return{name:Ie,path:ue,relativePath:de,extension:Ie.includes(".")?Ie.split(".").pop()?.toLowerCase():void 0}})},[V,c,d]),B=b,Z=W,L=m;h.useEffect(()=>{const z=X=>{const Y=X.target;!Y||!N.current||N.current.contains(Y)||n()};return document.addEventListener("pointerdown",z,!0),()=>{document.removeEventListener("pointerdown",z,!0)}},[n]),h.useEffect(()=>{if(!o){g([]);return}const X=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!X){g([]);return}let Y=!1;return x.current++,v(!0),f(o,X,80,{includeHidden:!0,respectGitignore:!p,type:"file"}).then(ce=>{if(Y)return;const se=new Set(W.map(ue=>ue.path));g(ce.filter(ue=>!se.has(ue.path)).slice(0,15))}).catch(()=>{Y||g([])}).finally(()=>{Y||(x.current--,x.current<=0&&(x.current=0,v(!1)))}),()=>{Y=!0,x.current=Math.max(0,x.current-1),x.current<=0&&v(!1)}},[o,u,W,f,p]),h.useEffect(()=>{if(!o){y([]);return}const X=(u??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!X){y([]);return}let Y=!1;return x.current++,v(!0),f(o,X,20,{includeHidden:!0,respectGitignore:!p,type:"directory"}).then(ce=>{Y||y(ce.slice(0,10))}).catch(()=>{Y||y([])}).finally(()=>{Y||(x.current--,x.current<=0&&(x.current=0,v(!1)))}),()=>{Y=!0,x.current=Math.max(0,x.current-1),x.current<=0&&v(!1)}},[o,u,f,p]),h.useEffect(()=>{w(0),M({}),A({})},[L,B,Z.length]),h.useEffect(()=>{C.current=k},[k]),h.useEffect(()=>{j.current[k]?.scrollIntoView({block:"nearest"})},[k]),h.useEffect(()=>{let z=null;const X=()=>{z!==null&&cancelAnimationFrame(z),z=requestAnimationFrame(()=>{const Y={},ce={};R.current.forEach((se,ue)=>{if(!se)return;const de=O.current[ue]?.offsetWidth??se.scrollWidth,Fe=Math.max(0,de-se.clientWidth),$e=Fe>8;if(Y[ue]=$e,$e){const Xe=Math.max(.6,Fe/110);ce[ue]=Xe}}),M(Y),A(ce)})};return X(),window.addEventListener("resize",X),()=>{z!==null&&cancelAnimationFrame(z),window.removeEventListener("resize",X)}},[L,B]),h.useEffect(()=>{const z=R.current[k];if(!z)return;const X=()=>{const ce=z.clientWidth;ce>0&&_(ce)};if(X(),typeof ResizeObserver>"u")return;const Y=new ResizeObserver(X);return Y.observe(z),()=>{Y.disconnect()}},[k]);const $=h.useCallback(z=>{t(z)},[t]);h.useImperativeHandle(s,()=>({handleKeyDown:z=>{if(z==="Escape"){n();return}const X=B.length+Z.length+L.length;if(X!==0){if(z==="ArrowDown"){w(Y=>(Y+1)%X);return}if(z==="ArrowUp"){w(Y=>(Y-1+X)%X);return}if(z==="Enter"||z==="Tab"){const ce=(C.current%X+X)%X;if(ce<B.length){const Ie=B[ce];Ie&&$(Ie);return}const se=ce-B.length,ue=se<Z.length?Z[se]:L[se-Z.length];ue&&$(ue)}}}}),[L,B,Z,n,$]);const G=z=>{switch(z.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return l.jsx(F,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-info)]"});case"json":return l.jsx(F,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-warning)]"});case"md":case"mdx":return l.jsx(F,{name:"file",className:"h-3.5 w-3.5 text-muted-foreground"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return l.jsx(F,{name:"file-image",className:"h-3.5 w-3.5 text-[var(--status-success)]"});default:return l.jsx(F,{name:"file-pdf",className:"h-3.5 w-3.5 text-muted-foreground"})}},Q=(z,X,Y)=>{const ce=z.relativePath||z.name,se=$1(ce,{maxLength:60}),ue=k===X,Ie=E[X]??!1,de=T[X]??2.6;return l.jsxs("div",{ref:Fe=>{j.current[X]=Fe},className:P("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ue&&"bg-interactive-selection"),onClick:()=>$(z),onMouseMove:()=>w(X),children:[G(z),l.jsxs("span",{ref:Fe=>{R.current[X]=Fe},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:ue?{"--file-mention-marquee-width":`${I}px`,"--file-mention-marquee-duration":`${de}s`}:void 0,"aria-label":ce,children:[l.jsx("span",{ref:Fe=>{O.current[X]=Fe},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:ce}),Ie&&ue?l.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:ce}):l.jsx("span",{className:"block truncate",children:se})]})]},Y)};return l.jsxs("div",{ref:N,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:K!==void 0?{...r,maxHeight:K}:r,children:[l.jsx(Fn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-0",children:S?l.jsx("div",{className:"flex items-center justify-center py-4",children:l.jsx(F,{name:"refresh",className:"h-4 w-4 animate-spin text-muted-foreground"})}):l.jsxs("div",{className:"pb-2",children:[B.map((z,X)=>{const Y=X,ce=z.relativePath||z.name,se=$1(ce,{maxLength:60}),ue=k===Y;return l.jsxs("div",{ref:Ie=>{j.current[Y]=Ie},className:P("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ue&&"bg-interactive-selection"),onClick:()=>$(z),onMouseMove:()=>w(Y),children:[l.jsx(F,{name:"folder-3-fill",className:"h-3.5 w-3.5 text-primary/60"}),l.jsx("span",{className:"flex-1 min-w-0 truncate","aria-label":ce,children:se})]},`dir-${z.path}`)}),B.length>0&&(Z.length>0||L.length>0)&&l.jsx("div",{className:"my-1 border-t border-border/60"}),Z.map((z,X)=>Q(z,B.length+X,`recent-${z.path}`)),Z.length>0&&L.length>0&&l.jsx("div",{className:"my-1 border-t border-border/60"}),L.map((z,X)=>Q(z,B.length+Z.length+X,z.path)),L.length===0&&B.length===0&&Z.length===0&&l.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No matches found"})]})}),!D&&l.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});function $O(e){const t=(e.description||e.content).replace(/\s+/g," ").trim();return t.length>140?`${t.slice(0,140).trimEnd()}…`:t}const Kb=h.forwardRef(({searchQuery:e,onSnippetSelect:t,onClose:n,style:r},s)=>{const o=h.useRef(null),i=ne(I=>I.isMobile),a=zm(o,i),[c,d]=h.useState(0),f=h.useRef(0),[u,p]=h.useState([]),m=h.useRef([]),g=Cr(I=>I.snippets),b=Cr(I=>I.loadSnippets),y=Bn(),S=Cr(I=>I.setSnippetDraft),v=Cr(I=>I.setSelectedSnippet),x=ne(I=>I.setSettingsDialogOpen),k=ne(I=>I.setSettingsPage);h.useEffect(()=>{b(y)},[b,y]),h.useEffect(()=>{const I=e.trim(),E=[...I.length?g.filter(M=>Js(M.name,I)||M.aliases.some(T=>Js(T,I))):g].sort((M,T)=>M.source==="project"&&T.source!=="project"?-1:M.source!=="project"&&T.source==="project"?1:M.name.localeCompare(T.name));p(E),d(E.length?1:0)},[e,g]),h.useEffect(()=>{f.current=c,m.current[c]?.scrollIntoView({block:"nearest"})},[c]),h.useEffect(()=>{const I=_=>{const E=_.target;E&&o.current&&!o.current.contains(E)&&n()};return document.addEventListener("pointerdown",I,!0),()=>document.removeEventListener("pointerdown",I,!0)},[n]);const w=h.useCallback(I=>{const _=e.trim(),E=I.aliases.includes(_)?_:I.name;t(I,E)},[t,e]),C=h.useCallback(()=>{const I=new Set(g.map(M=>M.name));let _="new-snippet",E=1;for(;I.has(_);)_=`new-snippet-${E++}`;S({name:_,scope:"global"}),v(null),k("snippets"),x(!0),n()},[n,v,x,k,S,g]);return h.useImperativeHandle(s,()=>({handleKeyDown:I=>{if(I==="Escape"){n();return}const _=u.length+1;if(I==="ArrowDown"){d(E=>(E+1)%_);return}if(I==="ArrowUp"){d(E=>(E-1+_)%_);return}if(I==="Enter"||I==="Tab"){if(f.current===0){C();return}const E=u[f.current-1];E&&w(E)}}}),[w,u,n,C]),l.jsxs("div",{ref:o,role:"listbox","aria-label":"Snippets","aria-activedescendant":c===0?"snippet-option-new":`snippet-option-${c}`,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:[l.jsxs(Fn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:[l.jsx("div",{id:"snippet-option-new",ref:I=>{m.current[0]=I},role:"option","aria-selected":c===0,className:P("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",c===0?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:I=>I.preventDefault(),onClick:C,onMouseMove:()=>d(0),children:l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"typography-ui-label font-medium",children:"Create a new snippet"}),l.jsx("div",{className:P("mt-1 text-xs leading-5",c===0?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:"Save reusable text for the # picker"})]})}),u.length?u.map((I,_)=>{const E=_+1,M=E===c,T=I.source==="project"?"Project":"Global",A=$O(I);return l.jsx("div",{id:`snippet-option-${E}`,ref:j=>{m.current[E]=j},role:"option","aria-selected":M,className:P("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",M?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:j=>j.preventDefault(),onClick:()=>w(I),onMouseMove:()=>d(E),children:l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsxs("span",{className:"min-w-0 truncate font-mono typography-ui-label font-medium",children:["#",I.name]}),l.jsx("span",{className:P("ml-auto shrink-0 text-xs leading-4",M?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:T})]}),A?l.jsx("div",{className:P("mt-1 truncate text-xs leading-5",M?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:A}):null]})},`${I.source}:${I.id}`)}):l.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No snippets found"})]}),!i&&l.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"})]})});Kb.displayName="SnippetAutocomplete";const zO={mention:520,command:520,snippet:520};function UO(e,t){if(t)return{left:`${t.left}px`,top:`${t.top}px`,bottom:"auto",width:`min(${zO[e]}px, calc(100% - ${t.left+8}px))`,maxHeight:`${t.maxHeight}px`,transform:t.place==="above"?"translateY(-100%)":void 0}}function qO(e){const{open:t,query:n,overlayPosition:r,onClose:s}=e;if(!t)return null;const o=UO(t,r);switch(t){case"command":return l.jsx(Gb,{ref:e.commandRef,searchQuery:n,onCommandSelect:e.onCommandSelect,onClose:s,style:o,onComboboxStateChange:e.onCommandComboboxStateChange});case"snippet":return l.jsx(Kb,{ref:e.snippetRef,searchQuery:n,onSnippetSelect:e.onSnippetSelect,onClose:s,style:o});case"mention":return l.jsx(BO,{ref:e.mentionRef,searchQuery:n,onFileSelect:e.onFileSelect,onClose:s,style:o})}}function ZO(e){return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...e,children:[l.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"}),l.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 WO=h.memo(function(t){const{isMobile:n,footerIconButtonClass:r,sendIconSizeClass:s,stopIconSizeClass:o,canSend:i,disabledReason:a,canAbort:c,hasContent:d,currentSessionId:f,newSessionDraftOpen:u,isSending:p=!1,onPrimaryAction:m,onQueueMessage:g,onAbort:b}=t,y=l.jsx("button",{type:n?"button":"submit",disabled:!i||!f&&!u||p,onClick:S=>{n&&(S.preventDefault(),m())},className:P(r,i&&(f||u)&&!p?"text-primary hover:text-primary":"opacity-30",p&&"animate-pulse"),"aria-label":p?"Creating session…":a||"Send message",title:p?"Creating session…":a||void 0,children:p?l.jsx(F,{name:"loader-4",className:P(s,"animate-spin")}):l.jsx(F,{name:"send-plane-2",className:P(s)})});return c?l.jsxs("div",{className:"relative",children:[d?l.jsx("button",{type:"button",disabled:!f||!i,onClick:S=>{n&&S.preventDefault(),g()},className:P(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:l.jsx(F,{name:"send-plane-2",className:P(s,"-rotate-90")})}):null,l.jsx("button",{type:"button",onClick:b,className:P(r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:l.jsx(ZO,{className:P(o)})})]}):y},(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),GO=h.memo(function(t){const{footerIconButtonClass:n,iconSizeClass:r,handlePickLocalFiles:s,onOpenSettings:o,isAttachmentDisabled:i,disabled:a=!1,onLinkGitHub:c}=t;return l.jsxs("div",{className:"flex items-center gap-x-1.5",children:[l.jsx("div",{className:"relative inline-flex",children:t.onOpenMobileSheet?l.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:l.jsx(F,{name:"add-circle",className:P(r,"text-current")})}):l.jsxs(Pd,{onOpenChange:t.onMenuOpenChange,children:[l.jsx(Dd,{asChild:!0,children:l.jsx("button",{type:"button",className:n,title:"Add attachment","aria-label":"Add attachment",disabled:i,children:l.jsx(F,{name:"add-circle",className:P(r,"text-current")})})}),l.jsxs(Od,{align:"start",children:[l.jsxs(Qs,{onSelect:()=>{requestAnimationFrame(s)},children:[l.jsx(F,{name:"attachment-2"}),"Attach files"]}),c?l.jsxs(Qs,{onSelect:()=>{requestAnimationFrame(c)},children:[l.jsx(F,{name:"github"}),"Link issue / pull request"]}):null]})]})}),o?l.jsx("button",{type:"button",onClick:o,className:n,title:"Model and agent settings","aria-label":"Model and agent settings",disabled:a,children:l.jsx(F,{name:"ai-agent",className:P(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 KO(e){const{isMobile:t,isInline:n,alignToolsEnd:r,sessionId:s,newSessionDraftOpen:o,children:i,leadingExtra:a,trailingExtra:c,actionsOverride:d,footerPaddingClass:f,footerGapClass:u,footerIconButtonClass:p,iconSizeClass:m,sendIconSizeClass:g,stopIconSizeClass:b,canSend:y,disabledReason:S,canAbort:v,hasContent:x,isSending:k=!1,isAttachmentDisabled:w,onOpenSettings:C,onPickLocalFiles:I,onLinkGitHub:_,onPrimaryAction:E,onQueueMessage:M,onAbort:T}=e,A=l.jsx(GO,{footerIconButtonClass:p,iconSizeClass:m,handlePickLocalFiles:I,onLinkGitHub:_,onOpenSettings:C,onOpenMobileSheet:t?I:void 0,disabled:k,isAttachmentDisabled:w}),j=d??l.jsx(WO,{isMobile:t,footerIconButtonClass:p,sendIconSizeClass:g,stopIconSizeClass:b,canSend:y,disabledReason:S,canAbort:v,hasContent:x,isSending:k,currentSessionId:s,newSessionDraftOpen:o,onPrimaryAction:E,onQueueMessage:M,onAbort:T});if(t)return l.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[l.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),l.jsx("div",{className:P("flex-shrink-0",f,"flex items-center gap-x-1.5"),"data-chat-input-footer":"true",children:l.jsxs("div",{className:"flex w-full items-center justify-between gap-x-1.5",children:[l.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:[A,a?l.jsx("div",{className:P("w-max shrink-0",k&&"pointer-events-none opacity-60"),inert:k||void 0,children:a}):null]}),l.jsxs("div",{className:"flex min-w-0 shrink-0 items-center justify-end gap-x-1",children:[c,j]})]})})]});if(n){const R=r?"self-end":"self-center";return l.jsxs("div",{className:P("grid grid-cols-[auto_minmax(0,1fr)_auto] bg-transparent",f,u),"data-chat-input-footer":"true",children:[l.jsx("div",{className:P("flex min-w-0 items-center",u,R),children:A}),l.jsx("div",{className:"min-w-0",children:i}),l.jsxs("div",{className:P("flex min-w-0 items-center justify-end",u,R),children:[c,j]})]})}return l.jsxs("div",{className:"flex min-h-0 flex-1 flex-col bg-transparent",children:[l.jsx("div",{className:"min-h-0 min-w-0 flex-1",children:i}),l.jsxs("div",{className:P("flex flex-shrink-0 items-center justify-between",f,u),"data-chat-input-footer":"true",children:[l.jsxs("div",{className:P("flex min-w-0 items-center",u),children:[A,a?l.jsx("div",{className:P("w-max min-w-0 shrink-0",k&&"pointer-events-none opacity-60"),inert:k||void 0,children:a}):null]}),l.jsxs("div",{className:P("flex flex-shrink-0 items-center",u),children:[c,j]})]})]})}const Yb=h.memo(({sessionId:e})=>{const t=pe(v=>v.restoreToMessage),n=pe(v=>v.forkFromMessage),r=pe(v=>v.handleSlashRedo),[s,o]=h.useState(null),[i,a]=h.useState(null),[c,d]=h.useState(!0),f=yk(e),u=f?.targetEntryId,p=h.useMemo(()=>f?f.abandoned.filter(v=>v.role==="user"):[],[f]),m="No text content",g=h.useMemo(()=>!f||p.length===0?[]:p.map(v=>({id:v.id,text:v.preview?.replace(/\s+/g," ").trim()||m})),[p,f,m]),b=g[0]?.id;h.useEffect(()=>{d(!0)},[u,b]);const y=h.useCallback(async v=>{if(!(!e||s)){o(v);try{const x=p.findIndex(w=>w.id===v),k=x>=0?p[x+1]:void 0;k?(await t(e,k.id),ke.success("Restored messages through this point")):await r(e)}catch(x){ke.error(x instanceof Error?x.message:"Failed to restore messages")}finally{o(null)}}},[p,r,t,s,e]),S=h.useCallback(async v=>{if(!(!e||i)){a(v);try{await n(e,v)}catch(x){ke.error(x instanceof Error?x.message:"Failed to fork session")}finally{a(null)}}},[n,i,e]);return!e||g.length===0?null:l.jsx("div",{className:"pb-2 w-full px-1",children:l.jsxs("div",{className:"rounded-xl border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm overflow-hidden",children:[l.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(v=>!v),"aria-expanded":!c,children:[l.jsxs("span",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:["Reverted"," messages ",g.length]}),l.jsx(F,{name:"arrow-down-s",className:P("ml-auto h-4 w-4 text-muted-foreground transition-transform",!c&&"rotate-180"),"aria-hidden":"true"})]}),!c&&l.jsx("div",{className:"px-3 pb-3 flex flex-col gap-1.5 max-h-[10.5rem] overflow-y-auto",children:g.map(v=>l.jsxs("div",{className:"flex min-w-0 items-center gap-2 py-1",children:[l.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:v.text}),l.jsxs(Me,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{S(v.id)},children:[i===v.id?l.jsx(F,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):l.jsx(F,{name:"git-branch",className:"h-3 w-3","aria-hidden":"true"}),"Fork"]}),l.jsxs(Me,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{y(v.id)},children:[s===v.id?l.jsx(F,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):l.jsx(F,{name:"arrow-go-forward",className:"h-3 w-3","aria-hidden":"true"}),"Restore"]})]},v.id))})]})})});Yb.displayName="RevertedMessageDock";const YO=({isInternalDrag:e,iconButtonBaseClass:t,iconSizeClass:n,radius:r,isAttachmentDisabled:s,onPickLocalFiles:o})=>l.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:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"inline-flex justify-center",children:l.jsx("button",{type:"button",className:t,onClick:o,disabled:s,title:"Attach files","aria-label":"Attach files",children:l.jsx(F,{name:"attachment-2",className:P(n,"text-current")})})}),l.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:e?"Drop to insert as mention":"Drop files here to attach"})]})}),XO={type:"file",multiple:!0,accept:bC};function JO({inputRef:e,onChange:t}){return l.jsx("input",{ref:e,...XO,className:"hidden",onChange:t})}function QO({available:e,disabled:t,className:n,iconClassName:r,onStart:s}){return e?l.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:n,disabled:t,onClick:s,title:"Start dictation","aria-label":"Start dictation",children:l.jsx(F,{name:"mic",className:P("size-4",r)})}):null}const eH=48,Kc=2,tH=1,hy=Kc+tH,Lf=.08,xo=512,nH=2,rH=(e,t)=>{e.values[e.cursor]=t,e.cursor=(e.cursor+1)%xo,e.count=Math.min(xo,e.count+1)},sH=(e,t)=>{const n=Math.min(e.count,t),r=(e.cursor-n+xo)%xo;return Array.from({length:n},(s,o)=>e.values[(r+o)%xo])},py=(e,t,n,r,s)=>{const o=Math.max(1,Math.round(Kc*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)),c=Math.round((n.height-a)/2);e.globalAlpha=.35+r*.65,e.fillStyle=s,e.beginPath(),e.roundRect(t,c,o,a,o/2),e.fill(),e.globalAlpha=1};function oH({subscribeLevel:e}){const t=h.useRef(null),n=h.useRef(null),r=h.useRef(null),s=h.useRef(0),o=h.useRef(""),i=h.useRef({width:0,height:0,pixelRatio:1}),a=h.useRef({values:Array.from({length:xo},()=>Lf),cursor:0,count:0}),c=h.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(hy*f.pixelRatio)),p=Math.ceil(f.width/u),m=sH(a.current,p),g=p-m.length;for(let b=0;b<p;b+=1){const y=b>=g?m[b-g]:Lf,S=f.width-Math.round(Kc*f.pixelRatio)-(p-1-b)*u;py(d,S,f,y,o.current)}},[]);return h.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 b=Math.min(nH,Math.max(1,window.devicePixelRatio||1)),y={width:Math.max(1,Math.round(g*b)),height:Math.round(eH*b),pixelRatio:b},S=i.current;S.width===y.width&&S.height===y.height&&S.pixelRatio===y.pixelRatio||(i.current=y,d.width=y.width,d.height=y.height,o.current=getComputedStyle(d).color,c())},p=new ResizeObserver(g=>{const b=g[0]?.contentRect.width;typeof b=="number"&&b>0&&u(b)});p.observe(d);const m=new MutationObserver(()=>{o.current=getComputedStyle(d).color,c()});return m.observe(document.documentElement,{attributes:!0,attributeFilter:["class","style"]}),()=>{p.disconnect(),m.disconnect(),n.current=null}},[c]),h.useEffect(()=>{const d=()=>{r.current=null;const u=t.current,p=n.current,m=i.current;if(!u||!p||m.width<=0||!o.current)return;const g=Math.max(Lf,s.current),b=Math.max(1,Math.round(hy*m.pixelRatio));m.width>b&&(p.globalCompositeOperation="copy",p.drawImage(u,b,0,m.width-b,m.height,0,0,m.width-b,m.height),p.globalCompositeOperation="source-over"),p.clearRect(Math.max(0,m.width-b),0,b,m.height),py(p,m.width-Math.round(Kc*m.pixelRatio),m,g,o.current),rH(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]),l.jsx("canvas",{ref:t,className:"h-12 w-full text-primary","aria-hidden":"true"})}const iH=e=>`${Math.floor(e/60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`;function aH({state:e,elapsedSeconds:t,buttonClassName:n,iconClassName:r,isMobile:s,onCancel:o,onDone:i}){const a=e==="recording"||e==="reconnecting";return l.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s?null:l.jsxs("div",{className:"mr-1 flex items-center gap-2 typography-ui-compact text-muted-foreground",children:[a?l.jsx("span",{className:"size-2 rounded-full bg-[var(--status-error)]","aria-hidden":"true"}):null,l.jsx("span",{className:"tabular-nums",children:iH(t)})]}),l.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:n,onClick:o,title:"Cancel dictation","aria-label":"Cancel dictation",children:l.jsx(F,{name:"close",className:P("size-4",r)})}),l.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:P(n,"text-primary hover:text-primary"),onClick:i,disabled:!a,title:"Finish dictation","aria-label":"Finish dictation",children:l.jsx(F,{name:"check",className:P("size-4",r)})})]})}function lH({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 l.jsx("div",{className:"flex h-[7rem] w-full items-center px-3 py-3",role:"group","aria-label":"Dictation recorder",children:l.jsxs("div",{className:"min-w-0 flex-1",children:[n?l.jsx(oH,{subscribeLevel:t}):l.jsx("div",{className:"flex h-12 items-center justify-center typography-ui-label text-muted-foreground",children:r}),l.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:r})]})})}const cH=3e4;let tp=null,Ti=null;const sG=()=>{tp=null,Ti=null},dH=async e=>{const t=J();if(!e?.fresh){const r=tp;if(r&&r.key===t&&Date.now()<r.expiresAt)return r.status;const s=Ti;if(s&&s.key===t)return s.promise}const n=(async()=>{const r=await Tt("/api/stt/status");if(!r.ok)throw new Error("Could not load dictation settings");const s=await r.json();return!e?.fresh&&J()===t&&(tp={key:t,status:s,expiresAt:Date.now()+cH}),s})();e?.fresh||(Ti={key:t,promise:n});try{return await n}finally{Ti?.promise===n&&(Ti=null)}},uH=`
100
- class PiChamberDictationProcessor extends AudioWorkletProcessor {
101
- constructor() {
102
- super();
103
- this.outputRate = 16000;
104
- this.step = sampleRate / this.outputRate;
105
- this.position = 0;
106
- this.source = [];
107
- this.pending = [];
108
- this.chunkSamples = 4000;
109
- this.port.onmessage = (event) => {
110
- if (event.data && event.data.type === 'flush') {
111
- if (this.pending.length > 0) {
112
- const samples = Int16Array.from(this.pending.splice(0));
113
- this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
114
- }
115
- this.port.postMessage({ type: 'flushed' });
116
- }
117
- };
118
- }
119
- process(inputs) {
120
- const input = inputs[0] && inputs[0][0];
121
- if (!input || input.length === 0) return true;
122
- let sum = 0;
123
- for (let i = 0; i < input.length; i += 1) { this.source.push(input[i]); sum += input[i] * input[i]; }
124
- this.port.postMessage({ type: 'level', value: Math.min(1, Math.sqrt(sum / input.length) * 3) });
125
- while (this.position + 1 < this.source.length) {
126
- const index = Math.floor(this.position);
127
- const fraction = this.position - index;
128
- const sample = this.source[index] + (this.source[index + 1] - this.source[index]) * fraction;
129
- const clamped = Math.max(-1, Math.min(1, sample));
130
- this.pending.push(clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767));
131
- this.position += this.step;
132
- }
133
- const consumed = Math.floor(this.position);
134
- if (consumed > 0) { this.source.splice(0, consumed); this.position -= consumed; }
135
- while (this.pending.length >= this.chunkSamples) {
136
- const samples = Int16Array.from(this.pending.splice(0, this.chunkSamples));
137
- this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
138
- }
139
- return true;
140
- }
141
- }
142
- registerProcessor('pichamber-dictation', PiChamberDictationProcessor);
143
- `,fH=16e3,my=4e3,Xb=()=>typeof window>"u"?null:window.AudioContext??window.webkitAudioContext??null,Nf=e=>{try{e?.disconnect()}catch{}};class hH{constructor(t){this.options=t}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=Xb();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([uH],{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/fH;for(;this.fallbackPosition+1<s.length;){const a=Math.floor(this.fallbackPosition),c=this.fallbackPosition-a,d=s[a]+(s[a+1]-s[a])*c,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>=my;)this.chunk(Int16Array.from(this.pendingFallback.splice(0,my)))}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),Nf(this.source),Nf(t),Nf(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 pH=()=>!!(Xb()&&navigator.mediaDevices?.getUserMedia),Rf=1,mH=300*16e3*2,gy=(e,t)=>{const n=new Uint8Array(4+t.byteLength);return new DataView(n.buffer).setUint32(0,e,!0),n.set(t,4),n},gH=()=>typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${crypto.getRandomValues(new Uint32Array(4)).join("-")}`;class yH{constructor(t,n,r){this.providerConfigId=t,this.onState=n,this.onError=r}recordingId=gH();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>mH){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===Rf&&this.socket.send(gy(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===Rf&&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 X7();if(this.cancelled||t!==this.generation)return;const r=J7(Q7().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 c=a+1;c<this.chunks.length;c+=1)r.send(gy(c,this.chunks[c]));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||e9(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!==Rf||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 vH(){const[e,t]=h.useState("idle"),[n,r]=h.useState(null),[s,o]=h.useState(!1),[i,a]=h.useState(0),c=h.useRef(null),d=h.useRef(null),f=h.useRef("local"),u=h.useRef(0),p=h.useRef(0),m=h.useCallback(async()=>{const x=await dH();f.current=x.config?.providerConfigId||"local",o(x.config?.enabled===!0&&pH())},[]);h.useEffect(()=>(m().catch(()=>{}),sn(()=>{p.current+=1,d.current?.cancel(),c.current?.stop(),d.current=null,c.current=null,t("idle"),r(null),o(!1),m().catch(()=>{})})),[m]),h.useEffect(()=>{if(!u.current||e!=="recording"&&e!=="reconnecting")return;const x=()=>a(Math.min(300,Math.floor((Date.now()-u.current)/1e3)));x();const k=window.setInterval(x,250);return()=>window.clearInterval(k)},[e]);const g=h.useCallback(x=>{r(x.message),t("error"),c.current?.stop(),c.current=null},[]),b=h.useCallback(async()=>{if(!s||e==="requesting-permission"||e==="recording"||e==="reconnecting"||e==="transcribing")return;r(null),a(0),t("requesting-permission");const x=++p.current,k=new yH(f.current,C=>{p.current===x&&t(C)},C=>{p.current===x&&g(C)}),w=new hH({onChunk:C=>k.append(C),onPermissionGranted:()=>{p.current===x&&(u.current=Date.now(),t("recording"))}});d.current=k,c.current=w;try{await w.start(),k.begin()}catch(C){if(k.cancel(),await w.stop().catch(()=>{}),p.current!==x)return;d.current=null,c.current=null,u.current=0;const I=C instanceof Error?C:new Error(String(C));throw r(I.name==="NotAllowedError"?"Microphone access was denied":I.message),t("error"),I}},[s,e,g]),y=h.useCallback(async()=>{const x=d.current,k=c.current;if(!x||!k)throw new Error("No dictation recording is active");const w=p.current;t("transcribing");try{if(await k.stop(),p.current!==w||d.current!==x)throw new Error("Dictation cancelled");c.current=null;const C=await x.finish();if(p.current!==w)throw new Error("Dictation cancelled");return d.current=null,u.current=0,t("idle"),r(null),C}catch(C){const I=C instanceof Error?C:new Error(String(C));throw p.current===w&&(r(I.message),t("error")),I}},[]),S=h.useCallback(()=>{p.current+=1,d.current?.cancel(),d.current=null,c.current?.stop(),c.current=null,u.current=0,a(0),r(null),t("idle")},[]);h.useEffect(()=>S,[S]);const v=h.useCallback(x=>c.current?.subscribeLevel(x)??(()=>{}),[]);return{state:e,error:n,available:s,elapsedSeconds:i,start:b,finish:y,cancel:S,subscribeLevel:v}}const xH=xs(()=>ft(()=>import("./GitHubLinkPicker-B0O3Vapu.js"),__vite__mapDeps([58,5,1,6,59,17,11,8,18,19,20,60,23,61,43,42])).then(e=>({default:e.GitHubLinkPicker}))),bH=xs(()=>ft(()=>import("./ToolOutputDialog-B3RRLhR3.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]))),wH=5,SH=16,CH=4,kH=560,yy=h.memo(LN),MH=h.memo(ib),IH=e=>{const t=pe.getState(),n=t.newSessionDraft?.open?t.newSessionDraft.directoryOverride:null,r=e?t.getDirectoryForSession(e)??t.currentSessionDirectory:n??tt.getState().currentDirectory;return No(J(),r,e)},Jb=({onOpenSettings:e,scrollToBottom:t})=>{const n=h.useRef(null),r=h.useRef(null),s=h.useRef({text:"",confirmedMentions:new Set}),[o,i]=h.useState(()=>{const H=pe.getState().currentSessionId,ae=IH(H),Te=vd(ae);return r.current=ae,s.current=Te,Te.text&&(n.current=Te.text),Te.text}),a=h.useRef(s.current.confirmedMentions),[c,d]=h.useState("normal"),[f,u]=h.useState(null),[p,m]=h.useState(""),[g,b]=h.useState(null),y=h.useCallback(()=>u(null),[]);h.useEffect(()=>{f!=="command"&&b(H=>H===null?H:null)},[f]);const S=f==="command"?g?.listboxId:void 0,v=!!S,[x,k]=h.useState(null),[w,C]=h.useState(null),[I,_]=h.useState(""),E=h.useRef(null),M=h.useRef(BD()).current;h.useEffect(()=>()=>{M.view?.destroy(),M.view=null},[M]);const T=h.useRef(null),A=h.useRef(0),j=h.useRef(null),R=h.useRef(!1),O=h.useRef(null),N=h.useRef(!1),D=h.useRef(null),K=h.useRef(null),V=h.useRef(null),W=h.useRef(o),B=h.useRef(r.current),Z=h.useRef((...H)=>Promise.resolve(pe.getState().sendMessage(...H))).current,L=pe(H=>H.currentSessionId),G=qe(H=>L?H.sessionLoadErrorById.get(L)?.code??null:null,void 0,L?`session:${L}`:"chrome")==="SESSION_IN_USE",Q=qe(H=>{if(!L)return;const ae=H.reducer.bySession.get(L);if(!ae)return;const Te=ae.extensionEditorOps??(ae.extensionEditor?[ae.extensionEditor]:void 0);if(!(!Te||Te.length===0))return{sessionId:L,ops:Te}},(H,ae)=>H===ae?!0:!H||!ae||H.sessionId!==ae.sessionId||H.ops.length!==ae.ops.length?!1:H.ops.every((Te,Ve)=>Te.sequence===ae.ops[Ve]?.sequence&&Te.text===ae.ops[Ve]?.text&&Te.mode===ae.ops[Ve]?.mode),L?`session:${L}`:"chrome"),z=h.useRef(new Map);h.useEffect(()=>{if(!L||!Q||Q.sessionId!==L)return;const{ops:H}=Q;if(!H||H.length===0)return;const ae=z.current.get(L)??-1,Te=H.filter(Pe=>Pe.sequence>ae);if(Te.length===0)return;let Ve=ae;for(const Pe of Te)Pe.sequence>Ve&&(Ve=Pe.sequence);let Be=-1;for(let Pe=Te.length-1;Pe>=0;Pe--)if(Te[Pe]?.mode!=="paste"){Be=Pe;break}if(Be!==-1){const Pe=Te[Be],Ye=Te.slice(Be+1).map(Un=>Un.text).join(""),wt=Pe.text+Ye;a.current.clear(),i(wt),y()}else for(const Pe of Te){const Ye=E.current;Ye?(Ye.insertText(Pe.text),Ye.focus({preventScroll:!0})):i(wt=>wt+Pe.text)}z.current.set(L,Ve),Ge().consumeExtensionEditor(L,Ve)},[y,L,Q]);const X=tt(H=>H.currentDirectory),Y=Bn()??X,ce=pe(h.useCallback(H=>L?H.getDirectoryForSession(L):null,[L])),se=J();gL({sessionId:L,directory:ce??Y,text:o}),h.useEffect(()=>(Ec(),kr.getState().loadSkills(),sn(()=>{Ec(),kr.getState().loadSkills()})),[Y]);const ue=h.useMemo(()=>No(se,ce??Y,L),[se,Y,ce,L]),Ie=pe(H=>H.newSessionDraft),de=!!Ie?.open,Fe=pe(H=>H.sendingNewSessionDraftId),$e=qx(Ie,L,Fe);pe(H=>H.openNewSessionDraft);const Xe=pe(H=>H.abortPromptSessionId),We=pe(H=>H.clearAbortPrompt),Ae=Ke(H=>H.attachedFiles),be=Ke(H=>H.addAttachedFile),te=Ke(H=>H.detachAttachedFiles),ve=Ke(H=>H.consumePendingInputText),we=Ke(H=>H.pendingStarterInsert),je=Ke(H=>H.pendingInputText),Ce=Ke(H=>H.pendingRevertText),ze=Ke(H=>H.consumePendingRevertText),ht=Ke(H=>H.consumePendingSyntheticParts),xe=pe(H=>H.acknowledgeSessionAbort),re=h.useCallback(H=>Ux(H??L??""),[L]),me=Ze(H=>H.currentProviderId),fe=Ze(H=>H.currentModelId),Se=Ze(H=>H.getModelMetadata);Ze(H=>H.modelsMetadata),Ze(H=>H.providers);const _e=me&&fe?Se(me,fe):void 0,Ee=Ze(H=>H.currentVariant),ye=ne(H=>H.isMobile),ie=vH(),ee=h.useRef({start:0,end:0}),oe=h.useRef(null),he=ie.state==="requesting-permission"||ie.state==="recording"||ie.state==="reconnecting"||ie.state==="transcribing",Ue=zd()==="mini-chat";pM();const{enabled:dt}=jd(),Lt=ye&&!dt,zt=ne(H=>H.setImagePreviewOpen),ws=ne(H=>H.inputBarOffset),Ta=ne(H=>H.isExpandedInput),Aa=ne(H=>H.setExpandedInput),Kd=ne(H=>H.setTimelineDialogOpen),{git:En}=Ca(),{currentTheme:Kt}=Vn(),Do=Tb(),Nt=Bd(Y),on=yt(H=>Y?H.directories.get(Y)?.status??null:null),Oo=yt(H=>H.ensureStatus),Ho=yt(H=>H.fetchStatus),Fo=yt(H=>H.clearDiffCache),[Ss,La]=h.useState(!1),Dr=h.useRef(async()=>{}),jn=kO({activeRuntimeKey:se,intent:Ie?.branchIntent,onReady:H=>{Dr.current(H)}}),mn=MO({taskId:Ie?.id,intent:Ie?.worktreeIntent}),[Cs,ks]=h.useState(!1),[Vt,Ms]=h.useState({open:!1,title:"",content:""}),[Ot,Or]=h.useState(!1);h.useEffect(()=>{Vt.open&&Or(!0)},[Vt.open]);const Na=h.useRef({modelKey:`${me??""}/${fe??""}`,modalitySignature:_e?.modalities?.input?.slice().sort().join(",")??null,attachmentIds:new Set});h.useEffect(()=>{const H=`${me??""}/${fe??""}`,ae=_e?.modalities?.input,Te=ae?.slice().sort().join(",")??null,Ve=Na.current,Be=Ve.modelKey!==H,Pe=Ve.modalitySignature===null&&Te!==null,Ye=Be||Pe?Ae:Ae.filter(at=>!Ve.attachmentIds.has(at.id));if(Na.current={modelKey:H,modalitySignature:Te,attachmentIds:new Set(Ae.map(at=>at.id))},!ae||Ye.length===0)return;const wt=SC(Ye,ae);if(wt.length===0)return;const Un=Array.from(new Set(wt.map(({modality:at})=>at))),cr={text:"Text",image:"Image",pdf:"PDF",audio:"Audio",video:"Video"},Ns=wt.map(({attachment:at})=>at.filename),lu=Ns.length>3?`${Ns.slice(0,3).join(", ")} (+${Ns.length-3})`:Ns.join(", ");ke.warning(`${_e.name??fe??""} does not support ${Un.map(at=>cr[at]).join(", ")} input required by ${lu}. You can still send the message, but these attachments may be ignored.`,{id:`attachment-modalities:${H}`})},[Ae,fe,_e,me]);const Is=h.useCallback(H=>{H.image&&(Ms(H),zt(!0))},[zt]),Ra=h.useCallback(H=>{Ms(ae=>({...ae,open:H})),zt(H)},[zt]);h.useEffect(()=>{!Y||!En||Oo(Y,En)},[Y,En,Oo]),h.useEffect(()=>{if(!(!Y||!En))return Vd.onGitRefreshHint(H=>{qt(H.directory)===qt(Y)&&(H.paths?.length&&Fo(Y,H.paths),Ho(Y,En,{silent:!0}))})},[Fo,Y,En,Ho]);const Vo=!1,ar=Ta&&ye,gn=ar,[Yd,Hr]=h.useState(1),$n=!ye&&!Ue,Bo=!!(de&&$n&&!gn),_s=!ye&&!gn&&!$n,lr=ye||$n?"1.5rem":"9999px",$o=ye||Cs;h.useEffect(()=>{const H=j.current;if(!H)return;const ae=Ve=>{const Be=Ve>0&&Ve<kH;ks(Pe=>Pe===Be?Pe:Be)};if(ae(H.clientWidth),typeof ResizeObserver>"u"){const Ve=()=>ae(H.clientWidth);return window.addEventListener("resize",Ve),()=>window.removeEventListener("resize",Ve)}const Te=new ResizeObserver(Ve=>{ae(Ve[0]?.contentRect.width??H.clientWidth)});return Te.observe(H),()=>Te.disconnect()},[]);const zo=h.useMemo(()=>new Set,[]),{commands:Pa}=Ab(Y),Da=h.useMemo(()=>{const H=new Set;for(const ae of Pa)H.add(ae.invocationName.toLowerCase());return H},[Pa]),Uo=Cr(H=>H.snippets),Oa=Cr(H=>H.loadSnippets);h.useEffect(()=>{Oa(Y)},[Y,Oa]);const Ha=h.useMemo(()=>{const H=new Set;for(const ae of Uo){H.add(ae.name.toLowerCase());for(const Te of ae.aliases??[])H.add(Te.toLowerCase())}return H},[Uo]),Fa=h.useMemo(()=>Ae.map(H=>H.filename),[Ae]),Xd=h.useMemo(()=>({inputMode:c,knownAgentNames:zo,confirmedMentions:a.current,knownSlashNames:Da,knownSnippetTriggers:Ha,attachmentFilenames:Fa}),[Fa,c,zo,Da,Ha]),qo=h.useCallback(H=>[...H??[]].map(ae=>({...ae,dataUrl:ae.source==="server"&&ae.serverPath?mT(ae.serverPath):ae.dataUrl})),[]),Jd=h.useCallback(H=>({sanitizedText:H,attachments:[]}),[]),Tn=h.useRef(null),q=h.useRef(!1),ge=L?bp(L,ce??Y):null,Re=ct(H=>H.followUpBehavior),He=ct(H=>H.addToQueue),rt=cO(EM(L??""));h.useEffect(()=>{W.current=o},[o]),h.useEffect(()=>{B.current=ue},[ue]);const{persistNow:nt}=uO({message:o,messageRef:W,setMessage:i,confirmedMentionsRef:a,identity:ue,persistEnabled:!0,initialDraft:{text:n.current??"",identity:r.current},onIdentityChange:()=>d("normal"),onDraftRestored:()=>E.current?.selectAll()});h.useEffect(()=>{const H=ue?Wt(ue):"";Ke.getState().activateAttachmentsDraft(H)},[ue]);const ot=Ke(H=>H.sentDraftClear);h.useEffect(()=>{if(!ot)return;const H=ue?Wt(ue):"";if(!H||ot.draftKey!==H)return;Ke.getState().consumeSentDraftClear(ot.nonce);const ae=E.current?.getValue()??W.current;YC(ot,H,ae)&&(a.current.clear(),rt.reset(),i(""))},[ot,ue,rt]);const Oe=h.useRef(de);h.useEffect(()=>{!Oe.current&&de&&requestAnimationFrame(()=>{ye?E.current?.focus({preventScroll:!0}):E.current?.focus()}),Oe.current=de},[de,ye]);const{phase:Je}=fm();h.useEffect(()=>{if(je!==null){const H=ve();H?.text&&(H.mode==="append"?i(ae=>{const Te=H.text;return Te.trim()?$D(ae,Te):ae}):H.mode==="append-inline"?i(ae=>Bb(ae,H.text)):i(H.text),setTimeout(()=>{E.current?.focus()},0))}},[je,ve]),h.useEffect(()=>{if(Ce!==null){const H=ze();H&&o.trim().length===0&&(i(H),setTimeout(()=>{E.current?.focus()},0))}},[Ce,ze,o]);const Ct=Ke(H=>H.pendingWorktreeRestore),Rt=Ke(H=>H.consumePendingWorktreeRestore);h.useEffect(()=>{if(Ct===null)return;const H=Rt();if(!H)return;const ae=yj(H,W.current??"");if(ae.ok)a.current=new Set(H.confirmedMentions),W.current=H.prompt,i(H.prompt),y(),setTimeout(()=>{E.current?.focus()},0);else{const Te=gj(ae,"pending-composer");Te&&ke.error(Te.title,{description:Te.description})}},[Ct,Rt,y]);const an=o.trim().length>0||Ae.length>0,An=!!(me&&fe),Es=xf(Ae),js=yb(),Zo=(js?"Connection lost. Waiting to reconnect — your draft is kept.":null)??(i0(Ae)?"Uploading attachments…":PA(Ae)||Ae.length>0&&!Es?"Retry or remove failed attachments":null),Fr=an&&An&&Es&&!js,Ln=!!(mn.state&&mn.state.phase!=="failed")||$e||G,Ls=!L&&!de||Ln,Cw=Je!=="idle",Wo=h.useCallback(()=>{const H=E.current?.getValue()??o;return{message:H,hasContent:H.trim().length>0||Ae.length>0}},[Ae.length,o]),Go=h.useRef(!1),Va=h.useCallback(async()=>{if(Wc()){ke.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const H=Wo();if(Go.current||!H.hasContent||!L||!ge||!xf(Ae))return;Go.current=!0;let ae;try{ae=await vx(qo(Ae))}catch{ke.error("Attachment data could not be saved for the follow-up."),Go.current=!1;return}const Te=H.message.replace(/^\n+|\n+$/g,""),Ve=L?_t.getState().getSessionAgentSelection(L)??void 0:void 0;if(!He(ge,{content:Te,attachments:ae.length>0?ae:void 0,sendConfig:me&&fe?{providerID:me,modelID:fe,agent:Ve,variant:Ee??void 0}:void 0})){Go.current=!1,ke.error("Follow-up limit reached. Remove a pending message before adding another.");return}(E.current?.getValue()??W.current)===H.message&&i(""),ae.length>0&&te(ae.map(Pe=>Pe.id)),Go.current=!1,ye||E.current?.focus()},[Wo,L,ge,Ae,qo,He,te,ye,me,fe,Ee]),kw=h.useCallback(H=>{i(H),setTimeout(()=>{E.current?.focus()},0)},[]),Mw=h.useCallback(H=>{Dr.current({queuedOnly:!0,queuedMessageId:H,delivery:"steer"})},[]),Iw=(H,ae)=>{const Te=H instanceof Error?H.message:"";return Te.toLowerCase().includes("runtime changed")?"Message failed to send. Attachments restored.":Te||ae},l1=async H=>{if(Wc()){ke.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const ae=H?.queuedOnly??!1,Te=H?.queuedMessageId,Ve=H?.delivery==="steer"?"steer":void 0,Be=ge;let Pe=null;if(!(ae&&(!Be||!Te||(Pe=ct.getState().claimQueuedMessage(Be,Te),!Pe)))){try{if(!ae&&!xf(Ae)){i0(Ae)?ke.info("Uploading attachments…"):ke.error("Retry or remove failed attachments");return}const Ye=H?.presetText!=null&&!ae?{message:H.presetText,hasContent:H.presetText.trim().length>0||Ae.length>0}:ae?{message:"",hasContent:!1}:Wo();if(ae){if(!L)return}else if(!Ye.hasContent||!L&&!de)return;const wt=ae?Pe?.sendConfig:void 0,Un=wt?.providerID??me,cr=wt?.modelID??fe,Ns=wt?.agent,lu=ae?wt?.variant:Ee;if(!Un||!cr){console.warn("Cannot send message: provider or model not selected"),ke.error("Select a provider and model before sending a message.");return}const at=pe.getState().newSessionDraft,qa=!Be&&!ae&&!Te&&at?.open===!0,Za=()=>pe.getState().newSessionDraft.id===at.id&&pe.getState().currentSessionId===null,cu=(c==="normal"?ry(Ye.message):null)?.name==="compact",_1=!!(qa&&at.worktreeIntent&&!cu),Br=_1?new Set(a.current):null;let ln=null;if(qa){if(at.id&&pe.getState().sendingNewSessionDraftId===at.id)return;if(pe.getState().setSendingNewSessionDraftId(at.id),_1){try{ln=await pj(Ae)}catch{pe.getState().sendingNewSessionDraftId===at.id&&pe.getState().setSendingNewSessionDraftId(null),ke.error("Attachment data could not be saved for the worktree send.");return}W.current="",i(""),a.current.clear(),nt(ue,"")}await new Promise($r=>{let Ut=!1;const Xt=()=>{Ut||(Ut=!0,$r())};typeof window<"u"&&typeof window.requestAnimationFrame=="function"&&window.requestAnimationFrame(()=>Xt()),setTimeout(()=>Xt(),50)})}try{const $r=!Be&&!H?.queuedOnly&&!H?.queuedMessageId&&at?.open&&!cu?at.worktreeIntent:null;let Ut=mn.getReceipt($r);if($r&&!Ut){const et=mn.request({intent:$r,prompt:Ye.message,failedSend:{prompt:Ye.message,confirmedMentions:Br?[...Br]:[],attachments:ln??[]}});if(ln&&ln.length>0&&te(ln.map(St=>St.id)),ke.info("Worktree queued",at.id?{id:`worktree-queued:${at.id}`}:void 0),pe.getState().openNewSessionDraft(),ne.getState().setActiveMainTab("chat"),Ut=await et,!Ut){if((at.id?en.getState().getEntryByKey(at.id):en.getState().getEntry($r))?.failedSend){ke.error("Worktree creation failed",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}if(Za()){if(W.current=Ye.message,a.current=Br??new Set,i(Ye.message),hs(ue,Ye.message,Br??[]),ln){const vt=Ke.getState().restoreAttachmentsForRetry(ln);if(!vt.ok){const yn=Dh({limit:vt.limit,currentCount:vt.currentCount,missingCount:vt.missingCount});ke.error(yn.title,{description:yn.description})}}}else ke.error("Worktree creation failed",{description:"Your prompt was not sent."});return}}const Xt=Ut?at.id??v3($r):null,dr=Xt?en.getState().getEntryByKey(Xt)?.failedSend??null:null,Wa=!Be&&!H?.queuedOnly&&!H?.queuedMessageId&&at?.open&&!cu?at.branchIntent:null;if(Wa&&!jn.getReceipt(Wa)){if(jn.dialogState)return;await jn.request({intent:Wa,projectId:at.selectedProjectId,continuation:H});return}const du=jn.getReceipt(Wa),E1=ae&&Be&&Pe?{target:Be,delivery:"steer",operationId:Pe.id}:Be?{target:Be,...Ve?{delivery:Ve}:{}}:Ve||du||Ut?{...Ve?{delivery:Ve}:{},...du?{branchCheckoutReceipt:du}:{},...Ut?{worktreeCreationReceipt:Ut,draftSnapshot:at}:{}}:void 0,j1=ht(),Jw=new Set(kr.getState().skills.map(et=>et.name)),uu=rO(ae&&Pe?{queued:[{content:Pe.content,attachments:Pe.attachments}],composerText:null,composerAttachments:[],syntheticTexts:j1?.map(et=>et.text)??[]}:{queued:[],composerText:Ye.hasContent?Ye.message:null,composerAttachments:mj(ln,Ae),syntheticTexts:j1?.map(et=>et.text)??[]},{parseAgentMention:et=>({text:et}),extractFileMentions:et=>{const{sanitizedText:St,attachments:vt}=Jd(et);return{text:St,attachments:vt}},sanitizeAttachments:qo,collectSkillNames:et=>tO(et,Jw),buildSkillInstruction:nO});let Ga=uu.primaryText;const{primaryAttachments:T1,additionalParts:Yo}=uu;if(uu.isEmpty){!ae&&Xt&&dr&&Ut&&xj(Xt,dr,"Prompt was empty and was not sent.")&&ke.error("Prompt was empty and was not sent.",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const Ka=()=>!Ut||Za();!ae&&Ka()&&(rt.reset(),Aa(!1)),ye&&Ka()&&E.current?.blur();const Ya=c==="normal"?ry(Ga):null;if(Ya&&await oO({command:Ya,currentSessionId:L,scrollToBottom:t,setTimelineDialogOpen:Kd,onUndoSession:async St=>{await pe.getState().handleSlashUndo(St)},onRedoSession:async St=>{await pe.getState().handleSlashRedo(St)},onCompactSession:async(St,vt)=>{try{await KM(),await YM(St,vt)}catch(yn){ke.error(Iw(yn,"Failed to compact session"))}}})){!ae&&Xt&&dr&&Ut&&bj(Xt,dr,ln,Ae),Ka()&&(nt(ue,""),i(""),a.current.clear());return}let fu=!!(qa&&Ya&&!zb(Ya.name))?{...E1,initialInputKind:"extension-command"}:E1;const A1=Be?.directory??Y,L1=await kP({newSessionDraftOpen:de,sessionId:Be?.sessionId??L,getStoreState:()=>Ge().getState()});if(L1&&Yo.push({text:MP(L1),synthetic:!0}),c!=="shell")try{const et=Cr.getState().expandText;Ga=et(Ga,A1);for(const St of Yo)St.synthetic||(St.text=et(St.text,A1))}catch(et){console.warn("[ChatInput] Failed to expand snippets, sending original text:",et)}const Qw=[...T1,...Yo.flatMap(et=>et.attachments??[])],N1=x3(ln,Ae);if(ae&&Be&&Pe){const et=ct.getState().markDeliveryAttempt(Be,Pe.id,"steer");if(!et?.streamEpoch){ct.getState().markSendUnconfirmed(Be,Pe.id,"steer"),ke.error("Follow-up status uncertain. Check status before retrying.");return}fu={...fu,streamEpoch:et.streamEpoch}}const e7=Z(Ga,Un,cr,Ns,T1,void 0,Yo.length>0?Yo:void 0,lu,c,fu);jn.clearReceipt(),typeof window>"u"?t?.():window.requestAnimationFrame(()=>{t?.()}),await e7.then(()=>{if(ae&&Be&&Pe&&ct.getState().completeQueuedSend(Be,Pe.id),!ae&&Xt&&dr&&en.getState().markWorktreePromptSucceeded(Xt,dr),!ae&&N1.length>0&&te(N1),!ae&&Ka()){const et=ue?Wt(ue):"",St=B.current,vt=St?Wt(St):"",yn=E.current?.getValue()??W.current,Xa=!yn||yn===Ye.message;et===vt?(nt(ue,Xa?"":yn),Xa&&(i(""),a.current.clear(),rt.reset()),Ke.getState().publishSentDraftClear(et,Ye.message)):nt(ue,"")}}).catch(et=>{if(ae&&Be&&Pe){if(N3(et)){ct.getState().markSendUnconfirmed(Be,Pe.id,"steer"),console.warn("Follow-up send unconfirmed:",et),ke.error("Follow-up status uncertain. Check status before retrying.");return}ct.getState().markSendFailed(Be,Pe.id)}const St=et instanceof Error?et.message:typeof et=="string"?et:String(et??""),vt=St.toLowerCase();if(console.error("Message send failed:",St||et),!ae&&Xt&&dr&&Ut){const Rs=St||"Prompt failed to send.";en.getState().markWorktreePromptFailed(Xt,dr,Rs),ke.error("Prompt failed to send",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const yn=E.current?.getValue()??W.current;if(Za()&&Ye.message&&(!yn||yn===Ye.message)&&(Br&&(a.current=Br),i(Ye.message),hs(ue,Ye.message,Br??a.current)),Za()&&ln){const Rs=Ke.getState().restoreAttachmentsForRetry(ln);if(!Rs.ok){const R1=Dh({limit:Rs.limit,currentCount:Rs.currentCount,missingCount:Rs.missingCount});ke.error(R1.title,{description:R1.description})}}const Xa=vt.includes("timeout")||vt.includes("timed out")||vt.includes("may still be processing")||vt.includes("being processed")||vt.includes("failed to fetch")||vt.includes("networkerror")||vt.includes("network error")||vt.includes("gateway timeout")||vt==="failed to send message";if(vt.includes("payload too large")||vt.includes("413")||vt.includes("entity too large")){ke.error("Attachments are too large to send. Please try reducing the number or size of images.");return}if(Xa){Qw.length>0&&ke.error("Failed to send attachments. Try fewer files or smaller images.");return}if(vt.includes("runtime changed")){ke.error("Message failed to send. Attachments remain available.");return}ke.error(St||"Message failed to send. Attachments remain available.")})}finally{qa&&pe.getState().sendingNewSessionDraftId===at.id&&pe.getState().setSendingNewSessionDraftId(null)}}finally{ae&&Be&&Pe&&ct.getState().clearSending(Be,Pe.id)}ye||E.current?.focus()}};Dr.current=l1;const c1=h.useCallback(()=>{const H=Wo(),ae=c==="normal"&&H.hasContent&&L&&Je!=="idle";Re==="queue"&&ae?Va():Re==="steer"&&ae?Dr.current({delivery:"steer"}):Dr.current()},[c,Wo,L,Je,Re,Va]),Yt=h.useCallback((H,ae,Te="manual",Ve)=>{const Be=HP(H,ae,{inputMode:c,inputSource:Te,insertedText:Ve});u(Be?.kind??null),m(Be?.query??"")},[c]),Ba=h.useCallback(H=>{const ae=()=>{try{E.current?.focus({preventScroll:!0})}catch{E.current?.focus()}E.current?.setSelection(H)};requestAnimationFrame(()=>{ae(),requestAnimationFrame(ae)}),setTimeout(ae,60)},[]),Qd=h.useCallback(H=>{const ae=H.trim();if(!ae)return;const Te=`/${ae} `,Ve=E.current,Be=Ve?.getValue()??W.current??"",Pe=Be.trim().length>0?`${Te}${Be.replace(/^\s+/,"")}`:Te,Ye=Te.length;if(Ve)try{Ve.replaceRange(0,Be.length,Pe,Ye)}catch{i(Pe),requestAnimationFrame(()=>Ve.setSelection(Ye))}else i(Pe);Yt(Pe,Ye,"manual",Te),y(),Ba(Ye)},[y,Ba,i,Yt]),eu=h.useCallback(H=>{const ae=H.trim();if(!ae)return;const Te=E.current,Ve=Te?.getValue()??W.current??"",Be=Ve.trim().length>0,Pe=Be?`${ae} ${Ve.replace(/^\s+/,"")}`:ae,Ye=Be?ae.length+1:ae.length;if(Te)try{Te.replaceRange(0,Ve.length,Pe,Ye)}catch{i(Pe),requestAnimationFrame(()=>Te.setSelection(Ye))}else i(Pe);Yt(Pe,Ye,"manual"),y(),Ba(Ye)},[y,Ba,i,Yt]);h.useEffect(()=>{if(we==null)return;const H=Ke.getState().consumePendingStarterInsert();H&&("text"in H?eu(H.text):Qd(H.name))},[we,Qd,eu]);const _w=vO({inputMode:c,setInputMode:d,message:o,setMessage:i,openAutocomplete:f,commandRef:K,snippetRef:V,mentionRef:D,composerRef:E,messageHistory:rt,updateAutocompleteState:Yt,isMobile:ye,hasContent:an,currentSessionId:L,sessionPhase:Je,followUpBehavior:Re,handleSubmit:l1,handleQueueMessage:Va}),{update:Ew}=iO({enabled:Vo,openAutocomplete:f,message:o,editorRef:E,containerRef:j}),$a=h.useCallback(()=>{Tn.current&&(clearTimeout(Tn.current),Tn.current=null),La(!0),Tn.current=setTimeout(()=>{La(!1),Tn.current=null},1800)},[]),jw=h.useCallback(()=>{We(),$a(),re(L||void 0)},[re,We,L,$a]),Tw=h.useCallback((H,ae="manual")=>{if(!H)return;const Te=E.current;if(!Te){const wt=o+H;i(wt),Yt(wt,wt.length,ae,H);return}const{start:Ve,end:Be}=Te.getSelection(),Pe=`${o.substring(0,Ve)}${H}${o.substring(Be)}`,Ye=Ve+H.length;Te.insertText(H),Yt(Pe,Ye,ae,H)},[o,Yt]),Aw=h.useCallback(()=>{const H=W.current.length;ee.current=E.current?.getSelection()??{start:H,end:H},y(),ie.start().catch(()=>{})},[y,ie]),Lw=h.useCallback(()=>{ie.finish().then(H=>{const ae=W.current,Te=ee.current,Ve=Math.min(Math.max(0,Te.start),ae.length),Be=Math.min(Math.max(Ve,Te.end),ae.length),Pe=$b(H.trim(),ae.slice(0,Ve),ae.slice(Be));if(!Pe)return;const Ye=E.current;if(Ye)Ye.replaceRange(Ve,Be,Pe,Ve+Pe.length),Ye.focus({preventScroll:!0});else{const wt=`${ae.slice(0,Ve)}${Pe}${ae.slice(Be)}`;i(wt),Yt(wt,Ve+Pe.length,"manual",Pe)}}).catch(()=>{})},[ie,Yt]);h.useEffect(()=>{ie.state!=="error"||!ie.error||oe.current===ie.error||(oe.current=ie.error,ke.error(ie.error))},[ie.error,ie.state]);const tu=h.useCallback(()=>{R.current=!1,O.current&&(clearTimeout(O.current),O.current=null)},[]),Nw=h.useCallback(()=>{R.current=!0,O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{R.current=!1,O.current=null},700)},[]),Rw=({value:H,selection:ae,fromPaste:Te,insertedText:Ve})=>{const Be=Te?Ve:"",Pe=Be.includes("@")||R.current;R.current&&tu();const Ye=Pe?"paste":"manual";if(c==="normal"&&H.startsWith("!")){const wt=H.slice(1),Un=Math.max(0,ae.start-1);d("shell"),i(wt),y();const cr=E.current;cr&&cr.getValue()!==wt?(cr.replaceRange(0,1,"",Un),y()):requestAnimationFrame(()=>E.current?.setSelection(Un));return}i(H),Yt(H,ae.start,Ye,Be)};h.useEffect(()=>()=>{tu()},[tu]);const Pw=eO({inputMode:c,enabled:!!(L||de),composerRef:E,message:o,setMessage:i,insertTextAtSelection:Tw,updateAutocompleteState:Yt,markFileMentionPasteSuppression:Nw,attachedFiles:Ae,addAttachedFile:be}),Dw=h.useCallback(H=>vT(H,Do||""),[Do]),{handleFileSelect:Ow,handleSnippetSelect:Hw,handleCommandSelect:Fw}=hO({composerRef:E,message:o,setMessage:i,updateAutocompleteState:Yt,closeAutocomplete:y,confirmedMentionsRef:a,toMentionPath:Dw});h.useEffect(()=>{L&&E.current&&!ye&&E.current.focus()},[L,ye]),h.useEffect(()=>{ye||k(null)},[ye]),h.useEffect(()=>{Xe&&Xe!==L&&We()},[Xe,L,We]),h.useEffect(()=>{N.current=!!(L||de)},[L,de]);const{isDragging:Vw,isInternalDrag:Bw,handleDragEnter:d1,handleDragOver:u1,handleDragLeave:$w,handleDragEnd:f1,handleDrop:h1,handleDropCapture:p1}=YD({enabled:!!(L||de),composerRef:E,messageRef:W,cursorPosRef:A,confirmedMentionsRef:a,setMessage:i,addAttachedFile:be}),m1=h.useRef(null),g1=h.useCallback(async H=>{const ae=Array.isArray(H)?H:Array.from(H),Te=await Promise.all(ae.map(async Ve=>{try{return await be(Ve)}catch(Be){return console.error("File attach failed",Be),!1}}));ae.length>0&&!Te.some(Boolean)&&ke.error("Failed to attach file")},[be]),y1=h.useCallback(()=>{Ls||m1.current?.click()},[Ls]),[v1,x1]=h.useState(!1),zw=h.useCallback(()=>{Ls||x1(!0)},[Ls]),Uw=h.useCallback(async H=>{const ae=H.target.files;ae&&(await g1(ae),H.target.value="")},[g1]),qw="gap-x-1.5 gap-y-0",Zw=!0,Ko=(de||!!L)&&!Ue,{projects:b1,selectedDraftProject:Vr,selectedDraftBranchLabel:nu,selectedBranchName:ru,draftBranchItems:w1,isDiscoveringDraftBranches:S1,shouldShowDraftBranchSelector:zn,worktreeMode:su,handleDraftProjectChange:C1,handleDraftBranchChange:k1,handleWorktreeModeChange:ou}=wO(Ko),M1=!!(Ko&&Vr&&(de||zn)),za=h.useMemo(()=>Ue||Nt!==!0||!on||on.isClean?!1:hb(on.files,on.diffStats,Y).length>0,[Y,on,Nt,Ue])?l.jsx(gb,{align:M1?"end":"start"}):null,iu=IO({isMobile:ye,editorRef:E,formRef:T,controlsPanelOpen:!!x,attachMenuOpen:!1}),Ww=iu.focused;h.useEffect(()=>{_("")},[w]),_O({isMobile:ye,isFullscreen:ar,isDraftScreen:de,isFocused:Ww,formRef:T,editorRef:E});const Gw=ye?"px-1.5 py-1.5":_s?"px-1.5 py-1":"px-3 py-2",Kw=ye?"h-8 w-8":"h-6 w-6",Yw="h-4 w-4",Xw=ye?"h-6 w-6":"h-5 w-5",Ua="h-[18px] w-[18px]",I1="flex cursor-pointer items-center justify-center text-foreground transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed",au=P(I1,Kw);return h.useEffect(()=>{const H=!!Xe&&Xe===L;!q.current&&H&&!Ss&&($a(),L&&xe(L)),q.current=H},[Xe,xe,L,Ss,$a]),h.useEffect(()=>()=>{Tn.current&&(clearTimeout(Tn.current),Tn.current=null)},[]),l.jsxs(l.Fragment,{children:[l.jsxs("form",{ref:T,onSubmit:H=>{H.preventDefault(),c1()},className:P("relative w-full pt-0 pb-4",Vo,ar&&"flex h-full min-h-0 flex-col pt-2",ye&&"bottom-safe-area oc-mobile-composer"),style:ye&&ws>0?{marginBottom:`${ws}px`}:void 0,children:[l.jsxs("div",{className:P("chat-input-column relative overflow-visible",gn&&"flex flex-1 min-h-0 flex-col"),children:[l.jsx(J3,{onEditMessage:kw,onSendMessage:Mw}),l.jsx(Yb,{sessionId:L,directory:ce??Y}),l.jsx(MH,{showAbortStatus:Ss,showAssistantStatus:!1,showTodos:Zw,leftAccessory:M1||de||!za?null:za}),!Lt&&Ko&&Vr&&(de||zn)?l.jsx("div",{inert:Ln||void 0,className:P(Ln&&"pointer-events-none opacity-60"),children:l.jsx(jO,{projects:b1,selectedProject:Vr,selectedBranchName:ru,selectedBranchLabel:nu,branchOptions:w1,branchInteractive:de,branchLoading:S1,showBranchSelector:zn,showProjectSelector:de,showWorktreeSelector:de&&zn,worktreeMode:su,endAccessory:za,onProjectChange:C1,onBranchChange:k1,onWorktreeModeChange:ou,theme:Kt})}):null,Lt&&Ko&&Vr&&(de||zn)?l.jsx("div",{inert:Ln||void 0,className:P(Ln&&"pointer-events-none opacity-60"),children:l.jsx(TO,{selectedProject:Vr,selectedBranchName:ru,selectedBranchLabel:nu,branchInteractive:de,showBranchSelector:zn,showProjectSelector:de,showWorktreeSelector:de&&zn,worktreeMode:su,onWorktreeModeChange:ou,endAccessory:za,theme:Kt,onOpenPicker:C})}):null,l.jsx("div",{className:P(!ye&&"contents",ye&&"relative",ar&&"flex min-h-0 flex-1 flex-col"),children:l.jsx(l.Fragment,{children:l.jsxs("div",{className:P("flex flex-col relative overflow-visible",gn&&"flex-1 min-h-0",$n&&!gn&&"min-h-[7rem]","border border-border/80","shadow-[0_4px_16px_-4px_rgb(0_0_0_/_0.12)]","focus-within:ring-1",c==="shell"?"focus-within:ring-[color:color-mix(in_srgb,var(--status-info)_45%,transparent)]":"focus-within:ring-primary/30"),style:{borderRadius:lr,backgroundColor:Kt?.colors?.surface?.subtle},ref:j,onDropCapture:p1,onDragEnter:d1,onDragOver:u1,onDragLeave:$w,onDrop:h1,onDragEnd:f1,children:[Vw&&l.jsx(YO,{isInternalDrag:Bw,iconButtonBaseClass:I1,iconSizeClass:Ua,radius:lr,isAttachmentDisabled:Ls,onPickLocalFiles:y1}),$e&&l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-20 overflow-hidden",style:{borderRadius:lr},children:l.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"})}),l.jsx(qO,{open:f,query:p,overlayPosition:null,commandRef:K,snippetRef:V,mentionRef:D,onCommandSelect:Fw,onSnippetSelect:Hw,onFileSelect:Ow,onClose:y,onCommandComboboxStateChange:b}),l.jsx(KO,{isMobile:ye,isInline:_s,alignToolsEnd:Yd>1,sessionId:L,directory:ce??Y,newSessionDraftOpen:de,messageLength:o.length,leadingExtra:$n||ye?l.jsx(yy,{keepLabels:!0,className:"w-max shrink-0",mobilePanel:ye?x:void 0,onMobilePanelChange:ye?k:void 0}):null,trailingExtra:he?null:l.jsx(QO,{available:ie.available,disabled:!L&&!de||Ln,className:au,iconClassName:Ua,onStart:Aw}),actionsOverride:he?l.jsx(aH,{state:ie.state,elapsedSeconds:ie.elapsedSeconds,buttonClassName:au,iconClassName:Ua,isMobile:ye,onCancel:ie.cancel,onDone:Lw}):void 0,radius:lr,footerPaddingClass:Gw,footerGapClass:qw,footerIconButtonClass:au,iconSizeClass:Ua,sendIconSizeClass:Yw,stopIconSizeClass:Xw,canSend:Fr&&!Ln,isSending:$e,isAttachmentDisabled:Ls,disabledReason:Zo,canAbort:Cw,hasContent:!!an,onOpenSettings:e,onPickLocalFiles:y1,onLinkGitHub:zw,onPrimaryAction:c1,onQueueMessage:Va,onAbort:jw,children:he?l.jsx(lH,{state:ie.state,subscribeLevel:ie.subscribeLevel}):l.jsxs("div",{className:P("overflow-hidden",gn&&"flex flex-1 min-h-0 flex-col"),children:[l.jsx("div",{className:"relative z-10",children:l.jsx(Y3,{onShowPopup:Is,isInline:_s,isMobile:ye})}),l.jsx("div",{className:P("relative overflow-hidden",gn&&"flex flex-1 min-h-0 flex-col"),onDragEnter:d1,onDragOver:u1,onDropCapture:p1,onDrop:h1,onDragEnd:f1,children:l.jsx(VD,{ref:E,viewStore:M,"data-testid":"chat-input",value:o,languageContext:Xd,onChange:Rw,onKeyDown:H=>(_w(H),H.defaultPrevented),onPaste:Pw,onSelectionChange:H=>{A.current=H.start,Ew()},onVisualLineCount:H=>{Hr(ae=>ae===H?ae:H)},onFocus:iu.onEditorFocus,onBlur:iu.onEditorBlur,placeholder:G?"Session is open elsewhere":L||de?c==="shell"?"Enter shell command...":Bo?"Plan, build, / for skills, @ for context":$o?"Use @ / ! # for helpers":"@ for files; / for commands, skills, and prompts; ! for shell; # for snippets":"Select or create a session to start chatting",editable:!!(L||de)&&!Ln,autoCorrect:!1,autoCapitalize:"none",spellCheck:ye,fillContainer:gn,maxLines:ye?SH:wH,boundSelector:ye?"[data-composer-bound]":void 0,boundGapPx:CH,commandComboboxExpanded:v,commandComboboxListboxId:S,commandComboboxActiveOptionId:v?g?.activeOptionId:void 0,className:P("relative z-10",_s?"min-h-0 px-1.5 py-1.5":"min-h-[52px] px-3",gn?P("h-full min-h-0",ye?"py-2.5":"py-4"):ye?Ae.length>0?"pt-1 pb-2.5":"py-2.5":_s?void 0:Ae.length>0?"pt-1.5 pb-2":"pt-3 pb-2",c==="shell"?"font-mono":"typography-markdown md:typography-ui-label")})})]})})]})})}),$n||ye?null:l.jsx("div",{className:P("mt-1.5 flex w-full shrink-0 items-center pl-2",Ln&&"pointer-events-none opacity-60"),inert:Ln||void 0,children:l.jsx(yy,{className:"w-full min-w-0"})})]}),de&&!Vo&&!ye&&!Ue?l.jsx(jb,{onInsert:H=>H.ref.type==="text"?eu(H.insertText):Qd(H.promptName),className:"chat-input-column mt-3"}):null]}),Ot?l.jsx(h.Suspense,{fallback:null,children:l.jsx(bH,{popup:Vt,onOpenChange:Ra,isMobile:ye})}):null,l.jsx(JO,{inputRef:m1,onChange:Uw}),l.jsx(LO,{state:jn.dialogState,onCancel:jn.cancel,onConfirm:()=>{jn.confirm()}}),v1&&(ce??Y)?l.jsx(h.Suspense,{fallback:null,children:l.jsx(xH,{directory:ce??Y,open:v1,onClose:()=>x1(!1)})}):null,Lt&&Ko&&Vr?l.jsx(AO,{projects:b1,selectedProject:Vr,selectedBranchName:ru,selectedBranchLabel:nu,branchOptions:w1,branchInteractive:de,branchLoading:S1,showBranchSelector:zn,showProjectSelector:de,showWorktreeSelector:de&&zn,worktreeMode:su,onProjectChange:C1,onBranchChange:k1,onWorktreeModeChange:ou,theme:Kt,openPicker:w,onOpenPickerChange:C,query:I,onQueryChange:_}):null]})};Jb.displayName="ChatInput";const pi=h.memo(Jb);function _H({label:e,className:t}){return l.jsx("span",{className:P("size-1.5 shrink-0 rounded-full bg-status-warning",t),"aria-label":e,title:e})}const EH=e=>e!=null&&e.count>0,oG=e=>EH(e.pendingInput)?"needs-input":e.isStreaming?"working":!e.isStreaming&&!e.isActive&&e.unseenCount>0?"unread":null,jH=(e,t)=>{const n=e==="approval"?"Needs approval":"Needs input";return t>1?`${n} (${t} requests)`:n},iG=e=>e===1?"A session needs input":`${e} sessions need input`,vy=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)"}),xy=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))"}),np=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)"}),by=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 wy(e){if(e<0||e>255)return"var(--foreground)";if(e<16)return np[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 TH=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;function kn(e){return e.replace(TH,"")}function Qb(e){return e.includes("\x1B")}function AH(e){if(!e)return[];if(!Qb(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.text+=a;return}}const c={text:a};n.fg&&(c.fg=n.fg),n.bg&&(c.bg=n.bg),n.bold&&(c.bold=!0),n.dim&&(c.dim=!0),n.italic&&(c.italic=!0),n.underline&&(c.underline=!0),n.strikethrough&&(c.strikethrough=!0),n.inverse&&(c.inverse=!0),t.push(c)};for(;(o=r.exec(e))!==null;){o.index>s&&i(e.slice(s,o.index)),s=r.lastIndex;const a=o[1];if(o[2]==="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=np[u],f+=1;else if(u===39)n.fg=void 0,f+=1;else if(u>=40&&u<=47)n.bg=by[u],f+=1;else if(u===49)n.bg=void 0,f+=1;else if(u>=90&&u<=97)n.fg=np[u],f+=1;else if(u>=100&&u<=107)n.bg=by[u],f+=1;else if(u===38){const p=d[f+1];if(p===5){const m=d[f+2];m!==void 0&&(n.fg=wy(m)),f+=3}else if(p===2){const m=d[f+2],g=d[f+3],b=d[f+4];m!==void 0&&g!==void 0&&b!==void 0&&(m===1&&g===1&&b in vy?n.fg=vy[b]:n.fg=`rgb(${m}, ${g}, ${b})`),f+=5}else f+=1}else if(u===48){const p=d[f+1];if(p===5){const m=d[f+2];m!==void 0&&(n.bg=wy(m)),f+=3}else if(p===2){const m=d[f+2],g=d[f+3],b=d[f+4];m!==void 0&&g!==void 0&&b!==void 0&&(m===1&&g===1&&b in xy?n.bg=xy[b]:n.bg=`rgb(${m}, ${g}, ${b})`),f+=5}else f+=1}else f+=1}}}return s<e.length&&i(e.slice(s)),t}const Sy=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},Gt=U.memo(({text:e,className:t,style:n})=>{if(e==null||e==="")return null;if(!Qb(e))return t||n?l.jsx("span",{className:t,style:n,children:e}):l.jsx(l.Fragment,{children:e});const r=AH(e);return r.length===0?null:r.length===1&&!Sy(r[0])?t||n?l.jsx("span",{className:t,style:n,children:r[0].text}):l.jsx(l.Fragment,{children:r[0].text}):l.jsx("span",{className:t,style:n,children:r.map((s,o)=>{const i=Sy(s);return i?l.jsx("span",{style:i,children:s.text},o):l.jsx(U.Fragment,{children:s.text},o)})})});Gt.displayName="AnsiText";const LH=(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}}},NH=async(e,t,n)=>{try{await Ne.respondToExtensionDialog({requestId:t.requestId,...n},{runtimeKey:J()}),Ge().dismissExtensionDialog(e,t.requestId)}catch(r){if(r instanceof lt&&r.code==="EXTENSION_DIALOG_NOT_PENDING"){Ge().dismissExtensionDialog(e,t.requestId);return}throw r}},RH=()=>{requestAnimationFrame(()=>{document.querySelector('[data-slot="composer-editor"], .chat-input-column textarea, textarea')?.focus()})},PH=(e,t)=>{const[n,r]=U.useState(()=>typeof e!="number"||e<=0?null:Math.max(0,Math.ceil(e/1e3)));return U.useEffect(()=>{if(typeof e!="number"||e<=0){r(null);return}const s=Date.now();let o=null;const i=()=>{const a=Date.now()-s,c=Math.max(0,Math.ceil((e-a)/1e3));r(c),c<=0&&o!==null&&(clearInterval(o),o=null)};return i(),o=setInterval(i,1e3),()=>{o!==null&&clearInterval(o)}},[e,t]),n},DH=e=>e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?e.value.trim().length>0:e.isContentEditable?(e.textContent??"").trim().length>0:!1:!1,OH=({request:e,onRespond:t,messageId:n,highlightedIndex:r,setHighlightedIndex:s})=>{const o=e.options??[];return l.jsxs("div",{children:[e.message&&l.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:l.jsx(Gt,{text:e.message})}),l.jsx("div",{className:"flex flex-col gap-1 max-h-60 overflow-y-auto",role:"listbox","aria-label":kn(e.title),children:o.map((i,a)=>{const c=a===r,d=a<9?a+1:void 0;return l.jsxs("button",{type:"button",role:"option","aria-selected":c,tabIndex:c?0:-1,onMouseEnter:()=>s(a),onFocus:()=>s(a),onClick:()=>t({value:i}),className:P("flex w-full items-center justify-between rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors outline-none",c?"bg-interactive-selection text-interactive-selection-foreground font-medium":"text-foreground hover:bg-interactive-hover"),children:[l.jsx("span",{className:"truncate",children:l.jsx(Gt,{text:i})}),d!==void 0&&l.jsx("span",{className:P("ml-2 shrink-0 font-mono text-xs opacity-70",c?"text-interactive-selection-foreground":"text-muted-foreground"),children:d})]},i)})})]})},HH=({request:e,onRespond:t,messageId:n})=>l.jsxs("div",{children:[e.message&&l.jsx("p",{id:n,className:"mb-3 text-sm text-muted-foreground",children:l.jsx(Gt,{text:e.message})}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(Me,{type:"button",variant:"outline",size:"sm",onClick:()=>t({confirmed:!1,cancelled:!0}),children:"No (N)"}),l.jsx(Me,{type:"button",variant:"default",size:"sm",onClick:()=>t({confirmed:!0}),children:"Yes (Y)"})]})]}),FH=({request:e,onRespond:t,messageId:n})=>{const r=e.method==="editor",[s,o]=U.useState(r?e.prefill??"":""),i=()=>{t({value:s})};return l.jsxs("div",{children:[e.message&&l.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:l.jsx(Gt,{text:e.message})}),r?l.jsx("textarea",{autoFocus:!0,value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?kn(e.placeholder):"","aria-label":kn(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())}}):l.jsx("input",{autoFocus:!0,type:"text",value:s,onChange:a=>o(a.target.value),placeholder:e.placeholder?kn(e.placeholder):"","aria-label":kn(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())}}),l.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[l.jsx(Me,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),l.jsx(Me,{type:"button",variant:"default",size:"sm",onClick:i,disabled:!r&&s.trim().length===0,children:"Submit"})]})]})},VH=({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]=U.useState(r),[i,a]=U.useState(!1),c=(e.fields??[]).filter(u=>u.required&&(s[u.id]??"").length===0),d=(e.fields??[]).filter(u=>{if(u.type!=="number")return!1;const p=s[u.id]??"";if(p.length===0)return!1;const m=Number(p);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&&(c.length>0||d.length>0);return l.jsxs("form",{onSubmit:u=>{u.preventDefault(),a(!0),!(c.length>0||d.length>0)&&t({values:{...s}})},children:[e.message&&l.jsx("p",{id:n,className:"mb-2 text-sm text-muted-foreground",children:l.jsx(Gt,{text:e.message})}),l.jsx("div",{className:"flex max-h-60 flex-col gap-2.5 overflow-y-auto",children:(e.fields??[]).map(u=>{const p=f&&u.required&&(s[u.id]??"").length===0,m=f&&d.some(v=>v.id===u.id),g=p||m,b=s[u.id]??"",y=v=>o(x=>({...x,[u.id]:v})),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"?l.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[l.jsx("input",{type:"checkbox",checked:b==="true",onChange:v=>y(v.target.checked?"true":"false"),className:"size-4"}),l.jsx("span",{children:l.jsx(Gt,{text:u.label})})]},u.id):l.jsxs("label",{className:"flex flex-col gap-1 text-sm",children:[l.jsxs("span",{className:"text-xs font-medium text-foreground",children:[l.jsx(Gt,{text:u.label}),u.required&&l.jsx("span",{"aria-hidden":"true",className:"text-status-error",children:" *"})]}),u.type==="textarea"?l.jsx("textarea",{value:b,onChange:v=>y(v.target.value),placeholder:u.placeholder?kn(u.placeholder):"",rows:2,"aria-invalid":g||void 0,className:S}):u.type==="number"?l.jsx("input",{type:"number",value:b,onChange:v=>y(v.target.value),placeholder:u.placeholder?kn(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"?l.jsx("select",{value:b,onChange:v=>y(v.target.value),"aria-invalid":g||void 0,className:S,children:(u.options??[]).map(v=>l.jsx("option",{value:v,children:v},v))}):l.jsx("input",{type:"text",value:b,onChange:v=>y(v.target.value),placeholder:u.placeholder?kn(u.placeholder):"","aria-invalid":g||void 0,className:S})]},u.id)})}),f&&l.jsx("p",{role:"alert",className:"mt-2 text-xs text-status-error",children:c.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."}),l.jsxs("div",{className:"mt-2.5 flex justify-end gap-2",children:[l.jsx(Me,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),l.jsx(Me,{type:"submit",variant:"default",size:"sm",children:"Submit"})]})]})},BH=3,$H=(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},zH=e=>qe(t=>{const n=[];for(const r of Gp(t.catalog)){if(e&&r.sessionId===e)continue;const s=t.catalog.byId.get(r.sessionId),o=s?h3(Mr(s),"Untitled session"):"Untitled session";n.push({sessionId:r.sessionId,directory:r.directory,pending:r.pending,title:o})}return n},$H,"catalog",e??""),UH=({sessions:e})=>{const t=pe(s=>s.setCurrentSession),n=e.slice(0,BH),r=e.length-n.length;return l.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:[l.jsx("ul",{className:"flex flex-col",children:n.map(s=>{const o=jH(s.pending.kind,s.pending.count);return l.jsxs("li",{className:"flex min-h-[44px] items-center gap-2 px-2 py-1",children:[l.jsx(_H,{label:o}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-foreground",title:`${s.title} — ${o}`,children:s.title}),s.pending.count>1?l.jsx("span",{className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:`${s.pending.count} requests`}):null,l.jsx(Me,{type:"button",variant:"outline",size:"sm",onClick:()=>{t(s.sessionId,s.directory)},"aria-label":`Open ${s.title}`,children:"Open"})]},s.sessionId)})}),r>0?l.jsx("p",{className:"px-2 pb-1 text-xs text-muted-foreground",children:`+${r} more`}):null]})},Cy=({sessionId:e})=>{const t=qe(v=>{const x=e??v.selectedSessionId,w=(x?v.reducer.bySession.get(x):void 0)?.extensionDialogs??[],C=w[0];if(C&&x)return{sessionId:x,request:C,queueLength:w.length};if(e!==void 0)return null;for(const[I,_]of v.reducer.bySession){const E=_.extensionDialogs,M=E[0];if(M)return{sessionId:I,request:M,queueLength:E.length}}return null},(v,x)=>v?.sessionId===x?.sessionId&&v?.request.requestId===x?.request.requestId&&v?.queueLength===x?.queueLength,"dialogs",e??""),n=pe(v=>v.currentSessionId),s=zH(e??n??null),[o,i]=U.useState(!1),[a,c]=U.useState(!1),[d,f]=U.useState(0),u=U.useRef(!1),p=U.useRef(null),m=U.useId(),g=t?`${t.sessionId}\0${t.request.requestId}`:null;U.useEffect(()=>{u.current=!1,i(!1),c(!1),f(0),g!==null&&p.current&&!p.current.contains(document.activeElement)&&!DH(document.activeElement)&&p.current.focus()},[g]);const b=PH(t?.request.timeoutMs,t?.request.requestId),y=U.useCallback(v=>{!t||o||u.current||(u.current=!0,i(!0),c(!1),NH(t.sessionId,t.request,v).then(()=>{RH()}).catch(()=>{c(!0)}).finally(()=>{u.current=!1,i(!1)}))},[o,t]),S=v=>{if(v.key==="Escape"){v.preventDefault(),v.stopPropagation(),y({cancelled:!0});return}if(t){if(t.request.method==="confirm"){if(v.key==="y"||v.key==="Y"){v.preventDefault(),y({confirmed:!0});return}if(v.key==="n"||v.key==="N"){v.preventDefault(),y({confirmed:!1,cancelled:!0});return}}if(t.request.method==="select"){const x=t.request.options??[],k=LH(v.key,d,x.length);if(!k)return;const C=(v.target instanceof HTMLElement?v.target:null)?.getAttribute("role")==="option";if(k.kind==="highlight"){v.preventDefault(),f(k.index),C&&p.current?.querySelectorAll('[role="option"]')[k.index]?.focus();return}if((v.key==="Enter"||v.key===" ")&&!C&&v.target!==v.currentTarget)return;const _=x[k.index];if(_===void 0)return;v.preventDefault(),y({value:_})}}};return!t&&s.length===0?null:l.jsxs("div",{className:"chat-input-column mb-2 flex flex-col gap-2",children:[s.length>0?l.jsx(UH,{sessions:s}):null,t?l.jsxs("div",{ref:p,role:"dialog","aria-label":kn(t.request.title),"aria-describedby":t.request.message?m:void 0,tabIndex:-1,onKeyDown:S,className:"overflow-hidden rounded-xl border border-border/80 bg-card p-3 shadow-md transition-[opacity,transform] duration-150 outline-none",children:[l.jsxs("div",{className:"mb-2.5 flex items-center justify-between gap-2 border-b border-border/40 pb-2",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[l.jsx(F,{name:"plug-2",className:"size-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-xs font-semibold uppercase tracking-wider text-foreground",children:l.jsx(Gt,{text:t.request.title})})]}),l.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.queueLength>1&&l.jsxs("span",{className:"rounded-full bg-muted px-2 py-0.5 typography-micro font-medium text-muted-foreground",children:["1 of ",t.queueLength]}),b!==null&&l.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",title:`${b}s remaining`,children:[b,"s"]}),l.jsx(Me,{type:"button",variant:"ghost",size:"xs",onClick:()=>y({cancelled:!0}),className:"h-6 px-1.5 typography-micro text-muted-foreground hover:text-foreground","aria-label":"Dismiss extension dialog",children:"Dismiss (Esc)"})]})]}),l.jsxs("div",{className:o?"pointer-events-none opacity-60":void 0,"aria-busy":o||void 0,children:[t.request.method==="select"&&l.jsx(OH,{request:t.request,onRespond:y,messageId:m,highlightedIndex:d,setHighlightedIndex:f}),t.request.method==="confirm"&&l.jsx(HH,{request:t.request,onRespond:y,messageId:m}),(t.request.method==="input"||t.request.method==="editor")&&l.jsx(FH,{request:t.request,onRespond:y,messageId:m}),t.request.method==="form"&&l.jsx(VH,{request:t.request,onRespond:y,messageId:m})]}),a&&l.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]})},qH=e=>{const t=e.replace(/[-_]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e},ZH=({sessionId:e,className:t})=>{const n=qe(d=>d.selectedSessionId),r=e??n,s=qe(d=>r?d.reducer.bySession.get(r)?.extensionWidgets:void 0,(d,f)=>d===f,r?`session:${r}`:"chrome"),o=U.useMemo(()=>[...s?.entries()??[]],[s]),[i,a]=U.useState({}),c=U.useCallback(d=>{a(f=>({...f,[d]:!f[d]}))},[]);return o.length===0?l.jsxs("div",{className:P("flex h-full flex-col items-center justify-center gap-1.5 p-6 text-center",t),"data-testid":"extensions-surface-empty",children:[l.jsx(F,{name:"plug-2","aria-hidden":"true",className:"size-6 text-muted-foreground/60"}),l.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"No extension widgets yet"}),l.jsx("p",{className:"max-w-60 typography-micro text-muted-foreground",children:"Widgets that extensions set with ctx.ui.setWidget show up here."})]}):l.jsx("div",{className:P("flex h-full min-h-0 flex-col overflow-y-auto",t),"data-testid":"extensions-surface",children:l.jsx(WH,{title:"Widgets",count:o.length,children:o.map(([d,f])=>l.jsx(GH,{title:qH(d),meta:f.placement==="belowEditor"?"below editor":"above editor",collapsed:!!i[d],onToggle:()=>c(d),testId:`extension-widget-${d}`,children:l.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,p)=>l.jsx("span",{className:"block whitespace-pre-wrap",children:l.jsx(Gt,{text:u})},p))})},d))})})},WH=({title:e,count:t,children:n})=>l.jsxs("section",{"aria-label":e,className:"border-t border-border/60 first:border-t-0",children:[l.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,l.jsx("span",{className:"tabular-nums text-muted-foreground/70",children:t})]}),l.jsx("div",{className:"flex flex-col p-1 pt-0.5",children:n})]}),GH=({title:e,meta:t,collapsed:n,onToggle:r,testId:s,children:o})=>l.jsxs("div",{"data-testid":s,children:[l.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:[l.jsx("span",{className:"inline-flex w-4 shrink-0 items-center justify-center",children:l.jsx(F,{name:n?"arrow-right-s":"arrow-down-s","aria-hidden":"true",className:"size-3.5 text-muted-foreground"})}),l.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:e,children:e}),t?l.jsx("span",{className:"shrink-0 whitespace-nowrap typography-micro text-muted-foreground",children:t}):null]}),!n&&l.jsx("div",{className:"pb-2 pl-8 pr-2 pt-0.5",children:o})]}),KH=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),ky=({sessionId:e})=>{const t=qe(u=>u.selectedSessionId),n=e??t,{isMobile:r}=Pr(),[s,o]=U.useState(!1),i=qe(u=>[...(n?u.reducer.bySession.get(n):void 0)?.extensionStatuses.entries()??[]],(u,p)=>KH(u.flat(),p.flat()),`session:${n??""}`),{widgetsCount:a,sessionDirectory:c}=qe(u=>{const p=n?u.reducer.bySession.get(n):void 0;return{widgetsCount:p?.extensionWidgets.size??0,sessionDirectory:p?.directory}},(u,p)=>u.widgetsCount===p.widgetsCount&&u.sessionDirectory===p.sessionDirectory,`session:${n??""}`);U.useEffect(()=>{a===0&&o(!1)},[a]);const d=a===0?"":a===1?"1 widget":`${a} widgets`,f=U.useCallback(()=>{if(r){o(p=>!p);return}const u=c||tt.getState().currentDirectory||"";ne.getState().openContextSurface(u,"extensions")},[r,c]);return i.length===0&&!d?null:l.jsxs("div",{className:"chat-input-column flex flex-col gap-2",children:[l.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:[l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[l.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center rounded-full bg-interactive-hover text-muted-foreground",children:l.jsx(F,{name:"plug-2",className:"size-3"})}),i.length>0&&l.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,p])=>l.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:l.jsx(Gt,{text:p})},u))})]}),d&&l.jsxs(Me,{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:[l.jsx(F,{name:"layout-right",className:"size-3"}),l.jsx("span",{children:d})]})]}),r&&s&&l.jsx("div",{className:"max-h-60 overflow-y-auto rounded-xl border border-border/80 bg-card p-2 shadow-md",children:l.jsx(ZH,{sessionId:n,className:"h-auto"})})]})},Ai=new Set,YH=200,XH=e=>{for(Ai.add(e);Ai.size>YH;){const t=Ai.values().next().value;if(t===void 0)break;Ai.delete(t)}},My=({sessionId:e})=>{const t=qe(s=>s.selectedSessionId),n=e??t,r=qe(s=>(n?s.reducer.bySession.get(n):void 0)?.extensionNotices??[],(s,o)=>s.length===o.length&&s.every((i,a)=>i.id===o[a]?.id),`session:${n??""}`);return U.useEffect(()=>{for(const s of r){if(Ai.has(s.id))continue;XH(s.id);const o=kn(s.message||"Extension notification");s.level==="error"?ke.error(o):s.level==="warning"?ke.warning(o):ke.info(o)}},[r]),null},JH=({sessionId:e})=>{const t=ne(r=>r.commandTriggers),n=h.useCallback((r,s)=>{e&&Ge().prompt(e,nv(r,s),"prompt").catch(()=>{})},[e]);return!e||t.length===0?null:l.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=>l.jsx(Me,{size:"xs",variant:"outline",disabled:!e,onClick:()=>n(r.command,r.args),title:r.combo?`${r.label} (${t9(r.combo)})`:r.label,children:r.label},r.id))})},QH=({isNewSession:e=!1})=>{const{currentTheme:t}=Vn(),n=t?.colors?.surface?.mutedForeground||"var(--muted-foreground)";return l.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[l.jsx(cm,{width:120,height:120,isAnimated:!e,className:e?"opacity-20":void 0}),e?l.jsx("span",{className:"text-body-md",style:{color:n},children:"Start a new chat"}):null]})},eF=h.memo(QH),Um=2,e4=2,tF=72,nF=(e,t=Um)=>t+Math.max(0,e),rF=(e,t,n,r=Um)=>{const s=nF(n,r);return t<=s?!1:e<t-s},sF=(e,t,n=Um)=>Math.max(0,t-n-e),oF=(e,t,n=e4)=>e+Math.max(0,Math.min(n,t)),iF=({foldedCount:e,onLoadOlder:t,onLoadAll:n})=>{const r=Math.min(e4,e),s=e>r;return l.jsx("div",{className:"chat-message-column flex flex-col items-center py-4",children:l.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[l.jsxs(Me,{type:"button",variant:"secondary",size:"sm",onClick:t,"aria-label":"Load older history",className:"gap-1.5 rounded-full px-3.5",children:[l.jsx(F,{name:"history",className:"size-3.5"}),"Load older history"]}),s?l.jsx(Me,{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]})})},aF=h.memo(iF),t4="The following tool was executed by the user",qm=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},lF=e=>{const t=e.info;return typeof t.parentID=="string"&&t.parentID.length>0?t.parentID:null},n4=e=>!e||qm(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(t4)}),r4=(e,t)=>{if(qm(e)!=="assistant")return{hide:!1,details:null};if(t&&lF(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}}},cF=(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(qm(o)==="user")break;const{hide:i,details:a}=r4(o,r);if(i){const c=typeof a?.command=="string"?a.command.trim():"";return c.length>0?c:null}}return null},ys=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},dF=e=>e.info.error?.name==="SessionRetry",uF=e=>{const t=e.text;if(typeof t=="string")return t;const n=e.content;return typeof n=="string"?n:""},fF=e=>{if(!e)return null;const t=e.info.id;return typeof t=="string"&&t.trim().length>0?t:null},hF=e=>{const t=e.info.parentID;return typeof t=="string"&&t.trim().length>0?t:null},pF=(e,t)=>{if(ys(e)!=="system")return e;const r=hF(e);return!r||!t.has(r)||e.info.clientRole==="assistant"?e:{...e,info:{...e.info,clientRole:"assistant"}}},mF=e=>!e||ys(e)!=="user"?!1:e.parts.some(t=>t?.type==="subtask"),gF=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},yF=e=>{if(ys(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:gF(e.parts[0])}},vF=(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}},xF=(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 c=a.text;if(a.synthetic===!0&&typeof c=="string"&&c.trim().startsWith(t4)){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}},Pf=(e,t)=>t?e.userMessage.info.id===t?!0:e.assistantMessages.some(n=>n.info.id===t):!1,bF=40,wF=40,SF=(e,t)=>{const n=e.reduce((a,c)=>a+(c.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}},CF=(e,t,n,r)=>n&&!r&&e.length>t.length?e:t,Zm=({text:e,isStreaming:t,identityKey:n,allowTextReplacement:r=!1})=>{const s=h.useRef(n),o=h.useRef(e);if(s.current!==n)return s.current=n,o.current=e,e;if(!t)return o.current=e,e;const i=CF(o.current,e,!0,r);return o.current=i,i},kF=e=>e.isStreaming?e.throttledTextContent:e.textContent,MF=e=>!e.isFinalized&&e.displayTextContent.trim().length===0?!1:e.displayTextContent.trim().length>0,IF=({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:"",c=typeof o.value=="string"?o.value:"",d=[i,a,c].reduce((v,x)=>x.length>v.length?x:v,""),p=n==="streaming"||n==="cooldown";us("ui.assistant_text_part.render"),p&&us("ui.assistant_text_part.render.streaming");const m=Zm({text:d,isStreaming:p,identityKey:`${t}:${e.id??"text"}`}),g=kF({textContent:d,throttledTextContent:m,isStreaming:p});n9("ui.assistant_text_part.display_len",g.length);const b=o.time,y=!!(b&&typeof b.end<"u");return!(e.type==="text"||e.type==="reasoning")||!MF({displayTextContent:g,isFinalized:y})?null:l.jsx("div",{className:P("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:l.jsx(_o,{content:g,part:e,messageId:t,isAnimated:!1,isStreaming:p,variant:e.type==="reasoning"?"reasoning":"assistant",enableFileReferences:y,onShowPopup:r})},e.id||`${t}-text`)},s4=h.memo(IF),Iy=300*1e3,Yc=({active:e,minDurationMs:t=300,className:n,children:r,style:s,title:o})=>{const i=h.useRef(e?Date.now():null),[a,c]=h.useState(e),d=h.useRef(null);e&&i.current===null&&(i.current=Date.now()),h.useEffect(()=>{if(e){if(d.current!==null&&(clearTimeout(d.current),d.current=null),i.current===null&&(i.current=Date.now()),Date.now()-i.current>=Iy){c(!1),i.current=null;return}c(!0);return}if(!a){i.current=null;return}const u=i.current??Date.now(),p=Date.now()-u;if(p>=Iy){c(!1),i.current=null;return}const m=Math.max(0,t-p);return d.current=setTimeout(()=>{c(!1),i.current=null,d.current=null},m),()=>{d.current!==null&&(clearTimeout(d.current),d.current=null)}},[e,t,a]);const f=h.useMemo(()=>{if(!a)return s;if(!s)return;const u={...s};return delete u.color,u},[a,s]);return l.jsxs("span",{className:P("transition-opacity duration-200",a&&"oc-shimmer-verb",n),style:f,title:o,children:[r,a&&typeof r=="string"?l.jsx(O3,{text:r}):null]})},_F="!text-[length:var(--text-markdown)] !leading-5 tracking-normal",jo=P("typography-markdown font-medium",_F),It=P("typography-code font-mono","!text-[length:var(--text-code)] !leading-5 tracking-normal"),rp={...r9.getCollapsedStyles(),padding:0,overflow:"visible"},_y={style:{background:"transparent",backgroundColor:"transparent"}},o4={color:"var(--status-error)"},EF={color:"var(--tools-icon)"},i4={color:"var(--status-error)"},Ea={color:"color-mix(in srgb, var(--tools-title) 72%, var(--tools-description))"},aG=`
144
- [data-diff-header],
145
- [data-diff] {
146
- [data-separator] {
147
- height: 24px !important;
148
- }
149
- }
150
- `,lG={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},jF=e=>typeof e!="string"||e.trim().length===0?"":e.split(`
151
- `).map(t=>t.replace(/^>\s?/,"").trimEnd()).filter(t=>t.trim().length>0).join(`
152
- `).trim(),Df=80,TF=40,Ey=4e3,AF=200,LF={duration:.2,ease:"easeOut"},a4=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(),l4=e=>{if(e.length<=Df)return e;const t=e.lastIndexOf(" ",Df),n=t>0?t:Df;return`${e.substring(0,n).trimEnd()}…`},NF=e=>{if(!e)return"";const t=a4(e).replace(/\s+/g," ").trim();return l4(t)},RF=e=>{const t=e.trimEnd();if(!t)return"";const n=t.lastIndexOf(`
153
- `),r=n===-1?t:t.slice(n+1);return l4(a4(r).replace(/\s+/g," ").trim())},PF=e=>{let t=1,n=0;for(let s=e.length-1;s>=0;s-=1)if(e.charCodeAt(s)===10&&(t+=1,t>TF)){n=s+1;break}const r=n>0?e.slice(n):e;return r.length<=Ey?r:r.slice(-Ey)},DF=({text:e,variant:t,onContentChange:n,blockId:r,isStreaming:s=!1,actions:o,withinActivityRail:i=!1})=>{const[a,c]=h.useState(!1),[d,f]=h.useState(!1),u=h.useRef(null),p=h.useRef(!0),m=h.useId(),g=h.useRef(s),b=h.useRef(null),y=h.useRef(null),S=h.useRef(!1),v=h.useRef(n);v.current=n;const x=h.useMemo(()=>s?RF(e):NF(e),[s,e]),k=a?"Collapse reasoning trace":"Expand reasoning trace",w=h.useCallback(()=>{f(!0),c(M=>!M),n?.("structural")},[n]),C=h.useCallback(M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),w())},[w]),I=h.useCallback(M=>{M.deltaY<0&&(p.current=!1)},[]),_=h.useCallback(M=>{const T=M.currentTarget;p.current=T.scrollHeight-T.scrollTop-T.clientHeight<=2},[]);if(h.useLayoutEffect(()=>{if(!s||!a){p.current=!0;return}const M=u.current;!M||!p.current||(M.scrollTop=M.scrollHeight)},[a,s,e]),h.useEffect(()=>{if(a){f(!0);return}if(!d)return;if(typeof window>"u"){f(!1);return}const M=window.setTimeout(()=>{f(!1)},AF);return()=>{window.clearTimeout(M)}},[a,d]),h.useLayoutEffect(()=>{const M=b.current;if(!M)return;if(y.current?.stop(),!S.current){S.current=!0,M.style.height=a?"auto":"0px",M.style.overflow=a?"visible":"hidden";return}M.style.overflow="hidden",a?M.style.height="0px":(M.style.height=`${M.scrollHeight}px`,v.current?.("animation"));const T=mS(M,{height:a?"auto":"0px"},LF);return y.current=T,T.finished.then(()=>{y.current===T&&(y.current=null,a?(M.style.overflow="visible",M.style.height="auto"):M.style.overflow="hidden")}).catch(()=>{}),()=>{T.stop(),y.current===T&&(y.current=null)}},[a]),h.useEffect(()=>()=>{y.current?.stop(),y.current=null},[]),!e||e.trim().length===0)return null;const E=l.jsxs(l.Fragment,{children:[l.jsx("div",{"data-message-text-export-source":"true",children:s?l.jsx("div",{className:"markdown-content markdown-reasoning w-full min-w-0 whitespace-pre-wrap break-words",children:PF(e)}):l.jsx(_o,{content:e,messageId:r,isAnimated:!1,isStreaming:!1,variant:"reasoning"})}),o?l.jsx("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5","data-message-actions":"true",children:l.jsx("div",{className:"flex items-center gap-1.5","data-message-action-group":"true",children:o})}):null]});return l.jsxs("div",{"data-reasoning-block-id":r,"data-message-text-export-root":"true",className:g.current?"oc-step-in":void 0,children:[l.jsxs("div",{role:"button",tabIndex:0,"aria-expanded":a,"aria-controls":m,"aria-label":k,className:P("group/tool flex items-center gap-1.5 py-1 pr-2 pl-px cursor-pointer"),"data-chat-activity-row":"true",onClick:w,onKeyDown:C,children:[l.jsxs("div",{className:"flex h-5 items-center gap-1.5 flex-shrink-0",children:[l.jsxs("div",{className:"relative flex h-5 w-3.5 items-center justify-center",children:[l.jsx("div",{className:P("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:l.jsx(F,{name:"brain-ai-3",className:"h-3.5 w-3.5"})}),l.jsx("div",{className:P("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?l.jsx(F,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):l.jsx(F,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),l.jsx(Yc,{active:s,className:P("flex h-5 items-center typography-markdown font-medium text-[length:var(--text-markdown)] leading-none tracking-normal"),style:Ea,title:t==="justification"?"Justification":"Thinking",children:t==="justification"?"Justification":"Thinking"})]}),!a&&x?l.jsx("span",{className:P("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:x,children:x}):null]}),d?l.jsx("div",{ref:b,id:m,"aria-hidden":!a,style:{height:a?"auto":"0px",overflow:a?"visible":"hidden",overflowAnchor:"none"},children:l.jsxs("div",{className:P("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:l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),l.jsx(Fn,{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?I:void 0,onScroll:s?_:void 0,children:E})]})}):null]})},OF=h.memo(({part:e,onContentChange:t,messageId:n,streamPhase:r,withinActivityRail:s=!1})=>{const o=e,i=o.text||o.content||"",a=h.useMemo(()=>jF(i),[i]),c=o.time,f=(r===void 0||r!=="completed")&&o.streaming===!0&&typeof c?.end!="number",u=Zm({text:a,isStreaming:f,identityKey:`${n}:${e.id??"reasoning"}`});return!u||u.trim().length===0?null:l.jsx(DF,{text:u,variant:"thinking",onContentChange:t,blockId:e.id||`${n}-reasoning`,time:c,isStreaming:f,withinActivityRail:s})}),jy=[{variant:"static",component:({children:e,className:t,...n})=>l.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?l.jsx("span",{className:P("inline-block align-baseline",t),children:r.split("").map((s,o)=>U.createElement(el.span,{...n,key:s+String(o),className:P("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})=>l.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[l.jsx("span",{...n,className:P("invisible",t),children:e}),l.jsx("span",{...n,className:P("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}),l.jsx("span",{...n,className:P("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 l.jsxs(el.span,{...n,className:P("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",t),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[l.jsx("div",{children:o.map((i,a)=>l.jsx(el.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:r,ease:"easeInOut",delay:s*a},children:i},String(a)))}),l.jsx("div",{className:P("absolute inset-0"),children:o.map((i,a)=>l.jsx(el.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})=>l.jsx("span",{...n,className:P("text-primary-muted hover:animate-text-shake",t),children:e})},{variant:"hover-decoration",component:({children:e,className:t,...n})=>l.jsx("div",{className:P("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:l.jsx("span",{...n,className:P("text-primary-muted",t),children:e})})}];function sr({variant:e="static",className:t,...n}){const s=jy.find(o=>o.variant===e)?.component||jy[0].component;return l.jsx(s,{...n,className:t})}const HF=600*1e3,sp=new Map,FF=e=>{const t=Bt(e);if(!t)return;const n=sp.get(t);if(n){if(n.expiresAt<=Date.now()){sp.delete(t);return}return n.outsideFileGrant}},Ty=(e,t,n)=>{const r=Bt(e);!r||!t||sp.set(r,{outsideFileGrant:t,expiresAt:Date.now()+HF})},VF=async(e,t)=>{const n=Bt(e);if(!n||!t||$d(n,t))return;const r=FF(n);if(r)return r;const s=await s9(n);if(!(!s.success||!s.path||!s.outsideFileGrant))return Ty(s.path,s.outsideFileGrant),Bt(s.path)!==n&&Ty(n,s.outsideFileGrant),s.outsideFileGrant},c4=(e,t)=>{const n=e.trim();if(n){if(kr.getState().setSelectedSkill(n),ne.getState().setSettingsPage("skills.installed"),t){t.openSettings("skills.installed");return}ne.getState().setSettingsDialogOpen(!0)}},Ay=e=>{if(!e)return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null},Ly=e=>{const t=e?.state?.status;return typeof t=="string"?t:null},Ny=e=>e?.state,Ry=e=>e?.metadata,Ll=e=>{const t=e?.time;return{start:typeof t?.start=="number"?t.start:null,end:typeof t?.end=="number"?t.end:null}},Py=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,"")},Zd=(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=Ay(r),i=Ay(s);if(o!==i)return!1;if(r.type==="tool"){if(Ny(r)!==Ny(s)||Ry(r)!==Ry(s)||Ly(r)!==Ly(s))return!1;const d=Ll(r),f=Ll(s);if(d.start!==f.start||d.end!==f.end)return!1;const u=r.tool,p=s.tool;if(u!==p)return!1;const m=r.output,g=s.output;if(m!==g)return!1;continue}const a=Ll(r),c=Ll(s);if(a.start!==c.start||a.end!==c.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(Py(r)!==Py(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},d4=(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,u4=(e,t)=>d4(e.info,t.info)&&e.info.error===t.info.error&&Zd(e.parts,t.parts),Xc=(e,t)=>e===t?!0:!e||!t?!1:d4(e.info,t.info),BF=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files,$F=(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},Wm=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&Zd([e.part],[t.part]),zF=(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(!Wm(o,i))return!1;r+=1,s+=1}},UF=(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(!Wm(e.parts[n],t.parts[n]))return!1;return!0},Dy=(e,t)=>!!e?.some(n=>n.anchorMessageId===t),qF=(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(!UF(o,i))return!1;r+=1,s+=1}},f4=(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||!zF(e.activityParts,t.activityParts,n)||!qF(e.activityGroupSegments,t.activityGroupSegments,n))return!1;const i=Dy(e.activityGroupSegments,n)||Dy(t.activityGroupSegments,n);return!((o||i)&&!BF(e.diffStats,t.diffStats)||(o||i||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!$F(e.changedFiles,t.changedFiles))},Jc=new Map,ZF=e=>{const t=Jc.get(e);if(t)return t;const n={subscribers:new Set,timerId:null};return Jc.set(e,n),n},WF=(e,t)=>{const n=ZF(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=Jc.get(e);r&&(r.subscribers.delete(t),!(r.subscribers.size>0)&&(r.timerId!==null&&typeof window<"u"&&window.clearInterval(r.timerId),Jc.delete(e)))}},h4=(e,t=250)=>{const[n,r]=h.useState(()=>Date.now());return h.useEffect(()=>{if(e)return WF(t,r)},[e,t]),n},Oy=e=>typeof e!="string"?null:e.trim()||null,GF=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 Oy(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:Oy(o.name)},ga=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"?l.jsx(F,{name:"pencil",className:t}):n==="write"||n==="create"||n==="file_write"?l.jsx(F,{name:"file-edit",className:t}):n==="read"||n==="view"||n==="file_read"||n==="cat"?l.jsx(F,{name:"file-text",className:t}):n==="bash"||n==="shell"||n==="cmd"||n==="terminal"?l.jsx(F,{name:"terminal-box",className:t}):n==="list"||n==="ls"||n==="dir"||n==="list_files"?l.jsx(F,{name:"folder-6",className:t}):n==="search"||n==="grep"||n==="find"||n==="ripgrep"?l.jsx(F,{name:"menu-search",className:t}):n==="glob"?l.jsx(F,{name:"file-search",className:t}):n==="fetch"||n==="curl"||n==="wget"||n==="webfetch"?l.jsx(F,{name:"global",className:t}):n==="web-search"||n==="websearch"||n==="search_web"||n==="codesearch"||n==="google"||n==="bing"||n==="duckduckgo"||n==="perplexity"?l.jsx(F,{name:"global",className:t}):n==="todowrite"||n==="todoread"?l.jsx(F,{name:"list-check-3",className:t}):n==="structuredoutput"||n==="structured_output"?l.jsx(F,{name:"list-check-2",className:t}):n==="skill"?l.jsx(F,{name:"book",className:t}):n==="task"?l.jsx(F,{name:"ai-agent",className:t}):n==="pichamber"?l.jsx(F,{name:"pichamber",className:t}):n==="question"?l.jsx(F,{name:"survey",className:t}):n==="lsp"?l.jsx(F,{name:"scan-2",className:t}):n==="plan_enter"?l.jsx(F,{name:"file-list-2",className:t}):n==="plan_exit"?l.jsx(F,{name:"task",className:t}):n.startsWith("git")?l.jsx(F,{name:"git-branch",className:t}):l.jsx(F,{name:"tools",className:t})},KF=({href:e})=>{const[t,n]=h.useState(!1),r=h.useMemo(()=>nE(e),[e]);return!r||t?null:l.jsx("span",{className:"inline-flex size-[18px] flex-shrink-0 items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)]",children:l.jsx("img",{src:r,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",className:"size-3.5 rounded-sm",onError:()=>n(!0)})})},YF=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"},XF=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}},JF=(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`},QF=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},eV=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},tV=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},mi=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=tV(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"}`},nV=e=>{const n=e.part.state,r=n?.input,s=n?.output;if(Array.isArray(r?.todos)){const o=mi(r.todos);if(o)return o}if(Array.isArray(s)){const o=mi(s);if(o)return o}if(s&&typeof s=="object"&&Array.isArray(s.todos)){const o=mi(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=mi(o);if(i)return i}if(o&&typeof o=="object"&&Array.isArray(o.todos)){const i=mi(o.todos);if(i)return i}}catch{}return null},rV=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)},sV=(e,t=!0)=>{const n=e.lastIndexOf("/");if(n===-1)return l.jsx(sr,{variant:t?"generate-effect":"static",className:P("min-w-0 flex-1 truncate whitespace-nowrap",It),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 l.jsxs("span",{className:P("min-w-0 inline-flex max-w-full flex-1 items-center overflow-hidden",It),title:e,children:[o?l.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,l.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),l.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),l.jsx(sr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:s})]})},oV=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"?nV(e):QF(e)},iV=({toolName:e,activity:t,animateTailText:n})=>{const r=h.useContext(wa),s=Ia(),o=tt(E=>E.currentDirectory),i=YF(t),a=XF(t),c=typeof a.start=="number",d=h4(!!(c&&i&&typeof a.end!="number"),250),f=c?JF(a.start,a.end,d):null,u=oV(t),p=GF(t.part),m=e.toLowerCase(),g=m==="skill"||m==="read"&&p!==null,b=m==="read"&&!g,y=g?"skill":e,S=Ma(y).displayName,v=ga(y),x=b?eV(t):null,k=b?rV(t):void 0,w=x?fb(x,o):null,C=h.useCallback((E,M)=>{const T=_a(o,E);if(!T)return;if(r?.editor){r.editor.openFile(T,M);return}if(s){const R=ne.getState(),O=o||Ef(o,T);M&&Number.isFinite(M)?R.openContextFileAtLine(O,T,Math.max(1,Math.trunc(M)),1):R.openContextFile(O,T),s.openFiles();return}if(!$d(T,o)){VF(T,o).then(()=>{const R=ne.getState(),O=o||Ef(o,T);if(M&&Number.isFinite(M)){R.openContextFileAtLine(O,T,Math.max(1,Math.trunc(M)),1);return}R.openContextFile(O,T)});return}const A=ne.getState(),j=Ef(o,T);if(M&&Number.isFinite(M)){A.openContextFileAtLine(j,T,Math.max(1,Math.trunc(M)),1);return}A.openContextFile(j,T)},[o,s,r]),I=m==="grep"||m==="search"||m==="find"||m==="ripgrep"||m==="glob",_=m==="webfetch"||m==="fetch"||m==="curl"||m==="wget";return l.jsxs("div",{className:P("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:[l.jsx("div",{className:"inline-flex h-5 items-center flex-shrink-0",style:{color:"var(--tools-icon)"},children:v}),l.jsx(Yc,{active:i,minDurationMs:1e3,className:P(jo,"inline-flex items-center flex-shrink-0"),style:Ea,title:S,children:S}),b&&x&&w?l.jsxs("button",{type:"button",onClick:E=>{E.preventDefault(),E.stopPropagation(),C(x,k)},className:P("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",It),style:{color:"var(--tools-description)"},title:k?`${w}:${k}`:w,children:[l.jsx(rr,{filePath:x,className:"h-3.5 w-3.5"}),sV(w,n)]}):null,I&&u!==null?l.jsx("span",{className:"inline-flex min-w-0 flex-1",children:l.jsxs(sr,{variant:n?"generate-effect":"static",className:P("min-w-0 flex-1 truncate whitespace-nowrap",It),style:{color:"var(--tools-description)"},title:u,children:['"',u,'"']})}):null,_&&u!==null?l.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:P("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",It),style:{color:"var(--status-info)"},title:u,children:[l.jsx(KF,{href:u}),l.jsx("span",{className:"min-w-0 truncate",children:u})]}):null,g&&p!==null?l.jsx("button",{type:"button",onClick:E=>{E.preventDefault(),E.stopPropagation(),c4(p,s)},className:P("inline-flex !min-h-0 h-5 min-w-0 flex-1 items-center truncate whitespace-nowrap text-left hover:opacity-90",It),style:{color:"var(--tools-description)"},title:`Open ${p} in Settings`,"aria-label":`Open ${p} skill in Settings`,children:p}):null,!b&&!I&&!_&&!g&&u!==null?l.jsx(sr,{variant:n?"generate-effect":"static",className:P("min-w-0 flex-1 truncate whitespace-nowrap",It),style:{color:"var(--tools-description)"},children:u}):null,f?l.jsx("span",{className:P("flex-shrink-0 tabular-nums text-muted-foreground/80",It),"aria-label":"Tool duration",children:f}):null]})},aV=(e,t)=>e.toolName===t.toolName&&e.animateTailText===t.animateTailText&&Wm(e.activity,t.activity),lV=h.memo(iV,aV),cV=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],cG="diffs-container";(()=>{try{return!1}catch{return!1}})();const dV=/(?=^From [a-f0-9]+ .+$)/m,p4=/(?=^diff --git)/gm,dG=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: (.*))?/m,uG=new RegExp("(?<=\\n)"),uV=/^(---|\+\+\+)\s+([^\t\r\n]+)/,fV=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,hV=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,pV=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,fG="header-prefix",hG="header-filename-suffix",pG="header-metadata",mG="header-custom",gG={dark:"pierre-dark",light:"pierre-light"},yG="data-theme-css",vG="data-unsafe-css",xG="data-diffs-scrollbar-measure",bG="--diffs-scrollbar-gutter-measured",wG=1e5,mV={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8};({...mV});const SG=Object.freeze({fromStart:0,fromEnd:0}),CG={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},kG={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0};function Hy(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}const gV=new TextEncoder,yV=new TextDecoder("utf-8",{ignoreBOM:!0}),vV=/[\uD800-\uDFFF]/,op=1024;let to=new Uint8Array(op);function m4(){to.length!==op&&(to=new Uint8Array(op))}function At(e){if(e.length===0)return e;if(vV.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;to.length<t&&(to=new Uint8Array(t));const{written:n}=gV.encodeInto(e,to);return yV.decode(to.subarray(0,n))}function xV(e,t,n){try{return bV(e,t,n)}finally{m4()}}function bV(e,t,n=!1){const r=jV(e),s=r?CV(e):kV(e);let o;const i=[];for(const a of s){if(r&&!p4.test(a)){if(o==null)o=At(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}else if(!r&&!MV(a)){if(o==null)o=At(a);else{if(n)throw Error("parsePatchContent: unknown file blob");console.error("parsePatchContent: unknown file blob:",a)}continue}const c=g4(a,{cacheKey:void 0,isGitDiff:r,throwOnError:n});c!=null&&i.push(c)}return{patchMetadata:o,files:i}}function MG(e,t){try{return g4(e,t)}finally{m4()}}function g4(e,{cacheKey:t,isGitDiff:n=p4.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let i=0;const a=b4(e,"@@ ");let c;const d=r==null||s==null;let f=0,u=0;for(const p of a){const m=y4(p),g=m[0];if(g==null){if(o)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",p);continue}const b=x4(g);let y=0,S=0;if(b==null||c==null){if(c!=null){if(o)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",p);continue}c={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:d,additionLines:!d&&r!=null&&s!=null?Fy(s.contents):[],deletionLines:!d&&r!=null&&s!=null?Fy(r.contents):[],cacheKey:$y(t)},c.additionLines.length===1&&s?.contents===""&&(c.additionLines.length=0),c.deletionLines.length===1&&r?.contents===""&&(c.deletionLines.length=0);for(const E of m){if(E.startsWith("diff --git")){const T=E.trim().match(hV),A=T?.[1]??T?.[2],j=T?.[3]??T?.[4];if(A==null||j==null){if(o)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",E);continue}c.name=At(j.trim()),A!==j&&(c.prevName=At(A.trim()));continue}const M=E.startsWith("---")||E.startsWith("+++")?E.match(n?fV:uV):null;if(M!=null){const[,T,A]=M;if(T==="---"&&A!=="/dev/null"){const j=At(A.trim());c.prevName=j,c.name=j}else T==="+++"&&A!=="/dev/null"&&(c.name=At(A.trim()))}else if(n){if(E.startsWith("new mode ")&&(c.mode=At(E.slice(8).trim())),E.startsWith("old mode ")&&(c.prevMode=At(E.slice(8).trim())),E.startsWith("new file mode")&&(c.type="new",c.mode=At(E.slice(13).trim())),E.startsWith("deleted file mode")&&(c.type="deleted",c.mode=At(E.slice(17).trim())),E.startsWith("similarity index")&&(E.startsWith("similarity index 100%")?c.type="rename-pure":c.type="rename-changed"),E.startsWith("index ")){const[,T,A,j]=E.trim().match(pV)??[];T!=null&&(c.prevObjectId=At(T)),A!=null&&(c.newObjectId=At(A)),j!=null&&(c.mode=At(j))}E.startsWith("rename from ")&&(c.prevName=At(E.slice(12).trim())),E.startsWith("rename to ")&&(c.name=At(E.slice(10).trim()))}}continue}let v,x;for(;m.length>0&&(m[m.length-1]===`
154
- `||m[m.length-1]==="\r"||m[m.length-1]===`\r
155
- `||m[m.length-1]==="");)m.pop();const{additionStart:k,deletionStart:w}=b;f=d?f:w-1,u=d?u:k-1;const C={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:b.additionCount,additionStart:k,additionLines:y,deletionCount:b.deletionCount,deletionStart:w,deletionLines:S,deletionLineIndex:f,additionLineIndex:u,hunkContent:[],hunkContext:$y(b.hunkContext),hunkSpecs:At(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let I=0,_=0;for(let E=1;E<m.length;E++){const M=m[E];if(I>=C.additionCount&&_>=C.deletionCount&&!M.startsWith("\\")){if(o&&IV(M)&&!_V(M))throw Error("parsePatchContent: hunk has more lines than expected");break}const T=M[0];if(T!=="+"&&T!=="-"&&T!==" "&&T!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${T}", full line: "${M}"`),console.error("processFile: invalid rawLine:",M);continue}const A=TV(T);if(A==="addition"){if(o&&I>=C.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const j=Of(M);(v==null||v.type!=="change")&&(v=Hf("change",f,u),C.hunkContent.push(v)),u++,I++,d&&c.additionLines.push(j),v.additions++,y++,x="addition"}else if(A==="deletion"){if(o&&_>=C.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const j=Of(M);(v==null||v.type!=="change")&&(v=Hf("change",f,u),C.hunkContent.push(v)),f++,_++,d&&c.deletionLines.push(j),v.deletions++,S++,x="deletion"}else if(A==="context"){if(o&&(_>=C.deletionCount||I>=C.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const j=Of(M);(v==null||v.type!=="context")&&(v=Hf("context",f,u),C.hunkContent.push(v)),u++,f++,I++,_++,d&&(c.deletionLines.push(j),c.additionLines.push(j)),v.lines++,x="context"}else if(A==="metadata"&&v!=null){if(v.type==="context"?(C.noEOFCRAdditions=!0,C.noEOFCRDeletions=!0):x==="deletion"?C.noEOFCRDeletions=!0:x==="addition"&&(C.noEOFCRAdditions=!0),d&&(x==="addition"||x==="context")){const j=c.additionLines.length-1;j>=0&&(c.additionLines[j]=Hy(c.additionLines[j]))}if(d&&(x==="deletion"||x==="context")){const j=c.deletionLines.length-1;j>=0&&(c.deletionLines[j]=Hy(c.deletionLines[j]))}}}if(o&&(I!==C.additionCount||_!==C.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");C.additionLines=y,C.deletionLines=S,C.collapsedBefore=Math.max(C.additionStart-1-i,0),c.hunks.push(C),i=C.additionStart+C.additionCount-1;for(const E of C.hunkContent)E.type==="context"?(C.splitLineCount+=E.lines,C.unifiedLineCount+=E.lines):(C.splitLineCount+=Math.max(E.additions,E.deletions),C.unifiedLineCount+=E.deletions+E.additions);C.splitLineStart=c.splitLineCount+C.collapsedBefore,C.unifiedLineStart=c.unifiedLineCount+C.collapsedBefore,c.splitLineCount+=C.collapsedBefore+C.splitLineCount,c.unifiedLineCount+=C.collapsedBefore+C.unifiedLineCount}if(c!=null){if(o&&d&&!n&&c.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(c.hunks.length>0&&!d&&c.additionLines.length>0&&c.deletionLines.length>0){const p=c.hunks[c.hunks.length-1],m=p.additionStart+p.additionCount-1,g=c.additionLines.length,b=Math.max(g-m,0);c.splitLineCount+=b,c.unifiedLineCount+=b}return n||(c.prevName!=null&&c.name!==c.prevName?c.hunks.length>0?c.type="rename-changed":c.type="rename-pure":(r==null||r.contents==="")&&s!=null&&s.contents!==""?c.type="new":r!=null&&r.contents!==""&&(s==null||s.contents==="")&&(c.type="deleted")),c.type!=="rename-pure"&&c.type!=="rename-changed"&&(c.prevName=void 0),c}}function wV(e,t,n=!1){const r=[],s=SV(e)?e.split(dV):[e];for(const o of s)try{r.push(xV(o,t!=null?`${t}-${r.length}`:void 0,n))}catch(i){if(n)throw i;console.error(i)}return r}function SV(e){return e.startsWith("From ")||e.includes(`
156
- From `)}function Fy(e){const t=y4(e);for(let n=0;n<t.length;n++)t[n]=At(t[n]);return t}function y4(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const r=e.indexOf(`
157
- `,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 CV(e){return b4(e,"diff --git")}function kV(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=ip(e,r);if(s<=0&&o<=0){if(v4(e,r)){r>n&&t.push(e.slice(n,r)),n=r,i=!0,r=ip(e,a);continue}if(i&&e.startsWith("@@ -",r)){const d=x4(e.slice(r,a));d!=null&&(s=d.deletionCount,o=d.additionCount)}r=a;continue}const c=e[r];if(c==="\\"){r=a;continue}c===" "?(s=Math.max(s-1,0),o=Math.max(o-1,0)):c==="-"?s=Math.max(s-1,0):c==="+"&&(o=Math.max(o-1,0)),r=a}return t.push(e.slice(n)),t}function MV(e){return v4(e,0)}function v4(e,t){const n=ip(e,t);return Vy(e,t,"---")&&Vy(e,n,"+++")}function Vy(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===`
158
- `||o==="\r")break;if(o!==" "&&o!==" ")return!0}return!1}function ip(e,t){const n=e.indexOf(`
159
- `,t);return n===-1?e.length:n+1}function IV(e){const t=e[0];return t==="+"||t==="-"||t===" "}function _V(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
160
- `&&n!=="\r")return!1}return!0}function x4(e){if(!e.startsWith("@@ -"))return;let t=4;const n=Nl(e,t);if(n==null)return;const r=n.value;t=n.endIndex;let s=1;if(e[t]===","){const f=Nl(e,t+1);if(f==null)return;s=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const o=Nl(e,t);if(o==null)return;const i=o.value;t=o.endIndex;let a=1;if(e[t]===","){const f=Nl(e,t+1);if(f==null)return;a=f.value,t=f.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let c;const d=t+3;return e[d]===" "&&(c=EV(e.slice(d+1))),{additionCount:a,additionStart:i,deletionCount:s,deletionStart:r,hunkContext:c}}function Nl(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 EV(e){return e.endsWith(`\r
161
- `)?e.slice(0,-2):e.endsWith(`
162
- `)?e.slice(0,-1):e}function jV(e){return e.startsWith("diff --git")||e.includes(`
163
- diff --git`)}function b4(e,t){if(e.length===0)return[""];const n=`
164
- ${t}`,r=e.startsWith(t)?0:By(e,n,0);if(r===-1)return[e];const s=[];r>0&&s.push(e.slice(0,r));let o=r;for(;;){const i=By(e,n,o+1);if(i===-1)break;s.push(e.slice(o,i)),o=i}return s.push(e.slice(o)),s}function By(e,t,n){const r=e.indexOf(t,n);return r===-1?-1:r+1}function $y(e){return e==null?e:At(e)}function TV(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function Of(e){const t=e.slice(1);return At(t===""?`
165
- `:t)}function Hf(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 w4=/^\*\*\*\s+(?:Begin Patch|End Patch|Add File:|Update File:|Delete File:|Move to:)/m,Qc=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,AV=/(?=^diff --git\s+)/gm,S4=/^diff --git\s+/m,LV=/(?=^---\s+\S)/gm,C4=/^---\s+\S/m,Rr=e=>typeof e=="object"&&e!==null,NV=e=>e.replace(/\r\n/g,`
166
- `).replace(/\r/g,`
167
- `).trim(),RV=e=>{let t=!1;return e.split(`
168
- `).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(`
169
- `)},PV=e=>{let t=!1;return e.split(`
170
- `).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(`
171
- `)},zy=(e,t)=>t===1?e:`${e},${t}`,DV=e=>{const t=e.split(`
172
- `),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 c=r+1;c<t.length;c+=1){const d=t[c]??"";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]=`@@ -${zy(o[1]??"0",i)} +${zy(o[2]??"0",a)} @@${o[3]??""}`}return n.join(`
173
- `)},k4=e=>DV(PV(RV(NV(e)))),Ft=e=>{if(typeof e=="string")return/\S/.test(e)?e:void 0;if(Rr(e)){const t=e.patch;if(typeof t=="string")return/\S/.test(t)?t:void 0}},ja=e=>Rr(e)?typeof e.movePath=="string"?e.movePath:typeof e.filePath=="string"?e.filePath:typeof e.relativePath=="string"?e.relativePath:null:null,Gm=(e,t,n)=>{if(e==="apply_patch"){const r=Array.isArray(n?.files)?n.files:[];for(const s of r)if(Rr(s)&&s.type!=="delete"){const o=ja(s);if(o)return o}return null}if(e==="edit"||e==="multiedit"){const r=Rr(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},OV=(e,t,n)=>{if(e==="apply_patch"){const s=Array.isArray(n?.files)?n.files:[],o=new Set;for(const i of s){if(!Rr(i))continue;const a=ja(i);a&&o.add(a),i.type==="move"&&typeof i.filePath=="string"&&o.add(i.filePath)}return[...o]}const r=Gm(e,t,n);return r?[r]:[]},HV=e=>e==="edit"||e==="multiedit"||e==="apply_patch",Uy=(e,t)=>{const n=Array.isArray(e.files)?e.files:[];if(!t){const r=n[0];return Rr(r)?r:void 0}return n.find(r=>Rr(r)&&(r.relativePath===t||r.filePath===t||r.movePath===t))},Qi=e=>{if(!e)return;let t,n;for(const r of e.split(`
174
- `)){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},qy=(e,t,n)=>{if(!t||!HV(e))return;if(n){const i=Uy(t,n),a=Ft(i?.patch)??Ft(i?.diff);if(a){const c=Qi(a);if(c!==void 0)return c}}const r=Ft(t.patch)??Ft(t.diff);if(r){const i=Qi(r);if(i!==void 0)return i}const s=Uy(t),o=Ft(s?.patch)??Ft(s?.diff);return o?Qi(o):void 0},FV=e=>{const t=(e??"").trim().replace(/\t.*$/,"");return!t||t==="/dev/null"?"":t.replace(/^[ab]\//,"")},VV=e=>{const t=e.trim().replace(/\s+/g,"-");return t.length>0?t:"file"},BV=e=>{let t=!1;for(const n of e.split(`
175
- `)){if(n.startsWith("@@")){if(!Qc.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},Ff=e=>{const t=k4(e);if(!t||w4.test(t)||!Qc.test(t)||!BV(t))return null;try{const n=wV(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:FV(s.name)}}catch{return null}},$V=e=>{const t=S4.test(e),n=C4.test(e);return!t&&!n?[]:e.split(t?AV:LV).map(r=>r.trim()).filter(r=>r.length>0)},Zy=(e,t,n,r)=>{const s=k4(e);if(!s)return[];const o=Ff(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 $V(s)){const c=Ff(a),d=c?.title?r(c.title):r(t);if(!c){(Qc.test(a)||S4.test(a)||C4.test(a))&&i.push({id:`${n}-${i.length}`,title:d,patch:a,renderMode:"text"});continue}i.push({id:`${n}-${i.length}`,title:d,patch:c.patch,renderMode:"diff"})}if(i.length>0)return i;if(!w4.test(s)&&Qc.test(s)){const a=VV(t),c=Ff(`--- ${a}
176
- +++ ${a}
177
- ${s}`);if(c)return[{id:`${n}-0`,title:r(t),patch:c.patch,renderMode:"diff"}]}return[{id:`${n}-0`,title:r(t),patch:s,renderMode:"text"}]},zV=e=>{if(!Rr(e))return null;const t=Ft(e.patch)??Ft(e.diff);if(!t)return null;const n=typeof e.relativePath=="string"?e.relativePath:typeof e.filePath=="string"?e.filePath:"";return{filePath:ja(e)??void 0,patch:t,title:n}},UV=(e,t,n)=>{const s=(Array.isArray(e?.files)?e.files:[]).flatMap((i,a)=>{const c=zV(i);return c?Zy(c.patch,c.title||`File ${a+1}`,`file-${a}`,n).map(d=>({...d,filePath:c.filePath})):[]});return s.length>0?s:Zy(typeof t=="string"?t:"","Diff","fallback",n)},qV=new Set(["read","skill"]),bs=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},ZV=e=>!WV(e),WV=e=>qV.has(bs(e)),GV=(e,t,n)=>{if(typeof t=="string"&&t.trim().length>0)return t;const r=bs(e)==="glob"?n?.pattern:void 0;return typeof r=="string"?r:""},KV=(e,t)=>{const n=t.replace(/\r\n/g,`
178
- `);if(!n.trim())return;const r=(()=>{const a=(e??"").trim();return a?a.startsWith("/")?a.slice(1):a:"new-file"})(),s=n.split(`
179
- `),o=s.length,i=s.map(a=>`+${a}`).join(`
180
- `);return["--- /dev/null",`+++ b/${r}`,`@@ -0,0 +1,${o} @@`,i].join(`
181
- `)},ed=e=>{const t=e.trim().replace(/\\/g,"/").replace(/\/{2,}/g,"/");return!t||t==="/"?t:t.replace(/\/+$/,"")},Dn=(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},YV=5,ea=e=>typeof e=="object"&&e!==null,XV=e=>{if(!ea(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=ea(e.range)?e.range:void 0,s=r&&ea(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}},JV=(e,t,n,r)=>{if(!["edit","multiedit","write","apply_patch"].includes(e))return null;const s=Gm(e,t,n);if(!s||!n||!ea(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 c=a.map(f=>XV(f)).filter(f=>!!f);if(c.length===0)return null;const d=c.slice(0,YV);return{displayPath:o.startsWith("/")?Dn(o,r):o,diagnostics:d,remaining:Math.max(0,c.length-d.length)}},QV=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},eB=e=>{const t=Ft(e?.patch)??Ft(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}},tB=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},M4=(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],c=a?.relativePath||a?.filePath;return i.length>1?null:typeof c=="string"?Dn(c,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 Dn(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 Dn(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 Dn(i,n)}if(e.tool==="lsp"&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Dn(i,n)}return null},nB=(e,t)=>{if(!e)return"";const n=typeof e.operation=="string"?e.operation:"lsp";if(n==="workspaceSymbol"){const c=typeof e.query=="string"&&e.query.trim().length>0?` "${e.query.trim()}"`:"";return`${n}${c}`}const r=typeof e.filePath=="string"?e.filePath:typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:"",s=r?Dn(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},rB=(e,t,n)=>{const r=t,s=r.metadata,o=r.input,i=M4(e,t,n);if(i)return i;if(e.tool==="apply_patch"){const c=Array.isArray(s?.files)?s?.files:[];return c.length>1?`${c.length} files`:""}if(e.tool==="question"&&o?.questions&&Array.isArray(o.questions)){const c=o.questions.length;return`Asked ${c} question${c!==1?"s":""}`}if(e.tool==="bash"&&o?.command&&typeof o.command=="string")return o.command.split(`
182
- `)[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 nB(o,n);const a=o?.description||s?.description||"title"in t&&t.title||"";return GV(e.tool,a,o)},I4=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""},To=e=>{const t=bs(e.tool),n=e.state?.status??"",r=I4(e);return`${e.id??""}${t}${n}${r}`},sB=({isTaskTool:e,isExpanded:t,isActive:n,hasFinalMetadataSummary:r,taskSessionId:s})=>e&&!!s&&!r&&(t||n),Ao=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},Wy=e=>{if(!e||typeof e!="object")return;const t=e;return Ao(t.sessionID)??Ao(t.sessionId)},_4=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},E4=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:Ao(n.sessionId)??Ao(n.sessionID),summaryEntries:_4(n.summary??n.entries??n.tools??n.calls)}}catch{return{summaryEntries:[]}}},oB=e=>{if(typeof e!="string"||e.trim().length===0)return;const t=E4(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 Ao(s||cV(e))},Gy=new WeakMap,iB=e=>e.type==="tool",aB=e=>{const t=Gy.get(e);if(t)return t;const n=[];if(e.info.role==="assistant")for(const r of e.parts){if(!iB(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 Gy.set(e,n),n},lB=e=>{const t=[];for(const n of e)t.push(...aB(n));return t},cB=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Ky=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},Yy=(e,t)=>e===null?t:t===null?e:e+t,dB=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=Ky(s.additions),a=Ky(s.deletions),c=n.get(o);if(c){c.added=Yy(c.added,i),c.removed=Yy(c.removed,a);continue}n.set(o,{file:s,path:o,name:o.split("/").pop()||o,added:i,removed:a})}return Array.from(n.values())},uB=({animate:e=!0,metadata:t,onFileClick:n,openDiffLabel:r,showFileIcons:s=!0,textClassName:o})=>{const i=dB(t);return i.length<=1?null:l.jsx(l.Fragment,{children:i.map(a=>{const c=a.added!==null||a.removed!==null,d=l.jsxs(l.Fragment,{children:[s?l.jsx(rr,{filePath:a.path,className:"h-3.5 w-3.5"}):null,l.jsx(sr,{variant:e?"generate-effect":"static",className:P("min-w-0 max-w-full truncate",o),style:{color:"var(--tools-description)"},title:a.path,children:a.name}),c?l.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[l.jsxs("span",{style:{color:"var(--status-success)"},children:["+",a.added??0]}),l.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),l.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a.removed??0]})]}):null]}),f=n&&a.file.type!=="delete"&&ja(a.file),u=`${r}: ${a.path}`;return f?l.jsx(Me,{variant:"ghost",size:"xs",className:P("min-w-0 max-w-full gap-1 normal-case font-normal tracking-normal",o),"aria-label":u,title:u,onClick:p=>n(a.file,p),children:d},a.path):l.jsx("span",{className:P("inline-flex min-w-0 max-w-full items-center gap-1",o),style:{color:"var(--tools-description)"},children:d},a.path)})})},fB=({currentDirectory:e,editor:t,file:n})=>{const r=ja(n);if(!r||n.type==="delete")return!1;const s=Ft(n.patch)??Ft(n.diff),o=s?Qi(s):void 0,i=_a(e,r);return t.openFile(i,o),!0},j4=({children:e,animate:t,className:n})=>l.jsx("div",{className:P(t&&"oc-step-in",n),children:e}),Km=({children:e,maxHeightClass:t="max-h-[60vh]",className:n,outerClassName:r,disableHorizontal:s=!1,followKey:o})=>{const i=h.useRef(null),a=h.useRef(!0);return h.useLayoutEffect(()=>{const c=i.current;if(o===void 0){a.current=!0;return}!c||!a.current||(c.scrollTop=c.scrollHeight)},[o]),l.jsx("div",{className:P("w-full min-w-0 flex-none overflow-hidden",r),children:l.jsx(Fd,{ref:i,"data-scrollable":"true",onWheelCapture:c=>{o!==void 0&&c.deltaY<0&&(a.current=!1)},onScroll:c=>{if(o===void 0)return;const d=c.currentTarget;a.current=d.scrollHeight-d.scrollTop-d.clientHeight<=2},className:P("tool-output-surface p-2 rounded-xl w-full min-w-0",t,s?"overflow-y-auto overflow-x-hidden":"overflow-auto",n),children:l.jsx("div",{className:"w-full min-w-0",children:e})})})},Xy=({path:e,grow:t=!0})=>{const n=e.lastIndexOf("/");if(n===-1)return l.jsx("span",{className:P("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 l.jsxs("span",{className:P("min-w-0 flex items-baseline overflow-hidden typography-ui-label",t&&"flex-1"),title:e,children:[o?l.jsx("span",{className:"flex-shrink-0 text-muted-foreground",children:"/"}):null,l.jsx("span",{className:"min-w-0 truncate text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:i}),l.jsxs("span",{className:"flex-shrink-0",children:[l.jsx("span",{className:"text-muted-foreground",children:"/"}),l.jsx("span",{className:"text-foreground",children:s})]})]})},ap=({path:e,animate:t=!0,grow:n=!0,showFileIcons:r=!0})=>{const s=e.lastIndexOf("/");if(s===-1)return l.jsxs("span",{className:P("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?l.jsx(rr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,l.jsx(sr,{variant:t?"generate-effect":"static",className:P("min-w-0 truncate whitespace-nowrap",It,n&&"flex-1"),style:{color:"var(--tools-title)"},children:e})]});const o=e.slice(0,s),i=e.slice(s+1),a=o.startsWith("/"),c=a?o.slice(1):o;return l.jsxs("span",{className:P("min-w-0 inline-flex items-center gap-1 overflow-hidden",n&&"flex-1"),title:e,children:[r?l.jsx(rr,{filePath:e,className:"h-3.5 w-3.5 flex-shrink-0"}):null,l.jsxs("span",{className:P("min-w-0 inline-flex max-w-full items-baseline overflow-hidden",It,n&&"flex-1"),children:[a?l.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}):null,l.jsx("span",{className:"min-w-0 shrink truncate whitespace-nowrap",style:{color:"var(--tools-description)",direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:c}),l.jsx("span",{className:"flex-shrink-0",style:{color:"var(--tools-description)"},children:"/"}),l.jsx(sr,{variant:t?"generate-effect":"static",className:"flex-shrink-0",style:{color:"var(--tools-title)"},children:i})]})]})},hB=new Set(["read","view","file_read","cat","write","create","file_write","edit","multiedit","apply_patch"]),pB=(e,t)=>{if(!hB.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)},mB=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(To(e[n])!==To(t[n]))return!1;return!0},T4=h.memo(({entry:e,isMobile:t,animateTailText:n})=>{const r=bs(e.tool),s=r.length>0?r:"tool",o=I4(e),i=o.trim().length>0,a=e.state?.status,c=Ma(s).displayName;return l.jsx(j4,{animate:n,children:l.jsxs("div",{className:P("flex gap-2 min-w-0 w-full",a==="error"&&t?"items-start":"items-center"),children:[l.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:ga(s)}),l.jsx("span",{className:P(jo,"text-foreground/80 flex-shrink-0"),style:Ea,title:c,children:c}),i?a!=="error"&&pB(s,o)?l.jsx(ap,{path:o,animate:n,showFileIcons:!0}):a==="error"?l.jsx("span",{className:P(It,"flex-1 min-w-0 text-[var(--status-error)]",t?"whitespace-normal break-words":"truncate"),children:o}):l.jsx(sr,{variant:n?"generate-effect":"static",className:P(It,"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&&To(e.entry)===To(t.entry));T4.displayName="TaskSummaryEntryRow";const A4=h.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 l.jsx(Km,{maxHeightClass:t?"max-h-[40vh]":"max-h-[min(17.5rem,45vh)]",disableHorizontal:!0,children:l.jsxs("div",{className:"w-full min-w-0 space-y-1","data-chat-task-entries-list":"true",children:[o>0?l.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",o," more…"]}):null,s.map((a,c)=>{const d=t?c:i+c,f=a.id??`${To(a)}:${d}`;return l.jsx(T4,{entry:a,isMobile:n,animateTailText:r},f)})]})})},(e,t)=>e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&mB(e.entries,t.entries));A4.displayName="TaskSummaryEntriesList";const gB=({entries:e,isExpanded:t,isMobile:n,output:r,sessionId:s,onShowPopup:o,input:i,animateTailText:a=!0,isActive:c=!1})=>{const d=Bn(),f=pe(S=>S.setCurrentSession),u=typeof r=="string"?cB(r):"",p=u.length>0,[m,g]=h.useState(!1),b=S=>{S.stopPropagation(),s&&d&&f(s,d)},y=typeof i?.subagent_type=="string"?i.subagent_type:"subagent";return e.length===0&&!p&&!s?l.jsx("div",{className:"oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",children:l.jsx("div",{className:"typography-meta text-muted-foreground/70",children:c?"Waiting for subagent activity...":"No subagent session id on task metadata."})}):l.jsxs("div",{className:P("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?l.jsx(A4,{entries:e,isExpanded:t,isMobile:n,animateTailText:a}):null,s&&l.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:b,children:[l.jsx(F,{name:"external-link",className:"h-3.5 w-3.5 flex-shrink-0"}),l.jsx("span",{className:"typography-meta text-primary font-medium",children:`Open ${y.charAt(0).toUpperCase()+y.slice(1)} subtask`})]}),p?l.jsxs("div",{className:P("space-y-1",(e.length>0||s)&&"pt-1"),children:[l.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(v=>!v)},children:[m?l.jsx(F,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0"}):l.jsx(F,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0"}),l.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?l.jsx(Km,{maxHeightClass:"max-h-[50vh]",children:l.jsx("div",{className:"w-full min-w-0",children:l.jsx(ka,{content:u,variant:"tool",onShowPopup:o})})}):null]}):null]})},yB=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}},vB="/assets/markdown-shiki.worker-DnvH1S1x.js";let Nn,xB=0;const ya=new Map,lp=new Set,Jy=()=>{ya.forEach(e=>e(null)),ya.clear(),lp.clear(),Nn?.terminate(),Nn=void 0},bB=()=>{if(Nn)return Nn;if(!(typeof window>"u"||typeof Worker>"u")){try{Nn=new Worker(vB,{type:"module"})}catch(e){console.error("Failed to create Shiki worker:",e);return}return Nn.onmessage=e=>{const t=ya.get(e.data.id);t&&(ya.delete(e.data.id),t(e.data))},Nn.onerror=Jy,Nn.onmessageerror=Jy,Nn.postMessage({type:"init"}),Nn}},Ym=e=>{const t=bB();if(!t)return Promise.resolve(null);const n=++xB;return new Promise(r=>{ya.set(n,r),t.postMessage(e(n))})},wB=async(e,t)=>{const n=await Ym(r=>({type:"highlight",id:r,code:e,lang:t}));return n?.type==="highlight"?n.html:null},IG=async(e,t)=>{const n=await Ym(r=>({type:"highlightLines",id:r,code:e,lang:t}));return n?.type==="highlightLines"?n.lines:null},_G=async(e,t,n,r)=>{const s=!lp.has(n),o=await Ym(i=>({type:"highlightTokens",id:i,code:e,lang:t,themeName:n,...s?{theme:r}:{}}));return o?.type==="highlightTokens"?(lp.add(n),o.lines):null},SB=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),CB=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(""):"",Qy=(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=CB(n);o&&s.setAttribute("style",`${s.getAttribute("style")??""}${o}`)}},kB=e=>`<pre><code>${SB(e)}</code></pre>`,td=({code:e,language:t,className:n,style:r,codeStyle:s,wrap:o=!1})=>{const{currentTheme:i}=Vn(),a=h.useRef(null),c=h.useMemo(()=>yB(i),[i]);return h.useLayoutEffect(()=>{const d=a.current;d&&(d.innerHTML=kB(e),Qy(d,o,s))},[e,o,s]),h.useEffect(()=>{const d=a.current;if(!d)return;let f=!0;return wB(e,(t||"text").toLowerCase()).then(u=>{!f||!d||!u||(d.innerHTML=u,Qy(d,o,s))}),()=>{f=!1}},[e,t,o,s]),l.jsx("div",{ref:a,className:P("typography-code",n),style:{...c,...r}})},MB={maxDepth:50,maxNodes:1e5,initiallyExpandedDepth:2};function IB(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 _B(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 cp=0;function L4(e,t,n,r,s){if(cp>=s.maxNodes)return null;cp++;const o=IB(e),i=_B(n),a=o==="object"||o==="array",c={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);c.childCount=d.length,c.children=[];for(const[f,u]of d){const p=[...n,f],m=L4(u,f,p,r+1,s);m&&c.children.push(m)}}else a&&(c.childCount=o==="array"?e.length:Object.keys(e).length);return c}function EB(e,t){const n={...MB,...t};cp=0;try{const r=e.trim();if(!r)return null;const s=JSON.parse(r);return L4(s,"root",[],0,n)}catch{return null}}function jB(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 TB(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 AB(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 e5=["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 LB(e){return e5[e%e5.length]}function NB(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 dp(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 RB(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=>dp(r)).join(", ")??""}]`:`[${t} items]`}return dp(e)}const up=h.memo(({flatNode:e,onToggle:t,onCopyPath:n})=>{const{node:r,isExpanded:s}=e,o=r.depth*20,i=h.useCallback(()=>{t(r.id)},[t,r.id]),a=h.useCallback(u=>{n&&(u.preventDefault(),n(r.id))},[n,r.id]),c=LB(r.depth),d=NB(r),f=r.isExpandable&&r.children&&r.children.length>0;return l.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?l.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?l.jsx(F,{name:"arrow-down-s",className:"h-3 w-3"}):l.jsx(F,{name:"arrow-right-s",className:"h-3 w-3"})}):l.jsx("span",{className:"mr-1 w-4"}),r.key!=="root"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"mr-1 font-semibold",style:{color:c},children:/^\d+$/.test(r.key)?r.key:`"${r.key}"`}),l.jsx("span",{className:"mr-1 text-[var(--surface-foreground)]",children:":"})]}),r.isExpandable?s?l.jsx("span",{className:"text-[var(--surface-foreground)]",children:r.type==="object"?"{":"["}):l.jsx("span",{style:{color:"var(--surface-mutedForeground)"},children:RB(r)}):l.jsx("span",{style:{color:d},children:dp(r)})]})});up.displayName="JsonRow";const PB=200,DB=22,OB=h.forwardRef(function({data:t,className:n,maxHeight:r="100%",initiallyExpandedDepth:s=2,onCopyPath:o},i){const a=h.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]),c=h.useMemo(()=>a?EB(a):null,[a]),[d,f]=h.useState(()=>c?new Set(AB(c,s)):new Set),u=h.useMemo(()=>jB(c,d),[c,d]),p=u.length>PB,m=h.useRef(null),g=vv({count:u.length,enabled:p,getScrollElement:()=>m.current,estimateSize:()=>DB,overscan:20,getItemKey:v=>u[v]?.node.id??v}),b=h.useCallback(v=>{f(x=>{const k=new Set(x);return k.has(v)?k.delete(v):k.add(v),k})},[]),y=h.useCallback(()=>{f(new Set)},[]),S=h.useCallback(()=>{c&&f(new Set(TB(c)))},[c]);return h.useImperativeHandle(i,()=>({expandAll:y,collapseAll:S}),[y,S]),c?p?l.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:l.jsx("div",{style:{height:g.getTotalSize(),position:"relative"},children:g.getVirtualItems().map(v=>{const x=u[v.index];return x?l.jsx("div",{"data-index":v.index,ref:g.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${v.start}px)`},children:l.jsx(up,{flatNode:x,onToggle:b,onCopyPath:o})},x.node.id):null})})}):l.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:u.map(v=>l.jsx(up,{flatNode:v,onToggle:b,onCopyPath:o},v.node.id))}):null}),HB=({mode:e,onModeChange:t,className:n})=>{const r=h.useCallback(s=>{s.stopPropagation(),t(e==="side-by-side"?"unified":"side-by-side")},[e,t]);return l.jsx(Me,{size:"sm",variant:"ghost",className:P("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"?l.jsx(F,{name:"align-justify",className:"h-3 w-3"}):l.jsx(F,{name:"layout-column",className:"h-3 w-3"})})},FB=e=>{let t=e.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return t=t.replace(/^\s*\d{5}\|\s?/gm,""),t.trim()},un=(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}},VB=e=>e?e.includes("<diagnostics")||e.includes("<file_diagnostics>")||e.includes("LSP errors detected")||e.includes("This file has errors"):!1,BB=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():"",t5=(e,t)=>!e||typeof e!="object"?String(e):WA(e,t||""),Rl=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}}},$B=e=>{if(!e||typeof e!="object")return;const t=Rl(e.patch)??Rl(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=Rl(r.patch)??Rl(r.diff);if(s)return s}},zB=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}}},N4=(e,t,n)=>{let r=FB(e);if((t==="edit"||t==="multiedit"||t==="write"||t==="apply_patch")&&VB(r)&&(r=BB(r)),(t==="edit"||t==="multiedit"||t==="apply_patch")&&r.trim().length===0){const s=$B(n);if(s)return s}return r},EG=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,`
183
- `).split(`
184
- `),a=f=>/\(\s*File has more lines\..*offset.*\)/i.test(f.trim()),d=i.map(f=>{const u=f.trim(),p=u.startsWith("(")&&u.endsWith(")")||a(u);if(n!=="directory"){const m=f.match(/^(\d+):\s?(.*)$/);if(m){const g=m[2],b=g.trim(),y=b.startsWith("(")&&b.endsWith(")")||a(b);return{lineNumber:y?null:Number(m[1]),text:g,isInfo:y}}}return{lineNumber:null,text:f,isInfo:p}}).filter((f,u,p)=>{if(f.text.trim().length>0)return!0;const m=p[u-1],g=p[u+1],b=!!(m?.isInfo||g?.isInfo),y=f.lineNumber!==null;return!(b&&y)});return{type:n,lines:d}},jG=(e,t)=>{try{const n=e.trim().split(`
185
- `).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,c=Math.floor(i.length/2),d=!a.endsWith("/");r.push({name:a.replace(/\/$/,""),depth:c,isFile:d})}}),l.jsx("div",{className:P("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:va.tool.popup,children:r.map((s,o)=>l.jsx("div",{className:"min-w-0",style:{paddingLeft:`${s.depth*20}px`},children:s.isFile?l.jsx("span",{className:"text-foreground/90 block truncate",children:s.name}):l.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[s.name,"/"]})},o))})}catch{return null}},UB={backgroundColor:"var(--status-info)",opacity:.6},TG=(e,t,n)=>{try{const r=e.trim().split(`
186
- `).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,c,d]=i,f=d!==void 0?c:"",u=d!==void 0?d:c;s[a]||(s[a]=[]),s[a].push({lineNum:f,content:u})}}),l.jsxs("div",{className:P("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:va.tool.popup,children:[l.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])=>l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:P("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:o}),l.jsx("div",{className:"pl-4 space-y-1",children:i.map((a,c)=>!a.lineNum&&!a.content?null:l.jsxs("div",{className:P("flex items-start gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[l.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:UB}),l.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[a.lineNum&&l.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",a.lineNum,":"]}),l.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:a.content||" "})]})]},c))})]},o))]})}catch{return null}},qB={backgroundColor:"var(--status-info)",opacity:.6},AG=(e,t,n)=>{try{const r=e.trim().split(`
187
- `).filter(Boolean);if(r.length===0)return null;const s={};r.forEach(i=>{const a=i.lastIndexOf("/"),c=a>0?i.substring(0,a):"/",d=a>=0?i.substring(a+1):i;s[c]||(s[c]=[]),s[c].push(d)});const o=Object.keys(s).sort();return l.jsxs("div",{className:P("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:va.tool.popup,children:[l.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," file",r.length!==1?"s":""]}),o.map(i=>l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:P("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:[i,"/"]}),l.jsx("div",{className:P("pl-4 grid gap-1",t?"grid-cols-1":"grid-cols-2"),children:s[i].sort().map(a=>l.jsxs("div",{className:P("flex items-center gap-2 min-w-0",t?"typography-micro":"typography-code"),children:[l.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:qB}),l.jsx("span",{className:"text-foreground font-mono truncate",children:a})]},a))})]},i))]})}catch{return null}},ZB=(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,c)=>{const d=c.status;return d in a&&a[d].push(c),a},{in_progress:[],pending:[],completed:[],cancelled:[]}),i=a=>{const c="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return l.jsx("div",{className:c,style:{backgroundColor:"var(--status-error)"}});case"medium":return l.jsx("div",{className:c,style:{backgroundColor:"var(--primary)"}});case"low":return l.jsx("div",{className:c,style:{backgroundColor:"var(--status-info)"}});default:return l.jsx("div",{className:c,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return l.jsxs("div",{className:P("space-y-3 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:va.tool.popup,children:[l.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[l.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:[t.total,": ",s.length]}),o.in_progress.length>0&&l.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:[t.inProgress,": ",o.in_progress.length]}),o.pending.length>0&&l.jsxs("span",{style:{color:"var(--muted-foreground)"},children:[t.pending,": ",o.pending.length]}),o.completed.length>0&&l.jsxs("span",{style:{color:"var(--status-success)"},children:[t.completed,": ",o.completed.length]}),o.cancelled.length>0&&l.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:[t.cancelled,": ",o.cancelled.length]})]}),o.in_progress.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),l.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:t.inProgress})]}),l.jsx("div",{className:"space-y-1.5 pl-4",children:o.in_progress.map((a,c)=>l.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),l.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:un(a.content)})]},a.id||c))})]}),o.pending.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),l.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:t.pending})]}),l.jsx("div",{className:"space-y-1.5 pl-4",children:o.pending.map((a,c)=>l.jsxs("div",{className:"flex items-start gap-2",children:[i(a.priority),l.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:un(a.content)})]},a.id||c))})]}),o.completed.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(F,{name:"check",className:"w-3 h-3",style:{color:"var(--status-success)"}}),l.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:t.completed})]}),l.jsx("div",{className:"space-y-1.5 pl-4",children:o.completed.map((a,c)=>l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx(F,{name:"check",className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),l.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:un(a.content)})]},a.id||c))})]}),o.cancelled.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),l.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:t.cancelled})]}),l.jsx("div",{className:"space-y-1.5 pl-4",children:o.cancelled.map((a,c)=>l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),l.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:un(a.content)})]},a.id||c))})]})]})}catch{return null}},LG=(e,t)=>{try{return l.jsx("div",{className:P("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:va.tool.popup,children:l.jsx(ka,{content:e,variant:"tool"})})}catch{return null}},WB=(e,t,n)=>ZA(t,e,n),GB=new Set(["id","identifier","title","name"]),KB=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pl=e=>e.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^./,t=>t.toUpperCase()),YB=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},XB=e=>{try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},nd=h.memo(({value:e,label:t,depth:n})=>{if(Array.isArray(e)){const o=t?`${Pl(t)} (${e.length})`:`(${e.length})`;return l.jsxs("details",{open:n<2,className:"group/json-summary",children:[l.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:[l.jsx(F,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),l.jsx("span",{className:"min-w-0 truncate font-medium",children:o})]}),l.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),l.jsx("div",{className:"space-y-1",children:e.map((i,a)=>l.jsx(nd,{value:i,depth:n+1},a))})]})]})}if(KB(e)){const o=YB(e),i=Object.entries(e).filter(([d])=>!GB.has(d)),a=t?`${Pl(t)}${o?` · ${o}`:""}`:o,c=l.jsx("div",{className:"space-y-1",children:i.map(([d,f])=>l.jsx(nd,{label:d,value:f,depth:n+1},d))});return!t&&n===0?l.jsxs("div",{className:"space-y-2",children:[o?l.jsx("div",{className:"typography-meta font-medium text-[var(--surface-foreground)]",children:o}):null,c]}):l.jsxs("details",{open:n<2,className:"group/json-summary",children:[l.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:[l.jsx(F,{name:"arrow-right-s",className:"h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90"}),l.jsx("span",{className:"min-w-0 truncate font-medium",children:a??(t?Pl(t):"{}")})]}),l.jsxs("div",{className:"relative ml-1 pl-3 pb-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)]"}),c]})]})}const r=e===null?"null":typeof e=="boolean"?e?"true":"false":String(e),s=typeof e=="string"&&XB(e)?l.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}):l.jsx("span",{className:P("min-w-0 break-words",e===null?"text-[var(--surface-mutedForeground)]":"text-[var(--surface-foreground)]"),children:r});return l.jsxs("div",{className:"grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-2 py-1 typography-meta",children:[t?l.jsx("span",{className:"truncate text-[var(--surface-mutedForeground)]",title:t,children:Pl(t)}):l.jsx("span",{}),s]})});nd.displayName="JsonSummaryValue";const rd=h.memo(({data:e})=>l.jsx("div",{className:"space-y-1",children:l.jsx(nd,{value:e,depth:0})}));rd.displayName="JsonSummaryView";const R4=({diff:e})=>l.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}),P4=1e5,n5=(e,t,n)=>{const r=Math.max(0,t-e.length+1),s=P4-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},JB=(e,t,n,r,s)=>{const o=e[t],i=P4-s.syntheticCells,a=Math.min(n,o.length+i),c=Math.max(0,a-o.length);for(;o.length<a;)o.push(" ");return s.syntheticCells+=c,o[a]=r,a},r5=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===`
188
- `){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=JB(t,r,s,i,n)+1;continue}const a=e[o+1];if(a==="["){const c=o+2;let d=c;for(;d<e.length&&!/[\x40-\x7E]/.test(e[d]);)d+=1;if(d===e.length)break;const f=e[d],u=e.slice(c,d).split(";").map(m=>Number.parseInt(m,10)||0),p=u[0]||1;if(f==="A")r=Math.max(0,r-p);else if(f==="B")r=n5(t,r+p,n);else if(f==="C")s+=p;else if(f==="D")s=Math.max(0,s-p);else if(f==="G")s=Math.max(0,p-1);else if(f==="H"||f==="f")r=n5(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 b=0;b<=s&&b<m.length;b+=1)m[b]=" ";else g===2?t[r]=[]:m.length=Math.min(m.length,s)}o=d;continue}if(a==="]"){const c=e.indexOf("\x07",o+2),d=e.indexOf("\x1B\\",o+2),f=c===-1?d:d===-1?c:Math.min(c,d);if(f===-1)break;o=e[f]==="\x07"?f:f+1;continue}o+=1}return t.map(o=>o.join("")).join(`
189
- `)},QB=(e,t,n,r)=>{const s=e==="bash",o=s&&r!=="running";if(typeof t=="string")return o?r5(t):t;if(s&&typeof n=="string"&&n.length>0)return o?r5(n):n},e$=(e,t)=>t.startsWith(e)?t.slice(e.length):void 0,D4=16,t$=(e,t=D4)=>{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},n$=(e,t,n,r)=>t.tool==="bash"?"bash":WB(N4(e,t.tool||"",n),t.tool||"",r),r$=(e,t,n)=>t.tool==="bash"?e:N4(e,t.tool||"",n),s$=({output:e})=>{const t=h.useRef(null),n=h.useRef("");return h.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=t$(e,D4),a=e$(n.current,i);a===void 0?o.data=i:a.length>0&&o.appendData(a),n.current=i},[e]),l.jsx("pre",{ref:t,className:"m-0 whitespace-pre-wrap break-words",style:{...rp,lineHeight:"round(var(--code-block-line-height), 1px)",overflowWrap:"break-word"}})},fp=({output:e,part:t,metadata:n,input:r,isStreaming:s=!1})=>{const o=r$(e,t,n),i=n$(e,t,n,r),a=h.useMemo(()=>zB(o),[o]),[c,d]=h.useState("summary"),[f,u]=h.useState(!1);h.useEffect(()=>{d("summary"),u(!1)},[o]);const p=h.useCallback((g,b)=>{b.stopPropagation(),d(g)},[]),m=h.useCallback(async g=>{if(g.stopPropagation(),!(await ir(o)).ok){ke.error("Failed to copy output");return}u(!0),typeof window<"u"&&window.setTimeout(()=>u(!1),1200)},[o]);return t.tool==="bash"&&s?l.jsx("div",{className:"typography-code text-muted-foreground/90",children:l.jsx(s$,{output:o})}):a.isJson?l.jsxs("div",{className:"tool-output-surface relative p-2 rounded-xl w-full min-w-0",children:[l.jsxs("div",{className:"absolute right-2 top-2 z-10 flex items-center gap-1",children:[l.jsx(Me,{variant:"ghost",size:"icon",className:P("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",c==="summary"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>p("summary",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show navigable JSON",title:"Show navigable JSON",children:l.jsx(F,{name:"list-unordered",className:"h-3.5 w-3.5"})}),l.jsx(Me,{variant:"ghost",size:"icon",className:P("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",c==="formatted"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>p("formatted",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show formatted JSON",title:"Show formatted JSON",children:l.jsx(F,{name:"node-tree",className:"h-3.5 w-3.5"})}),l.jsx(Me,{variant:"ghost",size:"icon",className:P("h-6 w-6 rounded-md text-muted-foreground hover:text-foreground",c==="raw"&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),onClick:g=>p("raw",g),onPointerDown:g=>g.stopPropagation(),"aria-label":"Show raw JSON",title:"Show raw JSON",children:l.jsx(F,{name:"code-box",className:"h-3.5 w-3.5"})}),l.jsx(Me,{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:l.jsx(F,{name:f?"check":"file-copy",className:"h-3.5 w-3.5"})})]}),c==="summary"?l.jsx(rd,{data:a.data}):c==="formatted"?l.jsx(OB,{data:a.data,initiallyExpandedDepth:1,maxHeight:"400px"}):l.jsx("div",{className:"typography-code pr-12 text-muted-foreground/90",children:l.jsx(td,{language:"json",code:o,style:rp,codeStyle:_y.style,wrap:!0})})]}):l.jsx("div",{className:t.tool==="bash"?"typography-code text-muted-foreground/90":void 0,children:l.jsx(td,{language:i,code:o,style:rp,codeStyle:_y.style,wrap:!0})})};fp.displayName="ToolScrollableTextOutput";const o$=xs(()=>ft(()=>import("./ToolPartDiffPreview-D9m_vrht.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]))),s5=({diff:e,diffViewMode:t})=>l.jsx(h.Suspense,{fallback:l.jsx(R4,{diff:e}),children:l.jsx(o$,{diff:e,diffViewMode:t})}),O4=h.memo(({part:e,state:t,currentDirectory:n,isExpanded:r,onShowPopup:s})=>{const o=Ia(),[i,a]=h.useState("unified"),c=t,d=c.metadata,f=c.input,u=QB(e.tool||"",c.output,d?.output,t.status),p=typeof u=="string"&&u.length>0,m=typeof u=="string"?u:"",g=e.tool==="bash"&&t.status==="running",b=Zm({text:m,isStreaming:g,identityKey:e.id,allowTextReplacement:g}),y=g?b:m,S=c.attachments,v=ea(d?.filediff)?d.filediff:void 0,x=Ft(d?.patch)??Ft(d?.diff)??Ft(v?.patch)??Ft(v?.diff)??null,k=h.useMemo(()=>UV(d,x??void 0,K=>Dn(K,n)),[n,x,d]),w=k.some(K=>K.renderMode==="diff"),C=e.tool==="pichamber"||e.tool==="apply_patch"||e.tool==="edit"||e.tool==="multiedit",I=h.useMemo(()=>JV(e.tool||"",f,d,n),[n,f,d,e.tool]),_=h.useMemo(()=>!f||typeof f!="object"||Object.keys(f).length===0?"":"command"in f&&typeof f.command=="string"&&e.tool==="bash"?t5(f,e.tool):typeof f.content=="string"?f.content??"":t5(f,e.tool),[f,e.tool]),E=!C&&_.trim().length>0,M=e.tool==="write"||e.tool==="create"||e.tool==="file_write",T=e.tool==="todowrite"||e.tool==="todoread",A=h.useMemo(()=>Array.isArray(f?.todos)?JSON.stringify(f.todos):y,[f?.todos,y]),j=h.useMemo(()=>{if(!M||!E)return;const K=typeof f?.filePath=="string"?f.filePath:typeof f?.file_path=="string"?f.file_path:typeof f?.path=="string"?f.path:void 0;return KV(K,_)},[E,f?.filePath,f?.file_path,f?.path,_,M]);h.useEffect(()=>{a("unified")},[e.id]);const R=(K,V)=>l.jsx(Km,{maxHeightClass:V?.maxHeightClass,className:V?.className,disableHorizontal:V?.disableHorizontal,outerClassName:V?.outerClassName,followKey:V?.followKey,children:K}),O=()=>{const K=Z=>_a(n,Z.filePath??Z.title),V=(Z,L)=>{L.stopPropagation();const $=Qi(Z.patch),G=K(Z);ne.getState().openContextFileAtLine(n,G,$??1,1),o?.openFiles()},W=(Z,L)=>{L.stopPropagation();const $=K(Z),G=ne.getState(),Q=Dn($,n);if(G.isMobile){G.navigateToDiff(Q);return}G.openContextDiff(n,Q)},B=()=>I?l.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:[l.jsx("div",{className:"typography-meta font-medium",style:{color:"var(--status-error)"},children:"LSP errors"}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"flex items-center gap-1 min-w-0",children:l.jsx(Xy,{path:I.displayPath,grow:!1})}),l.jsx("div",{className:"space-y-1",children:I.diagnostics.map((Z,L)=>l.jsx("div",{className:"rounded-md border px-2 py-1",style:{borderColor:"var(--status-error-border)",backgroundColor:"var(--surface-elevated)"},children:l.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[l.jsxs("span",{className:"typography-micro shrink-0",style:{color:"var(--status-error)"},children:["[",Z.line,":",Z.character,"]"]}),l.jsx("span",{className:"typography-meta text-foreground whitespace-pre-wrap break-words",children:Z.message})]})},`${I.displayPath}:${Z.line}:${Z.character}:${L}`))}),I.remaining>0?l.jsx("div",{className:"typography-micro text-muted-foreground",children:`+${I.remaining} more errors`}):null]})]}):null;if(e.tool==="question"){if(t.status==="completed"&&p){const L=QV(y);if(L&&L.length>0)return R(l.jsx("div",{className:"space-y-2",children:L.map(($,G)=>l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"typography-micro text-muted-foreground",children:$.question}),l.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:$.answer})]},G))}),{maxHeightClass:"max-h-[40vh]"})}if(t.status==="error"&&"error"in t)return l.jsxs("div",{children:[l.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),l.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:un(t.error)})]});const Z=f;return Z?.questions&&Array.isArray(Z.questions)&&Z.questions.length>0?R(l.jsx("div",{className:"space-y-2",children:Z.questions.map((L,$)=>l.jsxs("div",{className:"space-y-0.5",children:[L.header?l.jsx("div",{className:"typography-micro text-muted-foreground",children:un(L.header)}):null,l.jsx("div",{className:"typography-meta text-foreground",children:un(L.question)}),Array.isArray(L.options)&&L.options.length>0?l.jsx("div",{className:"flex flex-wrap gap-1 mt-0.5",children:L.options.map(G=>l.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-muted/30 border border-border/30 text-muted-foreground",children:un(G.label)},un(G.label)))}):null]},$))}),{maxHeightClass:"max-h-[40vh]"}):l.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(e.tool==="task"&&p)return R(l.jsx("div",{className:"w-full min-w-0",children:l.jsx(ka,{content:un(y),variant:"tool",onShowPopup:s})}));if((e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&(k.length>0||I))return R(l.jsxs("div",{className:"space-y-3",children:[k.map(Z=>l.jsxs("div",{className:"w-full min-w-0",children:[l.jsxs("div",{className:"mb-1 flex min-w-0 items-center gap-1 px-2 py-1",children:[l.jsx("div",{className:"min-w-0 flex-1 typography-meta font-medium text-muted-foreground",children:l.jsx(Xy,{path:Z.title})}),l.jsx(Me,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:L=>V(Z,L),"aria-label":"Open file at first change",title:"Open file at first change",children:l.jsx(F,{name:"file-edit",className:"h-3.5 w-3.5"})}),l.jsx(Me,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:L=>W(Z,L),"aria-label":"Open file diff",title:"Open file diff",children:l.jsx(F,{name:"git-pull-request",className:"h-3.5 w-3.5"})})]}),Z.renderMode==="diff"?l.jsx(s5,{diff:Z.patch,diffViewMode:i}):l.jsx(R4,{diff:Z.patch})]},Z.id)),B()]}),{className:"p-1"});if(e.tool==="write"&&I)return R(l.jsx("div",{className:"space-y-3",children:B()}),{className:"p-1"});if(M)return null;if(p&&y.trim()){const Z=l.jsx(fp,{output:un(y),part:e,metadata:d,input:f,isStreaming:g});return R(Z,{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?y:void 0})}return R(l.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})},N=y.trim().length>0,D=t.status==="completed"&&"output"in t||e.tool==="bash"&&N;if(T){if(t.status==="error"&&"error"in t)return l.jsxs("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:[l.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),l.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 K=ZB(A,{total:"Total",inProgress:"In Progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},{unstyled:!0});return l.jsx("div",{className:"oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4",children:R(K??l.jsx(fp,{output:A,part:e,metadata:d,input:f}),{className:"p-2",maxHeightClass:"max-h-[46vh]"})})}return l.jsxs("div",{className:P("oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4"),children:[e.tool==="question"?O():l.jsxs(l.Fragment,{children:[E?l.jsx("div",{className:"my-1",children:R(e.tool==="bash"?l.jsx("pre",{className:"tool-input-text whitespace-pre-wrap break-words typography-code text-muted-foreground/90 m-0 p-0",children:_}):M&&j?l.jsx(s5,{diff:j,diffViewMode:i}):l.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:_}),{maxHeightClass:M&&j&&r?"max-h-[50vh]":"max-h-60",className:e.tool==="bash"?"tool-input-surface p-0 rounded-none":"tool-input-surface"})}):null,D&&l.jsxs("div",{children:[(e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&w?l.jsx("div",{className:"mb-1 flex items-center justify-end gap-2",children:l.jsx(HB,{mode:i,onModeChange:a,className:"h-5 w-5 p-0"})}):null,O()]}),t.status==="error"&&"error"in t&&l.jsxs("div",{children:[l.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),l.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:un(t.error)})]})]}),Array.isArray(S)&&S.length>0&&t.status==="completed"?l.jsx(km,{files:S,onShowPopup:s,compact:!0}):null]})});O4.displayName="ToolExpandedContent";const hc=[];let ta;const H4=()=>{for(;hc.length>0;){const e=hc.pop();if(!e)break;if(e.active){e.fn(),ta=hc.length>0?window.requestAnimationFrame(H4):void 0;return}}ta=void 0},i$=e=>{if(typeof window>"u")return e(),()=>{};const t={active:!0,fn:e};return hc.push(t),ta===void 0&&(ta=window.requestAnimationFrame(()=>{ta=window.requestAnimationFrame(H4)})),()=>{t.active=!1}},o5=e=>{const[t,n]=h.useState(e),r=h.useRef(!1);return h.useEffect(()=>{if(!e){r.current=!0,n(!1);return}if(!r.current){r.current=!0,n(!0);return}return i$(()=>{n(!0)})},[e]),t},a$=new Set(["bash","edit","write","apply_patch","patch"]),l$=(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`},i5=({start:e,end:t,active:n})=>{const r=h4(n,250);return l.jsx(l.Fragment,{children:l$(e,t,r)})},a5=(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},c$=(e,t)=>a5(e.call,t.call)&&a5(e.result,t.result),d$=h.memo(({call:e,result:t})=>{const n=Array.isArray(e)&&e.length>0,r=Array.isArray(t)&&t.length>0;return!n&&!r?null:l.jsxs("div",{className:P("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)=>l.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:l.jsx(Gt,{text:s})},`call-${o}`)),r&&t.map((s,o)=>l.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:l.jsx(Gt,{text:s})},`res-${o}`))]})},c$),u$=({part:e,isExpanded:t,onToggle:n,isMobile:r,onContentChange:s,onShowPopup:o,animateTailText:i=!0})=>{const a=pe(ie=>ie.currentSessionId),c=e.state?.deferredBody===!0,d=AM(a,e.id,t&&c),f=t&&d&&d.type==="tool"?d:e,u=f.state,p=u,m=p.metadata,g=p.input,b=Bn()??"",y=u?.render,S=!!(y&&(Array.isArray(y.call)&&y.call.length>0||Array.isArray(y.result)&&y.result.length>0||Array.isArray(y.resultExpanded)&&y.resultExpanded.length>0)),v=bs(e.tool),x=v==="task",k=u?.status,w=k==="completed"||k==="error"||k==="aborted"||k==="failed"||k==="timeout"||k==="cancelled",C=k==="completed",I=k==="error"||k==="failed",[_,E]=h.useState(!w),M=h.useRef(e.id),T=h.useRef(!w);h.useEffect(()=>{M.current!==e.id&&(M.current=e.id,T.current=!w,E(!w))},[w,e.id]),h.useEffect(()=>{w||E(!0)},[w]),h.useEffect(()=>{if(!w){T.current=!0;return}if(!T.current)return;if(!C||!a$.has(v)){T.current=!1;return}if(!b)return;T.current=!1;const ee=OV(v,g,m).map(oe=>Dn(oe,b));Vd.requestGitRefresh({directory:b,...ee.length>0?{paths:ee}:{}})},[b,g,w,C,m,v]);const A=w||x||S,j=h.useRef(s);j.current=s;const R=h.useRef(null);h.useLayoutEffect(()=>{if(x||S)return;const ie=R.current;ie&&(ie.style.height=t?"auto":"0px",ie.style.overflow=t?"visible":"hidden",A&&j.current?.("structural"))},[S,t,x,A]);const O=h.useRef(t);h.useEffect(()=>{const ie=O.current!==t;O.current=t,!(!S||!t&&!ie)&&j.current?.("structural")},[S,t,y?.call,y?.result,y?.resultExpanded]);const N=e.metadata,D=p.time,[K,V]=h.useState(()=>({start:typeof D?.start=="number"?D.start:void 0,end:typeof D?.end=="number"?D.end:void 0})),[W,B]=h.useState(void 0),[Z,L]=h.useState(void 0);h.useEffect(()=>{V({}),B(void 0),L(void 0)},[e.id]),h.useEffect(()=>{w||typeof D?.start!="number"&&B(ie=>ie??Date.now())},[w,D?.start]),h.useEffect(()=>{V(ie=>{const ee={...ie};let oe=!1;return typeof D?.start=="number"&&(typeof ie.start!="number"||D.start<ie.start)&&(ee.start=D.start,oe=!0),typeof D?.end=="number"&&(typeof ie.end!="number"||D.end>ie.end)&&(ee.end=D.end,oe=!0),oe?ee:ie})},[D?.end,D?.start]);const $=h.useMemo(()=>{const ie=[K.start,D?.start].filter(ee=>typeof ee=="number");return ie.length>0?Math.min(...ie):W},[W,K.start,D?.start]),G=h.useMemo(()=>typeof p.output=="string"?p.output:void 0,[p.output]),Q=h.useMemo(()=>E4(G),[G]),z=h.useMemo(()=>{if(!x)return[];const ie=m,ee=_4(ie?.summary??ie?.entries??ie?.tools??ie?.calls);return ee.length>0?ee:Q.summaryEntries},[x,m,Q.summaryEntries]),X=w&&z.length>0,Y=h.useMemo(()=>{if(!x)return;const ie=Wy(m);if(ie)return ie;const ee=Wy(N);return ee||(Q.sessionId?Q.sessionId:oB(G))},[x,m,Q.sessionId,N,G]);h.useEffect(()=>{if(typeof D?.end=="number"||typeof K.end=="number"){L(void 0);return}typeof $=="number"&&w&&L(ie=>ie??Date.now())},[$,w,K.end,D?.end]);const ce=w?K.end??D?.end??Z:void 0,se=!w&&_,ue=w,Ie=sB({isTaskTool:x,isExpanded:t,isActive:se,hasFinalMetadataSummary:X,taskSessionId:Y})?Y??"":"",de=Id(Ie);RM(Ie);const Fe=h.useMemo(()=>!x||!Y?[]:!Array.isArray(de)||de.length===0?[]:lB(de),[de,x,Y]),$e=h.useMemo(()=>Fe.length>0?Fe:z,[Fe,z]),Xe=h.useMemo(()=>$e.map(To).join("\0"),[$e]),We=h.useRef(null);h.useEffect(()=>{if(!x){We.current=null;return}const ie=We.current;We.current=Xe,!(ie===null||ie===Xe||$e.length===0)&&j.current?.("structural")},[x,$e.length,Xe]);const Ae=h.useMemo(()=>v==="edit"||v==="multiedit"||v==="apply_patch"?eB(m):null,[m,v]),be=h.useMemo(()=>v==="write"?tB(g):null,[g,v]),te=v==="apply_patch"&&Array.isArray(m?.files)&&(m?.files).length>1,ve=v!==e.tool?{...e,tool:v}:e,we=u?M4(ve,u,b):void 0,je=u?rB(ve,u,b):void 0,Ce=Ma(v||e.tool||"").displayName,ze=h.useMemo(()=>{if(v==="bash"||v==="apply_patch"||v==="lsp"||we&&(v==="apply_patch"||v==="edit"||v==="multiedit"||v==="write"))return null;const ie=p.title;if(typeof ie=="string"&&ie.trim().length>0)return ie;const ee=g?.description;return typeof ee=="string"&&ee.trim().length>0?ee:null},[we,v,p,g]),ht=!!(ze||je||Ae||be),xe=h.useContext(wa),re=(ie,ee)=>{xe?.editor&&(ee.stopPropagation(),fB({currentDirectory:b,editor:xe.editor,file:ie}))},me=ie=>{if(x||S||!xe?.editor){n(e.id);return}let ee,oe;if(v==="edit"||v==="multiedit")ee=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path,typeof ee=="string"&&(oe=qy(v,m,ee));else if(v==="apply_patch")ee=Gm(v,g,m),typeof ee=="string"&&(oe=qy(v,m,ee));else if(["write","create","file_write"].includes(v))ee=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path;else if(v==="lsp"){ee=g?.filePath||g?.file_path||g?.path;const he=g?.line;oe=typeof he=="number"&&Number.isFinite(he)?Math.trunc(he):void 0}if(typeof ee=="string"){ie.stopPropagation();const he=_a(b,ee);xe.editor.openFile(he,oe)}else n(e.id)},fe=ie=>{ie.key!=="Enter"&&ie.key!==" "||(ie.preventDefault(),me(ie))},Se=!x&&I?o4:EF,_e=!x&&I?i4:Ea,Ee=o5(x&&($e.length>0||se||ue||!!Y)),ye=o5(!x&&!S&&t);return!ue&&!se&&!x?null:l.jsxs("div",{children:[l.jsxs("div",{className:P("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)]",te?"flex-wrap items-start cursor-pointer":"items-center cursor-pointer"),"data-chat-activity-row":"true",onClick:te?()=>n(e.id):me,onKeyDown:te?ie=>{ie.target===ie.currentTarget&&(ie.key!=="Enter"&&ie.key!==" "||(ie.preventDefault(),n(e.id)))}:fe,role:"button",tabIndex:0,children:[l.jsx("div",{className:P("flex min-w-0",te?"w-full flex-wrap items-center gap-x-2 gap-y-0.5":"flex-shrink-0 items-center gap-x-1.5"),children:te?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex h-5 flex-shrink-0 items-center gap-1.5",children:[l.jsxs("span",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[l.jsx("span",{className:P("absolute inset-0 flex items-center justify-center transition-opacity",t?"opacity-0":"group-hover/tool:opacity-0"),style:Se,children:ga(v||e.tool)}),l.jsx(F,{name:t?"arrow-down-s":"arrow-right-s",className:P("absolute inset-0 h-3.5 w-3.5 transition-opacity",t?"opacity-100":"opacity-0 group-hover/tool:opacity-100")})]}),l.jsx(Yc,{active:!!(se&&!I),minDurationMs:300,className:P(jo,"flex-shrink-0"),style:_e,children:Ce})]}),l.jsx(uB,{metadata:m,animate:i,showFileIcons:!0,textClassName:It,openDiffLabel:"Open file diff",onFileClick:xe?.editor?re:void 0}),typeof $=="number"?l.jsx("span",{className:P("ml-auto flex-shrink-0 tabular-nums text-muted-foreground/80",It),"aria-label":"Tool duration",children:l.jsx(i5,{start:$,end:typeof ce=="number"?ce:void 0,active:!!(se&&typeof ce!="number")})}):null]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"relative h-5 w-3.5 flex-shrink-0 cursor-pointer",onClick:ie=>{ie.stopPropagation(),n(e.id)},children:[l.jsx("div",{className:P("absolute inset-0 flex items-center justify-center transition-opacity",t&&"opacity-0",!t&&"group-hover/tool:opacity-0"),style:Se,children:ga(v||e.tool||"")}),l.jsx("div",{className:P("absolute inset-0 transition-opacity flex items-center justify-center",t&&"opacity-100",!t&&"opacity-0 group-hover/tool:opacity-100"),children:t?l.jsx(F,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):l.jsx(F,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),l.jsx("div",{className:"flex min-w-0 flex-shrink-0 items-center gap-x-1.5",children:l.jsx(Yc,{active:!!(se&&!I),minDurationMs:300,className:P(jo,"flex-shrink-0"),style:_e,title:Ce,children:Ce})})]})}),!te&&ht?l.jsx("div",{className:P("flex min-w-0 flex-1 items-center",It),style:{color:"var(--tools-description)"},children:l.jsx("span",{className:P("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",It),children:l.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-hidden",children:[ze&&l.jsx("span",{className:P("min-w-0 truncate",It),style:{color:"var(--tools-description)",opacity:.8},title:ze,children:ze}),!ze&&v==="lsp"&&we?l.jsx(ap,{path:we,animate:i,grow:!1,showFileIcons:!0}):null,!ze&&v!=="lsp"&&je&&(we&&je===we?l.jsx(ap,{path:we,animate:i,grow:!1,showFileIcons:!0}):l.jsx(sr,{variant:i?"generate-effect":"static",className:P("min-w-0 truncate",It),style:{color:"var(--tools-description)"},title:je,children:je})),Ae&&l.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:[l.jsxs("span",{style:{color:"var(--status-success)"},children:["+",Ae.added]}),l.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),l.jsxs("span",{style:{color:"var(--status-error)"},children:["-",Ae.removed]})]}),be&&l.jsx("span",{className:"flex-shrink-0 inline-flex items-center gap-0 typography-meta",style:{fontSize:"0.8rem",lineHeight:"1"},children:l.jsxs("span",{style:{color:"var(--status-success)"},children:["+",be]})})]})})}):null,!te&&typeof $=="number"?l.jsx("span",{className:P("ml-auto flex-shrink-0 tabular-nums text-muted-foreground/80",It),"aria-label":"Tool duration",children:l.jsx(i5,{start:$,end:typeof ce=="number"?ce:void 0,active:!!(se&&typeof ce!="number")})}):null]}),S&&t?l.jsx(d$,{call:y?.call,result:y?.resultExpanded&&y.resultExpanded.length>0?y.resultExpanded:y?.result}):null,Ee?l.jsx(gB,{entries:$e,isExpanded:t,isMobile:r,output:G,sessionId:Y,onShowPopup:o,input:g,animateTailText:i,isActive:se}):null,!x&&!S?l.jsx("div",{ref:R,"aria-hidden":!t,style:{height:t?"auto":"0px",overflow:t?"visible":"hidden",overflowAnchor:"none"},children:ye?l.jsxs("div",{className:"relative ml-2 pl-3","data-chat-tool-indent":"true",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute left-0 top-px bottom-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),u?l.jsx(O4,{part:f,state:u,currentDirectory:b,isExpanded:t,onShowPopup:o}):null]}):null}):null]})};class f$ extends h.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 l.jsxs("div",{className:"flex items-center gap-1.5 pr-2 pl-px py-1 min-w-0","data-chat-activity-row":"true",children:[l.jsx("div",{className:"h-3.5 w-3.5 flex-shrink-0",style:o4,children:ga(this.props.toolName)}),l.jsx("span",{className:P(jo,"flex-shrink-0"),style:i4,children:this.props.displayName}),t?l.jsxs("span",{className:P(It,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:t,children:[this.props.errorLabel,": ",t]}):null]})}}const h$=e=>{const t=bs(e.part.tool)||"tool",n=Ma(t).displayName;return l.jsx(f$,{displayName:n,errorLabel:"Error:",resetKey:e.part,toolName:t,children:l.jsx(u$,{...e})})},p$=h.memo(h$,(e,t)=>Zd([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),F4=h.createContext(!1),l5=({disabled:e,children:t})=>l.jsx(F4.Provider,{value:e,children:t}),Xm=({children:e,className:t,skipAnimation:n,forceAnimation:r=!1,ignoreContextDisabled:s=!1,respectReducedMotion:o=!1})=>{const i=h.useContext(F4),a=o&&typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,c=!!n||!s&&i||a,d=r,f=h.useRef(null);f.current===null&&(f.current=d&&!c);const u=f.current,[p,m]=h.useState(!u);return h.useEffect(()=>{if(!u)return;let g=null;const b=()=>m(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?g=window.requestAnimationFrame(b):b(),()=>{g!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(g)}},[u]),u?l.jsx("div",{className:P("w-full transition-all duration-300 ease-out",p?"opacity-100 translate-y-0":"opacity-0 translate-y-2",t),children:e}):l.jsx(l.Fragment,{children:e})},m$=4e3,Ks=new Map,V4=e=>{const t=Ks.get(e);return t?new Set(t):new Set},g$=(e,t)=>{if(Ks.size>=m$&&!Ks.has(e)){const n=Ks.keys().next().value;typeof n=="string"&&Ks.delete(n)}Ks.set(e,new Set(t))},y$=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=V4(r);for(const i of s)o.has(i)&&t.add(i)}return t},v$=({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 x$({activities:e}){const t=ne(g=>g.setImagePreviewOpen),n=h.useMemo(()=>e.filter(g=>g.kind==="tool"&&g.part.type==="tool"),[e]),r=h.useMemo(()=>{const g=new Map;for(const b of n)g.set(b.id,b.messageId);return g},[n]),s=h.useMemo(()=>{const g=new Map;for(const b of n){const y=g.get(b.messageId)??new Set;y.add(b.id),g.set(b.messageId,y)}return g},[n]),[o,i]=h.useState(()=>y$(n)),[a,c]=h.useState({open:!1,title:"",content:""}),d=o,f=h.useRef({ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d});f.current={ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d};const u=h.useCallback(g=>{const b=f.current,y=b.ownerByToolId.get(g);if(!y)return;const S=b.toolIdsByOwner.get(y)??new Set;i(v=>{const x=new Set(v);return x.has(g)?x.delete(g):x.add(g),v$({messageId:y,ownerToolIds:S,nextValue:x,read:V4,write:g$}),x})},[]),p=h.useCallback(g=>{(g.image||g.mermaid)&&(c(g),t(!0))},[t]),m=h.useCallback(g=>{c(b=>({...b,open:g})),t(g)},[t]);return{effectiveExpandedTools:d,popupContent:a,handleToggleTool:u,handleShowPopup:p,handlePopupChange:m}}const b$=xs(()=>ft(()=>import("./ToolOutputDialog-B3RRLhR3.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]))),w$=e=>{const t=h.useRef(e),[n,r]=h.useState(e);return e&&(t.current=!0),h.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}},S$=({activity:e,isLiveTurn:t,activeStreamingMessageId:n,activeStreamingPhase:r})=>t&&n&&e.messageId===n?r??"streaming":"completed",B4=h.memo(({activity:e,animate:t,isExpanded:n,isMobile:r,onContentChange:s,onToggle:o,onShowPopup:i})=>{const a=bs(e.part.tool),c=ZV(a)?l.jsx(p$,{part:e.part,isExpanded:n,onToggle:o,isMobile:r,alwaysShowActions:r,onContentChange:s,onShowPopup:i,animateTailText:t}):l.jsx(lV,{toolName:a,activity:e,animateTailText:t});return l.jsx(Xm,{children:l.jsx(j4,{animate:t,children:c})})},(e,t)=>e.activity.id===t.activity.id&&e.activity.messageId===t.activity.messageId&&e.activity.endedAt===t.activity.endedAt&&Zd([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);B4.displayName="TurnToolActivityRow";const C$=({turn:e,isExpanded:t,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s,onContentChange:o})=>{const{isMobile:i}=Pr(),[a,c]=h.useState(bF),d=w$(t),f=h.useRef(o);f.current=o;const u=h.useCallback(_=>{f.current?.(_)},[]),p=e.activityParts,m=h.useMemo(()=>p.reduce((_,E)=>_+(E.kind==="tool"?1:0),0),[p]),g=h.useMemo(()=>SF(p,a),[p,a]),{effectiveExpandedTools:b,popupContent:y,handleToggleTool:S,handleShowPopup:v,handlePopupChange:x}=x$({activities:p}),k=h.useMemo(()=>p.filter(_=>_.kind==="tool").map(_=>_.id),[p]),w=h.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 _ of k)w.current.knownToolIds.has(_)||w.current.animatedToolIds.add(_);h.useEffect(()=>{const _=w.current;for(const E of k)_.knownToolIds.add(E);_.committed=!0},[k]);const C=h.useCallback(()=>{c(_=>Math.min(m,_+wF)),u("structural")},[u,m]),I=h.useCallback(_=>{const E=S$({activity:_,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s}),M=w.current.animatedToolIds.has(_.id);return _.kind==="reasoning"?l.jsx(OF,{part:_.part,messageId:_.messageId,streamPhase:E,onContentChange:u,withinActivityRail:!0},_.id):_.kind==="justification"?l.jsx(s4,{part:_.part,messageId:_.messageId,streamPhase:E,onContentChange:u,withinActivityRail:!0},_.id):_.part.type!=="tool"?null:l.jsx(B4,{activity:_,animate:M,isExpanded:b.has(_.id),isMobile:i,onContentChange:u,onToggle:S,onShowPopup:v},_.id)},[r,s,b,v,S,n,i,u]);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"chat-message-column",children:l.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?l.jsxs("div",{className:P("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:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 -left-[18px] top-0 w-px",style:{backgroundColor:"var(--tools-border)"}}),l.jsxs("div",{className:"relative min-h-0 overflow-hidden",children:[t&&g.hiddenToolCount>0?l.jsx(Me,{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:C,children:"Load earlier activity"}):null,l.jsx("div",{className:"min-w-0 space-y-1","data-chat-activity-list":"true",children:g.activities.map(I)})]})]}):null})}),y.open?l.jsx(h.Suspense,{fallback:null,children:l.jsx(b$,{popup:y,onOpenChange:x,isMobile:i})}):null]})},k$=h.memo(C$),pc=new Map,M$=(e,t)=>{const n=pc.get(e);if(!n)return!1;let r=!1;for(const s of n)r=s(t)||r;return r},I$=(e,t)=>{const n=pc.get(e)??new Set;return n.add(t),pc.set(e,n),()=>{n.delete(t),n.size===0&&pc.delete(e)}},_$=e=>e.filter(r=>r?.type==="text").map(r=>(r.text||r.content||"").trim()).filter(r=>r.length>0).join(`
190
- `).replace(/\n\s*\n+/g,`
191
- `),E$="Authentication failed for this provider. Please re-authenticate and retry.",j$=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},$4=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:
192
- \`${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})`:"",p=typeof t.data?.message=="string"&&t.data.message.trim()?`
193
- \`${t.data.message.trim()}\``:"";return{text:`Compaction failed temporarily. Retrying${u}...${p}`,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?`
194
- ${d.toLocaleString()} → approximately ${f.toLocaleString()} tokens`:"",p=t.data?.willRetry===!0?`
195
- Retrying the interrupted turn.`:"";return{text:`Session compacted${u}${p}`,variant:"info"}}return i==="aborted"?{text:"Compaction stopped.",variant:"info"}:{text:`Compaction failed.${typeof t.data?.message=="string"&&t.data.message.trim()?`
196
- \`${t.data.message.trim()}\``:""}`,variant:"error"}}return j$(o)?{text:E$,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:
197
- \`${o}\``,variant:"error"}}},T$=({isUser:e,displayParts:t,assistantErrorText:n})=>{if(e){const r=t.filter(a=>a.type==="text").map(a=>{const c=a.shellAction?.output;return typeof c=="string"?c.trim():""}).filter(a=>a.length>0);if(r.length>0)return r.join(`
198
-
199
- `);const s=t.filter(a=>a.type==="text").map(a=>{const c=a.shellAction?.command;return typeof c=="string"?c.trim():""}).filter(a=>a.length>0);return s.length>0?s.join(`
200
- `):t.filter(a=>a.type==="text").map(a=>(a.text||a.content||"").trim()).filter(a=>a.length>0).join(`
201
- `).replace(/\n\s*\n+/g,`
202
- `)}return n&&n.trim().length>0?n:_$(t)},z4=e=>e.type==="subtask",U4=e=>{const t=e;return t.type==="text"&&typeof t.shellAction=="object"&&t.shellAction!==null},A$=e=>!!(e&&typeof e=="object"&&typeof e.type=="string"),Wd=e=>e.filter(A$),Jm=e=>{const t=e,n=t.text;return typeof n=="string"?n:t.content||t.value||""},q4=e=>{if(e.type!=="text")return!1;const t=Jm(e);return!t||t.trim().length===0},Z4=e=>e.type==="text"?!q4(e):z4(e)||U4(e),Qm=e=>e.filter(t=>q4(t)?!1:t.type!=="compaction"),W4=(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)}),L$=(e,t)=>typeof t=="string"&&t.trim().length>0?!0:Qm(e).length>0,e1=(e,t={})=>{const{includeReasoning:n=!0}=t,r=Wd(e),s=r.some(o=>!o.synthetic);return r.filter(o=>{const a=!!o.synthetic;return a&&o.type==="text"&&Jm(o).includes("<system-reminder>")||a&&s||!n&&o.type==="reasoning"?!1:!(o.type==="patch")})},N$=(e,t)=>{const n=$4(e.info)?.text;if(typeof n=="string"&&n.trim().length>0)return!0;const r=e1(e.parts),s=W4(r,t,e.info.id);return Qm(s).length>0},Vf=32,c5=32,R$=({turnId:e,assistantMessages:t,renderMessage:n,deferEarlierMessages:r,activityPartIds:s})=>{const[o,i]=h.useState(Vf),a=t[0],c=h.useMemo(()=>t.filter(v=>N$(v,s)),[s,t]),d=h.useMemo(()=>c.filter(v=>v!==a),[c,a]),f=r&&c.length>Vf,u=f?Math.max(0,o-1):d.length,p=u>=d.length?d:d.slice(-u),m=d.length-p.length;h.useEffect(()=>{i(Vf)},[e]),h.useEffect(()=>I$(e,v=>{if(a?.info.id===v)return!0;const x=d.findIndex(w=>w.info.id===v);if(x<0)return!1;const k=d.length-p.length;return!f||x>=k||i(w=>Math.max(w,d.length-x+1)),!0}),[d,a,f,e,p.length]);const g=h.useCallback(()=>{i(v=>Math.min(d.length+1,v+c5))},[d.length]),b=h.useCallback(()=>{i(d.length+1)},[d.length]),y=h.useCallback(v=>l.jsx(P$,{message:v,renderMessage:n},v.info.id),[n]);if(!f||m===0)return l.jsxs("div",{className:"relative z-0",children:[a?y(a):null,d.map(y)]});const S=m>c5;return l.jsxs("div",{className:"relative z-0",children:[a?y(a):null,l.jsxs("div",{className:"chat-message-column flex flex-wrap items-center justify-center gap-2 py-3",children:[l.jsxs(Me,{type:"button",variant:"secondary",size:"sm",onClick:g,"aria-label":"Load earlier response",className:"gap-1.5 rounded-full px-3.5",children:[l.jsx(F,{name:"history",className:"size-3.5"}),"Load earlier response"]}),S?l.jsx(Me,{type:"button",variant:"ghost",size:"sm",onClick:b,"aria-label":"Load full response",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load full response"}):null]}),p.map(y)]})},P$=h.memo(function({message:t,renderMessage:n}){return n(t)},(e,t)=>e.message===t.message),D$=h.memo(R$),O$="GitHub issue context (JSON)",H$="GitHub pull request context (JSON)",Li=e=>!e||typeof e!="object"?!1:!!e.synthetic,F$=e=>!Array.isArray(e)||e.length===0?!1:e.every(t=>Li(t)),V$=e=>{if(!Array.isArray(e)||e.length===0)return[];const t=e.some(r=>!Li(r)),n=r=>{if(!Li(r)||r.type!=="text")return!1;const s=r.text;if(typeof s!="string")return!1;const o=s.trimStart();return o.startsWith(O$)||o.startsWith(H$)};return t&&e.some(s=>Li(s))?e.filter(s=>!Li(s)||n(s)):e},B$={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},$$=new Map,G4="\0",z$=new Set(["apply_patch","create","edit","file_write","multiedit","str_replace","str_replace_based_edit_tool","write"]),U$={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"},d5=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],K4=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},q$=e=>{const t=K4(e);return U$[t]??`using ${t.replaceAll("_"," ")}`},Z$=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)},W$=e=>d5[Z$(e)%d5.length]??"working",u5=(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=K4(o.tool.name);return{activePartType:z$.has(i)?"editing":"tool",activeToolName:i,statusText:q$(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:W$(n),isGenericStatus:!0}},G$=e=>[e.activePartType??"",e.activeToolName??"",e.statusText,e.isGenericStatus?"1":"0"].join(G4),K$=e=>{const[t,n,r="working",s]=e.split(G4);return{activePartType:t==="text"||t==="tool"||t==="reasoning"||t==="editing"?t:void 0,activeToolName:n||void 0,statusText:r,isGenericStatus:s==="1"}},Y$=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 Y4(){const e=pe(y=>y.currentSessionId);pe(y=>y.currentSessionDirectory);const t=tm(e??""),n=h.useMemo(()=>Y$(t),[t]),r=n.assistantId,s=qe(h.useCallback(y=>{const S=`${e??""}:${r??""}`,v=e?y.reducer.bySession.get(e):void 0,x=aa(v)??r,k=x?v?.partOrder.get(x)??[]:[],w=v?u5(v.parts,k,S):u5($$,[],S);return G$(w)},[e,r]),void 0,e?`session:${e}`:"chrome"),o=pe(h.useCallback(y=>e?y.sessionAbortFlags?.get(e)??null:null,[e])),{phase:i,isWorking:a}=fm(),c=Md(e??""),d=c?.type==="retry"?c.attempt:void 0,f=c?.type==="retry"?c.next:void 0,u=h.useMemo(()=>K$(s),[s]),p=h.useMemo(()=>{const y=!!(o&&!o.acknowledged);return{wasAborted:y,abortActive:y}},[o]),m=h.useMemo(()=>{if(p.wasAborted)return{...B$,wasAborted:!0,abortActive:p.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1,retryInfo:null};const y=a,S=i==="busy",v=!1,x=i==="retry";let k="idle";y&&(u.activePartType==="tool"||u.activePartType==="editing"?k="tooling":k="streaming");const w=x?{attempt:d,next:f}:null;return{activity:k,hasWorkingContext:y,hasActiveTools:u.activePartType==="tool"||u.activePartType==="editing",isWorking:y,isStreaming:S,isCooldown:v,lifecyclePhase:S?"streaming":null,statusText:y?u.statusText:null,isGenericStatus:y?u.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:y,compactionDeadline:null,activePartType:y?u.activePartType:void 0,activeToolName:y?u.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:w}},[i,a,u,p,d,f]),g=h.useMemo(()=>({isActive:a&&u.activePartType==="text",characterCount:0}),[a,u.activePartType]),b=m;return{activeModel:n.model,forming:g,working:b}}const X$=({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,mc=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`},X4=h.memo(({isWorking:e,startedAt:t,statusText:n})=>{const r=pe(p=>p.currentSessionId),s=qe(h.useCallback(p=>(r?p.reducer.bySession.get(r):void 0)?.extensionWorking,[r]),(p,m)=>p?.message===m?.message&&p?.visible===m?.visible,r?`session:${r}`:"chrome"),{activeModel:o,working:i}=Y4(),a=ox(r??""),c=Ze(p=>p.providers),d=h.useMemo(()=>{if(!o)return null;const p=c.find(m=>m.id===o.providerId);return Em(p,o.modelId)||null},[o,c]);if(s?.visible===!1)return null;const f=s?.message?kn(s.message):n??i.statusText,u=s?.message||n?!1:i.isGenericStatus;return l.jsx(ob,{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})});X4.displayName="LiveTurnStatus";const J$=({turnId:e,isLiveTurn:t,isWorking:n,isAwaitingRecovery:r=!1,hasActivity:s,isActivityExpanded:o,onToggleActivity:i,startedAt:a,completedAt:c,durationMs:d,liveStatusText:f,wasSteered:u})=>{const p=X$({startedAt:a,completedAt:c,durationMs:d}),m=!t&&r,g=t?"Agent working":m?"Reconnecting · last seen working":p!==null?`Worked for ${mc(p)}${u?" · Steered":""}`:s?"Agent activity":null,b=`turn-${e}-activity`;return l.jsx("div",{className:"chat-message-column mb-1","data-turn-working-header":"true","data-turn-working":t&&n?"true":"false",children:l.jsxs("div",{className:"flex min-h-6 items-center gap-1 py-0.5",children:[l.jsx("div",{className:"flex min-w-0 items-center overflow-hidden",children:t?l.jsx(X4,{isWorking:n,startedAt:a,statusText:f}):g?l.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?l.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:P("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":b,"aria-label":o?"Collapse activity":"Expand activity","data-turn-activity-toggle":"true",onClick:i,children:l.jsx(F,{name:"arrow-right-s",className:P("size-4 transition-transform duration-200 ease-out motion-reduce:transition-none",o&&"rotate-90"),"aria-hidden":"true"})}):null]})})},Q$=h.memo(J$),ez=({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},tz=h.memo(function({userMessage:t,renderMessage:n}){return n(t)},(e,t)=>e.userMessage===t.userMessage),nz=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")},rz=({turn:e,renderMessage:t,deferEarlierAssistantMessages:n,showWorkingStatus:r=!1,isAwaitingRecovery:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,onActivityContentChange:a})=>{const c=h.useMemo(()=>e.activityParts.length>0,[e.activityParts]),d=h.useMemo(()=>nz(e),[e]),[f,u]=h.useState(()=>r&&c&&!d),p=h.useRef(!1),m=h.useRef(!1),g=h.useRef(e.activityParts.length),b=h.useRef(d);h.useLayoutEffect(()=>{const x=g.current,k=b.current,w=e.activityParts.length>x;g.current=e.activityParts.length,b.current=d;const C=ez({isExpanded:f,userToggled:p.current,wasAutoCollapsed:m.current,hasActivity:c,showWorkingStatus:r,hasFinalText:d,previousHadFinalText:k,hasNewActivity:w});m.current=C.wasAutoCollapsed,C.resetUserToggle&&(p.current=!1),C.isExpanded!==f&&u(C.isExpanded)},[c,d,f,r,e.activityParts.length]);const y=h.useCallback(()=>{p.current=!0,u(x=>!x),a?.("structural")},[a]),S=e.assistantMessages.length>0||r||s,v=h.useMemo(()=>new Set(e.activityParts.map(x=>x.id)),[e.activityParts]);return l.jsxs("section",{className:"relative w-full",id:`turn-${e.turnId}`,"data-turn-id":e.turnId,"data-scroll-spy-id":e.turnId,children:[l.jsx(tz,{userMessage:e.userMessage,renderMessage:t}),S?l.jsx(Q$,{turnId:e.turnId,isLiveTurn:r,isWorking:r,isAwaitingRecovery:s,hasActivity:c,isActivityExpanded:f,onToggleActivity:y,startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,liveStatusText:e.isSteering?"Steering agent":void 0,wasSteered:e.stream.settledReason==="steered"}):null,c?l.jsx(k$,{turn:e,isExpanded:f,isLiveTurn:r,activeStreamingMessageId:o,activeStreamingPhase:i,onContentChange:a},e.turnId):null,l.jsx(D$,{turnId:e.turnId,assistantMessages:e.assistantMessages,renderMessage:t,deferEarlierMessages:n,activityPartIds:v})]})},sz=h.memo(rz),hp="#pichamber-skill:",pp="#pichamber-agent:",oz=e=>`${hp}${encodeURIComponent(e)}`,iz=e=>`${pp}${encodeURIComponent(e)}`,az=e=>{if(!e?.startsWith(hp))return null;try{return decodeURIComponent(e.slice(hp.length))}catch{return null}},NG=e=>{if(!e?.startsWith(pp))return null;try{return decodeURIComponent(e.slice(pp.length))}catch{return null}},lz=/(^|\s)\/skill:([A-Za-z0-9][A-Za-z0-9_-]*)/g,cz=/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g,dz=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),J4=(e,t)=>e.split(cz).map((n,r)=>r%2===1?n:t(n)).join(""),uz=e=>J4(e,t=>t.replace(/ *\n/g,`
203
- `)),fz=({textContent:e,agentMention:t,skillNames:n})=>{let r=J4(e,dz);if(t?.token&&r.includes(t.token)){const s=`[${t.token}](${iz(t.name)})`;r=r.replace(t.token,s)}return r=r.replace(lz,(s,o,i)=>n.has(i)?`${o}[/skill:${i}](${oz(i)})`:s),uz(r)},hz=({part:e,messageId:t,agentMention:n})=>{const r=e,s=r.text,i=typeof s=="string"?s:r.content||r.value||"",[a,c]=h.useState(!1),[d,f]=h.useState(!1),u=kr(w=>w.skills),p=Ia(),m=!a,g=h.useRef(null),b=h.useMemo(()=>new Map(u.map(w=>[w.name,w])),[u]),y=h.useCallback(w=>{b.has(w)&&c4(w,p)},[p,b]),S=h.useCallback(w=>{if(typeof window>"u")return!1;const C=window.getSelection();if(!C||C.isCollapsed||C.rangeCount===0)return!1;const I=C.getRangeAt(0);return w.contains(I.startContainer)||w.contains(I.endContainer)},[]);h.useEffect(()=>{const w=g.current;if(!w)return;const C=()=>{a||f(w.scrollHeight>w.clientHeight)};C();const I=new ResizeObserver(C);return I.observe(w),()=>I.disconnect()},[i,a]);const v=h.useCallback(w=>{const C=w.target,_=C?.closest("[data-skill-name]")?.dataset.skillName??az(C?.closest("a[href]")?.getAttribute("href"));if(_){w.preventDefault(),w.stopPropagation(),y(_);return}const E=g.current;E&&(S(E)||!a&&d&&c(!0))},[S,a,d,y]),x=h.useCallback(w=>{w.stopPropagation(),c(!1)},[]),k=h.useMemo(()=>fz({textContent:i,agentMention:n,skillNames:new Set(b.keys())}),[n,b,i]);return!i||i.trim().length===0?null:l.jsxs("div",{className:"relative",children:[a&&l.jsx("button",{type:"button",onClick:x,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:l.jsx(F,{name:"arrow-up-s",className:"h-3.5 w-3.5"})}),l.jsx("div",{className:P("break-words font-sans typography-markdown-body",a&&"pb-3",m&&"line-clamp-2",d&&!a&&"cursor-pointer"),ref:g,onClick:v,children:l.jsx(ka,{content:k,className:P("[&_.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`)},pz=h.memo(hz),mz="application/vnd.github.issue-link",gz="application/vnd.github.pull-request-link",Q4=e=>e.mime===mz?"issue":e.mime===gz?"pr":null,ew=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`,yz=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},vz=e=>{if(!e)return"Unnamed file";const n=e.replace(/\\/g,"/").split("/");return n[n.length-1]||e},mp=e=>Q4(e)!==null&&typeof e.filename=="string"&&e.filename.trim().length>0?e.filename.trim():vz(e.filename||e.url),tw=U.memo(({files:e,onShowPopup:t,className:n})=>{const[r,s]=U.useState(!1),[o,i]=U.useState(null),a=U.useRef(null),c=U.useMemo(()=>e.filter(y=>y.type==="file"&&(y.filename||y.mime||y.url)),[e]),d=c.length,f=U.useCallback(()=>{const y=a.current?.closest('[data-slot="dialog-content"], [role="dialog"]');i(y||null)},[]),u=U.useCallback(y=>{ne.getState().navigateToDiagram(y),s(!1)},[]);if(d===0)return null;const p=c[0],m=mp(p),g=ew(p.size),b=d===1?`${m}${g?` (${g})`:""}`:`${d} attachments`;return l.jsxs(dv,{open:r,onOpenChange:s,children:[l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(uv,{render:l.jsxs("button",{ref:a,type:"button",className:P("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:[l.jsx(F,{name:"attachment-2",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate max-w-[200px]",children:b}),l.jsx(F,{name:r?"arrow-up-s":"arrow-down-s",className:"h-3.5 w-3.5 shrink-0 opacity-60"})]})})}),l.jsx(gt,{side:"top",children:d===1?`Attachment: ${m}`:`View ${d} attachments`})]}),l.jsx(fv,{container:o||void 0,children:l.jsx(hv,{side:"top",align:"end",sideOffset:6,collisionPadding:8,children:l.jsxs(pv,{style:mb,className:P(pb,"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:[l.jsx("div",{className:"flex items-center justify-between border-b border-border/30 pb-2",children:l.jsxs("span",{className:"text-xs font-semibold text-foreground flex items-center gap-1.5",children:[l.jsx(F,{name:"attachment-2",className:"h-3.5 w-3.5 text-muted-foreground"}),"Attachments (",d,")"]})}),l.jsx("div",{className:"space-y-3 divide-y divide-border/20",children:c.map((y,S)=>{const v=y.url||`${mp(y)}-${S}`;return l.jsx(xz,{file:y,onShowPopup:t,onNavigateToDiagram:u},v)})})]})})})]})}),xz=U.memo(function({file:t,onShowPopup:n,onNavigateToDiagram:r}){const s=mp(t),o=yz(s),i=ew(t.size),c=!!(t.mime?.startsWith("image/")&&t.url),d=Q4(t),f=t.source,u=typeof f?.type=="string"?f.type:void 0,p=f&&typeof f.path=="string"?f.path:void 0,m=u==="file"&&p?p:t.url||"",g=m&&$3(m),b=U.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]),y=U.useCallback(x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),b())},[b]),S=l.jsxs("div",{className:"flex items-start gap-2.5",children:[l.jsx(rr,{filePath:s,extension:o,className:"size-5 shrink-0 mt-0.5"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"text-xs font-medium text-foreground truncate",title:s,children:s}),l.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:[o.toUpperCase()||"FILE",t.mime,i].filter(Boolean).join(" · ")})]}),d&&t.url?l.jsx("button",{type:"button",onClick:x=>{x.stopPropagation(),Lh(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:l.jsx(F,{name:"github",className:"h-4 w-4"})}):g?l.jsx("button",{type:"button",onClick:x=>{x.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:l.jsx(F,{name:"external-link",className:"h-4 w-4"})}):null]});if(!c||!t.url)return l.jsx("div",{className:"pt-3 first:pt-0 space-y-2",children:S});const v=t.url;return l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx("div",{role:"button",tabIndex:0,"aria-label":`Preview ${s}`,onClick:b,onKeyDown:y,className:"pt-3 first:pt-0 space-y-2 cursor-pointer rounded-lg",children:S})}),l.jsx(gt,{side:"left",className:P(U3),children:l.jsx(q3,{imageUrl:v,filename:s,metaLine:[o.toUpperCase(),i].filter(Boolean).join(" · ")})})]})});tw.displayName="UserMessageAttachments";const nw=e=>{if(e==="12h")return!0;if(e==="24h")return!1},bz=(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:nw(t)}):n.fallback??""},RG=(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?nw(t):n.hour12}):""},rw=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),wz=(e,t)=>{const n=new Date(t);return n.setDate(t.getDate()-1),rw(e,n)},Sz=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),sw=(e,t)=>{if(!Sz(e))return"";const n=new Date(e),r=new Date,s=bz(n,t),o="en-US";if(rw(n,r))return s;if(wz(n,r))return`Yesterday ${s}`;const i=n.toLocaleString(o,{month:"short"}),a=n.getDate(),c=`${i} ${a}`;return n.getFullYear()===r.getFullYear()?`${c}, ${s}`:`${c}, ${n.getFullYear()}, ${s}`},t1=h.memo(({sessionId:e,messageId:t,size:n="user",isLatestMessage:r=!1})=>{const s=pe(m=>m.revertToMessage),[o,i]=h.useState(!1),[a,c]=h.useState(()=>{if(!e)return!1;const g=Ge().getState().reducer.bySession.get(e);return g?.lifecycle==="busy"||g?.lifecycle==="retry"});h.useEffect(()=>{if(!e){c(!1);return}const m=()=>{const b=Ge().getState().reducer.bySession.get(e);c(b?.lifecycle==="busy"||b?.lifecycle==="retry")};return m(),Ge().subscribe(m,`session:${e}`)},[e]);const d=h.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),ke.success("Reverted — conversation rewound. Files on disk were not changed.")}catch(b){const y=b instanceof Error?b.message:"Failed to revert conversation";ke.error(y)}finally{i(!1)}},[o,a,t,s,e]),f=o||a||!e||!t,u=n==="user"?"h-6 w-6":"h-8 w-8",p=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return r?null:l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(Me,{type:"button",variant:"ghost",size:"icon",disabled:f,"aria-label":"Revert conversation to here",className:P(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?l.jsx(F,{name:"loader-4",className:P(p,"animate-spin"),"aria-hidden":"true"}):l.jsx(F,{name:"history",className:p,"aria-hidden":"true"})})}),l.jsx(gt,{sideOffset:6,children:"Revert to here"})]})});t1.displayName="MessageRevertAction";const n1=h.memo(({sessionId:e,messageId:t,size:n="user"})=>{const r=pe(p=>p.forkFromMessage),[s,o]=h.useState(!1),[i,a]=h.useState(()=>{if(!e)return!1;const m=Ge().getState().reducer.bySession.get(e);return m?.lifecycle==="busy"||m?.lifecycle==="retry"});h.useEffect(()=>{if(!e){a(!1);return}const p=()=>{const g=Ge().getState().reducer.bySession.get(e);a(g?.lifecycle==="busy"||g?.lifecycle==="retry")};return p(),Ge().subscribe(p,`session:${e}`)},[e]);const c=h.useCallback(async p=>{if(p.stopPropagation(),p.preventDefault(),!e||!t||s||i)return;const m=t.includes(":")?t.split(":")[0]??t:t;o(!0);try{await r(e,m),ke.success("Forked — new session created from this message.")}catch(g){const b=g instanceof Error?g.message:"Failed to fork session";ke.error(b)}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 l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(Me,{type:"button",variant:"ghost",size:"icon",disabled:d,"aria-label":"Fork conversation from here",className:P(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:p=>p.stopPropagation(),onClick:c,children:s?l.jsx(F,{name:"loader-4",className:P(u,"animate-spin"),"aria-hidden":"true"}):l.jsx(F,{name:"git-branch",className:u,"aria-hidden":"true"})})}),l.jsx(gt,{sideOffset:6,children:"Fork to new session"})]})});n1.displayName="MessageForkAction";const Cz=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}`},kz=({part:e})=>{const[t,n]=h.useState(!1),r=Bn(),s=pe(m=>m.setCurrentSession),o=Ia(),i=typeof e.description=="string"?e.description.trim():"",a=typeof e.command=="string"?e.command.trim():"",c=typeof e.agent=="string"?e.agent.trim():"",d=typeof e.prompt=="string"?e.prompt.trim():"",f=typeof e.taskSessionID=="string"?e.taskSessionID.trim():"",u=Cz(e.model),p=h.useCallback(()=>{!r||!f||(s(f,r),o?.closeDrawers?.())},[r,f,s,o]);return l.jsxs("div",{className:"mt-2",children:[l.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[l.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Delegated task"}),a?l.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,c?l.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground",children:["@",c]}):null,u?l.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?l.jsx("div",{className:"typography-ui-label text-foreground/90 mt-1.5",children:i}):null,d?l.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[l.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?l.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?l.jsx("div",{className:"mt-1.5",children:l.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:p,children:"Open subtask session"})}):null]})},f5={background:"transparent",backgroundColor:"transparent"},Mz=({part:e})=>{const t=typeof e.shellAction?.output=="string"?e.shellAction.output:"",[n,r]=h.useState(!0),{value:s,show:o}=$m(!1,2e3),i=typeof e.shellAction?.command=="string"?e.shellAction.command.trim():"",a=typeof e.shellAction?.status=="string"?e.shellAction.status.trim().toLowerCase():"",c=t.trim().length>0,d=h.useCallback(async()=>{!c||!(await ir(t)).ok||o(!0)},[c,t,o]);return l.jsxs("div",{className:"mt-2",children:[l.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[l.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Shell command"}),a?l.jsx("span",{className:P("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?l.jsx("div",{className:"typography-meta mt-1.5 overflow-x-auto font-mono","data-no-drawer-swipe":"true",children:l.jsx(td,{language:"bash",code:i,codeStyle:f5,wrap:!0})}):null,c?l.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[l.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[l.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"}),l.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?l.jsx(F,{name:"check",className:"h-3.5 w-3.5"}):l.jsx(F,{name:"file-copy",className:"h-3.5 w-3.5"})})]}),n?l.jsx("div",{className:"typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85",children:l.jsx(td,{language:"bash",code:t,codeStyle:f5,wrap:!0})}):null]}):null]})},Iz={contain:"layout",transform:"translateZ(0)"},_z=h.memo(function({sessionId:t,messageId:n,parts:r,messageCreatedAt:s,isLatestMessage:o=!1,isMobile:i,alwaysShowActions:a=i,hasTouchInput:c,hasTextContent:d,onCopyMessage:f,copiedMessage:u,onShowPopup:p,agentMention:m,userActionsMode:g="inline"}){const b=ne(V=>V.timeFormatPreference),[y,S]=h.useState(!1),v=h.useRef(null),x=h.useMemo(()=>r.filter(Z4),[r]),k=h.useMemo(()=>r.filter(V=>V.type==="file"&&!!(V.filename||V.mime||V.url)),[r]),w=m?.token;let C=!1;const I=!!f,_=!!u,E=!!(c??i),M=!!d,T=g!=="external-actions",A=g!=="external-content",j=h.useCallback(()=>{v.current!==null&&typeof window<"u"&&(window.clearTimeout(v.current),v.current=null)},[]),R=h.useCallback(()=>{!E||!I||!M||typeof window>"u"||(j(),S(!0),v.current=window.setTimeout(()=>{S(!1),v.current=null},1800))},[I,j,M,E]);h.useEffect(()=>{M||(S(!1),j())},[j,M]);const O=h.useCallback(V=>{!f||!M||(V.stopPropagation(),V.preventDefault(),f(),E&&R())},[M,E,f,R]),N=h.useMemo(()=>{if(typeof s!="number"||s<=0)return null;const V=sw(s,b);return V.length>0?V:null},[s,b]),D=i||a,K=A?l.jsx("div",{className:P("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:l.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-3 gap-y-1",children:[l.jsxs("div",{className:P("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:[N?l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("span",{className:"mr-1 flex items-center gap-1 text-sm tabular-nums text-muted-foreground/60","aria-label":`Message time: ${N}`,children:[l.jsx(F,{name:"time",className:"h-3.5 w-3.5"}),l.jsx("span",{className:"message-footer__label",children:N})]})}),l.jsx(gt,{children:N})]}):null,o?null:l.jsx(t1,{sessionId:t??null,messageId:n,size:"assistant"}),l.jsx(n1,{sessionId:t??null,messageId:n,size:"assistant"}),I&&M&&l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(Me,{type:"button",variant:"ghost",size:"icon","data-visible":y||_?"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:V=>V.stopPropagation(),onClick:O,onFocus:()=>S(!0),onBlur:()=>{_||S(!1)},children:_?l.jsx(F,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):l.jsx(F,{name:"file-copy",className:"h-3.5 w-3.5"})})}),l.jsx(gt,{sideOffset:6,children:"Copy message"})]})]}),k.length>0?l.jsx(tw,{files:k,onShowPopup:p}):null]})}):null;return T?l.jsxs("div",{className:"relative w-full group/message",style:Iz,onTouchStart:E&&I&&M?R:void 0,children:[l.jsx("div",{className:P("leading-relaxed text-foreground/90 text-base overflow-x-hidden","overflow-y-hidden"),style:void 0,children:x.map((V,W)=>{if(z4(V))return l.jsx(h.Fragment,{children:l.jsx(kz,{part:V})},V.id??`user-subtask-${W}`);if(U4(V))return l.jsx(h.Fragment,{children:l.jsx(Mz,{part:V})},V.id??`user-shell-${W}`);let B;return m&&w&&!C&&Jm(V).includes(w)&&(B=m,C=!0),l.jsx(h.Fragment,{children:l.jsx(pz,{part:V,messageId:n,isMobile:i,agentMention:B})},V.id??`user-text-${W}`)})}),K]}):l.jsx(l.Fragment,{children:K})}),h5=8,Ez=280,jz=({containerRef:e})=>{const[t,n]=h.useState({x:0,y:0,show:!1}),[r,s]=h.useState(""),[o,i]=h.useState(""),a=h.useRef(!1),[c,d]=h.useState(!1),f=h.useRef(null),u=h.useRef(Ez),p=h.useRef(null),m=h.useRef(null),g=h.useRef(null),b=h.useRef(!1),y=pe(M=>M.createSession),S=Ke(M=>M.setPendingInputText),v=ne(M=>M.isMobile);h.useEffect(()=>{b.current=t.show},[t.show]),h.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),g.current!==null&&(window.clearTimeout(g.current),g.current=null)},[]);const x=h.useCallback(()=>{p.current=null,b.current&&(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),d(!1),n(M=>({...M,show:!1})),s(""),i(""),b.current=!1)},[]),k=h.useCallback(M=>{if(typeof window>"u")return M;const T=window.innerWidth,j=u.current/2,R=h5+j,O=T-h5-j;return R>O?T/2:Math.min(Math.max(M,R),O)},[]),w=h.useCallback(()=>{if(!p.current)return;const{plainText:M,markdownText:T,rect:A}=p.current,j=!t.show,R=v?A.left+A.width/2:k(A.left+A.width/2),O=A.top-10;s(M),i(T),n({x:R,y:O,show:!0}),b.current=!0,j&&(d(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{d(!1),m.current=null}))},[k,v,t.show]);h.useLayoutEffect(()=>{if(!t.show||v||!f.current)return;const M=f.current.offsetWidth;!Number.isFinite(M)||M<=0||M===u.current||(u.current=M,n(T=>({...T,x:k(T.x)})))},[k,v,t.show]),h.useEffect(()=>{if(!t.show||v)return;const M=()=>{n(T=>({...T,x:k(T.x)}))};return window.addEventListener("resize",M),()=>{window.removeEventListener("resize",M)}},[k,v,t.show]);const C=h.useCallback(()=>{const M=window.getSelection(),T=e.current;if(!M||!T){a.current||x();return}const A=pn(M.toString());if(!A){a.current||x();return}const j=M.getRangeAt(0);if(!T.contains(j.commonAncestorContainer)){a.current||x();return}const R=j.getBoundingClientRect();p.current={plainText:A,markdownText:_3(j,A),rect:R},a.current||w()},[e,x,w]);h.useEffect(()=>{const M=e.current;if(!M)return;const T=()=>{a.current=!0,x()},A=()=>{a.current=!1,p.current&&(g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{g.current=null;const R=window.getSelection();R&&R.toString().trim()?w():x()},10))};document.addEventListener("selectionchange",C),M.addEventListener("mousedown",T),document.addEventListener("mouseup",A);const j=R=>{f.current&&!f.current.contains(R.target)&&!window.getSelection()?.toString().trim()&&x()};return document.addEventListener("mousedown",j),()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null),document.removeEventListener("selectionchange",C),M.removeEventListener("mousedown",T),document.removeEventListener("mouseup",A),document.removeEventListener("mousedown",j)}},[e,C,x,w]);const I=h.useCallback(()=>{if(!o)return;const M=vm(o);S(M,"append"),x(),window.getSelection()?.removeAllRanges(),queueMicrotask(()=>{fo()})},[o,S,x]),_=h.useCallback(async()=>{if(!r)return;await y(void 0,null,null)&&S(r,"replace"),x(),window.getSelection()?.removeAllRanges()},[r,y,S,x]),E=h.useCallback(async()=>{if(!r)return;const M=await ir(r);M.ok||console.error("Failed to copy:",M.error),x(),window.getSelection()?.removeAllRanges()},[r,x]);return t.show?v?na.createPortal(l.jsx("div",{ref:f,className:P("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]",c?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),style:{bottom:"calc(0.5rem + env(safe-area-inset-bottom, 0px))"},children:l.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[l.jsxs("button",{onClick:I,className:P("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:[l.jsx(F,{name:"add",className:"h-5 w-5 flex-shrink-0"}),l.jsx("span",{className:"min-w-0 whitespace-normal",children:"Add to chat"})]}),l.jsxs("button",{onClick:_,className:P("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:[l.jsx(F,{name:"chat-new",className:"h-5 w-5 flex-shrink-0"}),l.jsx("span",{className:"min-w-0 whitespace-normal",children:"New session"})]}),l.jsxs("button",{onClick:E,className:P("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:[l.jsx(F,{name:"file-copy",className:"h-5 w-5 flex-shrink-0"}),l.jsx("span",{className:"min-w-0 whitespace-normal",children:"Copy"})]})]})}),document.body):na.createPortal(l.jsx("div",{ref:f,className:"fixed z-50",style:{left:t.x,top:t.y,transform:"translate(-50%, -100%)"},children:l.jsxs("div",{className:P("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]",c?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),children:[l.jsxs("button",{onClick:I,className:P("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:[l.jsx(F,{name:"add",className:"h-4 w-4"}),l.jsx("span",{className:"whitespace-nowrap",children:"Add to chat"})]}),l.jsx("div",{className:"w-px h-4 bg-[var(--interactive-border)]"}),l.jsxs("button",{onClick:_,className:P("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:[l.jsx(F,{name:"chat-new",className:"h-4 w-4"}),l.jsx("span",{className:"whitespace-nowrap",children:"New session"})]})]})}),document.body):null},Dl=[{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 Tz(e){if(!e||e==="build")return Dl[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)%(Dl.length-1);return Dl[n]}const Az=h.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,onShareImage:r,sessionId:s,messageId:o,isLatestMessage:i=!1})=>{const a=zd(),[c,d]=h.useState(!1),{value:f,show:u,clear:p}=$m(!1,2e3),[m,g]=h.useState(!1),b=h.useRef(null),y=!!n,S=h.useCallback(()=>{b.current!==null&&typeof window<"u"&&(window.clearTimeout(b.current),b.current=null)},[]);h.useEffect(()=>S,[S]),h.useEffect(()=>{(!e||!y)&&(d(!1),S(),p())},[y,S,p,e]);const v=h.useCallback(()=>{!t||!y||!e||typeof window>"u"||(S(),d(!0),b.current=window.setTimeout(()=>{d(!1),b.current=null},1800))},[y,S,e,t]),x=h.useCallback(async w=>{!n||!e||(w.stopPropagation(),w.preventDefault(),await n()===!1)||(u(!0),t&&v())},[e,t,n,v,u]),k=h.useCallback(async w=>{if(w.stopPropagation(),w.preventDefault(),!(m||!e)){g(!0);try{const I=w.currentTarget.closest("[data-message-text-export-root]")?.querySelector("[data-message-text-export-source]")??null;await r(I)}finally{g(!1)}}},[e,m,r]);return l.jsxs(l.Fragment,{children:[s&&o&&!i?l.jsx(t1,{sessionId:s,messageId:o,size:"assistant"},"message-revert"):null,s&&o?l.jsx(n1,{sessionId:s,messageId:o,size:"assistant"},"message-fork"):null,n&&l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(Me,{type:"button",variant:"ghost",size:"icon","data-visible":c||f?"true":void 0,className:P("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=>{x(w)},onFocus:()=>{e&&d(!0)},onBlur:()=>{f||d(!1)},children:f?l.jsx(F,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):l.jsx(F,{name:"file-copy",className:"h-3.5 w-3.5"})})}),l.jsx(gt,{sideOffset:6,children:"Copy answer"})]},"message-copy"),a!=="mini-chat"?l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(Me,{type:"button",size:"icon",variant:"ghost",disabled:m||!e,className:P("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=>{k(w)},children:m?l.jsx(F,{name:"loader-4",className:"h-4 w-4 animate-spin"}):l.jsx(F,{name:"image-download",className:"h-4 w-4"})})}),l.jsx(gt,{sideOffset:6,children:m?"Saving image...":"Save as image"})]},"message-share"):null]})});async function Lz(e,t){const n=t;if(!n)return;let r=null;try{const{toPng:s}=await ft(async()=>{const{toPng:v}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{toPng:v}},[]),o=n,i=window.getComputedStyle(o),c=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=`
204
- padding: ${d}px;
205
- background-color: ${c};
206
- display: inline-block;
207
- `;const f=o.cloneNode(!0);f.style.cssText=`
208
- ${i.cssText}
209
- transform: none;
210
- contain: none;
211
- `,f.querySelectorAll('[data-message-actions="true"]').forEach(v=>{v.style.display="none"}),f.querySelectorAll('[data-message-action-group="true"]').forEach(v=>{v.style.display="none"});const m=f.querySelectorAll('[aria-label^="Message time:"]'),g=new Set;m.forEach(v=>{const k=v.getAttribute("aria-label")?.replace("Message time:","").trim();if(!k||v.textContent?.includes(k))return;const w=document.createElement("span");w.style.marginLeft="4px",w.textContent=k,v.appendChild(w);const I=v.parentElement?.parentElement;!I||g.has(I)||(I.style.justifyContent="flex-start",g.add(I))}),r.appendChild(f),document.body.appendChild(r);const b=await s(r,{quality:1,pixelRatio:2,backgroundColor:c}),y=`message-${e}.png`,S=await vS({filename:y,mimeType:"image/png",data:b});S==="downloaded"?ke.success("Image saved"):S==="shared"&&ke.success("Image shared")}catch(s){console.error("Failed to generate image:",s),ke.error("Failed to generate image")}finally{r&&r.parentNode&&r.parentNode.removeChild(r)}}function Nz({visibleParts:e,isMessageCompleted:t,messageFinish:n,messageCompletedAt:r,messageCreatedAt:s,durationMs:o,turnGroupingContext:i,errorMessage:a,isMobile:c,isMiniChatSurface:d,timeFormatPreference:f}){const u=h.useMemo(()=>e.filter(w=>w.type==="text"),[e]),p=h.useMemo(()=>{if(c||d)return null;for(const w of u){const C=w.text;if(typeof C!="string"||C.length===0)continue;const I=iE(C)[0];if(I)return I.includes("0.0.0.0")?I.replace("0.0.0.0","127.0.0.1"):I}return null},[u,c,d]),m=i?.isLastAssistantInTurn??!1,g=!!i?.isWorking,b=h.useRef(g),y=b.current&&!g;h.useEffect(()=>{b.current=g},[g]);const S=n==="stop"||t&&!a,v=!t,x=h.useMemo(()=>{if(!m||g)return;if(typeof o=="number"&&o>0)return mc(o);if(typeof r=="number"&&typeof s=="number"&&r>s)return mc(r-s);const w=i?.userMessageCreatedAt;if(typeof w=="number"&&typeof r=="number"&&r>w)return mc(r-w)},[m,g,o,r,s,i?.userMessageCreatedAt]),k=h.useMemo(()=>{const w=typeof r=="number"&&r>0?r:typeof s=="number"&&s>0?s:null;if(w===null)return null;const C=sw(w,f);return C.length>0?C:null},[r,s,f]);return{messagePreviewUrl:p,isLastAssistantInTurn:m,isTurnWorking:g,shouldAnimateTurnFooter:y,hasStopFinish:S,awaitingMessageCompletion:v,turnDurationText:x,footerTimestamp:k}}const Rz={contain:"layout",transform:"translateZ(0)"},Pz={containerType:"inline-size",containerName:"message-footer"},Dz=h.memo(({sessionId:e,messageId:t,parts:n,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,durationMs:a,isLatestMessage:c=!1,isMobile:d,alwaysShowActions:f,hasTouchInput:u,onShowPopup:p,streamPhase:m,onContentChange:g,hasTextContent:b=!1,onCopyMessage:y,turnGroupingContext:S,errorMessage:v,errorVariant:x="error",footerProviderID:k,footerModelName:w,footerAgentName:C,footerVariant:I,isDarkTheme:_=!1})=>{const E=zd(),M=h.useRef(null),T=h.useRef(null),A=!!(u??d),j=!!(f??d),{src:R,onError:O,hasLogo:N}=Mm(k??null),D=h.useMemo(()=>Qm(n),[n]),K=E==="mini-chat",V=pe(we=>we.currentSessionId),W=pe(we=>we.getDirectoryForSession),B=Bn(),Z=ne(we=>we.timeFormatPreference),L=ne(we=>we.openContextPreview),{messagePreviewUrl:$,isLastAssistantInTurn:G,isTurnWorking:Q,shouldAnimateTurnFooter:z,hasStopFinish:X,awaitingMessageCompletion:Y,turnDurationText:ce,footerTimestamp:se}=Nz({visibleParts:D,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,durationMs:a,turnGroupingContext:S,errorMessage:v,isMobile:d,isMiniChatSurface:K,timeFormatPreference:Z}),ue=X?"completed":m,Ie=!!b&&!Y,de=h.useCallback(async we=>{const je=we??T.current??M.current;await Lz(t,je)},[t]),Fe=!!v,$e=x==="info"?"information":"error-warning",Xe=G&&(b||!!v)&&!Q,We=h.useMemo(()=>l.jsx(Az,{hasCopyableText:Ie,isTouchContext:A,onCopyMessage:y,onShareImage:de,sessionId:e,messageId:t,isLatestMessage:c}),[de,Ie,c,A,t,y,e]),Ae=h.useMemo(()=>{const we=[];let je=0;for(;je<D.length;){const Ce=D[je];if(Ce.type!=="text"){je++;continue}we.push(l.jsx("div",{ref:T,"data-message-text-export-source":"true",children:l.jsx(s4,{part:Ce,sessionId:e,messageId:t,streamPhase:ue,onContentChange:g,onShowPopup:p})},`assistant-text-${t}-${je}`)),je++}return we},[t,e,g,p,ue,D]),be="text-sm text-muted-foreground tabular-nums flex items-center gap-1",te=!K&&!d,ve=l.jsx(l.Fragment,{children:te&&$?l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsx(Me,{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:we=>we.stopPropagation(),onClick:()=>{const we=B??(V?W(V):null);we&&L(we,$)},children:l.jsx(F,{name:"global",className:"h-4 w-4"})})}),l.jsx(gt,{sideOffset:6,children:"Open preview"})]}):null});return l.jsxs("div",{ref:M,"data-message-text-export-root":"true",className:P("relative w-full group/message"),style:Rz,children:[l.jsx(jz,{containerRef:M}),l.jsxs("div",{children:[l.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:[Ae,Fe&&l.jsx(Xm,{children:l.jsx("div",{className:P("group/assistant-text relative mt-3 p-3 rounded-lg border break-words max-w-full",x==="info"?"bg-[var(--status-info-background)] border-[var(--status-info-border)]":"bg-[var(--status-error-background)] border-[var(--status-error-border)]"),children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(F,{name:$e,className:P("h-4 w-4 shrink-0",x==="info"?"text-[var(--status-info)]":"text-[var(--status-error)]")}),l.jsx("div",{className:"min-w-0 flex-1 break-words",children:l.jsx(ka,{content:v??"",onShowPopup:p,className:"[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",enableFileReferences:!1})})]})})},"assistant-error")]}),l.jsx(km,{files:n,onShowPopup:p}),Xe&&l.jsxs("div",{className:P("mt-2 mb-1 flex flex-wrap items-center justify-start gap-x-3 gap-y-1.5",z&&"message-footer-enter"),style:Pz,children:[l.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?l.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[N&&R?l.jsx("img",{src:R,alt:"",className:"h-3.5 w-3.5 flex-shrink-0",style:{filter:_?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:O}):l.jsx(F,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0",style:{color:`var(${Tz(C).var})`}}),l.jsx("span",{className:"truncate",children:w})]}):null,I&&!["default","none"].includes(I.toLowerCase())?l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx(F,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0"}),l.jsx("span",{className:"message-footer__label",children:I[0].toLowerCase()+I.slice(1)})]}):null,C?l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx(F,{name:"ai-agent",className:"h-3.5 w-3.5 flex-shrink-0"}),l.jsx("span",{className:"message-footer__label",children:C})]}):null,ce?l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("span",{className:"text-sm text-muted-foreground tabular-nums flex items-center gap-1",children:[l.jsx(F,{name:"hourglass",className:"h-3.5 w-3.5"}),l.jsx("span",{className:"message-footer__label",children:ce})]})}),l.jsx(gt,{children:ce})]}):null,se?l.jsxs(pt,{children:[l.jsx(mt,{asChild:!0,children:l.jsxs("span",{className:be,"aria-label":`Message time: ${se}`,children:[l.jsx(F,{name:"time",className:"h-3.5 w-3.5"}),l.jsx("span",{className:"message-footer__label",children:se})]})}),l.jsx(gt,{children:se})]}):null]}),l.jsxs("div",{className:P("flex items-center gap-1.5",j||A?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:[We,ve]})]})]})]})}),Bf=h.memo(({isUser:e,...t})=>e?l.jsx(_z,{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}):l.jsx(Dz,{...t})),sd=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}},ow="GitHub issue context (JSON)",iw="GitHub pull request context (JSON)",p5=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,m5=(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}},Oz=e=>{const t=m5(e,ow);if(t){const r=t.issue,s=r?.number,o=r?.title,i=r?.url;return!p5(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.issue-link",filename:`Issue #${s}: ${o}`,url:i}}const n=m5(e,iw);if(n){const r=n.pr,s=r?.number,o=r?.title,i=r?.url;return!p5(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},Hz=e=>!!e.trim().startsWith("The following tool was executed by the user"),r1=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 Hz(r)||s.startsWith(ow)||s.startsWith(iw)}).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=Oz(r);if(o)return o}if(r.startsWith("The following tool was executed by the user"))return{type:"text",text:"/shell"}}return t}),g5=new WeakMap,aw=e=>{if(!e||!sd(e.info).isUser)return!1;const t=g5.get(e.parts);if(t!==void 0)return t;const n=r1(Wd(e.parts)),r=e1(n,{includeReasoning:!0}).length===0;return g5.set(e.parts,r),r};function $f(e){const[t,n]=h.useState(e);return h.useEffect(()=>{e!=null&&n(e)},[e]),e??t}const fn=(e,t)=>{if(typeof e=="object"&&e!==null)return e[t]},Yr=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},y5=e=>{const t=fn(e,"model"),n=typeof t=="object"&&t!==null?t:null;return{providerId:Yr(fn(e,"providerID"))??Yr(n?.providerID)??Yr(n?.providerId),modelId:Yr(fn(e,"modelID"))??Yr(n?.modelID)??Yr(n?.modelId)}};function Fz({message:e,previousMessage:t,isUser:n,sessionId:r,isInActiveTurn:s,turnGroupingContext:o}){const i=Ze(A=>A.providers),a=_t(A=>A.getAgentModelForSession),c=_t(A=>A.getSessionModelSelection),d=_t(gS(A=>s&&r?A.sessionAgentSelections.get(r)??null:null)),f=h.useMemo(()=>{if(n||!t)return null;const A=fn(t.info,"clientRole"),j=fn(t.info,"role");if((typeof A=="string"?A:typeof j=="string"?j:void 0)!=="user")return null;const O=fn(t.info,"mode"),N=fn(t.info,"agent"),D=y5(t.info),K=fn(t.info,"variant"),V=typeof O=="string"&&O.trim().length>0?O:typeof N=="string"&&N.trim().length>0?N:void 0,W=D.providerId,B=D.modelId,Z=typeof K=="string"&&K.trim().length>0?K:void 0;return!V&&!W&&!B&&!Z?null:{agentName:V,providerId:W,modelId:B,variant:Z}},[n,t]),u=h.useMemo(()=>{if(n)return;const A=fn(e.info,"mode");if(typeof A=="string"&&A.trim().length>0)return A;const j=fn(e.info,"agent");if(typeof j=="string"&&j.trim().length>0)return j;if(f?.agentName)return f.agentName;if(r)return d??void 0},[n,e.info,f,r,d]),p=n?{providerId:void 0,modelId:void 0}:y5(e.info),m=p.providerId??null,g=p.modelId??null,b=h.useMemo(()=>{if(n||!r)return null;if(f?.providerId&&f?.modelId)return{providerId:f.providerId,modelId:f.modelId};if(u){const j=a(r,u);if(j?.providerId&&j?.modelId)return j}const A=c(r);return A?.providerId&&A?.modelId?A:null},[n,r,u,f,a,c]),y=h.useMemo(()=>n?null:typeof m=="string"&&m.trim().length>0?m:b?.providerId??null,[n,m,b]),S=h.useMemo(()=>n?null:typeof g=="string"&&g.trim().length>0?g:b?.modelId??null,[n,g,b]),v=h.useMemo(()=>{if(n)return;const A=y&&i.length>0?i.find(j=>j.id===y):void 0;return Em(A,S)||void 0},[n,y,S,i]),x=h.useMemo(()=>{if(n||!y||!S)return!1;const A=i.find(O=>O.id===y);if(!A?.models||!Array.isArray(A.models))return!1;const R=A.models.find(O=>O.id===S)?.variants;return!!(R&&Object.keys(R).length>0)},[n,S,y,i]),k=$f(u),w=$f(y??void 0),C=$f(v),I=k??void 0,_=w??null,E=C??void 0,M=n?void 0:Yr(fn(e.info,"variant"))??o?.userMessageVariant??f?.variant;return{headerAgentName:I,headerProviderID:_,headerModelName:E,headerVariant:n?void 0:x?M??"Default":M}}class is{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return is.instance||(is.instance=new is),is.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 Vz({message:e,isUser:t,sessionId:n,streamPhase:r,assistantTextParts:s,shouldCoordinateRendering:o,animationHandlers:i,messageContainerRef:a}){const c=h.useMemo(()=>t||!n?!1:is.getInstance().shouldAnimateMessage(e.info,n),[e.info,t,n]),d=i??null,f=h.useRef(!1),u=h.useRef(!1),p=h.useRef(!1),m=h.useRef(!1),g=h.useRef(!1);h.useEffect(()=>{f.current=!1,u.current=!1,p.current=!1,m.current=!1,g.current=!1},[e.info.id]);const b=!!fn(e.info,"animationSettled"),y=r==="streaming"||r==="cooldown";y&&(g.current=!0);const S=c&&!b&&!y&&!g.current,v=!t&&c&&s.length>0&&!o;h.useEffect(()=>{if(d?.onStreamingCandidate){if(!v){u.current&&(d?.onReservationCancelled&&d.onReservationCancelled(),u.current=!1);return}m.current||(m.current=!0,d.onStreamingCandidate(),u.current=!0)}},[d,v]),h.useEffect(()=>{d?.onAnimationStart&&S&&(p.current||(d.onAnimationStart(),p.current=!0))},[d,S]),h.useEffect(()=>{if(t)return;const x=d?.onAnimatedHeightChange;if(!x||!(S||v))return;const w=a.current;if(!w)return;if(typeof window>"u"||typeof ResizeObserver>"u"){x(w.getBoundingClientRect().height);return}let C=null;const I=E=>{if(typeof window>"u"){x(E);return}C!==null&&window.cancelAnimationFrame(C),C=window.requestAnimationFrame(()=>{x(E)})},_=new ResizeObserver(E=>{const M=E[0];M&&I(M.contentRect.height)});return _.observe(w),I(w.getBoundingClientRect().height),()=>{C!==null&&(window.cancelAnimationFrame(C),C=null),_.disconnect()}},[S,t,d,v,a])}function Bz(){const e=ne(o=>o.setImagePreviewOpen),[t,n]=h.useState({open:!1,title:"",content:""}),r=h.useCallback(o=>{(o.image||o.mermaid)&&(n(o),e(!0))},[e]),s=h.useCallback(o=>{n(i=>({...i,open:o})),e(o)},[e]);return{popupContent:t,handleShowPopup:r,handlePopupChange:s}}const $z=xs(()=>ft(()=>import("./ToolOutputDialog-B3RRLhR3.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]))),zz=({message:e,previousMessage:t,nextMessage:n,onContentChange:r,animationHandlers:s,turnGroupingContext:o,isInActiveTurn:i=!1,activeStreamingPhase:a=null,animateUserOnMount:c=!1,onUserAnimationConsumed:d})=>{const{isMobile:f,isTablet:u,hasTouchInput:p}=Pr(),m=f||u,{currentTheme:g}=Vn(),b=h.useRef(null);us("ui.chat_message.render"),i&&us("ui.chat_message.render.streaming");const[y,S]=h.useState(!1),x=h.useMemo(()=>sd(e.info),[e.info]).isUser,k=e.info.sessionID,{headerAgentName:w,headerProviderID:C,headerModelName:I,headerVariant:_}=Fz({message:e,previousMessage:t,isUser:x,sessionId:k,isInActiveTurn:i,turnGroupingContext:o}),E=h.useMemo(()=>{const Ce=Wd(e.parts);return x?r1(Ce):Ce},[x,e.parts]),M=h.useMemo(()=>{const Ce=e.info.time;return typeof Ce?.completed=="number"?Ce.completed:null},[e.info.time]),T=h.useMemo(()=>{const Ce=e.info.time;return typeof Ce?.created=="number"?Ce.created:null},[e.info.time]),A=h.useMemo(()=>x?!0:!!(M&&M>0),[x,M]),j=h.useMemo(()=>{const Ce=e.info.finish;return typeof Ce=="string"?Ce:void 0},[e.info]),R=h.useMemo(()=>e1(E,{includeReasoning:!0}),[E]),O=h.useMemo(()=>{const Ce=new Set;for(const ze of o?.activityParts??[])Ce.add(ze.id);return Ce},[o?.activityParts]),N=h.useMemo(()=>x?R:W4(R,O,e.info.id),[O,x,e.info.id,R]),D=x&&N.some(Z4),K=h.useMemo(()=>x?[]:N.filter(Ce=>Ce.type==="text"),[N,x]),V=h.useMemo(()=>x?[]:R.filter(Ce=>Ce.type==="tool"),[x,R]),{popupContent:W,handleShowPopup:B,handlePopupChange:Z}=Bz(),L=h.useMemo(()=>{if(!x)return;const Ce=E.find(re=>re.type==="agent");if(!Ce)return;const ze=Ce,ht=typeof ze.name=="string"?ze.name:void 0;if(!ht)return;const xe=ze.source&&typeof ze.source.value=="string"&&ze.source.value.trim().length>0?ze.source.value:`@${ht}`;return{name:ht,token:xe}},[x,E]),$=x&&N.length===0,G=!A&&typeof j!="string",Q=h.useMemo(()=>x?!1:K.length===0||V.length===0?G:!0,[K.length,V.length,G,x]),z=g?.metadata.variant,X=h.useMemo(()=>z?z==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[z]),Y=h.useMemo(()=>n?sd(n.info):null,[n]),ce=!!o,se=o?.isLastAssistantInTurn??!1,ue=h.useMemo(()=>!x&&aw(n),[x,n]),Ie=h.useMemo(()=>x?!1:ce?!se:Y?!Y.isUser&&Y.role==="assistant":!1,[ce,se,x,Y]),de=h.useMemo(()=>A?"completed":i?a??"streaming":"completed",[a,i,A]);Vz({message:e,isUser:x,sessionId:k,streamPhase:de,assistantTextParts:K,shouldCoordinateRendering:Q,animationHandlers:s,messageContainerRef:b}),h.useEffect(()=>{!x||!c||d?.(e.info.id)},[c,x,e.info.id,d]);const Fe=h.useMemo(()=>{if(!x)return $4(e.info)},[x,e.info]),$e=Fe?.text,Xe=Fe?.variant,We=h.useMemo(()=>T$({isUser:x,displayParts:N,assistantErrorText:$e}),[$e,N,x]),Ae=We.length>0,be=h.useMemo(()=>x?!1:!L$(N,$e),[$e,N,x]),te=h.useCallback(async()=>{let Ce;if(x)Ce=await ir(We);else{const{renderMarkdownSync:ze}=await ft(async()=>{const{renderMarkdownSync:ht}=await import("./markdownCore-C2YQ3Z0q.js").then(xe=>xe.m);return{renderMarkdownSync:ht}},__vite__mapDeps([21,8,22,23,24]));Ce=await iI(We,ze(We))}return Ce.ok?(x&&(S(!0),setTimeout(()=>S(!1),2e3)),!0):!1},[x,We]);if($||be)return null;const ve="pt-0",we="var(--radius-xl)",je={sessionId:e.info.sessionID,messageId:e.info.id,parts:N,isUser:x,isMessageCompleted:A,messageFinish:j,messageCreatedAt:T??void 0,isMobile:f,alwaysShowActions:m,hasTouchInput:p,onShowPopup:B,streamPhase:de,onContentChange:r,hasTextContent:Ae,onCopyMessage:te,copiedMessage:y,agentMention:L,errorMessage:$e,errorVariant:Xe,isLatestMessage:!n};return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:P("group w-full",x?f?"pt-2":"pt-4":ve,x?f?"pb-0":"pb-2":Ie||ue?"pb-0":"pb-2"),id:`message-${e.info.id}`,"data-message-id":e.info.id,ref:b,children:l.jsx("div",{className:"chat-message-column relative",children:x?N.length===0?null:l.jsx(Xm,{forceAnimation:!0,skipAnimation:!c,ignoreContextDisabled:!0,respectReducedMotion:!0,children:l.jsx("div",{className:P("relative flex justify-end",f?void 0:"group/user-shell"),children:l.jsxs("div",{className:"max-w-[85%]",children:[D?l.jsx("div",{style:{backgroundColor:"var(--chat-user-message-bg)",borderRadius:we,borderBottomRightRadius:"var(--radius-sm)"},className:P("shadow-none border border-primary/5",f?"px-3 py-2":"px-5 py-3",!f&&"pb-4"),children:l.jsx(Bf,{...je,userActionsMode:"external-content"})}):null,l.jsx(Bf,{...je,userActionsMode:"external-actions"})]})})}):l.jsx("div",{className:"relative",children:l.jsx(Bf,{sessionId:e.info.sessionID,messageId:e.info.id,parts:N,isUser:x,isMessageCompleted:A,isLatestMessage:!n,messageFinish:j,messageCompletedAt:M??void 0,messageCreatedAt:T??void 0,durationMs:e.info.durationMs,isMobile:f,alwaysShowActions:m,hasTouchInput:p,onShowPopup:B,streamPhase:de,onContentChange:r,hasTextContent:Ae,onCopyMessage:te,copiedMessage:y,agentMention:L,turnGroupingContext:o,errorMessage:$e,errorVariant:Xe,footerProviderID:C,footerModelName:I,footerAgentName:w,footerVariant:_,isDarkTheme:X})})})}),l.jsx(h.Suspense,{fallback:null,children:l.jsx($z,{popup:W,onOpenChange:Z,isMobile:f})})]})},Uz=h.memo(zz,(e,t)=>u4({info:e.message.info,parts:e.message.parts},{info:t.message.info,parts:t.message.parts})&&Xc(e.previousMessage?{info:e.previousMessage.info,parts:e.previousMessage.parts}:void 0,t.previousMessage?{info:t.previousMessage.info,parts:t.previousMessage.parts}:void 0)&&Xc(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&&f4(e.turnGroupingContext,t.turnGroupingContext,e.message.info.id,sd(e.message.info).isUser)),v5={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"},qz=e=>typeof e=="string"&&e.length>0&&e in e3,Zz=({action:e,variant:t,sessionId:n})=>{const[r,s]=U.useState(!1),[o,i]=U.useState(!1),[a,c]=U.useState(!1),[d,f]=U.useState(""),u=U.useCallback(async y=>{if(!(!n||r)){s(!0);try{await Ge().prompt(n,nv(e.command,y),"prompt")}finally{s(!1)}}},[n,r,e.command]),p=U.useCallback(async()=>{if(e.promptForArgs){c(!0),f("");return}await u(e.args)},[e,u]),m=U.useCallback(async()=>{if(!(!n||r||e.disabled)){if(e.confirm){i(!0);return}await p()}},[n,r,e,p]);if(!n)return null;const g=r||e.loading===!0,b=qz(e.icon)?l.jsx(F,{name:e.icon,className:"size-3.5"}):null;return o?l.jsxs("div",{role:"alertdialog","aria-label":e.confirm,className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[l.jsx("span",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:e.confirm}),l.jsx(Me,{type:"button",size:"xs",variant:"default",onClick:()=>{i(!1),p()},children:"Continue"}),l.jsx(Me,{type:"button",size:"xs",variant:"ghost",onClick:()=>i(!1),children:"Cancel"})]}):a?l.jsxs("form",{className:"flex min-w-0 flex-wrap items-center gap-1.5",onSubmit:y=>{y.preventDefault(),c(!1),u(d)},children:[l.jsx("input",{autoFocus:!0,value:d,onChange:y=>f(y.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:y=>{y.key==="Escape"&&(y.stopPropagation(),c(!1))}}),l.jsx(Me,{type:"submit",size:"xs",variant:"default",disabled:r,children:"Run"}),l.jsx(Me,{type:"button",size:"xs",variant:"ghost",onClick:()=>c(!1),children:"Cancel"})]}):l.jsxs(Me,{size:"xs",variant:t,onClick:()=>{m()},disabled:g||e.disabled,"aria-label":e.label,children:[g?l.jsx("span",{"aria-hidden":"true",className:"size-3.5 shrink-0 animate-spin rounded-full border border-current border-t-transparent"}):b,e.label]})},Wz=({label:e,value:t,max:n})=>{const r=Math.min(Math.max(t,0),n),s=Math.round(r/n*100);return l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[l.jsx("span",{className:"truncate text-muted-foreground",children:e??""}),l.jsxs("span",{className:"tabular-nums text-muted-foreground",children:[s,"%"]})]}),l.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:l.jsx("div",{className:"h-full rounded-full bg-primary transition-[width] duration-300",style:{width:`${s}%`}})})]})},Gz=({body:e,messageId:t,text:n})=>{const[r,s]=U.useState(!1),o=typeof n=="string"&&n.trim().length>0;return l.jsxs("div",{className:"flex flex-col gap-1.5",children:[o&&l.jsx(_o,{messageId:t,content:n,className:"text-sm text-foreground"}),e&&e!==n&&l.jsxs("div",{children:[l.jsxs(Me,{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:[l.jsx(F,{name:r?"arrow-down-s":"arrow-right-s",className:"size-3"}),l.jsx("span",{children:"Details"})]}),r&&l.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:l.jsx("code",{children:e})})]})]})},Kz=({sessionId:e,messageId:t,customType:n,text:r,data:s,details:o,className:i})=>{const a=U.useMemo(()=>Ev({customType:n,data:s,details:o,text:r}),[n,s,o,r]),c=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 l.jsx(Gz,{body:a.kind==="fallback"?a.body:"",messageId:t,text:r});switch(f.component){case"markdown":return l.jsx(_o,{messageId:t,content:f.body,className:"text-sm"});case"kv":return l.jsx("dl",{className:"grid grid-cols-[minmax(6rem,auto)_1fr] gap-x-3 gap-y-1.5 text-sm",children:f.rows.map(p=>l.jsxs(U.Fragment,{children:[l.jsx("dt",{className:"truncate text-muted-foreground",children:p.label}),l.jsx("dd",{className:P("break-words",v5[p.tone??"neutral"]?.split(" ")[1]),children:p.value})]},`${p.label}:${p.value}`))});case"list":return l.jsx("ul",{className:"flex flex-col gap-1.5 text-sm",children:f.items.map(p=>l.jsxs("li",{className:"flex items-baseline gap-2",children:[l.jsx("span",{className:"size-1.5 shrink-0 translate-y-[-1px] rounded-full bg-interactive-hover"}),l.jsx("span",{className:"font-medium",children:p.label}),p.value&&l.jsx("span",{className:"text-muted-foreground",children:p.value})]},`${p.label}:${p.value}`))});case"table":return l.jsx("div",{className:"overflow-x-auto",children:l.jsxs("table",{className:"w-full border-collapse text-sm",children:[l.jsx("thead",{children:l.jsx("tr",{children:f.columns.map(p=>l.jsx("th",{className:"border-b px-2 py-1.5 text-left font-medium text-muted-foreground",children:p},p))})}),l.jsx("tbody",{children:f.rows.map((p,m)=>l.jsx("tr",{children:p.map((g,b)=>l.jsx("td",{className:"border-b px-2 py-1.5 break-words",children:g},b))},m))})]})});case"progress":{const p=f.max??100;return l.jsx(Wz,{label:f.label,value:f.value,max:p>0?p:100})}case"badges":return l.jsx("div",{className:"flex flex-wrap gap-1.5",children:f.items.map(p=>l.jsx("span",{className:P("rounded-full px-2 py-0.5 text-xs font-medium",v5[p.tone??"neutral"]),children:p.label},p.label))});case"code":return l.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:l.jsx("code",{children:f.code})});default:return null}};return l.jsxs("div",{className:P("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:[(c!==void 0||d!==void 0)&&l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c!==void 0&&l.jsx("div",{className:"flex min-w-0 items-center gap-1.5",children:l.jsx("span",{className:"text-xs font-medium tracking-wide text-muted-foreground uppercase",children:c})}),d!==void 0&&l.jsx("div",{className:"flex shrink-0 flex-wrap gap-1.5",children:d.map(p=>l.jsx(Zz,{action:p,variant:p.variant??"outline",sessionId:e},`${p.command}:${p.label}`))})]}),u()]})},Yz=({messageId:e,customType:t,text:n,data:r,details:s,render:o,className:i})=>{const[a,c]=U.useState(!1),[d,f]=U.useState(!1),[u,p]=U.useState(!1),m=s!==void 0?s:r,g=m!=null,b=typeof n=="string"&&n.trim().length>0,y=t||"extension",S=Array.isArray(o?.message)&&o.message.length>0?o.message:void 0,v=Array.isArray(o?.messageExpanded)&&o.messageExpanded.length>0?o.messageExpanded:void 0,x=d&&v?v:S,k=l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"inline-flex h-5 shrink-0 items-center",style:{color:"var(--tools-icon)"},children:l.jsx(F,{name:"plug-2",className:"size-3.5","aria-hidden":"true"})}),l.jsx("span",{className:P(jo,"shrink-0"),style:Ea,children:"Extension"}),l.jsx("span",{className:P(It,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:y,children:y})]});return l.jsxs("div",{className:P("py-1",i),"data-extension-ui":e,children:[g&&!S?l.jsxs("button",{type:"button",onClick:()=>c(w=>!w),"aria-expanded":a,"aria-label":a?`Hide ${y} details`:`Show ${y} 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:[k,l.jsx(F,{name:"arrow-right-s","aria-hidden":"true",className:P("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")})]}):l.jsx("div",{className:"flex w-full min-w-0 items-center gap-x-1.5 py-1 pl-px pr-2",children:k}),g&&a&&!S&&l.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),l.jsx("div",{className:"max-h-80 overflow-auto",children:l.jsx(rd,{data:m})})]}),x&&l.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:x.map((w,C)=>l.jsx("div",{className:"min-h-[1.25em] leading-relaxed",children:l.jsx(Gt,{text:w})},C))}),S&&v&&l.jsxs(Me,{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 text-muted-foreground hover:bg-interactive-hover hover:text-foreground",children:[l.jsx(F,{name:d?"arrow-down-s":"arrow-right-s",className:"size-3"}),l.jsx("span",{children:d?"Show less":"Show more"})]}),S&&(b||g)&&l.jsxs("div",{children:[l.jsxs(Me,{type:"button",variant:"ghost",size:"xs",onClick:()=>p(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:[l.jsx(F,{name:u?"arrow-down-s":"arrow-right-s",className:"size-3"}),l.jsx("span",{children:"Raw message"})]}),u&&l.jsxs("div",{className:"relative mb-1 ml-2 pl-3",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute bottom-0 left-0 top-0 w-px bg-[var(--tools-border)]"}),b&&l.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:l.jsx(_o,{messageId:e,content:n,variant:"assistant"})}),g&&l.jsx("div",{className:"max-h-80 overflow-auto",children:l.jsx(rd,{data:m})})]})]}),!S&&b&&l.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:l.jsx(_o,{messageId:e,content:n,variant:"assistant"})})]})},s1=h.memo(({message:e,previousMessage:t,nextMessage:n,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:c,animationHandlers:d,scrollToBottom:f})=>{const u=e.info;if(u.role==="extension"){const p=Ev({customType:u.customType,data:u.data,details:u.details,text:typeof u.text=="string"?u.text:void 0});return l.jsx("div",{className:"chat-message-column",children:p.kind==="ui"?l.jsx(Kz,{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}):l.jsx(Yz,{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 l.jsx(Uz,{message:e,previousMessage:t,nextMessage:n,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:c,animationHandlers:d,scrollToBottom:f,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o})},(e,t)=>{const n=e.turnGroupingContext,r=t.turnGroupingContext;return u4(e.message,t.message)&&Xc(e.previousMessage,t.previousMessage)&&Xc(e.nextMessage,t.nextMessage)&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&e.onContentChange===t.onContentChange&&e.scrollToBottom===t.scrollToBottom&&f4(n,r,e.message.info.id,ys(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});s1.displayName="MessageRow";const lw=h.memo(({turn:e,isLastTurn:t,nextEntryFirstMessage:n,sessionIsWorking:r,sessionAwaitingRecovery:s=!1,awaitingPromptEcho:o=!1,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:c,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:p})=>{const m=h.useMemo(()=>{const A=[e.userMessage,...e.assistantMessages],j=new Map;return A.forEach((R,O)=>{j.set(R.info.id,O)}),{ordered:A,lookup:j}},[e.assistantMessages,e.userMessage]),g=h.useMemo(()=>Fj({activeStreamingMessageId:u,assistantMessages:e.assistantMessages}),[u,e.assistantMessages]),b=e.assistantMessages,y=h.useMemo(()=>{const A=new Map;return b.forEach((j,R)=>{A.set(j.info.id,R)}),A},[b]),S=h.useMemo(()=>Pf(e,g),[e,g]),v=Pf(e,u),x=t&&s,k=h.useMemo(()=>S&&g?g:b[0]?.info.id,[g,S,b]),w=e.activityParts,C=e.activitySegments,I=h.useMemo(()=>{const A=new Map;for(const j of w){const R=A.get(j.messageId)??[];R.push(j),A.set(j.messageId,R)}return A},[w]),_=h.useMemo(()=>{const A=e.userMessage.info.time?.created,j=e.userMessage.info,R=j?.model?.variant??j?.variant,O=typeof R=="string"&&R.trim().length>0?R:void 0;return{turnId:e.turnId,summaryBody:e.summaryText,activityParts:w,activityGroupSegments:C,headerMessageId:e.headerMessageId,hasTools:e.hasTools,hasReasoning:e.hasReasoning,diffStats:e.diffStats,changedFiles:e.changedFiles,userMessageCreatedAt:typeof A=="number"?A:void 0,userMessageVariant:O}},[e.changedFiles,e.diffStats,e.hasReasoning,e.hasTools,e.headerMessageId,e.summaryText,e.turnId,e.userMessage.info,w,C]),E=h.useCallback(A=>{const R=ys(A)==="user",O=m.lookup.get(A.info.id),N=y.get(A.info.id)??-1,D=N>=0,K=N===0,V=N===b.length-1,B=!!k&&A.info.id===k||K||V,Z=I.get(A.info.id)??[],L=R?void 0:D?K?e.userMessage:void 0:typeof O=="number"&&O>0?m.ordered[O-1]:void 0,$=D&&V?n:void 0,G=D?{turnId:e.turnId,activityOwnerMessageId:k,isFirstAssistantInTurn:K,isLastAssistantInTurn:V,isLatestTurn:t,isWorking:zj({messageId:A.info.id,activeStreamingMessageId:u,isRetrying:dF(A),isAwaitingRecovery:x&&V}),hasTools:e.hasTools,hasReasoning:e.hasReasoning,...B?{summaryBody:_.summaryBody,activityParts:_.activityParts,activityGroupSegments:_.activityGroupSegments,headerMessageId:_.headerMessageId,diffStats:_.diffStats,changedFiles:_.changedFiles,userMessageCreatedAt:_.userMessageCreatedAt,userMessageVariant:_.userMessageVariant}:{activityParts:Z}}:void 0;return l.jsx(s1,{message:A,previousMessage:L,nextMessage:$,turnGroupingContext:G,isInActiveTurn:!!g&&A.info.id===g,activeStreamingPhase:A.info.id===g?p:null,animateUserOnMount:d(A),onUserAnimationConsumed:f,onContentChange:i,animationHandlers:a(A.info.id),scrollToBottom:c},A.info.id)},[a,t,n,m.lookup,m.ordered,i,c,e.hasReasoning,e.hasTools,e.turnId,e.userMessage,_,g,u,p,b,y,k,I,x,d,f]),M=!Pf(e,u),T=$j({isLastTurn:t,sessionIsWorking:r,turnIsInActiveStream:e.stream.isStreaming&&v,activeStreamingMessageId:u,isSteering:e.isSteering,awaitingPromptEcho:o});return l.jsx(sz,{turn:e,renderMessage:E,deferEarlierAssistantMessages:M,showWorkingStatus:T,isAwaitingRecovery:x&&!T,activeStreamingMessageId:u,activeStreamingPhase:p,onActivityContentChange:i})});lw.displayName="TurnBlock";const cw=h.memo(({message:e,previousMessage:t,nextMessage:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,shouldAnimateUserMessage:i,onUserAnimationConsumed:a,activeStreamingMessageId:c,activeStreamingPhase:d})=>l.jsx(s1,{message:e,previousMessage:t,nextMessage:n,isInActiveTurn:!!c&&e.info.id===c,activeStreamingPhase:e.info.id===c?d:null,animateUserOnMount:i(e),onUserAnimationConsumed:a,onContentChange:r,animationHandlers:s(e.info.id),scrollToBottom:o}));cw.displayName="UngroupedMessageRow";const Xz=new Set(["task"]),Jz=e=>typeof e=="string"&&Xz.has(e.toLowerCase()),Qz=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},x5=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},eU=e=>{const t=e.info.finish;return typeof t=="string"?t:void 0},tU=e=>e.info.summary===!0,nU=(e,t,n,r)=>({id:n.id??`${t}-part-${r}-${n.type}`,turnId:e,messageId:t,part:n,partIndex:r,endedAt:Qz(n)}),rU=e=>{const t=[];let n=!1,r=!1;e.assistantMessages.forEach(g=>{g.parts.forEach(b=>{if(b.type==="tool"){n=!0;return}b.type==="reasoning"&&x5(b)&&(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,b)=>(g.id??`${e.assistantMessages[i]?.info.id}-part-${b}-${g.type}`)===e.summarySourcePartId)??-1:-1,c=e.assistantMessages.some(g=>g.parts.some(b=>b.type==="tool"||b.type==="reasoning")),d=new Map;let f=null;e.assistantMessages.forEach((g,b)=>{const y=eU(g),S=g.parts.some(x=>x.type==="tool"),v=tU(g);g.parts.forEach((x,k)=>{const w=x.type==="tool",C=x.type==="reasoning"||x.type==="text"?x5(x):void 0,I=x.id??`${g.info.id}-part-${k}-${x.type}`,_=w?x.tool:void 0,E=w&&Jz(_);if(E){const O=I;s.has(O)||(s.set(O,g.info.id),o.push(O)),f=O}const M=x.type==="text"&&typeof C=="string"&&(y==="stop"||typeof y!="string")&&e.summarySourceMessageId===g.info.id&&e.summarySourcePartId===I,T=i>=0&&(b<i||b===i&&a>=0&&k<a);let A=null;if(w?A="tool":x.type==="reasoning"?C&&(A="reasoning"):e.showTextJustificationActivity&&x.type==="text"&&C&&(v||!M&&(S||typeof y=="string"&&y!=="stop"||c||T))&&(A="justification"),!A)return;const j={...nU(e.turnId,g.info.id,x,k),kind:A};if(t.push(j),A==="tool"&&E)return;const R=d.get(f)??[];R.push(j),d.set(f,R)})});const u=[],p=g=>{if(g.length===0)return;const b=new Map;g.forEach(S=>{b.set(S.messageId,(b.get(S.messageId)??0)+1)});let y;for(const S of e.assistantMessages)(b.get(S.info.id)??0)>0&&!y&&(y=S.info.id);return y};return[null,...o].forEach(g=>{const b=d.get(g)??[];if(b.length===0)return;const y=g===null?p(b):s.get(g);y&&u.push({id:`${e.turnId}:${y}:${g??"start"}`,anchorMessageId:y,afterToolPartId:g,parts:b})}),{activityParts:t,activitySegments:u,hasTools:n,hasReasoning:r}},sU=e=>{const t=new Map,n=new Map,r=new Map,s=new Set;e.forEach(a=>{t.set(a.turnId,a);const c=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===c,isLastAssistantInTurn:f===d,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)})),{turns:e,indexes:{turnById:t,messageToTurnId:n,messageMetaById:r},lastTurnId:o?.turnId??null,lastTurnMessageIds:i,ungroupedMessageIds:new Set}},oU=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},iU=e=>e.info.summary===!0,b5=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!iU(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=oU(o);if(i)return{text:i,sourceMessageId:r.info.id,sourcePartId:o.id??`${r.info.id}-part-${s}-text`}}}},aU=e=>b5(e,!0)??b5(e,!1)??{},lU=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,c=typeof i.deletions=="number"?i.deletions:0;(a!==0||c!==0)&&(o+=1),r+=a,s+=c}),o!==0)return{additions:r,deletions:s,files:o}},gc=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},dw=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},cU=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},dU=e=>{const t=e.info.time?.completed;return typeof t=="number"?t:void 0},uU=e=>{const t=e.info?.summary?.body;return typeof t!="string"?void 0:t.trim().length>0?t:void 0},zf=(e,t)=>{const n=gc(e);return{messageId:e.info.id,role:n,parentMessageId:dw(e),message:e,order:t}},fU=(e,t)=>{const n=cU(e);let r,s=!1;t.forEach(i=>{const a=dU(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}},hU={previousProjection:null,showTextJustificationActivity:!1,mergeHiddenUserTurns:void 0},pU=(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},mU=(e,t)=>e.userMessage===t.userMessage&&e.headerMessageId===t.headerMessageId&&pU(e.assistantMessages,t.assistantMessages),w5=(e,t)=>{e.summary=aU(e.assistantMessages),e.summaryText=e.summary.text??uU(e.userMessage),e.diffStats=lU(e.userMessage),e.changedFiles=void 0;const n=rU({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=fU(e.userMessage,e.assistantMessages),e.startedAt=e.stream.startedAt,e.completedAt=e.stream.completedAt,e.durationMs=e.stream.durationMs,e},gU=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,c=typeof a=="number"&&i>=a?i-a:void 0;n[r-1]={...s,stream:{...s.stream,isStreaming:!1,completedAt:i,durationMs:c,settledReason:"steered"},completedAt:i,durationMs:c},n[r]=o.isSteering?o:{...o,isSteering:!0},t=!0}return t?n:e},yU=(e,t)=>{const n=t.previousProjection;if(!n||n.turns.length===0||e.length===0)return e.map(i=>w5(i,t));let r=n.turns.length===e.length,s=!1;const o=e.map((i,a)=>{const c=n.indexes.turnById.get(i.turnId);return c&&mU(c,i)?(s=!0,n.turns[a]!==c&&(r=!1),c):(r=!1,w5(i,t))});return r&&s?n.turns:o},uw=(e,t)=>{const n={...hU,...t},r=[],s=new Map,o=new Set,i=n.mergeHiddenUserTurns;e.forEach((f,u)=>{if(gc(f)!=="user")return;const m=r[r.length-1];if(i&&m&&aw(f)){s.set(f.info.id,m),m.messages.push(zf(f,u)),o.add(f.info.id);return}const b={turnId:f.info.id,isSteering:!1,userMessageId:f.info.id,userMessage:f,headerMessageId:void 0,messages:[zf(f,u)],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(b),s.set(b.userMessageId,b),o.add(f.info.id)}),e.forEach((f,u)=>{if(gc(f)!=="assistant")return;const m=dw(f),g=m?s.get(m):void 0;g&&(g.assistantMessages.push(f),g.assistantMessageIds.push(f.info.id),g.messages.push(zf(f,u)),g.headerMessageId||(g.headerMessageId=f.info.id),o.add(f.info.id))});const a=gU(yU(r,n)),c=sU(a),d=new Set;return e.forEach(f=>{gc(f)!=="assistant"&&(o.has(f.info.id)||d.add(f.info.id))}),{...c,ungroupedMessageIds:d}},vU=30,xU=4,xr=new Map,S5=new WeakMap;let C5=1;const bU=()=>nn()?xU:vU,Uf=e=>{const t=S5.get(e);if(t!==void 0)return t;const n=C5;return C5+=1,S5.set(e,n),n},wU=e=>e.map(t=>{const n=Uf(t.info),r=Uf(t.parts),s=t.parts.map(o=>Uf(o)).join(",");return`${n}:${r}:${s}`}).join(";"),SU=(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,wU(t),n?"1":"0",r].join("|")},CU=e=>{const t=xr.get(e);return t&&(xr.delete(e),xr.set(e,t)),t},kU=(e,t)=>{xr.delete(e);const n=bU();for(;xr.size>=n;){const r=xr.keys().next().value;if(typeof r!="string")break;xr.delete(r)}xr.set(e,t)},MU=(e,t)=>{const n=h.useRef(null),r=h.useRef([]),s=h.useRef(void 0),o=h.useRef(t.sessionKey),i=h.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),h.useEffect(()=>{n.current=null,r.current=[],s.current=void 0},[t.sessionKey,t.showTextJustificationActivity]);const a=h.useMemo(()=>{const f=t.sessionKey??"",u=SU(f,e,t.showTextJustificationActivity,"merge"),p=CU(u);return p?(n.current=p,p):$l("ui.turns.projection_ms",()=>{const m=uw(e,{previousProjection:n.current,showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:!0});return n.current=m,kU(u,m),m})},[e,t.showTextJustificationActivity,t.sessionKey]),c=h.useMemo(()=>{const f=a.turns.length<=1?[]:a.turns.slice(0,-1),u=r.current;if(u.length===f.length){let p=!0;for(let m=0;m<f.length;m+=1)if(u[m]!==f[m]){p=!1;break}if(p)return u}return r.current=f,f},[a.turns]),d=h.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:c,streamingTurn:d}},IU=1.5,_U=({hasMoreBefore:e,beforeCursor:t,resolveScrollContainer:n,loadOlder:r,onBeforeLoad:s,onLoadError:o})=>{h.useEffect(()=>{if(!e||!t)return;const i=n();if(!i)return;let a=!1,c,d=!0;const f=()=>{if(a||!e)return;const u=i.scrollTop<i.clientHeight*IU,p=i.scrollHeight<=i.clientHeight+1;!u&&!p||(a=!0,s(),r().then(m=>{d&&(a=!1,m&&(c=window.setTimeout(f,0)))}).catch(()=>{d&&(a=!1,o())}))};return i.addEventListener("scroll",f,{passive:!0}),f(),()=>{d=!1,c!==void 0&&window.clearTimeout(c),i.removeEventListener("scroll",f)}},[t,e,r,s,o,n])},k5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},M5=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},EU=(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=M5(e[f]);if(!(s!==void 0&&u!==void 0&&u>s)&&k5(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=M5(e[f]);if(s!==void 0&&u!==void 0&&u>s)break;k5(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,c={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,c),d},I5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},jU=(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(I5(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(I5(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:[]},c=e.slice();return c.splice(r+1,0,a),c},_5=[],TU=({staticTurns:e,messages:t,ungroupedMessageIds:n,lastTurnId:r,tailUserMessageId:s})=>{const o=e.map(p=>({kind:"turn",key:`turn:${p.turnId}`,turn:p,isLastTurn:p.turnId===r}));if(n.size===0)return{entries:o,trailing:_5};const i=new Map;o.forEach(p=>{i.set(p.turn.userMessage.info.id,p)});const a=t[t.length-1],c=!s&&a&&n.has(a.info.id)?a.info.id:void 0,d=[],f=[];let u=!1;return t.forEach((p,m)=>{if(s&&p.info.id===s){u=!0;return}const g=i.get(p.info.id);if(g){d.push(g);return}!n.has(p.info.id)||p.info.id===c||(u?f:d).push({kind:"ungrouped",key:`msg:${p.info.id}`,message:p,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:_5}},fw=e=>e.parts.some(t=>t?.type==="compaction"),AU=e=>{if(!fw(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}},LU=e=>{const t=Wd(e.parts);return t.length===e.parts.length?e:{...e,parts:t}},E5=new WeakMap,hw=e=>{const t=E5.get(e);if(t)return t;const n=LU(e),r=AU(n),s=V$(r.parts),o=s===r.parts?r:{...r,parts:s};return E5.set(e,o),o},j5=(e,t,n)=>e.info.id!==t||e.parts===n?e:hw({...e,parts:n}),NU=(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},T5=(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},RU=(e,t)=>{const n=t.activeStreamingMessageId;if(!n)return e;if(e.kind==="ungrouped"){const p=j5(e.message,n,t.liveParts);return p===e.message?e:{...e,message:p}}let r=!1;const s=e.turn.assistantMessages.map(p=>{const m=j5(p,n,t.liveParts);return m!==p&&(r=!0),m});if(!r)return e;const o=e.turn.assistantMessages.find(p=>p.info.id===n),i=s.find(p=>p.info.id===n);if(!!(o&&i&&NU(o.parts,i.parts)))return{...e,turn:{...e.turn,assistantMessages:s,messages:T5(e.turn,s)}};const c=new Map(s.map(p=>[p.info.id,p])),d=e.turn.messages.length>0?e.turn.messages.slice().sort((p,m)=>p.order-m.order).map(p=>c.get(p.messageId)??p.message):[e.turn.userMessage,...s],u=uw(d,{showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:t.mergeHiddenUserTurns}).turns[0]??{...e.turn,assistantMessages:s,assistantMessageIds:s.map(p=>p.info.id),messages:T5(e.turn,s)};return{...e,turn:u}},A5=e=>!!(e&&e.clientHeight>0),PU=5,DU=[],OU=new Set,HU=16,FU=(e,t)=>e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r]),VU=320,BU=8,$U=16,zU=()=>nn()?$U:BU,UU=30,qU=180,ZU=5,WU=120,GU=1200,KU=80,YU=160,L5=1500,XU=1.5,JU=90,QU=(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},Jr=new Map,eq=32,Ys=new Map,N5=e=>Ys.get(e)??0,tq=(e,t)=>{if(Ys.size>=eq&&!Ys.has(e)){const n=Ys.keys().next().value;typeof n=="string"&&Ys.delete(n)}Ys.set(e,t)},nq=(e,t)=>{const n=Jr.get(e);if(n){if(FU(n.keys,t))return n.items;Jr.delete(e)}},rq=(e,t,n)=>{if(!(!n||t.length===0))for(Jr.delete(e),Jr.set(e,{keys:t.slice(),items:n.takeSnapshot()});Jr.size>HU;){const r=Jr.keys().next().value;if(typeof r!="string")break;Jr.delete(r)}},Ol=e=>{const t=h.useRef(e);return h.useEffect(()=>{t.current=e},[e]),h.useCallback((...n)=>t.current(...n),[])},Gd=h.memo(({entry:e,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,sessionIsWorking:s,sessionAwaitingRecovery:o=!1,awaitingPromptEcho:i=!1,shouldAnimateUserMessage:a,onUserAnimationConsumed:c,activeStreamingMessageId:d,activeStreamingPhase:f,onLoadOlderHistory:u,onLoadAllHistory:p})=>(us("ui.message_list_entry.render"),e.kind==="ungrouped"?l.jsx(cw,{message:e.message,previousMessage:e.previousMessage,nextMessage:e.nextMessage,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,shouldAnimateUserMessage:a,onUserAnimationConsumed:c,activeStreamingMessageId:d,activeStreamingPhase:f}):e.kind==="history-gate"?l.jsx(aF,{foldedCount:e.turns.length,onLoadOlder:()=>u?.(e.turns.length),onLoadAll:()=>p?.(e.turns.length)}):l.jsx(lw,{turn:e.turn,isLastTurn:e.isLastTurn,nextEntryFirstMessage:e.nextEntryFirstMessage,sessionIsWorking:s,sessionAwaitingRecovery:o,awaitingPromptEcho:i,shouldAnimateUserMessage:a,onUserAnimationConsumed:c,activeStreamingMessageId:d,activeStreamingPhase:f,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r})));Gd.displayName="MessageListEntry";const pw=h.memo(({entries:e,engine:t,contentRef:n,scrollRef:r,registerTanstackVirtualizer:s,virtualizerKey:o,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:c,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,onLoadOlderHistory:u,onLoadAllHistory:p})=>{const m=t==="tanstack",g=h.useRef(!1),b=h.useRef(0),y=h.useRef(null),S=m&&nn();h.useEffect(()=>{if(!S)return;const D=r?.current;if(!D)return;const K=()=>{g.current=!0},V=()=>{g.current=!1},W=()=>{b.current=performance.now()};return D.addEventListener("touchstart",K,{passive:!0}),D.addEventListener("touchend",V,{passive:!0}),D.addEventListener("touchcancel",V,{passive:!0}),D.addEventListener("scroll",W,{passive:!0}),()=>{D.removeEventListener("touchstart",K),D.removeEventListener("touchend",V),D.removeEventListener("touchcancel",V),D.removeEventListener("scroll",W)}},[S,r]);const v=h.useCallback(()=>g.current||performance.now()-b.current<YU,[]),x=h.useCallback(()=>{const D=r?.current;return D?D.scrollTop<D.clientHeight*XU:!0},[r]),[k,w]=h.useState(e);let C=k;e!==k?S&&QU(k,e)&&v()&&!x()&&(y.current===null||performance.now()-y.current<L5)?y.current===null&&(y.current=performance.now()):(y.current=null,w(e),C=e):y.current!==null&&(y.current=null);const[,I]=h.useReducer(D=>D+1,0);h.useEffect(()=>{if(!S)return;const D=window.setInterval(()=>{if(y.current===null)return;const K=performance.now()-y.current>=L5;(!v()||x()||K)&&I()},JU);return()=>window.clearInterval(D)},[S,v,x]);const _=h.useRef(C);_.current=C;const[E]=h.useState(()=>m?nq(o,e.map(D=>D.key)):void 0),M=h.useRef(null),T=h.useRef(VU),[A,j]=h.useState(null);h.useLayoutEffect(()=>{if(!m){j(B=>B===null?B:null);return}let D,K=0;const V=()=>{const B=r?.current??null;return A5(B)?(j(Z=>Z===B?Z:B),!0):!1};if(V())return;const W=r?.current;return W?(D=new ResizeObserver(()=>{V()&&D?.disconnect()}),D.observe(W)):typeof window<"u"&&(K=window.requestAnimationFrame(()=>{if(V())return;const B=r?.current;B&&(D=new ResizeObserver(()=>{V()&&D?.disconnect()}),D.observe(B))})),()=>{K&&window.cancelAnimationFrame(K),D?.disconnect()}},[m,r,o]);const R=m&&A5(A),O=vv({count:C.length,enabled:R,getScrollElement:()=>A,estimateSize:D=>_.current[D]?.kind==="history-gate"?tF:T.current,overscan:zU(),scrollToFn:(D,K,V)=>{const W=M.current;W&&(W.style.height=`${V.getTotalSize()}px`),yS(D,K,V)},getItemKey:D=>_.current[D]?.key??`index:${D}`,anchorTo:"end",initialOffset:()=>Number.MAX_SAFE_INTEGER,initialMeasurementsCache:E});O.shouldAdjustScrollPositionOnItemSizeChange=(D,K,V)=>{if(V.isAtEnd(KU))return!1;const W=V.range?.startIndex;return W!==void 0&&D.index<W},h.useEffect(()=>{if(!m)return;const D=O.itemSizeCache;if(D.size>=ZU){let K=0;for(const V of D.values())K+=V;T.current=Math.min(GU,Math.max(WU,Math.round(K/D.size)))}}),h.useEffect(()=>{if(R)return s?.(O),()=>{rq(o,_.current.map(D=>D.key),O),s?.(null)}},[R,s,O,o]);const N=h.useCallback(D=>l.jsx(Gd,{entry:D,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:c,sessionIsWorking:!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:null,activeStreamingPhase:null,onLoadOlderHistory:u,onLoadAllHistory:p},D.key),[a,p,u,i,f,c,d]);if(t==="none"||t==="tanstack"&&!R)return l.jsx("div",{ref:n,className:"relative w-full",children:C.map(D=>l.jsx("div",{"data-turn-entry":D.key,children:N(D)},D.key))});if(t==="tanstack"){const D=O.getVirtualItems(),K=D[0]?.start??0;return l.jsx("div",{ref:M,className:"relative w-full",style:{height:O.getTotalSize()},children:l.jsx("div",{style:{paddingTop:`${K}px`},children:D.map(V=>{const W=C[V.index];return W?l.jsx("div",{"data-index":V.index,ref:O.measureElement,"data-turn-entry":W.key,children:N(W)},W.key):null})})})}return null});pw.displayName="StaticHistoryList";const mw=({entry:e,sessionId:t,directory:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a=!1,awaitingPromptEcho:c=!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:p})=>{const m=CM(t,u??"",n),g=h.useMemo(()=>RU(e,{activeStreamingMessageId:u,liveParts:m,showTextJustificationActivity:!0,mergeHiddenUserTurns:!0}),[u,e,m]);return l.jsx(Gd,{entry:g,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a,awaitingPromptEcho:c,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:u,activeStreamingPhase:p})};mw.displayName="StreamingTailContent";const gw=h.forwardRef(({sessionKey:e,messages:t,sessionIsWorking:n=!1,sessionAwaitingRecovery:r=!1,awaitingPromptEcho:s=!1,activeStreamingMessageId:o=null,activeStreamingPhase:i=null,retryOverlay:a=null,compactionOverlay:c=null,onMessageContentChange:d,getAnimationHandlers:f,scrollToBottom:u,scrollRef:p,directory:m},g)=>{o9("react.message_list_render"),us("ui.message_list.render");const{hasMoreBefore:b,beforeCursor:y,loadOlder:S}=NM(e),[v,x]=h.useState(()=>N5(e)),k=h.useRef(null),w=h.useRef(null),C=h.useCallback(()=>{const re=p?.current;if(!re)return null;const me=re.getBoundingClientRect(),fe=Array.from(re.querySelectorAll("[data-message-id]")).find(Se=>Se.getBoundingClientRect().bottom>me.top+1);return{top:re.scrollTop,height:re.scrollHeight,anchor:fe?.dataset.messageId?{messageId:fe.dataset.messageId,offsetTop:fe.getBoundingClientRect().top-me.top}:null}},[p]),I=h.useCallback(re=>{x(me=>{const fe=typeof re=="function"?re(me):re;return tq(e,fe),fe})},[e]),_=h.useCallback(re=>{k.current=C(),I(me=>oF(me,re))},[C,I]),E=h.useCallback(re=>{k.current=C(),I(me=>me+re)},[C,I]),M=h.useCallback((re,me,fe)=>{const Se=me.findIndex(_e=>_e.turnId===re);Se<0||(w.current=re,I(_e=>Math.max(_e,sF(Se,fe))))},[I]);h.useLayoutEffect(()=>{x(N5(e)),w.current=null},[e]);const T=h.useRef({sessionKey:void 0,previousOrder:[],animatedIds:new Set}),A=Ol(f),j=Ol(()=>{u?.()}),R=h.useMemo(()=>$l("ui.message_list.base_display_ms",()=>{const re=new Set,me=new Map,fe=[];for(const Ee of t){const ye=Ee.info?.id;typeof ye=="string"&&me.set(ye,Ee)}for(let Ee=0;Ee<t.length;Ee+=1){const ye=t[Ee],ie=ye.info?.id;if(typeof ie=="string"){if(re.has(ie))continue;re.add(ie)}fe.push(hw(typeof ie=="string"?me.get(ie)??ye:ye))}const Se=[],_e=new Set;for(let Ee=0;Ee<fe.length;Ee+=1){const ye=fe[Ee],ie=pF(ye,_e);(fw(ye)||ye.parts.some(oe=>oe.type==="text"&&uF(oe).trim()==="/compact"))&&_e.add(ye.info.id);const ee=Se.length>0?Se[Se.length-1]:void 0;if(mF(ee)){const oe=yF(ie);if(oe.hide){Se[Se.length-1]=vF(ee,oe.taskSessionId);continue}}if(n4(ee)){const oe=r4(ie,fF(ee));if(oe.hide){Se[Se.length-1]=xF(ee,oe.details);continue}}Se.push(ie)}return Se}),[t]),O=h.useRef(null),N=h.useCallback(()=>p?.current?p.current:typeof document>"u"?null:document.querySelector('[data-scrollbar="chat"]'),[p]),D=h.useCallback(()=>{k.current=C()},[C]),K=h.useCallback(()=>{k.current=null},[]);_U({hasMoreBefore:b,beforeCursor:y,resolveScrollContainer:N,loadOlder:S,onBeforeLoad:D,onLoadError:K});const V=h.useMemo(()=>$l("ui.message_list.retry_overlay_ms",()=>{const re=jU(R,{sessionId:a?.sessionId??null,message:a?.message??"Quota limit reached. Retrying automatically.",confirmedAt:a?.confirmedAt,fallbackTimestamp:a?.fallbackTimestamp??0});return EU(re,c?.sessionId??null,c?.compaction??null)}),[R,c,a]),{projection:W,staticTurns:B,streamingTurn:Z}=MU(V,{sessionKey:e,showTextJustificationActivity:!0}),L=W.ungroupedMessageIds.size>0,$=L?V:DU,G=L?W.ungroupedMessageIds:OU,Q=Z?.userMessage.info.id,{entries:z,trailing:X}=h.useMemo(()=>$l("ui.message_list.render_entries_ms",()=>TU({staticTurns:B,messages:$,ungroupedMessageIds:G,lastTurnId:W.lastTurnId,tailUserMessageId:Q})),[W.lastTurnId,$,G,B,Q]),Y=h.useMemo(()=>{if(Z)return{kind:"turn",key:`turn:${Z.turnId}`,turn:Z,isLastTurn:Z.turnId===W.lastTurnId};if(W.ungroupedMessageIds.size===0)return;const re=V[V.length-1];if(!(!re||!W.ungroupedMessageIds.has(re.info.id)))return{kind:"ungrouped",key:`msg:${re.info.id}`,message:re,previousMessage:V.length>1?V[V.length-2]:void 0,nextMessage:void 0}},[V,W.lastTurnId,W.ungroupedMessageIds,Z]);Y&&us("ui.message_list.render.streaming");const ce=Y?Y.kind==="turn"?Y.turn.userMessage:Y.message:void 0,se=h.useMemo(()=>{const re=z.map((Ee,ye)=>{if(Ee.kind!=="turn")return Ee;const ie=ye<z.length-1?(()=>{const ee=z[ye+1];return ee&&ee.kind==="turn"?ee.turn.userMessage:ee?.kind==="ungrouped"?ee.message:void 0})():ce;return ie?{...Ee,nextEntryFirstMessage:ie}:Ee});let me=0;for(const Ee of re)Ee.kind==="turn"&&(me+=1);let fe=-1;const Se=[],_e=[];for(const Ee of re){if(Ee.kind!=="turn"){_e.push(Ee);continue}if(fe+=1,rF(fe,me,v)){Se.push(Ee.turn);continue}_e.push(Ee)}return Se.length===0?_e:[{kind:"history-gate",key:"history-gate",turns:Se},..._e]},[v,z,ce]);h.useLayoutEffect(()=>{const re=k.current;if(re){k.current=null;const _e=p?.current;if(_e){const Ee=re.anchor?.messageId?_e.querySelector(`[data-message-id="${re.anchor.messageId}"]`):null;if(Ee&&re.anchor){const ye=_e.getBoundingClientRect(),ie=Ee.getBoundingClientRect().top-ye.top-re.anchor.offsetTop;ie!==0&&(_e.scrollTop+=ie)}else{const ye=_e.scrollHeight-re.height;ye>0?_e.scrollTop=re.top+ye:_e.scrollTop=re.top}}}const me=w.current;if(!me)return;w.current=null,N()?.querySelector(`[data-turn-id="${me}"]`)?.scrollIntoView({block:"start"})},[se,N,p]);const ue=nn()||se.length>=PU,Ie=ue?"tanstack":"none",de=h.useRef(null),Fe=h.useCallback(re=>{de.current=re},[]),$e=h.useMemo(()=>{const re=Y?[...se,Y]:se;return X.length>0?[...re,...X]:re},[se,Y,X]),Xe=Ol(re=>{d(re)}),We=Ol(re=>{d(re)}),Ae=h.useMemo(()=>t.filter(re=>ys(re)==="user").map(re=>re.info.id),[t]);{const re=T.current;re.sessionKey!==e&&(re.sessionKey=e,re.previousOrder=Ae,re.animatedIds=new Set);const me=re.previousOrder;if(Ae.length>me.length&&me.every((Se,_e)=>Ae[_e]===Se)&&Bk(e))for(let Se=me.length;Se<Ae.length;Se+=1){const _e=Ae[Se];if(_e&&!re.animatedIds.has(_e)){if(!$k(e))break;re.animatedIds.add(_e)}}re.previousOrder=Ae}const be=h.useCallback(re=>ys(re)!=="user"?!1:T.current.animatedIds.has(re.info.id),[]),te=h.useCallback(re=>{T.current.animatedIds.delete(re)},[]),ve=h.useMemo(()=>{const re=new Map;return $e.forEach((me,fe)=>{if(me.kind==="ungrouped"){re.set(me.message.info.id,fe);return}if(me.kind==="history-gate"){me.turns.forEach(Se=>{re.set(Se.userMessage.info.id,fe),Se.assistantMessages.forEach(_e=>{re.set(_e.info.id,fe)})});return}re.set(me.turn.userMessage.info.id,fe),me.turn.assistantMessages.forEach(Se=>{re.set(Se.info.id,fe)})}),re},[$e]),we=h.useMemo(()=>{const re=new Map;return $e.forEach((me,fe)=>{me.kind==="turn"&&re.set(me.turn.turnId,fe),me.kind==="history-gate"&&me.turns.forEach(Se=>{re.set(Se.turnId,fe)})}),re},[$e]),je=h.useCallback(re=>{const me=N();return me?me.querySelector(`[data-message-id="${re}"]`):null},[N]),Ce=h.useCallback(re=>{if(re<0||re>=se.length||!ue)return!1;const me=de.current;return me?(me.scrollToIndex(re,{align:"start",behavior:"auto"}),!0):!1},[se.length,ue]),ze=h.useCallback((re,me="auto")=>{const fe=N();if(!fe)return!1;const Se=je(re);if(!Se)return!1;const _e=fe.getBoundingClientRect(),ie=Se.getBoundingClientRect().top-_e.top+fe.scrollTop-50;return fe.scrollTo({top:ie,behavior:me}),!0},[je,N]),ht=h.useCallback((re,me,fe)=>{if(typeof window>"u")return!1;let Se=0;const _e=()=>{M$(re,me),!ze(me,fe)&&(Se+=1,Se<60&&window.requestAnimationFrame(_e))};return window.requestAnimationFrame(_e),!0},[ze]);return h.useEffect(()=>{if(!g)return;const re={scrollToTurnId:(fe,Se)=>{const _e=se.find(he=>he.kind==="history-gate");if(_e?.kind==="history-gate"){const he=se.reduce((Le,Ue)=>Ue.kind==="turn"?Le+1:Le,0);M(fe,_e.turns,_e.turns.length+he)}const Ee=Se?.behavior??"auto",ye=we.get(fe);if(ye===void 0)return!1;const ie=N();if(!ie)return!1;const ee=ie.querySelector(`[data-turn-id="${fe}"]`);return ee?(ee.scrollIntoView({behavior:Ee,block:"start"}),!0):Y!==void 0&&ye>=se.length?!1:Ce(ye)},scrollToMessageId:(fe,Se)=>{const _e=Se?.behavior??"auto",Ee=ve.get(fe);if(Ee===void 0)return!1;const ye=$e[Ee];if(ye?.kind==="history-gate"){const oe=ye.turns.find(he=>he.userMessage.info.id===fe||he.assistantMessages.some(Le=>Le.info.id===fe));if(oe){const he=se.reduce((Le,Ue)=>Ue.kind==="turn"?Le+1:Le,0);M(oe.turnId,ye.turns,ye.turns.length+he)}}if(ze(fe,_e))return!0;Y!==void 0&&Ee>=se.length||Ce(Ee);const ee=W.indexes.messageToTurnId.get(fe);return ee?ht(ee,fe,_e):!1},holdViewportAnchor:fe=>{const Se=N();if(!Se||typeof window>"u")return;let _e=0,Ee=0,ye=!1;const ie=()=>{ye=!0,Se.removeEventListener("touchstart",ie),Se.removeEventListener("wheel",ie)};Se.addEventListener("touchstart",ie,{passive:!0}),Se.addEventListener("wheel",ie,{passive:!0});const ee=()=>{if(ye)return;const oe=je(fe.messageId);if(oe){const he=oe.getBoundingClientRect().top-Se.getBoundingClientRect().top-fe.offsetTop;Math.abs(he)>.5?(Se.scrollTop+=he,Ee=0):Ee+=1}if(_e+=1,Ee>=UU||_e>=qU){Se.removeEventListener("touchstart",ie),Se.removeEventListener("wheel",ie);return}window.requestAnimationFrame(ee)};window.requestAnimationFrame(ee)},isHistoryVirtualized:()=>ue,captureViewportAnchor:()=>{const fe=N();if(!fe)return null;const Se=fe.getBoundingClientRect(),Ee=Array.from(fe.querySelectorAll("[data-message-id]")).find(ie=>ie.getBoundingClientRect().bottom>Se.top+1);if(!Ee)return null;const ye=Ee.dataset.messageId;return ye?{messageId:ye,offsetTop:Ee.getBoundingClientRect().top-Se.top}:null},restoreViewportAnchor:fe=>{const Se=N();if(!Se||!ve.has(fe.messageId))return!1;const _e=()=>{const Ee=je(fe.messageId);if(!Ee)return!1;const ye=Se.getBoundingClientRect(),ee=Ee.getBoundingClientRect().top-ye.top-fe.offsetTop;return ee!==0&&(Se.scrollTop+=ee),!0};if(!_e()){const Ee=ve.get(fe.messageId);if(typeof Ee=="number"&&Ee<se.length)return Ce(Ee)}return _e()},scrollToBottom:()=>{if(ue&&se.length>0&&de.current){de.current.scrollToEnd();return}const fe=N();fe&&(fe.scrollTop=fe.scrollHeight+4096)}};if(typeof g=="function")return g(re),()=>{g(null)};const me=g;return me.current=re,()=>{me.current=null}},[$e,je,se,ve,W.indexes.messageToTurnId,N,M,ht,Ce,ze,ue,Y,we,g]),l.jsx("div",{children:l.jsx(l5,{disabled:!1,children:l.jsxs("div",{className:"relative w-full",children:[l.jsx(l5,{disabled:ue,children:l.jsx(pw,{entries:se,engine:Ie,contentRef:O,scrollRef:p,registerTanstackVirtualizer:Fe,virtualizerKey:e,onMessageContentChange:Xe,getAnimationHandlers:A,scrollToBottom:j,shouldAnimateUserMessage:be,onUserAnimationConsumed:te,onLoadOlderHistory:_,onLoadAllHistory:E},e)}),Y?l.jsx(mw,{entry:Y,sessionId:e??null,directory:m,onMessageContentChange:We,getAnimationHandlers:A,scrollToBottom:j,sessionIsWorking:n,sessionAwaitingRecovery:r,awaitingPromptEcho:s,shouldAnimateUserMessage:be,onUserAnimationConsumed:te,activeStreamingMessageId:o,activeStreamingPhase:i}):null,X.map(re=>l.jsx(Gd,{entry:re,onMessageContentChange:We,getAnimationHandlers:A,scrollToBottom:j,sessionIsWorking:n,shouldAnimateUserMessage:be,onUserAnimationConsumed:te},re.key))]})})})});gw.displayName="MessageList";const sq=h.memo(gw),oq=({visible:e,onClick:t})=>l.jsx("div",{className:P("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:l.jsx(Me,{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:l.jsx(F,{name:"arrow-down",className:"h-4 w-4"})})}),iq=h.memo(oq),aq=.1,lq=40,cq=2,R5=1500,P5=2,yw=350,dq=300,uq=600,fq=8e3,Ni=()=>typeof performance<"u"?performance.now():Date.now(),hq=(e,t)=>{if(e)return lq;const n=t?.clientHeight??0;return n<=0?96:Math.max(48,n*aq)},vw=e=>e.scrollHeight-e.scrollTop-e.clientHeight,gi=e=>e.scrollHeight-e.clientHeight>1,D5=(e,t)=>vw(e)<=hq(t,e),pq=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case"ArrowUp":case"PageUp":case"Home":return!0;default:return!1}},mq=(e,t)=>{if(!(t instanceof Element))return null;const n=t.closest("[data-scrollable]");return!n||n===e||!(n instanceof HTMLElement)?null:n},O5=(e,t)=>{const n=mq(e,t);return n?n.scrollTop>0:!1},gq=100,yq=48,vq=.1,xq=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=Math.max(yq,e.clientHeight*vq),bq=(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},wq=e=>{const t=e.raf??requestAnimationFrame,n=e.caf??cancelAnimationFrame,r=e.ResizeObserver??globalThis.ResizeObserver,s=e.MutationObserver??globalThis.MutationObserver;let o,i,a,c,d,f,u=!0;const p=new Map;let m=[];const g=()=>{c===void 0&&(c=t(()=>{c=void 0,y()}))},b=()=>{const _=o;if(!_){m=[],u=!1;return}const E=_.getBoundingClientRect().top;m=[...p].map(([M,T])=>({id:M,top:T.getBoundingClientRect().top-E+_.scrollTop})),m.sort((M,T)=>M.top-T.top),u=!1},y=()=>{const _=o;if(!_)return;u&&b();const E=xq(_)?m[m.length-1]?.id:bq(m,_.scrollTop+gq);!E||E===f||(f=E,e.onActive(E))},S=()=>{const _=o;if(_){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(_);for(const E of p.values())i.observe(E)}if(a?.disconnect(),a=void 0,s){a=new s(()=>{u=!0,g()});const E={subtree:!0,childList:!0};r||(E.characterData=!0,E.characterDataOldValue=!1),a.observe(_,E)}u=!0,g()}},v=_=>{o!==_&&(o=_,f=void 0,S())},x=(_,E)=>{const M=p.get(E);M&&M!==_&&i?.unobserve(M),p.set(E,_),i&&i.observe(_),u=!0,g()},k=_=>{const E=p.get(_);E&&(i?.unobserve(E),p.delete(_),u=!0,g())},w=()=>{u=!0,g()},C=()=>{for(const _ of p.values())i?.unobserve(_);p.clear(),m=[],f=void 0,u=!0};return{setContainer:v,register:x,unregister:k,onScroll:g,markDirty:w,clear:C,destroy:()=>{c!==void 0&&n(c),c=void 0,clearTimeout(d),d=void 0,C(),i?.disconnect(),a?.disconnect(),i=void 0,a=void 0,o=void 0},getActiveId:()=>f}};function Sq(e,t){h.useEffect(()=>{if(!t)return;const n=e;if(!n)return;let r=null;const s=wq({onActive:u=>{u!==r&&(r=u,t(u))}});s.setContainer(n);const o=new Map,i=u=>{const p=u.dataset.turnId;return p?(o.set(p,u),s.register(u,p),!0):!1},a=u=>{const p=u.dataset.turnId;return!p||o.get(p)!==u?!1:(o.delete(p),s.unregister(p),!0)},c=u=>{if(!(u instanceof HTMLElement))return[];const p=[];return u.matches("[data-turn-id]")&&p.push(u),u.querySelectorAll("[data-turn-id]").forEach(m=>p.push(m)),p};n.querySelectorAll("[data-turn-id]").forEach(i),s.markDirty();const d=new MutationObserver(u=>{let p=!1;u.forEach(m=>{m.removedNodes.forEach(g=>{c(g).forEach(b=>{a(b)&&(p=!0)})}),m.addedNodes.forEach(g=>{c(g).forEach(b=>{i(b)&&(p=!0)})})}),p&&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 Cq({containerEl:e,handleScrollEvent:t,releaseFromUserIntent:n,scrollRef:r,stateRef:s,canScroll:o,scrollToBottomNow:i,updateOverflowAndButton:a,keyboardAnimRef:c,animationGuardUntilRef:d,lastScrollTopRef:f}){h.useEffect(()=>{const u=e;if(!u)return;f.current=u.scrollTop;const p=x=>{x.deltaY>=0||O5(u,x.target)||n()};let m=null;const g=x=>{const k=x.touches.item(0);m=k?k.clientY:null},b=x=>{const k=x.touches.item(0);if(!k){m=null;return}const w=m;m=k.clientY,!(w===null||k.clientY-w<=cq)&&(O5(u,x.target)||n())},y=()=>{m=null},S=x=>{pq(x)&&n()},v=x=>{const k=x.target;k instanceof Element&&k.closest("[data-overlay-scrollbar-thumb]")&&n()};return u.addEventListener("scroll",t,{passive:!0}),u.addEventListener("wheel",p,{passive:!0}),u.addEventListener("touchstart",g,{passive:!0}),u.addEventListener("touchmove",b,{passive:!0}),u.addEventListener("touchend",y,{passive:!0}),u.addEventListener("touchcancel",y,{passive:!0}),u.addEventListener("keydown",S),typeof window<"u"&&window.addEventListener("pointerdown",v,!0),()=>{u.removeEventListener("scroll",t),u.removeEventListener("wheel",p),u.removeEventListener("touchstart",g),u.removeEventListener("touchmove",b),u.removeEventListener("touchend",y),u.removeEventListener("touchcancel",y),u.removeEventListener("keydown",S),typeof window<"u"&&window.removeEventListener("pointerdown",v,!0)}},[e,t,f,n]),h.useEffect(()=>{if(typeof window>"u")return;const u=m=>{const g=m.detail;g&&(c.current=!0,d.current=Ni()+g.durationMs+yw)},p=()=>{c.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",p),()=>{window.removeEventListener("oc:keyboard-anim",u),window.removeEventListener("oc:keyboard-settled",p),c.current=!1}},[d,o,c,r,i,s,a])}const kq=({currentSessionId:e,currentSessionKey:t,sessionMessageCount:n,sessionIsWorking:r,isMobile:s,onActiveTurnChange:o})=>{const i=h.useRef(null),[a,c]=h.useState(null),d=h.useRef(null),[f,u]=h.useState("following"),[p,m]=h.useState(!1),[g,b]=h.useState(!1),[y,S]=h.useState(!1),v=h.useRef("following"),x=h.useRef(s);x.current=s;const k=h.useRef(r);k.current=r;const w=h.useRef(!1),C=h.useRef(null),I=h.useRef(t);I.current=t;const _=h.useRef(null),E=h.useRef(null),M=h.useRef(null),T=h.useRef(0),A=h.useRef(!1),j=h.useRef(0),R=h.useRef(!1),O=h.useRef(null),N=h.useRef(null),D=h.useRef(0),K=h.useRef(null);h.useLayoutEffect(()=>{i.current!==d.current&&(d.current=i.current,c(i.current))});const V=h.useCallback(()=>k.current||w.current,[]),W=h.useCallback(be=>{v.current!==be&&(v.current=be,u(be))},[]),B=h.useCallback(be=>{E.current={top:Math.max(0,be.scrollHeight-be.clientHeight),time:Ni()},M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{E.current=null,M.current=null},R5)},[]),Z=h.useCallback(be=>{const te=E.current;return te?Ni()-te.time>R5?(E.current=null,!1):Math.abs(be.scrollTop-te.top)<P5:!1},[]),L=h.useCallback(()=>Ni()<T.current,[]),$=h.useCallback(()=>{R.current=!1,O.current&&(clearTimeout(O.current),O.current=null),N.current&&(clearTimeout(N.current),N.current=null)},[]),G=h.useCallback(()=>{O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{O.current=null,$()},uq)},[$]),Q=h.useCallback(()=>{const be=i.current;be&&(R.current=!0,D.current=be.scrollHeight,G(),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{N.current=null,$()},fq))},[G,$]),z=h.useCallback(()=>{const be=i.current;if(!be){m(!1),b(!1);return}const te=gi(be);if(m(te),!te){b(!1);return}const ve=v.current==="released"&&!D5(be,x.current);b(ve)},[]),X=h.useCallback(be=>{const te=i.current;if(!te)return;B(te);const ve=te.scrollHeight+4096;if(be==="smooth"){te.scrollTo({top:ve,behavior:be});return}te.scrollTop=ve},[B]),Y=h.useCallback((be,te="auto")=>{const ve=i.current;!be&&!V()||(be&&v.current!=="following"&&W("following"),ve&&(!be&&v.current!=="following"||X(be?te:"auto")))},[V,X,W]),ce=h.useCallback(()=>{const be=i.current;if(be){if(!gi(be)){W("following");return}v.current!=="released"&&(W("released"),z())}},[W,z]),se=h.useCallback((be="instant")=>{Y(!0,be==="smooth"?"smooth":"auto")},[Y]),ue=h.useCallback(()=>{Y(!0)},[Y]),Ie=h.useCallback(()=>{W("released"),z()},[W,z]),de=h.useCallback(()=>{$(),ce()},[$,ce]),Fe=h.useCallback(async()=>{const be=I.current;return be?i.current?(K.current=null,W("following"),Y(!0),Q(),z(),!1):(K.current=be,W("following"),!1):!1},[Q,Y,W,z]);h.useEffect(()=>{!e||!t||t===_.current||(_.current=t,is.getInstance().recordSessionStart(e),E.current=null,K.current&&K.current!==t&&(K.current=null))},[e,t]),h.useEffect(()=>{if(w.current=!1,C.current&&(clearTimeout(C.current),C.current=null),r){v.current==="following"&&Y(!0);return}w.current=!0,C.current=setTimeout(()=>{w.current=!1,C.current=null},dq)},[r,Y]),h.useEffect(()=>{S(f==="following"&&r)},[f,r]),h.useLayoutEffect(()=>{a&&K.current&&K.current===t&&Fe()},[a,t,Fe]);const $e=h.useCallback(()=>{const be=i.current;if(!be)return;const te=j.current;j.current=be.scrollTop;const ve=be.scrollTop>te+.5;if(z(),!gi(be)){W("following");return}if(D5(be,x.current)){const we=vw(be)<=P5;(ve||v.current==="following"||we)&&W("following");return}if(v.current==="following"&&(Z(be)||L())){Y(!1);return}ce()},[L,Z,Y,W,ce,z]);Cq({containerEl:a,handleScrollEvent:$e,releaseFromUserIntent:de,scrollRef:i,stateRef:v,canScroll:gi,scrollToBottomNow:X,updateOverflowAndButton:z,keyboardAnimRef:A,animationGuardUntilRef:T,lastScrollTopRef:j}),h.useEffect(()=>{const be=a;if(!be||typeof ResizeObserver>"u")return;const te=new ResizeObserver(()=>{if(A.current){z();return}const we=i.current;if(we&&!gi(we)){W("following"),z();return}if(z(),R.current&&we){const je=we.scrollHeight>D.current+1;D.current=we.scrollHeight,Y(!0),je&&G();return}V()&&v.current==="following"&&Y(!1)});te.observe(be);const ve=be.firstElementChild;return ve instanceof Element&&te.observe(ve),()=>te.disconnect()},[G,a,V,Y,W,z]),h.useEffect(()=>{z()},[n,z]);const Xe=h.useCallback(be=>{if(be==="animation"&&(T.current=Ni()+yw),z(),R.current){Y(!0),G();return}v.current==="following"&&Y(!1)},[G,Y,z]),We=h.useRef(new Map),Ae=h.useCallback(be=>{const te=We.current.get(be);if(te)return te;const ve=()=>{v.current==="following"&&Y(!1)},we={onChunk:ve,onComplete:()=>{z()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:ve,onReservationCancelled:()=>{}};return We.current.set(be,we),we},[Y,z]);return h.useEffect(()=>()=>{M.current&&(clearTimeout(M.current),M.current=null),C.current&&(clearTimeout(C.current),C.current=null),$()},[$]),Sq(a,o),{scrollRef:i,state:f,isPinned:f==="following",isOverflowing:p,isFollowingProgrammatically:y,showScrollButton:g,notifyContentChange:Xe,getAnimationHandlers:Ae,goToBottom:se,scrollToBottomOnSend:ue,releaseAutoFollow:Ie,restoreSnapshot:Fe}},o1=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},i1=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},H5=e=>{if(!e)return null;const t=o1(e),n=typeof e.info?.id=="string"?e.info.id:"",r=i1(e)??"";return`${n}::${t}::${r}`},Mq=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}),Iq=(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:H5(t[f])===H5(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=o1(r),o=r.info.id,i=Mq(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=i1(r);if(!a)return i;const c=i.turnIndexById.get(a);if(typeof c!="number"||c<0)return null;const d=i.turnIds[c];return d?(i.messageToTurnId.set(o,d),i.messageToTurnIndex.set(o,c),i):null},_q=e=>{const t=[],n=[],r=new Map,s=new Map,o=new Map,i=new Map;let a=-1;return e.forEach((c,d)=>{const f=o1(c),u=c.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 b=t[a];b&&(s.set(u,b),o.set(u,a))}return}const p=i1(c);if(!p)return;const m=i.get(p);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}},Eq=30,jq=1200,Tq=1.5,Aq=e=>Math.max(jq,e*Tq),Lq=4,Nq=30,Rq=250,Pq=2e3,Dq=2500,Xs=new Map,Oq=()=>nn()?Lq:Eq,Hq=e=>nn()?e.length<=Nq:!0,F5=(e,t)=>{if(Xs.delete(e),!Hq(t.messages))return;const n=Oq();for(;Xs.size>=n;){const r=Xs.keys().next().value;if(typeof r!="string")break;Xs.delete(r)}Xs.set(e,t)},Fq=e=>!e.sessionId||!e.isPinned||!e.canLoadEarlier||e.isLoadingOlder||e.pendingRevealWork?!1:e.scrollHeight<=e.clientHeight+1,V5=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),Vq=20,Bq=4,B5=(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-Bq&&(e.scrollTop=t),s+=1,s<Vq?window.requestAnimationFrame(i):e.removeEventListener("touchstart",o))};window.requestAnimationFrame(i)},$5=(e,t,n)=>!e||!t||t===e?!1:n.some(r=>r.info.id===e);function $q({sessionKey:e,timelineIdentityRef:t,scrollRef:n,messageListRef:r,renderedMessages:s,isPinnedRef:o,goToBottom:i,captureViewportAnchor:a,restoreViewportAnchor:c}){const d=h.useRef(null),f=h.useRef(null);return h.useLayoutEffect(()=>{d.current=null,f.current=null},[e]),h.useLayoutEffect(()=>{const u=n.current;if(!u)return;let p=d.current;const m=f.current,g=s[0]?.info?.id??null,b=s[s.length-1]?.info?.id??null,y=m?V5({previousOldestId:m.oldestId,previousNewestId:m.newestId,currentOldestId:g,currentNewestId:b})||$5(m.oldestId,g,s):!1;p&&p.identity!==t.current&&(d.current=null,p=null);const S=p?V5({previousOldestId:p.oldestId,previousNewestId:p.newestId,currentOldestId:g,currentNewestId:b})||$5(p.oldestId,g,s):!1,v=y||S,x=!!(p&&(y||S)),k=()=>{f.current={oldestId:g,newestId:b,scrollHeight:u.scrollHeight}},w=()=>{const I=d.current;I&&(d.current={...I,height:u.scrollHeight,top:u.scrollTop,anchor:a(),oldestId:g,newestId:b})};if(o.current){v?(d.current=null,i("instant")):p&&w(),k();return}const C=r.current?.isHistoryVirtualized()??!1;if(p&&x){if(d.current=null,C){!p.historyVirtualized&&p.anchor&&c(p.anchor),k();return}const I=u.scrollHeight-p.height,_=()=>I<=0?!1:(u.scrollTop=p.top+I,!0);if(nn()&&I>0){B5(u,p.top+I),k();return}p.anchor&&c(p.anchor)||_()}else if(y&&m&&!C){const I=u.scrollHeight-m.scrollHeight;if(I>0){const _=u.scrollTop+I;nn()?B5(u,_):u.scrollTop=_}}else p&&w();k()},[a,r,s,n,c,i,o,t]),{prePrependScrollRef:d}}const zq=({sessionId:e,sessionKey:t,messages:n,historyMeta:r,scrollRef:s,messageListRef:o,loadMoreMessages:i,goToBottom:a,releaseAutoFollow:c,isPinned:d,showScrollButton:f})=>{const u=h.useRef(null),p=h.useRef(null),m=h.useRef(null),g=h.useMemo(()=>{const te=t??"";m.current!==t&&(m.current=t,u.current=null,p.current=null);const ve=te?Xs.get(te):void 0;if(ve&&ve.messages===n)return F5(te,ve),u.current=ve.model,p.current=n,ve.model;const je=Iq(u.current,p.current,n)??_q(n);return u.current=je,p.current=n,te&&n.length>0&&F5(te,{messages:n,model:je}),je},[n,t]),[b,y]=h.useState(!1),[S,v]=h.useState(!1),[x,k]=h.useState(null),w=h.useRef(g),C=h.useRef(d),I=h.useRef(b),_=h.useRef(S),E=h.useRef(e),M=h.useRef({key:t});M.current.key!==t&&(M.current={key:t});const T=h.useRef(n),A=h.useRef(r),j=h.useRef(null),R=h.useRef([]),O=h.useRef(null),N=h.useRef(null),D=h.useRef(!1),K=h.useRef(null),V=h.useMemo(()=>{const te=l0().HISTORICAL_MESSAGES,ve=!1,we=r?!r.complete:n.length>=te,je=!!r?.loading;return{hasBufferedTurns:ve,hasMoreAboveTurns:we,historyLoading:je,canLoadEarlier:we}},[r,n.length]),W=h.useRef(V);w.current=g,C.current=d,I.current=b,_.current=S,W.current=V,E.current=e,T.current=n,A.current=r;const B=h.useCallback(()=>{D.current=!0,K.current!==null&&typeof window<"u"&&(window.clearTimeout(K.current),K.current=null)},[]),Z=h.useCallback(()=>{if(typeof window>"u"){D.current=!1;return}K.current!==null&&window.clearTimeout(K.current),K.current=window.setTimeout(()=>{K.current=null,D.current=!1},Pq)},[]);h.useLayoutEffect(()=>{if(j.current===t)return;K.current!==null&&typeof window<"u"&&(window.clearTimeout(K.current),K.current=null),D.current=!1,j.current=t;const te=O.current;te&&te.identity!==M.current&&(O.current=null,te.resolve(!1)),y(!1),v(!1),N.current=null,k(null)},[t]),h.useLayoutEffect(()=>{if(!d)return;const te=g.turnIds[g.turnIds.length-1];te&&k(ve=>ve===te?ve:te)},[d,g.turnIds]);const L=h.useCallback(()=>{const te=R.current;te.length!==0&&(R.current=[],te.forEach(ve=>ve()))},[]),$=h.useCallback(()=>new Promise(te=>{if(typeof window>"u"){te();return}let ve=!1;const we=()=>{ve||(ve=!0,window.clearTimeout(je),te())};R.current.push(we);const je=window.setTimeout(we,Rq)}),[]),G=h.useCallback(te=>{const ve=O.current;ve&&(O.current=null,ve.resolve(te))},[]),Q=h.useCallback(()=>{const te=O.current;if(!te)return;if(te.identity!==M.current){G(!1);return}if(te.kind==="turn"?o.current?.scrollToTurnId(te.id,{behavior:te.behavior})??!1:o.current?.scrollToMessageId(te.id,{behavior:te.behavior})??!1){te.turnId&&(N.current={turnId:te.turnId,expiresAt:Date.now()+Dq},k(te.turnId)),G(!0);return}typeof(te.kind==="turn"?w.current.turnIndexById.get(te.id):w.current.messageToTurnIndex.get(te.id))=="number"&&G(!1)},[o,G]);h.useEffect(()=>()=>{K.current!==null&&typeof window<"u"&&(window.clearTimeout(K.current),K.current=null),L(),G(!1)},[L,G]);const z=n;h.useLayoutEffect(()=>{L(),Q()},[Q,z,L]);const X=h.useCallback(()=>o.current?.captureViewportAnchor()??null,[o]),Y=h.useCallback(te=>o.current?.restoreViewportAnchor(te)??!1,[o]),{prePrependScrollRef:ce}=$q({sessionKey:t,timelineIdentityRef:M,scrollRef:s,messageListRef:o,renderedMessages:z,isPinnedRef:C,goToBottom:a,captureViewportAnchor:X,restoreViewportAnchor:Y}),se=h.useCallback(async()=>!1,[]),ue=h.useCallback(async te=>{if(!E.current||!M.current.key||I.current||!W.current.hasMoreAboveTurns)return!1;const ve=E.current,we=M.current;if(!ve||!we.key)return!1;const je=()=>{ce.current?.identity===we&&(ce.current=null)},Ce=s.current,ze=T.current,ht=ze.length,xe=ze[0]?.info?.id??null,re=A.current?.limit??l0().HISTORICAL_MESSAGES;te.preserveViewport&&Ce&&(ce.current={identity:we,height:Ce.scrollHeight,top:Ce.scrollTop,anchor:X(),historyVirtualized:o.current?.isHistoryVirtualized()??!1,oldestId:xe,newestId:ze[ze.length-1]?.info?.id??null}),B(),y(!0);try{let me=ht,fe=xe,Se=re;const _e=w.current.turnCount;for(;;){if(await i(ve,"up"),M.current!==we||(await $(),M.current!==we))return je(),!1;const Ee=T.current,ye=Ee.length,ie=Ee[0]?.info?.id??null,ee=A.current?.limit??Se,oe=ye>me||typeof fe=="string"&&typeof ie=="string"&&fe!==ie||ee>Se;if(w.current.turnCount-_e>0)return!0;if(!oe)return je(),!1;if(!W.current.hasMoreAboveTurns)return!0;me=ye,fe=ie,Se=ee}}catch(me){throw je(),me}finally{M.current===we&&(y(!1),Z())}},[B,X,i,o,ce,s,Z,$]),Ie=h.useCallback(async te=>{const ve=M.current;B(),te?.userInitiated&&c();try{await ue({preserveViewport:!0})}finally{M.current===ve&&Z()}},[B,ue,c,Z]),de=h.useCallback(()=>{if(nn())return;const te=s.current;te&&(C.current||te.scrollTop>=Aq(te.clientHeight)||W.current.canLoadEarlier&&(I.current||_.current||Ie({userInitiated:!0})))},[Ie,s]),Fe=h.useCallback(()=>{if(nn()||D.current)return;const te=s.current;te&&Fq({sessionId:E.current,isPinned:C.current,canLoadEarlier:W.current.canLoadEarlier,isLoadingOlder:I.current,pendingRevealWork:_.current,scrollHeight:te.scrollHeight,clientHeight:te.clientHeight})&&Ie()},[Ie,s]);h.useEffect(()=>{if(typeof window>"u")return;const te=window.requestAnimationFrame(()=>{Fe()});return()=>window.cancelAnimationFrame(te)},[V.canLoadEarlier,b,d,Fe,S,z.length,t]),h.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const te=s.current;if(!te)return;let ve=null;const we=()=>{ve===null&&(ve=window.requestAnimationFrame(()=>{ve=null,Fe()}))},je=new ResizeObserver(we);je.observe(te);const Ce=te.firstElementChild;return Ce instanceof Element&&je.observe(Ce),we(),()=>{ve!==null&&window.cancelAnimationFrame(ve),je.disconnect()}},[Fe,s,t]);const $e=h.useCallback(async(te,ve)=>{if(!te||!E.current||!M.current.key)return!1;const we=M.current;c(),v(!0);try{return M.current!==we||typeof w.current.turnIndexById.get(te)!="number"?!1:!!await new Promise(ze=>{O.current={identity:we,kind:"turn",id:te,behavior:ve?.behavior??"auto",turnId:te,resolve:ze},Q()})}finally{M.current===we&&v(!1)}},[Q,c]),Xe=h.useCallback(async(te,ve)=>{if(!te||!E.current||!M.current.key)return!1;const we=M.current;c(),v(!0);try{if(M.current!==we)return!1;const je=w.current.messageToTurnId.get(te);return typeof w.current.messageToTurnIndex.get(te)!="number"?!1:!!await new Promise(ht=>{O.current={identity:we,kind:"message",id:te,behavior:ve?.behavior??"auto",turnId:je??null,resolve:ht},Q()})}finally{M.current===we&&v(!1)}},[Q,c]),We=h.useCallback(async()=>{v(!1),y(!1),a("smooth")},[a]),Ae=h.useCallback(async()=>{v(!1),y(!1),a("instant")},[a]),be=h.useCallback(te=>{const ve=N.current;if(ve){if(te!==ve.turnId&&Date.now()<ve.expiresAt)return;N.current=null}k(te)},[]);return{turnIds:g.turnIds,turnStart:0,renderedMessages:z,historySignals:V,isLoadingOlder:b,pendingRevealWork:S,activeTurnId:x,showScrollToBottom:f&&!S,turnWindowModel:g,loadEarlier:Ie,revealBufferedTurns:se,resumeToBottom:We,resumeToBottomInstant:Ae,scrollToTurn:$e,scrollToMessage:Xe,handleHistoryScroll:de,captureViewportAnchor:X,restoreViewportAnchor:Y,handleActiveTurnChange:be}};function gp(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
212
- `)}function xw(e,t=80){const r=gp(e).replace(/\n/g," ");return r.length>t?`${r.slice(0,t)}…`:r}const Uq=({open:e,onOpenChange:t,onScrollToMessage:n,onScrollByTurnOffset:r,onResumeToLatest:s,canLoadEarlier:o=!1,isLoadingEarlier:i=!1,onLoadEarlier:a,onRevert:c,onFork:d})=>{const{isMobile:f}=Pr(),u=pe($=>$.currentSessionId),[p,m]=h.useState(0);h.useEffect(()=>{if(!u){m(0);return}const $=()=>{try{const{getPiSessionStore:G}=require("@/apps/pi-session-store");m(G().getState().reducer.bySession.get(u)?.sessionTreeRevision??0)}catch{m(0)}};$();try{const{getPiSessionStore:G}=require("@/apps/pi-session-store");return G().subscribe($,`session:${u}`)}catch{return}},[u]);const[g,b]=h.useState(new Map),y=h.useRef(null);h.useEffect(()=>{if(!e||!u)return;y.current!==u&&(y.current=u,b(new Map));let $=!1;return(async()=>{try{const{getPiSessionStore:G}=require("@/apps/pi-session-store"),Q=await G().tree(u);if($)return;const z=new Map,X=Y=>{Y.label&&z.set(Y.entryId,Y.label);for(const ce of Y.children)X(ce)};for(const Y of Q.nodes)X(Y);b(z)}catch{}})(),()=>{$=!0}},[u,e,p]);const[S,v]=h.useState(!1);h.useEffect(()=>{if(!u){v(!1);return}const $=()=>{try{const{getPiSessionStore:G}=require("@/apps/pi-session-store"),Q=G().getState().reducer.bySession.get(u);v(Q?.lifecycle==="busy"||Q?.lifecycle==="retry")}catch{v(!1)}};$();try{const{getPiSessionStore:G}=require("@/apps/pi-session-store");return G().subscribe($,`session:${u}`)}catch{return}},[u]);const x=Id(u??""),[k,w]=h.useState(""),[C,I]=h.useState(0),_=h.useRef([]),E=h.useRef(null),M=h.useRef(null),T=h.useRef(!1),A=h.useRef(e),j=h.useCallback($=>new Date($).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),[]),R=h.useCallback($=>new Date($).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),[]),O=h.useMemo(()=>x.filter($=>$.info.role==="user").map($=>({message:$})),[x]),N=h.useMemo(()=>{const $=k.trim();if(!$)return O;const G=$.toLowerCase();return O.filter(({message:Q})=>gp(Q.parts).toLowerCase().includes(G))},[O,k]);h.useEffect(()=>{T.current||I(k.trim()?0:Math.max(0,N.length-1))},[N,k]),h.useEffect(()=>{_.current=_.current.slice(0,N.length)},[N.length]),h.useEffect(()=>{T.current||_.current[C]?.scrollIntoView({block:"nearest"})},[C]),h.useEffect(()=>{!T.current||M.current||i||(T.current=!1)},[N.length,i]),h.useLayoutEffect(()=>{const $=A.current;if(A.current=e,!e||$||T.current||k.trim())return;const G=E.current;G&&(G.scrollTop=G.scrollHeight)},[e,k]),h.useLayoutEffect(()=>{const $=M.current,G=E.current;if(!$||!G||i)return;M.current=null;const Q=_.current.find(X=>X?.dataset.timelineMessageId===$.messageId);if(!Q)return;const z=Q.getBoundingClientRect().top-G.getBoundingClientRect().top;G.scrollTop+=z-$.top},[N.length,i]);const D=h.useCallback(()=>{const $=E.current;if($){const G=$.getBoundingClientRect().top,Q=_.current.find(z=>z?z.getBoundingClientRect().bottom>=G:!1);Q?.dataset.timelineMessageId&&(M.current={messageId:Q.dataset.timelineMessageId,top:Q.getBoundingClientRect().top-G})}T.current=!0,a?.()},[a]),K=h.useCallback(async $=>{await n?.($)!==!1&&t(!1)},[t,n]),V=h.useCallback($=>{const G=N.length;if(G!==0){if($.key==="ArrowDown"){$.preventDefault(),I(Q=>(Q+1)%G);return}if($.key==="ArrowUp"){$.preventDefault(),I(Q=>(Q-1+G)%G);return}if($.key==="Enter"){$.preventDefault();const Q=(C%G+G)%G,z=N[Q];z&&K(z.message.info.id)}}},[N,K,C]),W=h.useCallback(async()=>{const $=N.length;if($===0||!c||S)return;const G=(C%$+$)%$,Q=N[G];if(Q)try{await c(Q.message.info.id),t(!1)}catch(z){ke.error(z instanceof Error?z.message:"Failed to revert")}},[N,S,c,t,C]),B=h.useCallback(async()=>{const $=N.length;if($===0||!d||S)return;const G=(C%$+$)%$,Q=N[G];if(Q)try{await d(Q.message.info.id),t(!1)}catch(z){ke.error(z instanceof Error?z.message:"Failed to fork")}},[N,S,d,t,C]),Z=h.useCallback($=>{const G=N.length;if(G!==0){if($.key==="ArrowDown"){$.preventDefault(),I(Q=>(Q+1)%G);return}if($.key==="ArrowUp"){$.preventDefault(),I(Q=>(Q-1+G)%G);return}if($.key==="Enter"){$.preventDefault();const Q=(C%G+G)%G,z=N[Q];z&&K(z.message.info.id)}}},[N,K,C]);if(h.useEffect(()=>{if(!e||f)return;const $=window.setTimeout(()=>E.current?.focus(),100);return()=>window.clearTimeout($)},[e,f]),!u)return null;const L=N[(C%Math.max(1,N.length)+Math.max(1,N.length))%Math.max(1,N.length)]?.message??null;return l.jsx(Td,{open:e,onOpenChange:t,children:l.jsxs(Ad,{className:P("flex flex-col",f?"max-w-full max-h-[85vh] rounded-t-2xl mt-auto":"max-w-2xl max-h-[70vh]"),children:[l.jsxs(Ld,{children:[l.jsxs(Nd,{className:"flex items-center gap-2",children:[l.jsx(F,{name:"time",className:"h-5 w-5"}),"Conversation Timeline"]}),l.jsx(im,{children:f?"Tap a message, then Revert or Fork":"Arrow keys to move • Enter to jump"})]}),!f&&l.jsxs("div",{className:"relative mt-2",children:[l.jsx(F,{name:"search",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(Io,{placeholder:"Search messages...",value:k,onChange:$=>w($.target.value),onKeyDown:V,className:"pl-9 w-full"})]}),o&&a&&l.jsx("div",{className:"flex justify-center py-1",children:l.jsxs(Me,{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&&l.jsx(F,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),l.jsx("div",{ref:E,tabIndex:0,onKeyDown:Z,className:"flex-1 overflow-y-auto outline-none focus-visible:ring-1 focus-visible:ring-ring rounded","aria-label":"Message list",children:N.length===0?l.jsx("div",{className:"text-center text-muted-foreground py-8",children:k?"No messages found":"No messages in this session yet"}):N.map(({message:$},G)=>{const Q=xw($.parts),z=$.info.time?.created??0,X=j(z),Y=N[G-1],ce=Y?j(Y.message.info.time?.created??0):null,se=X!==ce,ue=R(z),Ie=G===C,de=g.get($.info.id),Fe=k.trim()?Zq(gp($.parts),k):null;return l.jsxs(h.Fragment,{children:[se&&l.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-3 bg-background/95 py-2 backdrop-blur-sm",children:[l.jsx("div",{className:"h-px flex-1 bg-border/60"}),l.jsx("span",{className:"typography-meta text-muted-foreground",children:X}),l.jsx("div",{className:"h-px flex-1 bg-border/60"})]}),l.jsxs("div",{ref:$e=>{_.current[G]=$e},"data-timeline-message-id":$.info.id,className:P("group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",Ie&&"bg-interactive-selection text-interactive-selection-foreground"),onClick:()=>{K($.info.id)},onMouseEnter:()=>I(G),children:[l.jsx("span",{className:P("typography-meta w-16 flex-shrink-0 text-right tabular-nums",Ie?"text-interactive-selection-foreground/70":"text-muted-foreground"),children:ue}),de&&l.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:de}),l.jsxs("p",{className:P("flex-1 min-w-0 typography-small truncate",Ie?"text-interactive-selection-foreground":"text-foreground"),children:[Fe??(Q||"[No text content]"),!Fe&&Q&&Q.length>=80&&"…"]})]})]},$.info.id)})}),L&&l.jsxs("div",{className:P("flex gap-2 mt-3",f?"flex-col":"flex-row"),children:[l.jsxs(Me,{type:"button",variant:f?"default":"outline",size:f?"default":"sm",className:P(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{W()},children:[l.jsx(F,{name:"history",className:"h-4 w-4"}),"Revert"]}),l.jsxs(Me,{type:"button",variant:"outline",size:f?"default":"sm",className:P(f&&"w-full justify-center h-11 text-base"),disabled:S,onClick:()=>{B()},children:[l.jsx(F,{name:"git-branch",className:"h-4 w-4"}),"Fork"]})]})]})})},qq=e=>e.open?l.jsx(Uq,{...e}):null;function Zq(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 Wq=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},Gq=(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"}},Hl=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)},Kq=({sessionId:e,turnIds:t,activeTurnId:n,scrollToTurn:r,scrollToMessage:s,resumeToBottom:o})=>{const i=h.useRef(t),a=h.useRef(n);h.useEffect(()=>{i.current=t},[t]),h.useEffect(()=>{a.current=n},[n]);const c=h.useCallback(async(p,m)=>p?(m?.updateHash!==!1&&Hl(`turn-${p}`),r(p,{behavior:m?.behavior})):!1,[r]),d=h.useCallback(async(p,m)=>p?(m?.updateHash!==!1&&Hl(`message-${p}`),s(p,{behavior:m?.behavior})):!1,[s]),f=h.useCallback(async(p,m)=>{const g=i.current,b=Gq(g,a.current,p);if(b.kind==="noop")return p===0;if(b.kind==="resume"){if(m?.resumePastEnd===!1){const y=g[g.length-1];return y?c(y,{behavior:"auto"}):!1}return Hl(null),o(),!0}return c(b.turnId,{behavior:"auto"})},[o,c]),u=h.useCallback(()=>{Hl(null),o()},[o]);return h.useEffect(()=>{if(!e||typeof window>"u")return;const p=()=>{const m=Wq(window.location.hash);if(m){if(m.kind==="turn"){c(m.id,{behavior:"auto",updateHash:!1});return}d(m.id,{behavior:"auto",updateHash:!1})}};return p(),window.addEventListener("hashchange",p),()=>{window.removeEventListener("hashchange",p)}},[e,d,c,t.length]),{scrollToTurnId:c,scrollToMessageId:d,scrollByTurnOffset:f,resumeToLatest:u}},Yq=[],Xq={type:"idle"},z5="pichamber:chat-force-scroll-bottom",Jq="Quota limit reached. Retrying automatically.",Qq={overflowAnchor:"none",overscrollBehavior:"contain",overscrollBehaviorY:"contain"},qf=e=>P("relative z-10 flex flex-col gap-2 bg-background",e?"flex-1 min-h-0":"shrink-0"),eZ=["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(","),tZ=e=>e instanceof HTMLElement,a1=e=>tZ(e)?!!e.closest(eZ):!1,nZ=(e,t)=>typeof document>"u"||!e||e===document.body||e===document.documentElement||a1(e)?!0:!t?.contains(e),rZ=()=>{const{isCommandPaletteOpen:e,isHelpDialogOpen:t,isImagePreviewOpen:n,isSessionSwitcherOpen:r,isSettingsDialogOpen:s}=ne.getState();return e||t||n||r||s},sZ=(e,t)=>{if(!t)return e;const n=e.indexOf(t);return n===-1?e:l.jsxs(l.Fragment,{children:[e.slice(0,n),l.jsx("span",{className:"font-medium",children:t}),e.slice(n+t.length)]})},U5=()=>{const e=pe(n=>n.newSessionDraft.selectedProjectId??null),t=it(h.useCallback(n=>CT({selectedProjectId:e,activeProjectId:n.activeProjectId,projects:n.projects}),[e]));return l.jsxs("div",{className:"oc-draft-center flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center",children:[l.jsx("h1",{className:"text-balance text-3xl font-normal tracking-tight text-foreground",children:sZ(t?`What are we working on in ${t}?`:"What are we working on?",t)}),l.jsx(jb,{onInsert:n=>{n.ref.type==="text"?Ke.getState().requestStarterTextInsert(n.insertText):Ke.getState().requestStarterInsert(n.promptName)},className:"oc-draft-starters mt-8 max-w-md"})]})},bw=h.memo(()=>{const e=pe(c=>c.currentSessionId),t=pe(h.useCallback(c=>e?c.sessionAbortFlags?.get(e)??null:null,[e])),{activeModel:n,working:r}=Y4(),s=ox(e??""),o=Ze(c=>c.providers),i=h.useMemo(()=>{if(!n)return null;const c=o.length>0?o.find(d=>d.id===n.providerId):void 0;return Em(c,n.modelId)||null},[n,o]),a=!!(t&&!t.acknowledged);return l.jsx(ib,{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})});bw.displayName="StatusRowContainer";const oZ=160,Zf=28,iZ=12,yi=6,aZ=8,vi=30,xi=12,q5=18,lZ=80,Fl=4,cZ=10,dZ=14,uZ=20,Jt=54,Z5=4,fZ=8,W5=2,hZ=160,pZ=(e,t)=>e.map(n=>{const r=t.get(n)??[];return{turnId:n,preview:xw(r,oZ)}}),mZ=[1,.6,.35,.15],gZ=(e,t,n)=>{const r=n?dZ:cZ;if(t===null)return r;const s=Math.abs(e-t),o=mZ[s]??0;return Math.round(r+(uZ-r)*o)};function yZ({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:s,isLoadingOlder:o,onLoadEarlier:i}){const a=ne(ee=>ee.isPromptNavigatorPanelOpen),c=ne(ee=>ee.setPromptNavigatorPanelOpen),d=h.useRef(null),f=h.useRef(null),[u,p]=h.useState(null),[m,g]=h.useState(0),[b,y]=h.useState(!1),[S,v]=h.useState(yi);h.useEffect(()=>{const ee=f.current?.parentElement;if(!ee||typeof ResizeObserver>"u")return;const oe=()=>{const Ue=ee.querySelector(".chat-message-column");if(!Ue){y(!1),v(yi);return}const dt=ee.getBoundingClientRect(),Lt=Ue.getBoundingClientRect(),zt=dt.right-Lt.right-aZ-Zf;if(zt<=yi){v(yi);const ws=dt.right-yi-Zf;y(Lt.right>ws);return}v(zt),y(!1)};oe();const he=new ResizeObserver(oe);he.observe(ee);const Le=ee.querySelector(".chat-message-column");return Le&&he.observe(Le),()=>he.disconnect()},[e.length]);const x=h.useMemo(()=>pZ(e,t),[t,e]),k=Math.min(x.length,vi),w=Math.max(0,x.length-k),C=Math.min(m,w),I=C+k,_=C>0,E=I<x.length,M="[No text content]",T="Current prompt",A="Load more prompts",j=h.useMemo(()=>n?x.findIndex(ee=>ee.turnId===n):-1,[n,x]),R=h.useRef(C);R.current=C;const O=h.useRef(x.length);O.current=x.length;const N=h.useRef(null),D=h.useRef(null),K=h.useRef(0),V=h.useCallback(ee=>{g(oe=>{const he=O.current,Le=Math.min(he,vi),Ue=Math.max(0,he-Le),dt=Math.min(oe,Ue);return ee<dt?ee:ee>=dt+Le?Math.min(Ue,ee-Le+1):dt})},[]),W=h.useRef(x[0]?.turnId),B=h.useRef(x.length);h.useLayoutEffect(()=>{const ee=W.current,oe=B.current,he=x.length-oe;he>0&&oe>0&&ee&&x[0]?.turnId!==ee&&(g(Le=>Le+he),p(Le=>Le===null?null:Le+he)),W.current=x[0]?.turnId,B.current=x.length},[x]),h.useEffect(()=>{if(u!==null)return;const ee=j>=0?j:x.length-1;g(()=>{const oe=O.current,he=Math.min(oe,vi),Le=Math.max(0,oe-he);return Math.max(0,Math.min(Le,ee-Math.floor(he/2)))})},[j,u,x.length]);const Z=h.useCallback(ee=>{const oe=d.current;if(!oe)return null;const he=oe.getBoundingClientRect(),Le=Math.floor((ee-he.top)/xi),Ue=Math.min(O.current,vi);return Ue===0?null:Math.max(0,Math.min(Ue-1,Le))},[]),L=h.useCallback(()=>{K.current=0,D.current!==null&&(window.clearInterval(D.current),D.current=null)},[]),$=h.useCallback(()=>{const ee=K.current;if(ee===0){L();return}const oe=O.current,he=Math.min(oe,vi),Le=Math.max(0,oe-he),Ue=Math.min(R.current,Le),dt=Math.max(0,Math.min(Le,Ue+ee));if(dt===Ue){L();return}R.current=dt,g(dt);const Lt=N.current;if(Lt!==null){const zt=Z(Lt);zt!==null&&p(Math.min(oe-1,dt+zt))}},[Z,L]),G=h.useCallback(ee=>{const oe=d.current;if(!oe)return;const he=oe.getBoundingClientRect(),Le=ee-he.top;let Ue=0;if(Le<=q5&&_?Ue=-1:Le>=he.height-q5&&E&&(Ue=1),K.current=Ue,Ue===0){L();return}D.current===null&&(D.current=window.setInterval($,lZ))},[$,_,E,L]);h.useEffect(()=>()=>{D.current!==null&&window.clearInterval(D.current)},[]);const Q=h.useRef(null),z=h.useCallback(()=>{Q.current!==null&&(window.clearTimeout(Q.current),Q.current=null)},[]),X=h.useCallback(()=>{z(),Q.current=window.setTimeout(()=>{Q.current=null,p(null)},hZ)},[z]);h.useEffect(()=>()=>{Q.current!==null&&window.clearTimeout(Q.current)},[]);const Y=h.useCallback(ee=>{z(),N.current=ee.clientY;const oe=Z(ee.clientY);oe!==null&&p(Math.min(O.current-1,R.current+oe)),G(ee.clientY)},[z,Z,G]),ce=h.useCallback(()=>{N.current=null,L(),X()},[X,L]),se=h.useCallback(()=>{c(!1)},[c]),ue=h.useCallback(ee=>{if(ee===null)return;const oe=x[ee];oe&&(r(oe.turnId),L(),p(null),se(),d.current?.blur())},[se,r,x,L]),Ie=h.useCallback(ee=>{const oe=Z(ee.clientY);oe!==null&&ue(Math.min(x.length-1,R.current+oe))},[ue,x.length,Z]);h.useEffect(()=>{if(!a)return;const ee=d.current;!ee||ee===document.activeElement||(ee.focus(),p(oe=>{if(oe!==null)return oe;const he=j>=0?j:x.length-1;return V(he),he}))},[j,V,a,x.length]),h.useEffect(()=>()=>{c(!1)},[c]);const de=h.useCallback(ee=>{if(x.length===0)return;const oe=u??(j>=0?j:x.length-1),he=Le=>{const Ue=Math.max(0,Math.min(x.length-1,Le));V(Ue),p(Ue)};if(ee.key==="ArrowUp"||ee.key==="ArrowDown"){ee.preventDefault(),he(oe+(ee.key==="ArrowUp"?-1:1));return}if(ee.key==="Home"){ee.preventDefault(),he(0);return}if(ee.key==="End"){ee.preventDefault(),he(x.length-1);return}if(ee.key==="Enter"||ee.key===" "){ee.preventDefault(),ue(oe);return}ee.key==="Escape"&&(ee.preventDefault(),p(null),se(),d.current?.blur())},[j,se,V,ue,u,x]),Fe=h.useCallback(()=>{L(),p(null),se()},[se,L]),$e=h.useRef(null),Xe=h.useRef(u);Xe.current=u;const We=u!==null,Ae=h.useRef(0);h.useEffect(()=>{const ee=$e.current;if(!ee)return;const oe=he=>{he.preventDefault(),he.stopPropagation(),Ae.current+=he.deltaY;const Le=Math.trunc(Ae.current/Jt);if(Le===0)return;Ae.current-=Le*Jt;const Ue=Xe.current;if(Ue===null)return;const dt=Math.max(0,Math.min(O.current-1,Ue+Le));dt!==Ue&&(V(dt),p(dt))};return ee.addEventListener("wheel",oe,{passive:!1}),()=>ee.removeEventListener("wheel",oe)},[V,We]);const be=u!==null?x[u]:void 0,te=Math.min(x.length,fZ),ve=te*Jt,we=x.length*Jt-ve,je=ee=>Math.max(0,Math.min(we,ee)),Ce=h.useRef(null);let ze=0;if(u===null)Ce.current=null;else if(Ce.current===null)ze=je(u*Jt-(ve-Jt)/2),Ce.current=ze;else{let ee=Ce.current;const oe=(u-W5)*Jt,he=(u+1+W5)*Jt-ve;ee>oe?ee=oe:ee<he&&(ee=he),ze=je(ee),Ce.current=ze}const ht=Math.floor(ze/Jt),xe=Math.max(0,ht-Fl),re=Math.min(x.length,ht+te+Fl),me=ze>0,fe=ze<we,Se=me||fe?`linear-gradient(to bottom, ${me?"transparent, black 10%":"black"}, ${fe?"black 90%, transparent":"black"})`:void 0,_e=Math.max(0,C-Fl),Ee=Math.min(x.length,I+Fl),ye=x.slice(_e,Ee),ie=_||E?`linear-gradient(to bottom, ${_?"transparent, black 14%":"black"}, ${E?"black 86%, transparent":"black"})`:void 0;return x.length===0?null:l.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:l.jsxs("div",{className:"pointer-events-auto flex flex-col items-end",children:[s?l.jsx("button",{type:"button",tabIndex:-1,className:P("-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":A,title:A,disabled:o,onClick:ee=>{ee.stopPropagation(),o||i()},children:o?l.jsx(F,{name:"loader-4",className:"size-3.5 animate-spin"}):l.jsx(F,{name:"arrow-up-s",className:"size-3.5"})}):null,l.jsxs("div",{ref:d,role:"listbox",tabIndex:-1,"aria-activedescendant":be?`prompt-rail-tick-${be.turnId}`:void 0,className:"relative cursor-pointer outline-none",style:{width:`${b?iZ:Zf}px`,height:`${k*xi}px`},onMouseMove:Y,onMouseLeave:ce,onClick:Ie,onKeyDown:de,onBlur:Fe,children:[l.jsx("div",{className:"absolute inset-0 overflow-hidden",style:ie?{maskImage:ie,WebkitMaskImage:ie}:void 0,children:l.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-300 ease-out",style:{transform:`translateY(-${C*xi}px)`},children:ye.map((ee,oe)=>{const he=_e+oe,Le=ee.turnId===n,Ue=u===he,dt=gZ(he,u,Le);return l.jsx("div",{id:`prompt-rail-tick-${ee.turnId}`,role:"option","aria-selected":Ue,"aria-current":Le?"true":void 0,"aria-label":ee.preview.trim()||M,className:"pointer-events-none absolute right-1 flex items-center justify-end",style:{top:`${he*xi}px`,height:`${xi}px`},children:l.jsx("span",{"aria-hidden":"true",className:P("block h-0.5 rounded-full transition-all duration-200 ease-out",Le?"bg-[var(--surface-foreground)]":Ue?"bg-[var(--surface-foreground)]/80":"bg-[var(--surface-foreground)]/30"),style:{width:`${dt}px`}})},ee.turnId)})},x[0]?.turnId)}),be&&u!==null?l.jsx("div",{ref:$e,className:P("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:z,onMouseLeave:X,onMouseMove:ee=>ee.stopPropagation(),onClick:ee=>ee.stopPropagation(),children:l.jsx("div",{className:"relative overflow-hidden",style:{height:`${te*Jt}px`,maskImage:Se,WebkitMaskImage:Se},children:l.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-200 ease-out",style:{height:`${x.length*Jt}px`,transform:`translateY(-${ze}px)`},children:x.slice(xe,re).map((ee,oe)=>{const he=xe+oe,Le=ee.turnId===n,Ue=u===he;return l.jsx("div",{role:"option","aria-selected":Ue,"aria-current":Le?"true":void 0,title:Le?T:void 0,className:"absolute inset-x-0 cursor-pointer px-1.5",style:{top:`${he*Jt+Z5}px`,height:`${Jt-Z5*2}px`},onMouseMove:()=>{z(),Xe.current!==he&&(V(he),p(he))},onClick:()=>ue(he),children:l.jsx("div",{className:P("flex h-full items-center rounded-lg border px-2 transition-colors",Le?"border-transparent bg-[var(--interactive-selection)]":Ue?"border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]":"border-[var(--interactive-border)]/40"),children:l.jsx("span",{className:P("min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] typography-meta",Le?"text-[var(--interactive-selectionForeground)]":"text-[var(--surface-mutedForeground)]"),children:ee.preview.trim()||M})})},ee.turnId)})})})}):null]})]})})}const ww=h.memo(({currentSessionId:e,currentSessionKey:t,isDesktopExpandedInput:n,isMobile:r,directory:s,scrollRef:o,messageListRef:i,pendingRevealWork:a,renderedMessages:c,isLoadingOlder:d,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:p,streamingMessageId:m,activeStreamingPhase:g,retryOverlay:b,compactionOverlay:y,handleMessageContentChange:S,getAnimationHandlers:v,handleHistoryScroll:x,scrollToBottom:k,isProgrammaticFollowActive:w,showLoadOlderButton:C,onLoadOlder:I,turnIds:_,activeTurnId:E,onSelectTurn:M,showPromptNavigator:T,canLoadEarlierPrompts:A,isLoadingOlderPrompts:j,onLoadEarlierPrompts:R})=>{const O=h.useRef(new Map),N=h.useRef(new WeakMap),D=h.useRef(new Map),K=h.useRef(e);K.current!==e&&(K.current=e,D.current.clear());const V=h.useMemo(()=>{const L=new Map;for(let G=0;G<c.length;G+=1){const Q=c[G];if(Q.info.role!=="user")continue;if(n4(Q)){const X=cF(c,G)??"",Y=D.current.get(Q.info.id);if(Y&&Y.command===X)L.set(Q.info.id,Y.parts);else{const ce=[{type:"text",text:X?`$ ${X}`:"/shell"}];D.current.set(Q.info.id,{command:X,parts:ce}),L.set(Q.info.id,ce)}continue}if(F$(Q.parts))continue;let z=N.current.get(Q.parts);z||(z=r1(Q.parts),N.current.set(Q.parts,z)),z.length!==0&&L.set(Q.info.id,z)}const $=O.current;if($.size===L.size){let G=!0;for(const[Q,z]of L)if($.get(Q)!==z){G=!1;break}if(G)return $}return O.current=L,L},[c]),W=h.useMemo(()=>_.filter(L=>V.has(L)),[V,_]),B=h.useMemo(()=>{if(!E||V.has(E))return E;const L=_.indexOf(E);for(let $=L-1;$>=0;$-=1){const G=_[$];if(V.has(G))return G}return null},[E,V,_]),Z=h.useCallback(L=>{L.defaultPrevented||a1(L.target)||typeof window<"u"&&window.getSelection()?.type==="Range"||o.current?.focus({preventScroll:!0})},[o]);return l.jsx("div",{className:P("relative min-h-0",n?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":n,children:l.jsxs("div",{className:"absolute inset-0",children:[l.jsx(Fd,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:o,style:Qq,observeMutations:!1,hideTopShadow:!1,tabIndex:0,onClick:Z,onScroll:x,"data-scroll-shadow":"true","data-scrollbar":"chat",children:l.jsxs("div",{className:"relative z-0 min-h-full",children:[C&&l.jsx("div",{className:"flex justify-center pt-3 pb-1",children:l.jsxs(Me,{variant:"secondary",size:"sm",onClick:I,disabled:d,children:[d&&l.jsx(F,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),l.jsx(sq,{ref:i,sessionKey:e,disableStaging:a,messages:c,sessionIsWorking:f,sessionAwaitingRecovery:u,awaitingPromptEcho:p,activeStreamingMessageId:m,activeStreamingPhase:g,retryOverlay:b,compactionOverlay:y,onMessageContentChange:S,getAnimationHandlers:v,isLoadingOlder:d,scrollToBottom:k,scrollRef:o,directory:s},t),_.length===0&&f?l.jsx("div",{className:"mb-3",children:l.jsx(bw,{})}):_.length===0&&u?l.jsx("div",{className:"chat-message-column mb-3",children:l.jsx("span",{className:"typography-markdown leading-5 text-muted-foreground",role:"status","data-turn-reconnecting":"true",children:"Reconnecting · last seen working"})}):null,l.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"})]})}),l.jsx(f3,{containerRef:o,suppressVisibility:w,userIntentOnly:!0,observeMutations:!1}),T&&W.length>=2?l.jsx(yZ,{turnIds:W,previewsByTurnId:V,activeTurnId:B,onSelectTurn:M,canLoadEarlier:A,isLoadingOlder:j,onLoadEarlier:R}):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);ww.displayName="ChatViewport";const vZ={isWorking:!1,isAwaitingRecovery:!1},PG=({active:e=!0,autoOpenDraft:t=!0})=>{const n=pe(oe=>oe.currentSessionId),r=pe(oe=>oe.currentSessionDirectory),s=pe(oe=>oe.openNewSessionDraft),o=pe(oe=>oe.newSessionDraft),i=pe(oe=>oe.sendingNewSessionDraftId),a=qx(o,n,i),c=eb(),d=IM(),f=r??d,u=n?JSON.stringify([J(),f,n]):null,p=h.useCallback(oe=>c.ensureSessionRenderable(oe),[c]),m=h.useCallback(async()=>{},[]),g=ne(oe=>oe.isExpandedInput),b=ne(oe=>oe.isTimelineDialogOpen),y=ne(oe=>oe.setTimelineDialogOpen),S=Bx(),v=yb(),x=jM(n??""),w=S==="ready"&&!v?x:null,C=w?"streaming":null,I=LM(n??""),_=zx(n??""),E=Id(n??""),M=n?E:Yq,T=_M(n??""),[A]=h.useState(FE);h.useEffect(()=>{if(!(!e||!u||!_||M.length===0))return A.schedule(u,M.length)},[e,u,A,_,M.length]);const j=Md(n??"")??Xq,R=h.useMemo(()=>{if(!n)return vZ;const oe=j.type??"idle",he=M[M.length-1]?.info,Le=typeof he?.finish=="string"?he.finish:void 0,Ue=!!(he&&he.role==="assistant"&&typeof he.time?.completed!="number"&&Le!=="stop"&&Le!=="error");return Bj({connection:S,transportUncertain:v,authoritativeWorking:oe==="busy"||oe==="retry",hasPendingAssistant:Ue,hasRetainedStream:!!x})},[S,n,x,M,j.type,v]),O=R.isWorking,N=R.isAwaitingRecovery,D=TM(n??""),K=h.useMemo(()=>{if(!n||j.type!=="retry")return null;const oe=typeof j.message=="string"?(j.message??"").trim():"";return{sessionId:n,message:oe||Jq,confirmedAt:j.confirmedAt}},[n,j]),V=kM(n??""),W=h.useMemo(()=>n&&V?{sessionId:n,compaction:V}:null,[V,n]),[B,Z]=h.useState(0),L=h.useRef(null);h.useEffect(()=>{if(!K||typeof K.confirmedAt=="number"){L.current=null,Z(0);return}L.current!==K.sessionId&&(L.current=K.sessionId,Z(Date.now()))},[K]);const $=h.useMemo(()=>K?{...K,fallbackTimestamp:B}:null,[K,B]),G=h.useMemo(()=>n?{limit:M.length,complete:T.complete||!T.cursor,loading:T.status==="loading"}:null,[n,T.complete,T.cursor,T.status,M.length]),{isMobile:Q}=Pr(),z=zd(),X=!!o?.open,Y=Q&&g,ce=Q||z==="mini-chat",se=h.useRef(null);h.useEffect(()=>{Nx().sessionId||t&&!n&&!X&&s({automatic:!0})},[t,n,X,s]);const ue=h.useRef(()=>{}),Ie=h.useCallback(oe=>{ue.current(oe)},[]),{scrollRef:de,notifyContentChange:Fe,getAnimationHandlers:$e,goToBottom:Xe,scrollToBottomOnSend:We,releaseAutoFollow:Ae,restoreSnapshot:be,isPinned:te,isFollowingProgrammatically:ve,showScrollButton:we}=kq({currentSessionId:n,currentSessionKey:u,sessionMessageCount:I,sessionIsWorking:O,isMobile:Q,onActiveTurnChange:Ie}),Ce=zq({sessionId:n,sessionKey:u,messages:M,historyMeta:G,scrollRef:de,messageListRef:se,loadMoreMessages:m,goToBottom:Xe,releaseAutoFollow:Ae,isPinned:te,showScrollButton:we}),ze=h.useCallback(()=>{Xe("instant")},[Xe]),ht=nn()&&Ce.historySignals.canLoadEarlier,xe=Ce.loadEarlier,re=h.useCallback(()=>{xe({userInitiated:!0})},[xe]);h.useEffect(()=>{ue.current=Ce.handleActiveTurnChange},[Ce.handleActiveTurnChange]);const me=Kq({sessionId:n,turnIds:Ce.turnIds,activeTurnId:Ce.activeTurnId,scrollToTurn:Ce.scrollToTurn,scrollToMessage:Ce.scrollToMessage,resumeToBottom:Ce.resumeToBottomInstant}),fe=h.useCallback(oe=>{me.scrollToTurnId(oe,{behavior:"smooth"})},[me]),Se=Ce.historySignals.canLoadEarlier,_e=!Q&&!Y&&Ce.turnIds.length>=2;h.useEffect(()=>{_e||ne.getState().setPromptNavigatorPanelOpen(!1)},[_e]),h.useEffect(()=>{if(typeof window>"u"||!n)return;const oe=he=>{const Le=he;Le.detail?.sessionId&&Le.detail.sessionId!==n||Xe("instant")};return window.addEventListener(z5,oe),()=>{window.removeEventListener(z5,oe)}},[n,Xe]),h.useEffect(()=>{if(typeof window>"u"||!n||Y)return;const oe=he=>{if(he.defaultPrevented||he.isComposing||he.key!=="ArrowUp"&&he.key!=="ArrowDown"||he.altKey||he.ctrlKey||he.metaKey||he.shiftKey)return;const{activeMainTab:Le}=ne.getState();if(Le!=="chat"||rZ())return;const Ue=de.current;if(nZ(document.activeElement,Ue)||a1(he.target))return;he.preventDefault();const dt=he.key==="ArrowUp"?-1:1;me.scrollByTurnOffset(dt,{resumePastEnd:!1})};return window.addEventListener("keydown",oe),()=>{window.removeEventListener("keydown",oe)}},[n,Y,me,de]),h.useLayoutEffect(()=>{const oe=de.current;if(!oe)return;const he=()=>{oe.style.setProperty("--chat-scroll-height",`${oe.clientHeight}px`)};he();let Le=0;const Ue=()=>{Le||(Le=requestAnimationFrame(()=>{Le=0,he()}))};if(typeof ResizeObserver>"u")return window.addEventListener("resize",Ue),()=>{Le&&cancelAnimationFrame(Le),window.removeEventListener("resize",Ue)};const dt=new ResizeObserver(Ue);return dt.observe(oe),()=>{Le&&cancelAnimationFrame(Le),dt.disconnect()}},[n,Y,de]);const Ee=h.useRef(null),ie=!!n&&(!!n&&!_||T.status==="loading"),ee=h.useCallback(()=>{!e||!n||c.ensureSessionRenderable(n)},[e,n,c]);return h.useEffect(()=>{if(!e||!n||Ee.current===u)return;const oe=typeof window<"u"&&window.location.hash.length>0;if(Ee.current=u,oe){Ae();return}const he=()=>{be()};typeof window>"u"?he():window.requestAnimationFrame(he)},[e,n,u,Ae,be]),h.useEffect(()=>{!e||!n||_||p(n)},[e,n,p,_]),!n&&!X?t?l.jsx("div",{className:"flex h-full flex-col bg-background"}):l.jsx("div",{className:"flex flex-col h-full bg-background",children:l.jsx(eF,{isNewSession:!0})}):!n&&X?l.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:[ce&&!Y?l.jsx(U5,{}):null,l.jsx("div",{className:P("relative z-10 flex min-h-0",Y?"flex-1 bg-background":ce?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:l.jsx(pi,{scrollToBottom:We})})]}):n?ie?T.status==="error"?l.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:[l.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center px-6",children:l.jsxs("div",{className:"max-w-sm text-center",children:[l.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:l.jsx(F,{name:"error-warning",className:"size-4"})}),l.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:T.errorCode==="SESSION_IN_USE"?"Session is open elsewhere":"Session could not be loaded"}),l.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:T.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."}),l.jsx(Me,{variant:"outline",size:"sm",className:"mt-4",onClick:ee,children:"Try again"})]})}),l.jsx("div",{className:qf(!1),children:l.jsx(pi,{scrollToBottom:We})})]}):l.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:[l.jsx("div",{className:P("relative min-h-0 flex items-center justify-center",Y?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":Y,children:l.jsxs("div",{className:"flex flex-col items-center gap-3",children:[l.jsx(cm,{width:120,height:120,isAnimated:!0}),a?l.jsx("p",{role:"status",className:"typography-meta animate-pulse text-muted-foreground",children:"Creating session…"}):null]})}),l.jsx("div",{className:qf(Y),children:l.jsx(pi,{scrollToBottom:We})})]}):M.length===0&&!O&&!N?l.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:[ce&&!Y?l.jsx(U5,{}):null,l.jsx("div",{className:P("relative z-10 flex min-h-0",Y?"flex-1 bg-background":ce?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:l.jsxs("div",{className:"flex w-full min-w-0 flex-col gap-2",children:[l.jsx(Cy,{sessionId:n}),l.jsx(ky,{sessionId:n}),l.jsx(pi,{scrollToBottom:We})]})}),l.jsx(My,{sessionId:n})]}):l.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:[l.jsx(ww,{currentSessionId:n,currentSessionKey:u??n,isDesktopExpandedInput:Y,isMobile:Q,directory:f,scrollRef:de,messageListRef:se,pendingRevealWork:Ce.pendingRevealWork,renderedMessages:Ce.renderedMessages,isLoadingOlder:Ce.isLoadingOlder,sessionIsWorking:O,sessionAwaitingRecovery:N,awaitingPromptEcho:D,streamingMessageId:w,activeStreamingPhase:C,retryOverlay:$,compactionOverlay:W,handleMessageContentChange:Fe,getAnimationHandlers:$e,handleHistoryScroll:Ce.handleHistoryScroll,scrollToBottom:ze,isProgrammaticFollowActive:ve,showLoadOlderButton:ht,onLoadOlder:re,turnIds:Ce.turnIds,activeTurnId:Ce.activeTurnId,onSelectTurn:fe,showPromptNavigator:_e,canLoadEarlierPrompts:Se,isLoadingOlderPrompts:Ce.isLoadingOlder,onLoadEarlierPrompts:re}),l.jsxs("div",{className:qf(Y),children:[!Y&&M.length>0&&l.jsx(iq,{visible:Ce.showScrollToBottom,onClick:me.resumeToLatest}),l.jsx(JH,{sessionId:n}),l.jsx(Cy,{sessionId:n}),l.jsx(ky,{sessionId:n}),l.jsx(pi,{scrollToBottom:We})]}),l.jsx(My,{sessionId:n}),l.jsx(qq,{open:b,onOpenChange:y,onScrollToMessage:Ce.scrollToMessage,onScrollByTurnOffset:me.scrollByTurnOffset,onResumeToLatest:ze,canLoadEarlier:Ce.historySignals.canLoadEarlier,isLoadingEarlier:Ce.isLoadingOlder,onLoadEarlier:re,onRevert:async oe=>{if(!n)return;const he=oe.includes(":")?oe.split(":")[0]??oe:oe;await pe.getState().revertToMessage(n,he)},onFork:async oe=>{if(!n)return;const he=oe.includes(":")?oe.split(":")[0]??oe:oe;await pe.getState().forkFromMessage(n,he)}})]}):null},xZ=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(100,Math.round(e))),bZ=e=>e>=90?"critical":e>=75?"warn":"safe",DG=({percentage:e,size:t=18,stroke:n=3,className:r})=>{const s=xZ(e),o=bZ(e),i=o==="critical"?"var(--status-error)":o==="warn"?"var(--status-warning)":"var(--status-success)",a=(t-n)/2,c=2*Math.PI*a;return l.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:[l.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:"var(--interactive-border)",strokeWidth:n}),l.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",stroke:i,strokeWidth:n,strokeLinecap:"round",strokeDasharray:c,strokeDashoffset:c*(1-s/100),className:"transition-[stroke-dashoffset,stroke] duration-300"})]})},wZ=()=>{const e=ne(n=>n.uiFont),t=ne(n=>n.monoFont);return{uiFont:e,monoFont:t}},OG=h.memo(function({visible:t}){const[n,r]=h.useState(!1);if(U.useEffect(()=>{if(!t)return;let o=!1;Qn("desktop_get_current_window_state").then(a=>{o||r(!!a?.maximized)}).catch(()=>{});const i=a=>{const c=a.detail;r(!!c?.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 l.jsxs("div",{className:"app-region-no-drag ml-1 flex h-12 shrink-0 items-center","aria-label":"Window controls",children:[l.jsx("button",{type:"button",className:s,onClick:()=>{Qn("desktop_minimize_current_window")},title:"Minimize window","aria-label":"Minimize window",children:l.jsx(F,{name:"subtract",className:"h-4 w-4"})}),l.jsx("button",{type:"button",className:s,onClick:()=>{Qn("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:l.jsx(F,{name:n?"fullscreen-exit":"checkbox-blank",className:"h-3.5 w-3.5"})}),l.jsx("button",{type:"button",className:P(s,"hover:bg-status-error hover:text-status-error-foreground"),onClick:()=>{Qn("desktop_close_current_window")},title:"Close window","aria-label":"Close window",children:l.jsx(F,{name:"close",className:"h-4 w-4"})})]})}),G5=new Set,Wf=new Map,SZ=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace("%40","@").replace("%2F","/")}/files/${e.filePrefix}-latin-${t}-normal.woff2`,CZ=(e,t)=>{const n=`${e.family}:${t}`;if(G5.has(n))return Promise.resolve();const r=Wf.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(${SZ(e,t)}) format('woff2')`,{style:"normal",weight:String(t),display:"swap"});document.fonts.add(s);const o=s.load().then(()=>{G5.add(n)}).catch(i=>{document.fonts.delete(s),console.warn(`Failed to load font: ${e.family} ${t}`,i)}).finally(()=>{Wf.delete(n)});return Wf.set(n,o),o},Sw=e=>e?Promise.all(e.weights.map(t=>CZ(e,t))).then(()=>{}):Promise.resolve(),kZ=e=>Sw(Yf[e]?.source),MZ=e=>Sw(Xf[e]?.source);function HG(){const{uiFont:e,monoFont:t}=wZ();h.useEffect(()=>{if(typeof document>"u")return;const n=document.documentElement,r=Yf[e]?.stack??Yf[i9].stack,s=Xf[t]?.stack??Xf[a9].stack;kZ(e),MZ(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{kW as $,Sa as A,Me as B,hm as C,OW as D,CW as E,Wj as F,jd as G,dW as H,F as I,pM as J,rm as K,WW as L,wZ as M,kZ as N,Ze as O,cm as P,yb as Q,KW as R,b_ as S,JZ as T,QZ as U,kh as V,Dj as W,iM as X,HG as Y,J2 as Z,tW as _,it as a,FR as a$,RW as a0,AW as a1,LW as a2,NW as a3,IE as a4,FW as a5,MW as a6,IW as a7,fW as a8,Ed as a9,Vn as aA,$m as aB,$x as aC,Id as aD,sd as aE,td as aF,RG as aG,xs as aH,Bd as aI,df as aJ,ZH as aK,DW as aL,PW as aM,yt as aN,_t as aO,qe as aP,Gj as aQ,Zj as aR,DG as aS,SM as aT,$Z as aU,VO as aV,Vd as aW,qZ as aX,SR as aY,HR as aZ,vb as a_,aW as aa,wW as ab,lW as ac,uW as ad,Pr as ae,Ke as af,Xx as ag,rr as ah,Pd as ai,pt as aj,mt as ak,Dd as al,gt as am,Od as an,ir as ao,Qs as ap,t_ as aq,mR as ar,Io as as,Fn as at,Td as au,Ad as av,Ld as aw,Nd as ax,im as ay,BI as az,tC as b,zZ as b$,VR as b0,BR as b1,$R as b2,XW as b3,Sr as b4,Yx as b5,fa as b6,en as b7,TW as b8,XZ as b9,UZ as bA,Vx as bB,am as bC,KI as bD,XI as bE,bR as bF,uh as bG,EH as bH,iG as bI,A3 as bJ,WZ as bK,rn as bL,Hn as bM,S3 as bN,Ia as bO,CR as bP,T_ as bQ,cW as bR,DZ as bS,eb as bT,Yp as bU,OZ as bV,OG as bW,Cr as bX,fc as bY,N8 as bZ,kr as b_,YZ as ba,Nx as bb,ka as bc,C2 as bd,hE as be,pE as bf,mE as bg,gE as bh,PG as bi,nG as bj,rG as bk,cN as bl,_m as bm,Eo as bn,AA as bo,lN as bp,Zv as bq,EW as br,vj as bs,_W as bt,gj as bu,jW as bv,vk as bw,dh as bx,Jj as by,zp as bz,oa as c,n_ as c$,FZ as c0,sG as c1,DR as c2,xZ as c3,bZ as c4,tm as c5,fo as c6,eT as c7,mA as c8,KZ as c9,$W as cA,zW as cB,UW as cC,FF as cD,qW as cE,YW as cF,cb as cG,QI as cH,e_ as cI,t0 as cJ,r0 as cK,n0 as cL,s0 as cM,o0 as cN,f3 as cO,gR as cP,yR as cQ,vR as cR,kR as cS,MR as cT,Xj as cU,er as cV,hW as cW,pW as cX,mW as cY,gW as cZ,r_ as c_,aa as ca,zk as cb,JM as cc,tI as cd,Ax as ce,GZ as cf,oW as cg,Qp as ch,gG as ci,SW as cj,nE as ck,sE as cl,ER as cm,Bt as cn,$d as co,VF as cp,Ef as cq,_a as cr,yB as cs,Xm as ct,_G as cu,Fd as cv,$3 as cw,B3 as cx,BW as cy,BA as cz,aC as d,jG as d$,l_ as d0,JW as d1,QW as d2,jf as d3,eG as d4,rc as d5,a3 as d6,vW as d7,V_ as d8,M2 as d9,Hy as dA,NG as dB,az as dC,wB as dD,CG as dE,kG as dF,mG as dG,fG as dH,hG as dI,pG as dJ,cG as dK,OB as dL,vG as dM,xG as dN,bG as dO,yG as dP,MG as dQ,uG as dR,SG as dS,wG as dT,IG as dU,aG as dV,lG as dW,EG as dX,HB as dY,t5 as dZ,ZB as d_,I2 as da,ef as db,xW as dc,bW as dd,Y_ as de,C_ as df,S_ as dg,j_ as dh,yW as di,Mm as dj,Tp as dk,fd as dl,Pt as dm,r8 as dn,jv as dp,tG as dq,oP as dr,iP as ds,JT as dt,bz as du,dH as dv,ox as dw,VZ as dx,h4 as dy,mV as dz,fE as e,TG as e0,AG as e1,LG as e2,zB as e3,wV as e4,R4 as e5,dG as e6,uw as e7,GW as e8,HZ as e9,ZZ as ea,iW as eb,HW as ec,VW as ed,ZW as ee,eW as f,Ge as g,pe as h,nW as i,dC as j,rW as k,Mr as l,oG as m,jH as n,Lh as o,BZ as p,_H as q,sm as r,u_ as s,ke as t,gd as u,h3 as v,sW as w,Mo as x,Bn as y,Ca as z};