@pi-chamber/web 1.0.4 → 1.0.5-rc.1

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 (204) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +21 -2
  3. package/bin/cli.test.js +164 -4
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +96 -13
  6. package/bin/lib/commands-connect-url-tailscale.test.js +136 -0
  7. package/bin/lib/commands-connect-url.js +146 -39
  8. package/bin/lib/commands-connect-url.test.js +126 -0
  9. package/bin/lib/commands-serve.js +45 -2
  10. package/bin/lib/commands-status.js +28 -5
  11. package/bin/lib/commands-status.test.js +107 -0
  12. package/bin/lib/commands-tunnel.js +36 -10
  13. package/dist/assets/{DiagramView-BpG1c3Hi.js → DiagramView-D-OSWTbO.js} +1 -1
  14. package/dist/assets/DiffView-BKT-MIH4.js +18 -0
  15. package/dist/assets/{FileSaveConflictDialog-DP7k9a-i.js → FileSaveConflictDialog-DBkVFssC.js} +2 -2
  16. package/dist/assets/FilesView-B7GIuRlh.js +6 -0
  17. package/dist/assets/{GitHubDetailScaffold-UxLAMAOl.js → GitHubDetailScaffold-C9rCZMUT.js} +2 -2
  18. package/dist/assets/{GitHubLinkPicker-Bh9RO1yK.js → GitHubLinkPicker-Bm09hvhJ.js} +1 -1
  19. package/dist/assets/{GitHubListPrimitives-DQyhT5wG.js → GitHubListPrimitives-DlhAlxI6.js} +1 -1
  20. package/dist/assets/{GitView-XBBheKRM.js → GitView-BgqdMb0m.js} +4 -4
  21. package/dist/assets/{IssuesSurface-BA1kpvAJ.js → IssuesSurface-BZXAvt49.js} +3 -3
  22. package/dist/assets/{JsonTreeView-BAaEPL4O.js → JsonTreeView-BKgCQjh_.js} +1 -1
  23. package/dist/assets/{MarkdownRendererImpl-DzgDmUsL.js → MarkdownRendererImpl-BdcyMPw-.js} +1 -1
  24. package/dist/assets/{PatchDiff-BMEUsgXH.js → PatchDiff-2MmWXcGe.js} +1 -1
  25. package/dist/assets/PierreDiffViewer-D1F2WvD0.js +135 -0
  26. package/dist/assets/PullRequestsSurface-CN2z3DFv.js +2 -0
  27. package/dist/assets/SessionSwitcherContent-CCljxAZb.js +1 -0
  28. package/dist/assets/SessionSwitcherDropdown-DtNt3qw4.js +2 -0
  29. package/dist/assets/SessionUnreadDot-B9bHMy5q.js +1 -0
  30. package/dist/assets/SettingsView-DaZVCInW.js +6 -0
  31. package/dist/assets/{SettingsWindow-j0e99YI0.js → SettingsWindow-C-ydfopH.js} +1 -1
  32. package/dist/assets/StickyHorizontalScrollbar-BMITjK4e.js +8 -0
  33. package/dist/assets/{ToolOutputDialog-VlS12Xyq.js → ToolOutputDialog-DJUAx_Oj.js} +4 -4
  34. package/dist/assets/{ToolPartDiffPreview-DdSneZws.js → ToolPartDiffPreview-DFyuJM4c.js} +1 -1
  35. package/dist/assets/{VirtualizedFileDiff-BqiXjvP6.js → VirtualizedFileDiff-BS-af6rn.js} +4 -4
  36. package/dist/assets/{Virtualizer-Cp_cJWbI.js → Virtualizer-DP6HbEeC.js} +1 -1
  37. package/dist/assets/{collapsible-C7oyikVm.js → collapsible-BOcd0lzY.js} +1 -1
  38. package/dist/assets/{computeVirtualFileMetrics-BJjC-tXV.js → computeVirtualFileMetrics-BI6wORhM.js} +1 -1
  39. package/dist/assets/{contextFileOpenGuard-BBzqKGei.js → contextFileOpenGuard-DUMSGR4M.js} +1 -1
  40. package/dist/assets/{gitStatusPredicates-Dq-E5DaH.js → gitStatusPredicates-FdKYDZe3.js} +1 -1
  41. package/dist/assets/{githubLink-Cryd7GkG.js → githubLink-B3-BaGpb.js} +5 -5
  42. package/dist/assets/index-DWSrsQWl.js +11 -0
  43. package/dist/assets/{index-BbhXFTId.js → index-Df-vmvzu.js} +1 -1
  44. package/dist/assets/index-DsQIBAWK.css +1 -0
  45. package/dist/assets/main-61_cd7S7.js +2 -0
  46. package/dist/assets/main-q43jqZ2I.js +136 -0
  47. package/dist/assets/{markdownCore-B9AuEyYi.js → markdownCore-CqHYlXi_.js} +2 -2
  48. package/dist/assets/{miniChat-CgOaJfD8.js → miniChat-vOuWN5pV.js} +2 -2
  49. package/dist/assets/mobile-mrXWV5ky.js +2 -0
  50. package/dist/assets/{nativeFileSave-BzhtrDoD.js → nativeFileSave-CFuugNKV.js} +1 -1
  51. package/dist/assets/pi-session-focus-preference-BEufpwC6.js +9 -0
  52. package/dist/assets/{renderDiffWithHighlighter-CVLsdtQ5.js → renderDiffWithHighlighter-BD9CAhZU.js} +1 -1
  53. package/dist/assets/renderElectronMiniChatApp-QQFXkY5Y.js +2 -0
  54. package/dist/assets/{renderFileWithHighlighter-DJ9mk2bZ.js → renderFileWithHighlighter-KiEWMtzI.js} +1 -1
  55. package/dist/assets/renderMobileApp-DIZYvrhi.js +11 -0
  56. package/dist/assets/runtimeEndpointReset-BA2uP2rj.js +62 -0
  57. package/dist/assets/{runtimeSurface-DBiUWYK2.js → runtimeSurface-Der4qUnI.js} +1 -1
  58. package/dist/assets/useAppFontEffects-Bfw_d5eB.js +212 -0
  59. package/dist/assets/{useFilesViewSearch-D2Au5Xgt.js → useFilesViewSearch-Budwejnx.js} +3 -3
  60. package/dist/assets/useGitHubRemoteSearch-gUdylYy3.js +1 -0
  61. package/dist/assets/{useSwitcherItems-Dej8BzXI.js → useSwitcherItems-yHSMduoo.js} +1 -1
  62. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BYohCVY0.js → vendor-aparajita-capacitor-secure-storage-BDrMx_CE.js} +1 -1
  63. package/dist/assets/{vendor-base-ui-BscvGUFt.js → vendor-base-ui-CKRUCG-f.js} +1 -1
  64. package/dist/assets/{vendor-boot-Dgb9NVFe.js → vendor-boot-EC6IyLt1.js} +13 -13
  65. package/dist/assets/{vendor-capacitor-app-BjdQVib9.js → vendor-capacitor-app-BaupizkW.js} +1 -1
  66. package/dist/assets/{vendor-capacitor-keyboard-eTtI5go3.js → vendor-capacitor-keyboard-9BVxykO7.js} +1 -1
  67. package/dist/assets/{vendor-capacitor-status-bar-9rNIGxlO.js → vendor-capacitor-status-bar-BsrUwiaA.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-autocomplete-DxS3jwvE.js → vendor-codemirror-autocomplete-CGpAsPWp.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-angular-DdjXl9e2.js → vendor-codemirror-lang-angular-CDJoHJSY.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-cpp--aMr7NVt.js → vendor-codemirror-lang-cpp-BmHofQls.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-css-CZ_qxZY9.js → vendor-codemirror-lang-css-RM2HqXZ0.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-go-Ca-y2Alu.js → vendor-codemirror-lang-go-Crwca_X7.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-html-COZ0L5wT.js → vendor-codemirror-lang-html-CHSHUpwq.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-java-D3Rf3QNJ.js → vendor-codemirror-lang-java-lhQXgWu0.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-javascript-DwJ-IvCs.js → vendor-codemirror-lang-javascript-Dw4kFO4e.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-jinja-D_5lod6k.js → vendor-codemirror-lang-jinja-_pAC3UTN.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-json-BG8C7OpC.js → vendor-codemirror-lang-json-B-b1vAv-.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-less-CVEkoaTw.js → vendor-codemirror-lang-less-xIgOi1ze.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-liquid-U9vj0m8w.js → vendor-codemirror-lang-liquid-CP49m5dB.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-markdown-DqlYH9gY.js → vendor-codemirror-lang-markdown-BTht2ATe.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-php-BFEiEVA1.js → vendor-codemirror-lang-php-BguZDhaO.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-python-Cz1dQXQd.js → vendor-codemirror-lang-python-CH6_em9L.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-rust-C_CoD9mj.js → vendor-codemirror-lang-rust-EG_DtGyi.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-lang-sass-BuR0aKh5.js → vendor-codemirror-lang-sass-BknY5Qpo.js} +1 -1
  85. package/dist/assets/{vendor-codemirror-lang-sql-DggNUjdM.js → vendor-codemirror-lang-sql-B0f-qCZo.js} +1 -1
  86. package/dist/assets/{vendor-codemirror-lang-vue-DFZHi2J3.js → vendor-codemirror-lang-vue-CyGn9snv.js} +1 -1
  87. package/dist/assets/{vendor-codemirror-lang-wast-zuTN3SHT.js → vendor-codemirror-lang-wast-CsFfSyyB.js} +1 -1
  88. package/dist/assets/{vendor-codemirror-lang-xml-CrcvhI-k.js → vendor-codemirror-lang-xml-Cdan_Jp1.js} +1 -1
  89. package/dist/assets/{vendor-codemirror-lang-yaml-DcVWsakb.js → vendor-codemirror-lang-yaml-COI5hck8.js} +1 -1
  90. package/dist/assets/{vendor-codemirror-language-data-CCLITgCF.js → vendor-codemirror-language-data-CqU7kHmg.js} +2 -2
  91. package/dist/assets/{vendor-codemirror-search-H7NOEdbX.js → vendor-codemirror-search-DUfSCF9S.js} +1 -1
  92. package/dist/assets/{vendor-lezer-cpp-C8aD2KAr.js → vendor-lezer-cpp-DMZOJzBa.js} +1 -1
  93. package/dist/assets/{vendor-lezer-css-2lbTJF-Y.js → vendor-lezer-css-DUkkbMp7.js} +1 -1
  94. package/dist/assets/{vendor-lezer-go-Bw6LFTrZ.js → vendor-lezer-go-CHIhCNY6.js} +1 -1
  95. package/dist/assets/{vendor-lezer-html-D7ym2z7S.js → vendor-lezer-html-B3h0MOrG.js} +1 -1
  96. package/dist/assets/{vendor-lezer-java-CZhK7w21.js → vendor-lezer-java-tMazV_6X.js} +1 -1
  97. package/dist/assets/{vendor-lezer-javascript-rpKeTHZp.js → vendor-lezer-javascript-ctwLWf4v.js} +1 -1
  98. package/dist/assets/{vendor-lezer-json-C7jwsd2G.js → vendor-lezer-json-BP_UAzLL.js} +1 -1
  99. package/dist/assets/{vendor-lezer-lr-DR-ylqNN.js → vendor-lezer-lr-B8TQctNw.js} +1 -1
  100. package/dist/assets/{vendor-lezer-markdown-Bir0m5nB.js → vendor-lezer-markdown-aGLZf_3h.js} +1 -1
  101. package/dist/assets/{vendor-lezer-php-y0hIEfo1.js → vendor-lezer-php-D5zCNzlt.js} +1 -1
  102. package/dist/assets/{vendor-lezer-python-D64A9lNV.js → vendor-lezer-python-EJ4Im4y2.js} +1 -1
  103. package/dist/assets/{vendor-lezer-rust-E3ZA9T2L.js → vendor-lezer-rust-DO5c7OtA.js} +1 -1
  104. package/dist/assets/{vendor-lezer-sass-C5UFI9SP.js → vendor-lezer-sass-CMi6zfXI.js} +1 -1
  105. package/dist/assets/{vendor-lezer-xml-DOy7FzCR.js → vendor-lezer-xml-0MHMeZDp.js} +1 -1
  106. package/dist/assets/{vendor-lezer-yaml-kEjaSCvZ.js → vendor-lezer-yaml-BE2EFjpA.js} +1 -1
  107. package/dist/assets/{vendor-replit-codemirror-vim-BLfh0LPy.js → vendor-replit-codemirror-vim-AnOuN8yJ.js} +1 -1
  108. package/dist/assets/{web-components-C7CmoFxi.js → web-components-CeHLxvED.js} +3 -3
  109. package/dist/index.html +4 -4
  110. package/dist/mini-chat.html +3 -3
  111. package/dist/mobile.html +3 -3
  112. package/dist/sw.js +1 -1
  113. package/package.json +1 -2
  114. package/server/index.js +69 -30
  115. package/server/lib/client-auth/DOCUMENTATION.md +15 -1
  116. package/server/lib/client-auth/pairing.js +2 -12
  117. package/server/lib/client-auth/remote-clients.js +2 -12
  118. package/server/lib/cloudflare-tunnel.js +0 -132
  119. package/server/lib/fs/DOCUMENTATION.md +8 -0
  120. package/server/lib/fs/atomic-write.js +111 -0
  121. package/server/lib/fs/atomic-write.test.js +133 -0
  122. package/server/lib/notifications/DOCUMENTATION.md +43 -32
  123. package/server/lib/notifications/pi-notification-watcher.js +8 -7
  124. package/server/lib/notifications/pi-notification-watcher.test.js +88 -2
  125. package/server/lib/pi/routes-extension-events.test.js +231 -0
  126. package/server/lib/pi/routes.js +137 -4
  127. package/server/lib/pi/routes.test.js +248 -2
  128. package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -4
  129. package/server/lib/pi/session-daemon/daemon-process.js +2 -0
  130. package/server/lib/pi/session-daemon/engines/index.js +6 -0
  131. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +1 -1
  132. package/server/lib/pi/session-daemon/extension-bridge.js +24 -0
  133. package/server/lib/pi/session-daemon/extension-message-render.js +74 -0
  134. package/server/lib/pi/session-daemon/extension-message-render.test.js +164 -0
  135. package/server/lib/pi/session-daemon/extension-tool-render.js +13 -6
  136. package/server/lib/pi/session-daemon/pending-input.js +188 -0
  137. package/server/lib/pi/session-daemon/pending-input.test.js +202 -0
  138. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +828 -0
  139. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +296 -6
  140. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +9 -0
  141. package/server/lib/pi/session-daemon/session-daemon.js +219 -19
  142. package/server/lib/pi/session-daemon/session-daemon.test.js +30 -2
  143. package/server/lib/pi/session-daemon/session-engine-router.js +390 -0
  144. package/server/lib/pi/session-daemon/session-engine-router.test.js +515 -0
  145. package/server/lib/pi/session-daemon/session-engines.js +467 -0
  146. package/server/lib/pi/session-daemon/session-engines.test.js +383 -0
  147. package/server/lib/pi/snippets-store.js +8 -17
  148. package/server/lib/pi/ui-settings-store.js +6 -10
  149. package/server/lib/pi/ui-settings-store.test.js +37 -1
  150. package/server/lib/relay/DOCUMENTATION.md +6 -4
  151. package/server/lib/relay/identity-store.js +116 -0
  152. package/server/lib/relay/identity-store.test.js +169 -0
  153. package/server/lib/relay/identity.js +6 -4
  154. package/server/lib/relay/server-id.js +63 -0
  155. package/server/lib/relay/server-id.test.js +132 -0
  156. package/server/lib/relay/signing-key.js +14 -11
  157. package/server/lib/security/bind-host.js +6 -2
  158. package/server/lib/security/bind-host.test.js +17 -0
  159. package/server/lib/server/core-routes.js +27 -1
  160. package/server/lib/server/lan-addresses.js +18 -6
  161. package/server/lib/server/lan-addresses.test.js +28 -0
  162. package/server/lib/server/tunnel-auth.js +47 -7
  163. package/server/lib/server/tunnel-auth.rate-limit.test.js +164 -0
  164. package/server/lib/server/tunnel-service.DOCUMENTATION.md +3 -4
  165. package/server/lib/server/tunnel-service.js +23 -20
  166. package/server/lib/server/tunnel-service.test.js +19 -2
  167. package/server/lib/stt/config-store.js +5 -15
  168. package/server/lib/tailscale/DOCUMENTATION.md +264 -0
  169. package/server/lib/tailscale/routes.js +45 -0
  170. package/server/lib/tailscale/service.js +959 -0
  171. package/server/lib/tailscale/tailscale.js +302 -0
  172. package/server/lib/tailscale/tailscale.test.js +1861 -0
  173. package/server/lib/tunnels/DOCUMENTATION.md +3 -4
  174. package/server/lib/tunnels/providers/cloudflare.js +1 -22
  175. package/server/lib/tunnels/types.js +0 -2
  176. package/server/lib/ui-auth/DOCUMENTATION.md +31 -0
  177. package/server/lib/ui-auth/ui-auth.js +80 -6
  178. package/server/lib/ui-auth/ui-auth.test.js +136 -0
  179. package/server/lib/ui-auth/ui-passkeys.js +2 -13
  180. package/server/lib/update-job-store.js +4 -6
  181. package/dist/assets/DiffView-BxwoRCYx.js +0 -18
  182. package/dist/assets/FilesView-D_2QcdUt.js +0 -6
  183. package/dist/assets/PierreDiffViewer-BW8MO-O6.js +0 -134
  184. package/dist/assets/PullRequestsSurface-B3ictm4I.js +0 -2
  185. package/dist/assets/SessionSwitcherContent-rLoyVqgs.js +0 -1
  186. package/dist/assets/SessionSwitcherDropdown-CfySKnUu.js +0 -2
  187. package/dist/assets/SessionUnreadDot-CmEF9sxM.js +0 -1
  188. package/dist/assets/SettingsView-BiwlwnTK.js +0 -6
  189. package/dist/assets/index-BnZVqcki.js +0 -11
  190. package/dist/assets/index-BnieExes.css +0 -1
  191. package/dist/assets/main-9O5IAtT_.js +0 -136
  192. package/dist/assets/main-DWGwALIw.js +0 -2
  193. package/dist/assets/mobile-BbJcYVym.js +0 -2
  194. package/dist/assets/pi-session-focus-preference-Bmk1iOvn.js +0 -10
  195. package/dist/assets/renderElectronMiniChatApp-R5o9NwFC.js +0 -2
  196. package/dist/assets/renderMobileApp-CQ9tWYIj.js +0 -11
  197. package/dist/assets/runtimeEndpointReset-CtK4C_5h.js +0 -62
  198. package/dist/assets/useAppFontEffects-DviRbaCJ.js +0 -212
  199. package/dist/assets/useGitHubRemoteSearch-D-K7aolk.js +0 -1
  200. package/dist/assets/vendor-capacitor-push-notifications-CBKq2Arn.js +0 -1
  201. package/server/lib/notifications/delivery-runtime.js +0 -314
  202. package/server/lib/notifications/delivery-runtime.test.js +0 -85
  203. package/server/lib/notifications/routes.js +0 -74
  204. package/server/lib/relay/service.js +0 -9
@@ -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-9rNIGxlO.js","assets/vendor-boot-Dgb9NVFe.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-capacitor-app-BjdQVib9.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-capacitor-keyboard-eTtI5go3.js","assets/permissionStore-B9Hkrqny.js","assets/vendor-zustand-CUi8eEds.js","assets/MarkdownRendererImpl-DzgDmUsL.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-BnZVqcki.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BnieExes.css","assets/markdownCore-B9AuEyYi.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-BzhtrDoD.js","assets/runtimeSurface-DBiUWYK2.js","assets/vendor-codemirror-lang-javascript-DwJ-IvCs.js","assets/vendor-lezer-javascript-rpKeTHZp.js","assets/vendor-lezer-lr-DR-ylqNN.js","assets/vendor-codemirror-autocomplete-DxS3jwvE.js","assets/vendor-codemirror-lang-json-BG8C7OpC.js","assets/vendor-lezer-json-C7jwsd2G.js","assets/vendor-codemirror-lang-css-CZ_qxZY9.js","assets/vendor-lezer-css-2lbTJF-Y.js","assets/vendor-codemirror-lang-html-COZ0L5wT.js","assets/vendor-lezer-html-D7ym2z7S.js","assets/vendor-codemirror-lang-markdown-DqlYH9gY.js","assets/vendor-lezer-markdown-Bir0m5nB.js","assets/vendor-codemirror-lang-python-Cz1dQXQd.js","assets/vendor-lezer-python-D64A9lNV.js","assets/GitHubLinkPicker-Bh9RO1yK.js","assets/GitHubListPrimitives-DQyhT5wG.js","assets/GitHubDetailScaffold-UxLAMAOl.js","assets/githubLink-Cryd7GkG.js","assets/ToolOutputDialog-VlS12Xyq.js","assets/JsonTreeView-BAaEPL4O.js","assets/web-components-C7CmoFxi.js","assets/computeVirtualFileMetrics-BJjC-tXV.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-Cp_cJWbI.js","assets/renderFileWithHighlighter-DJ9mk2bZ.js","assets/PatchDiff-BMEUsgXH.js","assets/VirtualizedFileDiff-BqiXjvP6.js","assets/renderDiffWithHighlighter-CVLsdtQ5.js","assets/vendor-diff-C3JhlQdm.js","assets/appThemeRegistry-gegrE2dq.js","assets/ToolPartDiffPreview-DdSneZws.js"])))=>i.map(i=>d[i]);
2
- import{aF as vo,S as xt,E as Qn,aK as Ew,aL as lc,aM as M5,aN as I5,aH as De,aO as ut,d as zt,C as ce,u as tt,m as Tt,aP as Qh,aG as _5,ab as _r,h as qc,aQ as jw,w as ep,a as X,aR as tp,aS as Gc,t as se,aT as _o,a6 as np,aU as rp,aV as lt,A as pn,aW as Tf,r as wr,aX as Tw,e as Aw,aY as Lw,aZ as Nw,aJ as Rw,a_ as Pw,an as Kc,a$ as g1,b0 as Dw,b1 as Ow,b2 as Hw,_ as Fw,b3 as Vw,o as R,av as Bw,b4 as Xn,aw as $w,ay as Pt,b5 as Af,au as sp,b6 as y1,b7 as Nl,b8 as Jd,s as Rl,b9 as Qd,az as Nn,ba as zw,bb as Uw,bc as Zw,ax as Ww,bd as qw,j as Gw,be as Kw,bf as Yw,y as Xw,bg as v1,bh as Jw,bi as x1,bj as Qw,i as yr,T as op,b as e7,bk as t7,bl as n7,bm as r7,bn as cc,bo as s7,bp as b1,v as Jr,bq as E5,a7 as j5,M as _i,N as o7,aB as kt,R as i7,br as a7,V as l7,bs as c7,bt as w1,bu as d7,bv as u7,bw as f7,bx as T5,by as h7,bz as A5,bA as p7,bB as m7,bC as g7,bD as y7,bE as eu,bF as tu,bG as Za,bH as v7,bI as Lf,bJ as Wa,bK as Ys,K as x7,Q as b7,J as w7,W as S1,F as S7,bL as C7,G as k7,bM as M7,bN as L5,U as I7,a8 as cs,bO as _7,bP as E7,bQ as j7,bR as da,bS as T7,bT as Pl,aa as A7,bU as Nf,ak as Rf,bV as L7,al as N7}from"./index-BnZVqcki.js";import{k as l,b2 as R7,b5 as P7,b8 as D7,b6 as O7,b7 as H7,b3 as F7,b4 as V7,bk as B7,bl as N5,bm as $7,bn as z7,bo as U7,bp as Z7,bq as W7,br as q7,bs as G7,bt as Zo,bu as K7,bv as Y7,bw as X7,bx as J7,by as Q7,bz as e9,bA as t9,aL as Gi,bB as n9,M as fn,bC as r9,bD as s9,bE as o9,bF as i9,bG as a9,bH as l9,bI as c9,bJ as d9,bK as u9,bL as f9,bM as h9,bN as p9,aO as ip,aP as Ki,aY as R5,aZ as P5,aR as ap,aS as lp,aT as cp,a$ as D5,aW as dp,aX as up,bO as m9,bP as g9,be as O5,bf as H5,bg as F5,bh as y9,bi as v9,bQ as x9,bR as b9,bS as w9,bT as S9,bU as C9,aQ as k9,bV as V5,bW as B5,bX as $5,bY as z5,bZ as U5,b_ as gs,a_ as M9,b$ as I9,c0 as _9,ba as E9,ah as j9,c1 as T9,c2 as A9,z as Fe,S as Z5,L as W5,am as L9,an as N9,K as R9,ad as P9,c3 as D9,c4 as O9,O as H9,Q as C1,c5 as F9,c6 as V9,c7 as q5,c8 as k1,b1 as B9,aM as qa,bb as G5,bj as $9,c9 as z9}from"./vendor-boot-Dgb9NVFe.js";import{a as z,R as h}from"./vendor-react-DASdDPIk.js";import{c as Et,d as or,p as Yc}from"./vendor-zustand-CUi8eEds.js";import{_ as mt}from"./vendor-vite-runtime-DD1OZmLC.js";import{i as rn}from"./runtimeSurface-DBiUWYK2.js";import{saveOrShareFile as U9}from"./nativeFileSave-BzhtrDoD.js";const uZ=()=>{if(!vo())return!1;const e=Ew();return e==="win32"||e==="linux"},fZ=async()=>{if(!xt())return!1;try{return await Qn("desktop_start_window_drag"),!0}catch{return!1}},Z9=24;class Qr{constructor(t,n,r){this.parent=t,this.overlay=n,this.depth=r}static empty(){return new Qr(null,new Map,0)}static from(t){return new Qr(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>=Z9?this.compact().fork():new Qr(this,new Map,this.depth+1)}compact(){if(!this.parent)return this;const t=new Map;return this.collect(t),new Qr(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 dc=e=>e?Qr.from(e):Qr.empty(),uc=()=>({bySession:new Map,lastSequence:new Map}),K5=()=>dc(),M1=10;let W9=0;const Y5=()=>`ext-${Date.now().toString(36)}-${W9+=1}`,X5=(e,t)=>{const n=[...e,t];return n.length>M1?n.slice(n.length-M1):n},Kn=(e,t,n)=>{t&&(e.lastMutatedMessageId=e.messages.get(t)?.id??t,e.lastMutationKind=n)},$r=e=>{e.parts=e.parts.fork()},q9=(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:K5(),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},Xc=(e,t)=>e.startsWith(`user-${t}-`),G9=250,I1=new WeakMap,K9=(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},ua=e=>{const t=I1.get(e.messages);if(t&&K9(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 I1.set(e.messages,{size:e.messages.size,list:r}),r},J5=(e,t,n)=>{if(!t)return;let r,s=Number.POSITIVE_INFINITY;for(const o of ua(e)){if(o.role!=="user"||o.text!==t||Xc(o.id,e.sessionId))continue;const i=Math.abs(o.createdAt-n);i<=G9&&i<s&&(r=o,s=i)}return r},Y9=(e,t,n)=>{if(n.role==="user"&&Xc(t,e.sessionId)){const r=J5(e,n.text,n.createdAt);if(r){e.messages.set(t,r);return}}e.messages.set(t,n)},Jc=(e,t)=>{if(!t)return;const n=e.messages.get(t)?.id;if(n)return n;if(Xc(t,e.sessionId)){const r=ua(e);for(let s=r.length-1;s>=0;s-=1){const o=r[s];if(o?.role==="user")return o.id}}return t},X9=(e,t,n)=>{const r=e.messages.get(t.messageId);if(r)return r;if(t.role==="user"&&Xc(t.messageId,e.sessionId)){const i=J5(e,t.text??"",t.startedAt);if(i)return e.messages.set(t.messageId,i),i}const s=Jc(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},Q5=(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},J9=(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}},_1=(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=Q5(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})}},fp=(e,t)=>{const n=e.messages.get(t);if(n&&n.role==="assistant")return n;const r=ua(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},Q9=(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})},ev=(e,t)=>{Q9(e,t,n=>n.type==="thinking")},e8=256,tv=(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(e8,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},Yi=(e,t,n=Date.now())=>{if(!(typeof e!="number"||!Number.isFinite(e)))return typeof t!="number"||!Number.isFinite(t)?e:e-(t-n)},t8=(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})}},n8=(e,t,n)=>{X9(e,n,t)},E1=(e,t,n)=>{const r=fp(e,t.messageId);if(!r)return!1;r.streaming=!0,e.streamingMessages.add(r.id),e.streamingMessages.add(t.messageId),n==="text"&&ev(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 u=e.parts.get(d);if(u&&u.type===n){o=u;break}}if(!o){const d=e.partOrder.get(r.id)??[];for(const u of d){const f=e.parts.get(u);if(f&&f.type===n&&f.index===a){o=f;break}}}}}if(o){if(o.type!==n)return!1;const a={...o,text:tv(o.text,t.delta),streaming:!0};return e.parts.set(o.id,a),s!==o.id&&e.parts.set(s,a),!0}const i=Q5(e,r,n,s);return e.parts.set(i.id,{...i,text:t.delta,streaming:!0}),!0},r8=(e,t)=>{const n=fp(e,t.messageId);if(!n)return;const{text:r,thinking:s}=J9(e,n.id);n.text=typeof t.text=="string"?t.text:r,n.thinking=typeof t.thinking=="string"?t.thinking:s,_1(e,n.id,"text",n.text),_1(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))},nu=(e,t,n)=>{const r=e.toolsByCallId.get(n.toolCallId)??n.messageId,s=fp(e,r);if(!s)return!1;ev(e,s.id);const o=Date.now(),i=Yi(n.startedAt,n.serverNow,o),a=Yi(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},u=c.tool,f=n.render!==void 0?{...u?.render??{},...n.render}:u?.render;return d.tool={toolCallId:n.toolCallId,name:n.name,...n.input!==void 0?{input:n.input}:u?.input!==void 0?{input:u.input}:{},...n.output!==void 0?{output:n.output}:u?.output!==void 0?{output:u.output}:{},...f!==void 0?{render:f}:{},...n.error!==void 0?{error:n.error}:u?.error!==void 0?{error:u.error}:{},...n.metadata!==void 0?{metadata:n.metadata}:u?.metadata!==void 0?{metadata:u.metadata}:{},...n.isError!==void 0?{isError:n.isError}:u?.isError!==void 0?{isError:u.isError}:{},state:n.state,...i!==void 0?{startedAt:i}:u?.startedAt!==void 0?{startedAt:u.startedAt}:{},...a!==void 0?{endedAt:a}:u?.endedAt!==void 0?{endedAt:u.endedAt}:{}},t==="end"&&(d.streaming=!1),e.parts.set(d.id,d),!0},s8=(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()}},o8=(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 u={...c,streaming:!1};d&&u.tool&&(u.tool={...u.tool,state:"error",...n?{error:n}:{},endedAt:u.tool.endedAt??r}),e.parts.set(a,u)}}e.streamingMessages.clear()},i8=(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),Kn(e,s.id,"structure")},a8=(e,t,n,r)=>{if(!r.customType)return;const s={id:r.id,sessionId:n,directory:t,role:"extension",customType:r.customType,...r.details!==void 0?{details:r.details}:{},createdAt:r.createdAt,text:r.text??"",thinking:"",streaming:!1};e.messages=new Map(e.messages),e.messages.set(s.id,s),Kn(e,s.id,"structure")},l8=(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)},c8=(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)},d8=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)||(e.extensionDialogs=[...e.extensionDialogs,t])},u8=(e,t)=>{e.extensionDialogs.some(n=>n.requestId===t.requestId)&&(e.extensionDialogs=e.extensionDialogs.filter(n=>n.requestId!==t.requestId))},f8=(e,t)=>{e.extensionNotices=X5(e.extensionNotices,{id:Y5(),message:t.message,level:t.level,createdAt:Date.now()})},h8=(e,t)=>{t.commands===!0&&(e.extensionCatalogRevision=(e.extensionCatalogRevision??0)+1)},p8=(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},m8=(e,t)=>{e.extensionTitle=t.title},g8=(e,t)=>{e.extensionPanels=new Map(e.extensionPanels);const n=t.component!==void 0||t.title!==void 0||t.actions!==void 0;t.removed===!0||!n?e.extensionPanels.delete(t.id):e.extensionPanels.set(t.id,t)},y8=(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)},v8=(e,t)=>{e.extensionErrors=X5(e.extensionErrors,{id:Y5(),source:t.source,...t.event!==void 0?{event:t.event}:{},message:t.message,createdAt:Date.now()})},x8=(e,t)=>{const n=t.message||void 0,r=t.visible;n===void 0&&r===void 0?delete e.extensionWorking:e.extensionWorking={...n!==void 0?{message:n}:{},...r!==void 0?{visible:r}:{}}},b8=(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"],w8={off:"Off",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},Dt=e=>e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",tn=e=>Dt(e)?e:null,S8=(e,t)=>{const n=e.filter(Dt),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]},hp=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"]},Qc=e=>e.some(t=>t!=="off"&&Dt(t)),pp=e=>{const t=hp(e);return Qc(t)?t:[]},Er=e=>e?Dt(e)?w8[e]:`${e.charAt(0).toUpperCase()}${e.slice(1)}`:"Default",C8=(e,t)=>t<=1||!Number.isFinite(e)?0:Math.min(t-1,Math.max(0,Math.round(e*(t-1)))),mp=(e,t,n)=>{const r=e.filter(Dt);if(!Qc(r))return;const s=[void 0,...r],o=Dt(t)&&r.includes(t)?t:void 0,i=s.indexOf(o);return s[(i+n+s.length)%s.length]},nv=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return`${t}/${n}`},rv=(e,t)=>{if(!(!t||!e))return tn(e[t])??void 0},j1=e=>{if(e.thinking)return e.thinking;const t=nv(e.model);return rv(e.defaultThinkingByModel,t)??tn(e.defaultThinking)??void 0},Ga=e=>{const t=hp(e);if(!Qc(t))return;const n=nv({providerId:e.providerId,modelId:e.modelId}),r=rv(e.defaultThinkingByModel,n)??(Dt(e.previousThinking)?e.previousThinking:void 0)??tn(e.defaultThinking)??void 0;if(r)return S8(t,r)},T1=e=>{if(!e)return;const t=e.providerId.trim(),n=e.modelId.trim();if(!(!t||!n))return{providerId:t,modelId:n}},k8=e=>{let t;if(e.messages)for(const s of e.messages){if(s.role!=="assistant")continue;const o=T1(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??T1(e.model),r=t?.thinkingLevel??tn(e.thinking)??void 0;return{...n?{model:n}:{},...r?{thinking:r}:{}}},A1=new WeakMap,M8=e=>{const t=A1.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 A1.set(e,n),n},I8=(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=Jc(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},_8=(e,t,n,r)=>n.id===t.id&&n.role===t.role&&n.parentId===Jc(e,t.parentId)&&n.text===t.text&&n.thinking===t.thinking&&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]),E8=(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(M8(a))}if(n&&_8(e,t,n,s))return n;const o=Jc(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}:{},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}},sv=(e,t)=>{const n=ua(e),r=I8(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(E8(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}},ov=(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 u=c.tool?.toolCallId?e.toolsByCallId.get(c.tool.toolCallId):void 0;u&&n.push(u)}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=ua(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))},fc=e=>{const t=uc(),n=Date.now(),r=q9(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={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}:{},...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,c);const d=[];for(const u of i){const f=u.type==="tool"?Yi(u.startedAt,e.serverNow,n):void 0,p=u.type==="tool"?Yi(u.endedAt,e.serverNow,n):void 0,m={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",...f!==void 0?{startedAt:f}:{},...p!==void 0?{endedAt:p}:{}}}:{},...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,m),d.push(u.id),u.type==="tool"&&u.toolCallId&&r.toolsByCallId.set(u.toolCallId,o.id)}r.partOrder.set(o.id,d)}const s=k8({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,ov(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}},ru=(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:K5(),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,ov(s,{isStreaming:t.payload.snapshot.isStreaming,lifecycle:s.lifecycle,...t.payload.snapshot.retry?{retry:t.payload.snapshot.retry}:{},settleWhenIdle:!0})}break;case"session.lifecycle":t8(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&&($r(s),s.partOrder=new Map(s.partOrder)),n8(s,t.directory,t.payload),t.payload.role==="assistant"&&s.streamingMessages.add(t.payload.messageId),Kn(s,t.payload.messageId,"structure");break;case"assistant.message.delta":$r(s),E1(s,t.payload,"text")&&(s.lifecycle="busy",s.retry=void 0),Kn(s,t.payload.messageId,"part");break;case"assistant.message.end":s.messages=new Map(s.messages),$r(s),s.partOrder=new Map(s.partOrder),s.streamingMessages=new Set(s.streamingMessages),r8(s,t.payload),Kn(s,t.payload.messageId,"structure");break;case"assistant.thinking.delta":$r(s),E1(s,t.payload,"thinking")&&(s.lifecycle="busy",s.retry=void 0),Kn(s,t.payload.messageId,"part");break;case"session.tool.start":$r(s),s.partOrder=new Map(s.partOrder),s.toolsByCallId=new Map(s.toolsByCallId),nu(s,"start",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Kn(s,t.payload.messageId,"part");break;case"session.tool.update":$r(s),nu(s,"update",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Kn(s,t.payload.messageId,"part");break;case"session.tool.end":$r(s),nu(s,"end",t.payload)&&(s.lifecycle="busy",s.retry=void 0),Kn(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.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})}o8(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})}s8(s,t.payload.streaming);break;case"extension.entry":i8(s,t.directory,t.sessionId,t.payload);break;case"extension.message":a8(s,t.directory,t.sessionId,t.payload);break;case"extension.notify":f8(s,t.payload);break;case"extension.catalog":h8(s,t.payload);break;case"extension.editor":p8(s,t.payload,t.sequence);break;case"extension.title":m8(s,t.payload);break;case"extension.status":l8(s,t.payload);break;case"extension.widget":c8(s,t.payload);break;case"extension.dialog":d8(s,t.payload);break;case"extension.dialog.dismiss":u8(s,t.payload);break;case"extension.ui":g8(s,t.payload);break;case"extension.app":y8(s,t.payload);break;case"extension.working":x8(s,t.payload);break;case"extension.editor.track":t.payload.enabled?s.extensionDraftTracked=!0:delete s.extensionDraftTracked;break;case"extension.error":v8(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}},j8={fetchHealth:M5,createStream:lc},su=e=>e instanceof ut?{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"},T8=async(e,t=j8)=>{const n={phase:"idle",reducerState:{bySession:new Map,lastSequence:new Map},lastSequence:new Map,stream:null,errors:[],health:{state:"pending"}},r=async a=>e.retry?e.retry(a):a();n.phase="runtime-probe";const s=e.initialHealth??await r(()=>t.fetchHealth(e.signal,e.runtimeKey));if(s.state==="ready"){if(!(s.capabilities.includes(I5)&&typeof s.streamEpoch=="string"&&s.streamEpoch.length>0)){const 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(()=>De.listSessions({...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new ut("DAEMON_PROTOCOL_MISMATCH","Session list omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new ut("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");o(a.sessions)}catch(a){if(n.errors.push({phase:"session-list",error:su(a)}),a instanceof ut&&a.code==="DAEMON_PROTOCOL_MISMATCH")return n.phase="failed",n}if(e.selectedSessionId){n.phase="session-hydrate";try{const a=e.initialDetail??await r(()=>De.getSession(e.selectedSessionId,{...e.scope,directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new ut("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.streamEpoch)throw new ut("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}=fc(a);n.reducerState=c,n.lastSequence.set(a.session.id,a.lastSequence)}catch(a){if(n.errors.push({phase:"session-hydrate",error:su(a)}),a instanceof ut&&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:su(a)})}const i=n.errors.some(a=>a.phase==="runtime-probe");return n.phase=i?"failed":"ready",n},A8=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}),L8=()=>({bySession:new Map,lastSequence:new Map}),N8=(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,A8(t)),r.lastSequence.set(t.sessionId,t.lastSequence),{state:r,didUpdate:!0}},R8={fetchHealth:M5,createStream:lc},L1=e=>e instanceof ut?{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"},P8=async(e,t=R8)=>{const n={phase:"idle",snapshotState:L8(),reducerState:{bySession:new Map,lastSequence:new Map},stream:null,lastSequence:e.lastKnownSequence??-1},r=async a=>e.retry?e.retry(a):a();n.phase="health-check";const s=await r(()=>t.fetchHealth(e.signal,e.runtimeKey,{fresh:!0}));if(s.state!=="ready")return n.phase="unavailable",n.error={code:s.error?.code??"DAEMON_UNAVAILABLE",...s.error?.message?{message:s.error.message}:{}},n;if(!s.capabilities.includes(I5)||typeof s.streamEpoch!="string"||s.streamEpoch.length===0)return n.phase="failed",n.error={code:"DAEMON_PROTOCOL_MISMATCH",message:"The Pi runtime does not advertise a restart-safe event stream (events.streamEpoch). Update the server."},n;n.epoch=s.streamEpoch;const o=typeof e.streamEpoch=="string"&&e.streamEpoch.length>0?e.streamEpoch:null,i=o!==null&&o!==n.epoch;i&&(n.epochChanged=!0),n.phase="snapshot-fetch";try{const a=await r(()=>De.getSession(e.sessionId,{directory:e.directory,...e.runtimeKey?{runtimeKey:e.runtimeKey}:{}}));if(typeof a.streamEpoch!="string"||a.streamEpoch.length===0)throw new ut("DAEMON_PROTOCOL_MISMATCH","Session detail omitted the current stream epoch");if(a.streamEpoch!==n.epoch)throw new ut("DAEMON_REQUEST_FAILED","Session detail predates the current stream epoch");const c=fc(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}:{}}}},u=N8(n.snapshotState,d.payload.snapshot);n.snapshotState=u.state;const f=e.lastKnownSequence??-1;n.lastSequence=i?a.lastSequence:o!==null&&f>=0?f:Math.max(f,a.lastSequence)}catch(a){const c=L1(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=L1(a),n}return n.phase="ready",n},D8=new Set(["assistant.message.delta","assistant.thinking.delta","session.tool.update"]),O8=e=>D8.has(e.name),hc=e=>e.name==="assistant.message.delta"||e.name==="assistant.thinking.delta"?e:null,H8=(e,t)=>{const n=hc(e),r=hc(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??"")},F8=(e,t)=>{const n=hc(e),r=hc(t);return!n||!r||n.name!==r.name?t:{...r,payload:{...r.payload,delta:tv(n.payload.delta,r.payload.delta)}}},V8=(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,ou=e=>{const t=[];for(const n of e){const r=t[t.length-1];r&&H8(r,n)?t[t.length-1]=F8(r,n):r&&V8(r,n)?t[t.length-1]=n:t.push(n)}return t};class B8{constructor(t){this.publish=t}buffer=[];scheduled="none";generation=0;rafId=0;push(t){if(!O8(t)){const n=this.takeBuffer();this.publish(ou([...n,t]));return}this.buffer.push(t),this.schedule()}flush(){const t=this.takeBuffer();t.length!==0&&this.publish(ou(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(ou(r))};if(typeof globalThis.requestAnimationFrame=="function"){this.scheduled="frame",this.rafId=globalThis.requestAnimationFrame(n);return}this.scheduled="microtask",queueMicrotask(n)}}const $8=[{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=()=>$8.map(e=>({id:`system:${e.name}`,name:e.name,invocationName:e.name,source:"system",description:e.description})),z8=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}:{}}}),U8=3e4,qt=new Map;let iv=0;const Pf=new Set,av=()=>{iv+=1;for(const e of Pf)e()},iu=()=>iv,Z8=e=>(Pf.add(e),()=>Pf.delete(e)),W8=20,ed=(e,t)=>`${e}
3
- ${t?.trim()??""}`,N1=(e,t)=>qt.get(ed(e,t))?.commands,q8=(e,t)=>{const n=qt.get(ed(e,t));return n?{...n}:void 0},G8=(e,t=Date.now())=>t-e.fetchedAt<U8,K8=(e,t,n,r)=>{const s=ed(e,t);for(qt.delete(s),qt.set(s,{commands:n,fetchedAt:r?.fetchedAt??Date.now(),promptSignature:r?.promptSignature??"",skillSignature:r?.skillSignature??""});qt.size>W8;){const o=qt.keys().next().value;if(typeof o!="string")break;qt.delete(o)}},Y8=(e,t,n,r)=>{const s=ed(e,t),o=qt.get(s);return o?(qt.delete(s),qt.set(s,{...o,promptSignature:n,skillSignature:r}),!0):!1},Dl=e=>{if(typeof e=="string"&&e.trim().length>0){const t=`
4
- ${e.trim()}`;for(const n of[...qt.keys()])n.endsWith(t)&&qt.delete(n)}else qt.clear();av()},X8=()=>{qt.clear(),av()};function lv(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,`
5
- `).split(`
6
- `).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 au="pichamber.piSessionCatalog.v1",pc=1,J8=250,cv=4,dv=512,Df=2e3,R1=512,Q8=8192,e6=4096,t6=16384,Wo=(e,t,n=!1)=>typeof e=="string"&&e.length<=t&&(n||e.length>0),Ol=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0,P1=e=>{if(!e||typeof e!="object")return null;const t=e;if(!Ol(t.updatedAt)||!Array.isArray(t.directories)||t.directories.length>dv)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(!Wo(a,Q8)||!Array.isArray(c))return null;const d=ce(a);if(!d||r.has(d)||(o+=c.length,o>Df))return null;const u=[];for(const f of c){if(!f||typeof f!="object")return null;const p=f;if(!Wo(p.id,R1)||p.parentId!==null&&!Wo(p.parentId,R1)||!Wo(p.title,e6,!0)||typeof p.archived!="boolean"||!Ol(p.createdAt)||!Ol(p.updatedAt)||p.preview!==void 0&&!Wo(p.preview,t6,!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}),u.push(m)}r.set(d,u),s.set(d,"idle")}return{byId:n,byDirectory:r,listStatusByDirectory:s}},D1=e=>{if(!e)return null;try{const t=JSON.parse(e);if(t.version!==pc||!t.runtimes||typeof t.runtimes!="object"||Array.isArray(t.runtimes))return null;const n=Object.entries(t.runtimes);return n.length>cv?null:{version:pc,runtimes:Object.fromEntries(n)}}catch{return null}},n6=(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>=dv||r>=Df)break;const i=ce(o);if(!i)continue;const a=[];for(const c of e.byDirectory.get(o)??[]){if(r>=Df)break;const d=e.byId.get(c);!d||ce(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}},r6=(e=zt(),t={})=>{const n=t.flushDelayMs??J8,r=new Map;let s=null,o=!1;const i=f=>{if(!f)return null;try{const p=D1(e.getItem(au));return!p||!Object.prototype.hasOwnProperty.call(p.runtimes,f)?null:P1(p.runtimes[f])}catch{return null}},a=()=>{if(s!==null&&clearTimeout(s),s=null,r.size===0)return;let f={version:pc,runtimes:{}};try{const y=D1(e.getItem(au));y&&(f=y)}catch{}const p=new Map(Object.entries(f.runtimes));let m=[...p.values()].reduce((y,b)=>Ol(b?.updatedAt)?Math.max(y,b.updatedAt):y,0);for(const[y,b]of r)m=Math.max(Date.now(),m+1),p.set(y,n6(b,m));r.clear();const g=[...p.entries()].filter(([,y])=>P1(y)!==null).sort(([,y],[,b])=>b.updatedAt-y.updatedAt).slice(0,cv);try{e.setItem(au,JSON.stringify({version:pc,runtimes:Object.fromEntries(g)}))}catch{}},c=(f,p)=>{o||!f||(r.set(f,p),s===null&&(s=setTimeout(a,Math.max(0,n))))},d=()=>a(),u=()=>{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",u),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",u),document.removeEventListener("freeze",d))))}}},s6={read:()=>null,schedule:()=>{},flush:()=>{},dispose:()=>{}};let O1=null;const o6=()=>typeof window>"u"?s6:(O1??=r6(zt(),{registerLifecycleListeners:!0}),O1),Dn=zt(),Of="projects",Hf="activeProjectId",i6=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim().replace(/\/+$/,""):""},gp=()=>{const e=qc().trim().replace(/\/+$/,"");return e||""},td=()=>{const e=gp();return e?`${Of}:${encodeURIComponent(e)}`:Of},uv=()=>{const e=gp();return e?`${Hf}:${encodeURIComponent(e)}`:Hf},fv=()=>{const e=gp();if(!e)return!0;const t=i6();return!!(t&&e===t)},a6=(e,t)=>{const n=e.trim();return!n.startsWith("~")||!t?n:n==="~"?t:n.startsWith("~/")||n.startsWith("~\\")?`${t}${n.slice(1)}`:n},l6=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,hv=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},pv=e=>{if(typeof e!="string")return null;const t=e.trim();return t&&l6.test(t)?t.toLowerCase():null},yp=e=>{const t=e.trim();if(!t)return"";const n=Dn.getItem("homeDirectory")||tt.getState().homeDirectory||"",s=a6(t,n).replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},c6=e=>{const t=yp(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())},d6=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}},u6=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},f6=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)}),mv=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=yp(i);if(!a)continue;const c=Qh(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 f=d6(o.iconImage);f&&(d.iconImage=f)}typeof o.color=="string"&&o.color.trim().length>0&&(d.color=o.color.trim());const u=hv(o.defaultModel);if(u&&(d.defaultModel=u),o.iconBackground===null)d.iconBackground=null;else{const f=pv(o.iconBackground);f&&(d.iconBackground=f)}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},h6=()=>{try{const e=Dn.getItem(td())||(fv()?Dn.getItem(Of):null);return e?mv(JSON.parse(e)):[]}catch{return[]}},p6=()=>{try{const e=Dn.getItem(td()+":manualOrder");if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}},H1=()=>{try{const e=Dn.getItem(uv())||(fv()?Dn.getItem(Hf):null);if(typeof e=="string"&&e.trim().length>0)return e.trim()}catch{return null}return null},gv=e=>{try{const t=uv();e?Dn.setItem(t,e):Dn.removeItem(t)}catch{}},yv=(e,t)=>{try{Dn.setItem(td(),JSON.stringify(e))}catch{}gv(t)},m6=e=>{gv(e),_r({activeProjectId:e})},qo=(e,t,n)=>{yv(e,t),n&&Ff(n),_r({projects:e,activeProjectId:t??void 0})},Ff=e=>{try{Dn.setItem(td()+":manualOrder",JSON.stringify(e))}catch{}},Vf=h6(),g6=Vf.some(e=>e.id===H1())?H1():Vf[0]?.id??null,it=Et()(or((e,t)=>({projects:Vf,activeProjectId:g6,manualProjectOrder:p6(),validateProjectPath:n=>{if(typeof n!="string"||n.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const r=yp(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()||c6(i),f={id:Qh(i),path:i,label:d,addedAt:c,lastOpenedAt:c},p=[...t().projects,f];return e({projects:p}),_5()&&console.info("[ProjectsStore] Added project",f),t().setActiveProject(f.id),f},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}),qo(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}),qo(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}),m6(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}),qo(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=pv(r.iconBackground)),r.defaultModel!==void 0){const d=hv(r.defaultModel);d?c.defaultModel=d:delete c.defaultModel}return c});e({projects:i}),qo(i,o,t().manualProjectOrder)},uploadProjectIcon:async(n,r)=>{const s=u6(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 f6(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}),qo(i,o,c)},resetForRuntimeSwitch:()=>{e({projects:[],activeProjectId:null,manualProjectOrder:[]})},synchronizeFromSettings:n=>{const r=mv(n.projects??[]),s=t(),o=n.activeProjectId===void 0?r.some(u=>u.id===s.activeProjectId)?s.activeProjectId:null:typeof n.activeProjectId=="string"&&n.activeProjectId.trim()?n.activeProjectId.trim():null,i=r.map(u=>u.id),a=JSON.stringify(s.projects)!==JSON.stringify(r),c=s.activeProjectId!==o,d=s.manualProjectOrder.length!==i.length||s.manualProjectOrder.some((u,f)=>u!==i[f]);if(!a&&!c){d&&(e({manualProjectOrder:i}),Ff(i));return}if(e({projects:r,activeProjectId:o,manualProjectOrder:i}),yv(r,o),Ff(i),o&&(c||n.activeProjectId!==void 0)){const u=r.find(f=>f.id===o);u&&tt.getState().setDirectory(u.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 es=ce,y6=(e,t)=>{const n=es(t);if(!n)return null;let r=null;for(const s of e){const o=es(s.path);o&&(n!==o&&!n.startsWith(`${o}/`)||(!r||o.length>(es(r.path)?.length??0))&&(r=s))}return r},er=(e,t,n)=>{const s=es((typeof t=="string"?t:n)??null);if(!s)return null;const o=y6(e,s);if(o)return o;if(!(t instanceof Map))return null;const i=new Map;for(const c of e){const d=es(c.path);d&&i.set(d,c)}let a=null;for(const[c,d]of t){const u=es(c),f=u?i.get(u):null;if(f)for(const p of d??[]){const m=es(p?.path??null);m&&(s!==m&&!s.startsWith(`${m}/`)||(!a||m.length>a.worktreePath.length)&&(a={project:f,worktreePath:m}))}}return a?.project??null},F1=500,v6=()=>{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(!v6())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>F1&&window.__PICHAMBER_STARTUP_TRACE__.splice(0,window.__PICHAMBER_STARTUP_TRACE__.length-F1)},x6=()=>{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__=x6);const Bf=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}},Ka="https://models.dev/api.json",Xi=e=>typeof e=="object"&&e!==null,mc=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),b6=e=>{if(!Xi(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))},w6=e=>{if(!Xi(e))return!1;const t=e;return t.models===void 0||Xi(t.models)},vv=(e,t)=>{const n=e?.toLowerCase?.()??"";return!n||!t?"":`${n}/${t}`},V1=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:V1(t.capabilities.input),output:V1(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}),C6=e=>{const t=new Map;if(!Xi(e))return t;for(const[n,r]of Object.entries(e)){if(!w6(r))continue;const s=typeof r.id=="string"&&r.id.length>0?r.id:n,o=r.models;if(!(!o||!Xi(o)))for(const[i,a]of Object.entries(o)){if(!b6(a))continue;const c=i||a.id;if(!c)continue;const d=vv(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},k6=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(Ka,{signal:e?.signal,headers:{Accept:"application/json"},cache:"no-store",mode:"cors"});if(!n.ok)throw new Error(`Metadata request to ${Ka} returned status ${n.status}`);return C6(await n.json())}catch(n){return n?.name==="AbortError"?console.warn(`Model metadata request aborted (${Ka})`):console.warn(`Failed to fetch model metadata from ${Ka}:`,n),new Map}finally{t&&clearTimeout(t)}};let Ei=null;const M6=3e4;let Hs=null;const I6=1500;let Ya=null;const _6=()=>{if(typeof window<"u"&&typeof window.requestIdleCallback=="function")return window.requestIdleCallback.bind(window);const e=globalThis.requestIdleCallback;return typeof e=="function"?e:null},$f=(e,t)=>{e().size>0||Ei||Hs!==null&&Date.now()-Hs<M6||(st("modelsMetadata:queued"),Ei=Bf("modelsMetadata",k6).then(n=>(n.size>0?(Hs=null,st("modelsMetadata:set",{entries:n.size}),t(n)):Hs=Date.now(),n)).catch(()=>(Hs=Date.now(),new Map)).finally(()=>{Ei=null}))},E6=()=>{Ei=null,Hs=null},j6=(e,t)=>{if(e().size>0||Ei||Ya)return;st("modelsMetadata:scheduledIdle");const n=()=>{Ya=null,st("modelsMetadata:idleFired"),$f(e,t)},r=_6();if(r){Ya={kind:"idle",handle:r(n,{timeout:5e3})};return}Ya={kind:"timeout",handle:setTimeout(n,I6)}},T6=(e,t,n,r)=>{const s=vv(t,n);if(s)return e.get(s)??(r?S6(t,r):void 0)},xv=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)}},A6=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!xv(n))continue;const s=tn(r);s&&(t[n]=s)}return t},L6=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:A6(n?.defaultThinkingByModel)}}catch{return{ok:!1}}},lu=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}},N6=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 L6(),r=(c,d)=>n.ok?t(c,{...d,defaultModel:n.defaultModel,defaultThinking:n.defaultThinking,defaultThinkingByModel:n.defaultThinkingByModel}):t(c,d),s=await jw().catch(()=>null);if(s)return r("shared-settings",lu(s));const o=ep()?.settings;if(o)try{const d=(await o.load())?.settings;if(d)return r("runtime-settings",lu(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)?lu(a):{})}catch(n){return st("config.defaults:error",{error:n instanceof Error?n.message:String(n)}),t("error",{})}},R6=3e4,Xa=new Map,B1=new WeakMap;let Ja=0;const P6=(e,t)=>JSON.stringify([e,ce(t)??t]),D6=(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}),$1=()=>({worktrees:[],status:"idle",error:null,fetchedAt:0}),sn=Et()((e,t)=>({runtimeKey:X(),projects:new Map,refreshProject:async(n,r,s)=>{const o=ce(n);if(!o)return null;const i=X(),a=Ja,c=P6(i,o),d=Xa.get(c);if(d)return d;const u=t().projects.get(o)??$1();if(!s?.force&&u.status==="ready"&&u.error===null&&Date.now()-u.fetchedAt<R6)return u.worktrees;u.status==="idle"&&e(p=>{const m=new Map(p.projects);return m.set(o,{...u,status:"loading"}),{projects:m}});const f=(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!==Ja||i!==X()||t().runtimeKey!==i?null:(e(g=>{const y=g.projects.get(o)??$1(),b=D6(y.worktrees,m);if(b&&y.status==="ready"&&y.error===null)return g;const k=new Map(g.projects);return k.set(o,{worktrees:b?y.worktrees:m,status:"ready",error:null,fetchedAt:Date.now()}),{projects:k}}),m)}catch(p){if(a!==Ja||i!==X()||t().runtimeKey!==i)return null;const m=p instanceof Error?p.message:"Failed to discover Git worktrees.";return e(g=>{const y=g.projects.get(o)??u,b=new Map(g.projects);return b.set(o,{...y,status:"failed",error:m}),{projects:b}}),null}finally{Xa.delete(c)}})();return Xa.set(c,f),f},resetForRuntimeSwitch:n=>{Ja+=1,Xa.clear(),e({runtimeKey:n,projects:new Map})}})),O6=(e,t)=>{const n=ce(t??null);if(!n)return[];const r=e.projects.get(n)?.worktrees;if(!r)return[];const s=B1.get(r);if(s)return s;const o=r.filter(i=>!i.isPrimary&&!i.prunable);return B1.set(r,o),o},On=(e,t)=>{const n=new Map;for(const r of e){const s=ce(r.path??null);s&&n.set(s,O6(t,s))}return n},vp="__global__",ts=e=>{const t=typeof e=="string"?e.trim():"";return t.length>0?t:vp},Wr=e=>e===vp?null:e,H6=()=>typeof window>"u"?vp:Fl(tt.getState().currentDirectory),bv="oc.worktreeProjectMap.v2",zf="oc.worktreeProjectMap",F6=8,z1=new Map,wv=()=>{try{const e=typeof localStorage<"u"?localStorage.getItem(bv):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:{}}}},Sv=e=>{const t=Object.fromEntries(Object.entries(e.runtimes).sort(([,n],[,r])=>r.updatedAt-n.updatedAt).slice(0,F6));localStorage.setItem(bv,JSON.stringify({...e,runtimes:t}))},Cv=()=>{const e=X()||"default",t=z1.get(e);if(t)return t;const n=wv();let r=n.runtimes[e]?.entries??null;if(!r&&!n.legacyClaimed)try{const o=typeof localStorage<"u"?localStorage.getItem(zf):null;r=o?JSON.parse(o):{},n.legacyClaimed=!0,n.runtimes[e]={updatedAt:Date.now(),entries:r},Sv(n),localStorage.removeItem(zf)}catch{r={}}const s=r??{};return z1.set(e,s),s},V6=(e,t)=>{if(!e||!t||e===t)return;const n=Cv();if(n[e]!==t){n[e]=t;try{const r=X()||"default",s=wv();s.legacyClaimed=!0,s.runtimes[r]={updatedAt:Date.now(),entries:n},Sv(s),localStorage.removeItem(zf)}catch{}}},ji=e=>{const t=ce(e);return t===null?null:t||"/"},B6=()=>{try{return it.getState().projects.map(e=>ji(e.path)).filter(e=>!!e)}catch{return[]}},$6=()=>{try{const{projects:e,activeProjectId:t}=it.getState(),n=t?e.find(r=>r.id===t):null;return ji(n?.path??e[0]?.path??null)}catch{return null}},Hl=e=>{const t=ji(e),n=B6();if(!t)return null;if(n.includes(t))return t;const r=ji(Cv()[t]);if(r)return r;try{const s=it.getState().projects,o=er(s,On(s,sn.getState()),t),i=ji(o?.path??null);if(i&&i!==t)return V6(t,i),i}catch{return null}return null},Fl=e=>ts(Hl(e)),kv="__add_provider__",zr="zen",U1="big-pickle",Mv=e=>xv(e),Iv=(e,t)=>{const n=tn(t);return n&&pp(e).includes(n)?n:void 0},Z1=e=>e===kv?"":e??"",gc=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},yc=(e,t,n)=>{const r=e.find(s=>s.id===t);return r?r.models.some(s=>s.id===n):!1},z6=({providers:e,currentProviderId:t,currentModelId:n,currentVariant:r,settingsDefaultModel:s,settingsDefaultVariant:o})=>{const i=(d,u,f)=>{if(!f)return;const p=e.find(m=>m.id===d)?.models.find(m=>m.id===u);return Iv(p,f)};if(t&&n&&yc(e,t,n))return{providerId:t,modelId:n,variant:i(t,n,r)};if(s){const d=Mv(s);if(d&&yc(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},cu=({providers:e,settingsZenModel:t})=>{const n=gc(t);if(!Array.isArray(e)||e.length===0)return n?{providerId:zr,modelId:n}:null;if(n&&yc(e,zr,n))return{providerId:zr,modelId:n};if(yc(e,zr,U1))return{providerId:zr,modelId:U1};const r=e.find(s=>s.id===zr);if(r?.models.length){const s=Math.floor(Math.random()*r.models.length),o=gc(r.models[s]?.id);if(o)return{providerId:zr,modelId:o}}return null},U6=4,Z6=800,W6=3e4,q6=1e3,G6=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 u={...d};delete u.agents,delete u.currentAgentName,delete u.agentModelSelections,delete u.runtimeDefaultAgent,delete u.runtimeDefaultModel,delete u.settingsDefaultFileViewerPreview,delete u.defaultFileViewerPreview,a[c]=u}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},W1=new Map,K6=(e,t)=>{const n=e.get(t);return typeof n=="number"&&Date.now()-n<W6},Y6=e=>new Promise(t=>setTimeout(t,e)),_v=async()=>(await De.health({runtimeKey:X()})).state==="ready",X6=async(e=Z6)=>Promise.race([_v().catch(()=>!1),Y6(Math.max(1,e)).then(()=>!1)]),q1=new Set;function J6(e){return q1.add(e),()=>{q1.delete(e)}}function Q6(e,t){return e.scopes.includes("all")||e.scopes.includes(t)}const eS=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(U6,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 G1=null,K1=null;const tS=e=>{typeof window<"u"&&(window.__zustand_config_store__=e),G1||(G1=J6(async t=>{Q6(t,"providers")&&await eS(e,"configChange:providers")})),typeof window<"u"&&!K1&&(K1=tt.subscribe((t,n)=>{const r=ts(t.currentDirectory),s=ts(n.currentDirectory);r!==s&&(st("directoryStore:changed",{previous:s,next:r}),e.getState().activateDirectory(t.currentDirectory))}))},nS=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},rS=e=>e.filter(nS),sS=async()=>{const e=await De.listProviders({runtimeKey:X()}),n=rS(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}},du=e=>new Promise(t=>setTimeout(t,e)),uu=new Map;let Qa=null;const qe=Et()(or(Yc((e,t)=>({activeDirectoryKey:H6(),directoryScoped:{},providers:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,selectedProviderId:"",defaultProviders:{},selectionSource:"auto",isConnected:!1,hasEverConnected:!1,connectionPhase:"connecting",lastDisconnectReason:null,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultThinking:void 0,settingsDefaultThinkingByModel:{},settingsAutoCreateWorktree:!1,settingsZenModel:void 0,activateDirectory:async n=>{const r=Hl(n),s=typeof n=="string"&&n.trim().length>0;if(!r&&s){st("activateDirectory:skippedUnknownDirectory",{directory:n});return}const o=ts(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?K6(W1,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:ts(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,u]of Object.entries(s.directoryScoped))a[d]=c(u);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=Hl(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=ts(s),c=n?.source??"unknown";st("loadProviders:called",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i});const d=uu.get(a);if(d)return st("loadProviders:deduped",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i}),d;const u=(async()=>{const f=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 y=null;for(let b=0;b<3;b++)try{const k=await Bf("loadProviders:api",async()=>sS(),{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,attempt:b+1}),v=k?.providers??[],x=k?.defaults??{};e(S=>{const w=S.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},M=S.activeDirectoryKey===a?S.currentProviderId:w.currentProviderId,I=S.activeDirectoryKey===a?S.currentModelId:w.currentModelId,E=S.activeDirectoryKey===a?S.currentVariant:w.currentVariant,_=z6({providers:v,currentProviderId:M,currentModelId:I,currentVariant:E,settingsDefaultModel:S.settingsDefaultModel,settingsDefaultVariant:S.settingsDefaultVariant}),T=S.activeDirectoryKey===a?S.selectedProviderId:w.selectedProviderId,A=T===kv||v.some(O=>O.id===T)?T:_?.providerId??v[0]?.id??"",j={...w,providers:v,defaultProviders:x,currentProviderId:_?.providerId??"",currentModelId:_?.modelId??"",currentVariant:_?.variant,selectedProviderId:A},N={directoryScoped:{...S.directoryScoped,[a]:j}};return S.activeDirectoryKey===a&&(N.providers=v,N.defaultProviders=x,N.currentProviderId=j.currentProviderId,N.currentModelId=j.currentModelId,N.currentVariant=j.currentVariant,N.selectedProviderId=A),N});const C=typeof performance<"u"?performance.now():Date.now();st("loadProviders:end",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,durationMs:Math.round(C-f),providers:v.length,models:v.reduce((S,w)=>S+w.models.length,0)}),W1.set(a,Date.now());return}catch(k){y=k,st("loadProviders:attemptError",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,attempt:b+1,error:k instanceof Error?k.message:String(k)});const v=200*(b+1);await new Promise(x=>setTimeout(x,v))}console.error("Failed to load providers:",y),st("loadProviders:error",{directoryKey:a,source:c,requestedDirectory:r,effectiveDirectory:i,error:y instanceof Error?y.message:String(y)}),e(b=>{const v={...b.directoryScoped[a]??{providers:[],currentProviderId:"",currentModelId:"",selectedProviderId:"",defaultProviders:{}},providers:m,defaultProviders:g},x={directoryScoped:{...b.directoryScoped,[a]:v}};if(b.activeDirectoryKey===a&&(x.providers=m,x.defaultProviders=g,!b.currentProviderId&&!b.currentModelId&&b.settingsDefaultModel)){const C=Mv(b.settingsDefaultModel);if(C){const S=m.find(w=>w.id===C.providerId);if(S?.models.some(w=>w.id===C.modelId)){const w=S.models.find(I=>I.id===C.modelId),M=Iv(w,b.settingsDefaultVariant);x.currentProviderId=C.providerId,x.currentModelId=C.modelId,x.currentVariant=M,x.selectedProviderId=C.providerId,v.currentProviderId=C.providerId,v.currentModelId=C.modelId,v.currentVariant=M,v.selectedProviderId=C.providerId}}}return x})})().finally(()=>uu.delete(a));return uu.set(a,u),u},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,u={...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]:u}}})},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:()=>pp(t().getCurrentModel()),cycleCurrentVariant:()=>{const n=mp(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:()=>{E6(),e({modelsMetadata:new Map})},ensureModelMetadata:()=>{$f(()=>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 cu({providers:n.providers,settingsZenModel:n.settingsZenModel})},probeConnection:async n=>{if(await X6(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 Bf("checkConnection:health",()=>_v(),{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 du(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 du(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(Qa)return st("initializeApp:deduped"),Qa;const n=(async()=>{const r=typeof performance<"u"?performance.now():Date.now();st("initializeApp:start");try{const s=_5();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=Hl(a?.path??i??null),d=c??$6();d||st("initializeApp:globalConfigScope"),d&&!c&&i!==d&&(st("initializeApp:normalizedUnknownDirectoryToProject",{initialDirectory:i,configDirectory:d}),tt.getState().setDirectory(d,{showOverlay:!1}));const u=ts(d);t().activeDirectoryKey!==u&&e({activeDirectoryKey:u}),s&&console.log("Loading providers..."),await t().loadProviders({directory:d,source:"initializeApp"});const f=await N6(),p=t().providers,m=gc(t().settingsZenModel),g=gc(f.zenModel),b=(cu({providers:p,settingsZenModel:m})??cu({providers:p,settingsZenModel:g}))?.modelId||g||m;e({settingsDefaultModel:f.defaultModel,settingsDefaultVariant:f.defaultVariant,settingsDefaultThinking:f.defaultThinking,settingsDefaultThinkingByModel:f.defaultThinkingByModel??{},settingsAutoCreateWorktree:f.autoCreateWorktree??!1,settingsZenModel:b}),b&&b!==g&&_r({zenModel:b,gitProviderId:"",gitModelId:""}).catch(()=>{}),e({isInitialized:!0,isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),j6(()=>t().modelsMetadata,v=>e({modelsMetadata:v})),t().prewarmProjectConfigs(d);const k=typeof performance<"u"?performance.now():Date.now();st("initializeApp:end",{durationMs:Math.round(k-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(()=>{Qa=null});return Qa=n,n},prewarmProjectConfigs:async n=>{if(!t().isConnected)return;const r=Fl(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=Fl(a);if(o.has(c)||(o.add(c),t().directoryScoped[c]?.providers.length))continue;const u=Wr(c);u&&i.push(u)}for(const a of i){if(await du(q6),!t().isConnected)return;const c=Fl(a),d=t().directoryScoped[c],u=[];d?.providers.length||u.push(t().loadProviders({directory:a,source:"projectConfigPrewarm"})),u.length>0&&await Promise.allSettled(u)}},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)=>{$f(()=>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 T6(s,n,r,i)}}),{name:"config-store",storage:tp(),merge:(e,t)=>G6({...t,...e&&typeof e=="object"?e:{}}),partialize:e=>({activeDirectoryKey:e.activeDirectoryKey,directoryScoped:Object.fromEntries(Object.entries(e.directoryScoped).map(([t,n])=>[t,{...n,selectedProviderId:Z1(n.selectedProviderId)}])),providers:e.providers,currentProviderId:e.currentProviderId,currentModelId:e.currentModelId,currentVariant:e.currentVariant,selectedProviderId:Z1(e.selectedProviderId),defaultProviders:e.defaultProviders,settingsDefaultModel:e.settingsDefaultModel,settingsDefaultVariant:e.settingsDefaultVariant,settingsDefaultThinking:e.settingsDefaultThinking,settingsDefaultThinkingByModel:e.settingsDefaultThinkingByModel,settingsAutoCreateWorktree:e.settingsAutoCreateWorktree,settingsZenModel:e.settingsZenModel})})));tS(qe);const oS=5e3,Qs=new Map,eo=new Map,vc=e=>{const t=X();Qs.delete(t),eo.delete(t),(!t||t==="local")&&(Qs.clear(),eo.clear())},Ev=()=>{Qs.clear(),eo.clear()},kr=Et()(or(Yc((e,t)=>({selectedSkillName:null,skills:[],isLoading:!1,setSelectedSkill:n=>e({selectedSkillName:n}),loadSkills:async()=>{const n=X(),r=Date.now(),s=Qs.get(n)??0;if(s>0&&r-s<oS)return!0;const o=eo.get(n);if(o)return o;const i=(async()=>{e({isLoading:!0});try{const c=(await De.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(u=>u.name===d.selectedSkillName)?{selectedSkillName:null}:{}})),Qs.set(n,Date.now()),!0}catch{return e({isLoading:!1}),!1}})();eo.set(n,i);try{return await i}finally{eo.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 De.updateResource({resourceId:s.id,content:r},{runtimeKey:X()})).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}),Qs.set(X(),Date.now()),!0}catch{return!1}},getSkillByName:n=>t().skills.find(r=>r.name===n),resetForRuntimeSwitch:()=>{Ev(),e({skills:[],isLoading:!1,selectedSkillName:null})}}),{name:"skills-store",storage:tp(),partialize:e=>({selectedSkillName:e.selectedSkillName})}),{name:"skills-store"})),hZ=Object.freeze(Object.defineProperty({__proto__:null,invalidateSkillsLoadCache:vc,resetSkillsForRuntimeSwitch:Ev,useSkillsStore:kr},Symbol.toStringTag,{value:"Module"})),iS=200,jv=1440*60*1e3,aS=3e4,lS=15e3,cS=9e4,Uf="oc.session-activity.v1",dS=new Set,uS=new Map,Mn=Et(()=>({startedAt:new Map,settledMs:new Map})),ds=new Map;let xp=0,xc=null;const fS=()=>typeof performance<"u"&&Number.isFinite(performance.timeOrigin)?performance.timeOrigin:Date.now();let bp=fS();const Tv=(e,t)=>e.start<=t&&t-e.start<=jv&&e.seen<=t&&bp-e.seen<=aS,hS=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}},pS=()=>{const e=new Map;let t=null;try{t=Gc().getItem(Uf)}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=hS(o);i&&Tv(i,r)&&e.set(s,i)}return e},nd=()=>(xc??=pS(),xc),mS=e=>e-bp>cS?(xc?.clear(),uS):nd(),os=(e,t)=>{const n={};for(const[r,s]of nd())Tv(s,t)&&(n[r]=s);for(const[r,s]of e)n[r]={start:s,seen:ds.get(r)??t};xp=t;try{const r=Gc();if(Object.keys(n).length===0){r.removeItem(Uf);return}r.setItem(Uf,JSON.stringify(n))}catch{}},fu=()=>{const{startedAt:e}=Mn.getState();if(e.size===0)return;const t=Date.now();for(const n of e.keys())ds.set(n,t);os(e,t)};let Y1=!1;const Av=()=>{if(!(Y1||typeof window>"u")){Y1=!0;try{window.addEventListener("pagehide",fu,{capture:!0}),typeof document<"u"&&(document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&fu()}),document.addEventListener("freeze",fu))}catch{}}},gS=e=>{for(;e.size>iS;){const t=e.keys().next();if(t.done)return;e.delete(t.value)}},X1=(e,t)=>{const n=Date.now(),r=mS(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 f of e)i=!0,ds.set(f,n),!(o.started??s.startedAt).has(f)&&(c().set(f,r.get(f)?.start??n),(o.settled??s.settledMs).has(f)&&d().delete(f));const u=(f,p)=>{c().delete(f),ds.delete(f),d().set(f,Math.max(0,n-p))};if(t!==null){nd().delete(t)&&(a=!0);const f=s.startedAt.get(t);f!==void 0&&u(t,f)}if(o.settled&&gS(o.settled),(o.started||o.settled)&&Mn.setState({startedAt:o.started??s.startedAt,settledMs:o.settled??s.settledMs}),o.started){o.started.size>0&&Av(),os(o.started,n);return}if(a){os(s.startedAt,n);return}i&&s.startedAt.size>0&&n-xp>=lS&&os(s.startedAt,n)},J1=(e,t)=>{if(t==="active"){X1(new Set([e]),null);return}X1(dS,e)},vn=(e,t,n)=>{if(!Number.isFinite(t))return;const r=Date.now(),s=Yi(t,n,r);if(s===void 0||r-s>jv||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),ds.set(e,r),Mn.setState({startedAt:a,settledMs:c}),Av(),os(a,r)},Q1=e=>{const t=nd().delete(e),n=Mn.getState(),r=n.startedAt.has(e),s=n.settledMs.has(e);if(ds.delete(e),!r&&!s){t&&os(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)&&os(o,Date.now())},pZ=(e={})=>{xc=null,ds.clear(),xp=0,bp=e.pageLoadAt??Date.now(),Mn.setState({startedAt:new Map,settledMs:new Map})},Lv=e=>Mn(z.useCallback(t=>t.startedAt.get(e),[e])),mZ=e=>Mn(z.useCallback(t=>t.settledMs.get(e),[e])),gZ=(e,t)=>Mn(z.useCallback(n=>t?n.startedAt.has(e):n.settledMs.has(e),[t,e])),Zf="oc.sessions.pinned.v2",yS="oc.sessions.pinned",Vl=zt(),Wf=(e,t,n)=>{const r=ce(t);return!e||!r||!n?null:JSON.stringify([e,r,n])},Nv=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=ce(r);return!n||!o||o!==r||!s?null:[n,o,s]}catch{return null}},qf=(e,t,n)=>{if(!t)return!1;const r=Wf(X(),t,n);return r?e.has(r):!1},vS=()=>{Vl.removeItem(yS);const e=Vl.getItem(Zf);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])=>Nv(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 Vl.removeItem(Zf),{ids:new Set,touchedAt:{}}}},eg=(e,t)=>{const n=[...e].filter(r=>Nv(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)}},tg=({ids:e,touchedAt:t})=>{const n=Object.fromEntries([...e].map(r=>[r,t[r]??Date.now()]));Vl.setItem(Zf,JSON.stringify({version:2,sessions:n}))},ng=vS(),xS=Et((e,t)=>({ids:ng.ids,touchedAt:ng.touchedAt,setIds:n=>{const r=t().ids,s=typeof n=="function"?n(r):n;if(s===r)return;const o=eg(s,t().touchedAt);e(o),tg(o)},toggle:n=>{const r=Wf(X(),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=eg(s,o);e(i),tg(i)},clearPinnedSession:(n,r,s)=>{const o=Wf(n,r,s);if(!o||!t().ids.has(o))return;const i=new Set(t().ids);i.delete(o),t().setIds(i)}})),yZ=new Map,bc=new Map,xo=new Map;let Bl=0;const Ji=Et(()=>({rankById:new Map})),rg=()=>(Bl=Math.max(Bl+1,Date.now()),Bl),bS=(e,t=!1)=>{const n=[...e];n.length!==0&&Ji.setState(r=>{const s=new Map(r.rankById),o=t?rg():null;for(const i of n)s.set(i,o??rg());return{rankById:s}})},wS=(e,t)=>{const n=bc.get(e);bc.set(e,t),t==="active"&&n!=="active"&&bS([e])},SS=e=>{bc.delete(e),xo.delete(e),Ji.setState(t=>{if(!t.rankById.has(e))return t;const n=new Map(t.rankById);return n.delete(e),{rankById:n}})},vZ=()=>{bc.clear(),xo.clear(),Bl=0,Ji.setState({rankById:new Map})},Gf=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Rv=e=>Gf(e.time?.updated)||Gf(e.time?.created),CS=e=>Gf(e.time?.created),Kf=e=>e.parentID??null,Yf=e=>{const t=e;return ce(t.directory??null)??ce(t.project?.worktree??null)},hi=(e,t)=>{const n=xo.get(e.id),r=t?"created":"updated",s=n?.[r];if(s!==void 0)return s;const o=t?CS(e):Rv(e);return xo.set(e.id,{...n,[r]:o}),o},kS=e=>{const t=Ji.getState().rankById;let n=!1;for(const r of e){const s=Rv(r);if(t.get(r.id)!==void 0)continue;const o=xo.get(r.id);o?.updated!==void 0&&o.updated>=s||(xo.set(r.id,{...o,updated:s}),n=!0)}n&&Ji.setState(r=>({rankById:new Map(r.rankById)}))},sg=(e,t,n=!1)=>t.get(e.id)??hi(e,n),Pv=(e,t,n,r,s)=>{if(n!==r)return n?-1:1;const o=hi(e,n),i=hi(t,r);if(Kf(e)===Kf(t)){const d=sg(t,s,r)-sg(e,s,n);if(d!==0)return d}const a=i-o;if(a!==0)return a;const c=hi(t,!0)-hi(e,!0);return c!==0?c:e.id.localeCompare(t.id)},xZ=(e,t,n,r)=>Pv(e,t,qf(n,Yf(e),e.id),qf(n,Yf(t),t.id),r),MS=(e,t,n=r=>r)=>{const r=new Map,s=o=>{let i=r.get(o);return i===void 0&&(i=qf(e,Yf(o),o.id),r.set(o,i)),i};return(o,i)=>{const a=n(o),c=n(i);return Pv(a,c,s(a),s(c),t)}},bZ=(e,t,n)=>{const r=new Set(e.map(u=>u.id)),s=[],o=new Map;for(const u of e){const f=Kf(u);if(!f||!r.has(f)){s.push(u);continue}const p=o.get(f);p?p.push(u):o.set(f,[u])}const i=MS(t,n);s.sort(i);for(const u of o.values())u.sort(i);const a=[],c=new Set,d=u=>{if(!c.has(u.id)){c.add(u.id),a.push(u);for(const f of o.get(u.id)??[])d(f)}};for(const u of s)d(u);for(const u of e)d(u);return a},og=500,IS=1e3*60*60*24*30;function _S(e){const t=Date.now()-IS,n=e.filter(r=>r.time>=t);return n.length<=og?n:n.slice(n.length-og)}function hu(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 rd=Et((e,t)=>({list:[],index:{session:{unseenCount:{},unseenHasError:{}},project:{unseenCount:{},unseenHasError:{}}},append:n=>{const r=t().list,s=_S([...r,n]);e({list:s,index:hu(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:hu(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:hu(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 sd(e){rd.getState().markSessionViewed(e)}function Dv(e,t,n){const r=rd.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 Ov(e){const t=se.getState();if(!t.nativeNotificationsEnabled||e.kind==="completion"&&!t.notifyOnCompletion||e.kind==="error"&&!t.notifyOnError)return;const n=ep()?.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 ES(e){return rd(t=>t.index.session.unseenCount[e]??0)}const wZ=Object.freeze(Object.defineProperty({__proto__:null,dispatchSessionNotification:Ov,markSessionViewed:sd,notifySessionTurnComplete:Dv,useNotificationStore:rd,useSessionUnseenCount:ES},Symbol.toStringTag,{value:"Module"})),jS="pichamber_sync_perf",wp=()=>({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}),TS=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem(jS)==="1"}catch{return!1}},Hv=TS();let $l=Hv||_o()?wp():null;const AS=()=>_o()||Hv,Sp=()=>AS()?($l||($l=wp()),$l):null;function Fv(){Sp()&&($l=wp())}function Vv(){const e=Sp();return e?{...e}:null}function LS(e){const t=Sp();t&&(t.persistenceSerializations+=1,t.persistenceUtf8Bytes+=new TextEncoder().encode(e).byteLength)}typeof window<"u"&&(window.__pichamberSyncPerformance={getSnapshot:Vv,reset:Fv});const Xf="pichamber.chatDrafts.v2",NS=50,Jf=zt(),Qf=new Set;let pi,Wn;const Eo=(e,t,n)=>{const r=ce(t);return!e||!r?null:{runtimeKey:e,directory:r,sessionId:n}},Gt=e=>JSON.stringify([e.runtimeKey,e.directory,e.sessionId]),Bv=()=>{const e=Jf.getItem(Xf);if(e===pi&&Wn)return Wn;try{const t=JSON.parse(e??"");if(t.version!==2||!t.drafts||typeof t.drafts!="object"||Array.isArray(t.drafts))return pi=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 pi=e,Wn={version:2,drafts:n},Wn}catch{return Jf.removeItem(Xf),pi=null,Wn={version:2,drafts:{}},Wn}},RS=e=>{const t=JSON.stringify(e);pi=t,Wn=e,LS(t),Jf.setItem(Xf,t)},od=e=>{if(!e)return{text:"",confirmedMentions:new Set};const t=Bv().drafts[Gt(e)];return t?{text:t.text,confirmedMentions:new Set(t.confirmedMentions)}:{text:"",confirmedMentions:new Set}},us=(e,t,n)=>{if(!e)return;const r=Bv(),s=Gt(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,NS);RS({version:2,drafts:Object.fromEntries(i)})},PS=(e,t=!1)=>{us(e,"",[]),t&&Qf.forEach(n=>n(e))},DS=e=>(Qf.add(e),()=>Qf.delete(e)),id=e=>({...e,previewUrl:void 0,uploadState:e.uploadState?{...e.uploadState}:e.uploadState}),OS=["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"],HS=OS.join(","),FS=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"},VS=(e,t)=>{const n=new Set(t.map(s=>s.toLowerCase())),r=[];for(const s of e){const o=FS(s.mimeType);o&&!n.has(o)&&r.push({attachment:s,modality:o})}return r},BS=new Map([["image/png","image/png"],["image/jpeg","image/jpeg"],["image/gif","image/gif"],["image/webp","image/webp"],["application/pdf","application/pdf"]]),$S=new Map([["gif","image/gif"],["jpeg","image/jpeg"],["jpg","image/jpeg"],["pdf","application/pdf"],["png","image/png"],["webp","image/webp"]]),zS=new Set(["application/json","application/ld+json","application/toml","application/x-toml","application/x-yaml","application/xml","application/yaml","image/svg+xml"]),US=4096,ZS=new Set(["docx","pptx","xlsx","odt","odp","ods"]),zl="[REDACTED]",WS="[OMITTED BY PICHAMBER]",eh=/^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api[-_]?key|client[-_]?secret|password|secret|access[-_]?token|refresh[-_]?token|id[-_]?token|token)$/i,Cp=e=>{const t=e.lastIndexOf(".");return t===-1?"":e.slice(t+1).toLowerCase()},$v=e=>e.type.split(";",1)[0]?.trim().toLowerCase()??"",qS=async e=>{const t=new Uint8Array(await e.slice(0,US).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"},GS=e=>{const t=$v(e),n=BS.get(t);if(n)return n;const r=Cp(e.name),s=$S.get(r);return(!t||t==="application/octet-stream")&&s?s:t.startsWith("text/")||zS.has(t)||t.endsWith("+json")||t.endsWith("+xml")?"text/plain":qS(e).then(o=>o||t||"application/octet-stream")},el=e=>typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join(""):"",KS=(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=el(a.source).trimEnd();if(a.cell_type==="markdown"){s.push(`## Markdown cell ${i+1}
7
-
8
- ${c}`);return}if(a.cell_type!=="code"||(s.push(`## Code cell ${i+1}
9
-
10
- \`\`\`${r}
11
- ${c}
12
- \`\`\``),!Array.isArray(a.outputs)))return;const d=[];for(const u of a.outputs){if(!u||typeof u!="object")continue;const f=u,p=el(f.text)||el(f.traceback);if(p){d.push(p.trimEnd());continue}if(f.data&&typeof f.data=="object"){const m=f.data,g=el(m["text/plain"]);g&&d.push(g.trimEnd());const y=Object.keys(m).filter(b=>b!=="text/plain");y.length>0&&d.push(`[Non-text output omitted: ${y.join(", ")}]`);continue}(typeof f.ename=="string"||typeof f.evalue=="string")&&d.push(`${String(f.ename??"Error")}: ${String(f.evalue??"")}`.trimEnd())}d.length>0&&s.push(`### Output
13
-
14
- ${d.join(`
15
-
16
- `)}`)}),`${s.join(`
17
-
18
- `)}
19
- `},YS=e=>{try{const t=new URL(e);for(const n of Array.from(t.searchParams.keys()))eh.test(n)&&t.searchParams.set(n,zl);return t.toString()}catch{return e}},th=(e,t)=>{if(t&&eh.test(t))return zl;if(t==="cookies"&&Array.isArray(e))return e.map(s=>!s||typeof s!="object"?s:{...s,value:zl});if(t==="text"||t==="encoding")return WS;if(typeof e=="string")return t==="url"?YS(e):e;if(Array.isArray(e))return e.map(s=>th(s));if(!e||typeof e!="object")return e;const n=e,r=typeof n.name=="string"&&eh.test(n.name);return Object.fromEntries(Object.entries(n).map(([s,o])=>[s,r&&s==="value"?zl:th(o,s)]))},XS=async(e,t)=>{const n=await e.text();if(t==="har")try{const r=th(JSON.parse(n));return new File([`${JSON.stringify(r,null,2)}
20
- `],e.name,{type:"text/plain"})}catch{return}if(t==="ipynb")try{const r=KS(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"})},JS=async e=>{try{const t=(await mt(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}},ig=e=>{const t=Cp(e.name),n=$v(e);if(n==="image/heic"||n==="image/heif"||t==="heic"||t==="heif")return JS(e).then(s=>s?{file:s,mimeType:"image/jpeg"}:void 0);if(t==="har"||t==="ipynb")return XS(e,t).then(s=>s?{file:s,mimeType:"text/plain"}:void 0);const r=GS(e);return typeof r=="string"?{file:e,mimeType:r}:r?.then(s=>s?{file:e,mimeType:s}:void 0)},QS=(e,t=[])=>{if(!ZS.has(Cp(e.name))){const n=ig(e);return n instanceof Promise?n.then(r=>r?[r]:void 0):n?[n]:void 0}return mt(()=>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 ig(o);if(!i||!i.mimeType.startsWith("image/"))return;s.push(i)}return s})},eC=3,tC=3,nC=100*1024*1024,Ns=20;let Fs=0,pu=0;const bo=[],to=new Map,Yr=new Map,wc=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()))},tl=(e="attachment")=>`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`,rC=(e,t)=>{if(!(!t.startsWith("image/")||typeof URL.createObjectURL!="function"))return URL.createObjectURL(e)},lg=new Set,zv=e=>{!e||lg.has(e)||(lg.add(e),typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e))},sC=e=>{for(const t of e)zv(t.previewUrl)},oC=(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)}),Uv=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 oC(n,t.mimeType),previewUrl:void 0}})),iC=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)},aC=(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}},lC=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 Ge.setState(r=>({attachedFiles:r.attachedFiles.map(s=>s.id!==e?s:(n=!0,t(s)))})),n},Zv=()=>{for(;pu<tC&&bo.length>0;){const e=bo.shift();if(!e)continue;const t=Ge.getState().attachedFiles.find(n=>n.id===e);!t||t.source!=="local"||t.uploadState?.status!=="preparing"||(pu+=1,cC(e).finally(()=>{pu-=1,Zv()}))}},mu=e=>{bo.includes(e)||to.has(e)||(bo.push(e),Zv())},cC=async e=>{const t=Ge.getState().attachedFiles.find(a=>a.id===e);if(!t||t.source!=="local")return;const n=t.file instanceof Blob?t.file:aC(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=X(),s=(Yr.get(e)??0)+1;Yr.set(e,s);const o=new AbortController;to.set(e,o);let i=-1;Qt(e,a=>({...a,uploadState:{status:"uploading",progress:n.size>0?0:null}}));try{const a=await De.uploadAttachment(n,{filename:t.filename,mime:t.mimeType,signal:o.signal,onProgress:({loaded:d,total:u})=>{const f=u>0?Math.min(99,Math.floor(d/u*100)):null;f!==i&&(i=f??i,!(Yr.get(e)!==s||r!==X())&&Qt(e,p=>p.uploadState?.status==="uploading"?{...p,uploadState:{status:"uploading",progress:f}}:p))}},{runtimeKey:r});if(Yr.get(e)!==s||r!==X()){De.deleteAttachment(a.id,{runtimeKey:r}).catch(()=>{});return}Qt(e,d=>({...d,uploadState:{status:"ready",attachmentId:a.id,expiresAt:a.expiresAt}}));const c=setTimeout(()=>{wc.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));wc.set(e,c)}catch(a){if(Yr.get(e)!==s)return;Qt(e,c=>({...c,uploadState:{status:"failed",error:lC(a)}}))}finally{to.get(e)===o&&to.delete(e)}},nh=e=>{Yr.set(e.id,(Yr.get(e.id)??0)+1),to.get(e.id)?.abort(),to.delete(e.id);const t=wc.get(e.id);t&&clearTimeout(t),wc.delete(e.id);const n=bo.indexOf(e.id);n>=0&&bo.splice(n,1)},dC=(e,t)=>{nh(e),zv(e.previewUrl),t&&e.uploadState?.status==="ready"&&De.deleteAttachment(e.uploadState.attachmentId,{runtimeKey:X()}).catch(()=>{})},Un=(e,t)=>{for(const n of e)dC(n,t)},uC=10,fC=50*1024*1024,hC=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 cg=0;const pC=(e,t,n)=>!e||e.draftKey!==t?!1:n===e.text,Ge=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&&(cg+=1,e({sentDraftClear:{draftKey:n,text:r,nonce:cg}}))},consumeSentDraftClear:n=>{t().sentDraftClear?.nonce===n&&e({sentDraftClear:null})},addAttachedFile:async n=>{const r=Fs,s=tl("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>Ns)return Qt(s,i=>({...i,uploadState:{status:"failed",error:`You can attach up to ${Ns} files to one message.`}})),!1;for(let i=0;i<eC;i+=1){const a=t().attachedFiles.filter(p=>p.id!==s).map(p=>p.filename);let c;try{const p=QS(n,a);c=p instanceof Promise?await p:p}catch{c=null}if(r!==Fs||!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>Ns)return Qt(s,p=>({...p,uploadState:{status:"failed",error:`You can attach up to ${Ns} files to one message.`}})),!1;if(c.some(p=>p.file.size>nC))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 u=c.length>1?tl("document"):void 0,f=c.map(p=>({id:tl(),file:p.file,dataUrl:"",previewUrl:rC(p.file,p.mimeType),mimeType:p.mimeType,filename:p.file.name,size:p.file.size,source:"local",uploadState:{status:"preparing"},sourceDocumentId:u}));if(r!==Fs)return Un(f,!1),!1;if(ag(d,t().attachedFiles.filter(p=>p.id!==s))){Un(f,!1);continue}e(p=>({attachedFiles:p.attachedFiles.flatMap(m=>m.id===s?f:[m])}));for(const p of f)mu(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"}})),mu(s.id));return}Qt(n,s=>({...s,uploadState:{status:"preparing"}})),mu(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];Un(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));Un(s,!1);const o=t().stashedAttachmentsByDraft;let i=o;if(o){i={};for(const[a,c]of Object.entries(o)){const d=c.filter(u=>!r.has(u.id));sC(c.filter(u=>r.has(u.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(u=>u.id)),o=new Set,i=[];for(const u of n)s.has(u.id)||o.has(u.id)||(o.add(u.id),i.push(u));if(i.length===0)return{ok:!0,restoredCount:0,totalCount:r};if(r+i.length>Ns)return{ok:!1,reason:"attachment-limit",limit:Ns,currentCount:r,missingCount:i.length};const a=new Set(i.map(u=>u.id)),c=t().stashedAttachmentsByDraft??{},d={};for(const[u,f]of Object.entries(c)){const p=f.filter(m=>!a.has(m.id));p.length>0&&(d[u]=p)}return e(u=>({attachedFiles:[...u.attachedFiles,...i.map(id)],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,u]of Object.entries(s))d!==r&&d!==n&&(a[d]=u);o.length>0&&(a[r]=o);const c=Object.keys(a);for(;c.length>uC||hC(a)>fC;){const d=c.shift();if(!d)break;Un(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)?Un(c,!0):o[a]=c;const i=s.activeAttachmentsDraftKey!==null&&r(s.activeAttachmentsDraftKey);i&&Un(s.attachedFiles,!0),e({attachedFiles:i?[]:s.attachedFiles,stashedAttachmentsByDraft:o})},setAttachedFiles:n=>{Fs+=1;const r=new Set(n.map(s=>s.id));Un(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:()=>{Fs+=1,Un(t().attachedFiles,!0),e({attachedFiles:[]})},addRestoredAttachment:({url:n,mimeType:r,filename:s})=>{const o=tl("restored"),i=new File([],s,{type:r}),a={id:o,file:i,dataUrl:n,mimeType:r,filename:s,size:iC(n),source:"server",serverPath:n};e(c=>({attachedFiles:[...c.attachedFiles,a]}))}}));np(()=>{Fs+=1;const e=s=>s.map(o=>o.source==="local"?{...o,uploadState:{status:"failed",error:"The runtime changed. Retry the upload."}}:o),t=Ge.getState().attachedFiles;for(const s of t)nh(s);const n=Ge.getState().stashedAttachmentsByDraft??{},r={};for(const[s,o]of Object.entries(n)){for(const i of o)nh(i);r[s]=e(o)}Ge.setState({attachedFiles:e(t),stashedAttachmentsByDraft:r,pendingWorktreeRestore:null,sentDraftClear:null})});const no="oc.sessions.folders",ro="oc.sessions.folderCollapse",Sc="oc.sessions.folders.v2.index",Wv="/api/pi/session-folders",mC=250,Ft=zt(),gu=Gc();let ns=null,Ti=!1,Ul=!1,Ai=!1,Li,Ni,Ri=null,Pi=null,wo=null,In=X(),is=0,Cc=0;const kc=new Map,jr=(e,t)=>`${e}.v2:${encodeURIComponent(t)}`,kp=()=>{try{const e=JSON.parse(Ft.getItem(Sc)??"");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:[]}}},Qi=(e,t=Date.now(),n=Ft)=>{const r=kp(),s=[{runtimeKey:e,updatedAt:t},...r.runtimes.filter(o=>o.runtimeKey!==e)];n.setItem(Sc,JSON.stringify({version:2,legacyClaimed:r.legacyClaimed,runtimes:s}))},qv=e=>{const t=kp();if(t.legacyClaimed)return;const n=Ft.getItem(no),r=Ft.getItem(ro);n&&Ft.setItem(jr(no,e),n),r&&Ft.setItem(jr(ro,e),r);const s={...t,legacyClaimed:!0};Ft.setItem(Sc,JSON.stringify(s)),Ft.getItem(Sc)===JSON.stringify(s)&&(Ft.removeItem(no),Ft.removeItem(ro)),Qi(e,0)},gC=(e,t)=>{if(typeof window>"u")return;ns&&clearTimeout(ns);const n=JSON.parse(JSON.stringify(e)),r=Array.from(t),s=In,o=is;ns=setTimeout(()=>{if(ns=null,s!==X()||o!==is)return;const i=Math.max(Date.now(),(kc.get(s)??0)+1);kc.set(s,i),Tt(Wv,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:1,foldersMap:n,collapsedFolderIds:r,updatedAt:i})}).then(c=>{c.status===409&&(s!==X()||o!==is||(Ti=!1,Ai=!0,ad()))}).catch(()=>{})},mC)},dg=(e=In)=>{try{qv(e);const t=Ft.getItem(jr(no,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():"",u=typeof c.name=="string"?c.name.trim():"",f=typeof c.createdAt=="number"?c.createdAt:0;if(!d||!u)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:u,sessionIds:p,createdAt:f,parentId:m})}i.length>0&&(r[s]=i)}return r}catch{return{}}},ug=(e=In)=>{try{qv(e);const t=Ft.getItem(jr(ro,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}},Gv=e=>{Ri=e,wo=In,clearTimeout(Li),Li=setTimeout(()=>{try{const t=wo??In;Ft.setItem(jr(no,t),JSON.stringify(e)),Qi(t),Ri=null}catch{}},300)},Kv=e=>{Pi=e,wo=In,clearTimeout(Ni),Ni=setTimeout(()=>{try{const t=wo??In;Ft.setItem(jr(ro,t),JSON.stringify(Array.from(e))),Qi(t),Pi=null}catch{}},300)},Yv=()=>{Li&&clearTimeout(Li),Ni&&clearTimeout(Ni),Li=void 0,Ni=void 0;const e=wo??In;let t=!1;if(Ri!==null){const n=jr(no,e),r=JSON.stringify(Ri);Ft.setItem(n,r),gu.setItem(n,r),Ri=null,t=!0}if(Pi!==null){const n=jr(ro,e),r=JSON.stringify(Array.from(Pi));Ft.setItem(n,r),gu.setItem(n,r),Pi=null,t=!0}if(t){const n=Date.now();Qi(e,n),Qi(e,n,gu)}wo=null};if(typeof window<"u"){const e=()=>{try{Yv()}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)=>{Cc+=1,Gv(e),Kv(t),gC(e,t)},yC=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`folder_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Go=(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},Mp=Et()(or((e,t)=>({foldersMap:dg(),collapsedFolderIds:ug(),resetForRuntimeSwitch:n=>{try{Yv()}catch{}In=n,is+=1,Cc=0,Ti=!1,Ul=!1,Ai=!1,ns&&clearTimeout(ns),ns=null,e({foldersMap:dg(n),collapsedFolderIds:ug(n)}),queueMicrotask(()=>{ad()})},getFoldersForScope:n=>n?t().foldersMap[n]??[]:[],createFolder:(n,r,s)=>{const o=r.trim()||"New folder",i={id:yC(),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(u=>u.id===r?{...u,name:o}:u),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},u=t().collapsedFolderIds,f=Go(o,c,u);e(f?{foldersMap:d,collapsedFolderIds:f}:{foldersMap:d}),Zn(d,f??u)},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}),u={...o,[n]:d},f=Go(i,d,t().collapsedFolderIds);e(f?{foldersMap:u,collapsedFolderIds:f}:{foldersMap:u}),Zn(u,f??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 u=i.map(m=>{const g=m.sessionIds.filter(y=>!a.has(y));return m.id===r?{...m,sessionIds:[...g,...a]}:g.length!==m.sessionIds.length?{...m,sessionIds:g}:m}),f={...o,[n]:u},p=Go(i,u,t().collapsedFolderIds);e(p?{foldersMap:f,collapsedFolderIds:p}:{foldersMap:f}),Zn(f,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(f=>typeof f=="string"&&f.length>0));if(i.size===0)return;let a=!1;const c=o.map(f=>{const p=f.sessionIds.filter(m=>!i.has(m));return p.length!==f.sessionIds.length?(a=!0,{...f,sessionIds:p}):f});if(!a)return;const d={...s,[n]:c},u=Go(o,c,t().collapsedFolderIds);e(u?{foldersMap:d,collapsedFolderIds:u}:{foldersMap:d}),Zn(d,u??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(u=>{const f=u.sessionIds.filter(p=>p!==r);return f.length!==u.sessionIds.length?(i=!0,{...u,sessionIds:f}):u});if(!i)return;const c={...s,[n]:a},d=Go(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!==X()||!r)return;const s=t().foldersMap;let o=null;for(const[i,a]of Object.entries(s)){let c=!1;const d=a.map(u=>{const f=u.sessionIds.filter(p=>p!==r);return f.length===u.sessionIds.length?u:(c=!0,{...u,sessionIds:f})});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"})),ad=async()=>{if(typeof window>"u"||Ul||Ti&&!Ai)return;Ai=!1,Ul=!0;const e=In,t=is,n=Cc;let r=!1;try{const s=await Tt(Wv).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(f=>typeof f=="string")):new Set;if(t!==is||e!==X())return;const c=kp().runtimes.find(f=>f.runtimeKey===e)?.updatedAt??0,d=typeof o.updatedAt=="number"&&Number.isFinite(o.updatedAt)?o.updatedAt:0;d>0&&kc.set(e,Math.max(kc.get(e)??0,d)),(o.exists===!0||d>0)&&Cc===n&&d>=c&&(Mp.setState({foldersMap:i,collapsedFolderIds:a}),Gv(i),Kv(a)),r=!0}catch{}finally{t===is&&e===X()&&(Ul=!1,r&&(Ti=!0),Ai&&(Ti=!1,queueMicrotask(()=>{ad()})))}},vC=()=>{typeof window>"u"||ad()};vC();const xC=e=>{if(e.runtimeKey!==X()||!e.directory||e.directory==="global"||!e.sessionId)return;const t=rp(e.sessionId,e.directory,e.runtimeKey);t&&lt.getState().clearQueue(t),Mp.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),xS.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Eo(e.runtimeKey,e.directory,e.sessionId);n&&PS(n,!0),Ge.getState().clearStashedAttachmentsForSession(e)},ea=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},bC=e=>{let t=null;for(const n of e.messages.values())n.role==="user"&&(t=n.id);return t},Xv=e=>{const t=e?.awaitingPromptEcho?.baselineUserMessageId;return!e||e.awaitingPromptEcho===void 0?!1:bC(e)===t},wC=(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=ea(t);return n?rh(e,t,n):!1},rh=(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:CC(e,t,n),SC=(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},CC=(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(!SC(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},kC="selection-store",MC=3,fg="context-store",hg=1,so=500,ta=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fs=e=>typeof e=="string",Ip=e=>typeof e=="object"&&e!==null&&typeof e.providerId=="string"&&typeof e.modelId=="string",pg=(e,t)=>`${e}/${t}`,mg=(e,t,n)=>JSON.stringify([e,t,n]),IC=(e,t)=>JSON.stringify([e,t]),Sn=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===3&&t.every(fs))return t}catch{}return null},yu=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length===2&&t.every(fs))return t}catch{}return null},Vs=new Set,Bs=new Set,pr=new Set;let sh=!1;const _C=()=>{Vs.clear(),Bs.clear(),pr.clear(),sh=!1},ld=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},EC=e=>{const t=ld(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},nl=(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},rl=(e,t)=>{if(!e.has(t))return e;const n=new Map(e);return n.delete(t),n},Ur=(e,t=[])=>{const n=EC(e);for(const o of t){const i=n.indexOf(o);i!==-1&&n.splice(i,1),n.push(o)}if(n.length<=so){const o=e.sessionRecency;return o.length===n.length&&o.every((a,c)=>a===n[c])?e:{...e,sessionRecency:n}}const r=new Set(n.slice(0,n.length-so));let s=e.clearedVariantKeys;return s.some(o=>{const i=typeof o=="string"?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:nl(e.sessionModelSelections,r),sessionAgentSelections:nl(e.sessionAgentSelections,r),sessionAgentModelSelections:nl(e.sessionAgentModelSelections,r),sessionAgentModelVariantSelections:nl(e.sessionAgentModelVariantSelections,r),clearedVariantKeys:s,sessionRecency:n.slice(n.length-so)}},gg=(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),jC=e=>{const t=ld(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},sl=(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,TC=(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,AC=e=>{if(!ta(e))return e;try{const t=jC(e),n=ld(e.sessionRecency),r=n.length===t.length&&n.every((o,i)=>o===t[i])&&Array.isArray(e.sessionRecency)&&e.sessionRecency.length===n.length;if(t.length<=so)return r?e:{...e,sessionRecency:t};const s=new Set(t.slice(t.length-so));return{...e,sessionModelSelections:sl(e.sessionModelSelections,s),sessionAgentSelections:sl(e.sessionAgentSelections,s),sessionAgentModelSelections:sl(e.sessionAgentModelSelections,s),sessionAgentModelVariantSelections:sl(e.sessionAgentModelVariantSelections,s),clearedVariantKeys:TC(e.clearedVariantKeys,s),sessionRecency:t.slice(t.length-so)}}catch{return e}},yg=(e,t,n)=>{e.delete(t),e.set(t,n)},as=(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}},Jv=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=as(o,Ip);i.failed&&(n=!0),(i.value.size>0||o.length===0)&&t.set(s,i.value)}return{value:t,failed:n}},Qv=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 u=as(d,fs);u.failed&&(n=!0),u.value.size>0&&i.set(c,u.value)}i.size>0&&t.set(s,i)}return{value:t,failed:n}},rs=()=>({models:new Map,agents:new Map,agentModels:new Map,variants:new Map,currentAgentContext:new Map}),vg=e=>{if(e===null)return{status:"missing",failed:!1,data:rs()};let t;try{t=JSON.parse(e)}catch{return{status:"failed",failed:!0,data:rs()}}if(!ta(t))return{status:"failed",failed:!0,data:rs()};const n="state"in t?t.state:t;if(!ta(n))return{status:"failed",failed:!0,data:rs()};const r=as(n.sessionModelSelections??void 0,Ip),s=as(n.sessionAgentSelections??void 0,fs),o=Jv(n.sessionAgentModelSelections??void 0),i=Qv(n.sessionAgentModelVariantSelections??void 0),a=as(n.currentAgentContext??void 0,fs),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}}},LC=()=>{try{if(typeof window<"u"&&window.localStorage)return vg(window.localStorage.getItem(fg))}catch{return{status:"failed",failed:!0,data:rs()}}try{return vg(Gc().getItem(fg))}catch{return{status:"failed",failed:!0,data:rs()}}},NC=(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()(Yc((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)=>{Vs.add(n),sh=!0,e(o=>{const i=new Map(o.sessionModelSelections);return i.delete(n),i.set(n,{providerId:r,modelId:s}),{...Ur({...o,sessionModelSelections:i},[n]),lastUsedProvider:{providerID:r,modelID:s}}})},getSessionModelSelection:n=>t().sessionModelSelections.get(n)??null,saveSessionAgentSelection:(n,r)=>{t().sessionAgentSelections.get(n)!==r&&(Vs.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),Ur({...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||(Bs.add(IC(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),u=new Map(d.get(n)??new Map);return d.delete(n),u.set(r,{providerId:s,modelId:o}),d.set(n,u),Ur({...a,sessionAgentModelSelections:d},[n])}))},getAgentModelForSession:(n,r)=>t().sessionAgentModelSelections.get(n)?.get(r)??null,saveAgentModelVariantForSession:(n,r,s,o,i)=>{const a=pg(s,o),c=mg(n,r,a);if(i===void 0){if(t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0){t().hasHydrated||(pr.add(c),e(u=>u.clearedVariantKeys.includes(c)?u:Ur({...u,clearedVariantKeys:[...u.clearedVariantKeys,c]},[n])));return}pr.add(c),e(u=>{if(u.sessionAgentModelVariantSelections.get(n)?.get(r)?.get(a)===void 0)return u;const f=new Map(u.sessionAgentModelVariantSelections),p=new Map(f.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?f.delete(n):(f.delete(n),f.set(n,p));const g=u.clearedVariantKeys.includes(c)?u.clearedVariantKeys:[...u.clearedVariantKeys,c];return Ur({...u,sessionAgentModelVariantSelections:f,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 u=new Map(d.sessionAgentModelVariantSelections),f=new Map(u.get(n)??new Map),p=new Map(f.get(r)??new Map);return u.delete(n),p.set(a,i),f.set(r,p),u.set(n,f),Ur({...d,sessionAgentModelVariantSelections:u},[n])}))},getAgentModelVariantForSession:(n,r,s,o)=>{const i=pg(s,o);return t().sessionAgentModelVariantSelections.get(n)?.get(r)?.get(i)},forgetSession:n=>{if(!(!n||!gg(t(),n))){Vs.delete(n);for(const r of Array.from(Bs))yu(r)?.[0]===n&&Bs.delete(r);for(const r of Array.from(pr))Sn(r)?.[0]===n&&pr.delete(r);e(r=>{if(!gg(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:rl(r.sessionModelSelections,n),sessionAgentSelections:rl(r.sessionAgentSelections,n),sessionAgentModelSelections:rl(r.sessionAgentModelSelections,n),sessionAgentModelVariantSelections:rl(r.sessionAgentModelVariantSelections,n),clearedVariantKeys:s,sessionRecency:o}})}}}),{name:kC,version:MC,storage:tp(),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:ta(e)?r=e:(n=!0,r=void 0);const s=as(r?.sessionModelSelections??void 0,Ip),o=as(r?.sessionAgentSelections??void 0,fs),i=Jv(r?.sessionAgentModelSelections??void 0),a=Qv(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 S=r.lastUsedProvider;S===null||ta(S)&&typeof S.providerID=="string"&&typeof S.modelID=="string"?c=S:n=!0}let d=[];if(r?.clearedVariantKeys!==void 0){const S=r.clearedVariantKeys;Array.isArray(S)&&S.every(fs)?d=[...S]:n=!0}const u=r?.contextStoreMigrationVersion===hg,f=u?{status:"missing",failed:!1,data:rs()}:LC(),p=f.failed,m=new Map(s.value),g=new Map(o.value),y=new Map(Array.from(i.value.entries()).map(([S,w])=>[S,new Map(w)])),b=new Map(Array.from(a.value.entries()).map(([S,w])=>[S,new Map(Array.from(w.entries()).map(([M,I])=>[M,new Map(I)]))])),k=new Set([...d,...t.clearedVariantKeys]);if(f.status==="ok"||f.status==="failed"){const S=f.data;for(const[w,M]of S.models)m.has(w)||m.set(w,M);for(const[w,M]of S.agents)g.has(w)||g.set(w,M);for(const[w,M]of S.currentAgentContext)g.has(w)||g.set(w,M);for(const[w,M]of S.agentModels){let I=y.get(w);I||(I=new Map,y.set(w,I));for(const[E,_]of M)I.has(E)||I.set(E,_)}for(const[w,M]of S.variants)for(const[I,E]of M)for(const[_,T]of E){if(k.has(mg(w,I,_)))continue;let A=b.get(w);A||(A=new Map,b.set(w,A));let j=A.get(I);j||(j=new Map,A.set(I,j)),j.has(_)||j.set(_,T)}}for(const S of Vs){const w=t.sessionModelSelections.get(S);w&&yg(m,S,w);const M=t.sessionAgentSelections.get(S);M!==void 0&&yg(g,S,M)}for(const S of Bs){const w=yu(S);if(!w)continue;const[M,I]=w,E=t.sessionAgentModelSelections.get(M)?.get(I);if(!E)continue;let _=y.get(M);_||(_=new Map,y.set(M,_)),_.set(I,E),y.delete(M),y.set(M,_)}for(const S of pr){const w=Sn(S);if(!w)continue;const[M,I,E]=w,_=t.sessionAgentModelVariantSelections.get(M)?.get(I)?.get(E);if(_!==void 0){let T=b.get(M);T||(T=new Map,b.set(M,T));let A=T.get(I);A||(A=new Map,T.set(I,A)),A.set(E,_)}else NC(b,M,I,E)}sh&&t.lastUsedProvider!==null&&(c=t.lastUsedProvider);const v=new Set;for(const S of Vs)v.add(S);for(const S of Bs){const w=yu(S);w&&v.add(w[0])}for(const S of pr){const w=Sn(S);w&&v.add(w[0])}const x=Ur({sessionModelSelections:m,sessionAgentSelections:g,sessionAgentModelSelections:y,sessionAgentModelVariantSelections:b,clearedVariantKeys:Array.from(k),sessionRecency:ld(r?.sessionRecency)},Array.from(v)),C=u||!n&&!p;return _C(),{...t,sessionModelSelections:x.sessionModelSelections,sessionAgentSelections:x.sessionAgentSelections,sessionAgentModelSelections:x.sessionAgentModelSelections,sessionAgentModelVariantSelections:x.sessionAgentModelVariantSelections,lastUsedProvider:c,hasHydrated:!0,clearedVariantKeys:C?[]:x.clearedVariantKeys,sessionRecency:x.sessionRecency,contextStoreMigrationVersion:C?hg:t.contextStoreMigrationVersion}},migrate:e=>AC(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 _p=(e,t)=>`${e}::${t}`,jo=Et(e=>({byKey:new Map,setEntry:t=>e(n=>{const r=new Map(n.byKey);return r.set(_p(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"&&pn(e=>{e.runtimeKey!==e.previousRuntimeKey&&e.previousRuntimeKey&&jo.getState().clearForRuntime(e.previousRuntimeKey)});const RC=(e,t,n)=>{const r=X();jo.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()})},vu=e=>{jo.getState().clearForSession(e)},xu=()=>{jo.getState().clearAll()},Ep=e=>{const t=X();return jo.getState().byKey.get(_p(t,e))},PC=e=>jo(t=>{if(e)return t.byKey.get(_p(X(),e))}),jp=e=>{const t=["~"],n=r=>{const s=ce(r);s&&!t.includes(s)&&t.push(s)};n(e);try{n(zt().getItem("homeDirectory"))}catch{}try{typeof window<"u"&&n(window.__PICHAMBER_HOME__)}catch{}return t},DC=(e,t)=>{const n=ce(e);return!!(n&&jp(t).includes(n))},oh=()=>({byId:new Map,byDirectory:new Map,listStatusByDirectory:new Map}),mi=(e,t,n,r,s)=>{if(e.byId.has(t))return e;const o=Tr(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),u=new Map(e.byDirectory);return d&&d.includes(t)?u.set(o,d):d?u.set(o,[t,...d]):u.set(o,[t]),{...e,byId:c,byDirectory:u}},Tr=e=>ce(e)??e,e3=(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,OC=(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])},HC=(e,t)=>e===t||!!e&&!!t&&e.attempt===t.attempt&&e.next===t.next&&e.message===t.message,FC=(e,t,n,r,s)=>{const o=Tr(t),i=[];let a=null,c=null;for(const m of n){const g=m?.session;if(!g?.id||!g.directory)continue;const y=Tr(g.directory);if(y!==o)continue;const b=typeof g.timeArchived=="number"?g.timeArchived>0:!!g.archived,k=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,C=x?x.lifecycle:k?.lifecycle??"idle",S=x?.lifecycle==="retry"?x.retry??{}:void 0,w=x?HC(k?.retry,S)?k?.retry:S:k?.retry,M={id:g.id,directory:y,parentId:g.parentId??null,title:g.title??"",archived:b,createdAt:g.createdAt,updatedAt:k?k.updatedAt:v,...typeof m.preview=="string"?{preview:m.preview}:{},...typeof g.messageCount=="number"?{messageCount:g.messageCount}:{},lifecycle:C,...w?{retry:w}:{},hydrated:k?.hydrated??!1};if(k&&e3(k,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 u=e.byDirectory.get(o)??[],f=u.length!==i.length||u.some((m,g)=>m!==i[g]);if(!a&&!f){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)),OC(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}},VC=(e,t)=>{const n=Tr(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}},BC=(e,t)=>{const n=Tr(t);if(e.listStatusByDirectory.get(n)==="failed")return e;const s=new Map(e.listStatusByDirectory);return s.set(n,"failed"),{...e,listStatusByDirectory:s}},Rs=(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}},bu=(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}},wu=(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}},xg=(e,t,n,r)=>{const s=e.byId.get(t);if(!s){if(!r)return e;const i=mi(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}},$C=(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}},bg=(e,t)=>{const n=e.byId.get(t.id);if(n&&e3(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}},zC=(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}},wg=new WeakMap,oo=e=>{const t=wg.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 wg.set(e,n),n},Sg=[],t3=(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},na=(e,t)=>{const n=t?.archived??!1,r=t?.directory;let s;if(typeof r=="string"&&r.length>0){const i=Tr(r),a=e.byDirectory.get(i)??[],c=jp();if(!c.includes(i))s=a;else{const d=[],u=new Set(a);for(const f of c){if(f===i)continue;const p=e.byDirectory.get(f);if(p)for(const m of p)u.has(m)||(u.add(m),d.push(m))}s=d.length>0?[...a,...d]:a}}else{if(r===null||r==="")return Sg;s=[...e.byId.keys()]}const o=[];for(const i of s){const a=e.byId.get(i);a&&!!a.archived===n&&o.push(oo(a))}return o.length===0?Sg:o},UC=e=>{const t=[];for(const n of e.byId.values())(n.lifecycle==="busy"||n.lifecycle==="retry")&&t.push(n);return t},SZ=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("|")},Su=(e,t,n,r,s,o,i)=>{const a=Tr(n),c=[],d=[],u=new Set;for(const O of r){const L=O?.session;!L?.id||!L.directory||Tr(L.directory)===a&&(u.has(L.id)||(u.add(L.id),c.push(L.id),d.push(O)))}const f=new Set(c),p=e.byDirectory.get(a)??[],m=t.byDirectory.get(a)??[],g=new Set(p),y=new Set;for(const O of g)t.byId.has(O)||y.add(O);const b=new Map,k=new Map,v=new Map,x=new Map,C=new Set,S=new Set;for(const O of p)S.add(O);for(const O of m)S.add(O);for(const O of c)S.add(O);for(const O of S){const L=t.byId.get(O);if(!L)continue;const P=e.byId.get(O);if(P===L)continue;if(L.directory!==a){P&&(P.directory===a||g.has(O)||f.has(O))&&C.add(O);continue}if(!P){if(f.has(O))continue;b.set(O,L);continue}const W=L.title!==P.title,F=L.archived!==P.archived;if(f.has(O)){(W||F)&&x.set(O,{rec:L,titleChanged:W,archivedChanged:F});continue}W||F?k.set(O,L):v.set(O,L)}const w=d.filter(O=>{const L=O.session.id;return!(y.has(L)||o?.has(L)||C.has(L))}),M=FC(t,a,w,s,i);let I=null;for(const[O,L]of x){const P=M.byId.get(O);if(!P){k.set(O,L.rec);continue}const W=L.titleChanged?L.rec.title:P.title,F=L.archivedChanged?L.rec.archived:P.archived;(P.title!==W||P.archived!==F)&&(I||(I=new Map(M.byId)),I.set(O,{...P,title:W,archived:F}))}if(b.size===0&&k.size===0&&v.size===0&&!I)return M;const E=I??M.byId,_=M.byDirectory.get(a)??[],T=new Set(_),A=new Map([...b,...k,...v]),j=[];for(const O of m)A.has(O)&&!T.has(O)&&j.push(O);let N=null;if(j.length>0){N=new Map(M.byDirectory),N.set(a,[...j,..._]),I||(I=new Map(E));for(const O of j){const L=A.get(O);L&&I.set(O,L)}}return!I&&!N?M:{byId:I??M.byId,byDirectory:N??M.byDirectory,listStatusByDirectory:M.listStatusByDirectory}},ZC=2,WC=(e,t)=>Tf([...e],ZC,async n=>t(n)),Cg="*",St="catalog",ol="dialogs",jt="chrome",Cu=16,kg=2,qC=5,GC=300,KC=new Set(["DAEMON_UNAVAILABLE","DAEMON_TIMEOUT","DAEMON_START_TIMEOUT","DAEMON_SPAWN_FAILED","DAEMON_REQUEST_FAILED"]),il=e=>e==="busy"||e==="retry"?e:e==="error"?"error":"idle",n3=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 ut?e:new ut("DAEMON_REQUEST_FAILED",e instanceof Error?e.message:void 0),Ko=e=>e instanceof ut&&e.code==="INVALID_SESSION",ku=e=>e instanceof ut&&e.code==="SESSION_IN_USE",YC=e=>e instanceof ut&&e.code==="SESSION_RUNTIME_CONFLICT",Mg=async()=>{await new Promise(e=>setTimeout(e,GC))},al=(e=oh())=>({directory:null,sessions:[],selectedSessionId:null,reducer:uc(),connection:"loading",error:null,showArchived:!1,hydratedSessionIds:new Set,sessionLoadErrorById:new Map,focusPending:!1,sessionsListStatus:"idle",catalog:e,syncReadiness:"ready",syncRecovery:{directories:[],residents:[]}}),XC=(e,t,n)=>{const r=n?.now??Date.now(),s=t.byId.get(e.id),o=ce(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}:{},lifecycle:s?.lifecycle??"idle",hydrated:s?.hydrated??!1}},JC=(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;if(t.messages.size===0&&!o)return e;const c={...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:dc(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}:{}}:{},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(o||a){for(const[d,u]of t.messages)(o||!c.messages.has(d))&&Y9(c,d,u);for(const[d,u]of t.partOrder)if(!(!o&&c.partOrder.has(d))){c.partOrder.set(d,u);for(const f of u){const p=t.parts.get(f);p&&c.parts.set(f,p)}}for(const[d,u]of t.toolsByCallId)(o||!c.toolsByCallId.has(d))&&c.toolsByCallId.set(d,u)}return c};let Ig=null;const QC=new Set(["session.snapshot","session.interrupted","session.deleted"]),_g=e=>n3(e)!==void 0||QC.has(e.name),Je=()=>(Ig??=new Tp,Ig);class Tp{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||ce(r.directory)===ce(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;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 u=Math.max(this.lifecycleSequenceById.get(c)??-1,this.hydratedSessionIds.has(c)?this.state.reducer.lastSequence.get(c)??-1:-1);if(d<u)return!1;if(this.pendingPromptById.has(c)){const f=this.promptGenerationById.get(c);return f!==void 0&&this.acceptedPromptGenerationById.get(c)===f&&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 u=d.live;if(!u||!s.has(d.session.id))continue;const f=d.session.id;(this.lifecycleSequenceById.get(f)??-1)<u.sequence&&this.lifecycleSequenceById.set(f,u.sequence),!(u.lifecycle==="idle"||typeof u.runStartedAt!="number")&&this.state.catalog.byId.get(f)?.lifecycle===u.lifecycle&&vn(f,u.runStartedAt,u.serverNow)}}}}}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:uc(),hydratedSessionIds:new Set(this.hydratedSessionIds)},this.queueSyncRecovery({directories:"all-known",residents:r}),r}handleVerifiedEpochChange(t){const n=this.applyVerifiedEpochChange(t);n&&this.emit([jt,St,...[...n].map(r=>`session:${r}`)])}resetForEpochChange(){const t=new Set(this.hydratedSessionIds);this.lifecycleSequenceById.clear(),this.hydratedSessionIds.clear(),this.restoringTranscriptById.clear(),this.hydrateInflightById.clear(),this.historyInflightById.clear(),this.clearTranscriptPrefetch();for(const[n,r]of this.navigationGenerationById)this.navigationGenerationById.set(n,r+1);return this.settleCarriedOverActivity(),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=Rs(t,n.id,"idle"),Q1(n.id));t!==this.state.catalog&&(this.state={...this.state,catalog:t})}queueSyncRecovery(t){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=ce(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=X(),r=this.streamEpoch,s=this.recoveryRevision,o=()=>t===this.runtimeGeneration&&n===X()&&r===this.streamEpoch&&s===this.recoveryRevision;try{const i=this.state.selectedSessionId,a=[...this.recoveryResidents].sort((u,f)=>u===i?-1:f===i?1:0);if(await Tf(a,kg,async u=>{if(!o()||!this.recoveryResidents.has(u))return;if(this.isDeleted(u)){this.recoveryResidents.delete(u);return}const f=this.resolveSessionDirectory(u)??this.state.directory??void 0;if(f){try{const p=await De.getSession(u,{directory:f,runtimeKey:n});if(!o()||p.session.id!==u)return;if(this.isDeleted(u)){this.recoveryResidents.delete(u);return}if(!this.isResponseEpochCurrent(p)||!o())return;const m=this.state.reducer.bySession.get(u);(!m||m.lastSequence<=p.lastSequence)&&((p.lifecycle==="busy"||p.lifecycle==="retry")&&typeof p.runStartedAt=="number"&&vn(p.session.id,p.runStartedAt,p.serverNow),this.commitHydratedSession(this.sessionFromDetail(p))),this.recoveryResidents.delete(u)}catch(p){o()&&Ko(p)&&(this.commitDeletion(u,f),this.recoveryResidents.delete(u))}this.publishSyncRecoveryState()}}),!o())return;const c=this.state.directory?ce(this.state.directory):null,d=[...this.recoveryDirectories].sort((u,f)=>u===c?-1:f===c?1:0);await Tf(d,kg,async u=>{if(o()&&this.recoveryDirectories.has(u)){try{(await this.refreshDirectoryCatalog(u)).ok&&o()&&this.recoveryDirectories.delete(u)}catch{}this.publishSyncRecoveryState()}})}finally{this.recoveryRunning=!1,t===this.runtimeGeneration&&n===X()&&(this.recoveryDirectories.size>0||this.recoveryResidents.size>0)&&(s!==this.recoveryRevision||r!==this.streamEpoch)&&this.runSyncRecovery()}if(!(t!==this.runtimeGeneration||n!==X())&&(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<=qC){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>Tp.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(v=>v.session.id===t)?.session.directory??this.state.reducer.bySession.get(t)?.directory;if(o&&o!=="global")try{xC({runtimeKey:X(),directory:o,sessionId:t})}catch{}try{_t.getState().forgetSession(t)}catch{}Q1(t),SS(t),vu(t),this.navigationGenerationById.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(v=>v.session.id===t),a=this.state.sessions.filter(v=>v.session.id!==t),c=this.state.selectedSessionId===t?a.find(v=>!v.session.archived)?.session.id??null:this.state.selectedSessionId,d=new Map(this.state.reducer.bySession);d.delete(t);const u=new Map(this.state.reducer.lastSequence);s&&u.delete(s);const f=this.state.reducer.lastSequence.get(t);f!==void 0?u.set(t,f):u.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 p=zC(this.state.catalog,t),m=p!==this.state.catalog,g=c!==this.state.selectedSessionId;let y=this.state.sessionLoadErrorById;if(y.has(t)){const v=new Map(y);v.delete(t),y=v}const b=y!==this.state.sessionLoadErrorById;if(!i&&r&&!m&&!g&&!b)return!1;this.state={...this.state,sessions:a,selectedSessionId:c,hydratedSessionIds:new Set(this.hydratedSessionIds),reducer:{bySession:d,lastSequence:u},catalog:p,sessionLoadErrorById:y};const k=[`session:${t}`,jt];return m&&k.push(St),this.emit(k),!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 B8(t=>this.commitEvents(t));catalogCache;unsubscribeRuntime;constructor(t=o6()){this.catalogCache=t,this.state=al(this.readCachedCatalog(X())),this.unsubscribeRuntime=pn(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=Cg)=>{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)}};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.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=ce(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(oo(i))}s.length>0&&kS(s)}recordClusterConnectionChange(t,n){this.state.connection!==t&&wr("pi-connection",{code:t,detail:(t==="error"||t==="unavailable")&&n?n.code:void 0})}dispose=()=>{this.catalogCache.flush(),this.resetLiveRuntimeState(),this.unsubscribeRuntime(),xu(),this.navigationGenerationById.clear(),this.navigationCounter=0;const t=al();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||!KC.has(t.code))return;const n=this.runtimeGeneration,r=X(),s=this.streamGeneration+1;this.streamGeneration=s;const o=this.streamCursor();let i=null;i=lc({onEvent:()=>{},onAuthRequired:()=>this.handleStreamAuthRequired(),onReconnect:()=>{if(n!==this.runtimeGeneration||r!==X()||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 ut("DAEMON_AUTH_FAILED","The Pi runtime rejected the client authorization.")),Tw()}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={...al(),connection:"ready"},xu(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()};async refreshDirectoryCatalog(t){const n=ce(t);if(!n)return{ok:!1,error:xn(new ut("INVALID_ARGUMENT","directory is required"))};const r=X(),s=(this.directoryRefreshGenerationByDirectory.get(n)??0)+1;this.directoryRefreshGenerationByDirectory.set(n,s);const o=this.runtimeGeneration,i=this.state.catalog,a=VC(this.state.catalog,n);a!==this.state.catalog&&(this.state={...this.state,catalog:a},this.emit([St]));try{const c=await De.listSessions({directory:n,runtimeKey:r});if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==X())return{ok:!0};if(!this.isResponseEpochCurrent(c))throw new ut("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const d=this.filterDeletedListItems(c.sessions),u=this.createListLiveGate(c),f=Su(i,this.state.catalog,n,d,Date.now(),this.deletedSessionIds,u.options);return f!==this.state.catalog?(this.state={...this.state,catalog:f},u.commit(d),this.emit([St]),this.raiseOrderingBaselinesForDirectory(n)):u.commit(d),{ok:!0}}catch(c){if(this.directoryRefreshGenerationByDirectory.get(n)!==s)return{ok:!0};if(o!==this.runtimeGeneration)return{ok:!0};if(r!==X())return{ok:!0};const d=xn(c),u=BC(this.state.catalog,n),f=ce(this.state.directory)===n,p=[];return u!==this.state.catalog&&(this.state={...this.state,catalog:u},p.push(St)),f&&(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=>ce(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 u=`${r}\0${d}`,f=this.pendingCatalogPassByKey.get(u);if(f){s.push(f);continue}o.push(d);const p=new Promise(m=>i.set(d,m));a.set(d,p),this.pendingCatalogPassByKey.set(u,p)}const c=WC(o,async d=>{const u=`${r}\0${d}`;try{return await this.refreshDirectoryCatalog(d)}finally{this.pendingCatalogPassByKey.get(u)===a.get(d)&&this.pendingCatalogPassByKey.delete(u),i.get(d)?.()}});try{await Promise.all([c,...s])}finally{for(const d of o){const u=`${r}\0${d}`;this.pendingCatalogPassByKey.get(u)===a.get(d)&&this.pendingCatalogPassByKey.delete(u),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 De.getSession(t.sessionId,{...r?{}:{directory:n??void 0},runtimeKey:X()});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 De.listProjects({runtimeKey:X()}),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 De.health({runtimeKey:X()});if(t!==this.runtimeGeneration)return;if(n.state!=="ready")throw new ut(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,X()),this.emit([jt,St])}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===X()&&r===this.streamGeneration,o=this.streamEpoch?this.streamCursor():void 0;this.stream=lc({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=ce(r)===ce(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=X(),o=this.runtimeGeneration,i=this.state.catalog;let a=this.pendingPreferredSessionId,c=n;try{try{const x=await De.selectProject(n,{runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;c=x.directory,ce(c)!==ce(this.state.directory)&&(this.state={...this.state,directory:c},this.emitChrome())}catch(x){if(!this.shouldRetryFocusError(x))throw x;if(await Mg(),t!==this.focusGeneration||o!==this.runtimeGeneration)return;c=(await De.selectProject(n,{runtimeKey:s})).directory,ce(c)!==ce(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 u={sessions:this.filterDeletedListItems(d.payload.sessions)};if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;a=this.newerSelection(r,c)??a;let f=a?u.sessions.find(x=>x.session.id===a):void 0;if(a&&!f&&!this.isDeleted(a))try{const x=await De.getSession(a,{directory:c,runtimeKey:s});if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;if(x?.session?.id)if(x.session.directory&&ce(x.session.directory)!==ce(c)&&t===this.focusGeneration){if(!this.newerSelection(r,c)){await this.focusProject(x.session.directory,a);return}}else u.sessions.unshift({session:x.session,updatedAt:x.session.updatedAt}),f={session:x.session,updatedAt:x.session.updatedAt}}catch(x){if(t!==this.focusGeneration||o!==this.runtimeGeneration)return;Ko(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)??f?.session.id??(m?a:u.sessions.find(x=>!x.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const y=this.createListLiveGate(d.payload),b=Su(i,this.state.catalog,c,u.sessions,Date.now(),this.deletedSessionIds,y.options),k=b!==this.state.catalog;this.state={...this.state,sessions:u.sessions,selectedSessionId:g,sessionsListStatus:"ready",focusPending:!!g&&!this.hydratedSessionIds.has(g),error:null,catalog:b},y.commit(u.sessions);const v=[jt];k&&v.push(St),this.emit(v),k&&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 ut){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 De.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(o))throw new ut("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 Mg(),n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};try{const i=await De.listSessions({directory:t,runtimeKey:s});if(n!==this.focusGeneration||r!==this.runtimeGeneration)return{kind:"stale"};if(!this.isResponseEpochCurrent(i))throw new ut("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=De.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(ce(t)===ce(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||ce(this.userSelection.directory)===ce(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=X(),a=this.state.catalog;this.pendingPreferredSessionId&&this.startTranscriptPrefetch(this.pendingPreferredSessionId,t,i,r);try{const c=await De.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 u=await De.health(d);if(r!==this.runtimeGeneration)return;if(u.state!=="ready")throw new ut(u.error?.code??"DAEMON_UNAVAILABLE",u.error?.message);const f=u.streamEpoch;typeof f=="string"&&f.length>0&&this.streamEpoch!==null&&f!==this.streamEpoch?(this.applyVerifiedEpochChange(f),this.emit([jt,St])):this.adoptStreamEpoch(f);const p={state:"ready",protocolVersion:u.protocolVersion,capabilities:[...u.capabilities],...typeof u.streamEpoch=="string"?{streamEpoch:u.streamEpoch}:{}},m=await De.listSessions(d);if(r!==this.runtimeGeneration)return;if(!this.isResponseEpochCurrent(m))throw new ut("DAEMON_REQUEST_FAILED","Session list predates the current stream epoch");const g=this.filterDeletedListItems(m.sessions),y=this.newerSelection(o,c.directory)??this.pendingPreferredSessionId??n;let b=y?g.find(E=>E.session.id===y):void 0,k=null;if(y&&!b&&!this.isDeleted(y))try{const E=await(this.takeTranscriptPrefetch(y,t,i,r)??De.getSession(y,{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,y);return}}else E?.session?.id&&(g.unshift({session:E.session,updatedAt:E.session.updatedAt}),b={session:E.session,updatedAt:E.session.updatedAt},k=E)}catch(E){if(r!==this.runtimeGeneration)return;Ko(E)&&this.commitDeletion(y,t)}const v=this.newerSelection(o,c.directory),x=y&&!this.isDeleted(y),C=(v&&!this.isDeleted(v)?v:null)??b?.session.id??(x?y:g.find(E=>!E.session.archived)?.session.id??null);this.pendingPreferredSessionId=null;const S=this.createListLiveGate(m,{streamAttaching:!0}),w=Su(a,this.state.catalog,c.directory,g,Date.now(),this.deletedSessionIds,S.options),M=w!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,sessions:g,selectedSessionId:C,connection:"ready",catalog:w},S.commit(g);const I=[jt];if(M&&I.push(St),this.emit(I),M&&this.raiseOrderingBaselinesForDirectory(c.directory),C){let E;C===y?E=k??await this.consumeTranscriptPrefetch(C,t,i,r):this.clearTranscriptPrefetch(),await this.hydrate(C,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&&ce(r)!==ce(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(ce(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(ce(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&&!qe.getState().isInitialized){const f=await De.getSettings({directory:r,runtimeKey:X()});o??=f.pichamber.defaultModel,i=j1({thinking:i,model:o,defaultThinkingByModel:f.pichamber.defaultThinkingByModel,defaultThinking:f.pichamber.defaultThinking})}else if(!i){const f=qe.getState();i=j1({model:o,defaultThinkingByModel:f.settingsDefaultThinkingByModel,defaultThinking:f.settingsDefaultThinking})}const a=await De.createSession({cwd:r,...t?{title:t}:{},...o?{model:o}:{},...i?{thinking:i}:{}},{directory:r,runtimeKey:X()});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=bg(this.state.catalog,this.recordFromPiSession(a.session)),d=c!==this.state.catalog;this.state={...this.state,catalog:c};const u=[jt];return d&&u.push(St),this.emit(u),await this.hydrate(a.session.id,s,a),a.session.id}async rename(t,n){const r=this.runtimeGeneration,s=X();if(await De.renameSession({sessionId:t,title:n},this.scope()),r!==this.runtimeGeneration||s!==X())return;const o=Date.now(),i=wu(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(St),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=X(),i=this.resolveSessionDirectory(t,r);if(await De.archiveSession({sessionId:t,archived:n},this.scope(i)),s!==this.runtimeGeneration||o!==X())return;const a=Date.now(),c=$C(this.state.catalog,t,n,a),d=c!==this.state.catalog;this.state={...this.state,sessions:this.state.sessions.map(f=>f.session.id===t?{...f,session:{...f.session,archived:n}}:f),catalog:c};const u=[jt];d&&u.push(St),this.emit(u)}async remove(t,n){const r=this.runtimeGeneration,s=X(),o=this.resolveSessionDirectory(t,n);if(await De.deleteSession({sessionId:t,ignoreMissing:!0},o?this.scope(o):this.scope()),r!==this.runtimeGeneration||s!==X())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=X(),i=await De.forkSession({sessionId:t,...n?{messageId:n}:{}},this.scope());if(s!==this.runtimeGeneration||o!==X())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=X(),s=await De.cloneSession({sessionId:t},this.scope());n!==this.runtimeGeneration||r!==X()||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 De.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);const u=c.navigation;if(u&&typeof u.targetEntryId=="string"&&c.hasMoreBefore!==!0){const f=new Set(c.messages.map(b=>b.message.id)),p=s.filter(b=>!f.has(b.id)).map(b=>{const k=(o.get(b.id)??"").replace(/\s+/g," ").slice(0,120)||"[No text]",v=b.role==="assistant"?"assistant":"user";return{id:b.id,role:v,preview:k}}),m=Ep(t),g=new Set(p.map(b=>b.id)),y=[...p];for(const b of m?.abandoned??[])!f.has(b.id)&&!g.has(b.id)&&(y.push(b),g.add(b.id));y.length===0?vu(t):RC(t,m?{...u,previousLeafId:m.previousLeafId}:u,y)}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??X(),c={directory:this.resolveSessionDirectory(t,o?.directory),runtimeKey:a,...o?.streamEpoch?{streamEpoch:o.streamEpoch}:{}};if(a!==X())throw new Error("Runtime changed before sending message.");let d=this.state.reducer.bySession.get(t);const u=o?.knownEmptyTranscript===!0&&this.hydratedSessionIds.has(t)&&d!==void 0&&d.messages.size===0;if((!d||d.messages.size===0)&&!u){if(await this.hydrate(t,i),i!==this.runtimeGeneration||a!==X())throw new Error("Runtime changed before sending message.");d=this.state.reducer.bySession.get(t)}const f=o?.operationId??Aw(),p={sessionId:t,text:n,operationId:f,messageId:`msg_${f}`,...s?.length?{attachments:s}:{}},m=d?{...d,lifecycle:"busy"}:{sessionId:t,directory:this.state.directory??this.state.sessions.find(C=>C.session.id===t)?.session.directory??"",lastSequence:this.state.reducer.lastSequence.get(t)??-1,lifecycle:"busy",messages:new Map,partOrder:new Map,parts:dc(),toolsByCallId:new Map,streamingMessages:new Set,queue:{steering:0,followUp:0},extensionStatuses:new Map,extensionWidgets:new Map,extensionDialogs:[],extensionNotices:[],extensionErrors:[],extensionPanels:new Map,extensionApps:new Map};if(r==="prompt"){let C=null;if(d)for(const S of d.messages.values())S.role==="user"&&(C=S.id);m.awaitingPromptEcho={baselineUserMessageId:C}}else m.awaitingPromptEcho=void 0;const g=new Map(this.state.reducer.bySession);g.set(t,m),this.state={...this.state,reducer:{...this.state.reducer,bySession:g}};const y=(this.promptGenerationById.get(t)??0)+1;this.promptGenerationById.set(t,y),this.pendingPromptById.add(t),this.promoteSession(t,"active",{reorder:!0}),this.touchSessionList(t);const b=Date.now(),k=xg(Rs(this.state.catalog,t,"busy"),t,b,{directory:m.directory||this.state.directory||"",lifecycle:"busy"}),v=k!==this.state.catalog;this.state={...this.state,catalog:k};const x=[`session:${t}`,jt];v&&x.push(St),this.emit(x);try{let C;return r==="steer"?C=await De.sendSteer(p,c):r==="followUp"?C=await De.sendFollowUp(p,c):C=await De.sendPrompt(p,c),this.promptGenerationById.get(t)===y&&this.acceptedPromptGenerationById.set(t,y),vu(t),r==="prompt"&&n.trimStart().startsWith("/")&&this.reconcileAcceptedSlashPrompt(t,y,i),C}catch(C){if(Lw("prompt-send",C),i!==this.runtimeGeneration||a!==X())throw C;if(ku(C)&&this.failSessionLoad(t,C),this.promptGenerationById.get(t)===y){this.pendingPromptById.delete(t);const S=this.state.reducer.bySession.get(t);if(S?.lifecycle==="busy"&&S.streamingMessages.size===0){const w=new Map(this.state.reducer.bySession);w.set(t,{...S,lifecycle:"error",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:w}},this.promoteSession(t,"settled"),this.emit([`session:${t}`,jt])}}throw C}}async reconcilePendingPromptSnapshot(t,n,r){const o=this.state.reducer.bySession.get(t)?.directory||this.resolveSessionDirectory(t)||this.state.directory;if(!o)return!1;try{const i=await De.getSession(t,{directory:o,runtimeKey:X()});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 u=new Map(this.state.reducer.bySession);u.set(t,{...d,lifecycle:"idle",awaitingPromptEcho:void 0}),this.state={...this.state,reducer:{...this.state.reducer,bySession:u}}}}return this.commitHydratedSession(this.sessionFromDetail(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=>De.abortSession({sessionId:t},this.scope());compact=(t,n)=>De.compactSession({sessionId:t,...n?{customInstructions:n}:{}},this.scope());setModel=(t,n,r)=>De.setSessionModel({sessionId:t,model:{providerId:n,modelId:r}},this.scope());setThinking=(t,n)=>De.setSessionThinking({sessionId:t,thinking:n},this.scope());tree=t=>De.getSessionTree(t,this.scope());providers=()=>De.listProviders({runtimeKey:X()});upload=t=>De.createAttachment(t,this.scope());uploadFile=(t,n)=>De.uploadAttachment(t,n,this.scope());deleteUpload=t=>De.deleteAttachment(t,this.scope());selected(){const t=this.state.selectedSessionId,n=t?this.state.reducer.bySession.get(t):void 0;return n?sv(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=b8(this.state.reducer,t,n);r!==this.state.reducer&&(this.state={...this.state,reducer:r},this.emit([`session:${t}`,ol]))}sessionFromDetail(t){return fc(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=X(),c=De.getSessionMessages(t,{before:i},{directory:r.directory,runtimeKey:a}).then(d=>{if(s!==this.runtimeGeneration||a!==X()||(this.navigationGenerationById.get(t)??0)!==o)return!1;const u=this.state.reducer.bySession.get(t);if(!u||u.beforeCursor!==i||d.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(d))return!1;const f=fc(d).session,p=new Map(f.messages);for(const[v,x]of u.messages)p.set(v,x);const m=new Map(f.partOrder);for(const[v,x]of u.partOrder)m.set(v,x);const g=dc(f.parts);for(const[v,x]of u.parts)g.set(v,x);const y=new Map(f.toolsByCallId);for(const[v,x]of u.toolsByCallId)y.set(v,x);const b={...u,messages:p,partOrder:m,parts:g,toolsByCallId:y,hasMoreBefore:f.hasMoreBefore===!0,beforeCursor:f.beforeCursor,lastSequence:u.lastSequence},k={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};return k.bySession.set(t,b),k.lastSequence.set(t,b.lastSequence),this.state={...this.state,reducer:k},this.touchLastAccess(t),this.emit([`session:${t}`]),b.hasMoreBefore===!0}).finally(()=>{this.historyInflightById.get(t)===c&&this.historyInflightById.delete(t)});return this.historyInflightById.set(t,c),c}recordFromPiSession(t,n){return XC(t,this.state.catalog,n)}mergeHydratedSession(t,n){return JC(t,n,{localSendPending:this.pendingPromptById.has(t.sessionId)})}touchLastAccess(t){t&&(this.lastAccessClock+=1,this.lastAccessById.set(t,this.lastAccessClock))}commitNavigationSession(t){this.cadence.flush();const n=this.state.reducer.bySession.get(t.sessionId),r=n?{...t,lastSequence:Math.max(t.lastSequence,n.lastSequence),...n.model&&!t.model?{model:n.model}:{},...n.thinking&&!t.thinking?{thinking:n.thinking}:{},queue:n.queue.steering>0||n.queue.followUp>0?n.queue:t.queue}:t,s={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};s.bySession.set(r.sessionId,r),s.lastSequence.set(r.sessionId,r.lastSequence),this.hydratedSessionIds.add(r.sessionId),this.touchLastAccess(r.sessionId);const i=this.state.selectedSessionId===r.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let a=this.state.sessionLoadErrorById;if(a.has(r.sessionId)){const p=new Map(a);p.delete(r.sessionId),a=p}const c=il(r.lifecycle);let d=this.state.catalog;d.byId.has(r.sessionId)||(d=mi(d,r.sessionId,r.directory,c)),d=bu(d,r.sessionId,!0),d=Rs(d,r.sessionId,c,r.retry);const u=d!==this.state.catalog;this.state={...this.state,reducer:s,error:null,focusPending:i,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:a,catalog:d};const f=[`session:${r.sessionId}`,jt];u&&f.push(St),this.emit(f),this.scheduleIdleEviction()}commitHydratedSession(t,n=[]){if(this.isDeleted(t.sessionId))return;this.cadence.flush();const r=this.state.reducer.bySession.get(t.sessionId),s=this.mergeHydratedSession(t,r);(s.lifecycle==="busy"||s.lifecycle==="retry")&&J1(s.sessionId,"active");let o={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)};o.bySession.set(s.sessionId,s),o.lastSequence.set(s.sessionId,s.lastSequence);for(const y of n){const b=ru(o,y);o=b.state,b.didApply&&this.observeActivity(y)}this.hydratedSessionIds.add(s.sessionId),this.touchLastAccess(s.sessionId);const a=this.state.selectedSessionId===s.sessionId?!1:this.state.focusPending&&!this.hydratedSessionIds.has(this.state.selectedSessionId??"");let c=this.state.sessionLoadErrorById;if(c.has(s.sessionId)){const y=new Map(c);y.delete(s.sessionId),c=y}let d=this.applyCatalogFromEvents(n,o);const u=o.bySession.get(s.sessionId),f=u?.lifecycle,p=f?il(f):void 0;d.byId.has(s.sessionId)||(d=mi(d,s.sessionId,s.directory,p??"idle")),d=bu(d,s.sessionId,!0),p!==void 0&&(d=Rs(d,s.sessionId,p,u?.retry));const m=d!==this.state.catalog;this.state={...this.state,reducer:o,error:null,focusPending:a,hydratedSessionIds:new Set(this.hydratedSessionIds),sessionLoadErrorById:c,catalog:d};const g=[`session:${s.sessionId}`,jt,ol];m&&g.push(St),this.emit(g),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 i=this.state.sessions.find(p=>p.session.id===t)?.session.directory||this.directory(),a=X(),d=!!(this.state.reducer.bySession.get(t)&&this.hydratedSessionIds.has(t)),u=this.navigationGenerationById.get(t)??0;if(!s?.force&&this.stream&&d&&!r){this.state.connection==="error"||this.state.connection==="unavailable"?this.reconnect(t,n,a):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 C=r??await De.getSession(t,{directory:i,runtimeKey:a});if(n!==this.runtimeGeneration||C.session.id!==t||!this.isResponseEpochCurrent(C)||this.isDeleted(t)||(this.navigationGenerationById.get(t)??0)!==u)return;(C.lifecycle==="busy"||C.lifecycle==="retry")&&typeof C.runStartedAt=="number"&&vn(C.session.id,C.runStartedAt,C.serverNow),this.commitHydratedSession(this.sessionFromDetail(C));return}const p=[];let m=!1;const g=this.streamGeneration+1;this.streamGeneration=g;const y=()=>n===this.runtimeGeneration&&a===X()&&g===this.streamGeneration,b=C=>{y()&&(m?this.apply(C):p.push(C))},k=await T8({directory:i,selectedSessionId:t,runtimeKey:a,...s?.initialHealth?{initialHealth:s.initialHealth}:{},...s?.initialSessions?{initialSessions:s.initialSessions}:{},...s?.initialDetail?{initialDetail:s.initialDetail}:{},onEvent:b,onStreamDisconnect:()=>{y()&&this.reconnect(this.state.selectedSessionId??t,n,a)},onStreamReconnect:()=>this.markStreamReconnected(n,a,g),onEpochChange:C=>{y()&&this.handleVerifiedEpochChange(C)},onAuthRequired:()=>{y()&&this.handleStreamAuthRequired()}});if(!y()){k.stream?.dispose();return}if(k.phase==="failed")throw k.stream?.dispose(),k.errors.at(-1)?.error??new ut("DAEMON_PROTOCOL_MISMATCH","The Pi runtime returned an incompatible bootstrap response.");const v=k.selectedSessionTiming;v&&v.sessionId===t&&(v.lifecycle==="busy"||v.lifecycle==="retry")&&typeof v.runStartedAt=="number"&&vn(v.sessionId,v.runStartedAt,v.serverNow);let x=r?this.sessionFromDetail(r):k.reducerState.bySession.get(t);if(r&&(r.lifecycle==="busy"||r.lifecycle==="retry")&&typeof r.runStartedAt=="number"&&vn(r.session.id,r.runStartedAt,r.serverNow),!x)try{const C=r??await De.getSession(t,{directory:i,runtimeKey:a});if(n!==this.runtimeGeneration){k.stream?.dispose();return}if(this.isDeleted(t)){k.stream?.dispose();return}if(!this.isResponseEpochCurrent(C)){k.stream?.dispose();return}(C.lifecycle==="busy"||C.lifecycle==="retry")&&typeof C.runStartedAt=="number"&&vn(C.session.id,C.runStartedAt,C.serverNow),x=this.sessionFromDetail(C)}catch(C){if(this.stream=k.stream,m=!0,n===this.runtimeGeneration&&Ko(C)){this.handleInvalidSession(t,i,n,p);return}if(n===this.runtimeGeneration&&ku(C)){p.length>0&&this.commitEvents(p),this.failSessionLoad(t,xn(C));return}throw k.stream?.dispose(),this.stream=null,C}if(x.sessionId!==t){k.stream?.dispose();return}if(this.isDeleted(t)){k.stream?.dispose();return}if((this.navigationGenerationById.get(t)??0)!==u){k.stream?.dispose();return}this.stream=k.stream,this.commitHydratedSession(x,p),m=!0}catch(p){if(n!==this.runtimeGeneration)return;if(Ko(p)){this.handleInvalidSession(t,i,n);return}if(ku(p)){this.failSessionLoad(t,xn(p));return}if(YC(p)){try{const m=await De.getSession(t,{directory:i,runtimeKey:a});if(n!==this.runtimeGeneration||m.session.id!==t||this.isDeleted(t)||!this.isResponseEpochCurrent(m)||(this.navigationGenerationById.get(t)??0)!==u)return;(m.lifecycle==="busy"||m.lifecycle==="retry")&&typeof m.runStartedAt=="number"&&vn(m.session.id,m.runStartedAt,m.serverNow),this.commitHydratedSession(this.sessionFromDetail(m))}catch(m){if(n!==this.runtimeGeneration)return;this.failSessionLoad(t,xn(m))}return}if(f&&this.stream===f&&xn(p).code!=="DAEMON_AUTH_FAILED"){this.failSessionLoad(t,xn(p));return}this.reportError(p)}}markStreamReconnected(t,n,r){if(!(t!==this.runtimeGeneration||n!==X()||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===X()&&(this.streamGeneration===i||this.streamGeneration===i-1&&o===this.streamReadyRevision);let d=!1;try{let u=!1;const f=await P8({directory:this.directory(),sessionId:t,runtimeKey:r,lastKnownSequence:a,streamEpoch:this.streamEpoch??void 0,onEvent:p=>{c()&&(!u&&p.name==="session.snapshot"&&p.payload?.snapshot?.resync===!0&&(u=!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!==X()){f.stream?.dispose();return}if(o!==this.streamReadyRevision){f.stream?.dispose();return}if(f.phase==="ready"){typeof f.runStartedAt=="number"&&vn(t,f.runStartedAt,f.serverNow);let p=!1;typeof f.epoch=="string"&&f.epoch.length>0&&this.streamEpoch!==f.epoch&&(p=this.applyVerifiedEpochChange(f.epoch)!==null),s?.dispose(),this.streamGeneration=i,this.stream=f.stream;const m={bySession:new Map(this.state.reducer.bySession),lastSequence:new Map(this.state.reducer.lastSequence)},g=[],y=[];for(const[x,C]of f.reducerState.bySession.entries()){const S=m.bySession.get(x),w=this.mergeHydratedSession(C,S);m.bySession.set(x,w),m.lastSequence.set(x,w.lastSequence),this.touchLastAccess(x),g.push(x),(S?.lifecycle==="busy"||S?.lifecycle==="retry")&&w.lifecycle!=="busy"&&w.lifecycle!=="retry"&&y.push(x)}for(const x of f.reducerState.bySession.keys())this.hydratedSessionIds.add(x);let b=this.state.catalog;for(const x of g){const C=m.bySession.get(x);C&&(b=Rs(b,x,il(C.lifecycle),C.retry))}const k=b!==this.state.catalog;this.recordClusterConnectionChange("ready"),this.state={...this.state,reducer:m,connection:"ready",error:null,hydratedSessionIds:new Set(this.hydratedSessionIds),...k?{catalog:b}:{}};const v=[jt,ol];for(const x of g)v.push(`session:${x}`);(k||p)&&v.push(St),this.emit(v);for(const x of y)this.promoteSession(x,"settled");for(const x of g){if(!this.pendingPromptById.has(x))continue;const C=this.promptGenerationById.get(x);if(C===void 0||this.acceptedPromptGenerationById.get(x)!==C)continue;const S=f.reducerState.bySession.get(x)?.lifecycle;S==="busy"||S==="retry"||this.reconcileAcceptedPromptFromList(x)}this.scheduleIdleEviction(),p&&this.publishSyncRecoveryState()}else d||this.reportError(new ut(f.error?.code??"DAEMON_UNAVAILABLE",f.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),J1(t,n),r?.reorder&&wS(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&&Dv(t,a,o?.kind==="error"?{error:o.error??{}}:void 0),o&&Ov({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 qe.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,u=new Map;for(const y of t){if(y.name!=="session.deleted")continue;const b=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0,k=u.get(b)??new Set;k.add(y.sessionId),u.set(b,k)}let f=null;for(const y of t){const b=typeof y.streamEpoch=="string"&&y.streamEpoch.length>0?y.streamEpoch:void 0;if(!b&&this.streamEpoch!==null||b&&this.retiredStreamEpochs.has(b))continue;if(b&&this.streamEpoch!==null&&b!==this.streamEpoch){if(y.name!=="session.snapshot")continue;this.adoptStreamEpoch(b);const w=this.resetForEpochChange();if(n=uc(),o.clear(),f)for(const M of w)f.add(M);else f=w;i.clear(),a.clear(),d.clear(),c.length=0,r=!1,s=!1}if(b&&this.adoptStreamEpoch(b),this.deletedSessionIds.has(y.sessionId))continue;if(y.name==="session.deleted"){const w=ru(n,y);if(n=w.state,!w.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(u.get(b)?.has(y.sessionId))continue;const k=!n.bySession.has(y.sessionId),v=(n.lastSequence.get(y.sessionId)??-1)>=0,x=ru(n,y);if(n=x.state,!x.didApply)continue;if(c.push(y),k&&v&&o.add(y.sessionId),y.name==="session.snapshot"&&o.add(y.sessionId),r=!0,i.add(y.sessionId),y.name==="extension.catalog"){const w=a.get(y.directory)??{providers:!1,resources:!1,commands:!1};a.set(y.directory,{providers:w.providers||y.payload.providers===!0,resources:w.resources||y.payload.resources===!0,commands:w.commands||y.payload.commands===!0})}this.notePromptProgress(y);const C=y.name==="session.error"||y.name==="session.interrupted"||y.name==="session.lifecycle"&&y.payload.state!=="busy"&&y.payload.state!=="retry",S=y.name==="assistant.message.start"&&y.payload.role==="user"||y.name==="session.snapshot";if(C||S){const w=n.bySession.get(y.sessionId);if(w?.awaitingPromptEcho!==void 0&&(C||!Xv(w))){const M=new Map(n.bySession);M.set(y.sessionId,{...w,awaitingPromptEcho:void 0}),n={...n,bySession:M}}}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){f&&(this.state={...this.state,reducer:n,hydratedSessionIds:new Set(this.hydratedSessionIds)},this.emit([jt,St,...[...f].map(y=>`session:${y}`)]),this.queueSyncRecovery({directories:"all-known",residents:f}));return}this.state={...this.state,reducer:n,...f?{hydratedSessionIds:new Set(this.hydratedSessionIds)}:{}};for(const[y,b]of d)this.commitDeletion(y,b);for(const y of c)_g(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;m&&(this.state={...this.state,catalog:p});const g=[];(m||f)&&g.push(St),c.some(y=>y.name==="extension.dialog"||y.name==="extension.dialog.dismiss"||y.name==="session.snapshot")&&g.push(ol);for(const y of i)g.push(`session:${y}`);g.length>0&&this.emit(g),s&&this.scheduleIdleEviction();for(const y of o)this.restoreTranscript(y);f&&this.queueSyncRecovery({directories:"all-known",residents:f});for(const[y,b]of a)b.providers&&this.requestProviderCatalogRefresh(y),b.commands&&Dl(y),b.resources&&(vc(),ce(y)===ce(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=n3(s);if(a!==void 0&&!r.byId.has(s.sessionId)&&(r=mi(r,s.sessionId,s.directory,a)),i!==void 0&&(this.hydratedSessionIds.has(s.sessionId)||_g(s))&&(r=Rs(r,s.sessionId,il(i),o?.retry)),s.name==="session.updated"){const c=typeof s.payload.title=="string"?s.payload.title.trim():"";if(c){r.byId.has(s.sessionId)||(r=mi(r,s.sessionId,s.directory,a??"idle"));const d=r.byId.get(s.sessionId);r=wu(r,s.sessionId,c,d?.updatedAt??Date.now())}}if(s.name==="assistant.message.start"&&s.payload.role==="user"){r=xg(r,s.sessionId,Date.now(),{directory:s.directory,lifecycle:"busy"});const c=r.byId.get(s.sessionId),d=lv(s.payload.text??"");d&&c&&c.title.trim().length===0&&(r=wu(r,s.sessionId,d,c.updatedAt))}}return r}scheduleIdleEviction(){this.evictionScheduled||this.state.reducer.bySession.size<=Cu||(this.evictionScheduled=!0,queueMicrotask(()=>{this.evictionScheduled=!1,this.evictIdleTranscripts()}))}evictIdleTranscripts(){const t=this.state.reducer.bySession;if(t.size<=Cu)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);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<=Cu)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=bu(a,p,!1),d+=1,c.push(p)}if(!s||!o||!i)return;this.lastAccessById=i;const u=!!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 f=[jt];for(const p of c)f.push(`session:${p}`);u&&f.push(St),this.emit(f)}async upsertAndHydrate(t){const n=this.runtimeGeneration,r=bg(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(St),this.emit(o),await this.hydrate(t.session.id,n,t)}directory(){if(!this.state.directory)throw new ut("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:X()}}reconnectAfterTransportSwitch(){const t=this.state.selectedSessionId;!this.stream||!t||!this.state.directory||this.reconnect(t,this.runtimeGeneration,X())}resetForRuntime(){this.catalogCache.flush(),this.resetLiveRuntimeState(),this.state=al(this.readCachedCatalog(X())),xu(),this.navigationGenerationById.clear(),this.navigationCounter=0,this.emitBroadcast()}emit(t){if(t.length===0)return;t.includes(St)&&this.catalogCache.schedule(X(),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(Cg);if(r)for(const s of r)n.has(s)||(n.add(s),s())}readCachedCatalog(t){try{return this.catalogCache.read(t)??oh()}catch{return oh()}}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 io=new Map,Eg=e=>{io.set(e,(io.get(e)??0)+1)},ek=e=>(io.get(e)??0)>0,tk=e=>{const t=io.get(e)??0;return t<=0?!1:(t===1?io.delete(e):io.set(e,t-1),!0)};function r3(){return na(Je().getState().catalog,{archived:!1})}function Ap(){const e=Je().getState().catalog;return[...na(e,{archived:!1}),...na(e,{archived:!0})]}function nk(e){const t=Je().getState();return t.catalog.byId.get(e)?.directory??t.sessions.find(n=>n.session.id===e)?.session.directory??t.directory}function rk(){return UC(Je().getState().catalog).map(e=>({id:e.id,title:e.title.trim()||null,directory:e.directory}))}function CZ(e,t){return[]}function kZ(e,t){return[]}const Lp=2048,jg=new WeakMap,sk=e=>e==="running"||e==="pending",s3=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 Lp+1}},ok=e=>{if(!e)return e;const t=e.patch??e.diff??e.filediff?.patch??e.filediff?.diff;if(s3(t)<=Lp)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},Np=(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=sk(e.tool?.state),r=t?.full===!0||n,s=!r&&s3(e.tool?.output)>Lp,o=r?e.tool?.metadata:ok(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}},ik=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}:{}}}),ak=(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=>Np(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.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}},lk=e=>e?e.messages.map(t=>{const n=jg.get(t);if(n&&n.info.sessionID===e.sessionId)return n;const r=ak(t,e.sessionId);return jg.set(t,r),r}):[],ck=["chat","git","diff","terminal","files","diagram"],dk=["settings","skills","providers","git-identities"],Sr={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function o3(e){const t=uk();return{sessionId:fk(t),tab:hk(t),settingsPath:pk(t),diffFile:mk(t)}}function uk(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function fk(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 hk(e){const t=e.get(Sr.TAB);if(!t)return null;const n=t.toLowerCase().trim();return ck.includes(n)?n:null}function pk(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":(dk.includes(n),n)}function mk(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 MZ(){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 Rp=(e,t)=>e?.open===!0&&t===null,IZ=e=>e.currentSessionId??(Rp(e.draft,e.currentSessionId)?null:e.piSelectedSessionId),gk=()=>{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)}},i3="oc.lastSession.v1",yk=8,Mu=()=>({version:1,runtimes:{}}),Pp=e=>{try{const t=e.getItem(i3);if(!t)return Mu();const n=JSON.parse(t);if(n.version!==1||!n.runtimes||typeof n.runtimes!="object")return Mu();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 Mu()}},a3=(e,t)=>{const n=Object.entries(t.runtimes).sort(([,r],[,s])=>s.updatedAt-r.updatedAt).slice(0,yk);try{e.setItem(i3,JSON.stringify({...t,runtimes:Object.fromEntries(n)}))}catch{}};function vk(e,t,n=zt()){if(!t.sessionId)return;const r=Pp(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)},a3(n,r)}function ih(e,t=zt()){if(!e)return null;const n=Pp(t).runtimes[e];return n?{sessionId:n.sessionId,directory:n.directory}:null}function xk(e,t=zt()){if(!e)return;const n=Pp(t);n.runtimes[e]&&(delete n.runtimes[e],a3(t,n))}const bk=120,wk=600,l3=typeof window<"u"&&typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"?window.__PICHAMBER_HARDWARE_KEYBOARD__:null;let Mc=l3===!0,cd=l3!==null,Di=null,Iu=!1;const ah=new Set;Mc&&typeof document<"u"&&document.documentElement.classList.add("oc-hardware-keyboard");const dd=()=>{Di!==null&&(window.clearTimeout(Di),Di=null)},ud=e=>{if(Mc!==e){Mc=e,typeof document<"u"&&document.documentElement.classList.toggle("oc-hardware-keyboard",e);for(const t of ah)t()}},Sk=()=>{if(typeof window>"u")return()=>{};const e=n=>{cd=!0,dd(),ud(n)};if(typeof window.__PICHAMBER_HARDWARE_KEYBOARD__=="boolean"&&e(window.__PICHAMBER_HARDWARE_KEYBOARD__),Iu)return()=>{};Iu=!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),Iu=!1}},Tg=e=>{cd||!Number.isFinite(e)||(dd(),ud(e>0&&e<bk))},Ck=()=>{cd||typeof window>"u"||typeof document>"u"||document.documentElement.classList.contains("oc-keyboard-open")||(dd(),Di=window.setTimeout(()=>{Di=null,ud(!0)},wk))},kk=()=>{dd(),!cd&&ud(!1)},Mk=()=>Mc,Ik=e=>(ah.add(e),()=>{ah.delete(e)});function _k(){return h.useSyncExternalStore(Ik,Mk,()=>!1)}const So=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0?!0:window.location.protocol==="capacitor:",_Z=()=>{h.useEffect(()=>{if(!So())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"),c3(),t.push(Sk());const s=o=>{n.style.setProperty("--oc-keyboard-inset",`${Math.max(0,Math.round(o))}px`)};return mt(()=>import("./vendor-capacitor-status-bar-9rNIGxlO.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:u}=await mt(async()=>{const{App:p}=await import("./vendor-capacitor-app-BjdQVib9.js");return{App:p}},__vite__mapDeps([7,8,5,1,6])),f=await u.addListener("appStateChange",({isActive:p})=>{p&&c()});if(e){f.remove();return}t.push(()=>{f.remove()})}).catch(()=>{}),mt(()=>import("./vendor-capacitor-keyboard-eTtI5go3.js"),__vite__mapDeps([9,5,1,6])).then(async({Keyboard:o})=>{if(e)return;if(window.Capacitor?.getPlatform?.()==="android"){const _=await o.addListener("keyboardWillShow",O=>{Tg(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}}))}),N=()=>{_.remove(),T.remove(),A.remove(),j.remove()};if(e){N();return}t.push(N);return}await o.setAccessoryBarVisible({isVisible:!1}).catch(()=>{});const a=250,c=200,d="cubic-bezier(0.38, 0.7, 0.125, 1)";let u=null,f=null,p=0,m=!1,g=0,y=!1;const b=(_,T)=>{n.style.setProperty(_,`${Math.max(0,Math.round(T))}px`)},k=()=>{u!==null&&(window.clearTimeout(u),u=null)},v=(_,T)=>{window.dispatchEvent(new CustomEvent(_,{detail:T}))},x=()=>{const _=[],T=document.querySelector(".oc-mobile-composer");T&&_.push({el:T,factor:1});const A=document.querySelector(".oc-draft-center");return A&&_.push({el:A,factor:.5}),_},C=()=>{for(const{el:_}of x())_.style.transition="",_.style.transform=""},S=await o.addListener("keyboardWillShow",_=>{if(k(),Tg(_.keyboardHeight),y=!0,p=_.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"),f!==null&&(window.clearTimeout(f),f=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)`;b("--oc-kb-scroll-inset",T),v("oc:keyboard-settled",{open:!0}),v("oc:keyboard-anim",{phase:"show",slide:T,durationMs:a,easing:d}),u=window.setTimeout(()=>{u=null,n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",p),m=!0,C(),v("oc:keyboard-settled",{open:!0}),f=window.setTimeout(()=>{f=null,n.classList.remove("oc-kb-caret-hold")},250)},a+20)}),w=()=>{if(!y)return;y=!1,k(),v("oc:keyboard-intent",{open:!1}),f!==null&&(window.clearTimeout(f),f=null),n.classList.remove("oc-kb-caret-hold");const _=Math.max(0,p-g);if(n.classList.remove("oc-keyboard-open"),s(0),b("--oc-kb-scroll-inset",0),m){n.classList.remove("oc-kb-animating"),b("--oc-kb-layout",0),m=!1;for(const{el:T,factor:A}of x())T.style.transition="none",T.style.transform=`translateY(${-_*A}px)`;document.querySelector(".oc-mobile-app-shell")?.offsetHeight}v("oc:keyboard-anim",{phase:"hide",slide:_,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)";u=window.setTimeout(()=>{u=null,n.classList.remove("oc-kb-animating","oc-kb-hide"),C(),v("oc:keyboard-settled",{open:!1})},c+20)},M=await o.addListener("keyboardWillHide",w),I=_=>_ instanceof HTMLElement&&(_.tagName==="TEXTAREA"||_.tagName==="INPUT"||_.isContentEditable),E=_=>{y&&I(_.target)&&(I(_.relatedTarget)||window.setTimeout(()=>{y&&(I(document.activeElement)||w())},0))};if(document.addEventListener("focusout",E,!0),e){k(),document.removeEventListener("focusout",E,!0),S.remove(),M.remove();return}t.push(k,()=>{f!==null&&(window.clearTimeout(f),f=null)},()=>document.removeEventListener("focusout",E,!0),()=>{S.remove()},()=>{M.remove()})}).catch(()=>{}),()=>{e=!0,t.forEach(o=>o()),kk(),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")}},[])},EZ=e=>{const t=h.useRef(!1);h.useEffect(()=>{if(!So())return;let n=!1;const r=[],s=()=>{t.current&&(t.current=!1,e())},o=()=>{if(document.visibilityState==="hidden"){t.current=!0,wr("app-lifecycle",{code:"hidden"});return}wr("app-lifecycle",{code:"visible"}),s()};return document.addEventListener("visibilitychange",o),r.push(()=>document.removeEventListener("visibilitychange",o)),mt(()=>import("./vendor-capacitor-app-BjdQVib9.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),wr("app-lifecycle",{code:d?"resume":"pause"}),!d){t.current=!0;return}s()}),c=await i.addListener("resume",()=>{wr("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])},Oi=[];let _u=null;const Ek=()=>{for(let e=Oi.length-1;e>=0;e--)try{if(Oi[e]())return!0}catch{}return!1},c3=()=>So()?(_u||(_u=mt(async()=>{const{App:e}=await import("./vendor-capacitor-app-BjdQVib9.js");return{App:e}},__vite__mapDeps([7,8,5,1,6])).then(({App:e})=>e.addListener("backButton",()=>{Ek()||e.minimizeApp().catch(()=>{})})).catch(()=>null)),_u.then(()=>{})):Promise.resolve(),jZ=e=>{const t=h.useRef(e);t.current=e,h.useEffect(()=>{if(!So())return;c3();const n=()=>t.current();return Oi.push(n),()=>{const r=Oi.lastIndexOf(n);r!==-1&&Oi.splice(r,1)}},[])},d3=h.createContext(null),fa=()=>h.useContext(d3)??Je(),TZ=({children:e,directory:t})=>{const n=h.useMemo(()=>Je(),[]),r=it(o=>o.projects.find(i=>i.id===o.activeProjectId)?.path??null),s=t?.trim()||r;return z.useEffect(()=>{const o=o3(),i=ve.getState(),a=Rp(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&&!So()){const d=ih(X());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&&!So()){const d=ih(X());if(d?.sessionId){n.start({directory:s,sessionId:d.sessionId,sessionDirectoryKnown:!1});return}}n.start({directory:s})},[n,s]),l.jsx(d3.Provider,{value:n,children:e})},jk=e=>e;function Ke(e,t,n="*",r=""){const s=fa(),o=z.useRef(e);o.current=e;const i=z.useRef(t);i.current=t;const a=z.useRef(null),c=`${n}\0${r}`;a.current?.key!==c&&(a.current={key:c,select:gk()});const d=z.useCallback(()=>{const f=o.current??jk,p=typeof i.current=="function"?i.current:Object.is;return a.current.select(s.getState(),f,p)},[s]),u=z.useMemo(()=>f=>s.subscribe(f,n),[s,n]);return z.useSyncExternalStore(u,d,d)}const u3={type:"idle"},Tk={type:"busy"},Ak={type:"retry"},Ag=new WeakMap,Lk=[],Nk=[],Lg={loading:!1,complete:!0,status:"ready",cursor:void 0,error:null,errorCode:null},Ng=[],Rg=new WeakMap,fd="catalog",Cn="chrome",_n=e=>`session:${e}`,Rk=(e,t)=>{if(e==="busy")return Tk;if(e!=="retry")return u3;if(!t)return Ak;const n=Ag.get(t);if(n)return n;const r={type:"retry",...t};return Ag.set(t,r),r};function Pk(e){const t=e?.archived??!1,n=e?.directory;return Ke(r=>na(r.catalog,{archived:t,directory:n}),t3,fd)}function AZ(e,t){return hd(e)}function Eu(e,t){Je().select(t,e||void 0)}function Dp(e,t){const n=pd(e);return z.useMemo(()=>n.map(r=>r.info),[n])}function Dk(e,t,n){const r=Ke(a=>e?a.reducer.bySession.get(e)??null:null,void 0,e?_n(e):"*"),s=Ke(a=>e?null:a.reducer.bySession,void 0,e?_n(e):"*"),o=z.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 z.useMemo(()=>{if(!t||!i)return Ng;const a=i.messages.get(t);if(!a)return Ng;const c=i.partOrder.get(t)??[];if(c.length>0){const u=[];for(const f of c){const p=i.parts.get(f);if(!p)continue;const m=Rg.get(p);if(m){u.push(m);continue}const g=Np({id:p.id,type:p.type,text:p.text,streaming:p.streaming,...p.tool?{tool:p.tool}:{},...p.attachment?{attachment:p.attachment}:{}},{full:!0});Rg.set(p,g),u.push(g)}return u}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 hd(e,t){const n=Ke(s=>s.catalog.byId,void 0,fd);if(!e)return u3;const r=n.get(e);return Rk(r?.lifecycle,r?.retry)}function f3(){return Ke(e=>e.connection,void 0,Cn)}function Ok(e){return Ke(t=>e?t.reducer.bySession.get(e)?.compaction??null:null,void 0,e?_n(e):"*")}function h3(){const e=Ke(t=>t.directory,void 0,Cn);return Pk({archived:!1,directory:e||null})}function LZ(e,t){const n=Ke(s=>s.catalog.byId,void 0,fd),r=e?n.get(e)??null:null;return r?oo(r):void 0}function Hk(e){const t=Ke(s=>s.catalog.byId,void 0,fd),n=Ke(s=>s.directory,void 0,Cn);return(e?t.get(e)?.directory:void 0)??n??void 0}function Fk(){return Ke(e=>e.directory??"",void 0,Cn)}function Vk(e,t){const n=Ke(a=>a.hydratedSessionIds,void 0,Cn),r=Ke(a=>a.selectedSessionId,void 0,Cn),s=Ke(a=>a.connection,void 0,Cn),o=Ke(a=>a.error,void 0,Cn),i=Ke(a=>a.sessionLoadErrorById,void 0,Cn);return z.useMemo(()=>{if(!e||n.has(e))return Lg;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 p3(e,t){const n=Ke(r=>r.hydratedSessionIds,void 0,Cn);return!e||n.has(e)}function Bk(e){const t=Ke(n=>e?n.reducer.bySession.get(e)??null:null,(n,r)=>Object.is(n,r)?!0:!n||!r?!1:wC(n,r),e?_n(e):"*");return z.useMemo(()=>{if(!t)return Lk;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 $k(e){return Ke(t=>ea(e?t.reducer.bySession.get(e)??null:null),Object.is,e?_n(e):"*")}function zk(e){return Ke(t=>Xv(e?t.reducer.bySession.get(e)??null:null),Object.is,e?_n(e):"*")}function pd(e,t,n){const r=n?.suspendPartUpdates!==!1,s=null,o=Ke(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=ea(c);return d?rh(a,c,d):!1},e?_n(e):"*"),i=z.useRef(null);return z.useMemo(()=>{if(!o)return i.current=null,Nk;const a=i.current,c=ea(o);if(c&&a&&a.sessionId===e&&rh(a.session,o,c))return i.current={sessionId:e,session:o,projection:a.projection,records:a.records},a.records;const d=sv(o,a&&a.sessionId===e?{session:a.session,projection:a.projection}:null),u=lk(d),f=a?.records,p=f&&f.length===u.length&&f.every((m,g)=>m===u[g])?f:u;return i.current={sessionId:e,session:o,projection:d,records:p},p},[s,o,e,r])}function Uk(e,t,n){const r=fa(),s=n&&e?_n(e):Cn,o=z.useMemo(()=>c=>r.subscribe(c,s),[r,s]),i=z.useCallback(()=>!n||!e||!t?null:r.getState().reducer.bySession.get(e)?.parts.get(t)??null,[n,t,e,r]),a=z.useSyncExternalStore(o,i,i);return z.useMemo(()=>!n||!a?null:Np({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 Zk(e,t){return Ke(n=>e?n.reducer.bySession.get(e)?.messages.size??0:0,void 0,e?_n(e):"*")}function Wk(e){const t=fa(),n=Ke(o=>!!(e&&o.reducer.bySession.get(e)?.hasMoreBefore),void 0,e?_n(e):"*"),r=Ke(o=>e?o.reducer.bySession.get(e)?.beforeCursor:void 0,void 0,e?_n(e):"*"),s=z.useCallback(()=>e?t.loadOlderMessages(e):Promise.resolve(!1),[e,t]);return{hasMoreBefore:n,beforeCursor:r,loadOlder:s}}function qk(e,t,n=!0){const r=fa();!n||!e||r.ensureHydrated(e)}const Ot=()=>Je();async function Gk(e,t,n,r){const s=await Ot().create(e,{...t?{directory:t}:{},...r?.model?{model:r.model}:{},...r?.thinking?{thinking:r.thinking}:{},...r?.select===!1?{select:!1}:{}}),o=Ot().getState().sessions.find(i=>i.session.id===s||i.session.id===Ot().getState().selectedSessionId);return o?ik(o.session):null}async function Kk(e,t){return await Ot().remove(e),!0}async function Yk(e,t){const n=[],r=[];for(const s of e)try{await Ot().remove(s),n.push(s)}catch{r.push(s)}return{deletedIds:n,failedIds:r}}async function Xk(e){return await Ot().archive(e,!0),!0}async function Jk(e,t){for(const n of e)await Ot().archive(n,!0);return{archivedIds:e,failedIds:[]}}async function Qk(e){return await Ot().archive(e,!1),!0}async function eM(e,t){for(const n of e)await Ot().archive(n,!1);return{restoredIds:e,failedIds:[]}}async function tM(e,t){await Ot().rename(e,t)}async function nM(e){return null}async function rM(e){return null}async function sM(e,t){const r=(await Ot().navigate(e,t))?.navigation?.editorText;if(typeof r=="string"&&r.length>0)try{Ge.getState().setPendingRevertText(r)}catch{}}async function oM(e,t){if(!Ep(e))throw new Error("No reverted conversation is available to restore.");await Ot().navigate(e,t)}async function iM(e){const t=Ep(e)?.previousLeafId;if(!t)throw new Error("No reverted conversation is available to restore.");await Ot().navigate(e,t)}async function aM(e,t){await Ot().fork(e,t)}async function lM(){const e=Ot().getState();if(e.connection!=="ready")throw e.error??new Error("Pi runtime is unavailable")}async function cM(e,t){await Ot().compact(e,t)}function m3(e){e&&Ot().abort(e)}const dM=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 Pg(e){const t=Je().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 lh(e){const t=e.delivery==="steer"||e.delivery==="followUp"?e.delivery:"prompt",n=e.runtimeKey??X(),r=()=>{if(n!==X())throw new Error("Runtime changed before sending message.")};r();const s=Je();let o=!1;if(e.sessionId&&e.providerID&&e.modelID){const c=Pg(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&&Dt(e.variant)){const c=Pg(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 u=>{const f=u.uploadState;if(f?.status==="preparing"||f?.status==="uploading")throw new Error("Attachments are still uploading.");if(f?.status==="failed")throw new Error("Retry or remove failed attachments.");if(f?.status==="ready"&&f.expiresAt>Date.now())return{id:f.attachmentId};if(typeof u.url=="string"&&u.url.startsWith("data:")){const m=await(await fetch(u.url)).blob();r();const g=await s.uploadFile(m,{filename:dM(u.filename),mime:u.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===X()?a:[]).map(d=>s.deleteUpload(d).catch(()=>{}))),c}}function uM(e){const t=ce(e.session?.directory??e.currentDirectory??null);return{directory:t,source:t?"session":void 0}}function NZ(e){return""}const Zl={id:null,open:!1,directoryOverride:null,branchIntent:null,worktreeIntent:null,parentID:null},g3=(e,t,n)=>!!(e.open&&e.id&&e.id===n&&t===null),y3=e=>ce(e.directory??null),v3=zt(),x3="oc.chatInput.lastDraftTarget",fM=()=>{try{const e=v3.getItem(x3);if(!e)return null;const t=JSON.parse(e);return{projectId:typeof t?.projectId=="string"?t.projectId:null,directory:ce(typeof t?.directory=="string"?t.directory:null)}}catch{return null}},ch=e=>{try{v3.setItem(x3,JSON.stringify(e))}catch{}},hM=e=>{const t=Ap().find(s=>s.id===e),n=t?y3(t):null;if(n)return ce(n);const r=nk(e);return r?ce(r):null},Ic=new Map,ju=new Map,qn=e=>(e??X()).trim()||"default",dh=e=>({...e}),Ps=(e,t)=>{const n=Ic.get(e);Ic.set(e,{sessionId:n?.sessionId??null,directory:n?.directory??null,draft:n?.draft?dh(n.draft):{...Zl},...t})},pM=e=>{const t=qn(),n=Ic.get(t),r=ih(t);return{runtime:n?.sessionId===e?ce(n.directory):null,persisted:r?.sessionId===e?ce(r.directory):null}};let md=null;const Dg=()=>md,mM=e=>{md=e},Og=()=>{md=null},gM=(e,t)=>({session:Ap().find(n=>n.id===e)??null,currentDirectory:e===md?null:ce(t)}),Hg=(e,t=null)=>e?uM(gM(e,t))?.directory??null:null,uh=async e=>{await qe.getState().activateDirectory(ce(e))},Hi=(e,t)=>!e||!t?!1:e.runtimeKey===t.runtimeKey&&ce(e.directory)===ce(t.directory)&&e.branch===t.branch;async function yM(e,t){const n=t.getState(),r=e.draftSnapshot??n.newSessionDraft;if(!r?.open)return null;if(r.branchIntent){const g=ce(r.branchIntent.directory),y=ce(r.directoryOverride);if(r.branchIntent.runtimeKey!==X()||g!==y)throw new Error("The selected branch no longer matches this draft target.");if(!Hi(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||ce(g.projectRoot)!==ce(r.worktreeIntent.projectRoot)||ce(g.sourceDirectory)!==ce(r.worktreeIntent.sourceDirectory)||g.startRef!==r.worktreeIntent.startRef||!ce(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("/")?lv(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:Dt(e.variant)?e.variant:void 0,select:!1},{draftSnapshot:r,closeDraft:!1});if(!d?.id)throw new Error("Failed to create session");const u=ce(d.directory??i??null),f=t.getState().newSessionDraft===r&&t.getState().currentSessionId===null;f&&ch({projectId:a,directory:u});const p=r.syntheticParts;f&&uh(u).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)),f&&n.setCurrentSession(d.id,u),s&&mt(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:u,agent:m,syntheticParts:p}}let Fg=0;const vM=()=>(Fg+=1,`draft-${Date.now()}-${Fg}`);async function b3(e){return yM(e,ve)}const ve=Et()((e,t)=>({currentSessionId:null,currentSessionDirectory:null,newSessionDraft:{...Zl},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=qn();ju.set(s,n);const o=tt.getState(),i=Hg(n),a=Je().getState().directory??o.currentDirectory??null,c=(r?ce(r):null)??i,d=c??a,u=c===null,f=it.getState(),p=d?er(f.projects,On(f.projects,sn.getState()),d):null;e({currentSessionId:n,currentSessionDirectory:n?d??null:null}),mM(u&&n?n:null);const m=u?null:d??null;Ps(s,{sessionId:n,directory:m}),n&&vk(s,{sessionId:n,directory:m}),n&&Je().select(n,u?void 0:d);try{d&&o.currentDirectory!==d&&o.setDirectory(d,{showOverlay:!1}),p&&f.activeProjectId!==p.id&&f.setActiveProjectIdOnly(p.id)}catch(g){console.warn("Failed to set Pi directory for session switch:",g)}n&&(sd(n),Eu(d??"",n))},prepareForRuntimeSwitch:n=>{const r=qn(n),s=tt.getState().currentDirectory||null,o=t().currentSessionId;ju.set(r,t().currentSessionId),Ps(r,{sessionId:o,directory:s,draft:dh(t().newSessionDraft)})},restoreForRuntimeSwitch:n=>{const r=qn(n),s=Ic.get(r),o=s?.sessionId??ju.get(r)??null,i=s?.draft?dh(s.draft):{...Zl},a=s?.directory??null;a&&tt.getState().setDirectory(a,{showOverlay:!1}),e({currentSessionId:o,currentSessionDirectory:o?a:null,newSessionDraft:o?{...Zl}:i,abortPromptSessionId:null,abortPromptExpiresAt:null,error:null,sendingNewSessionDraftId:null,sessionAbortFlags:new Map,pendingChangesBarDismissed:new Map}),o?Eu(a??Je().getState().directory??"",o):Eu("","")},openNewSessionDraft:n=>{n?.automatic||xk(qn());const r=it.getState(),s=r.projects,o=On(s,sn.getState()),i=r.getActiveProject(),a=ce(tt.getState().currentDirectory??null),c=fM(),d="__home__",u=n?.selectedProjectId===d,f=n?.directoryOverride!==void 0?ce(n.directoryOverride):null,p=n?.selectedProjectId?u?{id:d,path:f??""}:s.find(I=>I.id===n.selectedProjectId)??null:null,m=er(s,o,f),g=i||(r.activeProjectId?s.find(I=>I.id===r.activeProjectId)??null:s[0]??null),y=c?.projectId===d,b=c?.projectId?y?{id:d,path:c.directory??""}:s.find(I=>I.id===c.projectId)??null:null,k=er(s,o,c?.directory??null),v=er(s,o,a),x=u||p?p:f!==null?m:a?v:y?b:k??b??g,C=f!==null?f:u?f??ce(tt.getState().homeDirectory||zt().getItem("homeDirectory")||"~")??f:p?ce(p.path??null):a||(c?.directory?c.directory:ce(x?.path??null)),S=u?d:x?.id??null;ch({projectId:S,directory:C});const w={id:vM(),open:!0,selectedProjectId:S,directoryOverride:C,branchIntent:n?.branchIntent&&n.branchIntent.runtimeKey===X()&&ce(n.branchIntent.directory)===C?n.branchIntent:null,worktreeIntent:n?.worktreeIntent&&n.worktreeIntent.runtimeKey===X()&&ce(n.worktreeIntent.sourceDirectory)===C?n.worktreeIntent:null,permissionAutoAcceptEnabled:n?.permissionAutoAcceptEnabled===!0,preserveDirectoryOverride:n?.preserveDirectoryOverride===!0,parentID:n?.parentID??null,title:n?.title,initialPrompt:n?.initialPrompt,syntheticParts:n?.syntheticParts,targetFolderId:n?.targetFolderId};e({newSessionDraft:{...w},currentSessionId:null,currentSessionDirectory:null,error:null}),Ps(qn(),{sessionId:null,directory:C,draft:w}),n?.initialPrompt&&Ge.getState().setPendingInputText(n.initialPrompt);const M=ce(x?.path??null)??C;uh(M),C&&C!==tt.getState().currentDirectory&&tt.getState().setDirectory(C)},closeNewSessionDraft:()=>{const n=t().newSessionDraft;if(!n.open&&n.selectedProjectId==null&&n.directoryOverride==null&&n.branchIntent==null&&n.worktreeIntent==null&&!n.preserveDirectoryOverride&&n.parentID==null&&n.title===void 0&&n.initialPrompt===void 0&&n.syntheticParts===void 0&&n.targetFolderId===void 0&&n.permissionAutoAcceptEnabled===void 0)return;const r={id:null,open:!1,selectedProjectId:null,directoryOverride:null,branchIntent:null,worktreeIntent:null,preserveDirectoryOverride:!1,parentID:null,title:void 0,initialPrompt:void 0,syntheticParts:void 0,targetFolderId:void 0};e({newSessionDraft:r}),Ps(qn(),{draft:r})},setNewSessionDraftTarget:n=>{let r=null,s=null;e(o=>{r=ce(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=ce(o.newSessionDraft.directoryOverride),d=r!==c,u=s!==(o.newSessionDraft.selectedProjectId??null),f=n.branchIntent,p=f&&f.runtimeKey===X()&&ce(f.directory)===r?f:null,m=n.worktreeIntent,g=m&&m.runtimeKey===X()&&ce(m.sourceDirectory)===r?m:null;return{newSessionDraft:{...o.newSessionDraft,selectedProjectId:s,directoryOverride:n.directoryOverride??o.newSessionDraft.directoryOverride,branchIntent:i?p:d||u?null:o.newSessionDraft.branchIntent,worktreeIntent:a?g:d||u?null:o.newSessionDraft.worktreeIntent}}}),ch({projectId:s,directory:r}),uh(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,u,f)=>{const p=f?.target;if(p&&p.runtimeKey!==X())throw new Error("Message was not sent because the runtime changed.");const m=p?.sessionId??f?.sessionId??(f?.draftSnapshot?null:t().currentSessionId);if(m){const S=new Map(t().pendingChangesBarDismissed);S.delete(m),e({pendingChangesBarDismissed:S})}const g=t().newSessionDraft,y=typeof o=="string"&&o.trim().length>0?o.trim():void 0;if(!p&&!f?.sessionId&&(f?.draftSnapshot?.open||g?.open)){const S=await b3({providerID:r,modelID:s,agent:y,variant:d,initialPrompt:n,branchCheckoutReceipt:f?.branchCheckoutReceipt,worktreeCreationReceipt:f?.worktreeCreationReceipt,draftSnapshot:f?.draftSnapshot,initialInputKind:f?.initialInputKind});if(!S)throw new Error("Failed to create session");const w=S.syntheticParts?.length?[...c||[],...S.syntheticParts]:c;Eg(S.sessionId);const M=i?.map(I=>({type:"file",mime:I.mimeType,url:I.dataUrl,filename:I.filename,uploadState:I.uploadState}));await lh({sessionId:S.sessionId,directory:S.directory,content:n,providerID:r,modelID:s,agent:S.agent,agentMentionName:a,variant:d,inputMode:u,files:M,delivery:f?.delivery,operationId:f?.operationId,streamEpoch:f?.streamEpoch,knownEmptyTranscript:!0,additionalParts:w?.map(I=>({text:I.text,synthetic:I.synthetic,files:I.attachments?.map(E=>({type:"file",mime:E.mimeType,url:E.dataUrl,filename:E.filename,uploadState:E.uploadState}))}))});return}const b=p?.sessionId??f?.sessionId??t().currentSessionId,k=b?_t.getState().getSessionAgentSelection(b):null,v=y||k||void 0;b&&_t.getState().saveSessionModelSelection(b,r,s),b&&v&&(_t.getState().saveSessionAgentSelection(b,v),_t.getState().saveAgentModelForSession(b,v,r,s),_t.getState().saveAgentModelVariantForSession(b,v,r,s,d));const x=b?ce(p?.directory??f?.directory??t().getDirectoryForSession(b)):null;b&&Eg(b);const C=i?.map(S=>({type:"file",mime:S.mimeType,url:S.dataUrl,filename:S.filename,uploadState:S.uploadState}));await lh({runtimeKey:p?.runtimeKey,sessionId:b||"",directory:x,content:n,providerID:r,modelID:s,agent:v,agentMentionName:a,variant:d,inputMode:u,files:C,delivery:f?.delivery,operationId:f?.operationId,streamEpoch:f?.streamEpoch,additionalParts:c?.map(S=>({text:S.text,synthetic:S.synthetic,files:S.attachments?.map(w=>({type:"file",mime:w.mimeType,url:w.dataUrl,filename:w.filename,uploadState:w.uploadState}))}))})},createSession:async(n,r,s,o,i)=>{const a=i?.draftSnapshot??t().newSessionDraft,c=a.targetFolderId;try{const d=r??Je().getState().directory,u=await Gk(n,d,s??null,o);if(!u)return null;if(i?.closeDraft!==!1&&t().newSessionDraft===a&&t().closeNewSessionDraft(),c){const f=r||u.directory;f&&Mp.getState().addSessionToFolder(f,c,u.id)}return u}catch(d){return console.error("[session-ui-store] createSession failed",d),null}},deleteSession:async(n,r)=>{const s=await Kk(n);return s&&t().currentSessionId===n&&t().openNewSessionDraft(),s},deleteSessions:async(n,r)=>{const s=await Yk(n),o=t().currentSessionId;return o&&s.deletedIds.includes(o)&&t().openNewSessionDraft(),s},archiveSession:n=>Xk(n),archiveSessions:(n,r)=>Jk(n),unarchiveSession:n=>Qk(n),unarchiveSessions:(n,r)=>eM(n),updateSessionTitle:async(n,r)=>{await tM(n,r)},shareSession:async n=>nM(),unshareSession:async n=>rM(),revertToMessage:async(n,r)=>{await sM(n,r)},restoreToMessage:async(n,r)=>{await oM(n,r)},handleSlashUndo:async n=>{const r=Je().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 mt(async()=>{const{toast:c}=await import("./vendor-boot-Dgb9NVFe.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 iM(n);const{toast:r}=await mt(async()=>{const{toast:s}=await import("./vendor-boot-Dgb9NVFe.js").then(o=>o.ck);return{toast:s}},__vite__mapDeps([5,1,6]));r.success("Restored all messages")},forkFromMessage:async(n,r)=>{await aM(n,r)},getSessionsByDirectory:n=>{const r=ce(n);return r?Ap().filter(o=>y3(o)===r):[]},getDirectoryForSession:n=>{const r=n===t().currentSessionId?t().currentSessionDirectory:null,s=Hg(n,r);if(s)return s;try{return Je().getState().catalog.byId.get(n)?.directory??null}catch{return null}},adoptAuthoritativeSessionDirectory:n=>{const r=n??t().currentSessionId;if(!r||r!==Dg()||r!==t().currentSessionId)return;const s=hM(r);s&&(Og(),s!==t().currentSessionDirectory&&e({currentSessionDirectory:s}),Ps(qn(),{sessionId:r,directory:s}))},setSessionDirectory:(n,r)=>{const s=ce(r);n===Dg()&&Og(),n===t().currentSessionId&&(e({currentSessionDirectory:s}),Ps(qn(),{sessionId:n,directory:s}))}})),RZ=Object.freeze(Object.defineProperty({__proto__:null,draftBranchCheckoutReceiptMatches:Hi,getRememberedSessionDirectory:pM,materializeOpenDraftSession:b3,routeMessage:lh,useSessionUIStore:ve},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 xM(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 Op=z.createContext(void 0);function Fn(){const e=z.useContext(Op);if(!e)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return e}function w3(){return z.useContext(Op)}const S3=async(e,t)=>{if(!Nw())throw new Error("Desktop runtime is not available");return Qn(e,t)},bM=async e=>{if(xt())try{await S3("desktop_set_window_title",{title:e})}catch{}},wM=async(e,t)=>{if(xt())try{await S3("desktop_set_window_theme",{themeMode:e,themeVariant:t})}catch{}},Tu=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 SM{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(`
21
- `)}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=Tu(t.colors.surface.muted),s=Tu(t.colors.surface.subtle),o=Tu(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,u)=>{n.push(` --chart-${u+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 {
22
- ${n}
23
- }
24
-
25
- .dark {
26
- ${n}
27
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(s=`:root {
28
- ${n}
29
- }
30
-
31
- :root:not(.dark) {
32
- ${n}
33
- }`,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=Rw;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 Vg=(e,t)=>t.reduce((n,r)=>n&&typeof n=="object"?n[r]:void 0,e),CM=e=>typeof e=="string"&&e.trim().length>0,Bg=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(!CM(Vg(e,r)))return!1;const n=Vg(e,["metadata","variant"]);return n==="light"||n==="dark"},kM=Ow,MM=Dw,IM=e=>Fw(e==="dark"),_M=typeof window<"u"?h.useLayoutEffect:h.useEffect,EM=()=>{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")}},jM=e=>{let t=kM,n=MM,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 f=g1(c);f&&(r=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?n=f.metadata.id:t=f.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=g1(e);s&&(s.metadata.variant==="light"?t=s.metadata.id:n=s.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function PZ({children:e,defaultThemeId:t}){const n=z.useMemo(()=>new SM,[]),[r,s]=z.useState(()=>jM(t)),[o,i]=z.useState(()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches),[a,c]=z.useState([]),[d,u]=z.useState([]),[f,p]=z.useState(!1),m=z.useMemo(()=>xt(),[]),g=z.useRef(0),y=z.useMemo(()=>{const A=[],j=new Set,N=O=>{const L=O.metadata.id;j.has(L)||(j.add(L),A.push(O))};return a.forEach(N),d.forEach(N),Pw.forEach(N),A},[a,d]);z.useEffect(()=>{const A=j=>{const N=j.detail;if(!Bg(N))return;const O=Hw(N);u(L=>{const P=L.findIndex(F=>F.metadata.id===O.metadata.id);if(P<0)return[...L,O];const W=[...L];return W[P]=O,W})};return window.addEventListener("pichamber:theme-hmr",A),()=>window.removeEventListener("pichamber:theme-hmr",A)},[]);const b=z.useCallback(A=>y.find(j=>j.metadata.id===A),[y]),k=z.useCallback((A,j)=>{const N=b(A);return N&&N.metadata.variant===j?N:y.find(L=>L.metadata.variant===j)??IM(j)},[y,b]),v=z.useMemo(()=>r.themeMode==="light"?k(r.lightThemeId,"light"):r.themeMode==="dark"||o?k(r.darkThemeId,"dark"):k(r.lightThemeId,"light"),[k,r,o]),x=z.useCallback(async()=>{if(typeof window>"u")return;const A=X(),j=++g.current;p(!0);try{const N=await Tt("/api/pi/themes",{method:"GET",credentials:Kc()?"omit":"include",headers:{Accept:"application/json"}});if(N.status===401||!N.ok)return;const O=await N.json();if(j!==g.current||A!==X())return;const P=(Array.isArray(O?.themes)?O.themes:[]).filter(Bg);c(P)}catch{}finally{j===g.current&&A===X()&&p(!1)}},[]);z.useEffect(()=>{x()},[x]),z.useEffect(()=>pn(A=>{A.runtimeKey!==A.previousRuntimeKey&&(g.current+=1,c([]),p(!1),x())}),[x]);const C=z.useCallback(A=>{if(typeof document>"u")return;const j=A.colors.surface.background;document.body.style.backgroundColor=j;let N=document.querySelector('meta[name="theme-color"]');N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),document.head.appendChild(N)),N.setAttribute("content",j);const O=A.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let L=document.querySelector(`meta[name="theme-color"][media="${O}"]`);L||(L=document.createElement("meta"),L.setAttribute("name","theme-color"),L.setAttribute("media",O),document.head.appendChild(L)),L.setAttribute("content",j)},[]),S=z.useRef(!1);_M(()=>{if(typeof window>"u")return;const A=S.current?EM():void 0;S.current=!0,n.apply(v),C(v);const j=document.documentElement;return j.classList.remove("light","dark"),j.classList.add(v.metadata.variant),A},[n,v,C]),z.useEffect(()=>{if(r.themeMode!=="system"||typeof window>"u")return;const A=window.matchMedia("(prefers-color-scheme: dark)"),j=N=>{i(N.matches)};return i(A.matches),A.addEventListener("change",j),()=>A.removeEventListener("change",j)},[r.themeMode]),z.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=k(r.lightThemeId,"light"),j=k(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,k]),z.useEffect(()=>{if(typeof window>"u")return;const A=j=>{j.storageArea===window.localStorage&&(j.key!=="themeMode"&&j.key!=="lightThemeId"&&j.key!=="darkThemeId"||s(N=>{const O=localStorage.getItem("themeMode"),L=O==="light"||O==="dark"||O==="system"?O:N.themeMode,P=localStorage.getItem("lightThemeId"),W=typeof P=="string"&&P.trim().length>0?P.trim():N.lightThemeId,F=localStorage.getItem("darkThemeId"),q=typeof F=="string"&&F.trim().length>0?F.trim():N.darkThemeId;return L===N.themeMode&&W===N.lightThemeId&&q===N.darkThemeId?N:{themeMode:L,lightThemeId:W,darkThemeId:q}}))};return window.addEventListener("storage",A),()=>window.removeEventListener("storage",A)},[]),z.useEffect(()=>{const A=k(r.lightThemeId,"light"),j=k(r.darkThemeId,"dark");_r({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,k,r.themeMode,r.lightThemeId,r.darkThemeId]),z.useEffect(()=>{m&&(async()=>await wM(r.themeMode,v.metadata.variant))()},[v.metadata.variant,m,r.themeMode]),z.useEffect(()=>{if(typeof window>"u")return;const A=j=>{const N=j.detail;N&&s(O=>{let L=O.themeMode;N.useSystemTheme===!0?L="system":N.useSystemTheme===!1&&(N.themeVariant==="dark"||N.themeVariant==="light")&&(L=N.themeVariant);let P=O.lightThemeId;typeof N.lightThemeId=="string"&&N.lightThemeId.length>0&&(P=N.lightThemeId.trim());let W=O.darkThemeId;return typeof N.darkThemeId=="string"&&N.darkThemeId.length>0&&(W=N.darkThemeId.trim()),L===O.themeMode&&P===O.lightThemeId&&W===O.darkThemeId?O:{themeMode:L,lightThemeId:P,darkThemeId:W}})};return window.addEventListener("pichamber:settings-synced",A),()=>window.removeEventListener("pichamber:settings-synced",A)},[]);const w=z.useCallback(A=>{const j=y.find(N=>N.metadata.id===A);j&&s(N=>j.metadata.variant==="dark"?N.darkThemeId===j.metadata.id&&N.themeMode==="dark"?N:{...N,darkThemeId:j.metadata.id,themeMode:"dark"}:N.lightThemeId===j.metadata.id&&N.themeMode==="light"?N:{...N,lightThemeId:j.metadata.id,themeMode:"light"})},[y]),M=z.useCallback(A=>{r.themeMode!==A&&(s(j=>({...j,themeMode:A})),_r({themeVariant:A==="system"?v.metadata.variant:A,useSystemTheme:A==="system"}))},[v.metadata.variant,r.themeMode]),I=z.useCallback(A=>{if(A){s(N=>N.themeMode==="system"?N:{...N,themeMode:"system"});return}const j=v.metadata.variant==="dark"?"dark":"light";s(N=>N.themeMode===j?N:{...N,themeMode:j})},[v.metadata.variant]),E=z.useCallback(A=>{const j=y.find(N=>N.metadata.id===A&&N.metadata.variant==="light");j&&s(N=>N.lightThemeId===j.metadata.id?N:{...N,lightThemeId:j.metadata.id})},[y]),_=z.useCallback(A=>{const j=y.find(N=>N.metadata.id===A&&N.metadata.variant==="dark");j&&s(N=>N.darkThemeId===j.metadata.id?N:{...N,darkThemeId:j.metadata.id})},[y]),T={currentTheme:v,availableThemes:y,setTheme:w,customThemesLoading:f,reloadCustomThemes:x,isSystemPreference:r.themeMode==="system",setSystemPreference:I,themeMode:r.themeMode,setThemeMode:M,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:E,setDarkThemePreference:_};return l.jsx(Op.Provider,{value:T,children:e})}let ll=null;const DZ=()=>{if(typeof window>"u"||ll)return()=>{};let e={showDeletionDialog:se.getState().showDeletionDialog,nativeNotificationsEnabled:se.getState().nativeNotificationsEnabled,notificationMode:se.getState().notificationMode,notifyOnCompletion:se.getState().notifyOnCompletion,notifyOnError:se.getState().notifyOnError,summarizeLastMessage:se.getState().summarizeLastMessage,summaryThreshold:se.getState().summaryThreshold,summaryLength:se.getState().summaryLength,maxLastMessageLength:se.getState().maxLastMessageLength,autoDeleteEnabled:se.getState().autoDeleteEnabled,autoSaveEnabled:se.getState().autoSaveEnabled,autoDeleteAfterDays:se.getState().autoDeleteAfterDays,sessionRetentionAction:se.getState().sessionRetentionAction,fontSize:se.getState().fontSize,terminalFontSize:se.getState().terminalFontSize,terminalShell:se.getState().terminalShell,terminalLoginShells:se.getState().terminalLoginShells,editorFontSize:se.getState().editorFontSize,uiFont:se.getState().uiFont,monoFont:se.getState().monoFont,padding:se.getState().padding,cornerRadius:se.getState().cornerRadius,inputBarOffset:se.getState().inputBarOffset,mobileKeyboardMode:se.getState().mobileKeyboardMode,diffLayoutPreference:se.getState().diffLayoutPreference,gitChangesViewMode:se.getState().gitChangesViewMode};const t=se.subscribe(s=>{const o={showDeletionDialog:s.showDeletionDialog,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode,notifyOnCompletion:s.notifyOnCompletion,notifyOnError:s.notifyOnError,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.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&&_r(i)});let n=!1;const r=()=>{n||(n=!0,t(),ll===r&&(ll=null))};return ll=r,r},$s={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},C3={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1,hasTouchOnlyPointer:!1},TM=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).get("surface")==="desktop",AM=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}},LM=(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 gd(){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=xt()||TM(),{isExplicitTablet:c}=AM(i),d=s||o||i>0,u=s||o,f=e>$s.md&&e<=$s.lg,p=e<=$s.md;let m=d&&p,g=d&&!m&&(f||c),y=!d||!g&&e>$s.lg,b="desktop";a?(m=!1,g=!1,y=!0,b="desktop"):rn()?(m=!0,g=!1,y=!1,b="mobile"):m?b="mobile":g?b="tablet":(y=!0,b="desktop"),LM(a,b,d);let k="xs";for(const[v,x]of Object.entries($s))e>=x&&(k=v);return{isMobile:m,isTablet:g,isDesktop:y,deviceType:b,screenWidth:e,breakpoint:k,hasTouchInput:d,hasTouchOnlyPointer:u}}const NM=(e,t)=>e.isMobile===t.isMobile&&e.isTablet===t.isTablet&&e.isDesktop===t.isDesktop&&e.deviceType===t.deviceType&&e.screenWidth===t.screenWidth&&e.breakpoint===t.breakpoint&&e.hasTouchInput===t.hasTouchInput&&e.hasTouchOnlyPointer===t.hasTouchOnlyPointer,Wl=new Set;let Mr=null,ao,Yo=null;const RM=()=>typeof window>"u"?C3:(Mr||(Mr=gd()),Mr),PM=()=>{for(const e of Wl)e()},DM=()=>{ao=void 0;const e=gd();Mr&&NM(Mr,e)||(Mr=e,PM())},cl=()=>{typeof window>"u"||ao!==void 0||(ao=window.requestAnimationFrame(DM))},_c=(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)):()=>{}:()=>{},OM=()=>{if(typeof window>"u")return()=>{};Mr=gd(),window.addEventListener("resize",cl);const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null,t=typeof window.matchMedia=="function"?window.matchMedia("(hover: none)"):null,n=_c(e,cl),r=_c(t,cl);return()=>{window.removeEventListener("resize",cl),n(),r(),ao!==void 0&&(window.cancelAnimationFrame(ao),ao=void 0)}},HM=e=>typeof window>"u"?()=>{}:(Wl.add(e),Yo||(Yo=OM()),()=>{Wl.delete(e),Wl.size===0&&Yo&&(Yo(),Yo=null,Mr=null)}),FM=()=>typeof window>"u"?!1:!!(navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)")?.matches||window.matchMedia?.("(display-mode: fullscreen)")?.matches),$g=()=>{if(typeof window>"u"||xt())return!1;const e=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return FM()&&e>0&&window.innerWidth>$s.md};function OZ(){const[e,t]=h.useState(()=>$g());return h.useEffect(()=>{if(typeof window>"u")return;const n=()=>t($g()),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 VM=()=>typeof window>"u"?"portrait":window.matchMedia?.("(orientation: landscape)")?.matches?"landscape":"portrait";function HZ(){const[e,t]=h.useState(VM);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(),_c(n,r)},[]),e}const BM=600,$M=1e3,Hp=()=>{if(typeof window>"u")return{enabled:!1,roomyForPanels:!1};const e=window.innerWidth,t=window.innerHeight,n=Vw()||Math.min(e,t)>=BM;return{enabled:n,roomyForPanels:n&&e>t&&e>=$M}},zM=(e,t)=>e.enabled===t.enabled&&e.roomyForPanels===t.roomyForPanels,k3={enabled:!1,roomyForPanels:!1},ql=new Set;let Ir=null,lo,Xo=null;const UM=()=>typeof window>"u"?k3:(Ir||(Ir=Hp()),Ir),ZM=()=>{for(const e of ql)e()},WM=()=>{lo=void 0;const e=Hp();Ir&&zM(Ir,e)||(Ir=e,ZM())},Au=()=>{typeof window>"u"||lo!==void 0||(lo=window.requestAnimationFrame(WM))},qM=()=>{if(typeof window>"u")return()=>{};Ir=Hp(),window.addEventListener("resize",Au);const e=typeof window.matchMedia=="function"?window.matchMedia("(orientation: landscape)"):null,t=_c(e,Au);return()=>{window.removeEventListener("resize",Au),t(),lo!==void 0&&(window.cancelAnimationFrame(lo),lo=void 0)}},GM=e=>typeof window>"u"?()=>{}:(ql.add(e),Xo||(Xo=qM()),()=>{ql.delete(e),ql.size===0&&Xo&&(Xo(),Xo=null,Ir=null)});function yd(){return h.useSyncExternalStore(GM,UM,()=>k3)}function Rr(){return h.useSyncExternalStore(HM,RM,()=>C3)}const Fp=e=>{const t=e;return ce(t.directory??null)??ce(t.project?.worktree??null)},Lu=(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},fh=(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},KM=(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])&&fh(e[r],t[r]))},zg=()=>{const e=se.getState();return{favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts}},Ug=(e,t)=>Lu(e.favoriteModels,t.favoriteModels)&&Lu(e.hiddenModels,t.hiddenModels)&&fh(e.collapsedModelProviders,t.collapsedModelProviders)&&Lu(e.recentModels,t.recentModels)&&fh(e.recentAgents,t.recentAgents)&&KM(e.recentEfforts,t.recentEfforts),Zg=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()]))}),FZ=()=>{if(typeof window>"u")return()=>{};let e=null,t=Zg(zg()),n=null;const r=(a=!1)=>{e=null;const c=n;if(n=null,!c||c!==X())return;const d=zg();t&&Ug(t,d)||(t=Zg(d),_r(d,{immediate:a}).catch(()=>{}))},s=()=>{e!==null&&window.clearTimeout(e),n=X(),e=window.setTimeout(r,1200)},o=np(a=>{a.runtimeKey!==a.previousRuntimeKey&&(e!==null&&window.clearTimeout(e),r(!0),t=null)}),i=se.subscribe((a,c)=>{const d={favoriteModels:a.favoriteModels,hiddenModels:a.hiddenModels,collapsedModelProviders:a.collapsedModelProviders,recentModels:a.recentModels,recentAgents:a.recentAgents,recentEfforts:a.recentEfforts},u={favoriteModels:c.favoriteModels,hiddenModels:c.hiddenModels,collapsedModelProviders:c.collapsedModelProviders,recentModels:c.recentModels,recentAgents:c.recentAgents,recentEfforts:c.recentEfforts};Ug(d,u)||s()});return()=>{i(),o(),e!==null&&window.clearTimeout(e),r(!0)}};let Nu=null;const Vp=()=>(Nu??=mt(()=>import("./MarkdownRendererImpl-DzgDmUsL.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 Nu=null,e}),Nu),VZ=()=>{Vp().catch(()=>{})},M3={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"/>'},Wg="pichamber-icon-sprite";let Ru=!1;function YM(){if(Ru||typeof document>"u")return;const e=document.body;if(!e)return;if(document.getElementById(Wg)){Ru=!0;return}const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.id=Wg,n.setAttribute("aria-hidden","true"),n.style.display="none",n.innerHTML=Object.entries(M3).map(([r,s])=>`<symbol id="oc-${r}" viewBox="0 0 24 24">${s}</symbol>`).join(""),e.insertBefore(n,e.firstChild),Ru=!0}const V=h.memo(({name:e,className:t,...n})=>(typeof document<"u"&&YM(),l.jsx("svg",{className:R("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}`})})));V.displayName="Icon";let dl=0;function XM(e,t){return e&&z.isValidElement(t)?{render:t}:{children:t}}function vd({...e}){return l.jsx(R7,{...e})}function JM({asChild:e,children:t,...n}){const r=XM(e,t);return l.jsx(B7,{"data-slot":"dialog-trigger",...n,...r})}function QM({...e}){return l.jsx(F7,{...e})}const I3=z.forwardRef(({className:e,...t},n)=>(z.useEffect(()=>(dl+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{dl=Math.max(0,dl-1),dl===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),l.jsx(V7,{ref:n,"data-slot":"dialog-overlay",className:R("oc-glass-backdrop fixed inset-0 z-50 bg-black/25 dark:bg-black/40","transition-opacity duration-150 ease-out","data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",e),...t})));I3.displayName="DialogOverlay";function xd({className:e,children:t,showCloseButton:n=!0,...r}){return l.jsxs(QM,{children:[l.jsx(I3,{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(P7,{"data-slot":"dialog-content","data-state-slot":"dialog",className:R("relative pointer-events-auto bg-background text-foreground flex flex-col w-full max-w-lg max-h-full gap-4 rounded-xl border p-6 shadow-none overflow-y-auto pwa-dialog-content origin-center","transition-all duration-150 ease-out","data-[starting-style]:opacity-0 data-[starting-style]:scale-[0.98]","data-[ending-style]:opacity-0 data-[ending-style]:scale-[0.98]","data-[nested-dialog-open]:brightness-[0.55] dark:data-[nested-dialog-open]:brightness-[0.4]",e),...r,children:[t,n&&l.jsxs(D7,{"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(V,{name:"close"}),l.jsx("span",{className:"sr-only",children:"Close"})]})]})})]})}function bd({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",e),...t})}function eI({className:e,...t}){return l.jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",e),...t})}function wd({className:e,...t}){return l.jsx(O7,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",e),...t})}function Bp({className:e,...t}){return l.jsx(H7,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",e),...t})}function Ar({className:e,type:t,...n}){return l.jsx("input",{type:t,"data-slot":"input",className:R("text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent","focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none","aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...n})}function tI(...e){return t=>{for(const n of e)n&&(typeof n=="function"?n(t):n.current=t)}}function nI(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 rI=z.forwardRef(function({children:t,...n},r){if(!z.isValidElement(t))return null;const s=t;return z.cloneElement(s,{...nI(s.props,n),ref:tI(r,s.ref)})}),sI=["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(" "),oI=["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(" "),iI=["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(" "),aI=N5(["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:sI,destructive:R(oI,"focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40"),info:iI,neutral:"bg-interactive-hover text-foreground border border-border/60 hover:bg-interactive-active",outline:"bg-[var(--surface-elevated)] text-foreground border border-border/60 hover:bg-interactive-hover hover:text-foreground",chip:R("border border-border/60 bg-transparent text-foreground hover:bg-interactive-hover hover:text-foreground","aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_10%,var(--background))]","aria-pressed:text-[var(--primary-base)]","aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_12%,transparent)]","aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_16%,var(--background))]","aria-pressed:hover:text-[var(--primary-base)]","dark:aria-pressed:bg-[color-mix(in_srgb,var(--primary-base)_16%,transparent)]","dark:aria-pressed:border-[color-mix(in_srgb,var(--primary-base)_20%,transparent)]","dark:aria-pressed:hover:bg-[color-mix(in_srgb,var(--primary-base)_22%,transparent)]"),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 Ee({className:e,variant:t,size:n,asChild:r=!1,type:s,...o}){const i=r?rI:"button",a=r?s===void 0?{}:{type:s}:{type:s??"button"};return l.jsx(i,{"data-slot":"button",className:R(aI({variant:t,size:n,className:e})),...a,...o})}const lI=600,cI=1600,qg=10,_3=z.createContext(null);class E3 extends z.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function dI({delayDuration:e=0,skipDelayDuration:t,delay:n,closeDelay:r,...s}){return l.jsx($7,{delay:n??e,closeDelay:r??t,...s})}function ft({delayDuration:e,open:t,onOpenChange:n,...r}){const[s,o]=z.useState(!1),i=z.useRef(null),a=z.useRef(null),c=z.useRef(null),d=z.useRef(!1),u=t!==void 0,f=u?t:s,p=z.useCallback(()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),m=z.useCallback(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[]),g=z.useCallback(v=>{u||o(v)},[u]),y=z.useMemo(()=>({handlePointerDown:v=>{v.pointerType!=="touch"&&v.pointerType!=="pen"||(p(),m(),c.current={x:v.clientX,y:v.clientY},i.current=window.setTimeout(()=>{u||(d.current=!0,g(!0))},lI))},handlePointerMove:v=>{const x=c.current;if(!x)return;const C=Math.abs(v.clientX-x.x),S=Math.abs(v.clientY-x.y);(C>qg||S>qg)&&(p(),c.current=null)},handlePointerEnd:()=>{p(),c.current=null,d.current&&(m(),a.current=window.setTimeout(()=>{d.current=!1,g(!1)},cI))},handleClickCapture:v=>{d.current&&(d.current=!1,v.preventDefault(),v.stopPropagation())},handleContextMenu:v=>{d.current&&v.preventDefault()}}),[m,p,u,g]);z.useEffect(()=>()=>{p(),m()},[m,p]);const b=z.useCallback((v,x)=>{u||o(v),n?.(v,x)},[u,n]),k=l.jsx(_3.Provider,{value:y,children:l.jsx(z7,{open:f,onOpenChange:b,...r})});return e===void 0?k:l.jsx(dI,{delayDuration:e,children:k})}function ht({asChild:e,children:t,onPointerDown:n,onPointerMove:r,onPointerUp:s,onPointerCancel:o,onClickCapture:i,onContextMenu:a,...c}){const d=z.useContext(_3),u=e&&z.isValidElement(t)?{render:t}:{children:t};return l.jsx(E3,{fallback:t,children:l.jsx(U7,{"data-slot":"tooltip-trigger",onPointerDown:f=>{n?.(f),d?.handlePointerDown(f)},onPointerMove:f=>{r?.(f),d?.handlePointerMove(f)},onPointerUp:f=>{s?.(f),d?.handlePointerEnd()},onPointerCancel:f=>{o?.(f),d?.handlePointerEnd()},onClickCapture:f=>{d?.handleClickCapture(f),!f.defaultPrevented&&i?.(f)},onContextMenu:f=>{d?.handleContextMenu(f),!f.defaultPrevented&&a?.(f)},...c,...u})})}function pt({className:e,sideOffset:t=0,side:n,align:r,children:s,style:o,...i}){return l.jsx(E3,{children:l.jsx(Z7,{children:l.jsx(W7,{sideOffset:t,side:n,align:r,className:"z-50",children:l.jsxs(q7,{"data-slot":"tooltip-content",className:R("oc-glass-tooltip text-[var(--surface-elevated-foreground)] border border-border/60 transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 data-[instant]:transition-none data-[instant]:duration-0 z-50 w-fit origin-[var(--transform-origin)] rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden",e),style:{...o},...i,children:[s,l.jsx(G7,{className:"fill-[var(--surface-elevated)] z-50 size-2"})]})})})})}const Gg=async e=>{const t=await ir(e);t.ok||console.error("Failed to copy to clipboard:",t.error)},Ec=e=>e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(Ec).join(" ").trim():z.isValidElement(e)?Ec(e.props?.children):"",uI=e=>typeof e=="function"?e():e,Kg=(e,t)=>{const n=Ec(uI(t?.description));return n.length>0?n:Ec(e)},Ne={...Zo,success:(e,t)=>Zo.success(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),info:(e,t)=>Zo.info(e,{...t,action:t?.action||{label:"OK",onClick:()=>{}}}),error:(e,t)=>Zo.error(e,{...t,action:t?.action||{label:"Copy",onClick:()=>Gg(Kg(e,t))}}),warning:(e,t)=>Zo.warning(e,{...t,action:t?.action||{label:"Copy",onClick:()=>Gg(Kg(e,t))}})},Yg={},Xg=e=>{const t=Xn(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}},Jg=async()=>vo()?qw().catch(()=>""):"",fI=e=>e==="ok"?"bg-status-success":e==="auth"||e==="update-recommended"?"bg-status-warning":e==="incompatible"||e==="wrong-service"||e==="unreachable"?"bg-status-error":e==="checking"?"bg-status-info":"bg-muted-foreground/40",hI=e=>e==="ok"?"text-[var(--status-success)]":e==="auth"||e==="update-recommended"?"text-[var(--status-warning)]":e==="incompatible"||e==="wrong-service"||e==="unreachable"?"text-[var(--status-error)]":"text-muted-foreground",Pu=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",ul=e=>e==="unreachable"||e==="wrong-service"||e==="incompatible",pI=e=>e==="ok"?"Connected":e==="auth"?"Auth required":e==="checking"?"Checking":e==="update-recommended"?"Update recommended":e==="incompatible"?"Incompatible":e==="wrong-service"?"Wrong service":e==="unreachable"?"Unreachable":"Unknown";function mI({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){const s=se(B=>B.setSettingsDialogOpen),o=se(B=>B.setSettingsPage),[i,a]=z.useState([]),[c,d]=z.useState(null),[u,f]=z.useState(()=>({...Yg}));z.useEffect(()=>{Object.assign(Yg,u)},[u]);const[p,m]=z.useState(!1),[g,y]=z.useState(!1),[b,k]=z.useState(!1),[v,x]=z.useState(null),[C,S]=z.useState(""),[w,M]=z.useState(()=>Bw()),[I,E]=z.useState(null),[_,T]=z.useState(""),[A,j]=z.useState(""),[N,O]=z.useState(0),L=z.useMemo(()=>{const B=Ww(w),ie=i.map(xe=>({...xe,url:Xn(xe.url)||xe.url}));return[B,...ie]},[i,w]);z.useEffect(()=>pn(()=>O(B=>B+1)),[]);const P=z.useMemo(()=>$w(L),[L,N]),W=z.useMemo(()=>{const B=c||Pt;return L.find(ie=>ie.id===B)?.label||"Local"},[L,c]),F=z.useCallback(async(B,ie)=>{if(xt()){k(!0),S("");try{const xe=B.filter(de=>de.id!==Pt);await Af({hosts:xe,defaultHostId:ie}),a(xe),d(ie)}catch(xe){S(xe instanceof Error?xe.message:"Failed to save")}finally{k(!1)}}},[]),q=z.useCallback(()=>{o("remote-instances"),s(!0),t(!1)},[t,s,o]),K=z.useCallback(async()=>{if(xt()){m(!0),S("");try{const B=await sp();B.localOrigin&&M(B.localOrigin),a(B.hosts||[]),d(B.defaultHostId??null)}catch(B){S(B instanceof Error?B.message:"Failed to load"),a([]),d(null)}finally{m(!1)}}},[]),Q=z.useCallback(async B=>{if(xt()){y(!0);try{const ie=await Jg(),xe=await Promise.all(B.map(async Se=>{const je=Se.id===Pt?ie:Se.clientToken||"",Oe=async()=>{const fe=await y1(Se.relay,{clientToken:je,requestHeaders:Se.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));return{status:fe.status,latencyMs:fe.latencyMs,...fe.status==="ok"?{via:"relay"}:{}}};if(Se.relay&&!Se.apiUrl)return[Se.id,await Oe()];const Be=Xn(vo()?Nl(Se):Se.url);if(!Be)return[Se.id,{status:"unreachable",latencyMs:0}];const Ie=await Jd(Be,{clientToken:je||null,requestHeaders:Se.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Pu(Ie.status)&&Se.relay){const fe=await Oe();if(fe.status==="ok")return[Se.id,fe]}return[Se.id,{status:Ie.status,latencyMs:Ie.latencyMs}]})),de={};for(const[Se,je]of xe)de[Se]=je;f(de)}finally{y(!1)}}},[]);z.useEffect(()=>{if(!e){E(null),T(""),j(""),x(null),S("");return}K()},[e,K]),z.useEffect(()=>{e&&Q(L)},[e,L,Q]);const D=z.useCallback(async B=>{const ie=(Oe,Be)=>{Be&&Gw({relayUrl:Oe.relayUrl,serverId:Oe.serverId,hostEncPubJwk:Oe.hostEncPubJwk},Be),Rl({apiBaseUrl:typeof window<"u"?window.location.origin:"",clientToken:B.clientToken||null,runtimeKey:Qd(B),relay:Oe}),Kw(B.id)},xe=B.id===Pt?w:Xn(B.url)||"",de=B.id===Pt?w:Xn(Nl(B))||"",Se=!!B.relay&&!B.apiUrl&&B.id!==Pt;if(!xe&&!Se)return;if(vo()){if(!de&&!B.relay)return;x(B.id);const Oe=B.id===Pt?await Jg():B.clientToken||"",Be=u[B.id];if(Be?.status==="ok"){Be.via==="relay"&&B.relay?ie(B.relay):de?Rl({apiBaseUrl:de,clientToken:Oe||null,requestHeaders:B.requestHeaders||null,runtimeKey:Qd(B)}):B.relay&&ie(B.relay),r?.(),x(null);return}let Ie={status:"unreachable",latencyMs:0},fe=null;if(de){const he=await Jd(de,{clientToken:Oe||null,requestHeaders:B.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));Ie={status:he.status,latencyMs:he.latencyMs},Pu(he.status)||(fe="direct")}let ee;if(!fe&&B.relay){const he=await y1(B.relay,{keepTunnel:!0,clientToken:Oe||null,requestHeaders:B.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));he.status==="ok"&&(Ie={status:he.status,latencyMs:he.latencyMs,via:"relay"},fe="relay",ee="tunnel"in he?he.tunnel:void 0)}if(f(he=>({...he,[B.id]:Ie})),!fe){Ne.error(`Instance "${Nn(B.label)}" is unreachable`),x(null);return}fe==="relay"&&B.relay?ie(B.relay,ee):Rl({apiBaseUrl:de,clientToken:Oe||null,requestHeaders:B.requestHeaders||null,runtimeKey:Qd(B)}),r?.(),x(null);return}if(B.id!==Pt&&xt()){x(B.id);const Oe=await Jd(xe,{clientToken:B.clientToken||null,requestHeaders:B.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(f(Be=>({...Be,[B.id]:{status:Oe.status,latencyMs:Oe.latencyMs}})),Pu(Oe.status)){Ne.error(`Instance "${Nn(B.label)}" is unreachable`),x(null);return}}const je=Xg(xe);r?.();try{window.location.assign(je)}catch{window.location.href=je}},[w,r,u]),U=z.useCallback(()=>{E(null),T(""),j("")},[]),Y=z.useCallback(B=>{B.stopPropagation()},[]),ne=z.useCallback(async()=>{if(!I)return;if(I===Pt){U();return}const B=zw(A);if(!B){S("Invalid URL (must be http/https)");return}const ie=B.persistedUrl,xe=(_||Nn(ie)).trim(),de=i.map(Se=>Se.id===I?{...Se,label:xe,url:ie,apiUrl:ie}:Se);await F(de,c),U(),B.redeemUrl&&window.location.assign(B.redeemUrl)},[U,i,c,_,A,I,F]),$=z.useCallback(async B=>{await F(i,B===Pt?Pt:B)},[i,F]),J=z.useCallback(B=>{const ie=Se=>{Ne.error("Failed to open new window",{description:Se instanceof Error?Se.message:String(Se)})};if(B.relay&&B.id!==Pt){Uw(B.id).catch(ie);return}const xe=B.id===Pt?w:Nl(B);if(!xe)return;const de=Xg(xe);Zw(de,{clientToken:B.clientToken||null,requestHeaders:B.requestHeaders||null}).catch(ie)},[w]);if(!xt())return null;const G=xt(),ue=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:Nn(P.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:Nn(W)})]}),l.jsx("button",{type:"button",className:R("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:()=>{Q(L)},disabled:!G||p||g,"aria-label":"Refresh instances",children:l.jsx(V,{name:"refresh",className:R("h-4 w-4",g&&"animate-spin")})})]})}):l.jsxs(bd,{className:"flex-shrink-0",children:[l.jsxs(wd,{className:"flex items-center gap-2",children:[l.jsx(V,{name:"server",className:"h-5 w-5"}),"Instance"]}),l.jsx(Bp,{children:"Switch between Local 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:Nn(P.label)}),l.jsx("span",{className:"typography-meta text-muted-foreground",children:"Current default:"}),l.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Nn(W)})]}),l.jsx("div",{className:"flex items-center gap-1",children:l.jsxs(Ee,{type:"button",size:"sm",variant:"ghost",onClick:()=>{Q(L)},disabled:!G||p||g,children:[l.jsx(V,{name:"refresh",className:R("h-4 w-4",g&&"animate-spin")}),"Refresh"]})})]}),!G&&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:"Instance 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:R("space-y-1",n&&"space-y-1.5 px-3 py-1"),children:p?l.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading..."}):L.map(B=>{const ie=B.id===Pt,xe=B.id===P.id,de=(c||Pt)===B.id,Se=u[B.id]||null,je=Se?.status??"checking",Oe=I===B.id,Be=ie?w:Xn(B.url)||B.url,Ie=B.id===Pt?"Local":Nn(B.label),fe=B.relay&&!B.apiUrl?"via PiChamber Relay":Nn(Be);return l.jsxs("div",{className:R("group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden",n&&"rounded-xl bg-[var(--surface-muted)] px-3 py-2.5",n&&xe&&"bg-[var(--interactive-selection)]/25",Oe?"bg-interactive-hover/20":"hover:bg-interactive-hover/30"),children:[l.jsxs("button",{type:"button",className:R("flex items-center gap-2 flex-1 min-w-0 text-left",Oe&&"pointer-events-none opacity-70"),onClick:()=>{D(B)},disabled:v===B.id,"aria-label":`Switch to ${Ie}`,children:[l.jsx("span",{className:R("h-2 w-2 rounded-full flex-shrink-0",fI(je))}),l.jsxs("div",{className:"flex-1 min-w-0 space-y-0.5",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[l.jsx("span",{className:"typography-ui-label font-medium truncate text-foreground",children:Ie}),xe&&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("div",{className:R("typography-micro truncate",hI(je)),children:[pI(je),je==="ok"&&typeof Se?.latencyMs=="number"?` · ${Math.max(0,Math.round(Se.latencyMs))}ms ping`:"",Se?.via==="relay"?" · Relay":""]}),l.jsx("div",{className:"typography-micro text-muted-foreground/70 truncate font-mono",children:fe})]})]}),l.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx("button",{type:"button",className:R("h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",de?"text-primary hover:text-primary/80":"text-muted-foreground/60 hover:text-primary/80"),onClick:()=>{$(B.id)},"aria-label":de?"Default instance":"Set as default",disabled:b||!de&&ul(je),children:de?l.jsx(V,{name:"star-fill",className:"h-4 w-4"}):l.jsx(V,{name:"star",className:"h-4 w-4"})})}),l.jsx(pt,{sideOffset:6,children:de?"Default":"Set as default"})]}),l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx("button",{type:"button",className:R("h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors",ul(je)?"text-muted-foreground/30 cursor-not-allowed":"text-muted-foreground/60 hover:text-foreground"),onClick:ee=>{ee.stopPropagation(),J(B)},disabled:ul(je),"aria-label":"Open in new window",children:l.jsx(V,{name:"window",className:"h-4 w-4"})})}),l.jsx(pt,{sideOffset:6,children:ul(je)?"Instance unreachable":"Open in new window"})]})]})]},B.id)})})}),G&&I&&I!==Pt&&l.jsxs("div",{className:"flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Edit instance"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ee,{type:"button",variant:"outline",size:"sm",onClick:U,disabled:b,children:"Cancel"}),l.jsxs(Ee,{type:"button",size:"sm",onClick:()=>{ne()},disabled:b,children:[b?l.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}):null,"Save"]})]})]}),l.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2",children:[l.jsx(Ar,{value:_,onChange:B=>T(B.target.value),onKeyDown:Y,placeholder:"Label",disabled:b}),l.jsx(Ar,{value:A,onChange:B=>j(B.target.value),onKeyDown:Y,placeholder:"https://host:port",disabled:b})]})]}),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:q,children:[l.jsx(V,{name:"add",className:"h-4 w-4"}),l.jsx("span",{className:"typography-ui-label",children:"Add instance"})]})}),C&&l.jsx("div",{className:"flex-shrink-0 typography-meta text-status-error",children:C})]});return n?l.jsx("div",{className:"w-full max-h-[70vh] flex flex-col overflow-hidden gap-2",children:ue}):l.jsx(vd,{open:e,onOpenChange:t,children:l.jsx(xd,{className:"w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3",children:ue})})}function j3(){const[e,t]=z.useState(!1);return xt()?l.jsxs(l.Fragment,{children:[l.jsxs(Ee,{type:"button",variant:"ghost",size:"sm","data-oc-host-switcher":!0,className:"w-full justify-center",onClick:()=>t(!0),children:[l.jsx(V,{name:"server",className:"h-4 w-4"}),"Switch instance"]}),l.jsx(mI,{open:e,onOpenChange:t})]}):null}const Qg=z.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]",u=t||s;return l.jsx(K7,{checked:t,onCheckedChange:f=>n(!!f),disabled:r,indeterminate:s,"aria-label":o,className:R("group/checkbox relative flex shrink-0 self-center items-center justify-center rounded-[4px] border outline-none",c,"transition-[background-color,border-color,box-shadow] duration-200 ease-out",u?"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(Y7,{keepMounted:!0,className:R("flex items-center justify-center text-[var(--primary-base)]","data-[unchecked]:hidden",a),children:s?l.jsx(V,{name:"subtract",className:R(d,"text-[var(--primary-base)]")}):l.jsx(V,{name:"check",className:R(d,"text-[var(--primary-base)]")})})})}),$p=({className:e="",width:t=70,height:n=70,isAnimated:r=!1})=>{const s=w3(),i=z.useId().replace(/[^a-zA-Z0-9_-]/g,""),a=`pc-shimmer-mask-${i}`,c=`pc-shimmer-grad-${i}`,d=z.useMemo(()=>{if(s)return s.currentTheme.colors.surface.foreground;if(typeof window<"u"){const u=getComputedStyle(document.documentElement).getPropertyValue("--splash-stroke").trim();return u||(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]})},T3=({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})]})},gI=()=>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($p,{width:120,height:120,isAnimated:!0})}),e2=({onRetry:e,errorType:t="network",retryAfter:n,children:r})=>{const s=t==="rate-limit",o=n?Math.ceil(n/60):1;return l.jsx(T3,{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(Ee,{type:"button",onClick:e,className:"w-full max-w-xs",children:"Retry"}),r]})})},yI=({isTunnelLocked:e,password:t,setPassword:n,passwordInputRef:r,isSubmitting:s,errorMessage:o,setErrorMessage:i,trustDevice:a,setTrustDevice:c,supportsPasskeys:d,passkeyStatus:u,isPasskeyBusy:f,activePasskeyAction:p,showHostSwitcher:m,onSubmit:g,onPasskeyUnlock:y,onPasskeySetupOnly:b})=>{const k=d&&u.hasPasskeys,v=d&&!u.hasPasskeys;return l.jsx(T3,{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:[k&&l.jsxs(Ee,{type:"button",variant:"outline",className:"w-full",onClick:()=>{y()},disabled:s||f&&p!=="auth",children:[f?l.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}):l.jsx(V,{name:"lock-unlock",className:"h-4 w-4"}),l.jsx("span",{children:f&&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(V,{name:"lock",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),l.jsx(Ar,{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(Ee,{type:"submit",size:"icon",disabled:!t||s,"aria-label":s?"Unlocking":"Unlock",children:s?l.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}):l.jsx(V,{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(Qg,{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(Ee,{type:"button",variant:"ghost",size:"sm",className:"text-muted-foreground hover:text-foreground",onClick:()=>{b()},disabled:s,children:f&&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(Qg,{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(j3,{}),l.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})})},vI="/auth/passkey/authenticate/options",xI="/auth/passkey/authenticate/verify",bI="/auth/passkey/register/options",wI="/auth/passkey/register/verify",A3="/api/passkeys",SI="/auth/passkey/status",CI="/api/auth/reset",Gl={enabled:!1,hasPasskeys:!1,passkeyCount:0,rpID:null},ra=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)}),hs=async(e,t)=>{try{const n=await e.json();if(n&&typeof n.error=="string"&&n.error.trim())return n.error}catch{}return t},Du=e=>e instanceof Q7&&e.code==="ERROR_CEREMONY_ABORTED",t2=()=>{X7.cancelCeremony()},L3=()=>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."},n2=async()=>{const e=L3();if(!e.supported)throw new Error(e.reason);const t=typeof navigator.userAgent=="string"&&navigator.userAgent.trim()?navigator.userAgent:"This device",n=await ra(bI,{label:t});if(!n.ok)throw new Error(await hs(n,"Could not start passkey setup."));const{requestId:r,optionsJSON:s}=await n.json(),o=await J7({optionsJSON:s}),i=await ra(wI,{requestId:r,response:o});if(!i.ok)throw new Error(await hs(i,"Could not finish passkey setup."));return i.json().catch(()=>null)},kI=async(e,t={})=>{const n=L3();if(!n.supported)throw new Error(n.reason);const r=await ra(vI);if(!r.ok)throw new Error(await hs(r,"Passkey sign-in is not available right now."));const{requestId:s,optionsJSON:o}=await r.json(),i=await e9({optionsJSON:o}),a=await ra(xI,{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 hs(a,"Passkey sign-in failed."));return a.json().catch(()=>null)},MI=async()=>{const e=await Tt(SI,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)return Gl;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}},BZ=async()=>{const e=await Tt(A3,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});if(!e.ok)throw new Error(await hs(e,"Could not load passkeys."));const t=await e.json().catch(()=>null);return Array.isArray(t?.passkeys)?t.passkeys:[]},$Z=async e=>{const t=await Tt(`${A3}/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"include",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(await hs(t,"Could not remove passkey."));return t.json().catch(()=>null)},zZ=async()=>{const e=await ra(CI);if(!e.ok)throw new Error(await hs(e,"Could not clear saved authentication."));return e.json().catch(()=>null)},II=(e,t)=>e.apiBaseUrl===t.apiBaseUrl&&e.runtimeKey===t.runtimeKey,_I=e=>e.shouldUseDesktopShellPasswordLogin?"locked":"error",N3="/auth/session",EI=4,jI=1500,R3="pichamber.uiAuth.trustDevice",TI="desktop-local",AI="desktop-local",LI=()=>{if(typeof window>"u")return"";const e=window.__PICHAMBER_LOCAL_ORIGIN__;return typeof e=="string"?e.trim():""},NI=(e,t)=>{const n=Xn(e),r=Xn(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},hh=()=>xt(),RI=e=>{const t=e.replace(/^\[|\]$/g,"");return t==="localhost"||t==="127.0.0.1"||t==="::1"},P3=()=>{if(!xt())return!1;const e=LI();if(!e)return!1;const n=qc()||(typeof window<"u"?window.location.origin:"");if(NI(e,n))return!0;try{const r=Xn(n);return!!(r&&RI(new URL(r).hostname))}catch{return!1}},zp=()=>P3()?{clientKind:TI,dedupeKey:AI}:{},PI=async()=>await Tt(N3,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),DI=()=>typeof window>"u"?!1:window.localStorage.getItem(R3)==="true",OI=async(e,t)=>{const n=hh();return await Tt(N3,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:"PiChamber Desktop",...zp()})})},HI=async()=>{if(!xt())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",...zp()})}).catch(()=>null);if(!e?.ok)return"";const t=await e.json().catch(()=>null);return typeof t?.token=="string"?t.token.trim():""},Ou=()=>xt()&&!P3(),qr=()=>({apiBaseUrl:qc(),runtimeKey:X()}),dt=e=>II(e,qr()),Hu=async(e,t,n,r)=>{if(!xt()||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}:{}}},FI=async(e,t)=>{if(!xt()||!t||!dt(e))return!1;const n=await sp().catch(()=>null);if(!n||!dt(e))return!1;const r=Yw({runtimeKey:e.runtimeKey,apiBaseUrl:e.apiBaseUrl,hosts:n.hosts,localOrigin:n.localOrigin});return r?r.kind==="local"?(await Af({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>{}),dt(e)):r.host.clientToken===t?!0:dt(e)?(await Af({hosts:n.hosts.map(s=>s.id===r.host.id?{...s,clientToken:t}:s),defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>{}),dt(e)):!1:!0},fl=async(e,t,n)=>!e||!dt(t)||!await FI(t,e)||!dt(t)?!1:(Rl({apiBaseUrl:t.apiBaseUrl,clientToken:e,requestHeaders:Object.keys(n).length>0?n:null,runtimeKey:t.runtimeKey}),!0);function VI(){const t=h.useMemo(()=>xt(),[]),[n,r]=h.useState(()=>"pending"),[s,o]=h.useState(""),[i,a]=h.useState(!1),[c,d]=h.useState(""),[u,f]=h.useState(void 0),[p,m]=h.useState(!1),[g,y]=h.useState(Gl),[b,k]=h.useState(!1),[v,x]=h.useState(!1),[C,S]=h.useState(()=>DI()),[w,M]=h.useState(null),I=h.useRef(null),E=h.useRef(!1);h.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(R3,C?"true":"false")},[C]);const _=h.useCallback(async(U=qr())=>{try{const Y=await MI();return dt(U)&&y(Y),Y}catch{return dt(U)&&y(Gl),Gl}},[!1]);h.useEffect(()=>{let U=!1;return(async()=>{try{if(!window.isSecureContext||!t9()){U||k(!1);return}U||k(!0)}catch{U||k(!1)}})(),()=>{U=!0}},[!1]);const T=h.useRef(0),A=h.useRef(null),j=h.useRef(null),N=h.useCallback(()=>{A.current!==null&&(window.clearTimeout(A.current),A.current=null)},[]),O=h.useCallback(()=>{T.current=0,N()},[N]),L=h.useCallback(()=>T.current>=EI?!1:(T.current+=1,N(),A.current=window.setTimeout(()=>{A.current=null,j.current?.()},jI*T.current),!0),[N]);h.useEffect(()=>N,[N]);const P=h.useCallback(async()=>{const U=qr();r(Y=>Y==="authenticated"?Y:"pending");try{const[Y,ne]=await Promise.all([PI(),_(U)]),$=await Y.text();if(!dt(U))return;if(Y.ok){O(),r("authenticated"),m(!1),d(""),f(void 0);return}if(Y.status===401){let J={};try{J=JSON.parse($)}catch{J={}}O(),m(J.tunnelLocked===!0),y(ne),r("locked"),f(void 0);return}if(Y.status===429){let J={};try{J=JSON.parse($)}catch{J={}}O(),f(J.retryAfter),m(!1),r("rate-limited");return}if(L())return;r("error"),m(!1)}catch(Y){if(!dt(U))return;if(console.warn("Failed to check session status:",Y),_I({shouldUseDesktopShellPasswordLogin:Ou()})==="locked"){r("locked"),f(void 0),m(!1);return}if(L())return;r("error"),m(!1)}},[_,O,L,!1]);h.useEffect(()=>{j.current=P},[P]),h.useEffect(()=>{P()},[P,!1]),h.useEffect(()=>Xw(()=>{O(),P()}),[P,O,!1]),h.useEffect(()=>pn(()=>{t2(),o(""),d(""),f(void 0),m(!1),a(!1),M(null),x(!1),O(),r("pending"),P()}),[P,O,!1]),h.useEffect(()=>{n==="locked"&&(E.current=!1)},[!1,n]),h.useEffect(()=>{n==="locked"&&I.current&&(I.current.focus(),I.current.select())},[n]),h.useEffect(()=>{n==="authenticated"&&(E.current=!0)},[!1,n]);const W=h.useCallback(async()=>{const U=qr();M("register"),x(!0);try{await n2()}finally{dt(U)&&(M(null),x(!1))}dt(U)&&await _(U)},[_]),F=h.useCallback(()=>{t2(),M(null),x(!1)},[]),q=h.useCallback(async U=>{if(p||!s||i)return;v&&F();const Y=qr(),ne=v1();a(!0),d("");try{if(Ou()){const J=await Hu(s,C,Y,ne);if(!dt(Y))return;if(J?.token){if(o(""),m(!1),!await fl(J.token,Y,ne))return;r("authenticated");return}if(J?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(J?.status===429){f(void 0),m(!1),r("rate-limited");return}}const $=await OI(s,C);if(!dt(Y))return;if($.ok){const J=await $.json().catch(()=>null);if(!dt(Y))return;const G=hh();let ue="";if(G&&(ue=typeof J?.clientToken=="string"&&J.clientToken.trim()?J.clientToken.trim():"",!ue)){const B=await Hu(s,C,Y,ne);if(!dt(Y)||(ue=B?.token||await HI(),!dt(Y)))return}if(o(""),m(!1),ue&&!await fl(ue,Y,ne))return;if(U&&b)try{if(await W(),!dt(Y))return;Ne.success("Passkey added"),r("authenticated");return}catch(B){if(Du(B))Ne.message("Passkey setup canceled");else{const ie=B instanceof Error?B.message:"Passkey setup failed.";Ne.error(ie)}r("authenticated");return}r("authenticated");return}if($.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if($.status===429){const J=await $.json().catch(()=>({}));f(J.retryAfter),m(!1),r("rate-limited");return}d("Unexpected response from server."),m(!1),r("error")}catch($){if(!dt(Y))return;console.warn("Failed to submit UI password:",$);const J=Ou()?await Hu(s,C,Y,ne):null;if(!dt(Y))return;if(J?.token){if(o(""),m(!1),!await fl(J.token,Y,ne))return;r("authenticated");return}if(J?.status===401){d("Incorrect password. Try again."),m(!1),r("locked");return}if(J?.status===429){f(void 0),m(!1),r("rate-limited");return}d("Network error. Check connection and retry."),m(!1),r("error")}finally{dt(Y)&&a(!1)}},[F,v,i,p,s,W,b,C]),K=h.useCallback(async()=>{if(i||!b)return;if(v){F();return}x(!0),M("auth"),d("");const U=qr(),Y=v1();try{const ne=await kI(C,{issueClientToken:hh(),clientLabel:"PiChamber Desktop",...zp()});if(!dt(U))return;if(typeof ne?.clientToken=="string"&&ne.clientToken.trim()){const $=ne.clientToken.trim();if(!await fl($,U,Y))return}m(!1),r("authenticated")}catch(ne){if(!dt(U)||Du(ne))return;const $=ne instanceof Error?ne.message:"Passkey sign-in failed.";d($)}finally{dt(U)&&(M(null),x(!1))}},[F,v,i,b,C]),Q=h.useCallback(async()=>{if(i||!b)return;if(v){F();return}const U=qr();M("register"),x(!0);try{if(await n2(),!dt(U))return;Ne.success("Passkey added"),await _(U)}catch(Y){if(!dt(U))return;if(Du(Y))Ne.message("Passkey setup canceled");else{const ne=Y instanceof Error?Y.message:"Passkey setup failed.";Ne.error(ne)}}finally{dt(U)&&(M(null),x(!1))}},[F,v,i,_,b]);return{state:n,password:s,setPassword:o,passwordInputRef:I,isSubmitting:i,errorMessage:c,setErrorMessage:d,retryAfter:u,isTunnelLocked:p,passkeyStatus:g,supportsPasskeys:b,isPasskeyBusy:v,trustDevice:C,setTrustDevice:S,activePasskeyAction:w,showHostSwitcher:t,resetTransientRetry:O,checkStatus:P,handleSubmit:async U=>{U.preventDefault(),await q(!1)},handlePasswordUnlock:q,handlePasskeyUnlock:K,handlePasskeySetupOnly:Q}}const UZ=({children:e})=>{const{state:t,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,retryAfter:c,isTunnelLocked:d,passkeyStatus:u,supportsPasskeys:f,isPasskeyBusy:p,trustDevice:m,setTrustDevice:g,activePasskeyAction:y,showHostSwitcher:b,resetTransientRetry:k,checkStatus:v,handleSubmit:x,handlePasskeyUnlock:C,handlePasskeySetupOnly:S}=VI();return t==="pending"?l.jsx(gI,{}):t==="error"?l.jsx(e2,{onRetry:()=>{k(),v()},errorType:"network",children:b&&l.jsxs("div",{className:"w-full max-w-xs",children:[l.jsx(j3,{}),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(e2,{onRetry:()=>{v()},errorType:"rate-limit",retryAfter:c}):t==="locked"?l.jsx(yI,{isTunnelLocked:d,password:n,setPassword:r,passwordInputRef:s,isSubmitting:o,errorMessage:i,setErrorMessage:a,trustDevice:m,setTrustDevice:g,supportsPasskeys:f,passkeyStatus:u,isPasskeyBusy:p,activePasskeyAction:y,showHostSwitcher:b,onSubmit:x,onPasskeyUnlock:C,onPasskeySetupOnly:S}):l.jsx(l.Fragment,{children:e})},Sd=e=>{try{return new URL(e)}catch{return null}},ZZ=e=>{const t=Sd(e.trim());return t?t.protocol==="http:"||t.protocol==="https:":!1},BI=e=>{const t=Sd(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?null:`https://icons.duckduckgo.com/ip3/${t.hostname.toLowerCase()}.ico`},$I=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),zI=e=>{const t=Sd(e.trim());return!t||t.protocol!=="http:"&&t.protocol!=="https:"?!1:$I.has(t.hostname.toLowerCase())},UI=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi,ZI=e=>{if(!e)return[];const t=e.match(UI);if(!t||t.length===0)return[];const n=new Set,r=[];for(const s of t){const o=s.replace(/[),.;:!?'"`]+$/g,"");!o||!zI(o)||n.has(o)||(n.add(o),r.push(o))}return r},ph=async e=>{if(typeof window>"u")return!1;const t=e.trim();if(!t)return!1;const n=Sd(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 WI(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=gd();return e}catch{return"unknown"}}function qI(){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 GI(){const e=e7();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 KI(e){const t=new URLSearchParams;return t.set("deviceClass",WI()),t.set("arch",qI()),t.set("platform",GI()),e==="desktop"?(t.set("appType","desktop-electron"),t.set("instanceMode",Kc()?"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 Jo(e,t){try{const n=KI(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 YI(){return yr()?"mobile":vo()?"desktop":op()?"web":null}const r2={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,serverInfo:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},XI=Et()((e,t)=>({...r2,checkForUpdates:async()=>{const n=YI();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,s=null;if(n==="desktop"){const o="1.0.4",i=!Kc(),[a,c]=await Promise.allSettled([x1(),i?Jo("web"):Jo("desktop",o)]),d=a.status==="fulfilled"?a.value:null,u=c.status==="fulfilled"?c.value:null;return s=u?.nextSuggestedCheckInSec??null,e({checking:!1,available:d?.available??!1,info:d,serverInfo:i?u:null,lastChecked:Date.now(),nextCheckInSec:s}),s}else if(n==="web")r=await Jo("web"),s=r?.nextSuggestedCheckInSec??null;else if(n==="mobile"){const o="1.0.4",[i,a]=await Promise.all([Jo("mobile",o),Jo("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 x1();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 Qw(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 Jw())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(r2)}}));function JI({className:e,...t}){return l.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",e),...t})}function QI({className:e,...t}){return l.jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function e_({className:e,...t}){return l.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",e),...t})}function t_({className:e,...t}){return l.jsx("div",{"data-slot":"card-content",className:R("px-6",e),...t})}class n_ 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?`
34
-
35
- Stack:
36
- ${this.state.error.stack}`:"",s=this.state.errorInfo?.componentStack?`
37
-
38
- ${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(JI,{className:"w-full max-w-md",children:[l.jsx(QI,{className:"text-center",children:l.jsxs(e_,{className:"flex items-center justify-center gap-2 text-destructive",children:[l.jsx(V,{name:"error-warning",className:"h-5 w-5"}),t.title]})}),l.jsxs(t_,{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?`
39
-
40
- ${t.componentStackLabel}${this.state.errorInfo.componentStack}`:""]})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Ee,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[l.jsx(V,{name:"restart",className:"h-4 w-4 mr-2"}),t.tryAgain]}),l.jsx(Ee,{onClick:this.handleCopy,variant:"outline",className:"flex-1",children:this.state.copied?t.copied:t.copy})]})]})]})}):this.props.children}}const WZ=({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(n_,{fallback:t,strings:n,children:e})},r_=1e3,s2=.5,o2={length:0,offset:0},i2=(e,t)=>Math.abs(e.length-t.length)<s2&&Math.abs(e.offset-t.offset)<s2,D3=({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),[u,f]=h.useState({length:0,offset:0}),[p,m]=h.useState({length:0,offset:0}),g=h.useRef(null),y=h.useRef(null),b=h.useRef(null),k=h.useRef(!1),v=h.useRef(!1),x=h.useRef(0),C=h.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),S=h.useRef(null),w=h.useRef(new Set),M=h.useCallback(()=>{const K=e.current;if(!K)return;const{scrollHeight:Q,clientHeight:D,scrollTop:U,scrollWidth:Y,clientWidth:ne,scrollLeft:$}=K,J=8;let G=o2;if(Q>D){const B=Math.max(D-J*2,0),ie=D/Q*B,xe=Math.max(t,Math.min(B,ie)),de=Math.max(B-xe,0),Se=Math.max(Q-D,1),je=U/Se*de;G={length:xe,offset:je}}f(B=>i2(B,G)?B:G);let ue=o2;if(!s&&Y>ne){const B=Math.max(ne-J*2,0),ie=ne/Y*B,xe=Math.max(t,Math.min(B,ie)),de=Math.max(B-xe,0),Se=Math.max(Y-ne,1),je=$/Se*de;ue={length:xe,offset:je}}m(B=>i2(B,ue)?B:ue)},[e,t,s]),I=h.useCallback(()=>{b.current===null&&(b.current=requestAnimationFrame(()=>{b.current=null,M()}))},[M]),E=h.useCallback((K,Q)=>{if(!Q){w.current.clear();return}const D=new Set;D.add(K),Array.from(K.children).forEach(U=>{D.add(U)}),w.current.forEach(U=>{D.has(U)||Q.unobserve(U)}),D.forEach(U=>{w.current.has(U)||Q.observe(U)}),w.current=D},[]),_=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(()=>{y.current&&cancelAnimationFrame(y.current),y.current=requestAnimationFrame(()=>{if(M(),i&&!k.current){d(!1);return}if(a&&!k.current&&!(Date.now()-x.current<=r_)){d(!1);return}d(!0),_()})},[_,i,M,a]);h.useEffect(()=>{const K=e.current;if(!K)return;M(),d(!1);const Q=()=>A(),D=J=>{(J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="PageUp"||J.key==="PageDown"||J.key==="Home"||J.key==="End"||J.key===" ")&&T()};K.addEventListener("scroll",Q,{passive:!0}),a&&(K.addEventListener("wheel",T,{passive:!0}),K.addEventListener("touchstart",T,{passive:!0}),K.addEventListener("touchmove",T,{passive:!0}),K.addEventListener("keydown",D));const U=typeof ResizeObserver<"u"?new ResizeObserver(()=>{I()}):null;E(K,U);const Y=o&&typeof MutationObserver<"u"?new MutationObserver(()=>{E(K,U),I()}):null;Y?.observe(K,{childList:!0});const ne=()=>I(),$=()=>I();return K.addEventListener("input",ne,!0),K.addEventListener("load",$,!0),()=>{K.removeEventListener("scroll",Q),K.removeEventListener("input",ne,!0),K.removeEventListener("load",$,!0),a&&(K.removeEventListener("wheel",T),K.removeEventListener("touchstart",T),K.removeEventListener("touchmove",T),K.removeEventListener("keydown",D)),U?.disconnect(),Y?.disconnect(),w.current.clear(),g.current&&clearTimeout(g.current),y.current&&cancelAnimationFrame(y.current),b.current&&cancelAnimationFrame(b.current)}},[e,A,T,o,I,E,M,a]),h.useEffect(()=>{i&&(k.current||(d(!1),g.current&&(clearTimeout(g.current),g.current=null)))},[i]);const j=(K,Q)=>{const D=e.current;D&&(k.current=!0,C.current={pointerX:K.clientX,pointerY:K.clientY,scrollTop:D.scrollTop,scrollLeft:D.scrollLeft},S.current=Q,T(),d(!0),g.current&&clearTimeout(g.current),K.currentTarget.setPointerCapture(K.pointerId))},N=K=>{if(!k.current)return;const Q=e.current;if(!Q)return;const D=S.current;if(D==="vertical"){const{pointerY:U,scrollTop:Y}=C.current,ne=K.clientY-U,$=Q.clientHeight,J=Math.max($-u.length,1),G=Math.max(Q.scrollHeight-Q.clientHeight,1),ue=ne/J*G;Q.scrollTop=Y+ue}else if(D==="horizontal"){const{pointerX:U,scrollLeft:Y}=C.current,ne=K.clientX-U,$=Q.clientWidth,J=Math.max($-p.length,1),G=Math.max(Q.scrollWidth-Q.clientWidth,1),ue=ne/J*G;Q.scrollLeft=Y+ue}},O=K=>{k.current&&(k.current=!1,K.currentTarget.releasePointerCapture(K.pointerId),_())},L=h.useCallback(()=>{v.current=!0,g.current&&(clearTimeout(g.current),g.current=null)},[]),P=h.useCallback(()=>{v.current=!1,_()},[_]),W=u.length>0,F=p.length>0;if(!W&&!F)return null;const q=8;return l.jsxs("div",{className:R("overlay-scrollbar",r),"aria-hidden":"true",style:{opacity:c?1:0},children:[W&&l.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical","data-overlay-scrollbar-thumb":"vertical",style:{height:`${u.length}px`,top:`${q+u.offset}px`,right:`${q/2}px`},onPointerDown:K=>j(K,"vertical"),onPointerMove:N,onPointerUp:O,onPointerCancel:O,onMouseEnter:L,onMouseLeave:P}),F&&l.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal","data-overlay-scrollbar-thumb":"horizontal",style:{width:`${p.length}px`,left:`${q+p.offset}px`,bottom:`${q/2}px`},onPointerDown:K=>j(K,"horizontal"),onPointerMove:N,onPointerUp:O,onPointerCancel:O,onMouseEnter:L,onMouseLeave:P})]})};D3.displayName="OverlayScrollbar";const O3=D3;function s_(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n&&typeof n=="object"&&(n.current=t)})}}const Cd=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:u,children:f,...p},m)=>{const g=h.useRef(null),y=h.useRef("none"),b=p["data-scroll-shadow"];delete p["data-scroll-shadow"];const k=h.useMemo(()=>{const S={...d};return S["--scroll-shadow-size"]=`${r}px`,S},[r,d]),v=h.useCallback((S,w,M,I,E)=>{const _=`${I}${E.charAt(0).toUpperCase()}${E.slice(1)}Scroll`;w&&M?(S.dataset[_]="true",S.removeAttribute(`data-${I}-scroll`),S.removeAttribute(`data-${E}-scroll`)):(S.dataset[`${I}Scroll`]=String(w),S.dataset[`${E}Scroll`]=String(M),S.removeAttribute(`data-${I}-${E}-scroll`))},[]),x=h.useCallback(S=>{["top","bottom","top-bottom","left","right","left-right"].forEach(w=>{S.removeAttribute(`data-${w}-scroll`)})},[]),C=h.useCallback(()=>{const S=g.current;if(!S)return;if(!s){x(S);return}const w=1,M=t==="vertical"?S.scrollTop>n+w:S.scrollLeft>n+w;let I=t==="vertical"?S.scrollHeight-(S.scrollTop+S.clientHeight)>n+w:S.scrollWidth-(S.scrollLeft+S.clientWidth)>n+w;const E=o&&t==="vertical"?!1:M;i&&t==="vertical"&&(I=!1),v(S,E,I,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const _=E&&I?"both":E?t==="vertical"?"top":"left":I?t==="vertical"?"bottom":"right":"none";_!==y.current&&(y.current=_,c?.(_))},[x,o,i,s,n,c,t,v]);return h.useEffect(()=>{const S=g.current;if(!S)return;let w=null;const M=()=>{w===null&&(w=requestAnimationFrame(()=>{w=null,C()}))},I=()=>C(),E=typeof ResizeObserver<"u"?new ResizeObserver(M):null,_=a&&typeof MutationObserver<"u"?new MutationObserver(M):null;return C(),S.addEventListener("scroll",I,{passive:!0}),E?.observe(S),_?.observe(S,{childList:!0,subtree:!0,characterData:!0}),()=>{w!==null&&cancelAnimationFrame(w),S.removeEventListener("scroll",I),E?.disconnect(),_?.disconnect()}},[C,a]),l.jsx(e,{...p,ref:s_(g,m),className:u,"data-orientation":t,"data-scroll-shadow":b??!0,style:k,children:f})});Cd.displayName="ScrollShadow";const Hn=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:u=!0,preventOverscroll:f=!1,useScrollShadow:p=!1,scrollShadowSize:m,hideTopScrollShadow:g=!1,userIntentOnly:y=!1,...b},k)=>{const v=h.useRef(null);return h.useImperativeHandle(k,()=>v.current,[]),l.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden",f&&"overscroll-none",t),children:[p?l.jsx(Cd,{as:i,ref:v,size:m,hideTopShadow:g,className:R("overlay-scrollbar-target overlay-scrollbar-container",f&&"overscroll-none",u?"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,...b,children:n}):l.jsx(i,{ref:v,className:R("overlay-scrollbar-target overlay-scrollbar-container",f&&"overscroll-none",u?"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,...b,children:n}),l.jsx(O3,{containerRef:v,minThumbSize:s,hideDelayMs:o,className:a,disableHorizontal:c,observeMutations:d,userIntentOnly:y})]})});Hn.displayName="ScrollableOverlay";const a2="mobile-overlay-root",l2=16,c2=200,o_=()=>{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},sa=({open:e,title:t,onClose:n,children:r,footer:s,className:o,contentMaxHeightClassName:i,renderHeader:a})=>{const c=h.useRef(null),[d,u]=h.useState(!1),[f,p]=h.useState(!1);if(typeof document<"u"&&!c.current&&(c.current=o_()),h.useEffect(()=>{if(!e){u(!1),p(!1);return}const y=window.setTimeout(()=>u(!0),l2),b=window.setTimeout(()=>p(!0),l2+c2+50);return()=>{window.clearTimeout(y),window.clearTimeout(b)}},[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 y=document.body.style.overflow;document.body.style.overflow="hidden";const b=k=>{k.key==="Escape"&&n()};return document.addEventListener("keydown",b),()=>{document.body.style.overflow=y,document.removeEventListener("keydown",b)}},[e,n]),!e||!c.current)return null;const m=i??"max-h-[min(70vh,520px)]",g=l.jsx("div",{className:R("oc-keyboard-inset-surface fixed inset-0 z-[60] flex flex-col bg-[rgb(0_0_0_/_0.45)] transition-opacity duration-200 ease-out",!f&&"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:R("mt-auto flex max-h-[calc(100dvh-0.75rem)] min-h-0 w-full flex-col rounded-t-xl border-x border-t border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",o),style:{transform:d?"none":"translateY(100%)",transition:`transform ${c2}ms cubic-bezier(0.32, 0.72, 0, 1)`},onClick:y=>y.stopPropagation(),children:[(()=>{const y=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(V,{name:"close",className:"h-4 w-4"})});return a?a(y):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}),y]})})(),l.jsx(Hn,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:R("min-h-0 flex-1",m),className:"px-2 py-2 pwa-overlay-scroll",children:r}),s?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 Gi.createPortal(g,c.current)},Fu=new Set,Vu=new Set,Bu=new Set,$u=new Set,kd={onDeleteRequest(e){return Fu.add(e),()=>{Fu.delete(e)}},requestDelete(e){e.sessions.length&&Fu.forEach(t=>t(e))},onCreateRequest(e){return Vu.add(e),()=>{Vu.delete(e)}},requestCreate(e){const t=e??{};Vu.forEach(n=>n(t))},onDirectoryRequest(e){return Bu.add(e),()=>{Bu.delete(e)}},requestDirectoryDialog(){Bu.forEach(e=>e())},onGitRefreshHint(e){return $u.add(e),()=>{$u.delete(e)}},requestGitRefresh(e){e.directory.trim()&&$u.forEach(t=>t(e))}},ha=h.createContext(null),i_=40,d2=20*1024*1024;function a_(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[C,S]of t)(S.sourcePath===v||S.sourcePath.startsWith(x))&&c(C)},u=(v,x)=>x.isFile&&x.mtimeMs!==void 0&&v.mtimeMs===x.mtimeMs&&v.size===x.size,f=()=>{t.clear(),n=0},p=(v,x,C,S)=>{if(!s||!S.isFile||S.mtimeMs===void 0)return C;const w=a(C.content);if(w>d2)return C;for(c(v),t.set(v,{...C,sourcePath:x,size:S.size,mtimeMs:S.mtimeMs,bytes:w}),n+=w;t.size>i_||n>d2;){const M=t.keys().next().value;if(!M)break;c(M)}return C},m=async(v,x,C,S)=>{const w=await e.statFile?.(x,C).catch(()=>null),M=await e.readFile(x,C),I=await e.statFile?.(x,C).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return S!==r?g(x,C):w&&I&&w.isFile&&I.isFile&&w.mtimeMs!==void 0&&I.mtimeMs!==void 0&&w.size===I.size&&w.mtimeMs===I.mtimeMs?p(v,x,M,I):M},g=e.readFile?async(v,x)=>{if(await o,!s)throw new Error("File cache owner disposed");const C=r;if(x?.allowOutsideWorkspace)return e.readFile(v,x);const S=i(v,x),w=t.get(S);if(!w)return m(S,v,x,C);const M=await e.statFile?.(v,x).catch(()=>null);if(!s)throw new Error("File cache owner disposed");return C!==r?g(v,x):!M||!u(w,M)?(c(S),m(S,v,x,C)):(t.delete(S),t.set(S,w),{content:w.content,path:w.path,revision:w.revision})}:void 0,y=async(v,x)=>{const C=o;let S;o=new Promise(w=>{S=w}),await C,r+=1,v.forEach(d);try{return await x()}finally{v.forEach(d),r+=1,S()}},b={...e,readFile:g,writeFile:e.writeFile?(v,x,C)=>y([v],()=>e.writeFile(v,x,C)):void 0,delete:e.delete?v=>y([v],()=>e.delete(v)):void 0,rename:e.rename?(v,x)=>y([v,x],()=>e.rename(v,x)):void 0},k=np(v=>{v.runtimeKey!==v.previousRuntimeKey&&(r+=1,f())});return{files:b,dispose:()=>{s=!1,r+=1,f(),k()}}}function qZ({apis:e,children:t}){const[n,r]=h.useState(null);h.useEffect(()=>{const i=a_(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(ha.Provider,{value:o,children:t})}const l_="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)",c_="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 d_(){const e=()=>typeof document<"u"&&document.documentElement.classList.contains("dark"),[t,n]=z.useState(e);return z.useEffect(()=>{const r=()=>n(e()),s=new MutationObserver(r);return s.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r(),()=>s.disconnect()},[]),t}function u_(e){z.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 GZ=({...e})=>{const t=d_();return u_(t?l_:c_),l.jsx(n9,{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})},f_="pichamber_session_load_perf",mh=1e3,h_=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"]),p_=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"]),m_=new Set(["complete","error","stale","deduplicated","canceled"]),H3=()=>{if(_o())return!0;if(typeof window>"u")return!1;try{return window.localStorage.getItem(f_)==="1"}catch{return!1}};function g_(){return typeof window>"u"?0:window.__pichamberSessionLoadPerformance?.events.length??0}function y_(){typeof window>"u"||window.__pichamberSessionLoadPerformance&&(window.__pichamberSessionLoadPerformance.events=[])}const u2=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),v_=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0,zu=e=>Number.isInteger(e)&&Number(e)>=0?Number(e):void 0;function x_(e){if(!H3()||!h_.has(e.operation)||e.caller!==void 0&&!p_.has(e.caller))return()=>{};const t=u2();return(n,r)=>{if(typeof window>"u"||!m_.has(n))return;const s=window.__pichamberSessionLoadPerformance??{events:[]},o=v_(e.queuedMs),i=zu(e.requestLimit),a=zu(r?.retryCount??e.retryCount),c=zu(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,u2()-t),...a!==void 0?{retryCount:a}:{},...c!==void 0?{recordCount:c}:{},at:Date.now()}),s.events.length>mh&&s.events.splice(0,s.events.length-mh),window.__pichamberSessionLoadPerformance=s}}const f2="pichamber.chat.first_message_visible";function b_(e){const t=e?.enabled??H3,n=e?.requestFrame??(c=>window.requestAnimationFrame(c)),r=e?.cancelFrame??(c=>window.cancelAnimationFrame(c)),s=e?.markVisible??(()=>{performance.mark(f2),performance.clearMarks(f2)}),o=e?.startEvent??x_,i=new Set;let a=null;return{schedule(c,d){if(!t()||i.has(c))return()=>{};a&&(r(a.frame),a=null);const u=o({operation:"session-messages.visible",caller:"selected-session",recordCount:d}),f=n(()=>{a?.key!==c||a.frame!==f||(a=null,i.add(c),i.size>mh&&i.delete(i.values().next().value),s(),u("complete"))});return a={key:c,frame:f},()=>{a?.key!==c||a.frame!==f||(r(f),a=null)}}}}const w_=1e3,S_=6,C_=16.7,k_=50,M_=(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},I_=(e=w_)=>{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:M_(n,95),samples:n.length}}}},h2=(e,t=S_)=>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})),Qo=(e,t=1)=>Number.isFinite(e)?e.toFixed(t):"—",__=e=>typeof e!="number"||!Number.isFinite(e)||e<0?null:e/(1024*1024),E_=250,j_=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),T_=()=>{if(typeof performance>"u")return null;const e=performance.memory?.usedJSHeapSize;return typeof e=="number"&&Number.isFinite(e)?e:null},A_=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()=>{}}},L_=(e,t={})=>{const n=(t.getStreamSnapshot??n7)(),r=(t.getSyncSnapshot??Vv)(),s=(t.getSessionLoadEventCount??g_)(),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}},N_=(e,t={})=>{const n=t.now??j_,r=t.requestFrame??(k=>window.requestAnimationFrame(k)),s=t.cancelFrame??(k=>window.cancelAnimationFrame(k)),o=t.observeLongTasks??A_,i=t.readHeapUsedBytes??T_,a=I_();let c=0,d=0,u=0,f=0,p=0,m=!1;const g=o(k=>{c+=1,d=k,u+=k}),y=k=>{const v=a.snapshot();e(L_({fps:v.fps,frameMs:{last:v.lastMs,p95:v.p95Ms},longTasks:{count:c,lastMs:d,totalMs:u},heapUsedMb:__(i())},t)),f=k},b=k=>{if(m)return;const v=typeof k=="number"&&Number.isFinite(k)?k:n();a.sample(v),(f===0||v-f>=E_)&&y(v),p=r(b)};return p=r(b),{stop(){m=!0,s(p),g(),a.reset()},reset(){a.reset(),c=0,d=0,u=0,R_(),y(n())}}},R_=()=>{t7(),Fv(),y_()},P_=()=>({capturedAt:0,fps:0,frameMs:{last:0,p95:0},longTasks:{count:0,lastMs:0,totalMs:0},heapUsedMb:null,stream:[],sync:[],sessionLoadEvents:0});let gh=P_();const D_=()=>h.useSyncExternalStore(s7,_o,()=>!1),O_=e=>e>=k_?"var(--status-error)":e>=C_?"var(--status-warning)":"var(--surface-foreground)",Ds=(e,t)=>{e&&e.textContent!==t&&(e.textContent=t)},H_=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(`
41
- `):"no counters yet"},hl=8,Uu=(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+hl,u=i+hl,f=Math.max(d,o+a-n-hl),p=Math.max(u,i+c-r-hl);return{left:Math.round(Math.min(Math.max(e,d),f)),top:Math.round(Math.min(Math.max(t,u),p))}},p2=(e,t)=>{e.style.left=`${t.left}px`,e.style.top=`${t.top}px`,e.style.right="auto",e.style.transform="none"},F_=()=>{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),u=h.useRef(null),f=h.useRef(null),p=h.useRef(null),m=h.useRef(null),g=h.useRef(gh),y=h.useRef(null),b=h.useCallback(w=>{const M=i.current;if(!M||a.current)return;const I=M.getBoundingClientRect(),E=Uu(w.left,w.top,I.width,I.height);E.left===w.left&&E.top===w.top||(p2(M,E),r(E))},[]);h.useLayoutEffect(()=>{n&&b(n)},[e,b,n]),h.useEffect(()=>{if(!n||typeof window>"u")return;const w=()=>{b(n)},M=window.visualViewport;return window.addEventListener("resize",w),M?.addEventListener("resize",w),()=>{window.removeEventListener("resize",w),M?.removeEventListener("resize",w)}},[b,n]);const k=h.useCallback(w=>{if(w.button!==0||a.current)return;const M=i.current;if(!M)return;const I=M.getBoundingClientRect();a.current={pointerId:w.pointerId,offsetX:w.clientX-I.left,offsetY:w.clientY-I.top,originLeft:I.left,originTop:I.top,left:I.left,top:I.top,width:I.width,height:I.height};try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}o(!0),w.preventDefault()},[]),v=h.useCallback(w=>{const M=a.current;if(!M||M.pointerId!==w.pointerId)return;const I=Uu(w.clientX-M.offsetX,w.clientY-M.offsetY,M.width,M.height);I.left===M.left&&I.top===M.top||(M.left=I.left,M.top=I.top,i.current?.style.setProperty("transform",`translate3d(${I.left-M.originLeft}px, ${I.top-M.originTop}px, 0)`),w.cancelable&&w.preventDefault())},[]),x=h.useCallback((w,M)=>{const I=a.current;if(!I||I.pointerId!==w.pointerId)return;const E=i.current,_=E?.getBoundingClientRect(),T=M?{left:I.originLeft,top:I.originTop}:Uu(w.clientX-I.offsetX,w.clientY-I.offsetY,_?.width??I.width,_?.height??I.height);a.current=null,E&&(M?E.style.transform="none":p2(E,T)),o(!1),M||r(T);try{w.currentTarget.hasPointerCapture(w.pointerId)&&w.currentTarget.releasePointerCapture(w.pointerId)}catch{}},[]);h.useEffect(()=>()=>{a.current=null},[]),h.useEffect(()=>{const M=N_(I=>{gh=I,g.current=I,Ds(c.current,Qo(I.fps,0)),Ds(d.current,`${Qo(I.frameMs.last)}ms`),Ds(u.current,`${Qo(I.frameMs.p95)}ms`),u.current&&(u.current.style.color=O_(I.frameMs.p95)),Ds(f.current,`${I.longTasks.count} / ${Qo(I.longTasks.lastMs,0)}ms`),Ds(p.current,I.heapUsedMb==null?"—":`${Qo(I.heapUsedMb,0)}MB`),Ds(m.current,H_(I))});return y.current=M,()=>{M.stop(),y.current=null}},[]);const C=h.useCallback(()=>{ir(`${JSON.stringify(g.current,null,2)}
42
- `)},[]),S=h.useCallback(()=>{y.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:R("flex min-w-0 flex-1 cursor-grab touch-none select-none items-center gap-1",s?"cursor-grabbing":"active:cursor-grabbing"),title:"Drag to move performance overlay",onPointerDown:k,onPointerMove:v,onPointerUp:w=>x(w,!1),onPointerCancel:w=>x(w,!0),onLostPointerCapture:w=>x(w,!0),children:[l.jsx(V,{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(Ee,{variant:"ghost",size:"xs","aria-label":"Copy performance snapshot",onClick:C,children:l.jsx(V,{name:"file-copy",className:"size-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"xs","aria-label":"Reset performance counters",onClick:S,children:l.jsx(V,{name:"refresh",className:"size-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"xs","aria-label":e?"Expand performance overlay":"Collapse performance overlay","aria-expanded":!e,onClick:()=>t(w=>!w),children:l.jsx(V,{name:e?"arrow-down-s":"arrow-up-s",className:"size-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"xs","aria-label":"Turn off performance overlay",onClick:()=>cc(!1),children:l.jsx(V,{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:u,className:"text-right",children:"0.0ms"}),l.jsx("span",{children:"Long"}),l.jsx("span",{ref:f,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"})]})},KZ=()=>{const e=D_();return h.useLayoutEffect(()=>{r7()},[]),h.useEffect(()=>{if(!(typeof window>"u"))return window.__pichamberPerfHud={setEnabled:cc,isEnabled:_o,getSnapshot:()=>gh},()=>{delete window.__pichamberPerfHud}},[]),!e||typeof document>"u"||!document.body?null:Gi.createPortal(l.jsx(F_,{}),document.body)},Up=48,V_=e=>e.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,Up).replace(/-$/g,""),B_=e=>{const t=e.trim();return t.length===0||t.length>Up?null:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)?t:null},m2=e=>{const t=V_(e.trim());return t&&t.split("-").filter(Boolean).slice(0,7).join("-").slice(0,Up).replace(/-$/g,"")||null},$_=async(e,t)=>{const n=e.trim();if(!n||!t)return m2(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=B_(s.text);if(o)return o}}}catch{}return m2(n)},z_=500,Kl="Worktree creation superseded.",yh=e=>{const t=ce(e.projectRoot)??e.projectRoot,n=ce(e.sourceDirectory)??e.sourceDirectory;return JSON.stringify([e.runtimeKey,t,n,e.startRef])},F3=e=>e?yh(e):null,U_=e=>new Promise(t=>{setTimeout(t,e)}),Z_=(e,t)=>!!(e&&t&&e.runtimeKey===t.runtimeKey&&ce(e.projectRoot)===ce(t.projectRoot)&&ce(e.sourceDirectory)===ce(t.sourceDirectory)&&e.startRef===t.startRef),W_=(e,t)=>({...e,path:t.path,branch:t.branch}),fr=new Map,ei=new Map,q_=e=>({prompt:e.prompt,confirmedMentions:Array.from(new Set(Array.isArray(e.confirmedMentions)?e.confirmedMentions:[...e.confirmedMentions])),attachments:e.attachments.map(id)}),ti=(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)=>{ti(e,a,(u,f)=>u?{...u,state:d,failedSend:null,updatedAt:f}:{key:a,intent:c,state:d,receipt:null,failedSend:null,notificationSent:!1,startedAt:f,updatedAt:f})},r=(a,c,d,u)=>{ti(e,a,(f,p)=>({key:a,intent:c,state:d,receipt:null,failedSend:u,notificationSent:f?.notificationSent??!1,path:f?.path??null,branch:f?.branch??null,startedAt:f?.startedAt??p,updatedAt:p}))},s=(a,c,d,u,f,p)=>{ti(e,a,(m,g)=>({key:a,intent:c,state:null,receipt:d,failedSend:u,notificationSent:m?.notificationSent??!1,path:f??d.path,branch:p??d.branch,startedAt:m?.startedAt??g,updatedAt:g}))},o=(a,c,d)=>{ti(e,a,(u,f)=>u?{...u,path:c,branch:d,updatedAt:f}:null)},i=async a=>{const{intent:c,prompt:d,git:u,refreshProject:f}=a,p=a.failedSend?q_(a.failedSend):null,m=a.pollIntervalMs??z_,g=a.taskId??yh(c),y=(fr.get(g)??0)+1;fr.set(g,y);const b=()=>fr.get(g)!==y||c.runtimeKey!==X(),k=()=>{!u||c.runtimeKey!==X()||f(c.projectRoot,u,{force:!0}).catch(()=>{})};if(n(g,c,{phase:"naming",label:"Naming worktree..."}),!u?.createGitWorktree||!u.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!==X()){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 $_(d,c.sourceDirectory);if(b())throw new Error(Kl);const x={mode:"new",startRef:c.startRef,...v?{worktreeName:v}:{},returnAfterDirectoryCreated:!0};if(u.validateGitWorktree){const M=await u.validateGitWorktree(c.sourceDirectory,x);if(!M.ok)throw new Error(M.errors.map(I=>I.message).filter(Boolean).join(`
43
- `)||"The worktree request is invalid.")}if(b())throw new Error(Kl);n(g,c,{phase:"creating",label:"Creating worktree..."});const C=await u.createGitWorktree(c.sourceDirectory,x),S=W_(c,C);if(b())return S;o(g,C.path,C.branch);let w=C.bootstrapStatus;for(;w.status==="pending";){if(b()||(n(g,c,w.phase==="directory-created"?{phase:"checking-out",label:"Checking out files..."}:{phase:"setting-up",label:"Setting up project..."}),await U_(m),b()))return S;w=await u.getGitWorktreeBootstrapStatus(C.path)}if(w.status==="failed"||w.phase!=="setup-ready")throw new Error(w.error||"Worktree setup failed.");try{await f(c.projectRoot,u,{force:!0})}catch{}return b()||s(g,c,S,p,C.path,C.branch),S}catch(v){if(b())throw v;const x=v instanceof Error?v.message:"Failed to create the worktree.";throw x===Kl||(k(),r(g,c,{phase:"failed",label:"Worktree creation failed",error:x},p)),v}};return{runtimeKey:X(),entries:new Map,getEntry:a=>{const c=F3(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(u=>{const f=u.entries.get(a);if(!f||f.state?.phase!=="failed"||f.failedSend!==c)return u;const p=new Map(u.entries);return p.delete(a),fr.delete(a),d=!0,{entries:p}}),d},markWorktreePromptSucceeded:(a,c)=>{let d=!1;return e(u=>{const f=u.entries.get(a);if(!f||!f.receipt||f.failedSend!==c)return u;const p=new Map(u.entries);return p.delete(a),fr.delete(a),d=!0,{entries:p}}),d},markWorktreePromptFailed:(a,c,d)=>{let u=!1;return e(f=>{const p=f.entries.get(a);if(!p||!p.receipt||p.failedSend!==c)return f;const m=new Map(f.entries);return m.set(a,{...p,state:{phase:"failed",label:"Prompt failed to send",error:d},updatedAt:Date.now()}),u=!0,{entries:m}}),u},markNotificationSent:a=>{ti(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 u=new Map(c.entries);return u.delete(a),fr.delete(a),{entries:u}})},resetForRuntimeSwitch:a=>{fr.clear(),ei.clear(),e({runtimeKey:a,entries:new Map})},request:a=>{const c=a.taskId??yh(a.intent),d=ei.get(c);if(d)return d;const u=i(a).finally(()=>{ei.get(c)===u&&ei.delete(c)});return ei.set(c,u),u}}}),V3=e=>F3(e),G_=Z_,K_=async e=>(await Uv([...e])).map(id),Y_=(e,t)=>e??t,B3=(e,t)=>(e??t).map(n=>n.id),vh=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.`}},X_=(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"?vh(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."},$3=()=>{try{const e=ve.getState(),t=e.newSessionDraft?.open?e.newSessionDraft.directoryOverride:null,n=e.currentSessionId,r=n?e.getDirectoryForSession(n)??e.currentSessionDirectory:t??tt.getState().currentDirectory,s=Eo(X(),r,n);return s?Gt(s):null}catch{return null}},YZ=e=>{const t=en.getState(),n=t.getEntryByKey(e),r=n?.failedSend;if(!n||!r)return{ok:!1,reason:"missing"};if(n.intent.runtimeKey!==X())return{ok:!1,reason:"runtime-mismatch"};const s=Eo(X(),n.intent.sourceDirectory,null);if(!s)return{ok:!1,reason:"invalid-target"};const o=Gt(s);try{const d=od(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=$3();if(i!==null&&i===o){try{ve.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(id),expectedFailedSend:r};try{Ge.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{ve.getState().openNewSessionDraft({directoryOverride:n.intent.sourceDirectory,worktreeIntent:n.intent})}catch{return{ok:!1,reason:"open-failed"}}try{us(s,r.prompt,r.confirmedMentions)}catch{return{ok:!1,reason:"invalid-target"}}try{Ge.getState().activateAttachmentsDraft(o);const d=Ge.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}},J_=(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!==X())return{ok:!1,reason:"runtime-mismatch"};const o=Eo(X(),r.intent.sourceDirectory,null);if(!o)return{ok:!1,reason:"invalid-target"};const i=Gt(o);if(i!==e.targetKey)return{ok:!1,reason:"invalid-target"};const a=$3();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 f=od(o);if(f.text.trim().length>0&&f.text!==e.prompt)return{ok:!1,reason:"target-occupied"}}catch{return{ok:!1,reason:"invalid-target"}}const d=ce(r.intent.sourceDirectory),u=ce(o.directory);if(!d||d!==u)return{ok:!1,reason:"invalid-target"};try{us(o,e.prompt,e.confirmedMentions),Ge.getState().activateAttachmentsDraft(i);const f=Ge.getState().restoreAttachmentsForRetry(e.attachments);if(!f.ok)return{ok:!1,reason:"attachment-limit",limit:f.limit,currentCount:f.currentCount,missingCount:f.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}},XZ=e=>!!(e?.receipt&&e?.failedSend&&!e?.state),Q_=e=>!!(e?.receipt&&!e?.state&&!e?.failedSend),JZ=e=>Q_(e),QZ=e=>!!(e?.receipt&&!e?.notificationSent&&!e?.state&&!e?.failedSend),eE=(e,t,n)=>{if(!e||!t)return!1;try{return en.getState().markWorktreePromptFailed(e,t,n)}catch{return!1}},tE=(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=B3(n,r);o.length>0&&Ge.getState().detachAttachedFiles(o)}catch{}return!0},nE="PiChamber",g2=e=>e.replace(/[-_]/g," ").replace(/\b\w/g,t=>t.toUpperCase()),rE=e=>{const n=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??""},sE=(e,t)=>[e,t,nE].filter(r=>typeof r=="string"&&r.trim().length>0).join(" | "),oE=()=>{const e=ve(a=>a.currentSessionId),t=Ke(a=>e?a.reducer.bySession.get(e)?.extensionTitle??null:null,Object.is,e?`session:${e}`:"chrome"),n=it(a=>a.activeProjectId?a.projects.find(c=>c.id===a.activeProjectId)??null:null),r=h.useMemo(()=>{if(!n)return null;const a=n.label?.trim();if(a)return g2(a);const c=rE(n.path);return c?g2(c):null},[n]),[s,o]=h.useState(null);h.useEffect(()=>{if(typeof window>"u"||!xt()){o(null);return}let a=!1;const c=async()=>{try{if(Kc()){a||o(null);return}const u=window.__PICHAMBER_LOCAL_ORIGIN__||window.location.origin,f=qc();if(f&&b1(f,u)){a||o(null);return}const m=(await sp()).hosts.find(y=>f?b1(f,Nl(y)):!1),g=m?.label?.trim()?Nn(m.label.trim()):"Instance";a||o(g)}catch{a||o("Instance")}};c();const d=()=>{c()};return window.addEventListener("focus",d),()=>{a=!0,window.removeEventListener("focus",d)}},[]);const i=h.useMemo(()=>sE(t?.trim()||r,s),[t,s,r]);h.useEffect(()=>{if(typeof document<"u"&&(document.title=i),!xt())return;(async()=>{try{if(typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await bM(i)}catch{return}})()},[i])},eW=()=>(oE(),null),y2=(e,t)=>{const n=ce(t??null);if(!n)return;const r=n.toLowerCase();e.has(r)||e.set(r,n)},z3=(e,t,n)=>{const r=new Map;for(const s of e)y2(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)y2(r,o?.path);return new Set(r.values())},pl=new Map,iE=e=>{const t=new Set;for(const n of e){const r=ce(n);r&&t.add(r)}return t},aE=()=>{const e=new Set,t=it.getState().projects,n=z3(t,On(t,sn.getState()),{includeWorktrees:!0});for(const o of n){const i=ce(o);i&&i!=="~"&&e.add(i)}const r=ce(Je().getState().directory);r&&e.add(r);const s=tt.getState().homeDirectory??null;for(const o of jp(s)){const i=ce(o);i&&i!=="~"&&e.add(i)}return e},lE=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=Je(),c=a!==e||X()!==t||a.getRuntimeGeneration()!==n,d=a.getState().catalog,u=new Set,f=new Set;for(const m of r){const g=d.listStatusByDirectory.get(m);g==="ready"?u.add(m):g==="failed"&&f.add(m)}const p=!c&&f.size===0&&u.size===r.length&&(s||r.length>0);return{runtimeKey:t,catalog:d,readyDirectories:u,failedDirectories:f,complete:p,stale:c}},cE=e=>{const t=Je(),n=X(),r=t.getRuntimeGeneration(),s=e!==void 0,i=[...e===void 0?aE():iE(e)].sort(),a=`${n}::${i.join("|")}`,c=pl.get(a);if(c&&c.store===t&&c.runtimeKey===n&&c.generation===r)return c.promise;const d=lE(t,n,r,i,s);pl.set(a,{store:t,runtimeKey:n,generation:r,promise:d});const u=()=>{pl.get(a)?.promise===d&&pl.delete(a)};return d.then(u,u),d},dE=e=>{if(typeof Element>"u"||!(e instanceof Element))return null;const t=e.closest("[data-terminal-owner]");return t?.isConnected&&t.dataset.terminalOwner||null},Zu=e=>dE(e)!==null,uE=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},fE=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(!uE(n[r]))return n[r].info.id;return null},hE=e=>e.connection==="ready"&&(e.authoritativeWorking||e.hasPendingAssistant),pE=e=>{const t=e.connection==="ready"&&!e.transportUncertain,n=e.authoritativeWorking||e.hasPendingAssistant;return{isWorking:t&&n,isAwaitingRecovery:!t&&(n||e.hasRetainedStream)}},mE=e=>e.turnIsInActiveStream||e.isLastTurn&&e.sessionIsWorking&&e.awaitingPromptEcho!==!0&&(e.isSteering===!0||!e.activeStreamingMessageId),gE=e=>e.isRetrying===!0||e.isAwaitingRecovery===!0||!!e.activeStreamingMessageId&&e.messageId===e.activeStreamingMessageId,Wu={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function yE(e,t){const n=f3(),r=hd(e??""),s=Dp(e??"");return h.useMemo(()=>{if(!e)return Wu;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",u=hE({connection:n,authoritativeWorking:d,hasPendingAssistant:a});return c&&!d||!u?Wu:{phase:d?o:"busy",isWorking:!0,isBusy:o==="busy"||!d&&a,isCooldown:!1}},[n,e,r,s])}function Zp(){const e=ve(t=>t.currentSessionId);return ve(t=>t.currentSessionDirectory),yE(e)}const tW=.45,Wp=[{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"}],U3=new Map(Wp.map(e=>[e.id,e])),qu=Wp.find(e=>e.id==="git"),nW=e=>e===!1?{icon:"arrow-left-right",label:"Changes",description:"Review working and last-turn changes"}:{icon:qu?.icon??"git-branch",label:qu?.label??"Git",description:qu?.description??"Review diffs, commit, and push"},vE=e=>typeof e=="string"&&U3.has(e),xE=e=>{const t=[],n=new Set;for(const r of e){if(!vE(r)||n.has(r))continue;const s=U3.get(r);s&&(n.add(r),t.push(s))}for(const r of Wp)n.has(r.id)||t.push(r);return t},rW=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)}},bE=e=>!e||e.isLoading&&!e.hasResult?!1:e.hasError?!0:e.hasGitHubRepo,wE=e=>xE(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:bE(e.githubScope):t.availability==="extensions"?e.tabs.some(n=>n.mode===t.mode)?!0:!!e.hasExtensionContent:!0),Z3=3e4,Gr=()=>({scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),ni=new Map,SE=(e,t)=>`${e}
44
- ${t}`,CE=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub scope check failed"}},Yl=e=>!e.host||!e.owner||!e.repo?null:E5(`${e.host}/${e.owner}/${e.repo}`),Xl=e=>!!(e.host&&e.owner&&e.repo&&!e.disabledReason),qp=(e,t)=>{if(!e)return t;const n=new Set(e.repositories.filter(Xl).map(i=>Yl(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"&&Xl(i)),s=r?Yl(r):null;if(s&&n.has(s))return s;const o=e.repositories.find(Xl);return o?Yl(o):null},pa=Et()(or((e,t)=>({runtimeKey:X(),entriesByDirectory:{},resetForRuntimeSwitch:n=>{const r=n??X();ni.clear(),e({runtimeKey:r,entriesByDirectory:{}})},ensureScope:async(n,r)=>{const s=Jr(n.trim());if(!s)return Gr();const o=X();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t().entriesByDirectory[s],a=Date.now();return i?.scope&&i.fetchedAt&&a-i.fetchedAt<Z3&&!i.isLoading?i:t().refreshScope(s,r)},refreshScope:async(n,r,s)=>{const o=Jr(n.trim());if(!o)return Gr();const i=X();t().runtimeKey!==i&&t().resetForRuntimeSwitch(i);const a=SE(i,o),c=ni.get(a);if(c&&!s?.force)return c;const d=r??null;if(!d)return t().entriesByDirectory[o]??Gr();const u=t().entriesByDirectory[o]??Gr();u.isLoading||e(p=>({entriesByDirectory:{...p.entriesByDirectory,[o]:{...u,isLoading:!0}}}));const f=(async()=>{try{const p=await d.scope(o);if(X()!==i)return t().entriesByDirectory[o]??Gr();const m={scope:p,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null};e(b=>({entriesByDirectory:{...b.entriesByDirectory,[o]:m}}));const g=se.getState().githubSelectedRepoByDirectory[o]??null,y=qp(p,g);return y!==g&&se.getState().setGitHubSelectedRepo(o,y),m}catch(p){if(X()!==i)return t().entriesByDirectory[o]??Gr();const m=CE(p),g=u.scope?{...u,isLoading:!1,stale:!0,error:m}:{scope:null,fetchedAt:null,isLoading:!1,stale:!1,error:m};return e(y=>({entriesByDirectory:{...y.entriesByDirectory,[o]:g}})),g}})();ni.set(a,f);try{return await f}finally{ni.get(a)===f&&ni.delete(a)}},setSelectedRepo:(n,r)=>{const s=Jr(n.trim());if(!s)return;const o=t().entriesByDirectory[s]?.scope??null;if(r!=null){const i=E5(r);if(!i||o&&!new Set(o.repositories.filter(Xl).map(c=>Yl(c)).filter(c=>!!c)).has(i))return;se.getState().setGitHubSelectedRepo(s,i);return}se.getState().setGitHubSelectedRepo(s,null)},invalidate:async(n,r)=>{const s=Jr(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"&&pn(e=>{pa.getState().resetForRuntimeSwitch(e.runtimeKey)});const v2=Object.freeze(Gr()),kE=e=>pa(t=>e?t.entriesByDirectory[Jr(e)]??v2:v2),ME=e=>{const t=pa(r=>e?r.entriesByDirectory[Jr(e)]?.scope??null:null),n=se(r=>e?r.githubSelectedRepoByDirectory[Jr(e)]??null:null);return h.useMemo(()=>e?qp(t,n):null,[e,t,n])},sW=Object.freeze(Object.defineProperty({__proto__:null,GITHUB_SCOPE_STALE_MS:Z3,resolveGitHubSelectedRepo:qp,useGitHubScope:kE,useGitHubScopeStore:pa,useGitHubSelectedRepo:ME},Symbol.toStringTag,{value:"Module"})),Vn=()=>{const e=ve(s=>s.currentSessionId),t=ve(s=>s.newSessionDraft),n=Hk(e),r=tt(s=>s.currentDirectory);return e&&n?n:t?.open&&t.directoryOverride?t.directoryOverride:r??void 0},IE=()=>({setCurrentVariant:e=>qe.getState().setCurrentVariant(e)}),gi=(e,t=IE())=>(t.setCurrentVariant(e),"applied"),_E=async(e=1)=>{const t=qe.getState(),n=mp(t.getCurrentModelVariants(),t.currentVariant,e);return gi(n),n},EE='[data-chat-input="true"] .cm-content';function co(){document.querySelector(EE)?.focus()}const jE=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"]),Gp=e=>e.replace(/\r\n?/g,`
45
- `),hn=e=>Gp(e).trim(),TE=e=>e.replace(/\s+/g," ").trim(),W3=e=>(e.match(/language-([\w+#.-]+)/)?.[1]||"").trim(),AE=e=>e.closest("pre")?.getAttribute("data-md-lang")||W3(e.className),q3=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=>q3(n)).filter(n=>n!==null)}},Kp=e=>e.filter(t=>t.type==="text"||!t.isCodeLineNumber).map(t=>t.type==="text"?t:{...t,children:Kp(t.children)}),LE=e=>Array.from(e.childNodes).map(t=>q3(t)).filter(t=>t!==null),Fi=e=>e.type==="text"?e.value:e.children.map(t=>Fi(t)).join(""),xh=(e,t)=>{if(e.type==="text")return null;if(t(e))return e;for(const n of e.children){const r=xh(n,t);if(r)return r}return null},Yp=(e,t="")=>{const n=Gp(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}
46
- ${n}
47
- ${s}`},uo=e=>{if(e.type==="text")return TE(e.value);const t=e.children.map(n=>uo(n)).join("").replace(/\s+/g," ").trim();return!t&&e.tag!=="br"?"":e.tag==="br"?`
48
- `: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},x2=(e,t)=>e.children.filter(n=>n.type==="element"&&n.tag==="li").map((n,r)=>{const s=n.children.map(o=>uo(o)).join("").replace(/\s+/g," ").trim();return s?`${t?`${r+1}.`:"-"} ${s}`:""}).filter(Boolean).join(`
49
- `),yi=e=>{if(e.type==="text")return hn(e.value);if(e.isMarkdownBlock)return e.children.map(n=>yi(n)).filter(n=>n.length>0).join(`
50
-
51
- `);if(e.component==="markdown-code"){const n=xh(e,r=>r.tag==="pre");return n?yi(n):""}if(e.tag==="pre"||e.tag==="code"&&e.isCodeLines){const n=e.tag==="code"?e:xh(e,r=>r.tag==="code");return Yp(Fi(n||e),e.markdownLanguage||W3(n?.className||""))}if(e.tag==="code"){const n=Gp(Fi(e)).trim();return n?`\`${n.replace(/`/g,"\\`")}\``:""}if(e.tag==="ul")return x2(e,!1);if(e.tag==="ol")return x2(e,!0);if(e.tag==="blockquote")return hn(e.children.map(r=>yi(r)).join(`
52
- `)).split(`
53
- `).filter(r=>r.length>0).map(r=>`> ${r}`).join(`
54
- `);if(/^h[1-6]$/.test(e.tag)){const n=Number.parseInt(e.tag[1],10),r=hn(e.children.map(s=>uo(s)).join(""));return r?`${"#".repeat(n)} ${r}`:""}if(e.tag==="p"||e.tag==="div"||e.tag==="li")return hn(e.children.map(n=>uo(n)).join(""));const t=e.children.map(n=>yi(n)).filter(n=>n.length>0);return t.length>0?t.join(`
55
-
56
- `):hn(e.children.map(n=>uo(n)).join(""))},NE=e=>e.type==="text"?!0:!e.isMarkdownBlock&&!e.isCodeLines&&e.component!=="markdown-code"&&!jE.has(e.tag),RE=(e,t)=>{const n=Kp(e);if(n.every(s=>NE(s))){const s=hn(n.map(o=>uo(o)).join(""));if(s)return s}return n.map(s=>yi(s)).filter(s=>s.length>0).join(`
57
-
58
- `).trim()||hn(t)},b2=e=>(e.nodeType===1?e:e.parentElement)?.closest("pre code")??null,G3=(e,t)=>{const n=b2(e.startContainer),r=b2(e.endContainer),s=Kp(LE(e.cloneContents()));return n&&n===r?Yp(s.map(o=>Fi(o)).join(""),AE(n)):RE(s,t)},Xp=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
59
- ${e}
60
- ${n}`},PE='[data-chat-input="true"]',Jp=e=>{if(!e)return!1;const t=e;return!!(typeof t.closest=="function"?t:e.parentElement)?.closest(PE)},DE=e=>{if(Jp(e))return null;const t=e.tagName?.toLowerCase();if(t==="textarea"){const n=e,r=n.selectionStart??0,s=n.selectionEnd??0,o=hn(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=hn(n.value.slice(s,o));return i?(n.selectionStart=o,n.selectionEnd=o,i):null}return null},OE=()=>{if(typeof document>"u")return null;const e=document.activeElement;if(!e||typeof e.tagName!="string")return null;const t=DE(e);return t?Xp(t):null},HE=()=>{if(typeof document>"u")return null;const e=document.querySelector(".cm-editor.cm-focused");if(!e||Jp(e))return null;const t=fn.findFromDOM(e);if(!t)return null;const{from:n,to:r}=t.state.selection.main;if(n===r)return null;const s=hn(t.state.sliceDoc(n,r));return s?(t.dispatch({selection:{anchor:r}}),Yp(s)):null},FE=()=>{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(Jp(t.commonAncestorContainer))return null;const n=hn(e.toString());if(!n)return null;const r=G3(t,n);return e.removeAllRanges(),Xp(r)},VE=()=>HE()??OE()??FE(),K3=()=>{const e=VE();return se.getState().setActiveMainTab("chat"),se.getState().setSessionSwitcherOpen(!1),e&&Ge.getState().setPendingInputText(e,"append"),queueMicrotask(()=>{co()}),e!==null},Y3="file://";function BE(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 $E(e){const t=e.replace(/\\/g,"/").trim();return t.toLowerCase().startsWith(Y3)?t:`file://${BE(t)}`}function zE(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function w2(e){const t=e.trim().replace(/^['"]+|['"]+$/g,"");return!t||/[\r\n]/.test(t)?null:t.toLowerCase().startsWith(Y3)||zE(t)?t:null}function bh(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)bh(r,t,n+1);return}if(typeof e=="object")for(const r of Object.values(e))bh(r,t,n+1)}}function UE(e){const t=new Set,n=r=>{const s=w2(r);if(s){t.add(s);return}for(const o of r.split(/\r?\n/)){const i=w2(o);i&&t.add(i)}};n(e);try{const r=JSON.parse(e),s=new Set;bh(r,s);for(const o of s)n(o)}catch{}return Array.from(t)}function Wt(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 ZE(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 WE=["CodeFiles","codefiles","application/vnd.code.tree","application/vnd.code.tree.explorer","text/uri-list","text/plain"],tr="__home__",qE="Don't work in a folder",GE=()=>"~",KE=e=>e.enabled&&e.isDraftOpen&&!!e.activeProjectId&&e.selectedProjectId!==tr&&e.selectedProjectId!==e.activeProjectId,YE=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()||j5(n.path):null};function X3(e,t){const n=e.flatMap(o=>{const i={...o,id:o.id,ownerProjectId:o.id,kind:"project"},a=t.get(Wt(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=GE();return[{id:tr,ownerProjectId:tr,kind:"project",path:r,label:qE},...n]}const J3=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 Q3(e,t){if(e.length<=1)return null;const n=t?e.indexOf(t):-1;return e[(n+1)%e.length]??null}function wh(e=1){const t=it.getState(),n=t.projects;if(n.length<=1)return!1;const r=n.map(u=>u.id);let s=t.activeProjectId;if(!s||!r.includes(s)){const u=ce(tt.getState().currentDirectory??null);s=er(n,On(n,sn.getState()),u)?.id??null}const o=e===1?Q3(r,s):r[((s?r.indexOf(s):0)-1+r.length)%r.length]??null;if(!o)return!1;const i=n.find(u=>u.id===o),a=ce(i?.path??null);if(!i||!a)return!1;t.setActiveProjectIdOnly(o),J3.getState().selectSpace(o),se.getState().closeMainSurfaces();const c=On(n,sn.getState()),d=r3().find(u=>{const f=ce(u.directory??null);return f?er(n,c,f)?.id===o:!1});if(d){const u=ce(d.directory??null);return ve.getState().setCurrentSession(d.id,u),!0}return ve.getState().openNewSessionDraft({selectedProjectId:o,directoryOverride:a}),!0}function XE(){const e=ve.getState(),t=e.newSessionDraft;if(!t?.open)return!1;const n=it.getState(),r=n.projects,s=X3(r,On(r,sn.getState()));if(s.length<=1)return!1;const o=ce(t.directoryOverride??null),i=t.selectedProjectId?s.find(u=>u.ownerProjectId===t.selectedProjectId&&(!o||ce(u.path)===o))??s.find(u=>u.id===t.selectedProjectId)??(o?s.find(u=>ce(u.path)===o)??null:null):o?s.find(u=>ce(u.path)===o)??null:null,a=Q3(s.map(u=>u.id),i?.id??null),c=s.find(u=>u.id===a),d=ce(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),J3.getState().selectSpace(c.ownerProjectId)),e.setNewSessionDraftTarget({projectId:c.ownerProjectId,directoryOverride:d,branchIntent:null,worktreeIntent:null}),!0)}const JE=['[data-slot="dropdown-menu-content"][data-open]','[data-slot="select-content"][data-open]'].join(",");function QE(e=document){return!!e.querySelector(JE)}const ej=(e,t)=>!e.repeat&&kt(e,t),tj=e=>{const t=ve.getState().currentSessionId;t&&Je().prompt(t,c7(e),"prompt").catch(()=>{})},nj=()=>{const e=ve(j=>j.openNewSessionDraft),t=ve(j=>j.armAbortPrompt),n=ve(j=>j.clearAbortPrompt),r=ve(j=>j.currentSessionId),s=m3,o=se(j=>j.toggleCommandPalette),i=se(j=>j.toggleHelpDialog),a=se(j=>j.toggleSidebar),c=tt(j=>j.currentDirectory),d=Vn(),u=h.useCallback(()=>{c&&se.getState().openContextSurface(_i(c),"terminal")},[c]),f=se(j=>j.isMobile),p=se(j=>j.setSessionSwitcherOpen),m=se(j=>j.setActiveMainTab),g=se(j=>j.setSettingsDialogOpen),y=se(j=>j.setModelSelectorOpen),b=se(j=>j.setTimelineDialogOpen),k=se(j=>j.setPromptNavigatorPanelOpen),v=se(j=>j.shortcutOverrides),x=tt(j=>j.currentDirectory),C=it(j=>j.getActiveProject()),{themeMode:S,setThemeMode:w}=Fn(),{phase:M}=Zp(),I=h.useRef(null),E=h.useRef(null),_=h.useRef(S),T=h.useRef(new Set);h.useEffect(()=>{_.current=S},[S]);const A=h.useCallback(()=>{E.current&&(clearTimeout(E.current),E.current=null),I.current=null,n()},[n]);h.useEffect(()=>{const j=D=>l7(D,v),N=o7("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(","),L=D=>D instanceof Element&&!!D.closest(O),P=D=>{if(Zu(D.target)&&kt(D,j("toggle_terminal"))){const{isMobile:U}=se.getState();if(U)return;D.preventDefault(),D.stopPropagation(),u();return}},W=D=>{if(D.key!=="Escape")return;const U=D.target,Y=!!U?.closest('[role="dialog"]'),ne=!!document.querySelector('[data-settings-view="true"]'),$=Zu(U),J=L(U)||QE(),{isSettingsDialogOpen:G,isCommandPaletteOpen:ue,isHelpDialogOpen:B,isSessionSwitcherOpen:ie,isImagePreviewOpen:xe,activeMainTab:de,isPromptNavigatorPanelOpen:Se}=se.getState();if(Y||$||J){A();return}if(Se){D.preventDefault(),k(!1),A();return}if(G){D.preventDefault(),g(!1),A();return}if(ne){A();return}if(ue||B||ie||xe||!(de==="chat")){A();return}const Be=r;if(M==="idle"||!Be){A();return}const Ie=Date.now(),fe=I.current;if(fe&&Ie<fe){D.preventDefault(),A(),s(Be);return}D.preventDefault();const ee=t(3e3)??Ie+3e3;I.current=ee,E.current&&clearTimeout(E.current);const he=Math.max(ee-Ie,0);E.current=setTimeout(()=>{I.current&&Date.now()>=I.current&&A()},he||0)},F=D=>{if(D.key==="Escape"||Zu(D.target))return;if(kt(D,j("open_command_palette"))){D.preventDefault(),o();return}if(kt(D,j("open_timeline_dialog"))){D.preventDefault(),b(!0);return}if(kt(D,j("open_help"))){D.preventDefault(),i();return}if(i7()&&kt(D,j("new_mini_chat"))){D.preventDefault(),Qn("desktop_open_draft_mini_chat_window",{directory:x||C?.path||"",projectId:C?.id??null}).catch($=>{console.warn("[keyboard-shortcuts] failed to open draft mini chat window",$)});return}if(kt(D,j("new_chat"))){D.preventDefault(),m("chat"),p(!1),e();return}if(kt(D,j("cycle_theme"))){D.preventDefault();const $=["light","dark","system"],J=document.activeElement,ue=($.indexOf(_.current)+1)%$.length;w($[ue]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),J&&document.contains(J)&&J.focus({preventScroll:!0}))});return}if(kt(D,j("open_settings"))){D.preventDefault();const{isSettingsDialogOpen:$}=se.getState();g(!$);return}if(kt(D,j("add_selection_to_chat"))){D.preventDefault(),K3();return}if(kt(D,j("toggle_sidebar"))){D.preventDefault();const{isMobile:$,isSessionSwitcherOpen:J}=se.getState();$?p(!J):a();return}if(kt(D,j("focus_input"))){D.preventDefault(),co();return}if(kt(D,j("cycle_session_folder"))){if(!wh())return;D.preventDefault();return}if(kt(D,j("cycle_draft_folder"))){if(!XE())return;D.preventDefault();return}if(kt(D,j("open_right_sidebar"))){const $=se.getState();if($.isMobile||!x)return;D.preventDefault();const J=_i(x),G=$.contextPanelByDirectory[J];if(G?.isOpen)return;G?.activeTabId?$.setActiveContextPanelTab(J,G.activeTabId):$.openContextSurface(J,"git");return}if(kt(D,j("toggle_terminal"))){const{isMobile:$}=se.getState();if($)return;D.preventDefault(),u();return}const Y=D.key.length===1&&D.key>="0"&&D.key<="9"?D.key==="0"?10:Number(D.key):null;if(Y!==null&&!D.repeat&&a7(D,N,T.current)){const $=se.getState();if($.isMobile||!d)return;const J=_i(d),G=$.contextPanelByDirectory[J];let ue;const B=pa.getState().entriesByDirectory[J]??null;if(B){const de=B.scope?.repositories??[];ue={isLoading:B.isLoading,hasResult:!!(B.scope||B.error),hasGitHubRepo:de.some(Se=>!!(Se.host&&Se.owner&&Se.repo&&!Se.disabledReason)),hasError:!!(B.error&&!B.scope)}}const xe=wE({railOrder:$.contextRailOrder,tabs:G?.tabs??[],githubScope:ue})[Y-1];if(!xe)return;D.preventDefault(),$.openContextSurface(J,xe.mode);return}if(ej(D,j("open_model_selector"))){const{isSettingsDialogOpen:$,isCommandPaletteOpen:J,isHelpDialogOpen:G,isSessionSwitcherOpen:ue,activeMainTab:B,isModelSelectorOpen:ie}=se.getState();if($||J||G||ue||!(B==="chat"))return;D.preventDefault(),y(!ie);return}if(kt(D,j("cycle_thinking_variant"))){const{isSettingsDialogOpen:$,isCommandPaletteOpen:J,isHelpDialogOpen:G,isSessionSwitcherOpen:ue,activeMainTab:B}=se.getState();if($||J||G||ue||!(B==="chat")||qe.getState().getCurrentModelVariants().length===0)return;D.preventDefault(),_E(1).catch(()=>{Ne.error("Couldn't update thinking")});return}if(kt(D,j("cycle_favorite_model_forward"))||kt(D,j("cycle_favorite_model_backward"))){const{isSettingsDialogOpen:$,isCommandPaletteOpen:J,isHelpDialogOpen:G,isSessionSwitcherOpen:ue,activeMainTab:B,favoriteModels:ie,addRecentModel:xe}=se.getState();if($||J||G||ue||!(B==="chat")||ie.length===0)return;D.preventDefault();const{currentProviderId:je,currentModelId:Oe,setProvider:Be,setModel:Ie}=qe.getState(),fe=ie.length,ee=ie.findIndex(Ae=>Ae.providerID===je&&Ae.modelID===Oe),he=kt(D,j("cycle_favorite_model_forward"))?1:-1,Ce=ie[(ee+he+fe)%fe];Be(Ce.providerID),Ie(Ce.modelID),xe(Ce.providerID,Ce.modelID);return}const ne=se.getState().commandTriggers;if(ne.length>0&&!L(D.target)){for(const $ of ne)if(!(!$.combo||!kt(D,$.combo))){D.preventDefault(),D.stopPropagation(),tj($);return}}},q=D=>{T.current.add(D.key.toLowerCase())},K=D=>{T.current.delete(D.key.toLowerCase())},Q=()=>{T.current.clear()};return window.addEventListener("keydown",q,!0),window.addEventListener("keyup",K,!0),window.addEventListener("blur",Q),window.addEventListener("keydown",P,!0),window.addEventListener("keydown",W,!0),window.addEventListener("keydown",F),()=>{window.removeEventListener("keydown",q,!0),window.removeEventListener("keyup",K,!0),window.removeEventListener("blur",Q),window.removeEventListener("keydown",P,!0),window.removeEventListener("keydown",W,!0),window.removeEventListener("keydown",F)}},[e,s,o,i,a,u,f,p,m,g,y,b,k,w,M,t,A,r,x,d,C?.id,C?.path,v]),h.useEffect(()=>()=>{A()},[A])},rj=3,sj=(e,t)=>{if(typeof e!="string")return t;const n=e.trim().replace(/\s+/g," ");return n?n.slice(0,48):t},oj=(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:sj(o.title,`Session ${r.length+1}`)}),r.length>=rj))break}return r},ij=()=>{const e=h3(),t=ve(o=>o.currentSessionId),n=h.useMemo(()=>oj(e,t),[t,e]),r=h.useMemo(()=>JSON.stringify(n),[n]),s=n.length>0;h.useEffect(()=>{if(typeof window>"u"||!op())return;try{s?localStorage.setItem(w1,r):localStorage.removeItem(w1)}catch{return}window.__PICHAMBER_UPDATE_PWA_MANIFEST__?.()},[s,r])},aj=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")},lj=async(e,t)=>{try{const n=u7(e.runtimeKey);if(!t.streamEpoch||t.streamEpoch!==n)return"unknown";const r=await De.getSendReceipt({sessionId:e.sessionId,kind:t.kind,operationId:t.operationId,streamEpoch:t.streamEpoch},{directory:e.directory,runtimeKey:e.runtimeKey});return aj(r)}catch{return"unknown"}},ex=e=>e instanceof d7,cj=2e3,hr="hydrate-demand",tx=2e3,dj=6e4,uj=e=>Math.min(tx*2**Math.max(e-1,0),dj),S2=(e,t,n)=>e!==void 0&&e.messageId===t&&n<e.nextAttemptAt,fj=(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}}},hj=e=>{const t=ve.getState().sessionAbortFlags.get(e);if(!t)return null;const n=t.timestamp+cj;return Date.now()<n?n:null},pj=e=>{const t=e[0];return t?{queuedMessageId:t.id,primaryText:t.content,primaryAttachments:t.attachments??[],agentMentionName:void 0,sendConfig:t.sendConfig}:null},mj=(e,t,n,r)=>ve.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}:{}}),gj=e=>{const t=qe.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}},yj=(e,t)=>{if(e.connection!=="ready")return"unknown";const n=e.catalog.byId.get(t.sessionId);return!n||ce(n.directory)!==ce(t.directory)||n.archived?"unknown":n.lifecycle==="busy"||n.lifecycle==="retry"?"busy":n.hydrated?"ready":"unknown"};function vj(e){const t=typeof e=="boolean"?e:e?.enabled??!0,n=lt(p=>p.queuedMessages),r=tt(p=>p.currentDirectory),s=fa(),o=Ke(p=>p.catalog,void 0,St),i=Ke(p=>p.connection,void 0,jt),a=h.useRef(new Set),c=h.useRef(new Map),[d,u]=h.useState(0),f=h.useMemo(()=>fj(()=>u(p=>p+1)),[]);h.useEffect(()=>()=>f.dispose(),[f]),h.useEffect(()=>{if(!t)return;const p=lt.getState().queuedMessages;for(const[k,v]of c.current)v.messageId===hr&&!(k in p)&&c.current.delete(k);const m=k=>{c.current.get(k)?.messageId===hr&&c.current.delete(k)},g=async(k,v,x)=>{const C=s.getState();if(C.connection!=="ready")return;const S=C.catalog.byId.get(v);if(!S||S.archived||ce(S.directory)!==ce(k.directory))return;const w=c.current.get(x);if(w?.messageId===hr&&S2(w,hr,Date.now())){f.schedule(w.nextAttemptAt);return}if(a.current.has(x))return;a.current.add(x);try{await s.ensureHydrated(v)}finally{a.current.delete(x),u(A=>A+1)}const M=s.getState();if(s.isDeleted(v)||!M.catalog.byId.has(v)){m(x);return}if(M.catalog.byId.get(v)?.hydrated){m(x);return}const _=(w?.messageId===hr?w.failures:0)+1,T=Date.now()+uj(_);c.current.set(x,{messageId:hr,failures:_,nextAttemptAt:T}),f.schedule(T)},y=async(k,v)=>{const{sessionId:x}=k,C=T5(k);if(v.length===0||k.runtimeKey!==X()||a.current.has(C))return;const S=hj(x);if(S!==null){f.schedule(S);return}const w=s.getState(),M=yj(w,k);if(M==="busy")return;if(M==="unknown"){await g(k,x,C);return}const I=lt.getState().getAutoSendCandidate(k);if(!I)return;const E=c.current.get(C);if(E&&E.messageId!==I.id&&E.messageId!==hr)c.current.delete(C);else if(E&&E.messageId!==hr&&S2(E,I.id,Date.now())){Number.isFinite(E.nextAttemptAt)&&f.schedule(E.nextAttemptAt);return}const _=lt.getState().claimQueuedMessage(k,I.id);if(!_)return;const T=pj([_]);if(!T){lt.getState().clearSending(k,_.id);return}const A=T.sendConfig,j=A?.providerID&&A?.modelID?A:gj(x);if(!j.providerID||!j.modelID){lt.getState().clearSending(k,_.id),f.schedule(Date.now()+tx);return}a.current.add(C);const N=lt.getState().markDeliveryAttempt(k,_.id,"followUp");if(!N?.streamEpoch){a.current.delete(C),lt.getState().clearSending(k,_.id);return}try{await mj(k,T,{providerID:j.providerID,modelID:j.modelID,agent:j.agent,variant:j.variant},N.streamEpoch),lt.getState().completeQueuedSend(k,T.queuedMessageId),c.current.delete(C)}catch(O){console.warn("[follow-up] auto-send failed:",O);const L=E?.messageId===T.queuedMessageId?E.failures:0;c.current.set(C,{messageId:T.queuedMessageId,failures:L+1,nextAttemptAt:Number.POSITIVE_INFINITY}),ex(O)?(lt.getState().markSendUnconfirmed(k,T.queuedMessageId,"followUp"),Ne.error("Follow-up status uncertain. Check status before retrying.",{id:`follow-up-unconfirmed:${C}:${T.queuedMessageId}`})):(lt.getState().markSendFailed(k,T.queuedMessageId),Ne.error("Follow-up message failed to send. Use Send now to retry.",{id:`follow-up-failed:${C}:${T.queuedMessageId}`}))}finally{a.current.delete(C),lt.getState().clearSending(k,T.queuedMessageId)}};Object.entries(n).forEach(([k,v])=>{const x=f7(k);!x||x.runtimeKey!==X()||x.directory!==r||v.length!==0&&y(x,v)})},[t,n,r,o,i,d,f,s])}const xj=1440*60*1e3,nx=5,rx=1440*60*1e3,bj=[],Gu=e=>e.time?.updated??e.time?.created??0,Sh=({sessions:e,currentSessionId:t,cutoffDays:n,keepRecent:r=nx,now:s=Date.now()})=>{if(!Array.isArray(e)||n<=0)return[];const o=s-n*xj,i=[...e].sort((c,d)=>Gu(d)-Gu(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=Gu(c);return d?d<o:!1}).map(c=>c.id)},wj=(e,t,n)=>{const r=[],s=[];for(const o of e){const i=t.get(o),a=i?Fp(i):null;a&&n.has(a)?r.push(o):s.push(o)}return{actionable:r,unready:s}},Sj=()=>{try{const e=Je();return{store:e,runtimeKey:X(),generation:e.getRuntimeGeneration()}}catch{return null}},Ku=e=>{try{const t=Je();return t!==e.store||X()!==e.runtimeKey?!1:t.getRuntimeGeneration()===e.generation}catch{return!1}};let Jl=!1;const Cj=()=>Jl,kj=async({force:e=!1,now:t}={})=>{const n=()=>{try{return se.getState().sessionRetentionAction??"archive"}catch{return"archive"}};if(Jl)return{completedIds:[],failedIds:[],action:n(),skippedReason:"running"};let r;try{const i=se.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<rx)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"cooldown"};const o=Sj();if(!o)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"stale"};Jl=!0;try{try{let i;try{i=await cE()}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}if(i.stale||!Ku(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 S of i.catalog.byId.values())S.archived||a.push(oo(S));if(a.length===0){if(i.failedDirectories.size>0)return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"};try{se.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:[],failedIds:[],action:r.action,skippedReason:"no-candidates"}}let c,d,u;try{c=ve.getState().currentSessionId??null;const S=se.getState();d=S.sessionRetentionAction??r.action,u=S.autoDeleteAfterDays??r.days}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}const f=Sh({sessions:a,currentSessionId:c,cutoffDays:u,now:s});if(f.length===0){if(i.failedDirectories.size>0)return{completedIds:[],failedIds:[],action:d,skippedReason:"partial"};try{se.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:[],failedIds:[],action:d,skippedReason:"no-candidates"}}const p=new Map(a.map(S=>[S.id,S])),{actionable:m,unready:g}=wj(f,p,i.readyDirectories);if(m.length===0)return{completedIds:[],failedIds:[...g],action:d,skippedReason:"partial"};const y=[],b=new Set(g),k=[...g],v=S=>{b.has(S)||(b.add(S),k.push(S))};let x=!1,C=d;for(let S=0;S<m.length;S+=1){const w=m[S];if(!Ku(o)){for(let N=S;N<m.length;N+=1)v(m[N]);x=!0;break}let M,I,E,_;try{M=ve.getState().currentSessionId??null;const N=se.getState();I=N.sessionRetentionAction??d,E=N.autoDeleteAfterDays??u,_=Je().getState().catalog}catch{v(w);continue}C=I;let T=!1,A=null;try{const N=[];for(const L of _.byId.values())L.archived||N.push(oo(L));if(T=new Set(Sh({sessions:N,currentSessionId:M,cutoffDays:E,now:s})).has(w),T){const L=_.byId.get(w);A=L?Fp(oo(L)):null}}catch{v(w);continue}if(!T||!A){v(w);continue}let j;try{j=_.listStatusByDirectory.get(A)}catch{v(w);continue}if(j!=="ready"){v(w);continue}try{const N=Je();I==="archive"?await N.archive(w,!0,A):await N.remove(w,A)}catch{v(w);continue}if(!Ku(o)){v(w);for(let N=S+1;N<m.length;N+=1)v(m[N]);x=!0;break}y.push(w)}if(x)return{completedIds:y,failedIds:k,action:C,skippedReason:"stale"};if(i.failedDirectories.size>0||k.length>0)return{completedIds:y,failedIds:k,action:C,skippedReason:"partial"};try{se.getState().setAutoDeleteLastRunAt(s)}catch{}return{completedIds:y,failedIds:k,action:C}}catch{return{completedIds:[],failedIds:[],action:r.action,skippedReason:"partial"}}}finally{Jl=!1}},Mj=e=>{const t=typeof e=="object"?e:void 0,n=t?.autoRun!==!1,r=typeof e=="boolean"?e:t?.enabled??!0,s=ve(b=>b.currentSessionId),o=se(b=>b.autoDeleteEnabled),i=se(b=>b.autoDeleteAfterDays),a=se(b=>b.sessionRetentionAction),c=se(b=>b.autoDeleteLastRunAt),d=r&&(!n||o),u=Ke(b=>na(b.catalog,{archived:!1}),t3,"catalog"),f=d?u:bj,[p,m]=h.useState(!1),g=h.useMemo(()=>i<=0?[]:Sh({sessions:f,currentSessionId:s,cutoffDays:i}),[i,s,f]),y=h.useCallback(async({force:b=!1}={})=>{m(!0);try{return await kj({force:b})}finally{m(!1)}},[]);return h.useEffect(()=>{if(!r||!n||!o||i<=0||g.length===0)return;const b=Date.now();c&&b-c<rx||Cj()||y()},[i,o,c,n,g.length,r,y]),{candidates:g,isRunning:p,runCleanup:y,keepRecentCount:nx,action:a}},Yu=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:"0px",Xu=(e,t,n)=>{const r=e.style.getPropertyValue(t);r===n||!r&&n==="0px"||e.style.setProperty(t,n)},Ju=(e,t,n,r)=>{Xu(e,"--oc-wco-left-inset",Yu(t)),Xu(e,"--oc-wco-right-inset",Yu(n)),Xu(e,"--oc-wco-titlebar-height",Yu(r))},Ij=()=>{h.useEffect(()=>{if(typeof window>"u"||!op())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){Ju(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),u=Math.max(0,window.innerWidth-(a+c));Ju(e,a,u,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),Ju(e,0,0,0)}},[])},_j=()=>{};async function Ej(e,t){if(!e?.listen)return _j;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 ml=e=>{const t=se.getState();e&&t.setSettingsPage(e),t.setSettingsDialogOpen(!0)},C2=e=>{const t=r3();if(t.length<2)return;const n=ve.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,Fp(o))};function jj(){const{setThemeMode:e}=Fn(),t=h.useCallback(s=>{const o=se.getState();switch(s){case"about":ml("about");return;case"settings":ml();return;case"command-palette":o.setCommandPaletteOpen(!0);return;case"new-session":o.setActiveMainTab("chat"),o.setSessionSwitcherOpen(!1),ve.getState().openNewSessionDraft();return;case"change-workspace":kd.requestDirectoryDialog();return;case"add-selection-to-chat":K3();return;case"open-right-sidebar":{const i=tt.getState().currentDirectory;if(!i)return;const a=_i(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(_i(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":cc(!_o());return;case"go-back":window.history.back();return;case"go-forward":window.history.forward();return;case"previous-session":C2(-1);return;case"next-session":C2(1);return;case"previous-project":wh(-1);return;case"next-project":wh(1);return;case"help-dialog":o.setHelpDialogOpen(!0);return;case"download-logs":ml("general"),cc(!0);return;case"copy":return;default:return}},[e]),n=h.useCallback(()=>{ml("about"),XI.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(!vo())return;let s=!1,o=()=>{};return Ej(h7(),{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 Tj=()=>{const e=it.getState().projects,t=On(e,sn.getState()),n=[...z3(e,t,{includeWorktrees:!0})];try{const r=[tt.getState().homeDirectory,zt().getItem("homeDirectory"),typeof window<"u"?window.__PICHAMBER_HOME__:null],s=new Set(n.map(o=>ce(o)?.toLowerCase()??o));for(const o of r){if(!o)continue;const i=ce(o);if(!i)continue;const a=i.toLowerCase();s.has(a)||(s.add(a),n.push(i))}}catch{}return n},Aj=e=>e.length===0?"":[...e].sort().join("|"),Lj=()=>(z.useEffect(()=>{let e=!1,t="";const n=Je(),r=()=>{if(e)return;const a=Tj();if(a.length===0)return;const c=Aj(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 u=a.filter(f=>{const p=n.getState().catalog.listStatusByDirectory.get(f);return p!=="ready"&&p!=="loading"});if(u.length===0){t=c;return}t=c,n.refreshAllDirectoryCatalogs(u)};r();const s=it.subscribe(r),o=sn.subscribe(r),i=n.subscribe(r,"chrome");return()=>{e=!0,s(),o(),i()}},[]),null),ma=()=>{const e=h.useContext(ha);if(!e)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return e},Nj=6e4,Rj=2,Pj=()=>{const e=it(c=>c.projects),t=sn(c=>c.refreshProject),{git:n}=ma(),r=h.useMemo(()=>e.map(c=>c.path).filter(c=>!!c),[e]),s=h.useMemo(()=>[...r].sort().join("\0"),[r]),o=X(),i=h.useCallback(async()=>{if(!n||r.length===0)return;let c=0;const d=async()=>{for(;c<r.length;){const u=r[c];c+=1,await t(u,n)}};await Promise.all(Array.from({length:Math.min(Rj,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 u=window.setInterval(()=>{document.visibilityState==="visible"&&i()},Nj);return()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",d),window.clearInterval(u)}},[i]),null},k2=2e3,Dj=3e4,Oj=2;class Hj{constructor(t){this.options=t}timer=null;currentDelayMs=k2;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=k2}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,wr("config-reconcile",{code:"attempt"});try{await this.options.initializeApp()}catch{}finally{this.inFlight=!1}if(this.disposed)return;if(!this.isMismatched()){wr("config-reconcile",{code:"success"}),this.resetDelay();return}if(wr("config-reconcile",{code:"failure"}),this.isHidden())return;const t=this.currentDelayMs;this.currentDelayMs=Math.min(t*Oj,Dj),this.timer=setTimeout(()=>{this.timer=null,this.executeAttempt()},t)}}function Fj({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 Hj({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=pn(()=>{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 Vj="pichamber:mini-chat-presence",Bj=()=>(h.useEffect(()=>{if(typeof BroadcastChannel>"u")return;const e=new BroadcastChannel(Vj);return e.onmessage=t=>{const n=t.data;if(n?.type!=="mini-chat-session-presence"||!n.sessionId||!n.directory)return;n.viewed!==!1&&sd(n.sessionId)},()=>e.close()},[]),null);function $j({embeddedBackgroundWorkEnabled:e}){return Mj(e),vj(e),l.jsx(Lj,{})}const zj=()=>{const e=h.useMemo(()=>Je(),[]),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;ce(a)!==ce(s)&&tt.getState().setDirectory(s,{showOverlay:!1}),qe.getState().activateDirectory(s)},[s]),h.useEffect(()=>{const a=ve.getState();if(!r||!s){if(o==="loading"||i)return;(a.currentSessionId!==null||a.currentSessionDirectory!==null)&&ve.setState({currentSessionId:null,currentSessionDirectory:null});return}if(!i&&!Rp(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}}:{};ve.setState({currentSessionId:r,currentSessionDirectory:s,...c}),sd(r)}},[r,s,o,i]),null},Uj=()=>{const e=h.useMemo(()=>Je(),[]),t=h.useMemo(()=>c=>e.subscribe(c,"chrome"),[e]),n=h.useSyncExternalStore(t,e.getState,e.getState),r=qe(c=>c.initializeApp),s=qe(c=>c.isInitialized),o=qe(c=>c.isConnected),i=qe(c=>c.loadProviders),a=qe(c=>c.providers.length);return Fj({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 oW({embeddedBackgroundWorkEnabled:e}){return ij(),Ij(),nj(),jj(),l.jsxs(l.Fragment,{children:[l.jsx(Uj,{}),l.jsx($j,{embeddedBackgroundWorkEnabled:e}),l.jsx(zj,{}),l.jsx(Bj,{}),l.jsx(Pj,{})]})}const sx=({text:e})=>l.jsx("span",{"aria-hidden":"true",className:"oc-shimmer-clip",children:l.jsx("span",{className:"oc-shimmer-band","data-shimmer-text":e})}),Zj=Array.from({length:9},(e,t)=>{const n=Math.floor(t/3);return(t%3+Math.abs(n-1))*90}),Wj=650;function Qu({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:Zj.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 ${Wj}ms ease-in-out ${t}ms infinite`}},n))})}function qj(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 M2=({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=qj(a&&s,i),d=a?l.jsxs("span",{className:R("pixel-loader-label min-w-0 truncate whitespace-nowrap typography-markdown font-medium",o&&"agent-thinking-label-enter"),children:[e,l.jsx(sx,{text:e})]},o?e:void 0):null,u=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:R("inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-normal","bg-primary/10 text-primary border border-primary/20","transition-opacity duration-300",t),role:"status","aria-live":"polite",children:[l.jsx(Qu,{compact:!a}),d,u]}):n==="full"?l.jsxs("div",{className:R("flex items-center gap-2.5 rounded-lg border border-primary/25 bg-primary/5 px-3 py-1.5 text-sm text-foreground",t),role:"status","aria-live":"polite",children:[l.jsx(Qu,{compact:!a}),d,u]}):l.jsxs("span",{className:R("inline-flex min-w-0 items-center gap-2.5",t),role:"status","aria-live":"polite",children:[l.jsx(Qu,{compact:!a}),d,u]})},I2="pichamber:chunk-import-reload",Gj=250,Kj=3e4,Yj=[/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 ox(e){if(e instanceof Error)return`${e.name}
61
- ${e.message}
62
- ${e.stack??""}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function _2(e){const t=ox(e);return Yj.some(n=>n.test(t))}function Xj(e){return`1.0.4:${ox(e).slice(0,500)}`}function Jj(e){if(typeof window>"u")return;const t=Date.now(),n=Xj(e);let r=null;try{const o=window.sessionStorage.getItem(I2);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<Kj)){try{window.sessionStorage.setItem(I2,JSON.stringify({signature:n,timestamp:t}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function Qj(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,!_2(o)||s>=n)break;await new Promise(i=>setTimeout(i,Gj*(s+1)))}throw _2(r)&&Jj(r),r}const ys=e=>z.lazy(()=>Qj(e)),eT=ys(()=>Vp().then(e=>({default:e.MarkdownRenderer}))),tT=ys(()=>Vp().then(e=>({default:e.SimpleMarkdownRenderer}))),nT=l.jsx("div",{className:"break-words w-full min-w-0"}),rT=e=>e==="tool"?"markdown-content markdown-tool":e==="reasoning"?"markdown-content markdown-reasoning":"markdown-content leading-relaxed",ix=e=>!rn()||typeof e.content!="string"||e.content.length===0?nT:l.jsx("div",{className:R("break-words w-full min-w-0 whitespace-pre-wrap",rT(e.variant),typeof e.className=="string"?e.className:void 0),children:e.content}),ga=e=>l.jsx(h.Suspense,{fallback:l.jsx(ix,{...e}),children:l.jsx(eT,{...e})}),ya=e=>l.jsx(h.Suspense,{fallback:l.jsx(ix,{...e}),children:l.jsx(tT,{...e})}),sT=N5(["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"}}),Qp=z.createContext(null),oT=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function E2({onValueChange:e,modal:t=!1,...n}){const[r,s]=z.useState(null),o=z.useMemo(()=>({portalContainer:r,setPortalContainer:s}),[r]),i=z.useCallback((a,c)=>{typeof a=="string"&&e?.(a,c)},[e]);return l.jsx(Qp.Provider,{value:o,children:l.jsx(r9,{...n,modal:t,onValueChange:i})})}function iT({...e}){return l.jsx(h9,{"data-slot":"select-group",...e})}function j2({placeholder:e,children:t,...n}){return l.jsx(i9,{"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 T2({className:e,size:t="default",children:n,asChild:r,onPointerDownCapture:s,onFocusCapture:o,...i}){const a=z.useContext(Qp),c=z.useCallback(u=>{if(!a)return;const f=u instanceof HTMLElement?u:null;a.setPortalContainer(oT(f))},[a]),d=r&&z.isValidElement(n)?{render:n}:null;return l.jsx(s9,{"data-slot":"select-trigger","data-size":t,className:R(sT({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:u=>{c(u.currentTarget),s?.(u)},onFocusCapture:u=>{c(u.currentTarget),o?.(u)},...i,...d??{},children:d?void 0:l.jsxs(l.Fragment,{children:[n,l.jsx(o9,{children:l.jsx(V,{name:"arrow-down-s",className:"size-4 opacity-50"})})]})})}function A2({className:e,children:t,position:n="popper",fitContent:r=!1,portalToBody:s=!1,sideOffset:o,side:i,align:a,...c}){const d=z.useContext(Qp),u=n==="item-aligned",f=d?.portalContainer??null;return l.jsx(a9,{container:s?void 0:f||void 0,children:l.jsx(l9,{alignItemWithTrigger:u,sideOffset:o,side:i,align:a,className:"absolute z-[120] pointer-events-auto",children:l.jsx(c9,{"data-slot":"select-content",style:{color:"var(--surface-elevated-foreground)"},className:R("oc-glass-popover oc-glass-floating pointer-events-auto transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 relative z-[120] max-h-[var(--oc-select-max-height,var(--available-height))] min-w-[8rem] origin-[var(--transform-origin)] overflow-x-hidden rounded-xl","data-[side=top]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-top,0px))] data-[side=bottom]:[--oc-select-max-height:calc(var(--available-height)_-_env(safe-area-inset-bottom,0px))]",!u&&"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(Hn,{outerClassName:R("max-h-[var(--oc-select-max-height,var(--available-height))]",r?"w-max":"w-full"),className:R("p-1",!u&&(r?"w-max min-w-0 scroll-my-1":"w-full min-w-[var(--anchor-width)] scroll-my-1")),preventOverscroll:!0,children:t})})})})}function aT({className:e,...t}){return l.jsx(p9,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",e),...t})}function L2({className:e,children:t,...n}){return l.jsxs(d9,{"data-slot":"select-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[selected]:bg-interactive-selection data-[selected]:text-interactive-selection-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-pointer items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[l.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:l.jsx(u9,{children:l.jsx(V,{name:"check",className:"size-4"})})}),l.jsx(f9,{children:t})]})}const N2=e=>e.some(t=>t.source==="local"&&(t.uploadState?.status==="preparing"||t.uploadState?.status==="uploading")),lT=e=>e.some(t=>t.source==="local"&&t.uploadState?.status==="failed"),ef=(e,t=Date.now())=>e.every(n=>n.source==="server"||n.uploadState?.status==="ready"&&n.uploadState.expiresAt>t),Ql=200,R2={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:600*1e3},ax=()=>Ql,cT=()=>Math.round(ax()*.6),dT={MAX_SESSIONS:R2.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(Ql*.6),HISTORICAL_MESSAGES:Ql,FETCH_BUFFER:20,HISTORY_CHUNK:Ql,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:R2.ZOMBIE_TIMEOUT},P2=()=>{const e=ax(),t=cT();return{...dT,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},uT=5e3,bn=new Map,vr=new Map,Yn=new Map,Vi=new Map,zs=(e,t)=>`${e}
63
- ${t?.trim()??""}`,fo=e=>{Vi.set(e,(Vi.get(e)??0)+1),vr.delete(e)},fT=e=>{const t=X();if(typeof e=="string"&&e.trim().length>0){const r=zs(t,e);bn.delete(r),fo(r);return}const n=new Set([...bn.keys(),...vr.keys(),...Yn.keys()]);for(const r of n)r.startsWith(`${t}
64
- `)&&(bn.delete(r),fo(r))},tf=e=>{const t=new Set([...bn.keys(),...vr.keys(),...Yn.keys()]);for(const n of t)n.startsWith(`${e}
65
- `)&&(bn.delete(n),fo(n))},gl=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(),vr.clear(),Yn.clear(),Vi.clear(),e({snippets:[],isLoading:!1,selectedSnippetId:null,activeCacheKey:"",snippetDraft:null})},loadSnippets:async n=>{const r=X(),s=zs(r,n),o=Date.now(),i=Yn.get(s);e({activeCacheKey:s,snippets:i??[],isLoading:!0});const a=bn.get(s)??0;if(a>0&&o-a<uT)return e({isLoading:!1}),!0;const c=vr.get(s);if(c)return c;const d=Vi.get(s)??0,u=(async()=>{try{const f=await De.listSnippets(n,{runtimeKey:r});if(X()!==r)return!1;if((Vi.get(s)??0)!==d)return e(m=>m.activeCacheKey===s?{isLoading:!1}:m),!0;const p=gl(f);return Yn.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(f=>f.activeCacheKey===s?{isLoading:!1}:f),!1}})();vr.set(s,u);try{return await u}finally{vr.get(s)===u&&vr.delete(s)}},createSnippet:async(n,r,s={})=>{const o=X(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await De.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(X()!==o)return!1;const c=zs(o,i),d=gl(a);fo(c),Yn.set(c,d),tf(o),bn.set(c,Date.now());const u=d.find(f=>f.name===n&&f.source===(s.scope??"global"));return e(f=>f.activeCacheKey===c?{snippets:d,snippetDraft:null,selectedSnippetId:u?.id??null,isLoading:!1}:f),!0}catch{return!1}},updateSnippet:async(n,r,s)=>{const o=X(),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 De.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(X()!==o)return!1;const d=zs(o,a),u=gl(c);return fo(d),Yn.set(d,u),tf(o),bn.set(d,Date.now()),e(f=>f.activeCacheKey===d?{snippets:u,isLoading:!1}:f),!0}catch{return!1}},deleteSnippet:async(n,r)=>{const s=X(),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 De.deleteSnippet(o.id,i,{runtimeKey:s});if(X()!==s)return!1;const c=zs(s,i),d=gl(a);return fo(c),Yn.set(c,d),tf(s),bn.set(c,Date.now()),e(u=>u.activeCacheKey===c?{snippets:d,isLoading:!1,...u.selectedSnippetId===n?{selectedSnippetId:null}:{}}:u),!0}catch{return!1}},expandText:(n,r)=>{if(!n||!n.includes("#"))return n;const s=zs(X(),r),o=Yn.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 u of c.aliases??[]){const f=u.toLowerCase();i.has(f)||i.set(f,c.content)}}return i.size===0?n:n.replace(/(^|\s)#([A-Za-z0-9][A-Za-z0-9_-]*)/g,(c,d,u)=>{const f=i.get(u.toLowerCase());return f!==void 0?`${d}${f}`:c})},getSnippetByName:n=>t().snippets.find(r=>r.name===n)}),{name:"snippets-store"})),iW=Object.freeze(Object.defineProperty({__proto__:null,invalidateSnippetsLoadCache:fT,useSnippetsStore:Cr},Symbol.toStringTag,{value:"Module"}));function lx(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 hT=["drawio","dio"];function cx(e){const t=e.split(".").pop()?.toLowerCase();return hT.includes(t||"")}const dx=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function aW(e){const t=e.split(".").pop()?.toLowerCase();return dx.includes(t||"")}function lW(e){return e.split(".").pop()?.toLowerCase()==="pdf"}function pT(e){return e.toLowerCase().endsWith(".svg")}const mT=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",...dx.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 gT(e){const t=e.split(/[/\\]/).pop()??e,n=t.lastIndexOf(".");return n<=0||n===t.length-1?"":t.slice(n+1).toLowerCase()}function cW(e){if(pT(e))return!1;const t=gT(e);return mT.has(t)}function dW(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 uW(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 yT={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 vT(e){return e.trim().replace(/[_-]+/g," ").replace(/\s+/g," ").replace(/^./,t=>t.toUpperCase())}function va(e){return yT[e]||{displayName:vT(e),category:"system",outputLanguage:"text",inputFields:[]}}function xT(e,t,n){const r=va(e);if(r.outputLanguage==="auto"){if(n?.filePath||n?.file_path||n?.sourcePath){const s=n.filePath||n.file_path||n.sourcePath,o=lx(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 bT(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}
66
- ${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(`
67
- `):String(e)}const ux="p-1.5 max-w-[260px] overflow-hidden rounded-xl bg-popover/95 border border-border shadow-lg";function fx({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 em=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"]),Ch="oc-file-type-icon-sprite-root",D2="http://www.w3.org/2000/svg";let tm=null,ri=null,Bi=null;const jc=new Set,$i=new Set;let hx=0;const kh=new Set,O2=()=>hx,wT=e=>(kh.add(e),()=>{kh.delete(e)}),ST=()=>{hx+=1;for(const e of Array.from(kh))e()},CT=()=>mt(()=>import("./sprite-HGQGInUp.js"),[]);let kT=CT;const MT=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},px=()=>{if(typeof document>"u"||!document.body)return null;const e=document.getElementById(Ch),t=e?.querySelector("defs");if(t)return t;e?.remove(),jc.clear();const n=document.createElement("div");n.id=Ch,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(D2,"svg");r.setAttribute("width","0"),r.setAttribute("height","0");const s=document.createElementNS(D2,"defs");return r.appendChild(s),n.appendChild(r),document.body.appendChild(n),s},IT=()=>typeof document>"u"||!document.body?!1:!!document.getElementById(Ch)?.querySelector("defs"),nm=e=>{const t=px();if(!t||jc.has(e)||!Bi)return;const n=Bi.get(e);if(n){jc.add(e),t.insertAdjacentHTML("beforeend",n);for(const r of n.matchAll(/href="#([^"]+)"/g))Bi.has(r[1])&&nm(r[1])}},_T=e=>{if(!(jc.has(e)&&IT())){if(tm===null||Bi===null){$i.add(e),mx().catch(()=>{});return}$i.delete(e),nm(e)}},ET=e=>{if(tm=e,Bi=MT(e),$i.size>0&&px()!==null){const t=Array.from($i);$i.clear();for(const n of t)nm(n)}ST()},mx=()=>tm!==null?Promise.resolve():(ri||(ri=kT().then(e=>{ri=null,ET(typeof e=="string"?e:e.default)},()=>{throw ri=null,new Error("file-type sprite failed to load")})),ri),jT=()=>{if(typeof window>"u"||typeof document>"u")return;const e=()=>{mx().catch(()=>{})};if(typeof window.requestIdleCallback=="function"){window.requestIdleCallback(()=>e());return}window.setTimeout(e,0)};jT();const H2={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"},F2={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"},V2={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"},Tc="document",TT=(e,t)=>{if(!e)return t==="light"?`${Tc}_light`:Tc;if(t==="light"){const n=e.endsWith("_light")?e:`${e}_light`;return em.has(n)?n:e}return e},AT=e=>typeof e=="string"&&e.trim().length>0,LT=(e,t)=>{const r=e.replace(/\\/g,"/").split("/").pop()?.toLowerCase()||"";if(H2[r])return H2[r];if(r.startsWith(".env"))return"settings";const s=lx(e);if(s&&F2[s])return F2[s];const o=AT(t)?t.toLowerCase():r.includes(".")&&r.split(".").pop()?.toLowerCase()||"";return o&&V2[o]?V2[o]:o&&em.has(o)?o:Tc},NT=(e,t)=>{const n=LT(e,t?.extension),r=em.has(n)?n:Tc,s=TT(r,t?.themeVariant);return _T(s),`#${s}`},rr=({filePath:e,extension:t,className:n})=>{const r=w3(),s=z.useSyncExternalStore(wT,O2,O2),o=r?.currentTheme.metadata.variant==="light"?"light":"dark",i=NT(e,{extension:t,themeVariant:o});return l.jsx("svg",{className:R("block h-4 w-4 flex-shrink-0",n),"aria-hidden":"true",focusable:"false",children:l.jsx("use",{href:i,xlinkHref:i},s)})},RT=e=>e===null?null:Math.min(100,Math.max(0,e));function PT({filename:e,progress:t}){const n=RT(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 DT=z.memo(()=>{const e=z.useRef(null),t=Ge(a=>a.addAttachedFile),n=se(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),Ne.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(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx("button",{type:"button",onClick:()=>e.current?.click(),className:R("flex items-center justify-center rounded-lg transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring","hover:bg-muted text-muted-foreground",r),"aria-label":"Attach files",children:l.jsx(V,{name:"attachment-2",className:s})})}),l.jsx(pt,{side:"top",children:l.jsx("p",{children:"Attach files"})})]})]})});DT.displayName="FileAttachmentButton";const OT=e=>!Number.isFinite(e)||e<=0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,HT=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},gx=z.memo(({file:e,onRemove:t,onRetry:n,onShowPopup:r,gallery:s,galleryIndex:o})=>{const{isMobile:i,isTablet:a}=Rr(),c=i||a,d=e.uploadState,u=d?.status==="ready"&&d.expiresAt<=Date.now(),f=e.mimeType.startsWith("image/"),p=f&&e.previewUrl?e.previewUrl:f&&e.dataUrl.startsWith("data:image/")?e.dataUrl:f&&e.serverPath||"",m=HT(e.filename),g=OT(e.size),y=d?.status==="preparing"?"Preparing attachment":d?.status==="uploading"?"Uploading attachment":d?.status==="failed"||u?"Attachment upload failed":d?.status==="ready"?"Attachment ready":"Server attachment ready",b=d?.status==="uploading"?d.progress:null,k=d?.status==="uploading"||d?.status==="preparing",v=d?.status==="failed"?d.error:u?"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:R("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:y}),l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsxs("div",{role:p&&r?"button":void 0,tabIndex:p&&r?0:void 0,onClick:x,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),x())},className:R("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:[k?l.jsx(PT,{filename:e.filename,progress:b}):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(pt,{side:"top",className:R(p&&!v?ux:void 0),children:v?l.jsx("p",{children:v}):l.jsx(fx,{imageUrl:p||void 0,filename:e.filename,metaLine:p?[m.toUpperCase(),g].filter(Boolean).join(" · "):g})})]}),k?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(Ee,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),t()},className:R("absolute right-1 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",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(V,{name:"close",className:"size-3.5"})}),v?l.jsx(Ee,{variant:"ghost",size:"xs",onClick:C=>{C.stopPropagation(),n()},className:R("absolute right-8 top-1 size-6 px-0 bg-[var(--surface-elevated)]/90 z-10",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(V,{name:"refresh",className:"size-3.5"})}):null]})});gx.displayName="DraftAttachmentCard";const yx=z.memo(({onShowPopup:e,className:t,isInline:n=!1,isMobile:r=!1})=>{const s=Ge(p=>p.attachedFiles),o=Ge(p=>p.removeAttachedFile),i=Ge(p=>p.retryAttachmentUpload),[,a]=h.useState(0);if(h.useEffect(()=>{const p=s.reduce((g,y)=>y.uploadState?.status!=="ready"||y.uploadState.expiresAt<=Date.now()?g:g===null?y.uploadState.expiresAt:Math.min(g,y.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}}]:[]}),u=d.map(p=>p.image),f=new Map(d.map((p,m)=>[p.file.id,m]));return l.jsx("div",{className:R("grid w-full gap-2 grid-cols-2 sm:grid-cols-3",n?"px-1.5 pt-1.5 pb-1":r?"px-3 pt-2.5 pb-1.5":"px-3 pt-3 pb-1.5",t),"data-no-drawer-swipe":"true",children:s.map(p=>l.jsx(gx,{file:p,onRemove:()=>o(p.id),onRetry:()=>i(p.id),onShowPopup:e,gallery:u,galleryIndex:f.get(p.id)??0},p.id))})});yx.displayName="AttachedFilesList";const FT="application/vnd.github.issue-link",VT="application/vnd.github.pull-request-link",nf=e=>e.mime===FT?"issue":e.mime===VT?"pr":null,rm=z.memo(({files:e,onShowPopup:t,compact:n=!1})=>{const r=e.filter(f=>f.type==="file"&&(f.mime||f.url)),s=f=>{if(!f)return"Unnamed file";const m=f.replace(/\\/g,"/").split("/");return m[m.length-1]||f},o=h.useCallback(f=>nf(f)!==null&&typeof f.filename=="string"&&f.filename.trim().length>0?f.filename.trim():s(f.filename||f.url),[]),i=f=>!f||!Number.isFinite(f)||f<=0?"":f<1024?`${f} B`:f<1024*1024?`${(f/1024).toFixed(1)} KB`:`${(f/(1024*1024)).toFixed(1)} MB`,a=r.filter(f=>f.mime?.startsWith("image/")&&f.url),c=r.filter(f=>!f.mime?.startsWith("image/")),d=h.useMemo(()=>a.flatMap(f=>{if(!f.url)return[];const p=o(f)||"Image";return[{url:f.url,mimeType:f.mime,filename:p,size:f.size}]}),[a,o]),u=h.useCallback(f=>{if(!t)return;const p=d[f];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:f}})},[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((f,p)=>{const m=o(f),g=m.split(".").pop()||"",y=i(f.size),b=nf(f);return l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:b&&f.url?l.jsxs("button",{type:"button",onClick:()=>{ph(f.url||"")},className:"inline-flex items-center bg-muted/30 border border-border/30 typography-meta gap-1 px-2 py-0.5 rounded-lg text-foreground hover:text-primary transition-colors",children:[b==="pr"?l.jsx(V,{name:"git-pull-request",className:"text-muted-foreground h-3.5 w-3.5"}):l.jsx(V,{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:[f.mime?.includes("pdf")?l.jsx(V,{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(pt,{children:l.jsxs("p",{children:[m,y?` (${y})`:""]})})]},`file-${f.url||f.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((f,p)=>{const m=o(f)||"Image";return l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>u(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:[f.url?l.jsx("img",{src:f.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:g=>{const y=g.target;y.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(V,{name:"file-image",className:"h-6 w-6"})}),l.jsx("span",{className:"sr-only",children:m})]})}),l.jsx(pt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${f.url||f.filename||p}`)})})})]}):l.jsx("div",{className:R("grid gap-2",n?"grid-cols-1":"grid-cols-1 sm:grid-cols-2"),children:r.map((f,p)=>{const m=o(f),g=f.mime?.startsWith("image/"),y=i(f.size),b=nf(f);if(g&&f.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:f.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}),y&&l.jsx("p",{className:"text-xs opacity-80",children:y})]})]},f.url||`${m}-${p}`);if(b&&f.url)return l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>{ph(f.url||"")},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[l.jsx("div",{className:"flex-shrink-0",children:b==="pr"?l.jsx(V,{name:"git-pull-request",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):l.jsx(V,{name:"github",className:R("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}),y&&l.jsx("p",{className:"text-xs text-muted-foreground",children:y})]})]})}),l.jsx(pt,{children:l.jsxs("p",{children:[m,y?` (${y})`:""]})})]},f.url||`${m}-${p}`);const k=f.source,v=typeof k?.type=="string"?k.type:void 0,x=k&&typeof k.path=="string"?k.path:void 0,C=v==="file"&&x?x:f.url||"";return C&&cx(C)?l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>{se.getState().navigateToDiagram(C)},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left cursor-pointer",n?"text-xs":"text-sm"),children:[l.jsx(V,{name:"file",className:R("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(V,{name:"external-link",className:R("text-muted-foreground shrink-0",n?"h-3 w-3":"h-3.5 w-3.5")})]})}),l.jsx(pt,{children:l.jsx("p",{children:"Open in diagram view"})})]},f.url||`${m}-${p}`):l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:()=>{t&&f.url&&t({open:!0,title:m,content:"",image:{url:f.url,mimeType:f.mime,filename:m}})},className:R("flex items-center gap-2 p-2 rounded-lg border border-border/40 bg-muted/10 hover:bg-muted/20 transition-colors text-left",n?"text-xs":"text-sm"),children:[l.jsx("div",{className:"flex-shrink-0",children:f.mime?.startsWith("image/")?l.jsx(V,{name:"file-image",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):f.mime?.includes("pdf")?l.jsx(V,{name:"file-pdf",className:R("text-muted-foreground",n?"h-3.5 w-3.5":"h-4 w-4")}):l.jsx(V,{name:"file",className:R("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}),y&&l.jsx("p",{className:"text-xs text-muted-foreground",children:y})]})]})}),l.jsx(pt,{children:l.jsxs("p",{children:[m,y?` (${y})`:""]})})]},f.url||`${m}-${p}`)})})});rm.displayName="MessageFilesDisplay";const BT=z.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:R("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})]})});BT.displayName="ImageGallery";const vx=z.memo(({message:e,target:t,sending:n,checking:r,onEdit:s,onSend:o,onCheck:i})=>{const a=lt(x=>x.removeFromQueue),{attributes:c,listeners:d,setNodeRef:u,transform:f,transition:p,isDragging:m}=dp({id:e.id}),g=h.useMemo(()=>{const x=e.content.split(`
68
- `),C=x[0]||"",S=100;return C.length>S?C.substring(0,S)+"...":C+(x.length>1?"...":"")},[e.content]),y=e.attachments?.length??0,b=e.deliveryAttempt!==void 0,k=e.sendFailed===!0,v=n||r;return l.jsxs("div",{ref:u,style:{transform:up.Translate.toString(f),transition:p},className:R("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(V,{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)",y>0&&l.jsx("span",{className:"ml-1 text-muted-foreground",children:y===1?"+1 file":`+${y} files`})]}),l.jsxs(Ee,{type:"button",variant:"secondary",size:"xs",onClick:()=>s(e),disabled:v,children:[l.jsx(V,{name:"edit",className:"h-3 w-3","aria-hidden":"true"}),"Edit"]}),b?l.jsxs(Ee,{type:"button",variant:"secondary",size:"xs",onClick:()=>i(e),disabled:v,"aria-label":"Check delivery status",title:"Check delivery status",children:[l.jsx(V,{name:"refresh",className:"h-3 w-3","aria-hidden":"true"}),"Check status"]}):l.jsxs(Ee,{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(V,{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(V,{name:"close",className:"h-4 w-4 text-muted-foreground"})})]}),(n||r||k||b)&&l.jsx("p",{className:R("typography-micro pl-6",k&&!n&&!r?"text-[var(--status-error)]":b&&!n&&!r?"text-[var(--status-warning)]":"text-muted-foreground"),role:k||b?"status":void 0,children:n?"Sending…":r?"Checking status…":k?"Send failed. Retry with Steer or remove.":"Delivery uncertain. Check status before retrying."})]})});vx.displayName="QueuedMessageChip";const B2=[],$2=[],xx=z.memo(({onEditMessage:e,onSendMessage:t})=>{const n=ve(_=>_.currentSessionId),r=ve(h.useCallback(_=>n?_.getDirectoryForSession(n):null,[n])),s=n?rp(n,r):null,o=s?T5(s):null,i=lt(h.useCallback(_=>o?_.queuedMessages[o]??B2:B2,[o])),a=lt(h.useCallback(_=>o?_.sendingIds[o]??$2:$2,[o])),c=lt(_=>_.popToInput),d=lt(_=>_.reorderQueue),[u,f]=h.useState([]),p=n?`session:${n}`:"*",m=Ke(_=>_.reducer.bySession,(_,T)=>{if(Object.is(_,T)||!n)return!0;const A=_.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,y=g?.steering??0,b=g?.followUp??0,k=y>0||b>0,v=!!s&&i.length>0,x=y===1?"1 steering message waiting":`${y} steering messages waiting`,C=b===1?"1 follow-up message waiting":`${b} follow-up messages waiting`,S=ip(Ki(P5,{activationConstraint:{distance:8}}),Ki(R5,{activationConstraint:{delay:200,tolerance:6}})),w=h.useCallback(_=>{const{active:T,over:A}=_;!A||T.id===A.id||!s||d(s,String(T.id),String(A.id))},[s,d]),M=h.useCallback(_=>{if(!s)return;const T=c(s,_.id);if(T){if(T.attachments&&T.attachments.length>0){const A=Ge.getState().attachedFiles;Ge.getState().setAttachedFiles([...A,...T.attachments])}e(T.content,T.attachments)}},[s,c,e]),I=h.useCallback(_=>{t(_.id)},[t]),E=h.useCallback(async _=>{if(!s||!o||u.includes(_.id)||a.includes(_.id))return;const A=lt.getState().queuedMessages[o]?.find(j=>j.id===_.id)?.deliveryAttempt??_.deliveryAttempt;if(A){f(j=>j.includes(_.id)?j:[...j,_.id]);try{const j=await lj(s,A);j==="accepted"?lt.getState().completeQueuedSend(s,_.id):j==="pending"?Ne.info("Delivery still pending. Follow-ups are on hold. Check again later."):Ne.warning("Delivery status unknown. The message stays on hold. No resend attempted.")}finally{f(j=>j.filter(N=>N!==_.id))}}},[s,o,u,a]);return!v&&!k?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(V,{name:"time",className:"ml-auto h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}),l.jsx(ap,{sensors:S,collisionDetection:lp,onDragEnd:w,children:l.jsx(cp,{items:i.map(_=>_.id),strategy:D5,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(_=>l.jsx(vx,{message:_,target:s,sending:a.includes(_.id),checking:u.includes(_.id),onEdit:M,onSend:I,onCheck:E},_.id))})})})]}),k&&l.jsxs("div",{className:R("px-3 typography-micro text-muted-foreground",v?"pb-3 pt-1":"py-2"),children:[y>0&&l.jsx("p",{role:"status",children:x}),b>0&&l.jsx("p",{role:"status",children:C})]})]})})});xx.displayName="QueuedMessageChips";let rf=Date.now();const $T=()=>(rf=Math.max(rf+1,Date.now()),rf),z2=()=>!(typeof document>"u"||document.visibilityState!=="visible"||typeof document.hasFocus=="function"&&!document.hasFocus());function zT({sessionId:e,directory:t,text:n,debounceMs:r=250}){const s=Ke(m=>e?m.reducer.bySession.get(e)?.extensionDraftTracked===!0:!1,Object.is,e?`session:${e}`:"chrome"),o=s?n:null,i=z.useRef(n);i.current=n;const a=z.useRef(t);a.current=t;const c=z.useRef(e);c.current=e;const d=z.useRef(new Map),u=z.useRef(null),f=z.useRef(new Set);z.useEffect(()=>{if(!e)return;const m=f.current,g=d.current;return()=>{m.delete(e),g.delete(e)}},[e]);const p=z.useCallback((m,g)=>{if(!z2())return;d.current.set(m,g);const y=$T(),b=a.current;De.updateExtensionDraft({sessionId:m,text:g,revision:y,...b?{directory:b}:{}}).catch(()=>{d.current.get(m)===g&&d.current.delete(m)})},[]);z.useEffect(()=>{if(!e||!s)return;const m=()=>{if(!z2())return;const g=i.current,y=d.current.get(e);g!==y&&(u.current!==null&&(clearTimeout(u.current),u.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]),z.useEffect(()=>{if(!e||o===null){e&&f.current.delete(e),u.current!==null&&(clearTimeout(u.current),u.current=null);return}if(!f.current.has(e)){f.current.add(e),u.current!==null&&(clearTimeout(u.current),u.current=null),p(e,o);return}const g=d.current.get(e);if(o===g){u.current!==null&&(clearTimeout(u.current),u.current=null);return}return u.current!==null&&clearTimeout(u.current),u.current=setTimeout(()=>{u.current=null;const y=i.current,b=c.current;!b||y===d.current.get(b)||p(b,y)},r),()=>{u.current!==null&&(clearTimeout(u.current),u.current=null)}},[e,o,r,p])}const sm="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",UT="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",ZT="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",WT="bg-border -mx-1 my-0.5 h-px",Md=z.createContext(null),qT=e=>e?e.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function bx(e,t){return e&&z.isValidElement(t)?{render:t}:{children:t}}function wx({...e}){const[t,n]=z.useState(null),r=z.useMemo(()=>({portalContainer:t,setPortalContainer:n}),[t]);return l.jsx(Md.Provider,{value:r,children:l.jsx(m9,{...e})})}function Sx({asChild:e,children:t,onPointerDownCapture:n,onFocusCapture:r,...s}){const o=z.useContext(Md),i=z.useCallback(c=>{if(!o)return;const d=c instanceof HTMLElement?c:null;o.setPortalContainer(qT(d))},[o]),a=bx(e,t);return l.jsx(g9,{"data-slot":"dropdown-menu-trigger",onPointerDownCapture:c=>{i(c.currentTarget),n?.(c)},onFocusCapture:c=>{i(c.currentTarget),r?.(c)},...s,...a})}function Cx({className:e,sideOffset:t=4,align:n,side:r,alignOffset:s,portalToBody:o=!1,positionerClassName:i,style:a,children:c,onCloseAutoFocus:d,...u}){const f=z.useContext(Md);return l.jsx(O5,{container:o?void 0:f?.portalContainer||void 0,children:l.jsx(H5,{sideOffset:t,align:n,side:r,alignOffset:s,className:R("app-region-no-drag z-50",i),children:l.jsx(F5,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...a},className:R(sm,e),...u,children:c})})})}function U2({className:e,inset:t,variant:n="default",asChild:r,children:s,onSelect:o,onClick:i,...a}){const c=bx(r,s),d=u=>{i?.(u),u.defaultPrevented||o?.(u)};return l.jsx(y9,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:R(UT,e),...a,onClick:d,...c})}function fW({...e}){return l.jsx(x9,{"data-slot":"dropdown-menu-radio-group",...e})}function hW({className:e,children:t,...n}){return l.jsxs(b9,{"data-slot":"dropdown-menu-radio-item",className:R("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[checked]:bg-interactive-selection data-[checked]:text-interactive-selection-foreground relative flex cursor-pointer items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",e),...n,children:[l.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:l.jsx(w9,{children:l.jsx(V,{name:"check",className:"size-3"})})}),t]})}function pW({className:e,inset:t,...n}){return l.jsx("div",{"data-slot":"dropdown-menu-label","data-inset":t,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",e),...n})}function mW({className:e,...t}){return l.jsx(v9,{"data-slot":"dropdown-menu-separator",className:R(WT,e),...t})}function gW({...e}){return l.jsx(S9,{...e})}function yW({className:e,inset:t,children:n,...r}){return l.jsxs(C9,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:R(ZT,e),...r,children:[n,l.jsx(V,{name:"arrow-right-s",className:"ml-auto size-3.5"})]})}function vW({className:e,children:t,...n}){const r=z.useContext(Md);return l.jsx(O5,{container:r?.portalContainer||void 0,children:l.jsx(H5,{className:"z-50",children:l.jsx(F5,{"data-slot":"dropdown-menu-sub-content",style:{color:"var(--surface-elevated-foreground)"},className:R(sm,e),...n,children:t})})})}const GT="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",KT="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",YT="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",XT="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",JT="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",QT="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",eA="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",tA="/assets/kimi-for-coding-eVEHug_h.svg",nA="/assets/llmapi-detailed-Pup_107f.svg",rA="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",sA="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",oA="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",iA="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",aA="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",lA="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",cA="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",dA="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",uA="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",fA="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",hA="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",pA=Object.assign({"../assets/provider-logos/anthropic.svg":GT,"../assets/provider-logos/bailian-coding-plan.svg":KT,"../assets/provider-logos/cursor.svg":YT,"../assets/provider-logos/evroc.svg":XT,"../assets/provider-logos/github-copilot.svg":JT,"../assets/provider-logos/gocode.svg":QT,"../assets/provider-logos/google.svg":eA,"../assets/provider-logos/kimi-for-coding.svg":tA,"../assets/provider-logos/llmapi-detailed.svg":nA,"../assets/provider-logos/llmapi.svg":rA,"../assets/provider-logos/lmstudio.svg":sA,"../assets/provider-logos/minimax-cn-coding-plan.svg":oA,"../assets/provider-logos/minimax-coding-plan.svg":iA,"../assets/provider-logos/nano-gpt.svg":aA,"../assets/provider-logos/ollama.svg":lA,"../assets/provider-logos/openai.svg":cA,"../assets/provider-logos/openrouter.svg":dA,"../assets/provider-logos/wafer.ai.svg":uA,"../assets/provider-logos/zai-coding-plan.svg":fA,"../assets/provider-logos/zhipuai-coding-plan.svg":hA}),Mh=new Map,sf=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"]]),mA=e=>(e??"").toLowerCase().trim().replace(/^models\./,"").replace(/^provider\./,"").replace(/\s+/g,"-"),gA=e=>{const t=mA(e);if(!t)return[];const n=t.replace(/[^a-z0-9_\-./:]/g,""),r=n.split(/[/:]/)[0]||n,s=r.split(/[-_.]/)[0]||r,o=[sf.get(n),sf.get(r),sf.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(pA)){const n=e.match(/provider-logos\/([^/]+)\.svg$/i);n?.[1]&&t&&Mh.set(n[1].toLowerCase(),t)}function om(e){const t=gA(e),n=t.find(d=>Mh.has(d))??null,r=t[0]??null,s=!!n,o=n?Mh.get(n)??null:null,[i,a]=z.useState(s?"local":"remote");z.useEffect(()=>{a(s?"local":"remote")},[s,n,r]);const c=z.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 Co=({providerId:e,alt:t,className:n,onError:r})=>{const{src:s,onError:o,hasLogo:i}=om(e),a=h.useCallback(()=>{o(),r?.()},[o,r]);return!i||!s?null:l.jsx("img",{src:s,alt:t||`${e} logo`,className:R("dark:invert object-contain",n),loading:"eager",decoding:"async",fetchPriority:"high",draggable:!1,onError:a})},Z2=Et()(Yc(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})),W2=(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=W2(t.limit,"context"),s=W2(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}:{}}}},ls=e=>typeof e=="string"?e.trim():"",q2=(e,t)=>!t||t<=0||e.length<=t?e:t<=3?e.slice(0,t):`${e.slice(0,t-3)}...`,yA={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"},G2=e=>e?e[0].toUpperCase()+e.slice(1).toLowerCase():"",vA=e=>{const t=e.startsWith("~")?e.slice(1):e,n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t},xA=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)}},bA=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},wA=e=>{const t=e.toLowerCase(),n=yA[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)?G2(t).replace(/([a-z])(\d)/i,"$1$2"):G2(e)},SA=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},CA=e=>{const t=ls(e).toLowerCase();return t?t==="free"||t==="thinking"?t:kx(t):""},kx=e=>{const t=ls(e);if(!t)return"";const{base:n,suffix:r}=xA(vA(t)),s=SA(bA(n).map(wA));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=CA(r);return a?`${i} (${a})`:i},am=(e,t,n={})=>{const r=ls(e?.name);if(r)return q2(r,n.maxLength);const s=ls(e?.id)||ls(t);return s?q2(kx(s),n.maxLength):n.fallbackLabel??""},kA=(e,t)=>{const n=e?.models;if(!(!n||!t))return Array.isArray(n)?n.find(r=>ls(r.id)===t):n[t]},lm=(e,t,n={})=>{const r=ls(t),s=kA(e,r);return am(s,r,n)},MA=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),IA=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),ec=e=>am(e,void 0,{maxLength:40}),_A=e=>{if(typeof e!="number"||Number.isNaN(e))return"";if(e===0)return"0";const t=MA(e);return t.endsWith(".0")?t.slice(0,-2):t},K2=e=>typeof e!="number"||!Number.isFinite(e)?"—":IA(e),EA=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,jA=({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]),!EA(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(ft,{delayDuration:0,open:t&&s,onOpenChange:()=>{},children:[l.jsx(ht,{asChild:!0,children:r}),t&&s?l.jsxs(pt,{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:[K2(e?.cost?.input)," / ",K2(e?.cost?.output)]})]}):null]}):null]})},TA=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)})}),AA=({id:e,disabled:t=!1,children:n})=>{const{attributes:r,listeners:s,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:c,isDragging:d}=dp({id:e,disabled:t});return l.jsx("div",{ref:o,style:{transform:up.Transform.toString(a),transition:c},className:R(d&&"opacity-60"),children:n({attributes:r,listeners:s,setActivatorNodeRef:i,isDragging:d})})},LA=({entry:e,keyPrefix:t,showProviderLogo:n,rowIndex:r,dragHandleProps:s,selectionStore:o,modelsMetadata:i,selectedModel:a,disabled:c=!1,rowClassName:d,renderVersion:u,tooltipsEnabled:f=!0,labels:p,selectionCount:m,isFavorite:g,onToggleFavorite:y,onSelect:b,selectIndex:k,itemRefs:v,lastMousePositionRef:x,keyboardOwnsSelectionRef:C,reorderFavoriteAriaLabel:S,reorderFavoriteTitle:w,renderRowEnd:M})=>{const I=im(e.providerID,e.model,i.get(`${e.providerID}/${e.modelID}`)),E=_A(I?.limit?.context),_=m?.(e)??0,T=a?.providerID===e.providerID&&a.modelID===e.modelID,A=g?.(e)??!1,j=N=>{const O={x:N.clientX,y:N.clientY},L=x.current,P=!L||L.x!==O.x||L.y!==O.y;x.current=O,!(C.current&&!L)&&(C.current&&!P||(C.current&&P&&(C.current=!1),k(r)))};return l.jsx(TA,{store:o,index:r,renderVersion:u,children:N=>{const O=l.jsxs("div",{ref:L=>{v.current[r]=L},role:"option","aria-selected":T,"aria-disabled":c||void 0,tabIndex:-1,onClick:()=>{c||b(e)},onKeyDown:L=>{c||(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),b(e))},onMouseEnter:j,onMouseMove:j,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!c&&(N?"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:L=>{L.preventDefault(),L.stopPropagation()},className:"model-favorite-drag-handle flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground hover:text-foreground disabled:pointer-events-none","aria-label":S,title:w,children:l.jsx(V,{name:"draggable",className:"size-3.5"})}):null,n?l.jsx(Co,{providerId:e.providerID,className:"h-3.5 w-3.5 flex-shrink-0"}):null,l.jsx("span",{className:"font-medium truncate",children:ec(e.model)}),E?l.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:E}):null]}),_>0?l.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["x",_]}):null,M?.(e,{isHighlighted:N,isSelected:T}),T?l.jsx(V,{name:"check",className:"h-4 w-4 text-primary flex-shrink-0"}):null,y?l.jsx("button",{type:"button",disabled:c,onClick:L=>{L.preventDefault(),L.stopPropagation(),y(e)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-primary/80 flex-shrink-0 disabled:pointer-events-none",A?"text-primary":"text-muted-foreground"),"aria-label":A?p.unfavorite:p.favorite,title:A?p.unfavorite:p.favorite,children:l.jsx(V,{name:A?"star-fill":"star",className:"h-3.5 w-3.5"})}):null]});return l.jsx(jA,{metadata:I,active:f&&N,labels:p,children:O})}},`${t}-${e.providerID}-${e.modelID}`)},NA=(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()}}},RA=48,PA=32,DA=24;function OA({providers:e,favoriteModels:t,recentModels:n,searchQuery:r,hiddenModels:s=[],allowedProviderIds:o,isModelAllowed:i,stickyHeaders:a=!0,scrollRef:c,collapsedSections:d}){const u=h.useRef(0),f=h.useMemo(()=>o?new Set(o):null,[o]),p=h.useMemo(()=>new Map(e.map(M=>[M.id,M])),[e]),m=h.useCallback((M,I)=>s.some(E=>E.providerID===M&&E.modelID===I),[s]),g=h.useCallback((M,I)=>{const E=r.trim().toLowerCase();return E?M.toLowerCase().includes(E)||I.toLowerCase().includes(E):!0},[r]),y=h.useMemo(()=>t.filter(({model:M,providerID:I,modelID:E})=>{if(f&&!f.has(I)||i&&!i(I,E)||m(I,E))return!1;const _=p.get(I)?.name||I;return g(ec(M),_)}),[f,t,m,i,g,p]),b=h.useMemo(()=>n.filter(({model:M,providerID:I,modelID:E})=>{if(f&&!f.has(I)||i&&!i(I,E)||m(I,E))return!1;const _=p.get(I)?.name||I;return g(ec(M),_)}),[f,m,i,g,p,n]),k=h.useMemo(()=>e.filter(M=>!f||f.has(M.id)).map(M=>{const E=(Array.isArray(M.models)?M.models:[]).filter(_=>{const T=typeof _.id=="string"?_.id:"";return!T||m(M.id,T)||i&&!i(M.id,T)?!1:g(ec(_),M.name||M.id)});return{...M,models:E}}).filter(M=>M.models.length>0),[f,m,i,g,e]),v=h.useMemo(()=>[...y.length>0?["favorites"]:[],...b.length>0?["recent"]:[],...k.map(M=>`provider:${M.id}`)],[y.length,k,b.length]),x=h.useCallback(M=>{const E=M.scrollTop>1?Math.min(PA+M.scrollTop,RA):0;u.current=E,M.style.setProperty("--scroll-shadow-top-size",`${E}px`),M.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(E-8,0),DA)}px`)},[]),C=h.useCallback(M=>{M.target.closest("[data-overlay-scrollbar-thumb], [data-model-picker-sticky-header]")||M.clientY-M.currentTarget.getBoundingClientRect().top>=u.current||(M.preventDefault(),M.stopPropagation())},[]);h.useLayoutEffect(()=>{a&&c.current&&x(c.current)},[c,a,x,v]);const S=h.useMemo(()=>{const M=[];return d.has("favorites")||y.forEach(I=>M.push(I)),d.has("recent")||b.forEach(I=>M.push(I)),k.forEach(I=>{d.has(`provider:${I.id}`)||I.models.forEach(E=>M.push({model:E,providerID:I.id,modelID:E.id}))}),M},[d,y,k,b]),w=h.useMemo(()=>new Map(y.map(M=>[`${M.providerID}:${M.modelID}`,M])),[y]);return{allowedProviderSet:f,providerById:p,filteredFavorites:y,filteredRecents:b,filteredProviders:k,visibleSectionKeys:v,flatModelList:S,favoriteLookup:w,syncStickyFade:x,blockStickyFadeInteraction:C}}const Y2=32,HA=(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+Y2,d=s<c?s-Y2:o>a?o-e.clientHeight:i,u=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.max(0,Math.min(d,u))},FA=({providers:e,favoriteModels:t,recentModels:n,modelsMetadata:r,searchQuery:s,onSearchQueryChange:o,onSelect:i,labels:a,selectedModel:c,hiddenModels:d=[],allowedProviderIds:u,isModelAllowed:f,includeNotSelected:p=!1,onSelectNone:m,selectionCount:g,disabled:y=!1,maxHeightClassName:b="max-h-[min(400px,calc(100dvh-12rem))] flex-1",maxHeightStyle:k,sectionHeaderClassName:v,rowClassName:x,stickyHeaders:C=!0,autoFocus:S=!0,onEscape:w,isFavorite:M,onToggleFavorite:I,renderRowEnd:E,onActiveKeyDown:_,onActiveEntryChange:T,onVariantKey:A,onReorderFavorite:j,reorderFavoriteAriaLabel:N,reorderFavoriteTitle:O,renderVersion:L,tooltipsEnabled:P=!0})=>{const W=h.useRef(null);W.current||(W.current=NA());const F=W.current,q=h.useRef([]),K=h.useRef(null),Q=h.useRef(!1),D=h.useRef(null),U=Z2(we=>we.collapsedSections),Y=Z2(we=>we.toggleSection),ne=h.useMemo(()=>new Set(Object.keys(U).filter(we=>U[we])),[U]),$=ip(Ki(k9,{activationConstraint:{distance:8}})),{filteredFavorites:J,filteredRecents:G,filteredProviders:ue,flatModelList:B,favoriteLookup:ie,syncStickyFade:xe,blockStickyFadeInteraction:de}=OA({providers:e,favoriteModels:t,recentModels:n,searchQuery:s,hiddenModels:d,allowedProviderIds:u,isModelAllowed:f,stickyHeaders:C,scrollRef:K,collapsedSections:ne}),Se=B.length>0,je=!!j&&s.trim().length===0&&J.length>1;h.useEffect(()=>{F.set(0)},[s,F]);const Oe=h.useCallback(we=>{F.set(we),T?.(B[we])},[B,T,F]),Be=h.useCallback(we=>{const re=B.length;if(re===0)return;Q.current=!0,D.current=null;const pe=(F.getSnapshot()+we+re)%re;F.set(pe),T?.(B[pe]),requestAnimationFrame(()=>HA(K.current,q.current[pe]))},[B,T,F]);h.useEffect(()=>{T?.(B[F.getSnapshot()])},[B,T,F]);const Ie=h.useCallback(we=>{if(!we.defaultPrevented){if(we.stopPropagation(),we.key==="ArrowLeft"||we.key==="ArrowRight"){const re=B[F.getSnapshot()];if(re&&A?.(we,re))return}if(_?.(we,B[F.getSnapshot()]),!we.defaultPrevented){if(we.key==="ArrowDown"){we.preventDefault(),Be(1);return}if(we.key==="ArrowUp"){we.preventDefault(),Be(-1);return}if(we.key==="Enter"){we.preventDefault();const re=B[F.getSnapshot()];re&&!y&&i(re);return}we.key==="Escape"&&(we.preventDefault(),w?.())}}},[y,B,Be,_,w,i,A,F]),fe=R("typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 px-2 py-1.5",C&&"sticky top-0 z-20",v);let ee=0;const he=(we,re,ge,pe,ke)=>l.jsx(LA,{entry:we,keyPrefix:re,showProviderLogo:ge,rowIndex:pe,dragHandleProps:ke,selectionStore:F,modelsMetadata:r,selectedModel:c,disabled:y,rowClassName:x,renderVersion:L,tooltipsEnabled:P,labels:a,selectionCount:g,isFavorite:M,onToggleFavorite:I,onSelect:i,selectIndex:Oe,itemRefs:q,lastMousePositionRef:D,keyboardOwnsSelectionRef:Q,reorderFavoriteAriaLabel:N,reorderFavoriteTitle:O,renderRowEnd:E},`${re}-${we.providerID}-${we.modelID}`),Ce=we=>{if(!j)return;const{active:re,over:ge}=we;if(!ge||re.id===ge.id)return;const pe=ie.get(String(re.id)),ke=ie.get(String(ge.id));!pe||!ke||j(pe,ke)},Ae=we=>ne.has(we),Me=we=>Y(we),Ze=(we,re,ge)=>{const pe=Ae(we),ke=_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),Me(we))};return l.jsxs("button",{type:"button","aria-expanded":!pe,"data-model-picker-sticky-header":C?"true":void 0,className:R(fe,"w-full text-left"),onClick:()=>Me(we),onKeyDown:ke,children:[re,l.jsx("span",{className:"min-w-0 truncate",children:ge}),l.jsx("span",{className:"ml-auto flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",children:l.jsx(V,{name:pe?"arrow-right-s":"arrow-down-s",className:"size-4"})})]})},gt=()=>ue.map(we=>{const re=Ae(`provider:${we.id}`);return l.jsxs("div",{className:"relative overflow-hidden",children:[Ze(`provider:${we.id}`,l.jsx(Co,{providerId:we.id,className:"h-3.5 w-3.5 flex-shrink-0"}),we.name||we.id),re?null:l.jsx("div",{className:"space-y-0.5 mt-0.5",children:we.models.map(ge=>{const pe={model:ge,providerID:we.id,modelID:ge.id},ke=ee;return ee+=1,he(pe,we.id,!1,ke)})})]},we.id)});return l.jsxs("div",{className:"flex flex-col min-h-0",children:[l.jsx("div",{className:"p-2 border-b",children:l.jsx(Ar,{placeholder:a.searchPlaceholder,value:s,onChange:we=>o(we.target.value),onKeyDown:Ie,autoFocus:S,className:"h-8 typography-meta"})}),l.jsx("div",{className:"relative flex flex-col min-h-0",onMouseDown:de,onPointerDown:de,children:l.jsxs(Hn,{ref:K,className:R(b,"p-2 space-y-3 min-h-0"),style:k,onScroll:we=>{C&&xe(we.currentTarget)},children:[p&&m?l.jsx("div",{className:"pb-1 border-b mb-1",children:l.jsxs("button",{type:"button",disabled:y,onClick:m,className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta flex items-center gap-2 cursor-pointer",!y&&"hover:bg-interactive-hover/50",y&&"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(V,{name:"check",className:"h-4 w-4 text-primary ml-auto flex-shrink-0"})]})}):null,J.length>0?l.jsxs("div",{className:"relative overflow-hidden",children:[Ze("favorites",l.jsx(V,{name:"star-fill",className:"h-3.5 w-3.5 text-primary flex-shrink-0"}),a.favorites),Ae("favorites")?null:je?l.jsx(ap,{sensors:$,collisionDetection:lp,onDragEnd:Ce,children:l.jsx(cp,{items:J.map(we=>`${we.providerID}:${we.modelID}`),strategy:D5,children:l.jsx("div",{className:"space-y-0.5 mt-0.5",children:J.map(we=>{const re=`${we.providerID}:${we.modelID}`,ge=ee;return ee+=1,l.jsx(AA,{id:re,disabled:y,children:pe=>he(we,"favorite",!0,ge,pe)},`favorite-${re}`)})})})}):l.jsx("div",{className:"space-y-0.5 mt-0.5",children:J.map(we=>{const re=ee;return ee+=1,he(we,"favorite",!0,re)})})]}):null,G.length>0?l.jsxs("div",{className:"relative overflow-hidden",children:[Ze("recent",l.jsx(V,{name:"history",className:"h-3.5 w-3.5 flex-shrink-0"}),a.recent),Ae("recent")?null:l.jsx("div",{className:"space-y-0.5 mt-0.5",children:G.map(we=>{const re=ee;return ee+=1,he(we,"recent",!0,re)})})]}):null,gt(),Se?null:l.jsx("div",{className:"p-4 text-center typography-meta text-muted-foreground",children:a.noResults})]})})]})};function Mx(){const e=Je();return z.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 VA=()=>{const e=qe(a=>a.providers),t=se(a=>a.favoriteModels),n=se(a=>a.recentModels),r=se(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 f=(Array.isArray(d.models)?d.models:[]).find(p=>p.id===c);return!f||s(a,c)?null:{provider:d,model:f,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 f=(Array.isArray(d.models)?d.models:[]).find(p=>p.id===c);return!f||s(a,c)?null:{provider:d,model:f,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}},BA=typeof window<"u"?h.useLayoutEffect:h.useEffect,$A=(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 BA(()=>{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},cm=(e,t)=>t?[void 0,...e]:[...e],Ix=e=>e??"default",zA=(e,t)=>t===0?50:e/t*100,yl=10,UA={side:"none",align:"none",fallbackAxisSide:"none"};function X2({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:R("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(Er(i))]},Ix(i))),l.jsxs("span",{className:"col-start-1 row-start-1 truncate",children:[n,o(t)]})]})}function ZA({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=h.useRef(null),i=cm(e,s),[a,c]=h.useState(null),[d,u]=h.useState(null),f=a!==null?a:t,p=Math.max(0,i.findIndex(j=>j===f)),m=Math.max(0,i.length-1),g=m===0?0:p/m,y=d!==null?d:g,b=Er(i[p]),k=h.useRef(null),v=h.useRef(t),x=h.useRef(i),C=h.useRef(n),S=h.useRef(r),w=h.useRef(null);h.useEffect(()=>{v.current=t},[t]),h.useEffect(()=>{x.current=i},[i]),h.useEffect(()=>{C.current=n},[n]),h.useEffect(()=>{S.current=r},[r]),h.useEffect(()=>{w.current=a},[a]),h.useEffect(()=>{a!==null&&a===t&&(c(null),u(null))},[t,a]);const M=h.useCallback(j=>{const N=o.current?.getBoundingClientRect(),O=x.current;if(!N||N.width<=0||O.length===0)return{next:O[0],clamped:0};const L=Math.min(Math.max((j-N.left)/N.width,0),1),P=C8(L,O.length);return{next:O[P],clamped:L}},[]),I=j=>{j.preventDefault();const{next:N,clamped:O}=M(j.clientX);c(N),u(O),w.current=N,k.current=j.pointerId;try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}!S.current&&N!==v.current&&C.current(N)},E=j=>{if(k.current!==j.pointerId)return;j.preventDefault();const{next:N,clamped:O}=M(j.clientX);u(O),N!==w.current&&(c(N),w.current=N,!S.current&&N!==v.current&&C.current(N))},_=j=>{if(k.current!==j.pointerId)return;const{next:N,clamped:O}=M(j.clientX),L=w.current??N,P=d??O;k.current=null;try{j.currentTarget.hasPointerCapture(j.pointerId)&&j.currentTarget.releasePointerCapture(j.pointerId)}catch{}S.current?(S.current(L),u(P)):L!==v.current&&C.current(L),S.current||(c(null),u(null))},T=j=>{k.current===j.pointerId&&(k.current=null,c(null),u(null))},A=j=>{let N=null;if((j.key==="ArrowRight"||j.key==="ArrowUp")&&(N=Math.min(m,p+1)),(j.key==="ArrowLeft"||j.key==="ArrowDown")&&(N=Math.max(0,p-1)),j.key==="Home"&&(N=0),j.key==="End"&&(N=m),N===null||N===p)return;j.preventDefault();const O=i[N];S.current?S.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":b,"data-no-drawer-swipe":"true",className:"cursor-pointer touch-none select-none px-4 py-1 outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] rounded-full",style:{touchAction:"none"},onPointerDown:I,onPointerMove:E,onPointerUp:_,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(${yl}px + (100% - ${yl*2}px) * ${y})`}}),l.jsxs("div",{ref:o,className:"absolute inset-y-0",style:{left:yl,right:yl},children:[i.map((j,N)=>{const O=zA(N,m),L=N<=p;return l.jsx("div",{"aria-hidden":"true",className:R("pointer-events-none absolute top-1/2 size-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full",L?"bg-primary-foreground/50":"bg-foreground/35"),style:{left:`${O}%`}},Ix(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(${y*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 dm({levels:e,value:t,onChange:n,onCommit:r,allowUnset:s=!0}){const o=cm(e,s);return l.jsxs("div",{className:"w-full px-4 pt-3.5 pb-2","data-no-drawer-swipe":"true",children:[l.jsx(ZA,{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:Er(o[0])}),l.jsx("span",{className:"text-right",children:Er(o[o.length-1])})]})]})}function WA({levels:e,value:t,onChange:n,compact:r,keepLabel:s=!1,onCompactOpen:o,buttonHeight:i,iconSize:a,textSize:c,isMobile:d,isDesktop:u}){const[f,p]=h.useState(!1),m=Er(t),y=!t?"text-muted-foreground":"text-foreground",b=cm(e,!0),k=d?10:void 0,v=l.jsxs("button",{type:"button",onClick:r?o:void 0,className:R("model-controls__variant-trigger flex items-center gap-1.5 min-w-0",i,"cursor-pointer hover:bg-transparent hover:opacity-70",r?"transition-opacity focus:outline-none":"transition-opacity"),"aria-label":`Thinking: ${m}`,children:[l.jsx(V,{name:"brain-ai-3",className:R(a,"flex-shrink-0",y)}),l.jsx(X2,{options:b,value:m,truncateAt:k,className:R("model-controls__variant-label",c,"font-normal",s?"min-w-max whitespace-nowrap":null,r&&d&&!s&&"max-w-[60px]",!r&&u&&"max-w-[180px]",y)})]});return r?v:l.jsxs(V5,{open:f,onOpenChange:p,children:[l.jsxs(ft,{delayDuration:600,...f?{open:!1}:{},children:[l.jsx(ht,{asChild:!0,children:l.jsx(B5,{render:v})}),l.jsx(pt,{side:"top",align:"center",children:l.jsx(X2,{options:b,value:m,prefix:"Thinking: ",className:"typography-meta"})})]}),l.jsx($5,{children:l.jsx(z5,{className:"app-region-no-drag z-50",side:"top",align:"center",sideOffset:8,collisionPadding:8,collisionAvoidance:UA,children:l.jsx(U5,{className:R(sm,"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(dm,{levels:e,value:t,onChange:n})})})})]})}function qA(){const e=qe(i=>i.isInitialized),t=qe(i=>i.connectionPhase),n=qe(i=>i.lastDisconnectReason),r=qe(i=>i.providers.length>0),s=e||r,o=!s&&n==="init_error";return{isReady:s,isLoading:!s&&!o,isUnavailable:o,connectionPhase:t}}const GA=({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"},KA=[{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}],YA={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"}},XA=e=>e.trim().toLowerCase(),Ac=(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=>XA(o)))),s=[];for(const o of r){const i=YA[o];i&&s.push({key:o,icon:i.icon,label:i.label})}return s},JA=e=>new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(e),QA=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}).format(e),eL=e=>new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(e),tL=e=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e),oa=e=>{if(typeof e!="number"||Number.isNaN(e))return"—";if(e===0)return"0";const t=JA(e);return t.endsWith(".0")?t.slice(0,-2):t},vl=e=>typeof e!="number"||!Number.isFinite(e)?"—":QA(e),_x=e=>{const t=[];for(const n of KA)n.isActive(e)&&t.push({key:n.key,icon:n.icon,label:n.label});return t},Ex=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 eL(s)}return e},jx=e=>{if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:tL(t)},ho=({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(V,{name:e,className:"size-3.5"})}),nL=({currentMetadata:e,modelDisplayName:t,providerDisplayName:n,currentCapabilityIcons:r,inputModalityIcons:s,outputModalityIcons:o,costRows:i,limitRows:a})=>l.jsx(pt,{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:u})=>l.jsx(ho,{iconName:d,label:u},`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:u})=>l.jsx(ho,{iconName:d,label:`${u} 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:u})=>l.jsx(ho,{iconName:d,label:`${u} 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:Ex(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:jx(e.release_date)})]})]})]}):l.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),rL=({open:e,onClose:t,title:n,providerDisplayName:r,currentCapabilityIcons:s,inputModalityIcons:o,outputModalityIcons:i,currentMetadata:a})=>e?l.jsx(sa,{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:u})=>l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(ho,{iconName:d,label:u},`cap-${c}`),l.jsx("span",{className:"typography-meta text-foreground",children:u})]},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:u})=>l.jsx(ho,{iconName:d,label:`${u} 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:u})=>l.jsx(ho,{iconName:d,label:`${u} 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:oa(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:oa(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:Ex(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:jx(a?.release_date)})]})]})]})]})}):null,sL=({open:e,onClose:t,targetVariants:n,selectedVariant:r,onVariantLiveChange:s,onVariantCommit:o})=>!e||n.length===0?null:l.jsx(sa,{open:!0,onClose:t,title:"Thinking",children:l.jsx(dm,{levels:n,value:tn(r)??void 0,onChange:s,onCommit:o})}),oL=e=>{if(!e||e.trim().length===0)return Er(void 0);const t=e.trim();return/^\d+(\.\d+)?$/.test(t)?t:Er(t)},iL=(e,t)=>`${e}:${t}`,aL=({open:e,onClose:t,mobileModelQuery:n,onMobileModelQueryChange:r,filteredFavorites:s,filteredRecents:o,filteredProviders:i,expandedMobileProviders:a,onToggleMobileProviderExpansion:c,expandedMobileModelKey:d,onToggleExpandedMobileModelKey:u,currentProviderId:f,currentModelId:p,getModelDisplayName:m,getModelMetadata:g,getModelVariantOptions:y,resolveModelVariantSelection:b,pendingThinkingVariants:k,onUpdatePendingThinkingVariant:v,isFavoriteModel:x,onToggleFavoriteModel:C,onApplyModel:S})=>{if(!e)return null;const w=n.trim(),M=s.length>0||o.length>0||i.length>0,I=({model:E,providerId:_,modelId:T,showProviderLogo:A})=>{const j=iL(_,T),N=_===f&&T===p,O=im(_,E,g(_,T)),L=y(_,T),P=L.length>0,W=b(_,T),F=k.get(j),K=k.has(j)?F:W,Q=P?oL(K):null,D=d===j,U=_x(O),Y=[...Ac(O,"input"),...Ac(O,"output")],ne=Array.from(new Map([...U,...Y].map(J=>[J.key,J])).values()),$=O?.limit?.context?`${oa(O.limit.context)} ctx`:null;return l.jsxs("div",{className:R("border-b border-border/30 last:border-b-0",N&&"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:()=>S(_,T,K),className:R("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-lg"),children: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(Co,{providerId:_,className:"size-3.5 flex-shrink-0"}):null,l.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:m(E)}),N?l.jsx(V,{name:"check",className:"size-4 flex-shrink-0 text-primary"}):null]}),$||ne.length>0?l.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden typography-micro text-muted-foreground",children:[$?l.jsx("span",{className:"whitespace-nowrap flex-shrink-0",children:$}):null,$&&ne.length>0?l.jsx("span",{"aria-hidden":"true",className:"h-3 w-px flex-shrink-0 bg-border/50"}):null,ne.length>0?l.jsx("div",{className:"flex min-w-0 items-center gap-1 overflow-hidden whitespace-nowrap pl-0.5",children:ne.map(({key:J,icon:G,label:ue})=>l.jsx("span",{className:"flex size-4 flex-shrink-0 items-center justify-center text-muted-foreground",title:ue,"aria-label":ue,children:l.jsx(V,{name:G,className:"size-3"})},`meta-${_}-${T}-${J}`))}):null]}):null]})}),P?l.jsxs("button",{type:"button",onClick:()=>u(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":D,"aria-label":D?"Hide thinking modes":"Show thinking modes",children:[l.jsx("span",{className:"whitespace-nowrap",children:Q}),D?l.jsx(V,{name:"arrow-down-s",className:"size-3.5"}):l.jsx(V,{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:J=>{J.preventDefault(),J.stopPropagation(),C(_,T)},className:R("model-favorite-button flex size-5 items-center justify-center hover:text-primary/80 flex-shrink-0",x(_,T)?"text-primary":"text-muted-foreground"),"aria-label":x(_,T)?"Unfavorite":"Favorite",title:x(_,T)?"Remove from favorites":"Add to favorites",children:x(_,T)?l.jsx(V,{name:"star-fill",className:"size-4"}):l.jsx(V,{name:"star",className:"size-4"})})})]}),D&&P?l.jsx("div",{className:"border-t border-border/30 px-1 py-1","data-no-drawer-swipe":"true",children:l.jsx(dm,{levels:L,value:tn(K)??void 0,onChange:()=>{},onCommit:J=>v(j,J)})}):null]},`mobile-model-${_}-${T}`)};return l.jsx(sa,{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(V,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground"}),l.jsx(Ar,{value:n,onChange:E=>{r(E.target.value),u(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(""),u(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(V,{name:"close-circle",className:"size-4"})})]})}),!M&&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(V,{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:_,modelID:T})=>I({model:E,providerId:_,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(V,{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:_,modelID:T})=>I({model:E,providerId:_,modelId:T,showProviderLogo:!0}))})]}),i.map(({provider:E,providerModels:_})=>{if(_.length===0)return null;const T=String(E.id||""),A=String(E.name||T),j=T===f,N=a.has(T)||w.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:()=>{w.length>0||c(T)},className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":N,children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Co,{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"})]}),N?l.jsx(V,{name:"arrow-down-s",className:"size-3 text-muted-foreground"}):l.jsx(V,{name:"arrow-right-s",className:"size-3 text-muted-foreground"})]}),N&&_.length>0&&l.jsx("div",{className:"flex flex-col border-t border-border/30",children:_.map(O=>I({model:O,providerId:String(E.id||""),modelId:String(O.id||""),showProviderLogo:!1}))})]},T)})]})})},of=(e,t)=>`${e}:${t}`,lL="__add_provider__",cL=({className:e,keepLabels:t=!1,mobilePanel:n,onMobilePanelChange:r})=>{const{isReady:s,isUnavailable:o}=qA(),i=o?"Unavailable":"Loading...",a=qe(Z=>Z.providers),c=qe(Z=>Z.currentProviderId),d=qe(Z=>Z.currentModelId),u=qe(Z=>Z.currentVariant),f=qe(Z=>Z.settingsDefaultThinking),p=qe(Z=>Z.settingsDefaultThinkingByModel),m=qe(Z=>Z.setProvider),g=qe(Z=>Z.setSelectedProvider),y=qe(Z=>Z.setModel),b=qe(Z=>Z.setCurrentVariant),k=qe(Z=>Z.getCurrentModelVariants),v=qe(Z=>Z.getCurrentProvider),x=qe(Z=>Z.getModelMetadata),C=h.useRef(!1);h.useEffect(()=>{C.current||!s||(C.current=!0,st("ModelControls:ready",{providers:a.length,currentProviderId:c,currentModelId:d}))},[d,c,s,a.length]);const S=ve(Z=>Z.currentSessionId),w=ve(Z=>Z.newSessionDraft.open),M=ve(Z=>Z.getDirectoryForSession),I=Mx(),E=_t(Z=>Z.getSessionModelSelection),_=_t(Z=>Z.saveSessionModelSelection),T=_t(Z=>Z.hasHydrated),A=se(Z=>Z.toggleFavoriteModel),j=se(Z=>Z.reorderFavoriteModel),N=se(Z=>Z.isFavoriteModel),O=se(Z=>Z.addRecentModel),L=se(Z=>Z.addRecentEffort),P=se(Z=>Z.isModelSelectorOpen),W=se(Z=>Z.setModelSelectorOpen),F=se(Z=>Z.setSettingsDialogOpen),q=se(Z=>Z.setSettingsPage),K=se(Z=>Z.hiddenModels),{favoriteModelsList:Q,recentModelsList:D}=VA(),{isMobile:U}=Rr(),{enabled:Y}=yd(),ne=se(Z=>Z.isMobile),$=(U||ne)&&!Y,J=h.useMemo(()=>xt(),[]),G=$,[ue,B]=h.useState(null),ie=n!==void 0&&typeof r=="function",xe=ie?n:ue,de=ie?r:B,[Se,je]=h.useState(null),[Oe,Be]=h.useState(""),[Ie,fe]=h.useState(null),ee=h.useRef(!1),he=h.useCallback(()=>de(null),[de]),Ce=h.useCallback(()=>je(null),[]),Ae=h.useRef(void 0),[Me,Ze]=h.useState(()=>{const Z=new Set;return c&&Z.add(c),Z}),gt=h.useCallback(()=>{g(lL),q("providers"),F(!0),W(!1),he()},[g,q,F,W,he]),[we,re]=h.useState(""),ge=h.useRef(!1),pe=h.useRef(null),ke=h.useRef(void 0),_e=h.useRef(null),[Te,be]=h.useState(new Map),[ae,te]=h.useState(new Set),[oe,me]=h.useState(0);h.useEffect(()=>{xe==="model"&&(qe.getState().ensureModelMetadata(),Ze(()=>{const Z=new Set;return c&&Z.add(c),Z}))},[xe,c]),h.useEffect(()=>{xe===null&&fe(null)},[xe]),h.useEffect(()=>{xe!=="model"&&(Be(""),fe(null),be(new Map),te(new Set))},[xe]);const Re=h.useRef(P);h.useEffect(()=>{const Z=Re.current;Re.current=P,P&&qe.getState().ensureModelMetadata(),P||(re(""),ge.current=!1,pe.current=null,be(new Map),te(new Set),Z&&!G&&requestAnimationFrame(co))},[P,G]);const We=$?"mobile":"default",ct=We==="mobile"?"h-9":"h-7",Lt="size-3.5",Ut="typography-micro",xs=We==="mobile"?"gap-x-1":"gap-x-3",Ca=v(),ka=Array.isArray(Ca?.models)?Ca.models:[],Rd=h.useMemo(()=>{const Z=[];for(const ye of a){const $e=(Array.isArray(ye.models)?ye.models:[]).filter(rt=>{const nt=typeof rt?.id=="string"?rt.id:"";return!K.some(ot=>ot.providerID===String(ye.id)&&ot.modelID===nt)});$e.length>0&&Z.push({...ye,models:$e})}return Z},[a,K]),En=h.useCallback(Z=>{const ye=Z.toLowerCase().trim(),Pe=ye.replace(/[^a-z0-9]/g,""),$e=ye.split(/[^a-z0-9]+/).filter(Boolean);return{lower:ye,compact:Pe,tokens:$e}},[]),Kt=h.useCallback((Z,ye)=>{const Pe=En(ye);if(!Pe.lower)return!0;const $e=En(Z);return $e.lower.includes(Pe.lower)||Pe.compact.length>=2&&$e.compact.includes(Pe.compact)?!0:Pe.tokens.length===0?!1:Pe.tokens.every(rt=>$e.tokens.some(nt=>nt.startsWith(rt)||nt.includes(rt)))},[En]),To=d?ka.find(Z=>Z.id===d):void 0,Nt=c&&d&&To?im(c,To,x(c,d)):c&&d?x(c,d):void 0,on=h.useCallback(Z=>Z==="Tool calling"?"Tool calling":Z==="Reasoning"?"Reasoning":Z==="Text"?"Text":Z==="Image"?"Image":Z==="Video"?"Video":Z==="Audio"?"Audio":Z==="PDF"?"PDF":Z,[]),Ao=h.useMemo(()=>_x(Nt).map(Z=>({...Z,label:on(Z.label)})),[Nt,on]),Lo=h.useMemo(()=>Ac(Nt,"input").map(Z=>({...Z,label:on(Z.label)})),[Nt,on]),No=h.useMemo(()=>Ac(Nt,"output").map(Z=>({...Z,label:on(Z.label)})),[Nt,on]),bs=k().filter(Dt),Ma=bs.length>0,Pr=[{label:"Input",value:vl(Nt?.cost?.input)},{label:"Output",value:vl(Nt?.cost?.output)},{label:"Cache read",value:vl(Nt?.cost?.cache_read)},{label:"Cache write",value:vl(Nt?.cost?.cache_write)}],jn=[{label:"Context",value:oa(Nt?.limit?.context)},{label:"Output",value:oa(Nt?.limit?.output)}],mn=h.useRef(null),ws=h.useRef(null);S&&M(S);const Ss=p3(S??""),Bt=Ke(Z=>{if(!S)return null;const ye=Z.reducer.bySession.get(S);return ye?{model:ye.model,thinking:ye.thinking}:null},(Z,ye)=>Z===ye?!0:!Z||!ye?!1:Z.model?.providerId===ye.model?.providerId&&Z.model?.modelId===ye.model?.modelId&&Z.thinking===ye.thinking,S?`session:${S}`:"*"),Cs=h.useCallback((Z,ye)=>{if(!Z||!ye)return"model-missing";const Pe=a.find(Xe=>Xe.id===Z);if(!Pe)return"provider-missing";const rt=(Array.isArray(Pe.models)?Pe.models:[]).find(Xe=>Xe.id===ye);if(!rt)return"model-missing";if(c===Z&&d===ye)return"applied";m(Z),y(ye);const Ve=Ga({providerId:Z,modelId:ye,thinkingLevels:rt.thinkingLevels,reasoning:rt.reasoning,supportsThinking:rt.supportsThinking,defaultThinkingByModel:p,defaultThinking:f,previousThinking:u});return b(Ve),S&&_(S,Z,ye),"applied"},[a,c,d,u,m,y,b,S,_,f,p]),Ht=h.useCallback((Z,ye)=>{const Pe=a.find(rt=>rt.id===Z),$e=(Array.isArray(Pe?.models)?Pe.models:[]).find(rt=>rt.id===ye);return pp($e)},[a]),Dr=h.useCallback((Z,ye,Pe)=>{if(!Z||!ye)return"model-missing";const $e=a.find(ot=>ot.id===Z);if(!$e)return"provider-missing";if(!(Array.isArray($e.models)?$e.models:[]).some(ot=>ot.id===ye))return"model-missing";c!==Z&&m(Z),(c!==Z||d!==ye)&&y(ye),S&&_(S,Z,ye);const nt=Ht(Z,ye);return b(Pe&&nt.includes(Pe)?Pe:void 0),ws.current={...Z?{providerId:Z}:{},...ye?{modelId:ye}:{},...Pe?{thinking:Pe}:{}},"applied"},[d,c,S,Ht,a,_,b,y,m]),Ia=h.useCallback((Z,ye)=>{const Pe=Ht(Z,ye);if(Pe.length!==0){if(c===Z&&d===ye&&Dt(u)&&Pe.includes(u))return u;if(!S){const $e=a.find(nt=>nt.id===Z),rt=(Array.isArray($e?.models)?$e.models:[]).find(nt=>nt.id===ye);return Ga({providerId:Z,modelId:ye,thinkingLevels:rt?.thinkingLevels,reasoning:rt?.reasoning,supportsThinking:rt?.supportsThinking,defaultThinkingByModel:p,defaultThinking:f})}}},[d,c,S,u,Ht,a,f,p]),ks=h.useCallback((Z,ye,Pe)=>{const $e=Ht(Z,ye);if($e.length===0){ee.current=!1,gi(void 0);return}const rt=Dt(Pe)&&$e.includes(Pe)?Pe:void 0;ee.current=!0,gi(rt),L(Z,ye,Pe)},[L,Ht]),_a=h.useCallback((Z,ye,Pe)=>{const $e=Cs(Z,ye);return $e!=="applied"?$e:(O(Z,ye),ks(Z,ye,Pe),"applied")},[O,ks,Cs]);h.useEffect(()=>{if(!S){mn.current=null;return}if(!T||a.length===0)return;if(!Ss){I.ensureSessionRenderable(S);return}if(mn.current===S)return;const Z=$e=>{if($e&&c&&d){const rt=Ht(c,d);b(rt.includes($e)?$e:void 0);return}b(void 0)},ye=Bt?.model;if(ye){if(Dr(ye.providerId,ye.modelId,Bt?.thinking)==="provider-missing")return;mn.current=S;return}if(Bt?.thinking){Z(Bt.thinking),mn.current=S;return}const Pe=E(S);Pe&&Dr(Pe.providerId,Pe.modelId,Bt?.thinking)==="provider-missing"||(mn.current=S)},[Dr,T,d,c,S,Bt,Ht,E,Ss,a.length,b,I]),h.useEffect(()=>{if(!S||!T||a.length===0||!Ss||mn.current!==S)return;const Z=Bt?.model,ye=Bt?.thinking??void 0;if(!Z?.providerId||!Z?.modelId){ws.current=null;return}const Pe=GA({authoritative:{providerId:Z.providerId,modelId:Z.modelId,thinking:ye},observed:ws.current,composer:{providerId:c,modelId:d,thinking:tn(u)??void 0}});if(Pe!=="ignore"){if(Pe==="apply"){Dr(Z.providerId,Z.modelId,ye);return}ws.current={providerId:Z.providerId,modelId:Z.modelId,...ye?{thinking:ye}:{}}}},[Dr,T,d,c,S,u,Bt,Ss,a.length]),h.useEffect(()=>{if(!T){ee.current=!1,b(void 0);return}if(!c||!d){ee.current=!1,b(void 0);return}const Z=a.find($e=>$e.id===c),ye=(Array.isArray(Z?.models)?Z.models:[]).find($e=>$e.id===d),Pe=hp(ye);if(!Qc(Pe)){u&&Dt(u)&&b(void 0);return}if(!S&&!u&&!ee.current){const $e=Ga({providerId:c,modelId:d,thinkingLevels:ye?.thinkingLevels,reasoning:ye?.reasoning,supportsThinking:ye?.supportsThinking,defaultThinkingByModel:p,defaultThinking:f});$e&&b($e);return}if(u&&Dt(u)&&!Pe.includes(u)){b(Ga({providerId:c,modelId:d,thinkingLevels:ye?.thinkingLevels,reasoning:ye?.reasoning,supportsThinking:ye?.supportsThinking,defaultThinkingByModel:p,defaultThinking:f,previousThinking:u}));return}if(S&&!u&&!ee.current){const $e=tn(Bt?.thinking);$e&&Pe.includes($e)&&b($e)}},[T,S,c,d,u,Bt,a,b,f,p]),h.useEffect(()=>{ee.current=!1},[c,d]);const Ro=h.useCallback(Z=>{c&&d&&ks(c,d,Z)},[ks,d,c]),ar=h.useCallback(Z=>{if(!c||!d)return;const ye=Ht(c,d);if(ye.length===0){ee.current=!1,gi(void 0);return}const Pe=Dt(Z)&&ye.includes(Z)?Z:void 0;ee.current=!0,gi(Pe)},[c,d,Ht]),gn=h.useCallback(Z=>{Z!==u&&ar(Z),c&&d&&L(c,d,Z)},[ar,c,d,u,L]),Pd=(Z,ye,Pe)=>{try{const $e=Pe?.applyVariant?_a(Z,ye,Pe.variant):Cs(Z,ye);if($e!=="applied"){$e==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",Z):$e==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:Z,modelId:ye});return}Pe?.applyVariant||O(Z,ye),W(!1),G&&he(),requestAnimationFrame(co)}catch($e){console.error("[ModelControls] Handle model change error:",$e)}},Or=(Z,ye)=>am(Z,ye,{maxLength:40}),Bn=()=>a.find(ye=>ye.id===c)?.name||c||"",Po=()=>{if(!d)return"Select model";const Z=ka.find(ye=>ye.id===d);return Or(Z,d)||"Select model"},lr=h.useCallback((Z,ye)=>!$||Z.length<=ye?Z:`${Z.slice(0,ye)}...`,[$])(Po(),16),Do=h.useRef(null),Oo=$A(Do,[lr,G]),Ea=h.useCallback(Z=>{Ze(ye=>{const Pe=new Set(ye);return Pe.has(Z)?Pe.delete(Z):Pe.add(Z),Pe})},[]),ja=h.useCallback(Z=>{Ae.current&&clearTimeout(Ae.current),Ae.current=setTimeout(()=>{je(Z)},500)},[]),Ho=h.useCallback(()=>{Ae.current&&clearTimeout(Ae.current)},[]);h.useEffect(()=>()=>{Ae.current&&clearTimeout(Ae.current)},[]);const Ta=()=>!G||Se!=="model"?null:l.jsx(rL,{open:!0,onClose:Ce,title:Nt?.name||Po(),providerDisplayName:Bn(),currentCapabilityIcons:Ao,inputModalityIcons:Lo,outputModalityIcons:No,currentMetadata:Nt}),Aa=()=>{if(!G)return null;const Z=Oe.trim(),ye=Q.filter(({model:nt,providerID:ot})=>{const Xe=a.find(Rt=>Rt.id===ot)?.name||ot,Ct=Or(nt);return Z.length===0||Kt(String(Ct||""),Z)||Kt(String(Xe||""),Z)}),Pe=D.filter(({model:nt,providerID:ot})=>{const Xe=a.find(Rt=>Rt.id===ot)?.name||ot,Ct=Or(nt);return Z.length===0||Kt(String(Ct||""),Z)||Kt(String(Xe||""),Z)}),$e=[];for(const nt of Rd){const ot=Array.isArray(nt.models)?nt.models:[],Ve=Z.length===0?!0:Kt(String(nt.name||""),Z)||Kt(String(nt.id||""),Z),Xe=Z.length===0?ot:ot.filter(Rt=>{const an=Or(Rt),An=typeof Rt.id=="string"?Rt.id:"";return Kt(String(an||""),Z)||Kt(String(An||""),Z)}),Ct=Ve&&Z.length>0?ot:Xe;(Ve||Ct.length>0)&&$e.push({provider:nt,providerModels:Ct,matchesProvider:Ve})}const rt=(nt,ot,Ve)=>{const Xe=_a(nt,ot,Ve);if(Xe!=="applied"){Xe==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",nt):Xe==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:nt,modelId:ot});return}fe(null),he(),requestAnimationFrame(co)};return l.jsx(aL,{open:xe==="model",onClose:he,mobileModelQuery:Oe,onMobileModelQueryChange:Be,filteredFavorites:ye,filteredRecents:Pe,filteredProviders:$e,expandedMobileProviders:Me,onToggleMobileProviderExpansion:Ea,expandedMobileModelKey:Ie,onToggleExpandedMobileModelKey:fe,currentProviderId:c,currentModelId:d,getModelDisplayName:Or,getModelMetadata:x,getModelVariantOptions:Ht,resolveModelVariantSelection:Ia,pendingThinkingVariants:Te,onUpdatePendingThinkingVariant:(nt,ot)=>{be(Ve=>{const Xe=new Map(Ve);return Xe.set(nt,ot),Xe}),te(Ve=>{const Xe=new Set(Ve);return Xe.add(nt),Xe}),me(Ve=>Ve+1)},isFavoriteModel:N,onToggleFavoriteModel:A,onApplyModel:rt})},La=()=>{if(!G||!c||!d)return null;const Z=Ht(c,d);return l.jsx(sL,{open:xe==="variant",onClose:he,targetVariants:Z,selectedVariant:u,onVariantLiveChange:ar,onVariantCommit:gn})},Dd=()=>l.jsx(nL,{currentMetadata:Nt,modelDisplayName:Po(),providerDisplayName:Bn(),currentCapabilityIcons:Ao,inputModalityIcons:Lo,outputModalityIcons:No,costRows:Pr,limitRows:jn}),Fo=()=>{const Z=(Ve,Xe)=>{if(ge.current=!0,Ve.key!=="ArrowLeft"&&Ve.key!=="ArrowRight")return!1;const{providerID:Ct,modelID:Rt}=Xe,an=Ht(Ct,Rt);if(an.length===0)return!1;Ve.preventDefault(),Ve.stopPropagation();const An=of(Ct,Rt),Is=Te.has(An),_s=Te.get(An),Es=Is?_s:c===Ct&&d===Rt?u:void 0,Vo=mp(an,Dt(Es)?Es:void 0,Ve.key==="ArrowRight"?1:-1);return be(Hr=>{const js=new Map(Hr);return js.set(An,Vo),js}),te(Hr=>{const js=new Set(Hr);return js.add(An),js}),me(Hr=>Hr+1),!0},ye=(Ve,Xe)=>{Xe&&Z(Ve,Xe)},Pe=Ve=>{const Xe=of(Ve.providerID,Ve.modelID),Ct=Te.get(Xe),Rt=ae.has(Xe);Pd(Ve.providerID,Ve.modelID,Rt?{applyVariant:!0,variant:Ct}:void 0)},$e=Ve=>{_e.current={category:Ve.key.length===1?"printable":Ve.key.startsWith("Arrow")||Ve.key==="Escape"||Ve.key==="Enter"?"navigation":"other",modifiers:Ve.altKey||Ve.ctrlKey||Ve.metaKey||Ve.shiftKey}},rt=(Ve,Xe)=>{if(!Ve){const Ct=document.activeElement;console.info("[DEBUG-model-picker-close]",{reason:Xe.reason??"unknown",eventType:Xe.event?.type??"none",draftOpen:w,focusInsidePicker:Ct instanceof Element&&!!Ct.closest('[data-model-picker-popup="true"]'),precedingKey:_e.current})}W(Ve)},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=(Ve,{isHighlighted:Xe,isSelected:Ct})=>{const Rt=Ht(Ve.providerID,Ve.modelID).length>0,an=of(Ve.providerID,Ve.modelID),An=ae.has(an);if(!Rt||!Xe&&!Ct)return null;const Is=Te.has(an),_s=Te.get(an),Es=Is?_s:Ct?u:void 0,Vo=Er(Dt(Es)?Es:void 0);return l.jsxs("span",{className:R("typography-micro whitespace-nowrap",An?"text-foreground":"text-muted-foreground"),children:["Thinking: ",Vo]})};return l.jsxs(ft,{delayDuration:600,children:[G?l.jsx("button",{type:"button",onClick:s?()=>de("model"):void 0,onTouchStart:s?()=>ja("model"):void 0,onTouchEnd:s?Ho:void 0,onTouchCancel:s?Ho:void 0,disabled:!s,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",s?"cursor-pointer hover:bg-transparent hover:opacity-70":"opacity-60 cursor-not-allowed",ct),children:s?l.jsxs(l.Fragment,{children:[c?l.jsx(Co,{providerId:c,className:R(Lt,"flex-shrink-0")}):l.jsx(V,{name:"pencil-ai",className:R(Lt,"text-muted-foreground")}),l.jsx("span",{ref:Do,className:R("model-controls__model-label typography-micro font-normal overflow-hidden",t?"whitespace-nowrap":"min-w-0",!t&&($?"max-w-[120px]":"max-w-[220px]")),children:l.jsx("span",{className:R("marquee-text",Oo&&"marquee-text--active"),children:lr})}),l.jsx(V,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"})]}):l.jsxs(l.Fragment,{children:[l.jsx(V,{name:"loader-4",className:R(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(wx,{open:s&&P,onOpenChange:s?rt:void 0,children:[l.jsx(ht,{asChild:!0,children:l.jsx(Sx,{asChild:!0,children:l.jsxs("button",{type:"button",className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:bg-transparent hover:opacity-70 min-w-0",ct),children:[s?c?l.jsxs(l.Fragment,{children:[l.jsx(Co,{providerId:c,className:R(Lt,"flex-shrink-0")}),l.jsx(V,{name:"pencil-ai",className:R(Lt,"text-primary/60 hidden")})]}):l.jsx(V,{name:"pencil-ai",className:R(Lt,"text-muted-foreground")}):l.jsxs(l.Fragment,{children:[l.jsx(V,{name:"loader-4",className:R(Lt,"animate-spin text-muted-foreground flex-shrink-0")}),l.jsx("span",{className:R("model-controls__model-label",Ut,"font-normal whitespace-nowrap text-muted-foreground min-w-0"),children:i})]}),s&&l.jsx("span",{ref:Do,className:R("model-controls__model-label overflow-hidden",Ut,"font-normal whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:l.jsx("span",{className:R("marquee-text",Oo&&"marquee-text--active"),children:lr})},`${c}-${d}`),s?l.jsx(V,{name:"arrow-down-s",className:"size-3.5 shrink-0 text-muted-foreground"}):null]})})}),l.jsxs(Cx,{"data-model-picker-popup":"true",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,onKeyDownCapture:$e,children:[l.jsx("div",{className:"p-1 border-b border-border/40",children:l.jsxs("button",{type:"button",onClick:gt,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(V,{name:"add",className:"size-4 -mr-0.5"})}),l.jsx("span",{className:"font-medium text-foreground",children:"Add new provider"})]})}),l.jsx(FA,{providers:a,favoriteModels:Q,recentModels:D,modelsMetadata:qe.getState().modelsMetadata,searchQuery:we,onSearchQueryChange:re,onSelect:Pe,labels:nt,selectedModel:c&&d?{providerID:c,modelID:d}:null,hiddenModels:K,onActiveKeyDown:ye,onActiveEntryChange:Ve=>{ke.current=Ve},onVariantKey:Z,isFavorite:Ve=>N(Ve.providerID,Ve.modelID),onToggleFavorite:Ve=>A(Ve.providerID,Ve.modelID),renderRowEnd:ot,renderVersion:oe,onReorderFavorite:(Ve,Xe)=>j(Ve.providerID,Ve.modelID,Xe.providerID,Xe.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",tooltipsEnabled:P,onEscape:()=>W(!1)})]})]}),Dd()]})},Od=()=>!s||!Ma?null:l.jsx(WA,{levels:bs,value:tn(u)??void 0,onChange:Ro,compact:G,keepLabel:t,onCompactOpen:()=>de("variant"),buttonHeight:ct,iconSize:Lt,textSize:Ut,isMobile:$,isDesktop:J}),Tn=R(!t&&"@container/model-controls","flex items-center",t?"w-max shrink-0":"min-w-0",$&&!t&&"w-full",e);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:Tn,children:l.jsxs("div",{className:R("flex items-center justify-start",xs,t?"w-max shrink-0":"min-w-0",$&&!t&&"overflow-hidden"),children:[Fo(),Od()]})}),Aa(),La(),Ta()]})},dL=1e9,uL=1e12,af="thinking",fL=e=>e>=uL?e:e>=dL?e*1e3:Date.now()+e,hL=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 Tx({isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:s,modelName:o,providerId:i,startedAt:a=null}){const{src:c,onError:d,hasLogo:u}=om(i??null),{currentTheme:f}=Fn(),p=f?.metadata.variant==="dark",m=h.useRef(null),[g,y]=h.useState(null);if(h.useEffect(()=>{const w=s?.next;if(!w||w<=0){y(null);return}const M=fL(w),I=()=>{const _=Math.max(0,M-Date.now());y(Math.ceil(_/1e3))};I();const E=setInterval(I,500);return()=>clearInterval(E)},[s?.next,s?.attempt]),!e)return m.current=null,null;if(s){m.current=null;const w=s.attempt&&s.attempt>1?` (attempt ${s.attempt})`:"",I=`Retrying${g!==null&&g>0?` in ${hL(g)}`:""}${w}`;return l.jsx("div",{className:"flex h-full min-w-0 items-center text-muted-foreground",role:"status","aria-live":"polite","aria-label":`${I}...`,"data-agent-thinking-row":"true",children:l.jsx(M2,{text:I,variant:"inline",showElapsed:!1,className:"min-w-0"})})}const b=r?"waiting for permission":t,k=!!r,v=!!n&&!k;m.current===null?m.current={text:v?af:b??af,permission:k}:b&&(!v||k)?m.current={text:b,permission:k}:v&&m.current.permission&&(m.current={text:af,permission:!1});const x=m.current;if(!x)return null;const C=typeof o=="string"?o.trim():"",S=C.length>0?`${C} 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":S,"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:[u&&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(M2,{text:S,variant:"inline",animationType:"spinner",animateText:!0,startedAt:a,className:"min-w-0"})]})})}const pL={containerType:"inline-size",containerName:"status-row"},J2={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Q2={high:"text-[var(--status-warning)]",medium:"text-muted-foreground",low:"text-muted-foreground/70"},e0={high:l.jsx(V,{name:"arrow-up-double",className:"h-3.5 w-3.5","aria-hidden":"true"}),medium:l.jsx(V,{name:"arrow-up-s",className:"h-3.5 w-3.5","aria-hidden":"true"}),low:l.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5","aria-hidden":"true"})},t0={in_progress:"In progress",pending:"Pending",completed:"Completed",cancelled:"Cancelled"},n0={high:"High priority",medium:"Medium priority",low:"Low priority"},mL=({todo:e})=>{const t=String(e.status||"pending"),n=String(e.priority||"medium"),r=J2[t]||J2.pending,s=t0[t]??t0.pending,o=n0[n]??n0.medium,i=t==="in_progress"?l.jsx(V,{name:"record-circle",className:"h-3.5 w-3.5 text-[var(--status-info)]","aria-hidden":"true"}):t==="completed"?l.jsx(V,{name:"checkbox-circle",className:"h-3.5 w-3.5 text-[var(--status-success)]","aria-hidden":"true"}):l.jsx(V,{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(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx("span",{className:"flex-shrink-0",children:i})}),l.jsx(pt,{side:"left",sideOffset:6,children:s})]}),l.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:e.content}),l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx("span",{className:R("typography-meta flex items-center justify-center flex-shrink-0 leading-none",Q2[n]??Q2.medium),children:e0[n]??e0.medium})}),l.jsx(pt,{side:"right",sideOffset:6,children:o})]})]})},gL=[],Ax=({isWorking:e=!1,statusText:t=null,isGenericStatus:n,isWaitingForPermission:r,wasAborted:s,abortActive:o,retryInfo:i,showAbort:a,onAbort:c,showAbortStatus:d,showAssistantStatus:u=!0,showTodos:f=!0,agentName:p,modelName:m,providerId:g,leftAccessory:y,turnStartedAt:b=null})=>{const[k,v]=h.useState(!1),x=ve(D=>D.currentSessionId),C=gL,S=se(D=>D.isMobile),{enabled:w}=yd(),M=S&&!w,I=M,E=h.useMemo(()=>C.filter(D=>D.status!=="cancelled"),[C]),_=h.useMemo(()=>E.find(D=>D.status==="in_progress")||E.find(D=>D.status==="pending")||null,[E]),T=h.useMemo(()=>{const D=C.filter(Y=>Y.status!=="cancelled").length;return{completed:C.filter(Y=>Y.status==="completed").length,total:D}},[C]),A=h.useMemo(()=>{const D=E.filter(Y=>Y.status==="in_progress").length,U=E.filter(Y=>Y.status==="in_progress"||Y.status==="pending").length;return{active:D,left:U}},[E]),j=f&&A.left>0,N=u&&(e||!!s||!!d),O=!!y,L=!d&&(s||!o),P=N||j||O,W=h.useRef(null);h.useEffect(()=>{if(!k)return;const D=U=>{W.current&&!W.current.contains(U.target)&&v(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[k]);const F=()=>v(D=>!D),q=`${A.active} active · ${A.left} left`,K=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(V,{name:"close-circle","aria-hidden":"true"})}):null,Q=j?l.jsxs("button",{type:"button",onClick:F,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground","aria-label":q,title:q,children:[!I&&_?l.jsx("span",{className:"status-row__active-todo typography-ui-label text-foreground truncate max-w-[200px]",children:_.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(V,{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(V,{name:"time",className:"h-3.5 w-3.5"}),A.left]})]}),k?l.jsx(V,{name:"arrow-up-s",className:"h-3.5 w-3.5"}):l.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5"})]}):null;return P?l.jsx("div",{className:R("mb-1",M&&"mt-2",!O&&"chat-column"),style:pL,children:l.jsxs("div",{className:R("flex min-h-5 items-center justify-between gap-2 py-0.5",O&&"px-0.5"),children:[l.jsx("div",{className:R("flex min-w-0 flex-1 items-center gap-2",O?"pl-1.5":"overflow-x-hidden"),children:u&&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(V,{name:"close-circle","aria-hidden":"true"}),"Aborted"]})}):u&&L?l.jsx(Tx,{isWorking:e,statusText:t,isGenericStatus:n,isWaitingForPermission:r,retryInfo:i,agentName:p,modelName:m,providerId:g,startedAt:b},`${x??"no-session"}:${b??"no-start"}`):y||null}),l.jsxs("div",{className:R("relative flex items-center gap-2 flex-shrink-0",O?"pr-1.5":"-mr-3"),ref:W,children:[K,Q,k&&j&&l.jsxs("div",{style:{maxWidth:"min(28rem, calc(100cqw - 4ch))",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:R("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px] rounded-xl p-1","shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)]","dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[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((D,U)=>l.jsx(mL,{todo:D},D.id??`todo-${U}`))})]})]})]})}):null},yL=1e4,vL=6e4,xL=5e3,bL=15e3,wL=3e4,SL=6e4,r0=5*6e4,CL=3e4,kL=10,s0=25,ML=40,IL=2,o0=15e3,_L=500,EL=30,Lc=20*1024*1024,i0=200,a0=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}),l0="oc.gitBranchCache",tc="oc.gitBranchCache.v2",jL=8,TL=50,lf=()=>({version:2,legacyClaimed:!1,runtimes:{}}),Lx=e=>{try{const t=zt(),n=t.getItem(tc),r=n?JSON.parse(n):lf(),s=r?.version===2&&r.runtimes&&typeof r.runtimes=="object"?{version:2,legacyClaimed:!!r.legacyClaimed,runtimes:r.runtimes}:lf();if(!s.legacyClaimed){const o=t.getItem(l0);if(o){const a=JSON.parse(o),c={};for(const[d,u]of Object.entries(a??{}))d&&u&&Array.isArray(u.all)&&(c[d]={branches:u,updatedAt:0});Object.keys(c).length>0&&(s.runtimes[e]={updatedAt:0,directories:c})}s.legacyClaimed=!0;const i=JSON.stringify(s);t.setItem(tc,i),t.getItem(tc)===i&&t.removeItem(l0)}return s}catch{return lf()}},AL=(e,t,n)=>{if(!(!t||!n))try{const r=Lx(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,TL));r.runtimes[e]={updatedAt:s,directories:a},r.runtimes=Object.fromEntries(Object.entries(r.runtimes).sort(([,c],[,d])=>d.updatedAt-c.updatedAt).slice(0,jL)),zt().setItem(tc,JSON.stringify(r))}catch{}},c0=e=>{const t=new Map,n=Lx(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},Nx=e=>{const t=new TextEncoder;return t.encode(e.original??"").byteLength+t.encode(e.modified??"").byteLength},d0=(e,t=EL,n=Lc)=>{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],u=new TextEncoder().encode(d.original??"").byteLength+new TextEncoder().encode(d.modified??"").byteLength;if(o.size>=t)break;i+u>n||(o.set(c,d),i+=u)}return o},u0=e=>{const t=[];let n=0;for(const[o,i]of e)for(const[a,c]of i.diffCache){const d=Nx(c);t.push({directory:o,path:a,fetchedAt:c.fetchedAt,size:d}),n+=d}if(t.length<=i0&&n<=Lc)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<=i0&&n<=Lc)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},LL=(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},NL=(e,t)=>!e&&!t?!1:!e||!t?!0:e.remote!==t.remote||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind,RL=(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&&NL(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&&LL(e.diffStats,t.diffStats))},PL=(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),u=i.get(c);if(!d||!u){n.add(c);continue}if(d.index!==u.index||d.working_dir!==u.working_dir){n.add(c);continue}}if(t.diffStats!==void 0){const c=e?.diffStats??{},d=t.diffStats??{},u=new Set([...Object.keys(c),...Object.keys(d)]);for(const f of u){const p=c[f],m=d[f];if(!p||!m){n.add(f);continue}(p.insertions!==m.insertions||p.deletions!==m.deletions)&&n.add(f)}}return n},DL=(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},f0=e=>!e||e.trim().length===0,Nc=e=>(e||"").trim()==="U",OL=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Nc(t)||Nc(n)?e:{...e,index:t==="?"||n==="?"?"A":t||n||" ",working_dir:" "}},HL=e=>{const t=(e.index||"").trim(),n=(e.working_dir||"").trim();return Nc(t)||Nc(n)?e:{...e,index:" ",working_dir:n||(t==="A"||t==="?"?"?":t)||" "}},FL=e=>f0(e.index)&&f0(e.working_dir),Ih=new Map,um=new Map,Us=new Map,vi=new Map,xi=new Map,bi=new Map,wi=new Map,Si=new Map,Rc=new Map,ia=new Map;let fm=0,hm=X();const VL=()=>hm,BL=e=>{fm+=1,hm=e,Rc.clear(),ia.clear(),Us.clear(),vi.clear(),xi.clear(),bi.clear(),wi.clear(),Si.clear(),Ih.clear(),um.clear()},nr=(e,t)=>JSON.stringify([e,t]),h0=(e,t,n)=>JSON.stringify([e,t,n]),$L=(e,t,n)=>JSON.stringify([e,t,n]),zL=(e,t,n)=>JSON.stringify([e,t,n]),UL=(e,t,n)=>JSON.stringify([e,t,n]),Zr=(e,t,n=!1)=>{const r=X(),s=UL(r,e,t),o=(Rc.get(s)??0)+1;return Rc.set(s,o),{runtimeKey:r,runtimeGeneration:fm,channelKey:s,requestGeneration:o,...n?{statusMutationRevision:ia.get(nr(r,e))??0}:{}}},cn=(e,t)=>e.runtimeKey===X()&&e.runtimeKey===hm&&e.runtimeGeneration===fm&&Rc.get(e.channelKey)===e.requestGeneration&&(e.statusMutationRevision===void 0||e.statusMutationRevision===(ia.get(nr(e.runtimeKey,t))??0)),cf=(e,t)=>{const n=nr(e,t);ia.set(n,(ia.get(n)??0)+1)},nc=e=>um.get(nr(X(),e))??0,xl=e=>{const t=nc(e)+1;return um.set(nr(X(),e),t),t},ZL=e=>{const t=nr(X(),e),n=Ih.get(t);if(n)return n;const r=new Set;return Ih.set(t,r),r},p0=VL(),yt=Et()(or((e,t)=>({runtimeKey:p0,directories:c0(p0),activeDirectory:null,resetForRuntimeSwitch:n=>{BL(n),e({runtimeKey:n,directories:c0(n),activeDirectory:null})},setActiveDirectory:n=>{const{activeDirectory:r,directories:s}=t();if(r!==n)if(r&&xl(r),n&&xl(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=X(),a=h0(i,n,o),c=Us.get(a)??(o==="light"?Us.get(h0(i,n,"full")):void 0);if(c)return c;const d=Zr(n,"status",!0),u=(async()=>{const{silent:f=!1}=s,{directories:p}=t();let m=p.get(n);if(m||(m=Mt()),!f){const y=new Map(t().directories),b=y.get(n)??Mt();y.set(n,{...b,isLoadingStatus:!0}),e({directories:y})}let g=!1;try{const y=Date.now(),b=m.isGitRepo!==!0||y-(m.lastRepoCheckAt||0)>vL;let k=m.isGitRepo===!0;if(b&&(k=await r.checkIsGitRepository(n),!cn(d,n)))return!1;if(!k){const C=new Map(t().directories),S=C.get(n)??m;return C.set(n,{...S,isGitRepo:!1,status:null,isLoadingStatus:!1,lastRepoCheckAt:y,lastStatusFetch:y}),e({directories:C}),!1}const v=await r.getGitStatus(n,s.mode?{mode:s.mode}:void 0);if(!cn(d,n))return!1;const x=t().directories.get(n)??Mt();if(RL(x.status,v)){g=!0;const C=new Map(t().directories),S=C.get(n)??Mt(),w=PL(S.status,v),M=DL(S.status,v),I=new Set((S.status?.files??[]).map(j=>j.path)),E=new Set((v.files??[]).map(j=>j.path)),_=new Map(S.diffCache);for(const j of I)E.has(j)||_.delete(j);for(const j of w)_.delete(j);const T=w.size>0;T&&xl(n);const A={...v,diffStats:v.diffStats===void 0&&S.status?.diffStats!==void 0?S.status.diffStats:v.diffStats,upstreamComparison:v.upstreamComparison===void 0?S.status?.upstreamComparison:v.upstreamComparison};C.set(n,{...S,isGitRepo:!0,status:A,diffCache:_,indexRevision:M?S.indexRevision+1:S.indexRevision,lastRepoCheckAt:b?y:S.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:T?Date.now():S.lastStatusChange}),e({directories:C})}else{const C=new Map(t().directories),S=C.get(n)??Mt();C.set(n,{...S,isGitRepo:!0,lastRepoCheckAt:b?y:S.lastRepoCheckAt,lastStatusFetch:Date.now(),lastStatusChange:S.lastStatusChange}),e({directories:C})}}catch(y){console.error("Failed to fetch git status:",y)}finally{if(!f&&cn(d,n)){const y=new Map(t().directories),b=y.get(n)??Mt();y.set(n,{...b,isLoadingStatus:!1}),e({directories:y})}}return g})();Us.set(a,u);try{return await u}finally{Us.get(a)===u&&Us.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 u=[];for(const p of c.files){if(!o.has(p.path)){u.push(p);continue}const m=s==="stage"?OL(p):HL(p);m!==p&&(d=!0),FL(m)?d=!0:u.push(m)}if(!d)return c;cf(t().runtimeKey,n);const f=new Map(i);return f.set(n,{...a,status:{...c,files:u,isClean:u.length===0},indexRevision:a.indexRevision+1,lastStatusChange:Date.now()}),e({directories:f}),c},restoreStatus:(n,r)=>{const{directories:s}=t(),o=s.get(n);if(!o)return;cf(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;cf(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=X(),i=nr(o,n),a=vi.get(i);if(a)return a;const c=Zr(n,"branches"),{silent:d=!1}=s,u=(async()=>{if(!d){const f=new Map(t().directories),p=f.get(n)??Mt();f.set(n,{...p,isLoadingBranches:!0}),e({directories:f})}try{const f=await r.getGitBranches(n);if(!cn(c,n))return;const p=new Map(t().directories),m=p.get(n)??Mt();p.set(n,{...m,branches:f,isLoadingBranches:!1,lastBranchesFetch:Date.now()}),e({directories:p}),AL(c.runtimeKey,n,f)}catch(f){if(console.error("Failed to fetch git branches:",f),!cn(c,n))return;const p=new Map(t().directories),m=p.get(n)??Mt();p.set(n,{...m,isLoadingBranches:!1}),e({directories:p})}})().finally(()=>{vi.get(i)===u&&vi.delete(i)});return vi.set(i,u),u},fetchLog:async(n,r,s,o={})=>{const{directories:i}=t(),a=i.get(n),c=s??a?.logMaxCount??25,d=X(),u=$L(d,n,c),f=xi.get(u);if(f)return f;const p=Zr(n,"log"),{silent:m=!1}=o,g=(async()=>{if(!m){const y=new Map(t().directories),b=y.get(n)??Mt();y.set(n,{...b,isLoadingLog:!0}),e({directories:y})}try{const y=await r.getGitLog(n,{maxCount:c});if(!cn(p,n))return;const b=new Map(t().directories),k=b.get(n)??Mt();b.set(n,{...k,log:y,isLoadingLog:!1,lastLogFetch:Date.now(),logMaxCount:c}),e({directories:b})}catch(y){if(console.error("Failed to fetch git log:",y),!cn(p,n))return;const b=new Map(t().directories),k=b.get(n)??Mt();b.set(n,{...k,isLoadingLog:!1}),e({directories:b})}})().finally(()=>{xi.get(u)===g&&xi.delete(u)});return xi.set(u,g),g},fetchRemotes:async(n,r,s={})=>{const o=r.getRemotes;if(typeof o!="function")return;const i=r.getRemoteUrl,a=X(),c=nr(a,n),d=bi.get(c);if(d)return d;const u=Zr(n,"remotes"),{silent:f=!1}=s,p=(async()=>{if(!f){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}),[y,b]=await Promise.all([m,g]);if(!cn(u,n))return;const k=new Map(t().directories),v=k.get(n)??Mt();k.set(n,{...v,remotes:y,remoteUrl:b.ok?b.value:v.remoteUrl,lastRemotesFetch:Date.now(),isLoadingRemotes:!1}),e({directories:k})}catch(m){if(console.error("Failed to fetch git remotes:",m),!cn(u,n))return;const g=new Map(t().directories),y=g.get(n)??Mt();g.set(n,{...y,isLoadingRemotes:!1}),e({directories:g})}})().finally(()=>{bi.get(c)===p&&bi.delete(c)});return bi.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)<r0||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=a0(s),c=X(),d=zL(c,n,a),u=Date.now(),f=t().directories.get(n)?.logQueryCache.get(a);if(!i&&f&&u-f.fetchedAt<CL)return f.log;const p=wi.get(d);if(p)return p;const m=Zr(n,`log-query:${a}`),g=(async()=>{try{const y=await r.getGitLog(n,{maxCount:s.maxCount,from:s.from,to:s.to,all:s.all,file:s.file});if(!cn(m,n))return f?.log??null;const b=new Map(t().directories),k=b.get(n)??Mt(),v=new Map(k.logQueryCache);if(v.set(a,{log:y,fetchedAt:Date.now()}),v.size>kL){let x=null,C=Number.POSITIVE_INFINITY;for(const[S,w]of v)w.fetchedAt<C&&(C=w.fetchedAt,x=S);x!==null&&v.delete(x)}return b.set(n,{...k,logQueryCache:v}),e({directories:b}),y}catch(y){return console.error("Failed to fetch git log query:",y),f?.log??t().directories.get(n)?.logQueryCache.get(a)?.log??null}})().finally(()=>{wi.get(d)===g&&wi.delete(d)});return wi.set(d,g),g},getCachedLogQuery:(n,r)=>{const s=a0(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 u=t().directories.get(n);if(!u?.isGitRepo)return;await t().fetchBranches(n,r);const f=d-(u.lastLogFetch||0);(a||f>yL||!u.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||Nx(s)>Lc)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:u0(i)})},clearDiffCache:(n,r)=>{xl(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,s0);await t().prefetchDiffs(n,r,o,{maxFiles:s0})},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=ML}=o,d=new Set(a.status.files.map(T=>T.path)),u=a.status.diffStats,f=ZL(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)||f.has(T))continue;const A=u?.[T];A&&A.insertions+A.deletions>_L||p.push(T)}const g=p.slice(0,Math.max(1,c));if(g.length===0)return;const y=nc(n);if(typeof document<"u"&&document.hidden)return;g.forEach(T=>f.add(T));let b=0;const k=[],v=()=>{const T=b;return b+=1,T<g.length?g[T]:null},x=async T=>{const A=r.getGitFileDiff(n,{path:T}),j=new Promise((O,L)=>{setTimeout(()=>L(new Error(`Timed out after ${o0}ms`)),o0)}),N=await Promise.race([A,j]);return{path:T,diff:{original:N.original??"",modified:N.modified??"",isBinary:N.isBinary}}},C=async()=>{for(;;){if(y!==nc(n)||!cn(i,n))return;const T=v();if(!T)return;try{k.push(await x(T))}catch{}finally{f.delete(T)}}},S=Math.min(IL,g.length);if(await Promise.allSettled(Array.from({length:S},()=>C())),g.forEach(T=>f.delete(T)),y!==nc(n)||!cn(i,n))return;const w=new Map(t().directories),M=w.get(n);if(!M)return;const I=new Map(M.diffCache),E=Date.now();k.forEach(T=>{I.set(T.path,{...T.diff,fetchedAt:E})});const _=d0(I);w.set(n,{...M,diffCache:_}),e({directories:u0(w)})},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<xL||await t().fetchStatus(n,r,{silent:!!s?.status})},ensureAll:(n,r)=>{const s=nr(X(),n),o=Si.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)>=bL)&&await t().fetchStatus(n,r,{silent:!!a?.status});const u=t().directories.get(n);if(!u?.isGitRepo)return;const f=[];(!u.branches||c-u.lastBranchesFetch>=SL)&&f.push(t().fetchBranches(n,r,{silent:!!u.branches})),(!u.log||c-u.lastLogFetch>=wL)&&f.push(t().fetchLog(n,r,void 0,{silent:!!u.log})),(u.remotes==null||c-(u.lastRemotesFetch??0)>=r0)&&f.push(t().fetchRemotes(n,r,{silent:u.remotes!=null})),f.length>0&&await Promise.all(f)})();return Si.set(s,i),i.finally(()=>{Si.get(s)===i&&Si.delete(s)}),i},refresh:async(n,r={})=>{const{activeDirectory:s}=t();s&&await t().fetchAll(s,n,r)}}),{name:"git-store"})),WL=e=>yt(t=>e?t.directories.get(e)?.status??null:null),Rx=e=>yt(t=>e?t.directories.get(e)?.branches??null:null),qL=e=>yt(t=>e?t.directories.get(e)?.log??null:null),GL=e=>yt(t=>e?t.directories.get(e)?.remotes??null:null),KL=e=>yt(t=>e?t.directories.get(e)?.remoteUrl??null:null),YL=e=>yt(t=>e?t.directories.get(e)?.isLoadingRemotes??!1:!1),Id=e=>yt(t=>e?t.directories.get(e)?.isGitRepo??null:null),XL=e=>yt(t=>e?t.directories.get(e)?.status?.current?.trim()??null:null),m0={current:new Map},JL=new Map,QL=(e=!0)=>yt(t=>{if(!e)return JL;const n=m0.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 m0.current=s,s}),eN=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})},tN=e=>yt(t=>e?t.directories.get(e)?.isLoadingStatus??!1:!1),nN=e=>yt(t=>e?t.directories.get(e)?.isLoadingLog??!1:!1),rN=e=>yt(t=>e?t.directories.get(e)?.isLoadingBranches??!1:!1),xW=Object.freeze(Object.defineProperty({__proto__:null,useGitAllBranches:QL,useGitBranchLabel:XL,useGitBranches:Rx,useGitLoadingBranches:rN,useGitLoadingLog:nN,useGitLoadingRemotes:YL,useGitLoadingStatus:tN,useGitLog:qL,useGitRemoteUrl:KL,useGitRemotes:GL,useGitRepoStatusMap:eN,useGitStatus:WL,useGitStore:yt,useIsGitRepo:Id},Symbol.toStringTag,{value:"Module"})),Px=h.createContext(null),bW=({actions:e,children:t})=>l.jsx(Px.Provider,{value:e,children:t}),xa=()=>h.useContext(Px),sN=/^[A-Za-z]:\/$/,pm=/^[A-Za-z]:\//,$t=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=sN.test(s);return!o&&!i&&(s=s.replace(/\/+$/,"")),s},oN=e=>{const t=$t(e);return t.startsWith("/")||pm.test(t)},Pc=e=>{const t=$t(e);return pm.test(t)||t.startsWith("//")?t.toLowerCase():t},Dx=e=>e.split("/").filter(Boolean),iN=(e,t)=>{const n=[...e];for(const r of Dx(t))if(r!=="."){if(r===".."){n.length>0&&n.pop();continue}n.push(r)}return n},ba=(e,t)=>{const n=$t(t);if(!n)return $t(e);if(oN(n))return n;const r=$t(e);if(!r)return n;const s=pm.test(r)?r.slice(0,2):"",o=r.startsWith("//"),i=r.startsWith("/")&&!o,a=s?r.slice(2):r,d=iN(Dx(a),n).join("/");return s?d?`${s}/${d}`:`${s}/`:o?`//${d}`:i?`/${d}`:d},_d=(e,t)=>{const n=$t(e),r=$t(t);if(!n||!r)return!1;const s=Pc(n),o=Pc(r);return s===o||s.startsWith(`${o}/`)},Ox=(e,t)=>{const n=$t(e),r=$t(t);return n?r?Pc(n)===Pc(r)?".":_d(n,r)?n.slice(r.length+1):n:n:""},df=(e,t)=>{const n=$t(e),r=$t(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)},aN=new Set(["edit","multiedit","write","apply_patch","create","file_write"]),mm=e=>"insertions"in e,Os=e=>{if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.trunc(e))},lN=e=>{let t=0,n=0;for(const r of e.split(`
69
- `))r.startsWith("+")&&!r.startsWith("+++")&&t++,r.startsWith("-")&&!r.startsWith("---")&&n++;return{added:t,removed:n}},wW=e=>{const t=[],n=new Set;for(const r of e){if(r.type!=="tool"||!r.tool||!aN.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 u of d){if(!u||typeof u!="object")continue;const f=u,p=f.relativePath||f.filePath||"";!p||n.has(p)||(n.add(p),t.push({path:p,tool:s,partId:r.id,messageID:o,additions:Os(f.additions)??void 0,deletions:Os(f.deletions)??void 0,patch:typeof f.patch=="string"?f.patch:void 0}))}if(d.length===0&&c?.filediff&&typeof c.filediff=="object"){const u=c.filediff,f=typeof u.file=="string"?u.file:"";f&&!n.has(f)&&(n.add(f),t.push({path:f,tool:s,partId:r.id,messageID:o,additions:Os(u.additions)??void 0,deletions:Os(u.deletions)??void 0,patch:typeof u.patch=="string"?u.patch:void 0}))}if(d.length===0&&Array.isArray(c?.results))for(const u of c.results){if(!u||typeof u!="object")continue;const f=u.filediff;if(!f||typeof f!="object")continue;const p=typeof f.file=="string"?f.file:"";!p||n.has(p)||(n.add(p),t.push({path:p,tool:s,partId:r.id,messageID:o,additions:Os(f.additions)??void 0,deletions:Os(f.deletions)??void 0,patch:typeof f.patch=="string"?f.patch:void 0}))}if(t.length===a){const u=i?.input,f=typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0;f&&!n.has(f)&&(n.add(f),t.push({path:f,tool:s,partId:r.id,messageID:o}))}if(t.length===a){const u=typeof c?.patch=="string"?c.patch.trim():typeof c?.diff=="string"?c.diff.trim():"";if(u&&!n.has("Diff")){n.add("Diff");const f=lN(u);t.push({path:"Diff",tool:s,partId:r.id,messageID:o,additions:f.added,deletions:f.removed})}}}return t},Hx=(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 u=t?.[s.path];r.push({path:ba(n,s.path),relativePath:s.path,insertions:u?.insertions??0,deletions:u?.deletions??0,status:d,hasStagedChanges:a,hasWorkingChanges:c})}return r},cN=(e,t)=>Ox(e,t),dN=(e,t)=>{const n=mm(e)&&e.relativePath?e.relativePath:cN(e.path,t),r=n.split("/").pop()??n,s=n.includes("/")?n.slice(0,n.lastIndexOf("/")):"";return{fileName:r,dirPart:s}},uN=e=>mm(e)?{additions:e.insertions,deletions:e.deletions}:{additions:e.additions??0,deletions:e.deletions??0},fN=({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}=dN(r,t),a=uN(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}`)})})]}),Fx="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)]",Vx={maxWidth:"calc(100cqw - 4ch)",backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},Bx=h.memo(({align:e="start"})=>{const[t,n]=h.useState(!1),r=h.useRef(null),s=Vn()??null,o=h.useContext(ha),i=Id(s),a=yt(C=>s?C.directories.get(s)?.status??null:null),c=xa(),d=se(C=>C.isMobile),{enabled:u}=yd(),f=d&&!u;h.useEffect(()=>{if(!t)return;const C=S=>{r.current&&!r.current.contains(S.target)&&n(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[t]);const p=h.useMemo(()=>!s||i!==!0||!a||a.isClean?[]:Hx(a.files,a.diffStats,s),[i,a,s]),{totalAdded:m,totalRemoved:g}=h.useMemo(()=>{let C=0,S=0;for(const w of p)C+=w.insertions,S+=w.deletions;return{totalAdded:C,totalRemoved:S}},[p]);if(!s||i!==!0||p.length===0)return null;const y=C=>{if(!s||!mm(C))return;n(!1);const S=C.path;if(c){c.openChanges({diffPath:C.relativePath,staged:C.hasStagedChanges&&!C.hasWorkingChanges});return}const w=o?.editor;if(w){w.openFile(S);return}const M=se.getState(),I=C.hasStagedChanges&&!C.hasWorkingChanges;if(!M.isMobile){M.openContextDiff(s,C.relativePath,I);return}M.navigateToDiff(C.relativePath,I)},b=p.length,k=b===1?`${b} file`:`${b} files`,v=b===1?"1 change":`${b} changes`,x=l.jsxs(l.Fragment,{children:[l.jsx(V,{name:"git-branch",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),f?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:k}),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(V,{name:"arrow-up-s",className:"h-3.5 w-3.5 shrink-0"}):l.jsx(V,{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(C=>!C),"aria-expanded":t,children:x}),t&&l.jsx("div",{style:{...Vx,maxWidth:"min(28rem, calc(100cqw - 4ch))"},className:R(Fx,"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(fN,{files:p,currentDirectory:s,onOpenFile:y})})]})});Bx.displayName="PendingChangesBar";const hN=h.createContext("default"),Ed=()=>h.useContext(hN);let _h=!1;const Eh=new Set,Dc=()=>_h,SW=e=>{if(_h!==e){_h=e;for(const t of[...Eh])try{t()}catch{}}},pN=e=>(Eh.add(e),()=>{Eh.delete(e)}),$x=()=>h.useSyncExternalStore(pN,Dc,Dc);function mN({className:e,style:t,...n}){return l.jsx(gs,{"data-slot":"command",style:{color:"var(--surface-elevated-foreground)",...t},className:R("flex h-full w-full flex-col overflow-hidden rounded-xl",e),...n})}const zx=z.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(V,{name:"search",className:"size-4 shrink-0 opacity-50"}),l.jsx(gs.Input,{ref:n,"data-slot":"command-input",className:R("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));zx.displayName="CommandInput";function gN({className:e,children:t,scrollbarClassName:n,disableHorizontal:r,...s}){return l.jsx(Hn,{as:gs.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:R("scroll-py-1 overflow-x-hidden h-full min-h-0",e),scrollbarClassName:n??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:r??!0,...s,children:t})}function yN({...e}){return l.jsx(gs.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...e})}function vN({className:e,...t}){return l.jsx(gs.Group,{"data-slot":"command-group",className:R("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",e),...t})}function CW({className:e,...t}){return l.jsx(gs.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",e),...t})}function xN({className:e,...t}){return l.jsx(gs.Item,{"data-slot":"command-item",className:R("data-[selected=true]:bg-interactive-selection data-[selected=true]:text-interactive-selection-foreground data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function kW({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(V,{name:"command",className:"size-3.5"}):i==="shift"||i==="⇧"?l.jsx(V,{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:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",e),...t,children:s.length>0?s.map((o,i)=>l.jsxs(z.Fragment,{children:[i>0&&l.jsx("span",{className:"opacity-60 text-xs",children:"+"}),n(o)]},`${o}-${i}`)):t.children})}const uf=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")},MW=e=>!!(e&&typeof e=="object"&&e.deferred===!0),IW=e=>`${e} saved. It will apply when active sessions are idle.`,_W=e=>`${e} could not be changed while a session is running. Try again when it finishes.`,bN=5e3,wn=new Map,xr=new Map,gr=new Map,zi=new Map,Xs=(e,t)=>`${e}
70
- ${t?.trim()??""}`,po=e=>{zi.set(e,(zi.get(e)??0)+1),xr.delete(e)},EW=e=>{const t=X();if(typeof e=="string"&&e.trim().length>0){const r=Xs(t,e);wn.delete(r),po(r);return}const n=new Set([...wn.keys(),...xr.keys(),...gr.keys()]);for(const r of n)r.startsWith(`${t}
71
- `)&&(wn.delete(r),po(r))},ff=e=>{const t=new Set([...wn.keys(),...xr.keys(),...gr.keys()]);for(const n of t)n.startsWith(`${e}
72
- `)&&(wn.delete(n),po(n))},bl=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})),rc=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(),xr.clear(),gr.clear(),zi.clear(),e({prompts:[],isLoading:!1,selectedPromptId:null,activeCacheKey:"",promptDraft:null})},loadPrompts:async n=>{const r=X(),s=typeof n=="string"&&n.trim().length>0?n.trim():void 0,o=Xs(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<bN)return e({isLoading:!1}),!0;const d=xr.get(o);if(d)return d;const u=zi.get(o)??0,f=(async()=>{try{const p=s?await De.listResources(s,{runtimeKey:r}):await De.listResources({runtimeKey:r});if(X()!==r)return!1;if((zi.get(o)??0)!==u)return e(g=>g.activeCacheKey===o?{isLoading:!1}:g),!0;const m=bl(p);return gr.set(o,m),wn.set(o,Date.now()),e(g=>g.activeCacheKey===o?{prompts:m,isLoading:!1,...g.selectedPromptId&&!m.some(y=>y.id===g.selectedPromptId)?{selectedPromptId:null}:{}}:g),!0}catch{return e(p=>p.activeCacheKey===o?{isLoading:!1}:p),!1}})();xr.set(o,f);try{return await f}finally{xr.get(o)===f&&xr.delete(o)}},createPrompt:async(n,r,s)=>{const o=X(),i=s.directory?.trim()?s.directory.trim():void 0;try{const a=await De.createPromptTemplate({name:n,description:s.description,content:r,location:s.location},i,{runtimeKey:o});if(X()!==o)return a.deferred===!0?"deferred":!0;const c=Xs(o,i),d=bl(a);po(c),gr.set(c,d),ff(o),wn.set(c,Date.now());const u=d.find(f=>f.name===n&&f.location===s.location);return e(f=>f.activeCacheKey===c?{prompts:d,promptDraft:null,selectedPromptId:u?.id??null,isLoading:!1}:f),Dl(s.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return uf(a)?"busy":!1}},updatePrompt:async(n,r,s)=>{const o=X(),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 De.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(X()!==o)return c.deferred===!0?"deferred":!0;const d=Xs(o,a),u=bl(c);po(d),gr.set(d,u),ff(o),wn.set(d,Date.now());const f=u.find(p=>p.name===(r.name??i.name)&&p.location===(r.location??i.location));return e(p=>p.activeCacheKey===d?{prompts:u,selectedPromptId:f?.id??null,isLoading:!1}:p),Dl(i.location==="global"||r.location==="global"?null:a),c.deferred===!0?"deferred":!0}catch(c){return uf(c)?"busy":!1}},deletePrompt:async(n,r)=>{const s=X(),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 De.deletePromptTemplate(o.id,i,{runtimeKey:s});if(X()!==s)return a.deferred===!0?"deferred":!0;const c=Xs(s,i),d=bl(a);return po(c),gr.set(c,d),ff(s),wn.set(c,Date.now()),e(u=>u.activeCacheKey===c?{prompts:d,...u.selectedPromptId===n?{selectedPromptId:null}:{},isLoading:!1}:u),Dl(o.location==="global"?null:i),a.deferred===!0?"deferred":!0}catch(a){return uf(a)?"busy":!1}},getPromptById:n=>t().prompts.find(r=>r.id===n)}),{name:"prompt-templates-store"})),wN="pichamber.json",SN=".pichamber",CN=[".config","pichamber","projects"];function gm(){const e=ep();return e?.files?e.files:null}const kN=80,MN=4e3,IN=2e3,_N=300,EN=new Set(["macos","linux","windows"]),mo=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},aa=(e,t)=>{const n=mo(e),r=t.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},Ux=e=>aa(aa(e,SN),wN),jd=()=>{const e="/api";return e.startsWith("/"),e},ym=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}}},jN=async e=>{const t=gm();if(t?.createDirectory)try{if((await t.createDirectory(e))?.success)return!0}catch{}return!!(await ym(`${jd()}/fs/mkdir`,{path:e})).ok},Zx=async(e,t)=>{try{const n=await Tt(`${jd()}/fs/read`,{query:{path:e,optional:"true",...t?{directory:t}:{}},cache:"no-store"});return n.ok?await n.text():null}catch{return null}},TN=async(e,t)=>{const n=gm();if(n?.writeFile)try{if((await n.writeFile(e,t))?.success)return!0}catch{}return!!(await ym(`${jd()}/fs/write`,{path:e,content:t})).ok},Wx=async()=>{const e=await p7();let t=e.home?mo(e.home):null;const n=e.pichamberDataDir?mo(e.pichamberDataDir):null;if(!t)try{const r=await m7();r&&r.trim().length>0&&(t=mo(r))}catch{}return{home:t,pichamberDataDir:n}},AN=async()=>(await Wx()).home,LN=async()=>(await Wx()).pichamberDataDir,qx=async()=>{const e=await LN();if(e)return aa(e,"projects");const t=await AN();return t?CN.reduce((n,r)=>aa(n,r),t):null},NN=e=>{const t=typeof e?.path=="string"?e.path.trim():"",n=t?mo(t):"";return n&&Qh(n)||null},Gx=async e=>{const t=await qx();if(!t)return null;const n=NN(e);return n?aa(t,`${n}.json`):null},wl=(e,t)=>e.length<=t?e:e.slice(0,t),RN=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();!EN.has(s)||n.has(s)||(n.add(s),t.push(s))}return t},PN=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=wl(typeof s.name=="string"?s.name.trim():"",kN),a=wl(typeof s.command=="string"?s.command.trim():"",MN);if(!o||!i||!a||n.has(o))continue;n.add(o);const c=typeof s.icon=="string"?s.icon.trim():"",d=RN(s.platforms),u=s.autoOpenUrl===!0,f=typeof s.openUrl=="string"?s.openUrl.trim():"",p=wl(f,IN),m=typeof s.desktopOpenSshForward=="string"?s.desktopOpenSshForward.trim():"",g=wl(m,_N);t.push({id:o,name:i,command:a,icon:c||null,...u?{autoOpenUrl:!0}:{},...p?{openUrl:p}:{},...g?{desktopOpenSshForward:g}:{},...d.length>0?{platforms:d}:{}})}return t},Kx=e=>{const t=PN(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 vm(e){const t=typeof e?.path=="string"?e.path.trim():"";if(!t)return null;const n=await Gx(e),r=async(a,c)=>{const d=await Zx(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=Ux(t),i=s(await r(o,t));if(!i)return null;try{await Yx(e,i)&&await HN(t)}catch{}return i}async function Yx(e,t){const n=typeof e?.path=="string"?e.path.trim():"";if(!n)return!1;const r=await qx(),s=await Gx(e);if(!r||!s)return!1;try{if(!await jN(r))return!1;const i=await Zx(s);let a={};if(typeof i=="string"&&i.trim())try{const u=JSON.parse(i);u&&typeof u=="object"&&!Array.isArray(u)&&(a=u)}catch{a={}}const c={};a.version!==void 0&&(c.version=a.version);const d=JSON.stringify({...a,...t,...c,projectPath:mo(n)},null,2);return await TN(s,d)}catch(o){return console.error("Failed to write pichamber config:",o),!1}}async function Xx(e,t){const r={...await vm(e)||{},...t};return Yx(e,r)}async function DN(e){const t=await vm(e);return A5(t?.draftStarters)}async function ON(e,t){return Xx(e,{draftStarters:A5(t)})}async function jW(e){const t=await vm(e);return Kx({actions:t?.projectActions,primaryActionId:t?.projectActionsPrimaryId})}async function TW(e,t){const n=Kx({actions:t.actions,primaryActionId:t.primaryActionId});return Xx(e,{projectActions:n.actions,projectActionsPrimaryId:n.primaryActionId??void 0})}async function HN(e){const t=Ux(e),n=gm();if(n?.delete)try{await n.delete(t);return}catch{}try{await ym(`${jd()}/fs/delete`,{path:t})}catch{}}const FN=[],si=(e,t)=>`${e}:${Lf(t)}`;function VN(){const e=se(L=>L.globalDraftStarters),t=rc(L=>L.prompts),n=rc(L=>L.activeCacheKey),r=rc(L=>L.loadPrompts),s=it(L=>L.activeProjectId),o=it(L=>L.projects),i=Vn(),a=h.useMemo(()=>{if(!s)return null;const L=o.find(P=>P.id===s);return L?.path?{id:L.id,path:L.path}:null},[s,o]),[c,d]=h.useState([]),u=h.useRef(new Set),[f,p]=h.useState(0);h.useEffect(()=>{let L=!1;if(!a){d([]);return}return DN(a).then(P=>{L||d(P)}).catch(()=>{L||d([])}),()=>{L=!0}},[a]),h.useEffect(()=>pn(()=>{u.current.clear(),p(P=>P+1),d([])}),[]);const m=h.useCallback(()=>{i&&r(i)},[i,r]);h.useEffect(()=>{if(!i)return;let L=!1;const P=X();return r(i).then(W=>{L||X()===P&&W&&(u.current.add(i),p(F=>F+1))}),()=>{L=!0}},[i,r]);const g=Xs(X(),i),y=n===g,b=y?t:FN,k=h.useMemo(()=>g7(b),[b]),v=i?y&&u.current.has(i):!1,x=h.useCallback((L,P)=>{if(L.type==="text"){const F=y7[L.key];return F?{id:si(P,L),ref:L,group:P,label:F.label,icon:F.icon,insertText:F.text,promptName:""}:null}return k.get(L.name)?{id:si(P,L),ref:L,group:P,label:tu(L.name),icon:eu,insertText:`/${L.name} `,promptName:L.name}:v?null:{id:si(P,L),ref:L,group:P,label:tu(L.name),icon:eu,insertText:`/${L.name} `,promptName:L.name}},[k,v]),C=h.useMemo(()=>e??Za,[e]),S=h.useMemo(()=>C.map(L=>x(L,"global")).filter(L=>L!==null),[C,x]),w=h.useMemo(()=>c.map(L=>x(L,"project")).filter(L=>L!==null),[c,x]),{global:M,project:I}=h.useMemo(()=>v7(w,S),[w,S]),E=h.useMemo(()=>{const L=new Set;for(const P of C)L.add(Lf(P));for(const P of c)L.add(Lf(P));return L},[C,c]),_=h.useMemo(()=>{const L=new Map;for(const P of b){if(P.editable!==!0||P.location!=="global"&&P.location!=="project")continue;const W=L.get(P.name),F=P.location==="project"?"project":"user",q={type:"prompt",name:P.name,label:tu(P.name),icon:eu,section:"prompt",scope:F};if(!W){L.set(P.name,q);continue}F==="project"&&W.scope!=="project"&&L.set(P.name,q)}return[...L.values()].filter(P=>!E.has(`${P.type}:${P.name}`))},[b,E]),T=h.useCallback(L=>{se.getState().setGlobalDraftStarters(L),_r({draftStarters:L})},[]),A=h.useCallback(L=>{d(L),a&&ON(a,L)},[a]),j=h.useCallback(L=>{if(L.type!=="prompt")return;const P={type:"prompt",name:L.name};if(L.scope==="project"){if(!a||c.some(W=>Wa(W,P)))return;A([...c,P])}else{const W=e??Za;if(W.some(F=>Wa(F,P)))return;T([...W,P])}},[a,c,e,A,T]),N=h.useCallback((L,P)=>{L==="project"?A(c.filter(W=>!Wa(W,P))):T((e??Za).filter(F=>!Wa(F,P)))},[c,e,A,T]),O=h.useCallback((L,P,W)=>{const F=L==="project"?c:e??Za,q=F.findIndex(D=>si(L,D)===P),K=F.findIndex(D=>si(L,D)===W);if(q<0||K<0||q===K)return;const Q=M9([...F],q,K);L==="project"?A(Q):T(Q)},[c,e,A,T]);return{global:M,project:I,pinnable:_,hasProject:!!a,ensureLoaded:m,addStarter:j,removeStarter:N,reorder:O}}const Jx="__draft-starter-trash__",Qx="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors",BN=[{key:"prompt",headingKey:"Prompts"}],$N=({item:e,onInsert:t,onRemove:n,hideRemove:r})=>{const{currentTheme:s}=Fn(),{attributes:o,listeners:i,setNodeRef:a,transform:c,transition:d,isDragging:u}=dp({id:e.id}),f={backgroundColor:s?.colors?.surface?.elevated,borderColor:s?.colors?.interactive?.border};return l.jsxs("div",{ref:a,style:{transform:up.Translate.toString(c),transition:d},className:R("group/chip relative",u&&"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:f,children:[l.jsx(V,{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:f,children:l.jsx(V,{name:"close",className:"h-2.5 w-2.5"})})]})},g0=({items:e,onInsert:t,onRemove:n,hideRemove:r})=>l.jsx(cp,{items:e.map(s=>s.id),strategy:_9,children:e.map(s=>l.jsx($N,{item:s,onInsert:t,onRemove:()=>n(s),hideRemove:r},s.id))}),zN=()=>{const{currentTheme:e}=Fn(),{setNodeRef:t,isOver:n}=E9({id:Jx});return l.jsx("button",{type:"button",ref:t,"aria-label":"Remove",title:"Remove",className:R(Qx,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(V,{name:"delete-bin",className:"h-4 w-4"})})},UN=({pinnable:e,onPick:t,className:n})=>l.jsxs(mN,{className:R("min-h-0",n),children:[l.jsx(zx,{placeholder:"Search prompts…"}),l.jsxs(gN,{children:[l.jsx(yN,{children:"Nothing to add"}),BN.map(r=>{const s=e.filter(o=>o.section===r.key);return s.length===0?null:l.jsx(vN,{heading:r.headingKey,children:s.map(o=>l.jsx(xN,{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)})]})]}),ZN=({pinnable:e,onOpen:t,onAdd:n})=>{const{currentTheme:r}=Fn(),[s,o]=h.useState(!1);return l.jsxs(vd,{open:s,onOpenChange:i=>{o(i),i&&t()},children:[l.jsx(JM,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Add a starter",title:"Add a starter",className:R(Qx,"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(V,{name:"add",className:"h-4 w-4"})})}),l.jsxs(xd,{className:"gap-0 overflow-hidden p-0 sm:max-w-sm",children:[l.jsx(bd,{className:"px-4 pb-2 pt-4 text-left",children:l.jsx(wd,{children:"Add a starter"})}),l.jsx(UN,{pinnable:e,onPick:i=>{n(i),o(!1)},className:"flex max-h-[60vh] flex-col"})]})]})},WN=({onInsert:e,className:t})=>{const{global:n,project:r,pinnable:s,ensureLoaded:o,addStarter:i,removeStarter:a,reorder:c}=VN(),{isMobile:d}=Rr(),[u,f]=h.useState(!1),p=ip(Ki(P5,{activationConstraint:{distance:8}}),Ki(R5,{activationConstraint:{delay:200,tolerance:6}})),m=h.useCallback(k=>n.find(v=>v.id===k)??r.find(v=>v.id===k),[n,r]),g=()=>f(!0),y=()=>f(!1),b=k=>{f(!1);const{active:v,over:x}=k;if(!x)return;const C=String(v.id),S=m(C);if(!S)return;if(String(x.id)===Jx){a(S.group,S.ref);return}const w=String(x.id);if(C===w)return;const M=m(w);M&&M.group===S.group&&c(S.group,C,w)};return l.jsx(ap,{sensors:p,collisionDetection:lp,measuring:{droppable:{strategy:I9.Always}},onDragStart:g,onDragCancel:y,onDragEnd:b,children:l.jsxs("div",{className:R("flex flex-wrap items-center justify-center gap-2",t),children:[n.length>0?l.jsx(g0,{items:n,onInsert:e,onRemove:k=>a("global",k.ref),hideRemove:d}):null,r.length>0?l.jsx(g0,{items:r,onInsert:e,onRemove:k=>a("project",k.ref),hideRemove:d}):null,d&&u?l.jsx(zN,{}):l.jsx(ZN,{pinnable:s,onOpen:o,onAdd:i})]})})},e4=e=>se(n=>n.draftStartersVisible)?l.jsx(WN,{...e}):null,t4=()=>{const e=ve(i=>i.currentSessionId),t=h3(),n=ve(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},oi=new Map,qN=(e,t)=>`${e}
73
- ${t?.trim()??""}`;function n4(e){const t=e?.trim()?e.trim():void 0,n=h.useSyncExternalStore(Z8,iu,iu),r=rc(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=N1(X(),t);return m?[...ur(),...m]:ur()}),[a,c]=h.useState(!1),[d,u]=h.useState(0),f=h.useRef(void 0),p=h.useRef({promptSignature:"",skillSignature:""});return h.useEffect(()=>{p.current={promptSignature:r,skillSignature:s}},[r,s]),h.useEffect(()=>pn(()=>{X8(),oi.clear(),f.current=void 0,i(ur()),u(g=>g+1)}),[]),h.useEffect(()=>{const m=X(),g=qN(m,t),y=`${g}
74
- ${n}`;if(!t){f.current=g,i(ur());return}if(f.current!==g){f.current=g;const x=N1(m,t);i(x?[...ur(),...x]:ur())}const b=q8(m,t);if(b&&G8(b)){const x=b.promptSignature!==""&&b.promptSignature!==r,C=b.skillSignature!==""&&b.skillSignature!==s;if(!x&&!C){(b.promptSignature!==r||b.skillSignature!==s)&&Y8(m,t,r,s),c(!1);return}}let k=!1;c(!0);const v=()=>{const x=oi.get(y);let C;if(x)C=x;else{const S=n,w=p.current.promptSignature,M=p.current.skillSignature,I={},E=(async()=>{try{const _=await De.listCommands(t,{runtimeKey:m});if(X()!==m||iu()!==S)return null;const T=z8(_.commands);return K8(m,t,T,{promptSignature:w,skillSignature:M}),T}catch{return null}finally{oi.get(y)?.promise===I.promise&&oi.delete(y)}})();I.promise=E,C={promise:E,promptSignature:w,skillSignature:M},oi.set(y,C)}C.promise.then(S=>{if(!k&&X()===m){if(S){i([...ur(),...S]);const w=p.current,M=C.promptSignature!==""&&C.promptSignature!==w.promptSignature,I=C.skillSignature!==""&&C.skillSignature!==w.skillSignature;if(M||I){v();return}}c(!1)}}).catch(()=>{k||c(!1)})};return v(),()=>{k=!0}},[t,r,s,d,n]),{commands:o,isLoading:a}}const GN=["concise","detailed","mentor","pushback","noFiller","matchEnergy","warmPeer"],KN=e=>typeof e=="string"&&GN.includes(e),YN=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."}},XN=({enabled:e,preset:t,customInstructions:n})=>e?t==="custom"?(typeof n=="string"?n.trim():"")||null:KN(t)?YN(t):null:null,r4=(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")},JN=e=>e.newSessionDraftOpen||(e.sessionId!==null?r4(e.storeState,e.sessionId):!1),s4=e=>XN({enabled:e.responseStyleEnabled===!0,preset:e.responseStylePreset,customInstructions:e.responseStyleCustomInstructions});let Ui=null,Zs=null;const QN=e=>{Ui={runtimeKey:X(),value:s4(e)}};typeof window<"u"&&window.addEventListener("pichamber:settings-synced",e=>{QN(e.detail??{})});pn(e=>{e.runtimeKey!==e.previousRuntimeKey&&(Ui=null,Zs=null)});const eR=async()=>{const e=X();if(Ui?.runtimeKey===e)return Ui.value;if(Zs?.runtimeKey===e)return Zs.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||X()!==e)return null;const s=s4(r);return Ui={runtimeKey:e,value:s},s})();Zs={runtimeKey:e,promise:t};try{return await t}finally{Zs?.promise===t&&(Zs=null)}},tR=async e=>{if(!JN({newSessionDraftOpen:e.newSessionDraftOpen,sessionId:e.sessionId,storeState:e.getStoreState()}))return null;const t=await eR().catch(()=>null);return!t||!e.newSessionDraftOpen&&e.sessionId!==null&&!r4(e.getStoreState(),e.sessionId)?null:t},y0="<system-reminder>",v0="</system-reminder>",nR=e=>{const t=e.trim();return t?t.startsWith(y0)&&t.endsWith(v0)?t:`${y0}
75
- ${t}
76
- ${v0}`:""},x0=e=>e.includes("@")?"paste":"manual",rR=({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(`
77
- `)?null:a},sR=/[\s()[\]{}<>"'`,.;:]/,oR=/^[`"'<([{]+/,iR=/[)\]},.;:!?`"'>]+$/,b0=/@([^\s]+)/g;function aR(e,t){return t<=0?!0:sR.test(e[t-1])}function lR(e){return e.trim().replace(oR,"").replace(iR,"")}function cR(e){if(!e||!e.includes("@"))return[];const t=[];b0.lastIndex=0;let n;for(;(n=b0.exec(e))!==null;){const r=n.index;if(!aR(e,r))continue;const s=n[1]??"",o=lR(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 dR(e,t){return!e||e.includes("<")||e.includes(">")?null:t.knownAgentNames.has(e.toLowerCase())?"agent":uR(e,t.confirmedMentions)?"file":null}function uR(e,t){return e.includes("/")||e.includes("\\")||e.includes(".")||t.has(e)}const fR=(e,t)=>t<=0||/\s/.test(e[t-1]);function hR(e,t){if(!e.startsWith("/")||e.indexOf(" ")!==-1)return null;const r=e.indexOf(`
78
- `),s=r===-1?e.length:r;return t>s?null:{kind:"command",query:e.substring(1,s)}}function pR(e,t,n,r){const s=e.substring(0,t),o=s.lastIndexOf(n);if(o===-1||!fR(s,o))return null;const i=s.substring(o+1);return i.includes(" ")||i.includes(`
79
- `)?null:{kind:r,query:i}}function mR(e,t,n){return n.inputMode==="shell"?null:hR(e,t)??pR(e,t,"#","snippet")??gR(e,t,n)}function gR(e,t,n){const r=rR({value:e,cursorPosition:t,inputSource:n.inputSource,insertedText:n.insertedText});return r===null?null:{kind:"mention",query:r}}const yR=(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"]),vR={"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"},ps=e=>e.trim().toLowerCase(),xR=e=>e.charCodeAt(0)<32||'<>:"/\\|?*[]'.includes(e),bR=e=>{const t=e.replace(/\\/g,"/").split("/").pop()??"";return Array.from(t).map(n=>xR(n)?"-":n).join("").replace(/\s+/g," ").replace(/-+/g,"-").trim()},wR=e=>{const t=e?.trim().toLowerCase()??"";return vR[t]??"png"},o4=e=>{const t=bR(e.name),n=wR(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}},SR=e=>{const{base:t}=o4({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)},go=(e,t)=>`${e}.${t}`,CR=(e,t,n)=>{const r=go(e,t);if(!n.has(ps(r)))return r;for(let s=2;s<Number.MAX_SAFE_INTEGER;s+=1){const o=go(`${e}-${s}`,t);if(!n.has(ps(o)))return o}return go(`${e}-${Date.now()}`,t)},kR=(e,t)=>{for(let n=1;n<Number.MAX_SAFE_INTEGER;n+=1){const r=go(`image-${n}`,e);if(!Array.from(t).some(o=>o.startsWith(`image-${n}.`))&&!t.has(ps(r)))return r}return go(`image-${Date.now()}`,e)},MR=(e,t)=>{const n=new Set(t.map(ps));return e.map(r=>{const{base:s,ext:o}=o4(r),i=SR(go(s,o))?kR(o,n):CR(s,o,n);return n.add(ps(i)),i})},IR=e=>e.map(t=>`[${t}]`).join(" "),_R=(e,t)=>{if(!e||!e.includes("[")||t.length===0)return[];const n=new Set(t.map(ps)),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(ps(a))&&r.push({start:o,end:i+1})}s=i+1}return r},ER=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}},i4=e=>e.trim().toLowerCase(),jh=new Map,Sl=new Map;let Cl=null;const jR=async(e,t)=>{switch(e){case"javascript":{const{javascript:n}=await mt(async()=>{const{javascript:r}=await import("./vendor-codemirror-lang-javascript-DwJ-IvCs.js");return{javascript:r}},__vite__mapDeps([44,45,46,5,1,6,47]));switch(t){case"jsx":return n({jsx:!0}).language;case"ts":case"typescript":return n({typescript:!0}).language;case"tsx":return n({typescript:!0,jsx:!0}).language;default:return n().language}}case"json":{const{json:n}=await mt(async()=>{const{json:r}=await import("./vendor-codemirror-lang-json-BG8C7OpC.js");return{json:r}},__vite__mapDeps([48,49,46,5,1,6]));return n().language}case"css":{const{css:n}=await mt(async()=>{const{css:r}=await import("./vendor-codemirror-lang-css-CZ_qxZY9.js");return{css:r}},__vite__mapDeps([50,51,46,5,1,6]));return n().language}case"html":{const{html:n}=await mt(async()=>{const{html:r}=await import("./vendor-codemirror-lang-html-COZ0L5wT.js");return{html:r}},__vite__mapDeps([52,53,46,5,1,6,50,51,44,45,47]));return n().language}case"markdown":{const{markdown:n}=await mt(async()=>{const{markdown:r}=await import("./vendor-codemirror-lang-markdown-DqlYH9gY.js");return{markdown:r}},__vite__mapDeps([54,5,1,6,47,55,52,53,46,50,51,44,45]));return n().language}case"python":{const{python:n}=await mt(async()=>{const{python:r}=await import("./vendor-codemirror-lang-python-Cz1dQXQd.js");return{python:r}},__vite__mapDeps([56,57,46,5,1,6,47]));return n().language}case"shell":{if(Cl)return Cl;const{shell:n}=await mt(async()=>{const{shell:r}=await import("./shell-CjFT_Tl9.js");return{shell:r}},[]);return Cl=j9.define(n),Cl}}},a4=e=>e?jh.get(i4(e))??null:null,TR=e=>{const t=i4(e);if(!t)return Promise.resolve(null);const n=jh.get(t);if(n)return Promise.resolve(n);const r=Sl.get(t);if(r)return r;const s=ER(t);if(!s)return Promise.resolve(null);const o=jR(s,t).then(i=>(i&&jh.set(t,i),Sl.delete(t),i)).catch(()=>(Sl.delete(t),null));return Sl.set(t,o),o},AR={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},S0={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"},LR=new Set(["strong","emphasis"]),l4="text-foreground";function NR(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 RR(e,t,n){const r=e[t-1],s=e[t+n];return!(!r||/\s/.test(r)||e[t]==="_"&&s&&/[\w]/.test(s))}function PR(e,t){const n=e[t],r=/^(\*{1,3}|_{1,3})/.exec(e.slice(t))?.[1]??"";if(!r||!NR(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(RR(e,o,r.length))return{end:o+r.length,runLength:r.length};s=o+r.length}return null}function Ws(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,u=a+1,f=u+c,p=f+2,m=p+d,g=m+1;n.push({start:a,end:u,style:"marker"}),c>0&&n.push({start:u,end:f,style:"link"}),n.push({start:f,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=PR(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"}),Ws(e.slice(r+i.runLength,i.end-i.runLength),a,n),r=i.end;continue}}r+=1}}const DR=/^(\s*)(`{3,}|~{3,})\s*(\S*)/;function xm(e){const t=DR.exec(e);return t?{marker:t[2],lang:t[3]||""}:null}function c4(e,t){return new RegExp(`^\\s*\\${t[0]}{${t.length},}\\s*$`).test(e)}function OR(e){const t=[];if(!e)return t;let n=0,r=!1,s="";const o=e.split(`
80
- `);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"}),c4(a,s)&&(r=!1);continue}const u=xm(a);if(u){r=!0,s=u.marker,t.push({start:c,end:d,style:"codeFence"});continue}const f=/^(\s*)(!!!)(\s+)/.exec(a);if(f){const y=c+f[1].length,b=y+f[2].length;t.push({start:y,end:b,style:"marker"});const k=b+f[3].length;d>k&&(t.push({start:k,end:d,style:"attention"}),Ws(a.slice(k-c),k,t));continue}const p=/^(\s*)(#{1,6})(\s+)/.exec(a);if(p){const y=c+p[1].length,b=y+p[2].length;t.push({start:y,end:b,style:"marker"});const k=b+p[3].length;d>k&&(t.push({start:k,end:d,style:"heading"}),Ws(a.slice(k-c),k,t));continue}const m=/^(\s*)(>+)(\s?)/.exec(a);if(m){const y=c+m[1].length,b=y+m[2].length;t.push({start:y,end:b,style:"marker"});const k=b+m[3].length;d>k&&(t.push({start:k,end:d,style:"blockquote"}),Ws(a.slice(k-c),k,t));continue}const g=/^(\s*)([-*+]|\d{1,9}[.)])(\s+)/.exec(a);if(g){const y=c+g[1].length,b=y+g[2].length;t.push({start:y,end:b,style:"listMarker"});const k=b+g[3].length;Ws(a.slice(k-c),k,t);continue}Ws(a,c,t)}return t}function HR(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,u)=>d-u),o=t.map((d,u)=>({range:d,index:u})).filter(d=>d.range.end>d.range.start).sort((d,u)=>d.range.start-u.range.start),i=[],a=[];let c=0;for(let d=0;d<s.length-1;d+=1){const u=s[d],f=s[d+1];if(f<=u)continue;for(;c<o.length&&o[c].range.start<=u;)a.push(o[c]),c+=1;for(let x=a.length-1;x>=0;x-=1)a[x].range.end<=u&&a.splice(x,1);let p=null,m=-1,g=1/0;const y=[];for(const{range:x,index:C}of a){if(LR.has(x.style)){const w=x.className??S0[x.style];y.includes(w)||y.push(w);continue}const S=x.priority??AR[x.style];(S>m||S===m&&C<g)&&(m=S,g=C,p=x)}const b=p?p.className??S0[p.style]:l4,k=y.length>0?[b,...y].join(" "):b,v=i[i.length-1];v&&v.className===k&&v.end===u?v.end=f:i.push({start:u,end:f,className:k})}return i}const FR=l4;function VR(e){return e.map(t=>({start:t.start,end:t.end,style:t.kind==="file"?"mentionFile":"mentionAgent"}))}const Gn="bg-[var(--surface-subtle)]",BR=91,$R=94,hf={keyword:8,function:7,type:6,string:5,number:5,variable:4,operator:3,comment:2},zR={keyword:`${Gn} text-[var(--syntax-keyword)]`,string:`${Gn} text-[var(--syntax-string)]`,number:`${Gn} text-[var(--syntax-number)]`,comment:`${Gn} text-[var(--syntax-comment)]`,function:`${Gn} text-[var(--syntax-function)]`,type:`${Gn} text-[var(--syntax-type)]`,variable:`${Gn} text-[var(--syntax-variable)]`,operator:`${Gn} text-[var(--syntax-operator)]`},UR=A9([{tag:[Fe.comment,Fe.lineComment,Fe.blockComment,Fe.docComment,Fe.meta],class:"comment"},{tag:[Fe.keyword,Fe.modifier,Fe.controlKeyword,Fe.operatorKeyword,Fe.definitionKeyword,Fe.moduleKeyword,Fe.self,Fe.null],class:"keyword"},{tag:[Fe.string,Fe.special(Fe.string),Fe.docString,Fe.character,Fe.regexp],class:"string"},{tag:[Fe.number,Fe.integer,Fe.float,Fe.bool,Fe.atom],class:"number"},{tag:[Fe.function(Fe.variableName),Fe.function(Fe.propertyName),Fe.macroName,Fe.standard(Fe.variableName)],class:"function"},{tag:[Fe.typeName,Fe.className,Fe.namespace,Fe.tagName],class:"type"},{tag:[Fe.variableName,Fe.propertyName,Fe.attributeName,Fe.labelName,Fe.definition(Fe.variableName)],class:"variable"},{tag:[Fe.operator,Fe.punctuation,Fe.bracket,Fe.derefOperator,Fe.separator],class:"operator"},{tag:[Fe.heading,Fe.heading1,Fe.heading2,Fe.heading3,Fe.heading4,Fe.heading5,Fe.heading6,Fe.strong],class:"keyword"},{tag:[Fe.emphasis,Fe.quote],class:"type"},{tag:[Fe.link,Fe.url],class:"function"},{tag:[Fe.monospace],class:"string"},{tag:[Fe.strikethrough],class:"comment"}]),ZR=e=>{let t=null;for(const n of e.split(" ")){const r=n;hf[r]!==void 0&&(t===null||hf[r]>hf[t])&&(t=r)}return t?zR[t]:null},WR=2e4,qR=e=>e?a4(e):null;async function GR(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return!1;const t=new Set;for(const r of e.split(`
81
- `)){const s=xm(r);s?.lang&&(a4(s.lang)||t.add(s.lang))}return t.size===0?!1:(await Promise.all([...t].map(r=>TR(r)))).some(r=>r!==null)}function KR(e){if(!e||!e.includes("```")&&!e.includes("~~~"))return[];const t=[],n=e.split(`
82
- `);let r=0;for(let s=0;s<n.length;s+=1){const o=n[s];r+=o.length+1;const i=xm(o);if(!i)continue;const a=qR(i.lang),c=r,d=[];let u=s+1,f=r;for(;u<n.length;u+=1){const m=n[u];if(c4(m,i.marker)){f+=m.length+1;break}d.push(m),f+=m.length+1}if(s=u,r=f,!a||d.length===0)continue;const p=d.join(`
83
- `);if(p.trim()&&(t.push({start:c,end:c+p.length,style:"codeFence",className:`${Gn} text-[var(--syntax-foreground)]`,priority:BR}),!(p.length>WR)))try{const m=a.parser.parse(p);T9(m,UR,(g,y,b)=>{const k=ZR(b);k&&t.push({start:c+g,end:c+y,style:"codeFence",className:k,priority:$R})})}catch{}}return t}const C0=/~([^\s~]+)/g,YR=/[)\]},.;:!?`"'>]+$/,XR=/[\s()[\]{}<>"'`,;:]/;function JR(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z]/.test(e)}function QR(e){if(!e||!e.includes("~"))return[];const t=[];C0.lastIndex=0;let n;for(;(n=C0.exec(e))!==null;){const r=n.index,s=r>0?e[r-1]:"";if(s&&!XR.test(s))continue;const o=(n[1]??"").replace(YR,"");!o||!JR(o)||t.push({start:r,end:r+1+o.length,path:o})}return t}function eP(e){return QR(e).map(t=>({start:t.start,end:t.end,style:"path"}))}const tP="[A-Za-z0-9][A-Za-z0-9_-]*",nP="[A-Za-z0-9][^\\s/]*",rP={"/":new RegExp(`(^|\\s)\\/(${nP})`,"g"),"#":new RegExp(`(^|\\s)#(${tP})`,"g")};function Th(e,t){if(!e||!e.includes(t))return[];const n=rP[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 Ah(e,t,n="case-insensitive"){return t.size===0?[]:e.filter(r=>t.has(n==="exact"?r.name:r.name.toLowerCase()))}function sP(e,t,n,r="case-insensitive"){const s=new Set,o=[];for(const i of Ah(Th(e,t),n,r))s.has(i.name)||(s.add(i.name),o.push(i.name));return o}function oP(e,t){const n=[];for(const r of cR(e)){const s=dR(r.name,t);s&&n.push({start:r.start,end:r.end,kind:s})}return n}function iP(e,t){if(!e||t.inputMode==="shell")return[];const n=[...OR(e),...KR(e),...VR(oP(e,t)),...eP(e)];for(const r of Ah(Th(e,"/"),t.knownSlashNames))n.push({start:r.start,end:r.end,style:"mentionCommand"});for(const r of Ah(Th(e,"#"),t.knownSnippetTriggers))n.push({start:r.start,end:r.end,style:"mentionSnippet"});if(t.attachmentFilenames.length>0&&e.includes("["))for(const r of _R(e,[...t.attachmentFilenames]))n.push({...r,style:"mentionFile"});return n}const bm=Z5.define(),d4=Z5.define(),Lh=W5.define({create:()=>u4,update(e,t){for(const n of t.effects)if(n.is(bm))return n.value;return e}}),u4={inputMode:"normal",knownAgentNames:new Set,confirmedMentions:new Set,knownSlashNames:new Set,knownSnippetTriggers:new Set,attachmentFilenames:[]};function k0(e,t){const n=new N9;for(const r of HR(e,iP(e,t)))r.className!==FR&&n.add(r.start,r.end,R9.mark({class:r.className}));return n.finish()}const aP=W5.define({create:e=>k0(e.doc.toString(),e.field(Lh)),update(e,t){const n=t.effects.some(s=>s.is(bm)),r=t.effects.some(s=>s.is(d4));return!t.docChanged&&!n&&!r?e:k0(t.state.doc.toString(),t.state.field(Lh))},provide:e=>fn.decorations.from(e)}),lP=L9.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 GR(n)}catch{return}t===this.generation&&r&&e.state.doc.toString()===n&&e.dispatch({effects:d4.of(void 0)})}});function cP(e=u4){return[Lh.init(()=>e),aP,lP]}const dP={"&":{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)"}},uP=fn.theme(dP),fP={"& .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"}},hP=fn.theme(fP),pP=[hP,fn.editorAttributes.of(e=>e.state.selection.main.empty?null:{class:"oc-native-range"})];function mP(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 gP(e){let t="";return e.changes.iterChanges((n,r,s,o,i)=>{t+=i.toString()}),t}function M0(e){return!!e.synthetic}const I0=new q5,_0=new q5,yP=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:u=!1,maxLines:f=8,boundSelector:p,boundGapPx:m=0,className:g,contentClassName:y,commandComboboxExpanded:b,commandComboboxListboxId:k,commandComboboxActiveOptionId:v}=t,x=h.useRef(null),C=h.useRef(null),S=h.useRef(!1),w=h.useRef({element:null,role:null}),M=h.useRef(t),I=t.viewStore??null;I&&!I.handlers&&(I.handlers={current:t});const E=I?.handlers??M;E.current=t,h.useLayoutEffect(()=>{const T=x.current;if(!T)return;const A=I?.view;if(A){T.appendChild(A.dom),A.requestMeasure();const{anchor:L,head:P}=A.state.selection.main;return A.dispatch({selection:{anchor:L,head:P}}),C.current=A,()=>{A.dom.remove(),C.current=null}}const j=[{any:(L,P)=>(P.key==="Enter"&&M0(P)&&S.current&&Object.defineProperty(P,"shiftKey",{value:!0}),E.current.onKeyDown?.(P)??!1)}],N=new fn({state:P9.create({doc:E.current.value,extensions:[D9(),O9(),pP,fn.lineWrapping,H9.highest(C1.of(j)),C1.of([...F9,...V9]),cP(E.current.languageContext),I0.of(fn.editable.of(E.current.editable??!0)),_0.of(k1(E.current.placeholder??"")),uP,fn.updateListener.of(L=>{const P=E.current,W=j0(L.state);if(L.docChanged){const F=L.transactions.some(K=>K.isUserEvent("input.paste"));let q="";for(const K of L.transactions)q+=gP(K);P.onChange({value:L.state.doc.toString(),selection:W,fromPaste:F,insertedText:q})}else L.selectionSet&&P.onSelectionChange?.(W);(L.docChanged||L.heightChanged||L.geometryChanged)&&P.onVisualLineCount?.(E0(L.view))}),fn.domEventHandlers({focus:()=>(E.current.onFocus?.(),!1),blur:()=>(E.current.onBlur?.(),!1),paste:L=>(E.current.onPaste?.(L),!1)}),fn.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});C.current=N,I&&(I.view=N);const O=L=>{L.key!=="Enter"||M0(L)||(S.current=L.shiftKey)};return N.contentDOM.addEventListener("keydown",O),()=>{if(C.current=null,I){N.dom.remove();return}N.destroy()}},[]),h.useEffect(()=>{const T=C.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(()=>{C.current===T&&(T.scrollDOM.scrollTop=T.scrollDOM.scrollHeight)})}))},[r]),h.useEffect(()=>{C.current?.dispatch({effects:bm.of(s)})},[s]),h.useEffect(()=>{C.current?.dispatch({effects:I0.reconfigure(fn.editable.of(i))})},[i]),h.useEffect(()=>{C.current?.dispatch({effects:_0.reconfigure(k1(o??""))})},[o]),h.useEffect(()=>{const T=C.current,A=x.current;if(!T||!A)return;if(u){T.scrollDOM.style.maxHeight="";return}const j=p?A.closest(p):null;let N=null;if(j)for(N=A;N.parentElement&&N.parentElement!==j;)N=N.parentElement;const O=()=>{const P=parseFloat(getComputedStyle(T.contentDOM).lineHeight||"");if(!Number.isFinite(P)||P<=0)return;let W=P*f;if(j&&N){const q=N.offsetHeight-T.scrollDOM.offsetHeight,K=j.clientHeight-q-m;K>0&&(W=Math.min(W,K))}const F=`${W}px`;T.scrollDOM.style.maxHeight!==F&&(T.scrollDOM.style.maxHeight=F)};if(O(),E.current.onVisualLineCount?.(E0(T)),typeof ResizeObserver>"u")return;const L=new ResizeObserver(O);return L.observe(A),N&&L.observe(N),j&&L.observe(j),()=>L.disconnect()},[m,p,u,f]),h.useEffect(()=>{const T=C.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=C.current;if(!T)return;const A=T.contentDOM;if(w.current.element!==A){const P=w.current;P.element&&P.element!==A&&(P.role===null?P.element.getAttribute("role")==="combobox"&&P.element.removeAttribute("role"):P.element.setAttribute("role",P.role),P.element.removeAttribute("aria-expanded"),P.element.removeAttribute("aria-controls"),P.element.removeAttribute("aria-activedescendant")),w.current={element:A,role:A.getAttribute("role")}}const j=w.current.role,N=()=>{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"),N()};return!!(b&&k)&&k?(A.setAttribute("role","combobox"),A.setAttribute("aria-expanded","true"),A.setAttribute("aria-controls",k),v?A.setAttribute("aria-activedescendant",v):A.removeAttribute("aria-activedescendant"),O):(O(),O)},[b,k,v]);const _=h.useCallback(T=>{mP(C.current,T)},[]);return h.useImperativeHandle(n,()=>({focus(T){const A=C.current;A&&A.contentDOM.focus({preventScroll:T?.preventScroll})},blur(){C.current?.contentDOM.blur()},isFocused(){return C.current?.hasFocus??!1},getValue(){return C.current?.state.doc.toString()??""},getSelection(){const T=C.current;return T?j0(T.state):{start:0,end:0}},setSelection(T,A=T){const j=C.current;if(!j)return;const N=j.state.doc.length;j.dispatch({selection:{anchor:Math.min(Math.max(T,0),N),head:Math.min(Math.max(A,0),N)}})},selectAll(){const T=C.current;T&&T.dispatch({selection:{anchor:0,head:T.state.doc.length}})},insertText(T){const A=C.current;if(!A||!T)return;const{from:j,to:N}=A.state.selection.main;A.dispatch({changes:{from:j,to:N,insert:T},selection:{anchor:j+T.length},userEvent:"input.type"})},replaceRange(T,A,j,N){const O=C.current;O&&O.dispatch({changes:{from:T,to:A,insert:j},selection:{anchor:N??T+j.length},userEvent:"input.type"})},caretCoords(T){const A=C.current;if(!A)return null;const j=T??A.state.selection.main.head,N=A.coordsAtPos(j);return N?{top:N.top,bottom:N.bottom,left:N.left}:null},getScrollDOM(){return C.current?.scrollDOM??null}}),[]),l.jsx("div",{ref:x,"data-testid":t["data-testid"],"data-chat-input":"true",onMouseDown:_,className:R("composer-editor w-full","[&_.cm-editor]:h-full",u&&"flex min-h-0 flex-1 flex-col",g,y)})});function E0(e){const t=e.defaultLineHeight;return!Number.isFinite(t)||t<=0?1:Math.max(1,Math.round(e.contentHeight/t))}function j0(e){const t=e.selection.main;return{start:t.from,end:t.to}}function vP(){return{view:null,handlers:null}}function xP(e,t){const n=e?e.endsWith(`
84
-
85
- `)?"":e.endsWith(`
86
- `)?`
87
- `:`
88
-
89
- `:"",r=t.endsWith(`
90
-
91
- `)?t:t.endsWith(`
92
- `)?`${t}
93
- `:`${t}
94
-
95
- `;return`${e}${n}${r}`}function f4(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 h4(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 bP(e,t){return e?`${e}${/\s$/.test(e)?"":" "}${t}`:t}const wP=/^(https?:\/\/|mailto:)\S+$/i;function SP(e,t){return wP.test(e)&&!/\s/.test(e)&&t.trim().length>0&&!t.includes("](")}const CP="application/x-pichamber-file-path",kP=["files","text/uri-list","codefiles",CP];function MP(e,t){try{return e.getData(t)}catch{return""}}function kl(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(kP.some(n=>t.includes(n))||t.some(n=>n.includes("vnd.code.tree")))return!0}for(const t of WE){const n=MP(e,t);if(n&&UE(n).length>0)return!0}return!1}function IP(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 _P({enabled:e,composerRef:t,messageRef:n,cursorPosRef:r,confirmedMentionsRef:s,setMessage:o,addAttachedFile:i}){const[a,c]=h.useState(!1),[d,u]=h.useState(!1),f=h.useRef(0),p=h.useCallback(v=>{if(!kl(v.dataTransfer))return;v.preventDefault(),v.stopPropagation(),f.current++;const x=v.dataTransfer.types?.includes("application/x-pichamber-file-path")??!1;x!==d&&u(x),e&&!a&&c(!0)},[e,a,d]),m=h.useCallback(v=>{kl(v.dataTransfer)&&(v.preventDefault(),v.stopPropagation(),v.dataTransfer.dropEffect="copy",e&&!a&&c(!0))},[e,a]),g=h.useCallback(v=>{v.preventDefault(),v.stopPropagation(),f.current--,f.current<=0&&(f.current=0,c(!1),u(!1))},[]),y=h.useCallback(()=>{f.current=0,c(!1),u(!1)},[]),b=h.useCallback(async v=>{if(f.current=0,!kl(v.dataTransfer)||(v.preventDefault(),v.stopPropagation(),c(!1),!e))return;const C=v.dataTransfer.getData("application/x-pichamber-file-path");if(C&&C!=="."){s.current.add(C);const w=`@${C}`,M=t.current,I=n.current;if(M){const{start:E,end:_}=M.getSelection(),T=I.slice(0,E),A=I.slice(_),j=T.length>0&&!/\s$/.test(T),N=A.length>0&&!/^\s/.test(A),O=`${j?" ":""}${w}${N?" ":""}`;M.replaceRange(E,_,O),r.current=E+O.length,M.focus()}else o(E=>f4(E,w));return}const S=IP(v.dataTransfer);S.length>0&&((await Promise.all(S.map(async M=>{try{return await i(M)}catch(I){return console.error("File attach failed",I),!1}}))).some(Boolean)||Ne.error("Failed to attach file"))},[i,t,s,r,e,n,o]),k=h.useCallback(v=>{kl(v.dataTransfer)&&v.preventDefault()},[]);return{isDragging:a,isInternalDrag:d,handleDragEnter:p,handleDragOver:m,handleDragLeave:g,handleDragEnd:y,handleDrop:b,handleDropCapture:k}}function EP({inputMode:e,enabled:t,composerRef:n,message:r,setMessage:s,insertTextAtSelection:o,updateAutocompleteState:i,markFileMentionPasteSuppression:a,attachedFiles:c,addAttachedFile:d}){const u=h.useRef(new Set);return h.useCallback(async f=>{const p=f.clipboardData;if(!p)return;const m={...f,clipboardData:p,preventDefault:()=>f.preventDefault()};if(e==="normal"&&t){const M=n.current,I=M?.getSelection().start??-1,E=M?.getSelection().end??-1;if(M&&E>I){const T=m.clipboardData.getData("text").trim(),A=r.slice(I,E);if(SP(T,A)){m.preventDefault();const j=`${r.slice(0,I)}[${A}](${T})${r.slice(E)}`,N=I+1+A.length+2+T.length+1;s(j),n.current?.setSelection(N,N),i(j,N,x0(T),T);return}}}const g=new Map;Array.from(m.clipboardData.files||[]).forEach(M=>{M.type.startsWith("image/")&&g.set(`${M.name}-${M.size}`,M)}),Array.from(m.clipboardData.items||[]).forEach(M=>{if(M.kind==="file"&&M.type.startsWith("image/")){const I=M.getAsFile();I&&g.set(`${I.name}-${I.size}`,I)}});const y=Array.from(g.values()),b=m.clipboardData.getData("text");if(y.length===0){b.includes("@")&&a();return}if(!t){b.includes("@")&&a();return}m.preventDefault();const k=MR(y,[...c.map(M=>M.filename),...u.current]),v=IR(k),x=n.current,C=x?.getSelection().start??r.length,S=x?.getSelection().end??r.length,w=h4(bP(b,v),r.slice(0,C),r.slice(S));o(w,x0(w)),await Promise.all(y.map(async(M,I)=>{const E=k[I],_=yR(M,E);u.current.add(E);try{await d(_)}catch(T){console.error("Clipboard image attach failed",T),Ne.error(T instanceof Error?T.message:"Failed to attach image from clipboard")}finally{u.current.delete(E)}}))},[d,c,n,t,e,o,a,r,s,i])}const jP=(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=sP(e,"/",r,"case-insensitive"),o=new Set,i=[];for(const a of s){const c=a.slice(6),d=n.get(c.toLowerCase())??c,u=d.toLowerCase();o.has(u)||(o.add(u),i.push(d))}return i},TP=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 AP(e,t){let n="",r=[],s;const o=[],i=[],a=f=>{for(const p of t.collectSkillNames(f))i.includes(p)||i.push(p)},c=f=>{!s&&f&&(s=f)},d=f=>{const p=t.parseAgentMention(f);c(p.agentName);const m=t.extractFileMentions(p.text);return a(m.text),m};if(e.queued.forEach((f,p)=>{const m=d(f.content),g=[...t.sanitizeAttachments(f.attachments),...m.attachments];if(p===0){n=m.text,r=g;return}o.push({text:m.text,attachments:g})}),e.composerText!==null){const f=d(e.composerText.replace(/^\n+|\n+$/g,"")),p=[...t.sanitizeAttachments(e.composerAttachments),...f.attachments];e.queued.length===0?(n=f.text,r=p):o.push({text:f.text,attachments:p})}for(const f of e.syntheticTexts)o.push({text:f,synthetic:!0});const u=t.buildSkillInstruction(i);return u&&o.push({text:u,synthetic:!0}),{primaryText:n,primaryAttachments:r,additionalParts:o,agentMentionName:s,isEmpty:!n&&r.length===0&&o.length===0}}function T0(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 LP=["undo","redo","timeline","compact"];function p4(e){return LP.includes(e)}async function NP({command:e,currentSessionId:t,scrollToBottom:n,setTimelineDialogOpen:r,onCompactSession:s,onUndoSession:o,onRedoSession:i}){const{name:a,argument:c}=e;return p4(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):(Ne.error("Open a session before compacting."),!0):!1:!1}function RP(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,u=o.current;if(!d||!u)return;const f=d.caretCoords();if(!f)return;const p=u.getBoundingClientRect(),m=f.top-p.top,g=f.left-p.left,y=8,b=260,k=m-y,v=p.height-m-y,x=v>=b||v>=k?"below":"above",C=n==="mention"?520:450,S=Math.max(y,Math.min(g-24,p.width-C-y)),w=Math.max(120,Math.min(b,x==="below"?v:k));a({top:x==="below"?m+22:m-6,left:S,place:x,maxHeight:w})},[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 Td=-1,Nh={index:Td,stashedDraft:""},Rh=e=>({state:e,text:null});function PP(e,t,n){if(t.length===0)return Rh(e);if(e.index===Td)return{state:{index:0,stashedDraft:n},text:t[0]};if(e.index>=t.length-1)return Rh(e);const r=e.index+1;return{state:{...e,index:r},text:t[r]}}function DP(e,t){if(e.index===Td)return Rh(e);if(e.index===0)return{state:Nh,text:e.stashedDraft};const n=e.index-1;return{state:{...e,index:n},text:t[n]}}function OP(e){const[t,n]=h.useState(Nh),r=h.useCallback(i=>{const a=PP(t,e,i);return a.text===null?null:(n(a.state),a.text)},[e,t]),s=h.useCallback(()=>{const i=DP(t,e);return i.text===null?null:(n(i.state),i.text)},[e,t]),o=h.useCallback(()=>n(Nh),[]);return{isBrowsing:t.index!==Td,older:r,newer:s,reset:o}}const HP=500;function A0(e,t){return`${e}\0${[...t].sort().join("\0")}`}function FP(e){const{message:t,messageRef:n,setMessage:r,confirmedMentionsRef:s,identity:o,persistEnabled:i,initialDraft:a,onIdentityChange:c,onDraftRestored:d}=e,u=h.useRef(null),f=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 y=h.useCallback((x,C)=>{if(!x)return;const S=Gt(x),w=new Set;for(const I of s.current)C.includes(`@${I}`)&&w.add(I);s.current=w;const M=A0(C,w);p.current.get(S)!==M&&(us(x,C,w),p.current.set(S,M))},[s]),b=h.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null)},[]),k=h.useRef(!1);h.useEffect(()=>{if(!k.current&&(k.current=!0,!!a.text)){if(!i){r(""),us(a.identity,"",[]);return}requestAnimationFrame(()=>g.current.onDraftRestored?.())}},[i]);const v=h.useRef(a.identity);return h.useEffect(()=>{const x=v.current,C=x?Gt(x):null,S=o?Gt(o):null;if(C===S)return;if(v.current=o,g.current.onIdentityChange?.(),b(),f.current=!0,!i){r(""),s.current=new Set;return}y(x,n.current);const w=od(o);r(w.text),s.current=w.confirmedMentions,w.text&&requestAnimationFrame(()=>g.current.onDraftRestored?.())},[b,s,o,n,i,y,r]),h.useEffect(()=>DS(x=>{const C=Gt(x);p.current.set(C,A0("",[]));const S=m.current;!S||Gt(S)!==C||(b(),f.current=!0,n.current="",s.current=new Set,r(""))}),[b,s,n,r]),h.useEffect(()=>{if(!i){b(),y(o,"");return}if(f.current){f.current=!1;return}b();const x=t,C=o;return u.current=setTimeout(()=>{u.current=null,y(C,x)},HP),b},[b,o,t,i,y]),h.useEffect(()=>{const x=()=>{b(),i&&y(m.current,n.current)},C=()=>{document.visibilityState==="hidden"&&x()};return document.addEventListener("visibilitychange",C),document.addEventListener("freeze",x),window.addEventListener("pagehide",x),()=>{document.removeEventListener("visibilitychange",C),document.removeEventListener("freeze",x),window.removeEventListener("pagehide",x),x()}},[b,n,i,y]),{persistNow:y}}function VP(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 L0(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 BP({composerRef:e,message:t,setMessage:n,updateAutocompleteState:r,closeAutocomplete:s,confirmedMentionsRef:o,toMentionPath:i}){const a=h.useCallback(f=>{const p=e.current?.getSelection().start||0,m=f.relativePath&&f.relativePath.trim().length>0?f.relativePath.trim():i(f.path)||f.name;o.current.add(m);const{newMessage:g,nextCursor:y}=VP(t,p,m);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(y),r(g,y)}),s(),e.current?.focus()},[s,e,o,t,n,i,r]),c=h.useCallback(f=>{const p=e.current?.getSelection().start??t.length,{newMessage:m,nextCursor:g}=L0(t,p,"@",f);n(m),requestAnimationFrame(()=>{e.current&&e.current.setSelection(g),r(m,g)}),s(),e.current?.focus()},[s,e,t,n,r]),d=h.useCallback((f,p)=>{const m=e.current?.getSelection().start??t.length,{newMessage:g,nextCursor:y}=L0(t,m,"#",p);n(g),requestAnimationFrame(()=>{e.current&&e.current.setSelection(y),r(g,y)}),s(),e.current?.focus()},[s,e,t,n,r]),u=h.useCallback(f=>{const p=f.invocationName??f.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:u}}const $P=e=>{const t="nativeEvent"in e?e.nativeEvent:e;return t.isComposing||t.keyCode===229},zP={"`":["`","`"],"*":["*","*"],_:["_","_"],"~":["~","~"],"(":["(",")"],"[":["[","]"],"{":["{","}"],'"':['"','"'],"'":["'","'"]};function UP(e,t,n,r){if(n<=t)return null;const s=zP[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 ZP(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}\`
96
-
97
- \`\`\`${o}`,a=s.length+2;return{next:i,caret:a}}return null}function WP({inputMode:e,setInputMode:t,message:n,setMessage:r,openAutocomplete:s,commandRef:o,snippetRef:i,mentionRef:a,composerRef:c,messageHistory:d,updateAutocompleteState:u,isMobile:f,hasContent:p,currentSessionId:m,sessionPhase:g,followUpBehavior:y,handleSubmit:b,handleQueueMessage:k}){return h.useCallback(v=>{if($P(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,C=c.current?.getSelection().start===0&&c.current?.getSelection().end===0,S=c.current?.getSelection().start===n.length&&c.current?.getSelection().end===n.length,w=!x&&(n.length===0||C),M=!x&&(n.length===0||S);if(e==="normal"&&!x&&!v.metaKey&&!v.ctrlKey&&!v.altKey){const I=c.current,E=I?.getSelection().start??-1,_=I?.getSelection().end??-1;if(I&&E>=0){const T=(N,O,L)=>{v.preventDefault(),r(N),c.current?.setSelection(O,L),u(N,L)},A=UP(n,E,_,v.key);if(A){T(A.next,A.caretStart,A.caretEnd);return}const j=ZP(n,E,_,v.key);if(j){T(j.next,j.caret,j.caret);return}}}if(v.key==="ArrowUp"&&w){v.preventDefault();const I=d.older(n);I!==null&&(r(I),requestAnimationFrame(()=>c.current?.setSelection(0,0)));return}if(v.key==="ArrowDown"&&M){v.preventDefault();const I=d.newer();I!==null&&r(I);return}if(v.key==="Enter"&&!v.shiftKey&&(!f||v.ctrlKey||v.metaKey)){v.preventDefault();const I=v.ctrlKey||v.metaKey,E=e==="normal"&&p&&m&&g!=="idle";y==="queue"?I||!E?b():k():I||!E?b():b({delivery:"steer"})}},[o,c,m,y,k,b,p,e,f,a,n,d,s,g,t,r,i,u])}const qP=e=>e.enabled&&e.draftOpen&&!!e.directory&&e.gitAvailable&&e.isGitRepository,GP=(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 wm(e){return e.label?.trim()||j5(e.path)}function KP(e){const t=it(F=>F.projects),n=sn(F=>F.projects),r=h.useMemo(()=>On(t,{projects:n}),[t,n]),s=tt(F=>F.homeDirectory),o=h.useMemo(()=>X3(t,r),[r,t]),i=it(F=>F.activeProjectId),a=it(F=>F.setActiveProjectIdOnly),c=ve(F=>F.newSessionDraft),d=ve(F=>F.currentSessionId),u=ve(F=>F.currentSessionDirectory),f=ve(F=>F.setNewSessionDraftTarget),p=!!c?.open,m=yt(F=>F.fetchBranches),{git:g}=ma(),y=h.useMemo(()=>{if(p){const q=Wt(c?.directoryOverride??null),K=c?.selectedProjectId?o.find(Q=>Q.ownerProjectId===c.selectedProjectId&&(!q||Wt(Q.path)===q))??o.find(Q=>Q.id===c.selectedProjectId)??null:null;if(K)return K;if(q){const Q=o.find(D=>Wt(D.path)===q)??null;if(Q)return Q}}else if(d){const q=Wt(u??null);if(q&&DC(q,s)){const Q=o.find(D=>D.ownerProjectId===tr)??null;if(Q)return Q}const K=er(t,r,u);if(K){const Q=Wt(u??null);return o.find(D=>D.ownerProjectId===K.id&&Wt(D.path)===Q)??o.find(D=>D.id===K.id)??null}}return(i?o.find(q=>q.id===i)??null:null)??o[0]??null},[i,r,u,d,s,p,c?.directoryOverride,c?.selectedProjectId,o,t]),b=h.useMemo(()=>Wt(y?.path??null),[y?.path]),k=h.useMemo(()=>p?Wt(c?.directoryOverride??null)??b:Wt(u??null)??b,[u,p,c?.directoryOverride,b]),v=y?t.find(F=>F.id===y.ownerProjectId)??null:null,x=Wt(v?.path??null),C=y?wm(y):null;h.useEffect(()=>{if(!KE({enabled:e,isDraftOpen:p,activeProjectId:i,selectedProjectId:c?.selectedProjectId}))return;const F=o.find(q=>q.id===i);F&&f({projectId:F.id,directoryOverride:F.path,branchIntent:null,worktreeIntent:null})},[i,e,p,c?.selectedProjectId,o,f]);const S=Id(k),w=yt(F=>k&&F.directories.get(k)?.status?.current?.trim()||null),M=Rx(p?k:null),[I,E]=h.useState(!1);h.useEffect(()=>{const F=k?yt.getState().directories.get(k)?.branches??null:null;if(!qP({enabled:e,draftOpen:p,directory:k,gitAvailable:!!g,isGitRepository:S===!0})){E(!1);return}if(!k||!g)return;let q=!1;return E(F===null),m(k,g).finally(()=>{q||E(!1)}),()=>{q=!0}},[e,m,p,g,S,k]);const _=M?.current?.trim()||w,T=p&&(c?.worktreeIntent?.startRef?.trim()||c?.branchIntent?.branch?.trim())||null,A=T??_,j=h.useMemo(()=>p?GP(M?.all,T):[],[T,p,M?.all]),N=A??(S===!0?"Detached HEAD":null),O=S===!0&&!!(N||j.length>0||I),L=h.useCallback(F=>{if(!p)return;const q=o.find(Q=>Q.id===F),K=Wt(q?.path??null);if(!(!q||!K)){if(q.ownerProjectId===tr){f({projectId:tr,directoryOverride:K,branchIntent:null,worktreeIntent:null});return}i!==q.ownerProjectId&&a(q.ownerProjectId),f({projectId:q.ownerProjectId,directoryOverride:K,branchIntent:null,worktreeIntent:null})}},[i,p,o,a,f]),P=h.useCallback(F=>{if(!p||!k)return;const q=F.trim();if(!(!q||q.startsWith("remotes/"))){if(c?.worktreeIntent&&x){f({branchIntent:null,worktreeIntent:{runtimeKey:X(),projectRoot:x,sourceDirectory:k,startRef:q}});return}f({worktreeIntent:null,branchIntent:{runtimeKey:X(),directory:k,branch:q}})}},[p,c?.worktreeIntent,k,x,f]),W=h.useCallback(F=>{if(!(!p||!k||!x||!A)){if(F){f({branchIntent:null,worktreeIntent:{runtimeKey:X(),projectRoot:x,sourceDirectory:k,startRef:A}});return}f({worktreeIntent:null,branchIntent:A===_?null:{runtimeKey:X(),directory:k,branch:A}})}},[_,p,A,k,x,f]);return{projects:o,selectedDraftProject:y,selectedDraftProjectPath:b,selectedDraftProjectRoot:x,draftProjectLabel:C,selectedDraftDirectory:k,selectedDraftBranchLabel:N,selectedBranchName:A,currentBranch:_,draftBranchItems:j,isDiscoveringDraftBranches:I,shouldShowDraftBranchSelector:O,worktreeMode:!!(p&&c?.worktreeIntent),handleDraftProjectChange:L,handleDraftBranchChange:P,handleWorktreeModeChange:W}}const YP=e=>{const t=ce(e.targetDirectory)??e.targetDirectory,r=(e.projectId?e.projects.find(i=>i.id===e.projectId)??null:null)??e.projects.reduce((i,a)=>{const c=ce(a.path);if(!c||t!==c&&!t.startsWith(`${c}/`))return i;const d=ce(i?.path??null);return!d||c.length>d.length?a:i},null),s=ce(r?.path??null),o=new Set([t]);if(!s)return o;o.add(s);for(const[i,a]of e.availableWorktreesByProject)if(ce(i)===s)for(const c of a??[]){const d=ce(c?.path??null);d&&o.add(d)}return o},XP=(e,t)=>{const n=new Set(e.map(r=>r.id));return t.some(r=>!n.has(r.id))},N0=(e,t)=>{const n=it.getState(),r=On(n.projects,sn.getState()),s=YP({targetDirectory:e,projectId:t,projects:n.projects,availableWorktreesByProject:r});return rk().filter(o=>s.has(o.directory)).sort((o,i)=>(o.title??"").localeCompare(i.title??"")||o.id.localeCompare(i.id))};function JP(e){const{activeRuntimeKey:t,intent:n,onReady:r}=e,{git:s}=ma(),o=yt(w=>w.fetchStatus),i=yt(w=>w.fetchBranches),a=yt(w=>w.clearDiffCache),[c,d]=h.useState(null),u=h.useRef(!1),f=h.useRef(0),p=h.useRef(null),m=h.useRef(r);m.current=r;const g=n?.runtimeKey??"",y=n?.directory??"",b=n?.branch??"";h.useEffect(()=>{f.current+=1,p.current=null,d(null)},[t,b,y,g]);const k=h.useCallback(w=>{s&&(a(w),kd.requestGitRefresh({directory:w}),Promise.all([o(w,s,{silent:!0}),i(w,s)]))},[a,i,o,s]),v=h.useCallback((w,M)=>{const I={runtimeKey:M.runtimeKey,directory:M.directory,branch:M.branch};p.current=I,m.current(w,I)},[]),x=h.useCallback(async w=>{const M=w.intent;if(!(u.current||c)){if(!s){Ne.error("Git is not available for the selected runtime.");return}if(M.runtimeKey!==X()){Ne.error("The runtime changed. Select the branch again before sending.");return}u.current=!0;try{const[I,E]=await Promise.all([s.getGitBranches(M.directory),s.getGitStatus(M.directory,{mode:"light"})]),_=ve.getState().newSessionDraft.branchIntent;if(!Hi(M,_))return;if(!I.all.includes(M.branch)||M.branch.startsWith("remotes/")){Ne.error(`Local branch ${M.branch} no longer exists.`),i(M.directory,s);return}if(E.mergeInProgress||E.rebaseInProgress||E.attentionReason){const N=E.attentionReason??(E.rebaseInProgress?"rebase":"merge");Ne.error(`Finish or abort the ${N} before switching branches.`);return}const T=E.current?.trim()||I.current?.trim()||null;if(T===M.branch){v(w.continuation,M);return}const A=w.projectId?it.getState().projects.find(N=>N.id===w.projectId)?.label?.trim():null,j=M.directory.split(/[\\/]/).filter(Boolean).pop()||M.directory;d({runtimeKey:M.runtimeKey,projectId:w.projectId??null,directory:M.directory,branch:M.branch,currentBranch:T,projectLabel:A||j,changedFileCount:E.files.length,activeSessions:N0(M.directory,w.projectId),phase:"ready",continuation:w.continuation})}catch(I){Ne.error(I instanceof Error?I.message:"Failed to inspect the selected branch.")}finally{u.current=!1}}},[i,s,c,v]),C=h.useCallback(()=>{f.current+=1,p.current=null,d(null)},[]),S=h.useCallback(async()=>{const w=c;if(!w||w.phase==="checking"||w.phase==="terminal-error"||!s)return;const M=f.current+1;f.current=M,d({...w,phase:"checking",activeSessionsChanged:!1,error:void 0});try{const I=ve.getState().newSessionDraft;if(!I.open||!Hi(I.branchIntent,w))throw Object.assign(new Error("The draft target changed. Press Send again to review the branch."),{terminal:!0});if(w.runtimeKey!==X())throw Object.assign(new Error("The runtime changed. Select the branch again before sending."),{terminal:!0});const E=N0(w.directory,w.projectId);if(XP(w.activeSessions,E)){d({...w,activeSessions:E,phase:"ready",activeSessionsChanged:!0,error:void 0});return}const _=await s.getGitBranches(w.directory);if(f.current!==M)return;const T=_.current?.trim()||null;if(T!==w.currentBranch&&T!==w.branch)throw Object.assign(new Error(`The current branch changed to ${T??"detached HEAD"}. Press Send again to review it.`),{terminal:!0});if(!_.all.includes(w.branch)||w.branch.startsWith("remotes/"))throw Object.assign(new Error(`Local branch ${w.branch} no longer exists.`),{terminal:!0});if(T!==w.branch&&(await s.checkoutBranch(w.directory,w.branch,{expectedCurrent:T,localOnly:!0})).currentBranch!==w.branch)throw Object.assign(new Error(`Git did not confirm checkout of ${w.branch}.`),{terminal:!0});if(f.current!==M)return;if(w.runtimeKey!==X()){Ne.warning("The branch may have changed on the previous runtime. The message was not sent.");return}k(w.directory),d(null),v(w.continuation,w)}catch(I){if(f.current!==M)return;const E=I instanceof Error?I.message:"Failed to check out the selected branch.";let _;try{_=(await s.getGitBranches(w.directory)).current?.trim()||null}catch{_=void 0}if(f.current!==M)return;k(w.directory);const T=!!(I&&typeof I=="object"&&"terminal"in I)||I&&typeof I=="object"&&"code"in I&&I.code==="BRANCH_CHANGED"||_===w.branch||_===void 0,A=_===w.branch?`Git switched to ${w.branch}, but reported an error: ${E} Review the repository, then press Send again.`:E;d({...w,phase:T?"terminal-error":"retryable-error",error:A})}},[s,c,k,v]);return{dialogState:c,request:x,confirm:S,cancel:C,getReceipt:w=>Hi(w,p.current)?p.current:null,clearReceipt:()=>{p.current=null}}}function QP(e){const{taskId:t,intent:n}=e,{git:r}=ma(),s=sn(u=>u.refreshProject),o=t??V3(n),a=en(h.useCallback(u=>o?u.entries.get(o)??null:null,[o]))?.state??null,c=h.useCallback(async u=>{try{const f=await en.getState().request({taskId:t??void 0,intent:u.intent,prompt:u.prompt,...u.failedSend?{failedSend:u.failedSend}:{},git:r??void 0,refreshProject:s});return u.intent.runtimeKey!==X()?null:f}catch(f){return f instanceof Error&&f.message===Kl,null}},[r,s,t]),d=h.useCallback(u=>{const f=o?en.getState().getEntryByKey(o):en.getState().getEntry(u);return!f?.receipt||!u?null:G_(u,f.receipt)?f.receipt:null},[o]);return{state:a,request:c,getReceipt:d}}function eD(e){const{isMobile:t,editorRef:n,formRef:r,controlsPanelOpen:s,attachMenuOpen:o}=e,[i,a]=h.useState(!1),[c,d]=h.useState(!1),u=h.useRef(0),f=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 C=x,S=()=>d(C.childElementCount>0);S();const w=new MutationObserver(S);return w.observe(C,{childList:!0}),()=>w.disconnect()},[t]);const m=c||s||o,g=h.useRef(0),y=h.useRef(0);h.useEffect(()=>{if(!t||yr()||typeof window>"u"||!window.matchMedia?.("(display-mode: standalone)")?.matches)return;const x=()=>{g.current+=1},C=()=>{if(g.current=Math.max(0,g.current-1),!f.current||g.current>0)return;f.current=!1,y.current=Date.now()+600,n.current?.focus(),n.current?.isFocused()&&a(!0);const S=()=>{const w=n.current;w?.isFocused()&&(r.current??w.getScrollDOM())?.scrollIntoView({block:"end"})};window.setTimeout(S,300),window.setTimeout(S,650)};return window.addEventListener("oc:mobile-overlay-opened",x),window.addEventListener("oc:mobile-overlay-closed",C),()=>{window.removeEventListener("oc:mobile-overlay-opened",x),window.removeEventListener("oc:mobile-overlay-closed",C)}},[n,r,t]),h.useEffect(()=>{if(!t)return;if(m){(i||Date.now()-u.current<800)&&(f.current=!0);return}if(!f.current)return;const x=window.setTimeout(()=>{f.current=!1,n.current?.focus({preventScroll:yr()})},180);return()=>window.clearTimeout(x)},[n,i,t,m]),h.useEffect(()=>{if(!t||yr()||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 b=h.useCallback(()=>{t&&(yr()&&Ck(),p.current!==null&&(window.clearTimeout(p.current),p.current=null),a(!0))},[t]),k=h.useCallback(()=>{if(t){if(Date.now()<y.current){const x=n.current;if(x){x.focus(),window.setTimeout(()=>{Date.now()<y.current&&!x.isFocused()&&x.focus()},50);return}}if(u.current=Date.now(),yr()){Gi.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(()=>{f.current=!1},[]);return{focused:i,onEditorFocus:b,onEditorBlur:k,cancelOverlayCloseRestore:v}}function R0(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 tD(e){const{isMobile:t,isFullscreen:n,isDraftScreen:r,isFocused:s,formRef:o,editorRef:i}=e;h.useLayoutEffect(()=>{if(!t||!n||yr())return;const a=window.visualViewport,c=o.current,d=i.current;if(!a||!c)return;document.documentElement.classList.add("oc-browser-kb-fullscreen");const u=()=>{const f=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=`${f}px`,c.style.height=`${Math.floor(Math.min(a.height,p-f))}px`,c.style.zIndex="40",c.style.background="var(--background)"};return u(),a.addEventListener("resize",u),a.addEventListener("scroll",u),window.addEventListener("resize",u),window.addEventListener("scroll",u,!0),()=>{a.removeEventListener("resize",u),a.removeEventListener("scroll",u),window.removeEventListener("resize",u),window.removeEventListener("scroll",u,!0),document.documentElement.classList.remove("oc-browser-kb-fullscreen"),R0(c),requestAnimationFrame(()=>{d?.isFocused()&&d.getScrollDOM()?.scrollIntoView({block:"nearest"})})}},[i,o,n,t]),h.useLayoutEffect(()=>{if(!t||yr()||!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 u=Number.NaN,f=0;const p=()=>{const m=document.documentElement.clientHeight,g=a.offsetTop+a.height,y=Math.max(0,Math.floor(Math.min(g,m)-c.offsetHeight));y!==u&&(u=y,c.style.top=`${y}px`),f=requestAnimationFrame(p)};return p(),()=>{cancelAnimationFrame(f),R0(c)}},[o,r,s,n,t])}const Sm=(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}},m4=20,nD=24,g4=(e,t)=>e.length<=t?e:`${e.slice(0,t-1)}…`;function Oc({project:e,maxCharacters:t}){const n=wm(e),r=t?g4(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(V,{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 P0="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",y4=({checked:e,onChange:t,showCheck:n=!0,chromeLess:r=!1})=>l.jsxs(ft,{delayDuration:300,children:[l.jsx(ht,{asChild:!0,children:l.jsxs(Ee,{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(V,{name:"git-branch",className:"size-3.5"}),l.jsx("span",{className:"truncate",children:"New worktree"}),e&&n?l.jsx(V,{name:"check",className:"size-3.5"}):null]})}),l.jsx(pt,{side:"top",sideOffset:6,className:"max-w-72",children:"Starts from the selected branch's latest commit. Uncommitted changes are not copied."})]}),D0=({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(V,{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 v4({branchName:e}){const{value:t,show:n}=Sm(!1,2e3),r=h.useCallback(async s=>{if(s.stopPropagation(),s.preventDefault(),!e)return;(await ir(e)).ok?n(!0):Ne.error("Failed to copy")},[e,n]);return e?l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(Ee,{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(V,{name:"check",className:"size-3.5 text-[color:var(--status-success)]"}):l.jsx(V,{name:"file-copy",className:"size-3.5"})})}),l.jsx(pt,{sideOffset:6,children:t?"Copied":"Copy branch name"})]}):null}function rD(e){const{projects:t,selectedProject:n,selectedBranchName:r,selectedBranchLabel:s,branchOptions:o,branchInteractive:i,branchLoading:a,showBranchSelector:c,showProjectSelector:d=!0,showWorktreeSelector:u=!1,worktreeMode:f=!1,endAccessory:p,onProjectChange:m,onBranchChange:g,onWorktreeModeChange:y,theme:b}=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(E2,{value:n.id,onValueChange:m,children:[l.jsx(T2,{size:"sm",className:P0,children:l.jsx(j2,{children:l.jsx(Oc,{project:n,theme:b,maxCharacters:m4})})}),l.jsx(A2,{className:"w-max min-w-48",children:t.map(k=>l.jsx(L2,{value:k.id,className:k.kind==="worktree"?"max-w-[24rem] truncate pl-7":"max-w-[24rem] truncate",children:l.jsx(Oc,{project:k,theme:b})},k.id))})]}):null,c&&i?l.jsxs(E2,{value:r??void 0,onValueChange:g,disabled:!!(a&&o.length===0),children:[l.jsx(T2,{size:"sm",className:P0,children:l.jsx(j2,{children:l.jsx(D0,{label:s,startFrom:f})})}),l.jsx(A2,{className:"w-max min-w-56",children:l.jsxs(iT,{children:[l.jsx(aT,{children:a?"Loading branches...":"Local branches"}),o.map(k=>l.jsx(L2,{value:k.value,className:"max-w-[28rem] truncate",children:k.label},k.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(D0,{label:s,startFrom:f}),l.jsx(v4,{branchName:r})]}):null,u?l.jsx(y4,{checked:f,onChange:y}):null]}),p?l.jsx("div",{className:"min-w-0 shrink-0",children:p}):null]})}function sD(e){const{selectedProject:t,selectedBranchName:n,selectedBranchLabel:r,branchInteractive:s,showBranchSelector:o,showProjectSelector:i=!0,showWorktreeSelector:a=!1,worktreeMode:c=!1,onWorktreeModeChange:d,endAccessory:u,theme:f,onOpenPicker:p}=e,m=r?g4(r,nD):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(y4,{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(Oc,{project:t,theme:f,maxCharacters:m4}),l.jsx(V,{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(V,{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(V,{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(V,{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(v4,{branchName:n})]}):null,!i&&u?l.jsx("div",{className:`min-w-0 shrink-0 ${o?"":"ml-auto"}`,children:u}):null]})]})}function oD(e){const{projects:t,selectedProject:n,selectedBranchName:r,branchOptions:s,branchInteractive:o,onProjectChange:i,onBranchChange:a,theme:c,openPicker:d,onOpenPickerChange:u,showProjectSelector:f=!0,showBranchSelector:p,query:m="",onQueryChange:g}=e,[y,b]=h.useState("");h.useEffect(()=>{d!=="project"&&b(""),d!=="branch"&&g?.("")},[g,d]);const k=h.useMemo(()=>{const x=y.trim().toLowerCase();return x?t.filter(C=>wm(C).toLowerCase().includes(x)||C.path.toLowerCase().includes(x)):t},[y,t]),v=h.useMemo(()=>{const x=m.trim().toLowerCase();return x?s.filter(C=>C.label.toLowerCase().includes(x)):s},[s,m]);return l.jsxs(l.Fragment,{children:[l.jsx(sa,{open:f&&d==="project",onClose:()=>u(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(Ar,{value:y,onChange:x=>b(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:k.map(x=>{const C=x.id===n.id;return l.jsxs("button",{type:"button",onClick:()=>{i(x.id),u(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 ":""}${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[l.jsx(Oc,{project:x,theme:c}),C?l.jsx(V,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},x.id)})})]})}),l.jsx(sa,{open:o&&p&&d==="branch",onClose:()=>u(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(Ar,{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 C=x.value===r;return l.jsxs("button",{type:"button",onClick:()=>{a(x.value),u(null)},className:`flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg px-3 py-2 text-left typography-ui-label transition-colors hover:bg-[var(--interactive-hover)] ${C?"bg-[var(--interactive-hover)] font-medium text-foreground":"text-foreground/80"}`,children:[l.jsx("span",{className:"truncate",children:x.label}),C?l.jsx(V,{name:"check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):null]},x.value)})})]})})]})}function iD(e){const{state:t,onCancel:n,onConfirm:r}=e,s=t?.phase==="checking",o=t?.phase==="terminal-error";return l.jsx(vd,{open:t!==null,onOpenChange:i=>{!i&&!s&&n()},children:l.jsxs(xd,{showCloseButton:!1,className:"max-w-md gap-5",children:[l.jsxs(bd,{children:[l.jsx(wd,{children:o?"Branch checkout needs attention":"Check out branch?"}),l.jsx(Bp,{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(eI,{children:[l.jsx(Ee,{variant:"outline",onClick:n,disabled:s,children:o?"Close":"Cancel"}),o?null:l.jsx(Ee,{onClick:r,disabled:s,children:s?"Checking out...":t?.phase==="retryable-error"?"Try Again":"Check Out and Send"})]})]})})}const Cm=(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,u=Math.max(120,Math.floor(d));r(f=>f===u?f:u)};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},Lr=e=>e.invocationName??e.name;function O0(e,t){const n=Lr(e),r=Lr(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 aD(e,t,n,r=[]){const s=[],o=new Map,i=(a,c)=>{for(const d of a){const u=c(d),f=Lr(d),p=o.get(f);if(!p){o.set(f,{index:s.length,item:d,precedence:u}),s.push(d);continue}const m=u>p.precedence?O0(d,p.item):O0(p.item,d);s[p.index]=m,o.set(f,{index:p.index,item:m,precedence:Math.max(p.precedence,u)})}};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 H0(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 lD(e,t){return Ys(e.name,t)||Ys(Lr(e),t)||!!(e.description&&Ys(e.description,t))||!!e.searchAliases?.some(n=>Ys(n,t))}function cD(e,t,n){const r=t.trim(),s=r.toLowerCase(),i=[...r?e.filter(a=>H0(a,n)&&lD(a,r)):e.filter(a=>H0(a,n))];return i.sort((a,c)=>{const d=Lr(a).toLowerCase(),u=Lr(c).toLowerCase(),f=s.length>0&&d.startsWith(s),p=s.length>0&&u.startsWith(s);return f&&!p?-1:!f&&p?1:d.localeCompare(u)}),i}function dD(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function uD(e){return`command-listbox-${e.length>0?e:"commands"}`}function Ph(e,t){return`${e}-option-${t}`}function fD(e){if(!e.loading&&e.hasSelectedCommand)return Ph(e.listboxId,e.selectedIndex)}const F0=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},hD=[{value:"all",label:"All"},{value:"system",label:"System"},{value:"prompts",label:"Prompts"},{value:"skills",label:"Skills"},{value:"extensions",label:"Extensions"}],x4=h.forwardRef(({searchQuery:e,onCommandSelect:t,onClose:n,style:r,onComboboxStateChange:s},o)=>{const i=ve(L=>L.currentSessionId),c=Dp(i??"").length>0,d=!!i,u=se(L=>L.isMobile),[f,p]=h.useState("all"),m=Vn(),{commands:g,isLoading:y}=n4(m),[b,k]=h.useState([]),[v,x]=h.useState(!1),[C,S]=h.useState(0),w=h.useRef(0),M=h.useRef(!1),I=h.useRef([]),E=h.useRef(null),_=Cm(E,u),T=h.useRef(!1),A=h.useRef(null),j=h.useRef(!1),N=h.useId(),O=h.useMemo(()=>uD(dD(N)),[N]);return h.useEffect(()=>{const L=P=>{const W=P.target;!W||!E.current||E.current.contains(W)||n()};return document.addEventListener("pointerdown",L,!0),()=>{document.removeEventListener("pointerdown",L,!0)}},[n]),h.useEffect(()=>{x(y);const L=g.filter(q=>q.source==="system").filter(q=>q.invocationName==="compact"?!0:d).map(q=>({id:q.id,name:q.name,invocationName:q.invocationName,source:"system",description:q.description,isBuiltIn:!0,...q.scope?{scope:q.scope}:{}})),P=g.filter(q=>q.source!=="system").map(q=>({id:q.id,name:q.name,invocationName:q.invocationName,source:q.source,description:q.description,...q.source==="skill"?{isSkill:!0}:{},...q.scope?{scope:q.scope}:{}})),W=aD(L,P.filter(q=>q.source==="extension"),P.filter(q=>q.source==="skill"),P.filter(q=>q.source==="prompt"));k(cD(W,e,u?"all":f))},[e,d,c,g,y,f,u]),h.useEffect(()=>{S(0)},[b]),h.useEffect(()=>{w.current=C},[C]),h.useEffect(()=>{s?.({listboxId:O,activeOptionId:fD({loading:v,hasSelectedCommand:!!b[C],selectedIndex:C,listboxId:O})})},[b,O,v,s,C]),h.useEffect(()=>{I.current[C]?.scrollIntoView({block:"nearest"})},[C]),h.useImperativeHandle(o,()=>({handleKeyDown:L=>{const P=b.length;if(L==="Escape"){n();return}if(P!==0){if(L==="ArrowDown"){M.current=!0,S(W=>(W+1)%P);return}if(L==="ArrowUp"){M.current=!0,S(W=>(W-1+P)%P);return}if(L==="Enter"||L==="Tab"){const W=(w.current%P+P)%P,F=b[W];F&&t(F)}}}}),[b,n,t]),u?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:_!==void 0?{...r,maxHeight:_}:r,children:l.jsx(Hn,{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(V,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):l.jsxs("div",{children:[b.map((L,P)=>{const W=P===C,F=F0(L),q=Lr(L);return l.jsx("div",{id:Ph(O,P),ref:K=>{I.current[P]=K},role:"option","aria-selected":W,className:R("flex cursor-pointer items-center gap-2 rounded-lg px-3 py-1.5 typography-ui-label",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:K=>K.preventDefault(),onPointerDown:K=>{K.pointerType==="touch"&&(A.current={x:K.clientX,y:K.clientY},j.current=!1)},onPointerMove:K=>{if(K.pointerType!=="touch"||!A.current)return;const Q=K.clientX-A.current.x,D=K.clientY-A.current.y;Math.hypot(Q,D)>6&&(j.current=!0)},onPointerUp:K=>{if(K.pointerType!=="touch")return;const Q=j.current;A.current=null,j.current=!1,!Q&&(K.preventDefault(),K.stopPropagation(),T.current=!0,t(L))},onPointerCancel:()=>{A.current=null,j.current=!1},onClick:()=>{if(T.current){T.current=!1;return}t(L)},onMouseMove:()=>{M.current=!1,S(P)},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:["/",q]}),F&&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:F})]})},L.id)}),b.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:_!==void 0?{...r,maxHeight:_}: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:hD.map(L=>l.jsx(Ee,{variant:"chip",size:"xs","aria-pressed":f===L.value,onMouseDown:P=>P.preventDefault(),onClick:()=>p(L.value),children:L.label},L.value))}),l.jsx(Hn,{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(V,{name:"refresh",className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0})}):l.jsxs("div",{children:[b.map((L,P)=>{const W=P===C,F=F0(L),q=Lr(L);return l.jsx("div",{id:Ph(O,P),ref:K=>{I.current[P]=K},role:"option","aria-selected":W,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",W?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:K=>K.preventDefault(),onPointerDown:K=>{K.pointerType==="touch"&&(A.current={x:K.clientX,y:K.clientY},j.current=!1)},onPointerMove:K=>{if(K.pointerType!=="touch"||!A.current)return;const Q=K.clientX-A.current.x,D=K.clientY-A.current.y;Math.hypot(Q,D)>6&&(j.current=!0)},onPointerUp:K=>{if(K.pointerType!=="touch")return;const Q=j.current;A.current=null,j.current=!1,!Q&&(K.preventDefault(),K.stopPropagation(),T.current=!0,t(L))},onPointerCancel:()=>{A.current=null,j.current=!1},onClick:()=>{if(T.current){T.current=!1;return}t(L)},onMouseMove:()=>{M.current=!1,S(P)},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:["/",q]}),F&&l.jsx("span",{className:R("ml-auto max-w-[45%] shrink-0 truncate text-xs leading-4",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:F})]}),L.description&&l.jsx("div",{className:R("mt-1 truncate text-xs leading-5",W?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:L.description}),L.source==="skill"&&L.name!==q&&l.jsx("div",{className:R("mt-0.5 truncate text-xs leading-4",W?"text-interactive-selection-foreground/60":"text-muted-foreground/80"),children:L.name})]})},L.id)}),b.length===0&&l.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),!u&&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"})]})});x4.displayName="CommandAutocomplete";const pD=(e,t=200)=>{const[n,r]=z.useState(e);return z.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},mD=h.forwardRef(({searchQuery:e,onFileSelect:t,onClose:n,style:r},s)=>{const o=t4()??"",i=it($=>$.activeProjectId),a=it(h.useCallback($=>$.projects.find(J=>J.id===i)?.path??null,[i])),c=h.useMemo(()=>{const $=a||o;return $?$.replace(/\\/g,"/").replace(/\/+$/,""):null},[a,o]),d=x7(h.useCallback($=>c?$.byRoot[c]:void 0,[c])),u=b7($=>$.searchFiles),f=pD(e,180),p=w7(),[m,g]=h.useState([]),[y,b]=h.useState([]),[k,v]=h.useState(!1),x=h.useRef(0),[C,S]=h.useState(0),w=h.useRef(0),[M,I]=h.useState(360),[E,_]=h.useState({}),[T,A]=h.useState({}),j=h.useRef([]),N=h.useRef([]),O=h.useRef([]),L=h.useRef(null),P=se($=>$.isMobile),W=Cm(L,P),F=(e??"").trim(),q=h.useMemo(()=>{if(!c||!d)return[];const $=[d.selectedPath,...d.openPaths.slice().reverse()].filter(B=>typeof B=="string"&&B.length>0),J=new Set,G=F.toLowerCase();return $.filter(B=>{if(J.has(B))return!1;J.add(B);const ie=B.startsWith(`${c}/`)?B.slice(c.length+1):B;return G?ie.toLowerCase().includes(G):!0}).slice(0,6).map(B=>{const ie=B.replace(/\\/g,"/"),xe=ie.split("/").filter(Boolean).pop()||ie,de=ie.startsWith(`${c}/`)?ie.slice(c.length+1):ie;return{name:xe,path:ie,relativePath:de,extension:xe.includes(".")?xe.split(".").pop()?.toLowerCase():void 0}})},[F,c,d]),K=y,Q=q,D=m;h.useEffect(()=>{const $=J=>{const G=J.target;!G||!L.current||L.current.contains(G)||n()};return document.addEventListener("pointerdown",$,!0),()=>{document.removeEventListener("pointerdown",$,!0)}},[n]),h.useEffect(()=>{if(!o){g([]);return}const J=(f??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!J){g([]);return}let G=!1;return x.current++,v(!0),u(o,J,80,{includeHidden:!0,respectGitignore:!p,type:"file"}).then(ue=>{if(G)return;const B=new Set(q.map(ie=>ie.path));g(ue.filter(ie=>!B.has(ie.path)).slice(0,15))}).catch(()=>{G||g([])}).finally(()=>{G||(x.current--,x.current<=0&&(x.current=0,v(!1)))}),()=>{G=!0,x.current=Math.max(0,x.current-1),x.current<=0&&v(!1)}},[o,f,q,u,p]),h.useEffect(()=>{if(!o){b([]);return}const J=(f??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();if(!J){b([]);return}let G=!1;return x.current++,v(!0),u(o,J,20,{includeHidden:!0,respectGitignore:!p,type:"directory"}).then(ue=>{G||b(ue.slice(0,10))}).catch(()=>{G||b([])}).finally(()=>{G||(x.current--,x.current<=0&&(x.current=0,v(!1)))}),()=>{G=!0,x.current=Math.max(0,x.current-1),x.current<=0&&v(!1)}},[o,f,u,p]),h.useEffect(()=>{S(0),_({}),A({})},[D,K,Q.length]),h.useEffect(()=>{w.current=C},[C]),h.useEffect(()=>{j.current[C]?.scrollIntoView({block:"nearest"})},[C]),h.useEffect(()=>{let $=null;const J=()=>{$!==null&&cancelAnimationFrame($),$=requestAnimationFrame(()=>{const G={},ue={};N.current.forEach((B,ie)=>{if(!B)return;const de=O.current[ie]?.offsetWidth??B.scrollWidth,Se=Math.max(0,de-B.clientWidth),je=Se>8;if(G[ie]=je,je){const Oe=Math.max(.6,Se/110);ue[ie]=Oe}}),_(G),A(ue)})};return J(),window.addEventListener("resize",J),()=>{$!==null&&cancelAnimationFrame($),window.removeEventListener("resize",J)}},[D,K]),h.useEffect(()=>{const $=N.current[C];if(!$)return;const J=()=>{const ue=$.clientWidth;ue>0&&I(ue)};if(J(),typeof ResizeObserver>"u")return;const G=new ResizeObserver(J);return G.observe($),()=>{G.disconnect()}},[C]);const U=h.useCallback($=>{t($)},[t]);h.useImperativeHandle(s,()=>({handleKeyDown:$=>{if($==="Escape"){n();return}const J=K.length+Q.length+D.length;if(J!==0){if($==="ArrowDown"){S(G=>(G+1)%J);return}if($==="ArrowUp"){S(G=>(G-1+J)%J);return}if($==="Enter"||$==="Tab"){const ue=(w.current%J+J)%J;if(ue<K.length){const xe=K[ue];xe&&U(xe);return}const B=ue-K.length,ie=B<Q.length?Q[B]:D[B-Q.length];ie&&U(ie)}}}}),[D,K,Q,n,U]);const Y=$=>{switch($.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return l.jsx(V,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-info)]"});case"json":return l.jsx(V,{name:"code",className:"h-3.5 w-3.5 text-[var(--status-warning)]"});case"md":case"mdx":return l.jsx(V,{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(V,{name:"file-image",className:"h-3.5 w-3.5 text-[var(--status-success)]"});default:return l.jsx(V,{name:"file-pdf",className:"h-3.5 w-3.5 text-muted-foreground"})}},ne=($,J,G)=>{const ue=$.relativePath||$.name,B=S1(ue,{maxLength:60}),ie=C===J,xe=E[J]??!1,de=T[J]??2.6;return l.jsxs("div",{ref:Se=>{j.current[J]=Se},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ie&&"bg-interactive-selection"),onClick:()=>U($),onMouseMove:()=>S(J),children:[Y($),l.jsxs("span",{ref:Se=>{N.current[J]=Se},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:ie?{"--file-mention-marquee-width":`${M}px`,"--file-mention-marquee-duration":`${de}s`}:void 0,"aria-label":ue,children:[l.jsx("span",{ref:Se=>{O.current[J]=Se},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:ue}),xe&&ie?l.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:ue}):l.jsx("span",{className:"block truncate",children:B})]})]},G)};return l.jsxs("div",{ref:L,className:"absolute z-[100] min-w-0 w-full max-w-[640px] max-h-64 bg-background border-2 border-border/60 rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",style:W!==void 0?{...r,maxHeight:W}:r,children:[l.jsx(Hn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-0",children:k?l.jsx("div",{className:"flex items-center justify-center py-4",children:l.jsx(V,{name:"refresh",className:"h-4 w-4 animate-spin text-muted-foreground"})}):l.jsxs("div",{className:"pb-2",children:[K.map(($,J)=>{const G=J,ue=$.relativePath||$.name,B=S1(ue,{maxLength:60}),ie=C===G;return l.jsxs("div",{ref:xe=>{j.current[G]=xe},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",ie&&"bg-interactive-selection"),onClick:()=>U($),onMouseMove:()=>S(G),children:[l.jsx(V,{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":ue,children:B})]},`dir-${$.path}`)}),K.length>0&&(Q.length>0||D.length>0)&&l.jsx("div",{className:"my-1 border-t border-border/60"}),Q.map(($,J)=>ne($,K.length+J,`recent-${$.path}`)),Q.length>0&&D.length>0&&l.jsx("div",{className:"my-1 border-t border-border/60"}),D.map(($,J)=>ne($,K.length+Q.length+J,$.path)),D.length===0&&K.length===0&&Q.length===0&&l.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No matches found"})]})}),!P&&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 gD(e){const t=(e.description||e.content).replace(/\s+/g," ").trim();return t.length>140?`${t.slice(0,140).trimEnd()}…`:t}const b4=h.forwardRef(({searchQuery:e,onSnippetSelect:t,onClose:n,style:r},s)=>{const o=h.useRef(null),i=se(M=>M.isMobile),a=Cm(o,i),[c,d]=h.useState(0),u=h.useRef(0),[f,p]=h.useState([]),m=h.useRef([]),g=Cr(M=>M.snippets),y=Cr(M=>M.loadSnippets),b=Vn(),k=Cr(M=>M.setSnippetDraft),v=Cr(M=>M.setSelectedSnippet),x=se(M=>M.setSettingsDialogOpen),C=se(M=>M.setSettingsPage);h.useEffect(()=>{y(b)},[y,b]),h.useEffect(()=>{const M=e.trim(),E=[...M.length?g.filter(_=>Ys(_.name,M)||_.aliases.some(T=>Ys(T,M))):g].sort((_,T)=>_.source==="project"&&T.source!=="project"?-1:_.source!=="project"&&T.source==="project"?1:_.name.localeCompare(T.name));p(E),d(E.length?1:0)},[e,g]),h.useEffect(()=>{u.current=c,m.current[c]?.scrollIntoView({block:"nearest"})},[c]),h.useEffect(()=>{const M=I=>{const E=I.target;E&&o.current&&!o.current.contains(E)&&n()};return document.addEventListener("pointerdown",M,!0),()=>document.removeEventListener("pointerdown",M,!0)},[n]);const S=h.useCallback(M=>{const I=e.trim(),E=M.aliases.includes(I)?I:M.name;t(M,E)},[t,e]),w=h.useCallback(()=>{const M=new Set(g.map(_=>_.name));let I="new-snippet",E=1;for(;M.has(I);)I=`new-snippet-${E++}`;k({name:I,scope:"global"}),v(null),C("snippets"),x(!0),n()},[n,v,x,C,k,g]);return h.useImperativeHandle(s,()=>({handleKeyDown:M=>{if(M==="Escape"){n();return}const I=f.length+1;if(M==="ArrowDown"){d(E=>(E+1)%I);return}if(M==="ArrowUp"){d(E=>(E-1+I)%I);return}if(M==="Enter"||M==="Tab"){if(u.current===0){w();return}const E=f[u.current-1];E&&S(E)}}}),[S,f,n,w]),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(Hn,{preventOverscroll:!0,outerClassName:"flex-1 min-h-0",className:"px-1 py-1.5",children:[l.jsx("div",{id:"snippet-option-new",ref:M=>{m.current[0]=M},role:"option","aria-selected":c===0,className:R("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:M=>M.preventDefault(),onClick:w,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:R("mt-1 text-xs leading-5",c===0?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:"Save reusable text for the # picker"})]})}),f.length?f.map((M,I)=>{const E=I+1,_=E===c,T=M.source==="project"?"Project":"Global",A=gD(M);return l.jsx("div",{id:`snippet-option-${E}`,ref:j=>{m.current[E]=j},role:"option","aria-selected":_,className:R("flex min-h-14 cursor-pointer items-start rounded-lg px-3 py-2.5",_?"bg-interactive-selection text-interactive-selection-foreground":"text-foreground hover:bg-interactive-hover"),onMouseDown:j=>j.preventDefault(),onClick:()=>S(M),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:["#",M.name]}),l.jsx("span",{className:R("ml-auto shrink-0 text-xs leading-4",_?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:T})]}),A?l.jsx("div",{className:R("mt-1 truncate text-xs leading-5",_?"text-interactive-selection-foreground/75":"text-muted-foreground"),children:A}):null]})},`${M.source}:${M.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"})]})});b4.displayName="SnippetAutocomplete";const yD={mention:520,command:520,snippet:520};function vD(e,t){if(t)return{left:`${t.left}px`,top:`${t.top}px`,bottom:"auto",width:`min(${yD[e]}px, calc(100% - ${t.left+8}px))`,maxHeight:`${t.maxHeight}px`,transform:t.place==="above"?"translateY(-100%)":void 0}}function xD(e){const{open:t,query:n,overlayPosition:r,onClose:s}=e;if(!t)return null;const o=vD(t,r);switch(t){case"command":return l.jsx(x4,{ref:e.commandRef,searchQuery:n,onCommandSelect:e.onCommandSelect,onClose:s,style:o,onComboboxStateChange:e.onCommandComboboxStateChange});case"snippet":return l.jsx(b4,{ref:e.snippetRef,searchQuery:n,onSnippetSelect:e.onSnippetSelect,onClose:s,style:o});case"mention":return l.jsx(mD,{ref:e.mentionRef,searchQuery:n,onFileSelect:e.onFileSelect,onClose:s,style:o})}}function bD(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 wD=h.memo(function(t){const{isMobile:n,footerIconButtonClass:r,sendIconSizeClass:s,stopIconSizeClass:o,canSend:i,disabledReason:a,canAbort:c,hasContent:d,currentSessionId:u,newSessionDraftOpen:f,isSending:p=!1,onPrimaryAction:m,onQueueMessage:g,onAbort:y}=t,b=l.jsx("button",{type:n?"button":"submit",disabled:!i||!u&&!f||p,onClick:k=>{n&&(k.preventDefault(),m())},className:R(r,i&&(u||f)&&!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(V,{name:"loader-4",className:R(s,"animate-spin")}):l.jsx(V,{name:"send-plane-2",className:R(s)})});return c?l.jsxs("div",{className:"relative",children:[d?l.jsx("button",{type:"button",disabled:!u||!i,onClick:k=>{n&&k.preventDefault(),g()},className:R(r,"absolute z-20 bottom-full left-1/2 -translate-x-1/2 mb-1",u&&i?"text-primary hover:text-primary":"opacity-30"),"aria-label":a||"Add follow-up",title:a||void 0,children:l.jsx(V,{name:"send-plane-2",className:R(s,"-rotate-90")})}):null,l.jsx("button",{type:"button",onClick:y,className:R(r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:l.jsx(bD,{className:R(o)})})]}):b},(e,t)=>e.isMobile===t.isMobile&&e.footerIconButtonClass===t.footerIconButtonClass&&e.sendIconSizeClass===t.sendIconSizeClass&&e.stopIconSizeClass===t.stopIconSizeClass&&e.canSend===t.canSend&&e.disabledReason===t.disabledReason&&e.canAbort===t.canAbort&&e.hasContent===t.hasContent&&e.currentSessionId===t.currentSessionId&&e.newSessionDraftOpen===t.newSessionDraftOpen&&e.isSending===t.isSending&&e.onPrimaryAction===t.onPrimaryAction&&e.onQueueMessage===t.onQueueMessage&&e.onAbort===t.onAbort),SD=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(V,{name:"add-circle",className:R(r,"text-current")})}):l.jsxs(wx,{onOpenChange:t.onMenuOpenChange,children:[l.jsx(Sx,{asChild:!0,children:l.jsx("button",{type:"button",className:n,title:"Add attachment","aria-label":"Add attachment",disabled:i,children:l.jsx(V,{name:"add-circle",className:R(r,"text-current")})})}),l.jsxs(Cx,{align:"start",children:[l.jsxs(U2,{onSelect:()=>{requestAnimationFrame(s)},children:[l.jsx(V,{name:"attachment-2"}),"Attach files"]}),c?l.jsxs(U2,{onSelect:()=>{requestAnimationFrame(c)},children:[l.jsx(V,{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(V,{name:"ai-agent",className:R(r,"text-current")})}):null]})},(e,t)=>e.footerIconButtonClass===t.footerIconButtonClass&&e.iconSizeClass===t.iconSizeClass&&e.handlePickLocalFiles===t.handlePickLocalFiles&&e.onOpenSettings===t.onOpenSettings&&e.onMenuOpenChange===t.onMenuOpenChange&&e.onOpenMobileSheet===t.onOpenMobileSheet&&e.isAttachmentDisabled===t.isAttachmentDisabled&&e.disabled===t.disabled&&e.onLinkGitHub===t.onLinkGitHub);function CD(e){const{isMobile:t,isInline:n,alignToolsEnd:r,sessionId:s,newSessionDraftOpen:o,children:i,leadingExtra:a,trailingExtra:c,actionsOverride:d,footerPaddingClass:u,footerGapClass:f,footerIconButtonClass:p,iconSizeClass:m,sendIconSizeClass:g,stopIconSizeClass:y,canSend:b,disabledReason:k,canAbort:v,hasContent:x,isSending:C=!1,isAttachmentDisabled:S,onOpenSettings:w,onPickLocalFiles:M,onLinkGitHub:I,onPrimaryAction:E,onQueueMessage:_,onAbort:T}=e,A=l.jsx(SD,{footerIconButtonClass:p,iconSizeClass:m,handlePickLocalFiles:M,onLinkGitHub:I,onOpenSettings:w,onOpenMobileSheet:t?M:void 0,disabled:C,isAttachmentDisabled:S}),j=d??l.jsx(wD,{isMobile:t,footerIconButtonClass:p,sendIconSizeClass:g,stopIconSizeClass:y,canSend:b,disabledReason:k,canAbort:v,hasContent:x,isSending:C,currentSessionId:s,newSessionDraftOpen:o,onPrimaryAction:E,onQueueMessage:_,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:R("flex-shrink-0",u,"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:R("w-max shrink-0",C&&"pointer-events-none opacity-60"),inert:C||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 N=r?"self-end":"self-center";return l.jsxs("div",{className:R("grid grid-cols-[auto_minmax(0,1fr)_auto] bg-transparent",u,f),"data-chat-input-footer":"true",children:[l.jsx("div",{className:R("flex min-w-0 items-center",f,N),children:A}),l.jsx("div",{className:"min-w-0",children:i}),l.jsxs("div",{className:R("flex min-w-0 items-center justify-end",f,N),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:R("flex flex-shrink-0 items-center justify-between",u,f),"data-chat-input-footer":"true",children:[l.jsxs("div",{className:R("flex min-w-0 items-center",f),children:[A,a?l.jsx("div",{className:R("w-max min-w-0 shrink-0",C&&"pointer-events-none opacity-60"),inert:C||void 0,children:a}):null]}),l.jsxs("div",{className:R("flex flex-shrink-0 items-center",f),children:[c,j]})]})]})}const w4=h.memo(({sessionId:e})=>{const t=ve(v=>v.restoreToMessage),n=ve(v=>v.forkFromMessage),r=ve(v=>v.handleSlashRedo),[s,o]=h.useState(null),[i,a]=h.useState(null),[c,d]=h.useState(!0),u=PC(e),f=u?.targetEntryId,p=h.useMemo(()=>u?u.abandoned.filter(v=>v.role==="user"):[],[u]),m="No text content",g=h.useMemo(()=>!u||p.length===0?[]:p.map(v=>({id:v.id,text:v.preview?.replace(/\s+/g," ").trim()||m})),[p,u,m]),y=g[0]?.id;h.useEffect(()=>{d(!0)},[f,y]);const b=h.useCallback(async v=>{if(!(!e||s)){o(v);try{const x=p.findIndex(S=>S.id===v),C=x>=0?p[x+1]:void 0;C?(await t(e,C.id),Ne.success("Restored messages through this point")):await r(e)}catch(x){Ne.error(x instanceof Error?x.message:"Failed to restore messages")}finally{o(null)}}},[p,r,t,s,e]),k=h.useCallback(async v=>{if(!(!e||i)){a(v);try{await n(e,v)}catch(x){Ne.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(V,{name:"arrow-down-s",className:R("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(Ee,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{k(v.id)},children:[i===v.id?l.jsx(V,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):l.jsx(V,{name:"git-branch",className:"h-3 w-3","aria-hidden":"true"}),"Fork"]}),l.jsxs(Ee,{type:"button",variant:"secondary",size:"xs",disabled:!!(s||i),onClick:()=>{b(v.id)},children:[s===v.id?l.jsx(V,{name:"loader-4",className:"h-3 w-3 animate-spin","aria-hidden":"true"}):l.jsx(V,{name:"arrow-go-forward",className:"h-3 w-3","aria-hidden":"true"}),"Restore"]})]},v.id))})]})})});w4.displayName="RevertedMessageDock";const kD=({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(V,{name:"attachment-2",className:R(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"})]})}),MD={type:"file",multiple:!0,accept:HS};function ID({inputRef:e,onChange:t}){return l.jsx("input",{ref:e,...MD,className:"hidden",onChange:t})}function _D({available:e,disabled:t,className:n,iconClassName:r,onStart:s}){return e?l.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:n,disabled:t,onClick:s,title:"Start dictation","aria-label":"Start dictation",children:l.jsx(V,{name:"mic",className:R("size-4",r)})}):null}const ED=48,Hc=2,jD=1,V0=Hc+jD,pf=.08,yo=512,TD=2,AD=(e,t)=>{e.values[e.cursor]=t,e.cursor=(e.cursor+1)%yo,e.count=Math.min(yo,e.count+1)},LD=(e,t)=>{const n=Math.min(e.count,t),r=(e.cursor-n+yo)%yo;return Array.from({length:n},(s,o)=>e.values[(r+o)%yo])},B0=(e,t,n,r,s)=>{const o=Math.max(1,Math.round(Hc*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 ND({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:yo},()=>pf),cursor:0,count:0}),c=h.useCallback(()=>{const d=n.current,u=i.current;if(!d||u.width<=0||u.height<=0||!o.current)return;d.clearRect(0,0,u.width,u.height);const f=Math.max(1,Math.round(V0*u.pixelRatio)),p=Math.ceil(u.width/f),m=LD(a.current,p),g=p-m.length;for(let y=0;y<p;y+=1){const b=y>=g?m[y-g]:pf,k=u.width-Math.round(Hc*u.pixelRatio)-(p-1-y)*f;B0(d,k,u,b,o.current)}},[]);return h.useEffect(()=>{const d=t.current;if(!d)return;const u=d.getContext("2d",{alpha:!0});if(!u)return;n.current=u;const f=g=>{const y=Math.min(TD,Math.max(1,window.devicePixelRatio||1)),b={width:Math.max(1,Math.round(g*y)),height:Math.round(ED*y),pixelRatio:y},k=i.current;k.width===b.width&&k.height===b.height&&k.pixelRatio===b.pixelRatio||(i.current=b,d.width=b.width,d.height=b.height,o.current=getComputedStyle(d).color,c())},p=new ResizeObserver(g=>{const y=g[0]?.contentRect.width;typeof y=="number"&&y>0&&f(y)});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 f=t.current,p=n.current,m=i.current;if(!f||!p||m.width<=0||!o.current)return;const g=Math.max(pf,s.current),y=Math.max(1,Math.round(V0*m.pixelRatio));m.width>y&&(p.globalCompositeOperation="copy",p.drawImage(f,y,0,m.width-y,m.height,0,0,m.width-y,m.height),p.globalCompositeOperation="source-over"),p.clearRect(Math.max(0,m.width-y),0,y,m.height),B0(p,m.width-Math.round(Hc*m.pixelRatio),m,g,o.current),AD(a.current,g)},u=e(f=>{s.current=f,r.current===null&&(r.current=requestAnimationFrame(d))});return()=>{u(),r.current!==null&&cancelAnimationFrame(r.current)}},[e]),l.jsx("canvas",{ref:t,className:"h-12 w-full text-primary","aria-hidden":"true"})}const RD=e=>`${Math.floor(e/60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`;function PD({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:RD(t)})]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:n,onClick:o,title:"Cancel dictation","aria-label":"Cancel dictation",children:l.jsx(V,{name:"close",className:R("size-4",r)})}),l.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:R(n,"text-primary hover:text-primary"),onClick:i,disabled:!a,title:"Finish dictation","aria-label":"Finish dictation",children:l.jsx(V,{name:"check",className:R("size-4",r)})})]})}function DD({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(ND,{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 OD=3e4;let Dh=null,Ci=null;const AW=()=>{Dh=null,Ci=null},HD=async e=>{const t=X();if(!e?.fresh){const r=Dh;if(r&&r.key===t&&Date.now()<r.expiresAt)return r.status;const s=Ci;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&&X()===t&&(Dh={key:t,status:s,expiresAt:Date.now()+OD}),s})();e?.fresh||(Ci={key:t,promise:n});try{return await n}finally{Ci?.promise===n&&(Ci=null)}},FD=`
98
- class PiChamberDictationProcessor extends AudioWorkletProcessor {
99
- constructor() {
100
- super();
101
- this.outputRate = 16000;
102
- this.step = sampleRate / this.outputRate;
103
- this.position = 0;
104
- this.source = [];
105
- this.pending = [];
106
- this.chunkSamples = 4000;
107
- this.port.onmessage = (event) => {
108
- if (event.data && event.data.type === 'flush') {
109
- if (this.pending.length > 0) {
110
- const samples = Int16Array.from(this.pending.splice(0));
111
- this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
112
- }
113
- this.port.postMessage({ type: 'flushed' });
114
- }
115
- };
116
- }
117
- process(inputs) {
118
- const input = inputs[0] && inputs[0][0];
119
- if (!input || input.length === 0) return true;
120
- let sum = 0;
121
- for (let i = 0; i < input.length; i += 1) { this.source.push(input[i]); sum += input[i] * input[i]; }
122
- this.port.postMessage({ type: 'level', value: Math.min(1, Math.sqrt(sum / input.length) * 3) });
123
- while (this.position + 1 < this.source.length) {
124
- const index = Math.floor(this.position);
125
- const fraction = this.position - index;
126
- const sample = this.source[index] + (this.source[index + 1] - this.source[index]) * fraction;
127
- const clamped = Math.max(-1, Math.min(1, sample));
128
- this.pending.push(clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767));
129
- this.position += this.step;
130
- }
131
- const consumed = Math.floor(this.position);
132
- if (consumed > 0) { this.source.splice(0, consumed); this.position -= consumed; }
133
- while (this.pending.length >= this.chunkSamples) {
134
- const samples = Int16Array.from(this.pending.splice(0, this.chunkSamples));
135
- this.port.postMessage({ type: 'chunk', buffer: samples.buffer }, [samples.buffer]);
136
- }
137
- return true;
138
- }
139
- }
140
- registerProcessor('pichamber-dictation', PiChamberDictationProcessor);
141
- `,VD=16e3,$0=4e3,S4=()=>typeof window>"u"?null:window.AudioContext??window.webkitAudioContext??null,mf=e=>{try{e?.disconnect()}catch{}};class BD{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=S4();if(!t||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone recording is not supported");const n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});if(this.cancelled)throw n.getTracks().forEach(o=>o.stop()),new Error("Dictation cancelled");this.stream=n,this.options.onPermissionGranted?.();const r=new t;this.context=r,r.state==="suspended"&&await r.resume(),this.source=r.createMediaStreamSource(n),this.gain=r.createGain(),this.gain.gain.value=0;let s=null;if(r.audioWorklet&&typeof AudioWorkletNode<"u"){const o=URL.createObjectURL(new Blob([FD],{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/VD;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,u=Math.max(-1,Math.min(1,d));this.pendingFallback.push(u<0?Math.round(u*32768):Math.round(u*32767)),this.fallbackPosition+=o}const i=Math.floor(this.fallbackPosition);for(this.fallbackCarry=s.slice(i),this.fallbackPosition-=i;this.pendingFallback.length>=$0;)this.chunk(Int16Array.from(this.pendingFallback.splice(0,$0)))}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),mf(this.source),mf(t),mf(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 $D=()=>!!(S4()&&navigator.mediaDevices?.getUserMedia),gf=1,zD=300*16e3*2,z0=(e,t)=>{const n=new Uint8Array(4+t.byteLength);return new DataView(n.buffer).setUint32(0,e,!0),n.set(t,4),n},UD=()=>typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${crypto.getRandomValues(new Uint32Array(4)).join("-")}`;class ZD{constructor(t,n,r){this.providerConfigId=t,this.onState=n,this.onError=r}recordingId=UD();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>zD){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===gf&&this.socket.send(z0(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===gf&&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 S7();if(this.cancelled||t!==this.generation)return;const r=C7(k7().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(z0(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||M7(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!==gf||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 WD(){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),u=h.useRef("local"),f=h.useRef(0),p=h.useRef(0),m=h.useCallback(async()=>{const x=await HD();u.current=x.config?.providerConfigId||"local",o(x.config?.enabled===!0&&$D())},[]);h.useEffect(()=>(m().catch(()=>{}),pn(()=>{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(!f.current||e!=="recording"&&e!=="reconnecting")return;const x=()=>a(Math.min(300,Math.floor((Date.now()-f.current)/1e3)));x();const C=window.setInterval(x,250);return()=>window.clearInterval(C)},[e]);const g=h.useCallback(x=>{r(x.message),t("error"),c.current?.stop(),c.current=null},[]),y=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,C=new ZD(u.current,w=>{p.current===x&&t(w)},w=>{p.current===x&&g(w)}),S=new BD({onChunk:w=>C.append(w),onPermissionGranted:()=>{p.current===x&&(f.current=Date.now(),t("recording"))}});d.current=C,c.current=S;try{await S.start(),C.begin()}catch(w){if(C.cancel(),await S.stop().catch(()=>{}),p.current!==x)return;d.current=null,c.current=null,f.current=0;const M=w instanceof Error?w:new Error(String(w));throw r(M.name==="NotAllowedError"?"Microphone access was denied":M.message),t("error"),M}},[s,e,g]),b=h.useCallback(async()=>{const x=d.current,C=c.current;if(!x||!C)throw new Error("No dictation recording is active");const S=p.current;t("transcribing");try{if(await C.stop(),p.current!==S||d.current!==x)throw new Error("Dictation cancelled");c.current=null;const w=await x.finish();if(p.current!==S)throw new Error("Dictation cancelled");return d.current=null,f.current=0,t("idle"),r(null),w}catch(w){const M=w instanceof Error?w:new Error(String(w));throw p.current===S&&(r(M.message),t("error")),M}},[]),k=h.useCallback(()=>{p.current+=1,d.current?.cancel(),d.current=null,c.current?.stop(),c.current=null,f.current=0,a(0),r(null),t("idle")},[]);h.useEffect(()=>k,[k]);const v=h.useCallback(x=>c.current?.subscribeLevel(x)??(()=>{}),[]);return{state:e,error:n,available:s,elapsedSeconds:i,start:y,finish:b,cancel:k,subscribeLevel:v}}const qD=ys(()=>mt(()=>import("./GitHubLinkPicker-Bh9RO1yK.js"),__vite__mapDeps([58,5,1,6,59,17,11,8,18,19,20,60,23,61,43,42])).then(e=>({default:e.GitHubLinkPicker}))),GD=ys(()=>mt(()=>import("./ToolOutputDialog-VlS12Xyq.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]))),KD=5,YD=16,XD=4,JD=560,U0=h.memo(cL),QD=h.memo(Ax),eO=e=>{const t=ve.getState(),n=t.newSessionDraft?.open?t.newSessionDraft.directoryOverride:null,r=e?t.getDirectoryForSession(e)??t.currentSessionDirectory:n??tt.getState().currentDirectory;return Eo(X(),r,e)},C4=({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=ve.getState().currentSessionId,le=eO(H),Le=od(le);return r.current=le,s.current=Le,Le.text&&(n.current=Le.text),Le.text}),a=h.useRef(s.current.confirmedMentions),[c,d]=h.useState("normal"),[u,f]=h.useState(null),[p,m]=h.useState(""),[g,y]=h.useState(null),b=h.useCallback(()=>f(null),[]);h.useEffect(()=>{u!=="command"&&y(H=>H===null?H:null)},[u]);const k=u==="command"?g?.listboxId:void 0,v=!!k,[x,C]=h.useState(null),[S,w]=h.useState(null),[M,I]=h.useState(""),E=h.useRef(null),_=h.useRef(vP()).current;h.useEffect(()=>()=>{_.view?.destroy(),_.view=null},[_]);const T=h.useRef(null),A=h.useRef(0),j=h.useRef(null),N=h.useRef(!1),O=h.useRef(null),L=h.useRef(!1),P=h.useRef(null),W=h.useRef(null),F=h.useRef(null),q=h.useRef(o),K=h.useRef(r.current),Q=h.useRef((...H)=>Promise.resolve(ve.getState().sendMessage(...H))).current,D=ve(H=>H.currentSessionId),Y=Ke(H=>D?H.sessionLoadErrorById.get(D)?.code??null:null,void 0,D?`session:${D}`:"chrome")==="SESSION_IN_USE",ne=Ke(H=>{if(!D)return;const le=H.reducer.bySession.get(D);if(!le)return;const Le=le.extensionEditorOps??(le.extensionEditor?[le.extensionEditor]:void 0);if(!(!Le||Le.length===0))return{sessionId:D,ops:Le}},(H,le)=>H===le?!0:!H||!le||H.sessionId!==le.sessionId||H.ops.length!==le.ops.length?!1:H.ops.every((Le,ze)=>Le.sequence===le.ops[ze]?.sequence&&Le.text===le.ops[ze]?.text&&Le.mode===le.ops[ze]?.mode),D?`session:${D}`:"chrome"),$=h.useRef(new Map);h.useEffect(()=>{if(!D||!ne||ne.sessionId!==D)return;const{ops:H}=ne;if(!H||H.length===0)return;const le=$.current.get(D)??-1,Le=H.filter(He=>He.sequence>le);if(Le.length===0)return;let ze=le;for(const He of Le)He.sequence>ze&&(ze=He.sequence);let Ue=-1;for(let He=Le.length-1;He>=0;He--)if(Le[He]?.mode!=="paste"){Ue=He;break}if(Ue!==-1){const He=Le[Ue],Ye=Le.slice(Ue+1).map(zn=>zn.text).join(""),bt=He.text+Ye;a.current.clear(),i(bt),b()}else for(const He of Le){const Ye=E.current;Ye?(Ye.insertText(He.text),Ye.focus({preventScroll:!0})):i(bt=>bt+He.text)}$.current.set(D,ze),Je().consumeExtensionEditor(D,ze)},[b,D,ne]);const J=tt(H=>H.currentDirectory),G=Vn()??J,ue=ve(h.useCallback(H=>D?H.getDirectoryForSession(D):null,[D])),B=X();zT({sessionId:D,directory:ue??G,text:o}),h.useEffect(()=>(vc(),kr.getState().loadSkills(),pn(()=>{vc(),kr.getState().loadSkills()})),[G]);const ie=h.useMemo(()=>Eo(B,ue??G,D),[B,G,ue,D]),xe=ve(H=>H.newSessionDraft),de=!!xe?.open,Se=ve(H=>H.sendingNewSessionDraftId),je=g3(xe,D,Se);ve(H=>H.openNewSessionDraft);const Oe=ve(H=>H.abortPromptSessionId),Be=ve(H=>H.clearAbortPrompt),Ie=Ge(H=>H.attachedFiles),fe=Ge(H=>H.addAttachedFile),ee=Ge(H=>H.detachAttachedFiles),he=Ge(H=>H.consumePendingInputText),Ce=Ge(H=>H.pendingStarterInsert),Ae=Ge(H=>H.pendingInputText),Me=Ge(H=>H.pendingRevertText),Ze=Ge(H=>H.consumePendingRevertText),gt=Ge(H=>H.consumePendingSyntheticParts),we=ve(H=>H.acknowledgeSessionAbort),re=h.useCallback(H=>m3(H??D??""),[D]),ge=qe(H=>H.currentProviderId),pe=qe(H=>H.currentModelId),ke=qe(H=>H.getModelMetadata);qe(H=>H.modelsMetadata),qe(H=>H.providers);const _e=ge&&pe?ke(ge,pe):void 0,Te=qe(H=>H.currentVariant),be=se(H=>H.isMobile),ae=WD(),te=h.useRef({start:0,end:0}),oe=h.useRef(null),me=ae.state==="requesting-permission"||ae.state==="recording"||ae.state==="reconnecting"||ae.state==="transcribing",We=Ed()==="mini-chat";_k();const{enabled:ct}=yd(),Lt=be&&!ct,Ut=se(H=>H.setImagePreviewOpen),xs=se(H=>H.inputBarOffset),Ca=se(H=>H.isExpandedInput),ka=se(H=>H.setExpandedInput),Rd=se(H=>H.setTimelineDialogOpen),{git:En}=ma(),{currentTheme:Kt}=Fn(),To=t4(),Nt=Id(G),on=yt(H=>G?H.directories.get(G)?.status??null:null),Ao=yt(H=>H.ensureStatus),Lo=yt(H=>H.fetchStatus),No=yt(H=>H.clearDiffCache),[bs,Ma]=h.useState(!1),Pr=h.useRef(async()=>{}),jn=JP({activeRuntimeKey:B,intent:xe?.branchIntent,onReady:H=>{Pr.current(H)}}),mn=QP({taskId:xe?.id,intent:xe?.worktreeIntent}),[ws,Ss]=h.useState(!1),[Bt,Cs]=h.useState({open:!1,title:"",content:""}),[Ht,Dr]=h.useState(!1);h.useEffect(()=>{Bt.open&&Dr(!0)},[Bt.open]);const Ia=h.useRef({modelKey:`${ge??""}/${pe??""}`,modalitySignature:_e?.modalities?.input?.slice().sort().join(",")??null,attachmentIds:new Set});h.useEffect(()=>{const H=`${ge??""}/${pe??""}`,le=_e?.modalities?.input,Le=le?.slice().sort().join(",")??null,ze=Ia.current,Ue=ze.modelKey!==H,He=ze.modalitySignature===null&&Le!==null,Ye=Ue||He?Ie:Ie.filter(at=>!ze.attachmentIds.has(at.id));if(Ia.current={modelKey:H,modalitySignature:Le,attachmentIds:new Set(Ie.map(at=>at.id))},!le||Ye.length===0)return;const bt=VS(Ye,le);if(bt.length===0)return;const zn=Array.from(new Set(bt.map(({modality:at})=>at))),cr={text:"Text",image:"Image",pdf:"PDF",audio:"Audio",video:"Video"},As=bt.map(({attachment:at})=>at.filename),qd=As.length>3?`${As.slice(0,3).join(", ")} (+${As.length-3})`:As.join(", ");Ne.warning(`${_e.name??pe??""} does not support ${zn.map(at=>cr[at]).join(", ")} input required by ${qd}. You can still send the message, but these attachments may be ignored.`,{id:`attachment-modalities:${H}`})},[Ie,pe,_e,ge]);const ks=h.useCallback(H=>{H.image&&(Cs(H),Ut(!0))},[Ut]),_a=h.useCallback(H=>{Cs(le=>({...le,open:H})),Ut(H)},[Ut]);h.useEffect(()=>{!G||!En||Ao(G,En)},[G,En,Ao]),h.useEffect(()=>{if(!(!G||!En))return kd.onGitRefreshHint(H=>{Wt(H.directory)===Wt(G)&&(H.paths?.length&&No(G,H.paths),Lo(G,En,{silent:!0}))})},[No,G,En,Lo]);const Ro=!1,ar=Ca&&be,gn=ar,[Pd,Or]=h.useState(1),Bn=!be&&!We,Po=!!(de&&Bn&&!gn),Ms=!be&&!gn&&!Bn,lr=be||Bn?"1.5rem":"9999px",Do=be||ws;h.useEffect(()=>{const H=j.current;if(!H)return;const le=ze=>{const Ue=ze>0&&ze<JD;Ss(He=>He===Ue?He:Ue)};if(le(H.clientWidth),typeof ResizeObserver>"u"){const ze=()=>le(H.clientWidth);return window.addEventListener("resize",ze),()=>window.removeEventListener("resize",ze)}const Le=new ResizeObserver(ze=>{le(ze[0]?.contentRect.width??H.clientWidth)});return Le.observe(H),()=>Le.disconnect()},[]);const Oo=h.useMemo(()=>new Set,[]),{commands:Ea}=n4(G),ja=h.useMemo(()=>{const H=new Set;for(const le of Ea)H.add(le.invocationName.toLowerCase());return H},[Ea]),Ho=Cr(H=>H.snippets),Ta=Cr(H=>H.loadSnippets);h.useEffect(()=>{Ta(G)},[G,Ta]);const Aa=h.useMemo(()=>{const H=new Set;for(const le of Ho){H.add(le.name.toLowerCase());for(const Le of le.aliases??[])H.add(Le.toLowerCase())}return H},[Ho]),La=h.useMemo(()=>Ie.map(H=>H.filename),[Ie]),Dd=h.useMemo(()=>({inputMode:c,knownAgentNames:Oo,confirmedMentions:a.current,knownSlashNames:ja,knownSnippetTriggers:Aa,attachmentFilenames:La}),[La,c,Oo,ja,Aa]),Fo=h.useCallback(H=>[...H??[]].map(le=>({...le,dataUrl:le.source==="server"&&le.serverPath?$E(le.serverPath):le.dataUrl})),[]),Od=h.useCallback(H=>({sanitizedText:H,attachments:[]}),[]),Tn=h.useRef(null),Z=h.useRef(!1),ye=D?rp(D,ue??G):null,Pe=lt(H=>H.followUpBehavior),$e=lt(H=>H.addToQueue),rt=OP(Bk(D??""));h.useEffect(()=>{q.current=o},[o]),h.useEffect(()=>{K.current=ie},[ie]);const{persistNow:nt}=FP({message:o,messageRef:q,setMessage:i,confirmedMentionsRef:a,identity:ie,persistEnabled:!0,initialDraft:{text:n.current??"",identity:r.current},onIdentityChange:()=>d("normal"),onDraftRestored:()=>E.current?.selectAll()});h.useEffect(()=>{const H=ie?Gt(ie):"";Ge.getState().activateAttachmentsDraft(H)},[ie]);const ot=Ge(H=>H.sentDraftClear);h.useEffect(()=>{if(!ot)return;const H=ie?Gt(ie):"";if(!H||ot.draftKey!==H)return;Ge.getState().consumeSentDraftClear(ot.nonce);const le=E.current?.getValue()??q.current;pC(ot,H,le)&&(a.current.clear(),rt.reset(),i(""))},[ot,ie,rt]);const Ve=h.useRef(de);h.useEffect(()=>{!Ve.current&&de&&requestAnimationFrame(()=>{be?E.current?.focus({preventScroll:!0}):E.current?.focus()}),Ve.current=de},[de,be]);const{phase:Xe}=Zp();h.useEffect(()=>{if(Ae!==null){const H=he();H?.text&&(H.mode==="append"?i(le=>{const Le=H.text;return Le.trim()?xP(le,Le):le}):H.mode==="append-inline"?i(le=>f4(le,H.text)):i(H.text),setTimeout(()=>{E.current?.focus()},0))}},[Ae,he]),h.useEffect(()=>{if(Me!==null){const H=Ze();H&&o.trim().length===0&&(i(H),setTimeout(()=>{E.current?.focus()},0))}},[Me,Ze,o]);const Ct=Ge(H=>H.pendingWorktreeRestore),Rt=Ge(H=>H.consumePendingWorktreeRestore);h.useEffect(()=>{if(Ct===null)return;const H=Rt();if(!H)return;const le=J_(H,q.current??"");if(le.ok)a.current=new Set(H.confirmedMentions),q.current=H.prompt,i(H.prompt),b(),setTimeout(()=>{E.current?.focus()},0);else{const Le=X_(le,"pending-composer");Le&&Ne.error(Le.title,{description:Le.description})}},[Ct,Rt,b]);const an=o.trim().length>0||Ie.length>0,An=!!(ge&&pe),Is=ef(Ie),_s=$x(),Vo=(_s?"Connection lost. Waiting to reconnect — your draft is kept.":null)??(N2(Ie)?"Uploading attachments…":lT(Ie)||Ie.length>0&&!Is?"Retry or remove failed attachments":null),Hr=an&&An&&Is&&!_s,Ln=!!(mn.state&&mn.state.phase!=="failed")||je||Y,Ts=!D&&!de||Ln,Yb=Xe!=="idle",Bo=h.useCallback(()=>{const H=E.current?.getValue()??o;return{message:H,hasContent:H.trim().length>0||Ie.length>0}},[Ie.length,o]),$o=h.useRef(!1),Na=h.useCallback(async()=>{if(Dc()){Ne.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const H=Bo();if($o.current||!H.hasContent||!D||!ye||!ef(Ie))return;$o.current=!0;let le;try{le=await Uv(Fo(Ie))}catch{Ne.error("Attachment data could not be saved for the follow-up."),$o.current=!1;return}const Le=H.message.replace(/^\n+|\n+$/g,""),ze=D?_t.getState().getSessionAgentSelection(D)??void 0:void 0;if(!$e(ye,{content:Le,attachments:le.length>0?le:void 0,sendConfig:ge&&pe?{providerID:ge,modelID:pe,agent:ze,variant:Te??void 0}:void 0})){$o.current=!1,Ne.error("Follow-up limit reached. Remove a pending message before adding another.");return}(E.current?.getValue()??q.current)===H.message&&i(""),le.length>0&&ee(le.map(He=>He.id)),$o.current=!1,be||E.current?.focus()},[Bo,D,ye,Ie,Fo,$e,ee,be,ge,pe,Te]),Xb=h.useCallback(H=>{i(H),setTimeout(()=>{E.current?.focus()},0)},[]),Jb=h.useCallback(H=>{Pr.current({queuedOnly:!0,queuedMessageId:H,delivery:"steer"})},[]),Qb=(H,le)=>{const Le=H instanceof Error?H.message:"";return Le.toLowerCase().includes("runtime changed")?"Message failed to send. Attachments restored.":Le||le},zm=async H=>{if(Dc()){Ne.error("Connection lost. Waiting to reconnect — your draft is kept.");return}const le=H?.queuedOnly??!1,Le=H?.queuedMessageId,ze=H?.delivery==="steer"?"steer":void 0,Ue=ye;let He=null;if(!(le&&(!Ue||!Le||(He=lt.getState().claimQueuedMessage(Ue,Le),!He)))){try{if(!le&&!ef(Ie)){N2(Ie)?Ne.info("Uploading attachments…"):Ne.error("Retry or remove failed attachments");return}const Ye=H?.presetText!=null&&!le?{message:H.presetText,hasContent:H.presetText.trim().length>0||Ie.length>0}:le?{message:"",hasContent:!1}:Bo();if(le){if(!D)return}else if(!Ye.hasContent||!D&&!de)return;const bt=le?He?.sendConfig:void 0,zn=bt?.providerID??ge,cr=bt?.modelID??pe,As=bt?.agent,qd=le?bt?.variant:Te;if(!zn||!cr){console.warn("Cannot send message: provider or model not selected"),Ne.error("Select a provider and model before sending a message.");return}const at=ve.getState().newSessionDraft,Ha=!Ue&&!le&&!Le&&at?.open===!0,Fa=()=>ve.getState().newSessionDraft.id===at.id&&ve.getState().currentSessionId===null,Gd=(c==="normal"?T0(Ye.message):null)?.name==="compact",l1=!!(Ha&&at.worktreeIntent&&!Gd),Vr=l1?new Set(a.current):null;let ln=null;if(Ha){if(at.id&&ve.getState().sendingNewSessionDraftId===at.id)return;if(ve.getState().setSendingNewSessionDraftId(at.id),l1){try{ln=await K_(Ie)}catch{ve.getState().sendingNewSessionDraftId===at.id&&ve.getState().setSendingNewSessionDraftId(null),Ne.error("Attachment data could not be saved for the worktree send.");return}q.current="",i(""),a.current.clear(),nt(ie,"")}await new Promise(Br=>{let Zt=!1;const Xt=()=>{Zt||(Zt=!0,Br())};typeof window<"u"&&typeof window.requestAnimationFrame=="function"&&window.requestAnimationFrame(()=>Xt()),setTimeout(()=>Xt(),50)})}try{const Br=!Ue&&!H?.queuedOnly&&!H?.queuedMessageId&&at?.open&&!Gd?at.worktreeIntent:null;let Zt=mn.getReceipt(Br);if(Br&&!Zt){const et=mn.request({intent:Br,prompt:Ye.message,failedSend:{prompt:Ye.message,confirmedMentions:Vr?[...Vr]:[],attachments:ln??[]}});if(ln&&ln.length>0&&ee(ln.map(wt=>wt.id)),Ne.info("Worktree queued",at.id?{id:`worktree-queued:${at.id}`}:void 0),ve.getState().openNewSessionDraft(),se.getState().setActiveMainTab("chat"),Zt=await et,!Zt){if((at.id?en.getState().getEntryByKey(at.id):en.getState().getEntry(Br))?.failedSend){Ne.error("Worktree creation failed",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}if(Fa()){if(q.current=Ye.message,a.current=Vr??new Set,i(Ye.message),us(ie,Ye.message,Vr??[]),ln){const vt=Ge.getState().restoreAttachmentsForRetry(ln);if(!vt.ok){const yn=vh({limit:vt.limit,currentCount:vt.currentCount,missingCount:vt.missingCount});Ne.error(yn.title,{description:yn.description})}}}else Ne.error("Worktree creation failed",{description:"Your prompt was not sent."});return}}const Xt=Zt?at.id??V3(Br):null,dr=Xt?en.getState().getEntryByKey(Xt)?.failedSend??null:null,Va=!Ue&&!H?.queuedOnly&&!H?.queuedMessageId&&at?.open&&!Gd?at.branchIntent:null;if(Va&&!jn.getReceipt(Va)){if(jn.dialogState)return;await jn.request({intent:Va,projectId:at.selectedProjectId,continuation:H});return}const Kd=jn.getReceipt(Va),c1=le&&Ue&&He?{target:Ue,delivery:"steer",operationId:He.id}:Ue?{target:Ue,...ze?{delivery:ze}:{}}:ze||Kd||Zt?{...ze?{delivery:ze}:{},...Kd?{branchCheckoutReceipt:Kd}:{},...Zt?{worktreeCreationReceipt:Zt,draftSnapshot:at}:{}}:void 0,d1=gt(),Mw=new Set(kr.getState().skills.map(et=>et.name)),Yd=AP(le&&He?{queued:[{content:He.content,attachments:He.attachments}],composerText:null,composerAttachments:[],syntheticTexts:d1?.map(et=>et.text)??[]}:{queued:[],composerText:Ye.hasContent?Ye.message:null,composerAttachments:Y_(ln,Ie),syntheticTexts:d1?.map(et=>et.text)??[]},{parseAgentMention:et=>({text:et}),extractFileMentions:et=>{const{sanitizedText:wt,attachments:vt}=Od(et);return{text:wt,attachments:vt}},sanitizeAttachments:Fo,collectSkillNames:et=>jP(et,Mw),buildSkillInstruction:TP});let Ba=Yd.primaryText;const{primaryAttachments:u1,additionalParts:Uo}=Yd;if(Yd.isEmpty){!le&&Xt&&dr&&Zt&&eE(Xt,dr,"Prompt was empty and was not sent.")&&Ne.error("Prompt was empty and was not sent.",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const $a=()=>!Zt||Fa();!le&&$a()&&(rt.reset(),ka(!1)),be&&$a()&&E.current?.blur();const za=c==="normal"?T0(Ba):null;if(za&&await NP({command:za,currentSessionId:D,scrollToBottom:t,setTimelineDialogOpen:Rd,onUndoSession:async wt=>{await ve.getState().handleSlashUndo(wt)},onRedoSession:async wt=>{await ve.getState().handleSlashRedo(wt)},onCompactSession:async(wt,vt)=>{try{await lM(),await cM(wt,vt)}catch(yn){Ne.error(Qb(yn,"Failed to compact session"))}}})){!le&&Xt&&dr&&Zt&&tE(Xt,dr,ln,Ie),$a()&&(nt(ie,""),i(""),a.current.clear());return}let Xd=!!(Ha&&za&&!p4(za.name))?{...c1,initialInputKind:"extension-command"}:c1;const f1=Ue?.directory??G,h1=await tR({newSessionDraftOpen:de,sessionId:Ue?.sessionId??D,getStoreState:()=>Je().getState()});if(h1&&Uo.push({text:nR(h1),synthetic:!0}),c!=="shell")try{const et=Cr.getState().expandText;Ba=et(Ba,f1);for(const wt of Uo)wt.synthetic||(wt.text=et(wt.text,f1))}catch(et){console.warn("[ChatInput] Failed to expand snippets, sending original text:",et)}const Iw=[...u1,...Uo.flatMap(et=>et.attachments??[])],p1=B3(ln,Ie);if(le&&Ue&&He){const et=lt.getState().markDeliveryAttempt(Ue,He.id,"steer");if(!et?.streamEpoch){lt.getState().markSendUnconfirmed(Ue,He.id,"steer"),Ne.error("Follow-up status uncertain. Check status before retrying.");return}Xd={...Xd,streamEpoch:et.streamEpoch}}const _w=Q(Ba,zn,cr,As,u1,void 0,Uo.length>0?Uo:void 0,qd,c,Xd);jn.clearReceipt(),typeof window>"u"?t?.():window.requestAnimationFrame(()=>{t?.()}),await _w.then(()=>{if(le&&Ue&&He&&lt.getState().completeQueuedSend(Ue,He.id),!le&&Xt&&dr&&en.getState().markWorktreePromptSucceeded(Xt,dr),!le&&p1.length>0&&ee(p1),!le&&$a()){const et=ie?Gt(ie):"",wt=K.current,vt=wt?Gt(wt):"",yn=E.current?.getValue()??q.current,Ua=!yn||yn===Ye.message;et===vt?(nt(ie,Ua?"":yn),Ua&&(i(""),a.current.clear(),rt.reset()),Ge.getState().publishSentDraftClear(et,Ye.message)):nt(ie,"")}}).catch(et=>{if(le&&Ue&&He){if(ex(et)){lt.getState().markSendUnconfirmed(Ue,He.id,"steer"),console.warn("Follow-up send unconfirmed:",et),Ne.error("Follow-up status uncertain. Check status before retrying.");return}lt.getState().markSendFailed(Ue,He.id)}const wt=et instanceof Error?et.message:typeof et=="string"?et:String(et??""),vt=wt.toLowerCase();if(console.error("Message send failed:",wt||et),!le&&Xt&&dr&&Zt){const Ls=wt||"Prompt failed to send.";en.getState().markWorktreePromptFailed(Xt,dr,Ls),Ne.error("Prompt failed to send",{description:"Your prompt was kept in Background tasks. Use Restore draft to retry."});return}const yn=E.current?.getValue()??q.current;if(Fa()&&Ye.message&&(!yn||yn===Ye.message)&&(Vr&&(a.current=Vr),i(Ye.message),us(ie,Ye.message,Vr??a.current)),Fa()&&ln){const Ls=Ge.getState().restoreAttachmentsForRetry(ln);if(!Ls.ok){const m1=vh({limit:Ls.limit,currentCount:Ls.currentCount,missingCount:Ls.missingCount});Ne.error(m1.title,{description:m1.description})}}const Ua=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")){Ne.error("Attachments are too large to send. Please try reducing the number or size of images.");return}if(Ua){Iw.length>0&&Ne.error("Failed to send attachments. Try fewer files or smaller images.");return}if(vt.includes("runtime changed")){Ne.error("Message failed to send. Attachments remain available.");return}Ne.error(wt||"Message failed to send. Attachments remain available.")})}finally{Ha&&ve.getState().sendingNewSessionDraftId===at.id&&ve.getState().setSendingNewSessionDraftId(null)}}finally{le&&Ue&&He&&lt.getState().clearSending(Ue,He.id)}be||E.current?.focus()}};Pr.current=zm;const Um=h.useCallback(()=>{const H=Bo(),le=c==="normal"&&H.hasContent&&D&&Xe!=="idle";Pe==="queue"&&le?Na():Pe==="steer"&&le?Pr.current({delivery:"steer"}):Pr.current()},[c,Bo,D,Xe,Pe,Na]),Yt=h.useCallback((H,le,Le="manual",ze)=>{const Ue=mR(H,le,{inputMode:c,inputSource:Le,insertedText:ze});f(Ue?.kind??null),m(Ue?.query??"")},[c]),Ra=h.useCallback(H=>{const le=()=>{try{E.current?.focus({preventScroll:!0})}catch{E.current?.focus()}E.current?.setSelection(H)};requestAnimationFrame(()=>{le(),requestAnimationFrame(le)}),setTimeout(le,60)},[]),Hd=h.useCallback(H=>{const le=H.trim();if(!le)return;const Le=`/${le} `,ze=E.current,Ue=ze?.getValue()??q.current??"",He=Ue.trim().length>0?`${Le}${Ue.replace(/^\s+/,"")}`:Le,Ye=Le.length;if(ze)try{ze.replaceRange(0,Ue.length,He,Ye)}catch{i(He),requestAnimationFrame(()=>ze.setSelection(Ye))}else i(He);Yt(He,Ye,"manual",Le),b(),Ra(Ye)},[b,Ra,i,Yt]),Fd=h.useCallback(H=>{const le=H.trim();if(!le)return;const Le=E.current,ze=Le?.getValue()??q.current??"",Ue=ze.trim().length>0,He=Ue?`${le} ${ze.replace(/^\s+/,"")}`:le,Ye=Ue?le.length+1:le.length;if(Le)try{Le.replaceRange(0,ze.length,He,Ye)}catch{i(He),requestAnimationFrame(()=>Le.setSelection(Ye))}else i(He);Yt(He,Ye,"manual"),b(),Ra(Ye)},[b,Ra,i,Yt]);h.useEffect(()=>{if(Ce==null)return;const H=Ge.getState().consumePendingStarterInsert();H&&("text"in H?Fd(H.text):Hd(H.name))},[Ce,Hd,Fd]);const ew=WP({inputMode:c,setInputMode:d,message:o,setMessage:i,openAutocomplete:u,commandRef:W,snippetRef:F,mentionRef:P,composerRef:E,messageHistory:rt,updateAutocompleteState:Yt,isMobile:be,hasContent:an,currentSessionId:D,sessionPhase:Xe,followUpBehavior:Pe,handleSubmit:zm,handleQueueMessage:Na}),{update:tw}=RP({enabled:Ro,openAutocomplete:u,message:o,editorRef:E,containerRef:j}),Pa=h.useCallback(()=>{Tn.current&&(clearTimeout(Tn.current),Tn.current=null),Ma(!0),Tn.current=setTimeout(()=>{Ma(!1),Tn.current=null},1800)},[]),nw=h.useCallback(()=>{Be(),Pa(),re(D||void 0)},[re,Be,D,Pa]),rw=h.useCallback((H,le="manual")=>{if(!H)return;const Le=E.current;if(!Le){const bt=o+H;i(bt),Yt(bt,bt.length,le,H);return}const{start:ze,end:Ue}=Le.getSelection(),He=`${o.substring(0,ze)}${H}${o.substring(Ue)}`,Ye=ze+H.length;Le.insertText(H),Yt(He,Ye,le,H)},[o,Yt]),sw=h.useCallback(()=>{const H=q.current.length;te.current=E.current?.getSelection()??{start:H,end:H},b(),ae.start().catch(()=>{})},[b,ae]),ow=h.useCallback(()=>{ae.finish().then(H=>{const le=q.current,Le=te.current,ze=Math.min(Math.max(0,Le.start),le.length),Ue=Math.min(Math.max(ze,Le.end),le.length),He=h4(H.trim(),le.slice(0,ze),le.slice(Ue));if(!He)return;const Ye=E.current;if(Ye)Ye.replaceRange(ze,Ue,He,ze+He.length),Ye.focus({preventScroll:!0});else{const bt=`${le.slice(0,ze)}${He}${le.slice(Ue)}`;i(bt),Yt(bt,ze+He.length,"manual",He)}}).catch(()=>{})},[ae,Yt]);h.useEffect(()=>{ae.state!=="error"||!ae.error||oe.current===ae.error||(oe.current=ae.error,Ne.error(ae.error))},[ae.error,ae.state]);const Vd=h.useCallback(()=>{N.current=!1,O.current&&(clearTimeout(O.current),O.current=null)},[]),iw=h.useCallback(()=>{N.current=!0,O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{N.current=!1,O.current=null},700)},[]),aw=({value:H,selection:le,fromPaste:Le,insertedText:ze})=>{const Ue=Le?ze:"",He=Ue.includes("@")||N.current;N.current&&Vd();const Ye=He?"paste":"manual";if(c==="normal"&&H.startsWith("!")){const bt=H.slice(1),zn=Math.max(0,le.start-1);d("shell"),i(bt),b();const cr=E.current;cr&&cr.getValue()!==bt?(cr.replaceRange(0,1,"",zn),b()):requestAnimationFrame(()=>E.current?.setSelection(zn));return}i(H),Yt(H,le.start,Ye,Ue)};h.useEffect(()=>()=>{Vd()},[Vd]);const lw=EP({inputMode:c,enabled:!!(D||de),composerRef:E,message:o,setMessage:i,insertTextAtSelection:rw,updateAutocompleteState:Yt,markFileMentionPasteSuppression:iw,attachedFiles:Ie,addAttachedFile:fe}),cw=h.useCallback(H=>ZE(H,To||""),[To]),{handleFileSelect:dw,handleSnippetSelect:uw,handleCommandSelect:fw}=BP({composerRef:E,message:o,setMessage:i,updateAutocompleteState:Yt,closeAutocomplete:b,confirmedMentionsRef:a,toMentionPath:cw});h.useEffect(()=>{D&&E.current&&!be&&E.current.focus()},[D,be]),h.useEffect(()=>{be||C(null)},[be]),h.useEffect(()=>{Oe&&Oe!==D&&Be()},[Oe,D,Be]),h.useEffect(()=>{L.current=!!(D||de)},[D,de]);const{isDragging:hw,isInternalDrag:pw,handleDragEnter:Zm,handleDragOver:Wm,handleDragLeave:mw,handleDragEnd:qm,handleDrop:Gm,handleDropCapture:Km}=_P({enabled:!!(D||de),composerRef:E,messageRef:q,cursorPosRef:A,confirmedMentionsRef:a,setMessage:i,addAttachedFile:fe}),Ym=h.useRef(null),Xm=h.useCallback(async H=>{const le=Array.isArray(H)?H:Array.from(H),Le=await Promise.all(le.map(async ze=>{try{return await fe(ze)}catch(Ue){return console.error("File attach failed",Ue),!1}}));le.length>0&&!Le.some(Boolean)&&Ne.error("Failed to attach file")},[fe]),Jm=h.useCallback(()=>{Ts||Ym.current?.click()},[Ts]),[Qm,e1]=h.useState(!1),gw=h.useCallback(()=>{Ts||e1(!0)},[Ts]),yw=h.useCallback(async H=>{const le=H.target.files;le&&(await Xm(le),H.target.value="")},[Xm]),vw="gap-x-1.5 gap-y-0",xw=!0,zo=(de||!!D)&&!We,{projects:t1,selectedDraftProject:Fr,selectedDraftBranchLabel:Bd,selectedBranchName:$d,draftBranchItems:n1,isDiscoveringDraftBranches:r1,shouldShowDraftBranchSelector:$n,worktreeMode:zd,handleDraftProjectChange:s1,handleDraftBranchChange:o1,handleWorktreeModeChange:Ud}=KP(zo),i1=!!(zo&&Fr&&(de||$n)),Da=h.useMemo(()=>We||Nt!==!0||!on||on.isClean?!1:Hx(on.files,on.diffStats,G).length>0,[G,on,Nt,We])?l.jsx(Bx,{align:i1?"end":"start"}):null,Zd=eD({isMobile:be,editorRef:E,formRef:T,controlsPanelOpen:!!x,attachMenuOpen:!1}),bw=Zd.focused;h.useEffect(()=>{I("")},[S]),tD({isMobile:be,isFullscreen:ar,isDraftScreen:de,isFocused:bw,formRef:T,editorRef:E});const ww=be?"px-1.5 py-1.5":Ms?"px-1.5 py-1":"px-3 py-2",Sw=be?"h-8 w-8":"h-6 w-6",Cw="h-4 w-4",kw=be?"h-6 w-6":"h-5 w-5",Oa="h-[18px] w-[18px]",a1="flex cursor-pointer items-center justify-center text-foreground transition-none outline-none focus:outline-none flex-shrink-0 disabled:cursor-not-allowed",Wd=R(a1,Sw);return h.useEffect(()=>{const H=!!Oe&&Oe===D;!Z.current&&H&&!bs&&(Pa(),D&&we(D)),Z.current=H},[Oe,we,D,bs,Pa]),h.useEffect(()=>()=>{Tn.current&&(clearTimeout(Tn.current),Tn.current=null)},[]),l.jsxs(l.Fragment,{children:[l.jsxs("form",{ref:T,onSubmit:H=>{H.preventDefault(),Um()},className:R("relative w-full pt-0 pb-4",Ro,ar&&"flex h-full min-h-0 flex-col pt-2",be&&"bottom-safe-area oc-mobile-composer"),style:be&&xs>0?{marginBottom:`${xs}px`}:void 0,children:[l.jsxs("div",{className:R("chat-input-column relative overflow-visible",gn&&"flex flex-1 min-h-0 flex-col"),children:[l.jsx(xx,{onEditMessage:Xb,onSendMessage:Jb}),l.jsx(w4,{sessionId:D,directory:ue??G}),l.jsx(QD,{showAbortStatus:bs,showAssistantStatus:!1,showTodos:xw,leftAccessory:i1||de||!Da?null:Da}),!Lt&&zo&&Fr&&(de||$n)?l.jsx("div",{inert:Ln||void 0,className:R(Ln&&"pointer-events-none opacity-60"),children:l.jsx(rD,{projects:t1,selectedProject:Fr,selectedBranchName:$d,selectedBranchLabel:Bd,branchOptions:n1,branchInteractive:de,branchLoading:r1,showBranchSelector:$n,showProjectSelector:de,showWorktreeSelector:de&&$n,worktreeMode:zd,endAccessory:Da,onProjectChange:s1,onBranchChange:o1,onWorktreeModeChange:Ud,theme:Kt})}):null,Lt&&zo&&Fr&&(de||$n)?l.jsx("div",{inert:Ln||void 0,className:R(Ln&&"pointer-events-none opacity-60"),children:l.jsx(sD,{selectedProject:Fr,selectedBranchName:$d,selectedBranchLabel:Bd,branchInteractive:de,showBranchSelector:$n,showProjectSelector:de,showWorktreeSelector:de&&$n,worktreeMode:zd,onWorktreeModeChange:Ud,endAccessory:Da,theme:Kt,onOpenPicker:w})}):null,l.jsx("div",{className:R(!be&&"contents",be&&"relative",ar&&"flex min-h-0 flex-1 flex-col"),children:l.jsx(l.Fragment,{children:l.jsxs("div",{className:R("flex flex-col relative overflow-visible",gn&&"flex-1 min-h-0",Bn&&!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:Km,onDragEnter:Zm,onDragOver:Wm,onDragLeave:mw,onDrop:Gm,onDragEnd:qm,children:[hw&&l.jsx(kD,{isInternalDrag:pw,iconButtonBaseClass:a1,iconSizeClass:Oa,radius:lr,isAttachmentDisabled:Ts,onPickLocalFiles:Jm}),je&&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(xD,{open:u,query:p,overlayPosition:null,commandRef:W,snippetRef:F,mentionRef:P,onCommandSelect:fw,onSnippetSelect:uw,onFileSelect:dw,onClose:b,onCommandComboboxStateChange:y}),l.jsx(CD,{isMobile:be,isInline:Ms,alignToolsEnd:Pd>1,sessionId:D,directory:ue??G,newSessionDraftOpen:de,messageLength:o.length,leadingExtra:Bn||be?l.jsx(U0,{keepLabels:!0,className:"w-max shrink-0",mobilePanel:be?x:void 0,onMobilePanelChange:be?C:void 0}):null,trailingExtra:me?null:l.jsx(_D,{available:ae.available,disabled:!D&&!de||Ln,className:Wd,iconClassName:Oa,onStart:sw}),actionsOverride:me?l.jsx(PD,{state:ae.state,elapsedSeconds:ae.elapsedSeconds,buttonClassName:Wd,iconClassName:Oa,isMobile:be,onCancel:ae.cancel,onDone:ow}):void 0,radius:lr,footerPaddingClass:ww,footerGapClass:vw,footerIconButtonClass:Wd,iconSizeClass:Oa,sendIconSizeClass:Cw,stopIconSizeClass:kw,canSend:Hr&&!Ln,isSending:je,isAttachmentDisabled:Ts,disabledReason:Vo,canAbort:Yb,hasContent:!!an,onOpenSettings:e,onPickLocalFiles:Jm,onLinkGitHub:gw,onPrimaryAction:Um,onQueueMessage:Na,onAbort:nw,children:me?l.jsx(DD,{state:ae.state,subscribeLevel:ae.subscribeLevel}):l.jsxs("div",{className:R("overflow-hidden",gn&&"flex flex-1 min-h-0 flex-col"),children:[l.jsx("div",{className:"relative z-10",children:l.jsx(yx,{onShowPopup:ks,isInline:Ms,isMobile:be})}),l.jsx("div",{className:R("relative overflow-hidden",gn&&"flex flex-1 min-h-0 flex-col"),onDragEnter:Zm,onDragOver:Wm,onDropCapture:Km,onDrop:Gm,onDragEnd:qm,children:l.jsx(yP,{ref:E,viewStore:_,"data-testid":"chat-input",value:o,languageContext:Dd,onChange:aw,onKeyDown:H=>(ew(H),H.defaultPrevented),onPaste:lw,onSelectionChange:H=>{A.current=H.start,tw()},onVisualLineCount:H=>{Or(le=>le===H?le:H)},onFocus:Zd.onEditorFocus,onBlur:Zd.onEditorBlur,placeholder:Y?"Session is open elsewhere":D||de?c==="shell"?"Enter shell command...":Po?"Plan, build, / for skills, @ for context":Do?"Use @ / ! # for helpers":"@ for files; / for commands, skills, and prompts; ! for shell; # for snippets":"Select or create a session to start chatting",editable:!!(D||de)&&!Ln,autoCorrect:!1,autoCapitalize:"none",spellCheck:be,fillContainer:gn,maxLines:be?YD:KD,boundSelector:be?"[data-composer-bound]":void 0,boundGapPx:XD,commandComboboxExpanded:v,commandComboboxListboxId:k,commandComboboxActiveOptionId:v?g?.activeOptionId:void 0,className:R("relative z-10",Ms?"min-h-0 px-1.5 py-1.5":"min-h-[52px] px-3",gn?R("h-full min-h-0",be?"py-2.5":"py-4"):be?Ie.length>0?"pt-1 pb-2.5":"py-2.5":Ms?void 0:Ie.length>0?"pt-1.5 pb-2":"pt-3 pb-2",c==="shell"?"font-mono":"typography-markdown md:typography-ui-label")})})]})})]})})}),Bn||be?null:l.jsx("div",{className:R("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(U0,{className:"w-full min-w-0"})})]}),de&&!Ro&&!be&&!We?l.jsx(e4,{onInsert:H=>H.ref.type==="text"?Fd(H.insertText):Hd(H.promptName),className:"chat-input-column mt-3"}):null]}),Ht?l.jsx(h.Suspense,{fallback:null,children:l.jsx(GD,{popup:Bt,onOpenChange:_a,isMobile:be})}):null,l.jsx(ID,{inputRef:Ym,onChange:yw}),l.jsx(iD,{state:jn.dialogState,onCancel:jn.cancel,onConfirm:()=>{jn.confirm()}}),Qm&&(ue??G)?l.jsx(h.Suspense,{fallback:null,children:l.jsx(qD,{directory:ue??G,open:Qm,onClose:()=>e1(!1)})}):null,Lt&&zo&&Fr?l.jsx(oD,{projects:t1,selectedProject:Fr,selectedBranchName:$d,selectedBranchLabel:Bd,branchOptions:n1,branchInteractive:de,branchLoading:r1,showBranchSelector:$n,showProjectSelector:de,showWorktreeSelector:de&&$n,worktreeMode:zd,onProjectChange:s1,onBranchChange:o1,onWorktreeModeChange:Ud,theme:Kt,openPicker:S,onOpenPickerChange:w,query:M,onQueryChange:I}):null]})};C4.displayName="ChatInput";const ii=h.memo(C4),Z0=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)"}),W0=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))"}),Oh=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)"}),q0=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 G0(e){if(e<0||e>255)return"var(--foreground)";if(e<16)return Oh[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 tO=/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|_[^\u0007\u001b]*(?:\u0007|\u001b\\)|[PX^_][^\u001b]*\u001b\\|[@-Z\\-_])/g;function kn(e){return e.replace(tO,"")}function k4(e){return e.includes("\x1B")}function nO(e){if(!e)return[];if(!k4(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(f=>f===""?0:parseInt(f,10));let u=0;for(;u<d.length;){const f=d[u];if(Number.isNaN(f)||f===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,u+=1;else if(f===1)n.bold=!0,u+=1;else if(f===2)n.dim=!0,u+=1;else if(f===3)n.italic=!0,u+=1;else if(f===4)n.underline=!0,u+=1;else if(f===7)n.inverse=!0,u+=1;else if(f===9)n.strikethrough=!0,u+=1;else if(f===22)n.bold=!1,n.dim=!1,u+=1;else if(f===23)n.italic=!1,u+=1;else if(f===24)n.underline=!1,u+=1;else if(f===27)n.inverse=!1,u+=1;else if(f===29)n.strikethrough=!1,u+=1;else if(f>=30&&f<=37)n.fg=Oh[f],u+=1;else if(f===39)n.fg=void 0,u+=1;else if(f>=40&&f<=47)n.bg=q0[f],u+=1;else if(f===49)n.bg=void 0,u+=1;else if(f>=90&&f<=97)n.fg=Oh[f],u+=1;else if(f>=100&&f<=107)n.bg=q0[f],u+=1;else if(f===38){const p=d[u+1];if(p===5){const m=d[u+2];m!==void 0&&(n.fg=G0(m)),u+=3}else if(p===2){const m=d[u+2],g=d[u+3],y=d[u+4];m!==void 0&&g!==void 0&&y!==void 0&&(m===1&&g===1&&y in Z0?n.fg=Z0[y]:n.fg=`rgb(${m}, ${g}, ${y})`),u+=5}else u+=1}else if(f===48){const p=d[u+1];if(p===5){const m=d[u+2];m!==void 0&&(n.bg=G0(m)),u+=3}else if(p===2){const m=d[u+2],g=d[u+3],y=d[u+4];m!==void 0&&g!==void 0&&y!==void 0&&(m===1&&g===1&&y in W0?n.bg=W0[y]:n.bg=`rgb(${m}, ${g}, ${y})`),u+=5}else u+=1}else u+=1}}}return s<e.length&&i(e.slice(s)),t}const K0=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},nn=z.memo(({text:e,className:t,style:n})=>{if(e==null||e==="")return null;if(!k4(e))return t||n?l.jsx("span",{className:t,style:n,children:e}):l.jsx(l.Fragment,{children:e});const r=nO(e);return r.length===0?null:r.length===1&&!K0(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=K0(s);return i?l.jsx("span",{style:i,children:s.text},o):l.jsx(z.Fragment,{children:s.text},o)})})});nn.displayName="AnsiText";const rO=(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}}},sO=async(e,t,n)=>{try{await De.respondToExtensionDialog({requestId:t.requestId,...n},{runtimeKey:X()}),Je().dismissExtensionDialog(e,t.requestId)}catch(r){if(r instanceof ut&&r.code==="EXTENSION_DIALOG_NOT_PENDING"){Je().dismissExtensionDialog(e,t.requestId);return}throw r}},oO=()=>{requestAnimationFrame(()=>{document.querySelector('[data-slot="composer-editor"], .chat-input-column textarea, textarea')?.focus()})},iO=(e,t)=>{const[n,r]=z.useState(()=>typeof e!="number"||e<=0?null:Math.max(0,Math.ceil(e/1e3)));return z.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},aO=e=>e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?e.value.trim().length>0:e.isContentEditable?(e.textContent??"").trim().length>0:!1:!1,lO=({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(nn,{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:R("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(nn,{text:i})}),d!==void 0&&l.jsx("span",{className:R("ml-2 shrink-0 font-mono text-xs opacity-70",c?"text-interactive-selection-foreground":"text-muted-foreground"),children:d})]},i)})})]})},cO=({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(nn,{text:e.message})}),l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[l.jsx(Ee,{type:"button",variant:"outline",size:"sm",onClick:()=>t({confirmed:!1,cancelled:!0}),children:"No (N)"}),l.jsx(Ee,{type:"button",variant:"default",size:"sm",onClick:()=>t({confirmed:!0}),children:"Yes (Y)"})]})]}),dO=({request:e,onRespond:t,messageId:n})=>{const r=e.method==="editor",[s,o]=z.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(nn,{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(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),l.jsx(Ee,{type:"button",variant:"default",size:"sm",onClick:i,disabled:!r&&s.trim().length===0,children:"Submit"})]})]})},uO=({request:e,onRespond:t,messageId:n})=>{const r={};for(const f of e.fields??[])f.type==="checkbox"?r[f.id]=f.initial==="true"?"true":"false":f.initial!==void 0?r[f.id]=f.initial:f.type==="select"&&f.options?.[0]!==void 0?r[f.id]=f.options[0]:r[f.id]="";const[s,o]=z.useState(r),[i,a]=z.useState(!1),c=(e.fields??[]).filter(f=>f.required&&(s[f.id]??"").length===0),d=(e.fields??[]).filter(f=>{if(f.type!=="number")return!1;const p=s[f.id]??"";if(p.length===0)return!1;const m=Number(p);return!Number.isFinite(m)||"min"in f&&typeof f.min=="number"&&m<f.min||"max"in f&&typeof f.max=="number"&&m>f.max}),u=i&&(c.length>0||d.length>0);return l.jsxs("form",{onSubmit:f=>{f.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(nn,{text:e.message})}),l.jsx("div",{className:"flex max-h-60 flex-col gap-2.5 overflow-y-auto",children:(e.fields??[]).map(f=>{const p=u&&f.required&&(s[f.id]??"").length===0,m=u&&d.some(v=>v.id===f.id),g=p||m,y=s[f.id]??"",b=v=>o(x=>({...x,[f.id]:v})),k="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 f.type==="checkbox"?l.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[l.jsx("input",{type:"checkbox",checked:y==="true",onChange:v=>b(v.target.checked?"true":"false"),className:"size-4"}),l.jsx("span",{children:l.jsx(nn,{text:f.label})})]},f.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(nn,{text:f.label}),f.required&&l.jsx("span",{"aria-hidden":"true",className:"text-status-error",children:" *"})]}),f.type==="textarea"?l.jsx("textarea",{value:y,onChange:v=>b(v.target.value),placeholder:f.placeholder?kn(f.placeholder):"",rows:2,"aria-invalid":g||void 0,className:k}):f.type==="number"?l.jsx("input",{type:"number",value:y,onChange:v=>b(v.target.value),placeholder:f.placeholder?kn(f.placeholder):"",min:"min"in f&&typeof f.min=="number"?f.min:void 0,max:"max"in f&&typeof f.max=="number"?f.max:void 0,"aria-invalid":g||void 0,className:k}):f.type==="select"?l.jsx("select",{value:y,onChange:v=>b(v.target.value),"aria-invalid":g||void 0,className:k,children:(f.options??[]).map(v=>l.jsx("option",{value:v,children:v},v))}):l.jsx("input",{type:"text",value:y,onChange:v=>b(v.target.value),placeholder:f.placeholder?kn(f.placeholder):"","aria-invalid":g||void 0,className:k})]},f.id)})}),u&&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(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>t({cancelled:!0}),children:"Cancel"}),l.jsx(Ee,{type:"submit",variant:"default",size:"sm",children:"Submit"})]})]})},Y0=({sessionId:e})=>{const t=Ke(y=>{const b=e??y.selectedSessionId,v=(b?y.reducer.bySession.get(b):void 0)?.extensionDialogs??[],x=v[0];if(x&&b)return{sessionId:b,request:x,queueLength:v.length};if(e!==void 0)return null;for(const[C,S]of y.reducer.bySession){const w=S.extensionDialogs,M=w[0];if(M)return{sessionId:C,request:M,queueLength:w.length}}return null},(y,b)=>y?.sessionId===b?.sessionId&&y?.request.requestId===b?.request.requestId&&y?.queueLength===b?.queueLength,"dialogs",e??""),[n,r]=z.useState(!1),[s,o]=z.useState(!1),[i,a]=z.useState(0),c=z.useRef(!1),d=z.useRef(null),u=z.useId(),f=t?`${t.sessionId}\0${t.request.requestId}`:null;z.useEffect(()=>{c.current=!1,r(!1),o(!1),a(0),f!==null&&d.current&&!d.current.contains(document.activeElement)&&!aO(document.activeElement)&&d.current.focus()},[f]);const p=iO(t?.request.timeoutMs,t?.request.requestId),m=z.useCallback(y=>{!t||n||c.current||(c.current=!0,r(!0),o(!1),sO(t.sessionId,t.request,y).then(()=>{oO()}).catch(()=>{o(!0)}).finally(()=>{c.current=!1,r(!1)}))},[n,t]),g=y=>{if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m({cancelled:!0});return}if(t){if(t.request.method==="confirm"){if(y.key==="y"||y.key==="Y"){y.preventDefault(),m({confirmed:!0});return}if(y.key==="n"||y.key==="N"){y.preventDefault(),m({confirmed:!1,cancelled:!0});return}}if(t.request.method==="select"){const b=t.request.options??[],k=rO(y.key,i,b.length);if(!k)return;const x=(y.target instanceof HTMLElement?y.target:null)?.getAttribute("role")==="option";if(k.kind==="highlight"){y.preventDefault(),a(k.index),x&&d.current?.querySelectorAll('[role="option"]')[k.index]?.focus();return}if((y.key==="Enter"||y.key===" ")&&!x&&y.target!==y.currentTarget)return;const S=b[k.index];if(S===void 0)return;y.preventDefault(),m({value:S})}}};return t?l.jsx("div",{className:"chat-input-column mb-2",children:l.jsxs("div",{ref:d,role:"dialog","aria-label":kn(t.request.title),"aria-describedby":t.request.message?u:void 0,tabIndex:-1,onKeyDown:g,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(V,{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(nn,{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]}),p!==null&&l.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",title:`${p}s remaining`,children:[p,"s"]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"xs",onClick:()=>m({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:n?"pointer-events-none opacity-60":void 0,"aria-busy":n||void 0,children:[t.request.method==="select"&&l.jsx(lO,{request:t.request,onRespond:m,messageId:u,highlightedIndex:i,setHighlightedIndex:a}),t.request.method==="confirm"&&l.jsx(cO,{request:t.request,onRespond:m,messageId:u}),(t.request.method==="input"||t.request.method==="editor")&&l.jsx(dO,{request:t.request,onRespond:m,messageId:u}),t.request.method==="form"&&l.jsx(uO,{request:t.request,onRespond:m,messageId:u})]}),s&&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},fO=e=>{const t=e.replace(/[-_]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e},hO=({sessionId:e,className:t})=>{const n=Ke(d=>d.selectedSessionId),r=e??n,s=Ke(d=>r?d.reducer.bySession.get(r)?.extensionWidgets:void 0,(d,u)=>d===u,r?`session:${r}`:"chrome"),o=z.useMemo(()=>[...s?.entries()??[]],[s]),[i,a]=z.useState({}),c=z.useCallback(d=>{a(u=>({...u,[d]:!u[d]}))},[]);return o.length===0?l.jsxs("div",{className:R("flex h-full flex-col items-center justify-center gap-1.5 p-6 text-center",t),"data-testid":"extensions-surface-empty",children:[l.jsx(V,{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:R("flex h-full min-h-0 flex-col overflow-y-auto",t),"data-testid":"extensions-surface",children:l.jsx(pO,{title:"Widgets",count:o.length,children:o.map(([d,u])=>l.jsx(mO,{title:fO(d),meta:u.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:u.lines.map((f,p)=>l.jsx("span",{className:"block whitespace-pre-wrap",children:l.jsx(nn,{text:f})},p))})},d))})})},pO=({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})]}),mO=({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(V,{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})]}),gO=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),X0=({sessionId:e})=>{const t=Ke(f=>f.selectedSessionId),n=e??t,{isMobile:r}=Rr(),[s,o]=z.useState(!1),i=Ke(f=>[...(n?f.reducer.bySession.get(n):void 0)?.extensionStatuses.entries()??[]],(f,p)=>gO(f.flat(),p.flat()),`session:${n??""}`),{widgetsCount:a,sessionDirectory:c}=Ke(f=>{const p=n?f.reducer.bySession.get(n):void 0;return{widgetsCount:p?.extensionWidgets.size??0,sessionDirectory:p?.directory}},(f,p)=>f.widgetsCount===p.widgetsCount&&f.sessionDirectory===p.sessionDirectory,`session:${n??""}`);z.useEffect(()=>{a===0&&o(!1)},[a]);const d=a===0?"":a===1?"1 widget":`${a} widgets`,u=z.useCallback(()=>{if(r){o(p=>!p);return}const f=c||tt.getState().currentDirectory||"";se.getState().openContextSurface(f,"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(V,{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(([f,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(nn,{text:p})},f))})]}),d&&l.jsxs(Ee,{type:"button",variant:"ghost",size:"xs",onClick:u,"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(V,{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(hO,{sessionId:n,className:"h-auto"})})]})},ki=new Set,yO=200,vO=e=>{for(ki.add(e);ki.size>yO;){const t=ki.values().next().value;if(t===void 0)break;ki.delete(t)}},J0=({sessionId:e})=>{const t=Ke(s=>s.selectedSessionId),n=e??t,r=Ke(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 z.useEffect(()=>{for(const s of r){if(ki.has(s.id))continue;vO(s.id);const o=kn(s.message||"Extension notification");s.level==="error"?Ne.error(o):s.level==="warning"?Ne.warning(o):Ne.info(o)}},[r]),null},xO=({sessionId:e})=>{const t=se(r=>r.commandTriggers),n=h.useCallback((r,s)=>{e&&Je().prompt(e,L5(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(Ee,{size:"xs",variant:"outline",disabled:!e,onClick:()=>n(r.command,r.args),title:r.combo?`${r.label} (${I7(r.combo)})`:r.label,children:r.label},r.id))})},bO=({isNewSession:e=!1})=>{const{currentTheme:t}=Fn(),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($p,{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]})},wO=h.memo(bO),km=2,M4=2,SO=72,CO=(e,t=km)=>t+Math.max(0,e),kO=(e,t,n,r=km)=>{const s=CO(n,r);return t<=s?!1:e<t-s},MO=(e,t,n=km)=>Math.max(0,t-n-e),IO=(e,t,n=M4)=>e+Math.max(0,Math.min(n,t)),_O=({foldedCount:e,onLoadOlder:t,onLoadAll:n})=>{const r=Math.min(M4,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(Ee,{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(V,{name:"history",className:"size-3.5"}),"Load older history"]}),s?l.jsx(Ee,{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]})})},EO=h.memo(_O),I4="The following tool was executed by the user",Mm=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},jO=e=>{const t=e.info;return typeof t.parentID=="string"&&t.parentID.length>0?t.parentID:null},_4=e=>!e||Mm(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(I4)}),E4=(e,t)=>{if(Mm(e)!=="assistant")return{hide:!1,details:null};if(t&&jO(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}}},TO=(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(Mm(o)==="user")break;const{hide:i,details:a}=E4(o,r);if(i){const c=typeof a?.command=="string"?a.command.trim():"";return c.length>0?c:null}}return null},ms=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},AO=e=>e.info.error?.name==="SessionRetry",LO=e=>{const t=e.text;if(typeof t=="string")return t;const n=e.content;return typeof n=="string"?n:""},NO=e=>{if(!e)return null;const t=e.info.id;return typeof t=="string"&&t.trim().length>0?t:null},RO=e=>{const t=e.info.parentID;return typeof t=="string"&&t.trim().length>0?t:null},PO=(e,t)=>{if(ms(e)!=="system")return e;const r=RO(e);return!r||!t.has(r)||e.info.clientRole==="assistant"?e:{...e,info:{...e.info,clientRole:"assistant"}}},DO=e=>!e||ms(e)!=="user"?!1:e.parts.some(t=>t?.type==="subtask"),OO=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},HO=e=>{if(ms(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:OO(e.parts[0])}},FO=(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}},VO=(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(I4)){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}},yf=(e,t)=>t?e.userMessage.info.id===t?!0:e.assistantMessages.some(n=>n.info.id===t):!1,BO=40,$O=40,zO=(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}},UO=(e,t,n,r)=>n&&!r&&e.length>t.length?e:t,Im=({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=UO(o.current,e,!0,r);return o.current=i,i},ZO=e=>e.isStreaming?e.throttledTextContent:e.textContent,WO=e=>!e.isFinalized&&e.displayTextContent.trim().length===0?!1:e.displayTextContent.trim().length>0,qO=({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";cs("ui.assistant_text_part.render"),p&&cs("ui.assistant_text_part.render.streaming");const m=Im({text:d,isStreaming:p,identityKey:`${t}:${e.id??"text"}`}),g=ZO({textContent:d,throttledTextContent:m,isStreaming:p});_7("ui.assistant_text_part.display_len",g.length);const y=o.time,b=!!(y&&typeof y.end<"u");return!(e.type==="text"||e.type==="reasoning")||!WO({displayTextContent:g,isFinalized:b})?null:l.jsx("div",{className:R("group/assistant-text relative w-full min-w-0 break-words",s?"py-1":"pt-3 pb-1"),"data-chat-activity-text":s?"true":void 0,"data-chat-assistant-text":"true",children:l.jsx(ga,{content:g,part:e,messageId:t,isAnimated:!1,isStreaming:p,variant:e.type==="reasoning"?"reasoning":"assistant",enableFileReferences:b,onShowPopup:r})},e.id||`${t}-text`)},j4=h.memo(qO),Q0=300*1e3,Fc=({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>=Q0){c(!1),i.current=null;return}c(!0);return}if(!a){i.current=null;return}const f=i.current??Date.now(),p=Date.now()-f;if(p>=Q0){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 u=h.useMemo(()=>{if(!a)return s;if(!s)return;const f={...s};return delete f.color,f},[a,s]);return l.jsxs("span",{className:R("transition-opacity duration-200",a&&"oc-shimmer-verb",n),style:u,title:o,children:[r,a&&typeof r=="string"?l.jsx(sx,{text:r}):null]})},GO="!text-[length:var(--text-markdown)] !leading-5 tracking-normal",ko=R("typography-markdown font-medium",GO),It=R("typography-code font-mono","!text-[length:var(--text-code)] !leading-5 tracking-normal"),Hh={...E7.getCollapsedStyles(),padding:0,overflow:"visible"},ey={style:{background:"transparent",backgroundColor:"transparent"}},T4={color:"var(--status-error)"},KO={color:"var(--tools-icon)"},A4={color:"var(--status-error)"},wa={color:"color-mix(in srgb, var(--tools-title) 72%, var(--tools-description))"},LW=`
142
- [data-diff-header],
143
- [data-diff] {
144
- [data-separator] {
145
- height: 24px !important;
146
- }
147
- }
148
- `,NW={hunkLineCount:50,lineHeight:24,diffHeaderHeight:44,hunkSeparatorHeight:24,spacing:0},YO=e=>typeof e!="string"||e.trim().length===0?"":e.split(`
149
- `).map(t=>t.replace(/^>\s?/,"").trimEnd()).filter(t=>t.trim().length>0).join(`
150
- `).trim(),vf=80,XO=40,ty=4e3,JO=200,QO={duration:.2,ease:"easeOut"},L4=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(),N4=e=>{if(e.length<=vf)return e;const t=e.lastIndexOf(" ",vf),n=t>0?t:vf;return`${e.substring(0,n).trimEnd()}…`},eH=e=>{if(!e)return"";const t=L4(e).replace(/\s+/g," ").trim();return N4(t)},tH=e=>{const t=e.trimEnd();if(!t)return"";const n=t.lastIndexOf(`
151
- `),r=n===-1?t:t.slice(n+1);return N4(L4(r).replace(/\s+/g," ").trim())},nH=e=>{let t=1,n=0;for(let s=e.length-1;s>=0;s-=1)if(e.charCodeAt(s)===10&&(t+=1,t>XO)){n=s+1;break}const r=n>0?e.slice(n):e;return r.length<=ty?r:r.slice(-ty)},rH=({text:e,variant:t,onContentChange:n,blockId:r,isStreaming:s=!1,actions:o,withinActivityRail:i=!1})=>{const[a,c]=h.useState(!1),[d,u]=h.useState(!1),f=h.useRef(null),p=h.useRef(!0),m=h.useId(),g=h.useRef(s),y=h.useRef(null),b=h.useRef(null),k=h.useRef(!1),v=h.useRef(n);v.current=n;const x=h.useMemo(()=>s?tH(e):eH(e),[s,e]),C=a?"Collapse reasoning trace":"Expand reasoning trace",S=h.useCallback(()=>{u(!0),c(_=>!_),n?.("structural")},[n]),w=h.useCallback(_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),S())},[S]),M=h.useCallback(_=>{_.deltaY<0&&(p.current=!1)},[]),I=h.useCallback(_=>{const T=_.currentTarget;p.current=T.scrollHeight-T.scrollTop-T.clientHeight<=2},[]);if(h.useLayoutEffect(()=>{if(!s||!a){p.current=!0;return}const _=f.current;!_||!p.current||(_.scrollTop=_.scrollHeight)},[a,s,e]),h.useEffect(()=>{if(a){u(!0);return}if(!d)return;if(typeof window>"u"){u(!1);return}const _=window.setTimeout(()=>{u(!1)},JO);return()=>{window.clearTimeout(_)}},[a,d]),h.useLayoutEffect(()=>{const _=y.current;if(!_)return;if(b.current?.stop(),!k.current){k.current=!0,_.style.height=a?"auto":"0px",_.style.overflow=a?"visible":"hidden";return}_.style.overflow="hidden",a?_.style.height="0px":(_.style.height=`${_.scrollHeight}px`,v.current?.("animation"));const T=B9(_,{height:a?"auto":"0px"},QO);return b.current=T,T.finished.then(()=>{b.current===T&&(b.current=null,a?(_.style.overflow="visible",_.style.height="auto"):_.style.overflow="hidden")}).catch(()=>{}),()=>{T.stop(),b.current===T&&(b.current=null)}},[a]),h.useEffect(()=>()=>{b.current?.stop(),b.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:nH(e)}):l.jsx(ga,{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":C,className:R("group/tool flex items-center gap-1.5 py-1 pr-2 pl-px cursor-pointer"),"data-chat-activity-row":"true",onClick:S,onKeyDown:w,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:R("absolute inset-0 flex items-center justify-center transition-opacity",a&&"opacity-0",!a&&"group-hover/tool:opacity-0"),style:{color:"var(--tools-icon)"},children:l.jsx(V,{name:"brain-ai-3",className:"h-3.5 w-3.5"})}),l.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",a&&"opacity-100",!a&&"opacity-0 group-hover/tool:opacity-100"),style:{color:"var(--tools-icon)"},children:a?l.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):l.jsx(V,{name:"arrow-right-s",className:"h-3.5 w-3.5"})})]}),l.jsx(Fc,{active:s,className:R("flex h-5 items-center typography-markdown font-medium text-[length:var(--text-markdown)] leading-none tracking-normal"),style:wa,title:t==="justification"?"Justification":"Thinking",children:t==="justification"?"Justification":"Thinking"})]}),!a&&x?l.jsx("span",{className:R("flex h-5 flex-1 items-center min-w-0 truncate typography-code font-mono text-[length:var(--text-code)] leading-none tracking-normal"),style:{color:"var(--tools-description)",opacity:.8},title:x,children:x}):null]}),d?l.jsx("div",{ref:y,id:m,"aria-hidden":!a,style:{height:a?"auto":"0px",overflow:a?"visible":"hidden",overflowAnchor:"none"},children:l.jsxs("div",{className:R("relative pt-0.5",i?"pl-0 pb-0":"ml-2 pl-3 pb-1"),style:{opacity:a?1:0,transform:a?"translateY(0)":"translateY(-4px)",transition:"opacity 180ms ease-out, transform 180ms ease-out"},children:[i?null: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(Hn,{ref:f,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?M:void 0,onScroll:s?I:void 0,children:E})]})}):null]})},sH=h.memo(({part:e,onContentChange:t,messageId:n,streamPhase:r,withinActivityRail:s=!1})=>{const o=e,i=o.text||o.content||"",a=h.useMemo(()=>YO(i),[i]),c=o.time,u=(r===void 0||r!=="completed")&&o.streaming===!0&&typeof c?.end!="number",f=Im({text:a,isStreaming:u,identityKey:`${n}:${e.id??"reasoning"}`});return!f||f.trim().length===0?null:l.jsx(rH,{text:f,variant:"thinking",onContentChange:t,blockId:e.id||`${n}-reasoning`,time:c,isStreaming:u,withinActivityRail:s})}),ny=[{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:R("inline-block align-baseline",t),children:r.split("").map((s,o)=>z.createElement(qa.span,{...n,key:s+String(o),className:R("inline-block whitespace-pre align-baseline"),initial:{opacity:0},animate:{opacity:1},transition:{ease:"easeOut",duration:.14,delay:Math.min(o*.0045,.14)}},s))}):null}},{variant:"glitch",component:({children:e,className:t,...n})=>l.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[l.jsx("span",{...n,className:R("invisible",t),children:e}),l.jsx("span",{...n,className:R("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",t),children:e}),l.jsx("span",{...n,className:R("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",t),children:e})]})},{variant:"hover-enter",component:({children:e,className:t,...n})=>{if(typeof e!="string")return null;const r=.25,s=.025,o=e.split("").map(i=>i===" "?" ":i);return l.jsxs(qa.span,{...n,className:R("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(qa.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:R("absolute inset-0"),children:o.map((i,a)=>l.jsx(qa.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:R("text-primary-muted hover:animate-text-shake",t),children:e})},{variant:"hover-decoration",component:({children:e,className:t,...n})=>l.jsx("div",{className:R("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:l.jsx("span",{...n,className:R("text-primary-muted",t),children:e})})}];function sr({variant:e="static",className:t,...n}){const s=ny.find(o=>o.variant===e)?.component||ny[0].component;return l.jsx(s,{...n,className:t})}const oH=600*1e3,Fh=new Map,iH=e=>{const t=$t(e);if(!t)return;const n=Fh.get(t);if(n){if(n.expiresAt<=Date.now()){Fh.delete(t);return}return n.outsideFileGrant}},ry=(e,t,n)=>{const r=$t(e);!r||!t||Fh.set(r,{outsideFileGrant:t,expiresAt:Date.now()+oH})},aH=async(e,t)=>{const n=$t(e);if(!n||!t||_d(n,t))return;const r=iH(n);if(r)return r;const s=await j7(n);if(!(!s.success||!s.path||!s.outsideFileGrant))return ry(s.path,s.outsideFileGrant),$t(s.path)!==n&&ry(n,s.outsideFileGrant),s.outsideFileGrant},R4=(e,t)=>{const n=e.trim();if(n){if(kr.getState().setSelectedSkill(n),se.getState().setSettingsPage("skills.installed"),t){t.openSettings("skills.installed");return}se.getState().setSettingsDialogOpen(!0)}},sy=e=>{if(!e)return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null},oy=e=>{const t=e?.state?.status;return typeof t=="string"?t:null},iy=e=>e?.state,ay=e=>e?.metadata,Ml=e=>{const t=e?.time;return{start:typeof t?.start=="number"?t.start:null,end:typeof t?.end=="number"?t.end:null}},ly=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,"")},Ad=(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=sy(r),i=sy(s);if(o!==i)return!1;if(r.type==="tool"){if(iy(r)!==iy(s)||ay(r)!==ay(s)||oy(r)!==oy(s))return!1;const d=Ml(r),u=Ml(s);if(d.start!==u.start||d.end!==u.end)return!1;const f=r.tool,p=s.tool;if(f!==p)return!1;const m=r.output,g=s.output;if(m!==g)return!1;continue}const a=Ml(r),c=Ml(s);if(a.start!==c.start||a.end!==c.end)return!1;if(r.type==="file"){const d=r,u=s;if(d.filename!==u.filename||d.mime!==u.mime||d.url!==u.url||d.size!==u.size)return!1}if(r.type==="text"||r.type==="reasoning"){if(ly(r)!==ly(s))return!1;const d=r.shellAction,u=s.shellAction;if((d||u)&&(d?.command!==u?.command||d?.output!==u?.output||d?.status!==u?.status))return!1}}return!0},P4=(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),D4=(e,t)=>P4(e.info,t.info)&&e.info.error===t.info.error&&Ad(e.parts,t.parts),Vc=(e,t)=>e===t?!0:!e||!t?!1:P4(e.info,t.info),lH=(e,t)=>!e||!t?e===t:e.additions===t.additions&&e.deletions===t.deletions&&e.files===t.files,cH=(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},_m=(e,t)=>e.id===t.id&&e.messageId===t.messageId&&e.kind===t.kind&&e.partIndex===t.partIndex&&e.endedAt===t.endedAt&&Ad([e.part],[t.part]),dH=(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(!_m(o,i))return!1;r+=1,s+=1}},uH=(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(!_m(e.parts[n],t.parts[n]))return!1;return!0},cy=(e,t)=>!!e?.some(n=>n.anchorMessageId===t),fH=(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(!uH(o,i))return!1;r+=1,s+=1}},O4=(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||!dH(e.activityParts,t.activityParts,n)||!fH(e.activityGroupSegments,t.activityGroupSegments,n))return!1;const i=cy(e.activityGroupSegments,n)||cy(t.activityGroupSegments,n);return!((o||i)&&!lH(e.diffStats,t.diffStats)||(o||i||e.isLastAssistantInTurn||t.isLastAssistantInTurn)&&!cH(e.changedFiles,t.changedFiles))},Bc=new Map,hH=e=>{const t=Bc.get(e);if(t)return t;const n={subscribers:new Set,timerId:null};return Bc.set(e,n),n},pH=(e,t)=>{const n=hH(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=Bc.get(e);r&&(r.subscribers.delete(t),!(r.subscribers.size>0)&&(r.timerId!==null&&typeof window<"u"&&window.clearInterval(r.timerId),Bc.delete(e)))}},H4=(e,t=250)=>{const[n,r]=h.useState(()=>Date.now());return h.useEffect(()=>{if(e)return pH(t,r)},[e,t]),n},dy=e=>typeof e!="string"?null:e.trim()||null,mH=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 dy(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:dy(o.name)},la=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(V,{name:"pencil",className:t}):n==="write"||n==="create"||n==="file_write"?l.jsx(V,{name:"file-edit",className:t}):n==="read"||n==="view"||n==="file_read"||n==="cat"?l.jsx(V,{name:"file-text",className:t}):n==="bash"||n==="shell"||n==="cmd"||n==="terminal"?l.jsx(V,{name:"terminal-box",className:t}):n==="list"||n==="ls"||n==="dir"||n==="list_files"?l.jsx(V,{name:"folder-6",className:t}):n==="search"||n==="grep"||n==="find"||n==="ripgrep"?l.jsx(V,{name:"menu-search",className:t}):n==="glob"?l.jsx(V,{name:"file-search",className:t}):n==="fetch"||n==="curl"||n==="wget"||n==="webfetch"?l.jsx(V,{name:"global",className:t}):n==="web-search"||n==="websearch"||n==="search_web"||n==="codesearch"||n==="google"||n==="bing"||n==="duckduckgo"||n==="perplexity"?l.jsx(V,{name:"global",className:t}):n==="todowrite"||n==="todoread"?l.jsx(V,{name:"list-check-3",className:t}):n==="structuredoutput"||n==="structured_output"?l.jsx(V,{name:"list-check-2",className:t}):n==="skill"?l.jsx(V,{name:"book",className:t}):n==="task"?l.jsx(V,{name:"ai-agent",className:t}):n==="pichamber"?l.jsx(V,{name:"pichamber",className:t}):n==="question"?l.jsx(V,{name:"survey",className:t}):n==="lsp"?l.jsx(V,{name:"scan-2",className:t}):n==="plan_enter"?l.jsx(V,{name:"file-list-2",className:t}):n==="plan_exit"?l.jsx(V,{name:"task",className:t}):n.startsWith("git")?l.jsx(V,{name:"git-branch",className:t}):l.jsx(V,{name:"tools",className:t})},gH=({href:e})=>{const[t,n]=h.useState(!1),r=h.useMemo(()=>BI(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)})})},yH=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"},vH=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}},xH=(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`},bH=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},wH=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},SH=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},ai=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=SH(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"}`},CH=e=>{const n=e.part.state,r=n?.input,s=n?.output;if(Array.isArray(r?.todos)){const o=ai(r.todos);if(o)return o}if(Array.isArray(s)){const o=ai(s);if(o)return o}if(s&&typeof s=="object"&&Array.isArray(s.todos)){const o=ai(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=ai(o);if(i)return i}if(o&&typeof o=="object"&&Array.isArray(o.todos)){const i=ai(o.todos);if(i)return i}}catch{}return null},kH=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)},MH=(e,t=!0)=>{const n=e.lastIndexOf("/");if(n===-1)return l.jsx(sr,{variant:t?"generate-effect":"static",className:R("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:R("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})]})},IH=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"?CH(e):bH(e)},_H=({toolName:e,activity:t,animateTailText:n})=>{const r=h.useContext(ha),s=xa(),o=tt(E=>E.currentDirectory),i=yH(t),a=vH(t),c=typeof a.start=="number",d=H4(!!(c&&i&&typeof a.end!="number"),250),u=c?xH(a.start,a.end,d):null,f=IH(t),p=mH(t.part),m=e.toLowerCase(),g=m==="skill"||m==="read"&&p!==null,y=m==="read"&&!g,b=g?"skill":e,k=va(b).displayName,v=la(b),x=y?wH(t):null,C=y?kH(t):void 0,S=x?Ox(x,o):null,w=h.useCallback((E,_)=>{const T=ba(o,E);if(!T)return;if(r?.editor){r.editor.openFile(T,_);return}if(s){const N=se.getState(),O=o||df(o,T);_&&Number.isFinite(_)?N.openContextFileAtLine(O,T,Math.max(1,Math.trunc(_)),1):N.openContextFile(O,T),s.openFiles();return}if(!_d(T,o)){aH(T,o).then(()=>{const N=se.getState(),O=o||df(o,T);if(_&&Number.isFinite(_)){N.openContextFileAtLine(O,T,Math.max(1,Math.trunc(_)),1);return}N.openContextFile(O,T)});return}const A=se.getState(),j=df(o,T);if(_&&Number.isFinite(_)){A.openContextFileAtLine(j,T,Math.max(1,Math.trunc(_)),1);return}A.openContextFile(j,T)},[o,s,r]),M=m==="grep"||m==="search"||m==="find"||m==="ripgrep"||m==="glob",I=m==="webfetch"||m==="fetch"||m==="curl"||m==="wget";return l.jsxs("div",{className:R("oc-static-tool-row flex w-full items-center gap-x-1.5 pr-2 pl-px py-1 min-w-0"),"data-chat-activity-row":"true",children:[l.jsx("div",{className:"inline-flex h-5 items-center flex-shrink-0",style:{color:"var(--tools-icon)"},children:v}),l.jsx(Fc,{active:i,minDurationMs:1e3,className:R(ko,"inline-flex items-center flex-shrink-0"),style:wa,title:k,children:k}),y&&x&&S?l.jsxs("button",{type:"button",onClick:E=>{E.preventDefault(),E.stopPropagation(),w(x,C)},className:R("inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left hover:text-[var(--status-info)] hover:opacity-90",It),style:{color:"var(--tools-description)"},title:C?`${S}:${C}`:S,children:[l.jsx(rr,{filePath:x,className:"h-3.5 w-3.5"}),MH(S,n)]}):null,M&&f!==null?l.jsx("span",{className:"inline-flex min-w-0 flex-1",children:l.jsxs(sr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",It),style:{color:"var(--tools-description)"},title:f,children:['"',f,'"']})}):null,I&&f!==null?l.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:R("min-w-0 flex-1 inline-flex items-center gap-1.5 underline decoration-[color:var(--status-info)] underline-offset-2 hover:opacity-90","truncate whitespace-nowrap",It),style:{color:"var(--status-info)"},title:f,children:[l.jsx(gH,{href:f}),l.jsx("span",{className:"min-w-0 truncate",children:f})]}):null,g&&p!==null?l.jsx("button",{type:"button",onClick:E=>{E.preventDefault(),E.stopPropagation(),R4(p,s)},className:R("inline-flex !min-h-0 h-5 min-w-0 flex-1 items-center truncate whitespace-nowrap text-left hover:opacity-90",It),style:{color:"var(--tools-description)"},title:`Open ${p} in Settings`,"aria-label":`Open ${p} skill in Settings`,children:p}):null,!y&&!M&&!I&&!g&&f!==null?l.jsx(sr,{variant:n?"generate-effect":"static",className:R("min-w-0 flex-1 truncate whitespace-nowrap",It),style:{color:"var(--tools-description)"},children:f}):null,u?l.jsx("span",{className:R("flex-shrink-0 tabular-nums text-muted-foreground/80",It),"aria-label":"Tool duration",children:u}):null]})},EH=(e,t)=>e.toolName===t.toolName&&e.animateTailText===t.animateTailText&&_m(e.activity,t.activity),jH=h.memo(_H,EH),TH=e=>e.match(/<task\s+id="([^"]+)"(?:\s+[^>]*)?>/i)?.[1],RW="diffs-container";(()=>{try{return!1}catch{return!1}})();const AH=/(?=^From [a-f0-9]+ .+$)/m,F4=/(?=^diff --git)/gm,PW=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?: (.*))?/m,DW=new RegExp("(?<=\\n)"),LH=/^(---|\+\+\+)\s+([^\t\r\n]+)/,NH=/^(---|\+\+\+)\s+[ab]\/([^\t\r\n]+)/,RH=/^diff --git (?:"a\/(.+?)"|a\/(.+?)) (?:"b\/(.+?)"|b\/(.+?))$/,PH=/^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i,OW="header-prefix",HW="header-filename-suffix",FW="header-metadata",VW="header-custom",BW={dark:"pierre-dark",light:"pierre-light"},$W="data-theme-css",zW="data-unsafe-css",UW="data-diffs-scrollbar-measure",ZW="--diffs-scrollbar-gutter-measured",WW=1e5,DH={hunkLineCount:50,lineHeight:20,diffHeaderHeight:44,spacing:8};({...DH});const qW=Object.freeze({fromStart:0,fromEnd:0}),GW={startingLine:0,totalLines:1/0,bufferBefore:0,bufferAfter:0},KW={startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:0};function uy(e){let t=e.length;return e.charCodeAt(t-1)===10&&(t--,e.charCodeAt(t-1)===13&&t--),e.slice(0,t)}const OH=new TextEncoder,HH=new TextDecoder("utf-8",{ignoreBOM:!0}),FH=/[\uD800-\uDFFF]/,Vh=1024;let Js=new Uint8Array(Vh);function V4(){Js.length!==Vh&&(Js=new Uint8Array(Vh))}function At(e){if(e.length===0)return e;if(FH.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;Js.length<t&&(Js=new Uint8Array(t));const{written:n}=OH.encodeInto(e,Js);return HH.decode(Js.subarray(0,n))}function VH(e,t,n){try{return BH(e,t,n)}finally{V4()}}function BH(e,t,n=!1){const r=YH(e),s=r?UH(e):ZH(e);let o;const i=[];for(const a of s){if(r&&!F4.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&&!WH(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=B4(a,{cacheKey:void 0,isGitDiff:r,throwOnError:n});c!=null&&i.push(c)}return{patchMetadata:o,files:i}}function YW(e,t){try{return B4(e,t)}finally{V4()}}function B4(e,{cacheKey:t,isGitDiff:n=F4.test(e),oldFile:r,newFile:s,throwOnError:o=!1}={}){let i=0;const a=Z4(e,"@@ ");let c;const d=r==null||s==null;let u=0,f=0;for(const p of a){const m=$4(p),g=m[0];if(g==null){if(o)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",p);continue}const y=U4(g);let b=0,k=0;if(y==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:my(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(RH),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 _=E.startsWith("---")||E.startsWith("+++")?E.match(n?NH:LH):null;if(_!=null){const[,T,A]=_;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(PH)??[];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]===`
152
- `||m[m.length-1]==="\r"||m[m.length-1]===`\r
153
- `||m[m.length-1]==="");)m.pop();const{additionStart:C,deletionStart:S}=y;u=d?u:S-1,f=d?f:C-1;const w={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:y.additionCount,additionStart:C,additionLines:b,deletionCount:y.deletionCount,deletionStart:S,deletionLines:k,deletionLineIndex:u,additionLineIndex:f,hunkContent:[],hunkContext:my(y.hunkContext),hunkSpecs:At(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let M=0,I=0;for(let E=1;E<m.length;E++){const _=m[E];if(M>=w.additionCount&&I>=w.deletionCount&&!_.startsWith("\\")){if(o&&qH(_)&&!GH(_))throw Error("parsePatchContent: hunk has more lines than expected");break}const T=_[0];if(T!=="+"&&T!=="-"&&T!==" "&&T!=="\\"){if(o)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${T}", full line: "${_}"`),console.error("processFile: invalid rawLine:",_);continue}const A=XH(T);if(A==="addition"){if(o&&M>=w.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const j=xf(_);(v==null||v.type!=="change")&&(v=bf("change",u,f),w.hunkContent.push(v)),f++,M++,d&&c.additionLines.push(j),v.additions++,b++,x="addition"}else if(A==="deletion"){if(o&&I>=w.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const j=xf(_);(v==null||v.type!=="change")&&(v=bf("change",u,f),w.hunkContent.push(v)),u++,I++,d&&c.deletionLines.push(j),v.deletions++,k++,x="deletion"}else if(A==="context"){if(o&&(I>=w.deletionCount||M>=w.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const j=xf(_);(v==null||v.type!=="context")&&(v=bf("context",u,f),w.hunkContent.push(v)),f++,u++,M++,I++,d&&(c.deletionLines.push(j),c.additionLines.push(j)),v.lines++,x="context"}else if(A==="metadata"&&v!=null){if(v.type==="context"?(w.noEOFCRAdditions=!0,w.noEOFCRDeletions=!0):x==="deletion"?w.noEOFCRDeletions=!0:x==="addition"&&(w.noEOFCRAdditions=!0),d&&(x==="addition"||x==="context")){const j=c.additionLines.length-1;j>=0&&(c.additionLines[j]=uy(c.additionLines[j]))}if(d&&(x==="deletion"||x==="context")){const j=c.deletionLines.length-1;j>=0&&(c.deletionLines[j]=uy(c.deletionLines[j]))}}}if(o&&(M!==w.additionCount||I!==w.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");w.additionLines=b,w.deletionLines=k,w.collapsedBefore=Math.max(w.additionStart-1-i,0),c.hunks.push(w),i=w.additionStart+w.additionCount-1;for(const E of w.hunkContent)E.type==="context"?(w.splitLineCount+=E.lines,w.unifiedLineCount+=E.lines):(w.splitLineCount+=Math.max(E.additions,E.deletions),w.unifiedLineCount+=E.deletions+E.additions);w.splitLineStart=c.splitLineCount+w.collapsedBefore,w.unifiedLineStart=c.unifiedLineCount+w.collapsedBefore,c.splitLineCount+=w.collapsedBefore+w.splitLineCount,c.unifiedLineCount+=w.collapsedBefore+w.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,y=Math.max(g-m,0);c.splitLineCount+=y,c.unifiedLineCount+=y}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 $H(e,t,n=!1){const r=[],s=zH(e)?e.split(AH):[e];for(const o of s)try{r.push(VH(o,t!=null?`${t}-${r.length}`:void 0,n))}catch(i){if(n)throw i;console.error(i)}return r}function zH(e){return e.startsWith("From ")||e.includes(`
154
- From `)}function fy(e){const t=$4(e);for(let n=0;n<t.length;n++)t[n]=At(t[n]);return t}function $4(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const r=e.indexOf(`
155
- `,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 UH(e){return Z4(e,"diff --git")}function ZH(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=Bh(e,r);if(s<=0&&o<=0){if(z4(e,r)){r>n&&t.push(e.slice(n,r)),n=r,i=!0,r=Bh(e,a);continue}if(i&&e.startsWith("@@ -",r)){const d=U4(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 WH(e){return z4(e,0)}function z4(e,t){const n=Bh(e,t);return hy(e,t,"---")&&hy(e,n,"+++")}function hy(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===`
156
- `||o==="\r")break;if(o!==" "&&o!==" ")return!0}return!1}function Bh(e,t){const n=e.indexOf(`
157
- `,t);return n===-1?e.length:n+1}function qH(e){const t=e[0];return t==="+"||t==="-"||t===" "}function GH(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
158
- `&&n!=="\r")return!1}return!0}function U4(e){if(!e.startsWith("@@ -"))return;let t=4;const n=Il(e,t);if(n==null)return;const r=n.value;t=n.endIndex;let s=1;if(e[t]===","){const u=Il(e,t+1);if(u==null)return;s=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const o=Il(e,t);if(o==null)return;const i=o.value;t=o.endIndex;let a=1;if(e[t]===","){const u=Il(e,t+1);if(u==null)return;a=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let c;const d=t+3;return e[d]===" "&&(c=KH(e.slice(d+1))),{additionCount:a,additionStart:i,deletionCount:s,deletionStart:r,hunkContext:c}}function Il(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 KH(e){return e.endsWith(`\r
159
- `)?e.slice(0,-2):e.endsWith(`
160
- `)?e.slice(0,-1):e}function YH(e){return e.startsWith("diff --git")||e.includes(`
161
- diff --git`)}function Z4(e,t){if(e.length===0)return[""];const n=`
162
- ${t}`,r=e.startsWith(t)?0:py(e,n,0);if(r===-1)return[e];const s=[];r>0&&s.push(e.slice(0,r));let o=r;for(;;){const i=py(e,n,o+1);if(i===-1)break;s.push(e.slice(o,i)),o=i}return s.push(e.slice(o)),s}function py(e,t,n){const r=e.indexOf(t,n);return r===-1?-1:r+1}function my(e){return e==null?e:At(e)}function XH(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function xf(e){const t=e.slice(1);return At(t===""?`
163
- `:t)}function bf(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,$c=/^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@/m,JH=/(?=^diff --git\s+)/gm,q4=/^diff --git\s+/m,QH=/(?=^---\s+\S)/gm,G4=/^---\s+\S/m,Nr=e=>typeof e=="object"&&e!==null,eF=e=>e.replace(/\r\n/g,`
164
- `).replace(/\r/g,`
165
- `).trim(),tF=e=>{let t=!1;return e.split(`
166
- `).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(`
167
- `)},nF=e=>{let t=!1;return e.split(`
168
- `).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(`
169
- `)},gy=(e,t)=>t===1?e:`${e},${t}`,rF=e=>{const t=e.split(`
170
- `),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]=`@@ -${gy(o[1]??"0",i)} +${gy(o[2]??"0",a)} @@${o[3]??""}`}return n.join(`
171
- `)},K4=e=>rF(nF(tF(eF(e)))),Vt=e=>{if(typeof e=="string")return/\S/.test(e)?e:void 0;if(Nr(e)){const t=e.patch;if(typeof t=="string")return/\S/.test(t)?t:void 0}},Sa=e=>Nr(e)?typeof e.movePath=="string"?e.movePath:typeof e.filePath=="string"?e.filePath:typeof e.relativePath=="string"?e.relativePath:null:null,Em=(e,t,n)=>{if(e==="apply_patch"){const r=Array.isArray(n?.files)?n.files:[];for(const s of r)if(Nr(s)&&s.type!=="delete"){const o=Sa(s);if(o)return o}return null}if(e==="edit"||e==="multiedit"){const r=Nr(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},sF=(e,t,n)=>{if(e==="apply_patch"){const s=Array.isArray(n?.files)?n.files:[],o=new Set;for(const i of s){if(!Nr(i))continue;const a=Sa(i);a&&o.add(a),i.type==="move"&&typeof i.filePath=="string"&&o.add(i.filePath)}return[...o]}const r=Em(e,t,n);return r?[r]:[]},oF=e=>e==="edit"||e==="multiedit"||e==="apply_patch",yy=(e,t)=>{const n=Array.isArray(e.files)?e.files:[];if(!t){const r=n[0];return Nr(r)?r:void 0}return n.find(r=>Nr(r)&&(r.relativePath===t||r.filePath===t||r.movePath===t))},Zi=e=>{if(!e)return;let t,n;for(const r of e.split(`
172
- `)){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},vy=(e,t,n)=>{if(!t||!oF(e))return;if(n){const i=yy(t,n),a=Vt(i?.patch)??Vt(i?.diff);if(a){const c=Zi(a);if(c!==void 0)return c}}const r=Vt(t.patch)??Vt(t.diff);if(r){const i=Zi(r);if(i!==void 0)return i}const s=yy(t),o=Vt(s?.patch)??Vt(s?.diff);return o?Zi(o):void 0},iF=e=>{const t=(e??"").trim().replace(/\t.*$/,"");return!t||t==="/dev/null"?"":t.replace(/^[ab]\//,"")},aF=e=>{const t=e.trim().replace(/\s+/g,"-");return t.length>0?t:"file"},lF=e=>{let t=!1;for(const n of e.split(`
173
- `)){if(n.startsWith("@@")){if(!$c.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},wf=e=>{const t=K4(e);if(!t||W4.test(t)||!$c.test(t)||!lF(t))return null;try{const n=$H(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:iF(s.name)}}catch{return null}},cF=e=>{const t=q4.test(e),n=G4.test(e);return!t&&!n?[]:e.split(t?JH:QH).map(r=>r.trim()).filter(r=>r.length>0)},xy=(e,t,n,r)=>{const s=K4(e);if(!s)return[];const o=wf(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 cF(s)){const c=wf(a),d=c?.title?r(c.title):r(t);if(!c){($c.test(a)||q4.test(a)||G4.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)&&$c.test(s)){const a=aF(t),c=wf(`--- ${a}
174
- +++ ${a}
175
- ${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"}]},dF=e=>{if(!Nr(e))return null;const t=Vt(e.patch)??Vt(e.diff);if(!t)return null;const n=typeof e.relativePath=="string"?e.relativePath:typeof e.filePath=="string"?e.filePath:"";return{filePath:Sa(e)??void 0,patch:t,title:n}},uF=(e,t,n)=>{const s=(Array.isArray(e?.files)?e.files:[]).flatMap((i,a)=>{const c=dF(i);return c?xy(c.patch,c.title||`File ${a+1}`,`file-${a}`,n).map(d=>({...d,filePath:c.filePath})):[]});return s.length>0?s:xy(typeof t=="string"?t:"","Diff","fallback",n)},fF=new Set(["read","skill"]),vs=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},hF=e=>!pF(e),pF=e=>fF.has(vs(e)),mF=(e,t,n)=>{if(typeof t=="string"&&t.trim().length>0)return t;const r=vs(e)==="glob"?n?.pattern:void 0;return typeof r=="string"?r:""},gF=(e,t)=>{const n=t.replace(/\r\n/g,`
176
- `);if(!n.trim())return;const r=(()=>{const a=(e??"").trim();return a?a.startsWith("/")?a.slice(1):a:"new-file"})(),s=n.split(`
177
- `),o=s.length,i=s.map(a=>`+${a}`).join(`
178
- `);return["--- /dev/null",`+++ b/${r}`,`@@ -0,0 +1,${o} @@`,i].join(`
179
- `)},zc=e=>{const t=e.trim().replace(/\\/g,"/").replace(/\/{2,}/g,"/");return!t||t==="/"?t:t.replace(/\/+$/,"")},Pn=(e,t)=>{const n=zc(e),r=zc(t);if(!n)return"";if(!r)return n;if(n===r)return".";const s=`${r}/`;return n.startsWith(s)?n.slice(s.length):n},yF=5,Wi=e=>typeof e=="object"&&e!==null,vF=e=>{if(!Wi(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=Wi(e.range)?e.range:void 0,s=r&&Wi(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}},xF=(e,t,n,r)=>{if(!["edit","multiedit","write","apply_patch"].includes(e))return null;const s=Em(e,t,n);if(!s||!n||!Wi(n.diagnostics))return null;const o=zc(s),i=o.startsWith("/")?o:`${zc(r)}/${o}`.replace(/\/+/g,"/"),a=n.diagnostics[o]??n.diagnostics[i];if(!Array.isArray(a))return null;const c=a.map(u=>vF(u)).filter(u=>!!u);if(c.length===0)return null;const d=c.slice(0,yF);return{displayPath:o.startsWith("/")?Pn(o,r):o,diagnostics:d,remaining:Math.max(0,c.length-d.length)}},bF=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},wF=e=>{const t=Vt(e?.patch)??Vt(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}},SF=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},Y4=(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"?Pn(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 Pn(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 Pn(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 Pn(i,n)}if(e.tool==="lsp"&&o){const i=o?.filePath||o?.file_path||o?.path;if(typeof i=="string")return Pn(i,n)}return null},CF=(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?Pn(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},kF=(e,t,n)=>{const r=t,s=r.metadata,o=r.input,i=Y4(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(`
180
- `)[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 CF(o,n);const a=o?.description||s?.description||"title"in t&&t.title||"";return mF(e.tool,a,o)},X4=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""},Mo=e=>{const t=vs(e.tool),n=e.state?.status??"",r=X4(e);return`${e.id??""}${t}${n}${r}`},MF=({isTaskTool:e,isExpanded:t,isActive:n,hasFinalMetadataSummary:r,taskSessionId:s})=>e&&!!s&&!r&&(t||n),Io=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},by=e=>{if(!e||typeof e!="object")return;const t=e;return Io(t.sessionID)??Io(t.sessionId)},J4=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},Q4=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:Io(n.sessionId)??Io(n.sessionID),summaryEntries:J4(n.summary??n.entries??n.tools??n.calls)}}catch{return{summaryEntries:[]}}},IF=e=>{if(typeof e!="string"||e.trim().length===0)return;const t=Q4(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 Io(s||TH(e))},wy=new WeakMap,_F=e=>e.type==="tool",EF=e=>{const t=wy.get(e);if(t)return t;const n=[];if(e.info.role==="assistant")for(const r of e.parts){if(!_F(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 wy.set(e,n),n},jF=e=>{const t=[];for(const n of e)t.push(...EF(n));return t},TF=e=>e.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Sy=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},Cy=(e,t)=>e===null?t:t===null?e:e+t,AF=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=Sy(s.additions),a=Sy(s.deletions),c=n.get(o);if(c){c.added=Cy(c.added,i),c.removed=Cy(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())},LF=({animate:e=!0,metadata:t,onFileClick:n,openDiffLabel:r,showFileIcons:s=!0,textClassName:o})=>{const i=AF(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:R("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]}),u=n&&a.file.type!=="delete"&&Sa(a.file),f=`${r}: ${a.path}`;return u?l.jsx(Ee,{variant:"ghost",size:"xs",className:R("min-w-0 max-w-full gap-1 normal-case font-normal tracking-normal",o),"aria-label":f,title:f,onClick:p=>n(a.file,p),children:d},a.path):l.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1",o),style:{color:"var(--tools-description)"},children:d},a.path)})})},NF=({currentDirectory:e,editor:t,file:n})=>{const r=Sa(n);if(!r||n.type==="delete")return!1;const s=Vt(n.patch)??Vt(n.diff),o=s?Zi(s):void 0,i=ba(e,r);return t.openFile(i,o),!0},eb=({children:e,animate:t,className:n})=>l.jsx("div",{className:R(t&&"oc-step-in",n),children:e}),jm=({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:R("w-full min-w-0 flex-none overflow-hidden",r),children:l.jsx(Cd,{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:R("tool-output-surface p-2 rounded-xl w-full min-w-0",t,s?"overflow-y-auto overflow-x-hidden":"overflow-auto",n),children:l.jsx("div",{className:"w-full min-w-0",children:e})})})},ky=({path:e,grow:t=!0})=>{const n=e.lastIndexOf("/");if(n===-1)return l.jsx("span",{className:R("min-w-0 truncate typography-ui-label text-foreground",t&&"flex-1"),style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:e,children:e});const r=e.slice(0,n),s=e.slice(n+1),o=r.startsWith("/"),i=o?r.slice(1):r;return l.jsxs("span",{className:R("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})]})]})},$h=({path:e,animate:t=!0,grow:n=!0,showFileIcons:r=!0})=>{const s=e.lastIndexOf("/");if(s===-1)return l.jsxs("span",{className:R("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:R("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:R("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:R("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})]})]})},RF=new Set(["read","view","file_read","cat","write","create","file_write","edit","multiedit","apply_patch"]),PF=(e,t)=>{if(!RF.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)},DF=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(Mo(e[n])!==Mo(t[n]))return!1;return!0},tb=h.memo(({entry:e,isMobile:t,animateTailText:n})=>{const r=vs(e.tool),s=r.length>0?r:"tool",o=X4(e),i=o.trim().length>0,a=e.state?.status,c=va(s).displayName;return l.jsx(eb,{animate:n,children:l.jsxs("div",{className:R("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:la(s)}),l.jsx("span",{className:R(ko,"text-foreground/80 flex-shrink-0"),style:wa,title:c,children:c}),i?a!=="error"&&PF(s,o)?l.jsx($h,{path:o,animate:n,showFileIcons:!0}):a==="error"?l.jsx("span",{className:R(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:R(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&&Mo(e.entry)===Mo(t.entry));tb.displayName="TaskSummaryEntryRow";const nb=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(jm,{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,u=a.id??`${Mo(a)}:${d}`;return l.jsx(tb,{entry:a,isMobile:n,animateTailText:r},u)})]})})},(e,t)=>e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&DF(e.entries,t.entries));nb.displayName="TaskSummaryEntriesList";const OF=({entries:e,isExpanded:t,isMobile:n,output:r,sessionId:s,onShowPopup:o,input:i,animateTailText:a=!0,isActive:c=!1})=>{const d=Vn(),u=ve(k=>k.setCurrentSession),f=typeof r=="string"?TF(r):"",p=f.length>0,[m,g]=h.useState(!1),y=k=>{k.stopPropagation(),s&&d&&u(s,d)},b=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:R("oc-task-tool-summary relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-[var(--tools-border)] before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:[e.length>0?l.jsx(nb,{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:k=>k.stopPropagation(),onClick:y,children:[l.jsx(V,{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 ${b.charAt(0).toUpperCase()+b.slice(1)} subtask`})]}),p?l.jsxs("div",{className:R("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:k=>k.stopPropagation(),onClick:k=>{k.stopPropagation(),g(v=>!v)},children:[m?l.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0"}):l.jsx(V,{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(jm,{maxHeightClass:"max-h-[50vh]",children:l.jsx("div",{className:"w-full min-w-0",children:l.jsx(ya,{content:f,variant:"tool",onShowPopup:o})})}):null]}):null]})},HF=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}},FF="/assets/markdown-shiki.worker-DnvH1S1x.js";let Rn,VF=0;const ca=new Map,zh=new Set,My=()=>{ca.forEach(e=>e(null)),ca.clear(),zh.clear(),Rn?.terminate(),Rn=void 0},BF=()=>{if(Rn)return Rn;if(!(typeof window>"u"||typeof Worker>"u")){try{Rn=new Worker(FF,{type:"module"})}catch(e){console.error("Failed to create Shiki worker:",e);return}return Rn.onmessage=e=>{const t=ca.get(e.data.id);t&&(ca.delete(e.data.id),t(e.data))},Rn.onerror=My,Rn.onmessageerror=My,Rn.postMessage({type:"init"}),Rn}},Tm=e=>{const t=BF();if(!t)return Promise.resolve(null);const n=++VF;return new Promise(r=>{ca.set(n,r),t.postMessage(e(n))})},$F=async(e,t)=>{const n=await Tm(r=>({type:"highlight",id:r,code:e,lang:t}));return n?.type==="highlight"?n.html:null},XW=async(e,t)=>{const n=await Tm(r=>({type:"highlightLines",id:r,code:e,lang:t}));return n?.type==="highlightLines"?n.lines:null},JW=async(e,t,n,r)=>{const s=!zh.has(n),o=await Tm(i=>({type:"highlightTokens",id:i,code:e,lang:t,themeName:n,...s?{theme:r}:{}}));return o?.type==="highlightTokens"?(zh.add(n),o.lines):null},zF=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),UF=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(""):"",Iy=(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=UF(n);o&&s.setAttribute("style",`${s.getAttribute("style")??""}${o}`)}},ZF=e=>`<pre><code>${zF(e)}</code></pre>`,Uc=({code:e,language:t,className:n,style:r,codeStyle:s,wrap:o=!1})=>{const{currentTheme:i}=Fn(),a=h.useRef(null),c=h.useMemo(()=>HF(i),[i]);return h.useLayoutEffect(()=>{const d=a.current;d&&(d.innerHTML=ZF(e),Iy(d,o,s))},[e,o,s]),h.useEffect(()=>{const d=a.current;if(!d)return;let u=!0;return $F(e,(t||"text").toLowerCase()).then(f=>{!u||!d||!f||(d.innerHTML=f,Iy(d,o,s))}),()=>{u=!1}},[e,t,o,s]),l.jsx("div",{ref:a,className:R("typography-code",n),style:{...c,...r}})},WF={maxDepth:50,maxNodes:1e5,initiallyExpandedDepth:2};function qF(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 GF(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 Uh=0;function rb(e,t,n,r,s){if(Uh>=s.maxNodes)return null;Uh++;const o=qF(e),i=GF(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((u,f)=>[String(f),u]):Object.entries(e);c.childCount=d.length,c.children=[];for(const[u,f]of d){const p=[...n,u],m=rb(f,u,p,r+1,s);m&&c.children.push(m)}}else a&&(c.childCount=o==="array"?e.length:Object.keys(e).length);return c}function KF(e,t){const n={...WF,...t};Uh=0;try{const r=e.trim();if(!r)return null;const s=JSON.parse(r);return rb(s,"root",[],0,n)}catch{return null}}function YF(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 XF(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 JF(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 _y=["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 QF(e){return _y[e%_y.length]}function eV(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 Zh(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 tV(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=>Zh(r)).join(", ")??""}]`:`[${t} items]`}return Zh(e)}const Wh=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(f=>{n&&(f.preventDefault(),n(r.id))},[n,r.id]),c=QF(r.depth),d=eV(r),u=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:[u?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(V,{name:"arrow-down-s",className:"h-3 w-3"}):l.jsx(V,{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:tV(r)}):l.jsx("span",{style:{color:d},children:Zh(r)})]})});Wh.displayName="JsonRow";const nV=200,rV=22,sV=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?KF(a):null,[a]),[d,u]=h.useState(()=>c?new Set(JF(c,s)):new Set),f=h.useMemo(()=>YF(c,d),[c,d]),p=f.length>nV,m=h.useRef(null),g=G5({count:f.length,enabled:p,getScrollElement:()=>m.current,estimateSize:()=>rV,overscan:20,getItemKey:v=>f[v]?.node.id??v}),y=h.useCallback(v=>{u(x=>{const C=new Set(x);return C.has(v)?C.delete(v):C.add(v),C})},[]),b=h.useCallback(()=>{u(new Set)},[]),k=h.useCallback(()=>{c&&u(new Set(XF(c)))},[c]);return h.useImperativeHandle(i,()=>({expandAll:b,collapseAll:k}),[b,k]),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=f[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(Wh,{flatNode:x,onToggle:y,onCopyPath:o})},x.node.id):null})})}):l.jsx("div",{ref:m,className:n,style:{maxHeight:r,overflow:"auto"},children:f.map(v=>l.jsx(Wh,{flatNode:v,onToggle:y,onCopyPath:o},v.node.id))}):null}),oV=({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(Ee,{size:"sm",variant:"ghost",className:R("h-5 w-5 p-0 opacity-60 hover:opacity-100",n),onClick:r,title:e==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:e==="side-by-side"?l.jsx(V,{name:"align-justify",className:"h-3 w-3"}):l.jsx(V,{name:"layout-column",className:"h-3 w-3"})})},iV=e=>{let t=e.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return t=t.replace(/^\s*\d{5}\|\s?/gm,""),t.trim()},dn=(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}},aV=e=>e?e.includes("<diagnostics")||e.includes("<file_diagnostics>")||e.includes("LSP errors detected")||e.includes("This file has errors"):!1,lV=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():"",Ey=(e,t)=>!e||typeof e!="object"?String(e):bT(e,t||""),_l=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}}},cV=e=>{if(!e||typeof e!="object")return;const t=_l(e.patch)??_l(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=_l(r.patch)??_l(r.diff);if(s)return s}},dV=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}}},sb=(e,t,n)=>{let r=iV(e);if((t==="edit"||t==="multiedit"||t==="write"||t==="apply_patch")&&aV(r)&&(r=lV(r)),(t==="edit"||t==="multiedit"||t==="apply_patch")&&r.trim().length===0){const s=cV(n);if(s)return s}return r},QW=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,`
181
- `).split(`
182
- `),a=u=>/\(\s*File has more lines\..*offset.*\)/i.test(u.trim()),d=i.map(u=>{const f=u.trim(),p=f.startsWith("(")&&f.endsWith(")")||a(f);if(n!=="directory"){const m=u.match(/^(\d+):\s?(.*)$/);if(m){const g=m[2],y=g.trim(),b=y.startsWith("(")&&y.endsWith(")")||a(y);return{lineNumber:b?null:Number(m[1]),text:g,isInfo:b}}}return{lineNumber:null,text:u,isInfo:p}}).filter((u,f,p)=>{if(u.text.trim().length>0)return!0;const m=p[f-1],g=p[f+1],y=!!(m?.isInfo||g?.isInfo),b=u.lineNumber!==null;return!(y&&b)});return{type:n,lines:d}},eq=(e,t)=>{try{const n=e.trim().split(`
183
- `).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:R("w-full min-w-0 font-mono space-y-0.5",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:da.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}},uV={backgroundColor:"var(--status-info)",opacity:.6},tq=(e,t,n)=>{try{const r=e.trim().split(`
184
- `).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,u=d!==void 0?c:"",f=d!==void 0?d:c;s[a]||(s[a]=[]),s[a].push({lineNum:u,content:f})}}),l.jsxs("div",{className:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:da.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:R("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:R("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:uV}),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}},fV={backgroundColor:"var(--status-info)",opacity:.6},nq=(e,t,n)=>{try{const r=e.trim().split(`
185
- `).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:R("space-y-2 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:da.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:R("font-medium text-muted-foreground",t?"typography-micro":"typography-code"),children:[i,"/"]}),l.jsx("div",{className:R("pl-4 grid gap-1",t?"grid-cols-1":"grid-cols-2"),children:s[i].sort().map(a=>l.jsxs("div",{className:R("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:fV}),l.jsx("span",{className:"text-foreground font-mono truncate",children:a})]},a))})]},i))]})}catch{return null}},hV=(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:R("space-y-3 w-full min-w-0",n?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:da.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:dn(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:dn(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(V,{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(V,{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:dn(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:dn(a.content)})]},a.id||c))})]})]})}catch{return null}},rq=(e,t)=>{try{return l.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:da.tool.popup,children:l.jsx(ya,{content:e,variant:"tool"})})}catch{return null}},pV=(e,t,n)=>xT(t,e,n),mV=new Set(["id","identifier","title","name"]),gV=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),El=e=>e.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^./,t=>t.toUpperCase()),yV=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},vV=e=>{try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}},Zc=h.memo(({value:e,label:t,depth:n})=>{if(Array.isArray(e)){const o=t?`${El(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(V,{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(Zc,{value:i,depth:n+1},a))})]})]})}if(gV(e)){const o=yV(e),i=Object.entries(e).filter(([d])=>!mV.has(d)),a=t?`${El(t)}${o?` · ${o}`:""}`:o,c=l.jsx("div",{className:"space-y-1",children:i.map(([d,u])=>l.jsx(Zc,{label:d,value:u,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(V,{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?El(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"&&vV(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:R("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:El(t)}):l.jsx("span",{}),s]})});Zc.displayName="JsonSummaryValue";const Am=h.memo(({data:e})=>l.jsx("div",{className:"space-y-1",children:l.jsx(Zc,{value:e,depth:0})}));Am.displayName="JsonSummaryView";const ob=({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}),ib=1e5,jy=(e,t,n)=>{const r=Math.max(0,t-e.length+1),s=ib-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},xV=(e,t,n,r,s)=>{const o=e[t],i=ib-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},Ty=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===`
186
- `){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=xV(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 u=e[d],f=e.slice(c,d).split(";").map(m=>Number.parseInt(m,10)||0),p=f[0]||1;if(u==="A")r=Math.max(0,r-p);else if(u==="B")r=jy(t,r+p,n);else if(u==="C")s+=p;else if(u==="D")s=Math.max(0,s-p);else if(u==="G")s=Math.max(0,p-1);else if(u==="H"||u==="f")r=jy(t,Math.max(0,(f[0]||1)-1),n),s=Math.max(0,(f[1]||1)-1);else if(u==="K"){const m=t[r],g=f[0];if(g===1)for(let y=0;y<=s&&y<m.length;y+=1)m[y]=" ";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),u=c===-1?d:d===-1?c:Math.min(c,d);if(u===-1)break;o=e[u]==="\x07"?u:u+1;continue}o+=1}return t.map(o=>o.join("")).join(`
187
- `)},bV=(e,t,n,r)=>{const s=e==="bash",o=s&&r!=="running";if(typeof t=="string")return o?Ty(t):t;if(s&&typeof n=="string"&&n.length>0)return o?Ty(n):n},wV=(e,t)=>t.startsWith(e)?t.slice(e.length):void 0,ab=16,SV=(e,t=ab)=>{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},CV=(e,t,n,r)=>t.tool==="bash"?"bash":pV(sb(e,t.tool||"",n),t.tool||"",r),kV=(e,t,n)=>t.tool==="bash"?e:sb(e,t.tool||"",n),MV=({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=SV(e,ab),a=wV(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:{...Hh,lineHeight:"round(var(--code-block-line-height), 1px)",overflowWrap:"break-word"}})},qh=({output:e,part:t,metadata:n,input:r,isStreaming:s=!1})=>{const o=kV(e,t,n),i=CV(e,t,n,r),a=h.useMemo(()=>dV(o),[o]),[c,d]=h.useState("summary"),[u,f]=h.useState(!1);h.useEffect(()=>{d("summary"),f(!1)},[o]);const p=h.useCallback((g,y)=>{y.stopPropagation(),d(g)},[]),m=h.useCallback(async g=>{if(g.stopPropagation(),!(await ir(o)).ok){Ne.error("Failed to copy output");return}f(!0),typeof window<"u"&&window.setTimeout(()=>f(!1),1200)},[o]);return t.tool==="bash"&&s?l.jsx("div",{className:"typography-code text-muted-foreground/90",children:l.jsx(MV,{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(Ee,{variant:"ghost",size:"icon",className:R("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(V,{name:"list-unordered",className:"h-3.5 w-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:R("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(V,{name:"node-tree",className:"h-3.5 w-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:R("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(V,{name:"code-box",className:"h-3.5 w-3.5"})}),l.jsx(Ee,{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":u?"Copied output":"Copy output",title:u?"Copied output":"Copy output",children:l.jsx(V,{name:u?"check":"file-copy",className:"h-3.5 w-3.5"})})]}),c==="summary"?l.jsx(Am,{data:a.data}):c==="formatted"?l.jsx(sV,{data:a.data,initiallyExpandedDepth:1,maxHeight:"400px"}):l.jsx("div",{className:"typography-code pr-12 text-muted-foreground/90",children:l.jsx(Uc,{language:"json",code:o,style:Hh,codeStyle:ey.style,wrap:!0})})]}):l.jsx("div",{className:t.tool==="bash"?"typography-code text-muted-foreground/90":void 0,children:l.jsx(Uc,{language:i,code:o,style:Hh,codeStyle:ey.style,wrap:!0})})};qh.displayName="ToolScrollableTextOutput";const IV=ys(()=>mt(()=>import("./ToolPartDiffPreview-DdSneZws.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]))),Ay=({diff:e,diffViewMode:t})=>l.jsx(h.Suspense,{fallback:l.jsx(ob,{diff:e}),children:l.jsx(IV,{diff:e,diffViewMode:t})}),lb=h.memo(({part:e,state:t,currentDirectory:n,isExpanded:r,onShowPopup:s})=>{const o=xa(),[i,a]=h.useState("unified"),c=t,d=c.metadata,u=c.input,f=bV(e.tool||"",c.output,d?.output,t.status),p=typeof f=="string"&&f.length>0,m=typeof f=="string"?f:"",g=e.tool==="bash"&&t.status==="running",y=Im({text:m,isStreaming:g,identityKey:e.id,allowTextReplacement:g}),b=g?y:m,k=c.attachments,v=Wi(d?.filediff)?d.filediff:void 0,x=Vt(d?.patch)??Vt(d?.diff)??Vt(v?.patch)??Vt(v?.diff)??null,C=h.useMemo(()=>uF(d,x??void 0,W=>Pn(W,n)),[n,x,d]),S=C.some(W=>W.renderMode==="diff"),w=e.tool==="pichamber"||e.tool==="apply_patch"||e.tool==="edit"||e.tool==="multiedit",M=h.useMemo(()=>xF(e.tool||"",u,d,n),[n,u,d,e.tool]),I=h.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&e.tool==="bash"?Ey(u,e.tool):typeof u.content=="string"?u.content??"":Ey(u,e.tool),[u,e.tool]),E=!w&&I.trim().length>0,_=e.tool==="write"||e.tool==="create"||e.tool==="file_write",T=e.tool==="todowrite"||e.tool==="todoread",A=h.useMemo(()=>Array.isArray(u?.todos)?JSON.stringify(u.todos):b,[u?.todos,b]),j=h.useMemo(()=>{if(!_||!E)return;const W=typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0;return gF(W,I)},[E,u?.filePath,u?.file_path,u?.path,I,_]);h.useEffect(()=>{a("unified")},[e.id]);const N=(W,F)=>l.jsx(jm,{maxHeightClass:F?.maxHeightClass,className:F?.className,disableHorizontal:F?.disableHorizontal,outerClassName:F?.outerClassName,followKey:F?.followKey,children:W}),O=()=>{const W=Q=>ba(n,Q.filePath??Q.title),F=(Q,D)=>{D.stopPropagation();const U=Zi(Q.patch),Y=W(Q);se.getState().openContextFileAtLine(n,Y,U??1,1),o?.openFiles()},q=(Q,D)=>{D.stopPropagation();const U=W(Q),Y=se.getState(),ne=Pn(U,n);if(Y.isMobile){Y.navigateToDiff(ne);return}Y.openContextDiff(n,ne)},K=()=>M?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(ky,{path:M.displayPath,grow:!1})}),l.jsx("div",{className:"space-y-1",children:M.diagnostics.map((Q,D)=>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:["[",Q.line,":",Q.character,"]"]}),l.jsx("span",{className:"typography-meta text-foreground whitespace-pre-wrap break-words",children:Q.message})]})},`${M.displayPath}:${Q.line}:${Q.character}:${D}`))}),M.remaining>0?l.jsx("div",{className:"typography-micro text-muted-foreground",children:`+${M.remaining} more errors`}):null]})]}):null;if(e.tool==="question"){if(t.status==="completed"&&p){const D=bF(b);if(D&&D.length>0)return N(l.jsx("div",{className:"space-y-2",children:D.map((U,Y)=>l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"typography-micro text-muted-foreground",children:U.question}),l.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:U.answer})]},Y))}),{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:dn(t.error)})]});const Q=u;return Q?.questions&&Array.isArray(Q.questions)&&Q.questions.length>0?N(l.jsx("div",{className:"space-y-2",children:Q.questions.map((D,U)=>l.jsxs("div",{className:"space-y-0.5",children:[D.header?l.jsx("div",{className:"typography-micro text-muted-foreground",children:dn(D.header)}):null,l.jsx("div",{className:"typography-meta text-foreground",children:dn(D.question)}),Array.isArray(D.options)&&D.options.length>0?l.jsx("div",{className:"flex flex-wrap gap-1 mt-0.5",children:D.options.map(Y=>l.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-muted/30 border border-border/30 text-muted-foreground",children:dn(Y.label)},dn(Y.label)))}):null]},U))}),{maxHeightClass:"max-h-[40vh]"}):l.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(e.tool==="task"&&p)return N(l.jsx("div",{className:"w-full min-w-0",children:l.jsx(ya,{content:dn(b),variant:"tool",onShowPopup:s})}));if((e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&(C.length>0||M))return N(l.jsxs("div",{className:"space-y-3",children:[C.map(Q=>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(ky,{path:Q.title})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:D=>F(Q,D),"aria-label":"Open file at first change",title:"Open file at first change",children:l.jsx(V,{name:"file-edit",className:"h-3.5 w-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground hover:text-foreground",onClick:D=>q(Q,D),"aria-label":"Open file diff",title:"Open file diff",children:l.jsx(V,{name:"git-pull-request",className:"h-3.5 w-3.5"})})]}),Q.renderMode==="diff"?l.jsx(Ay,{diff:Q.patch,diffViewMode:i}):l.jsx(ob,{diff:Q.patch})]},Q.id)),K()]}),{className:"p-1"});if(e.tool==="write"&&M)return N(l.jsx("div",{className:"space-y-3",children:K()}),{className:"p-1"});if(_)return null;if(p&&b.trim()){const Q=l.jsx(qh,{output:dn(b),part:e,metadata:d,input:u,isStreaming:g});return N(Q,{className:e.tool==="bash"?"p-1 rounded-none":"p-1",maxHeightClass:g?"max-h-64":e.tool==="bash"?"max-h-[46vh]":void 0,followKey:g?b:void 0})}return N(l.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})},L=b.trim().length>0,P=t.status==="completed"&&"output"in t||e.tool==="bash"&&L;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 W=hV(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:N(W??l.jsx(qh,{output:A,part:e,metadata:d,input:u}),{className:"p-2",maxHeightClass:"max-h-[46vh]"})})}return l.jsxs("div",{className:R("oc-tool-expanded-body relative pr-2 pb-2 pt-2 space-y-2 pl-4"),children:[e.tool==="question"?O():l.jsxs(l.Fragment,{children:[E?l.jsx("div",{className:"my-1",children:N(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:I}):_&&j?l.jsx(Ay,{diff:j,diffViewMode:i}):l.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:I}),{maxHeightClass:_&&j&&r?"max-h-[50vh]":"max-h-60",className:e.tool==="bash"?"tool-input-surface p-0 rounded-none":"tool-input-surface"})}):null,P&&l.jsxs("div",{children:[(e.tool==="edit"||e.tool==="multiedit"||e.tool==="apply_patch"||e.tool==="write")&&S?l.jsx("div",{className:"mb-1 flex items-center justify-end gap-2",children:l.jsx(oV,{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:dn(t.error)})]})]}),Array.isArray(k)&&k.length>0&&t.status==="completed"?l.jsx(rm,{files:k,onShowPopup:s,compact:!0}):null]})});lb.displayName="ToolExpandedContent";const sc=[];let qi;const cb=()=>{for(;sc.length>0;){const e=sc.pop();if(!e)break;if(e.active){e.fn(),qi=sc.length>0?window.requestAnimationFrame(cb):void 0;return}}qi=void 0},_V=e=>{if(typeof window>"u")return e(),()=>{};const t={active:!0,fn:e};return sc.push(t),qi===void 0&&(qi=window.requestAnimationFrame(()=>{qi=window.requestAnimationFrame(cb)})),()=>{t.active=!1}},Ly=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 _V(()=>{n(!0)})},[e]),t},EV=new Set(["bash","edit","write","apply_patch","patch"]),jV=(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`},Ny=({start:e,end:t,active:n})=>{const r=H4(n,250);return l.jsx(l.Fragment,{children:jV(e,t,r)})},Ry=(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},TV=(e,t)=>Ry(e.call,t.call)&&Ry(e.result,t.result),AV=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:R("my-1 ml-5 overflow-x-auto rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-2","font-mono typography-micro whitespace-pre max-h-80 overflow-y-auto"),"data-chat-tool-extension-render":"true",children:[n&&e.map((s,o)=>l.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:l.jsx(nn,{text:s})},`call-${o}`)),r&&t.map((s,o)=>l.jsx("div",{className:"leading-relaxed min-h-[1.25em]",children:l.jsx(nn,{text:s})},`res-${o}`))]})},TV),LV=({part:e,isExpanded:t,onToggle:n,isMobile:r,onContentChange:s,onShowPopup:o,animateTailText:i=!0})=>{const a=ve(ae=>ae.currentSessionId),c=e.state?.deferredBody===!0,d=Uk(a,e.id,t&&c),u=t&&d&&d.type==="tool"?d:e,f=u.state,p=f,m=p.metadata,g=p.input,y=Vn()??"",b=f?.render,k=!!(b&&(Array.isArray(b.call)&&b.call.length>0||Array.isArray(b.result)&&b.result.length>0||Array.isArray(b.resultExpanded)&&b.resultExpanded.length>0)),v=vs(e.tool),x=v==="task",C=f?.status,S=C==="completed"||C==="error"||C==="aborted"||C==="failed"||C==="timeout"||C==="cancelled",w=C==="completed",M=C==="error"||C==="failed",[I,E]=h.useState(!S),_=h.useRef(e.id),T=h.useRef(!S);h.useEffect(()=>{_.current!==e.id&&(_.current=e.id,T.current=!S,E(!S))},[S,e.id]),h.useEffect(()=>{S||E(!0)},[S]),h.useEffect(()=>{if(!S){T.current=!0;return}if(!T.current)return;if(!w||!EV.has(v)){T.current=!1;return}if(!y)return;T.current=!1;const te=sF(v,g,m).map(oe=>Pn(oe,y));kd.requestGitRefresh({directory:y,...te.length>0?{paths:te}:{}})},[y,g,S,w,m,v]);const A=S||x||k,j=h.useRef(s);j.current=s;const N=h.useRef(null);h.useLayoutEffect(()=>{if(x||k)return;const ae=N.current;ae&&(ae.style.height=t?"auto":"0px",ae.style.overflow=t?"visible":"hidden",A&&j.current?.("structural"))},[k,t,x,A]);const O=h.useRef(t);h.useEffect(()=>{const ae=O.current!==t;O.current=t,!(!k||!t&&!ae)&&j.current?.("structural")},[k,t,b?.call,b?.result,b?.resultExpanded]);const L=e.metadata,P=p.time,[W,F]=h.useState(()=>({start:typeof P?.start=="number"?P.start:void 0,end:typeof P?.end=="number"?P.end:void 0})),[q,K]=h.useState(void 0),[Q,D]=h.useState(void 0);h.useEffect(()=>{F({}),K(void 0),D(void 0)},[e.id]),h.useEffect(()=>{S||typeof P?.start!="number"&&K(ae=>ae??Date.now())},[S,P?.start]),h.useEffect(()=>{F(ae=>{const te={...ae};let oe=!1;return typeof P?.start=="number"&&(typeof ae.start!="number"||P.start<ae.start)&&(te.start=P.start,oe=!0),typeof P?.end=="number"&&(typeof ae.end!="number"||P.end>ae.end)&&(te.end=P.end,oe=!0),oe?te:ae})},[P?.end,P?.start]);const U=h.useMemo(()=>{const ae=[W.start,P?.start].filter(te=>typeof te=="number");return ae.length>0?Math.min(...ae):q},[q,W.start,P?.start]),Y=h.useMemo(()=>typeof p.output=="string"?p.output:void 0,[p.output]),ne=h.useMemo(()=>Q4(Y),[Y]),$=h.useMemo(()=>{if(!x)return[];const ae=m,te=J4(ae?.summary??ae?.entries??ae?.tools??ae?.calls);return te.length>0?te:ne.summaryEntries},[x,m,ne.summaryEntries]),J=S&&$.length>0,G=h.useMemo(()=>{if(!x)return;const ae=by(m);if(ae)return ae;const te=by(L);return te||(ne.sessionId?ne.sessionId:IF(Y))},[x,m,ne.sessionId,L,Y]);h.useEffect(()=>{if(typeof P?.end=="number"||typeof W.end=="number"){D(void 0);return}typeof U=="number"&&S&&D(ae=>ae??Date.now())},[U,S,W.end,P?.end]);const ue=S?W.end??P?.end??Q:void 0,B=!S&&I,ie=S,xe=MF({isTaskTool:x,isExpanded:t,isActive:B,hasFinalMetadataSummary:J,taskSessionId:G})?G??"":"",de=pd(xe);qk(xe);const Se=h.useMemo(()=>!x||!G?[]:!Array.isArray(de)||de.length===0?[]:jF(de),[de,x,G]),je=h.useMemo(()=>Se.length>0?Se:$,[Se,$]),Oe=h.useMemo(()=>je.map(Mo).join("\0"),[je]),Be=h.useRef(null);h.useEffect(()=>{if(!x){Be.current=null;return}const ae=Be.current;Be.current=Oe,!(ae===null||ae===Oe||je.length===0)&&j.current?.("structural")},[x,je.length,Oe]);const Ie=h.useMemo(()=>v==="edit"||v==="multiedit"||v==="apply_patch"?wF(m):null,[m,v]),fe=h.useMemo(()=>v==="write"?SF(g):null,[g,v]),ee=v==="apply_patch"&&Array.isArray(m?.files)&&(m?.files).length>1,he=v!==e.tool?{...e,tool:v}:e,Ce=f?Y4(he,f,y):void 0,Ae=f?kF(he,f,y):void 0,Me=va(v||e.tool||"").displayName,Ze=h.useMemo(()=>{if(v==="bash"||v==="apply_patch"||v==="lsp"||Ce&&(v==="apply_patch"||v==="edit"||v==="multiedit"||v==="write"))return null;const ae=p.title;if(typeof ae=="string"&&ae.trim().length>0)return ae;const te=g?.description;return typeof te=="string"&&te.trim().length>0?te:null},[Ce,v,p,g]),gt=!!(Ze||Ae||Ie||fe),we=h.useContext(ha),re=(ae,te)=>{we?.editor&&(te.stopPropagation(),NF({currentDirectory:y,editor:we.editor,file:ae}))},ge=ae=>{if(x||k||!we?.editor){n(e.id);return}let te,oe;if(v==="edit"||v==="multiedit")te=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path,typeof te=="string"&&(oe=vy(v,m,te));else if(v==="apply_patch")te=Em(v,g,m),typeof te=="string"&&(oe=vy(v,m,te));else if(["write","create","file_write"].includes(v))te=g?.filePath||g?.file_path||g?.path||m?.filePath||m?.file_path||m?.path;else if(v==="lsp"){te=g?.filePath||g?.file_path||g?.path;const me=g?.line;oe=typeof me=="number"&&Number.isFinite(me)?Math.trunc(me):void 0}if(typeof te=="string"){ae.stopPropagation();const me=ba(y,te);we.editor.openFile(me,oe)}else n(e.id)},pe=ae=>{ae.key!=="Enter"&&ae.key!==" "||(ae.preventDefault(),ge(ae))},ke=!x&&M?T4:KO,_e=!x&&M?A4:wa,Te=Ly(x&&(je.length>0||B||ie||!!G)),be=Ly(!x&&!k&&t);return!ie&&!B&&!x?null:l.jsxs("div",{children:[l.jsxs("div",{className:R("group/tool flex w-full min-w-0 gap-x-1.5 rounded-md pr-2 pl-px py-1 transition-colors hover:bg-[var(--interactive-hover)]",ee?"flex-wrap items-start cursor-pointer":"items-center cursor-pointer"),"data-chat-activity-row":"true",onClick:ee?()=>n(e.id):ge,onKeyDown:ee?ae=>{ae.target===ae.currentTarget&&(ae.key!=="Enter"&&ae.key!==" "||(ae.preventDefault(),n(e.id)))}:pe,role:"button",tabIndex:0,children:[l.jsx("div",{className:R("flex min-w-0",ee?"w-full flex-wrap items-center gap-x-2 gap-y-0.5":"flex-shrink-0 items-center gap-x-1.5"),children:ee?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:R("absolute inset-0 flex items-center justify-center transition-opacity",t?"opacity-0":"group-hover/tool:opacity-0"),style:ke,children:la(v||e.tool)}),l.jsx(V,{name:t?"arrow-down-s":"arrow-right-s",className:R("absolute inset-0 h-3.5 w-3.5 transition-opacity",t?"opacity-100":"opacity-0 group-hover/tool:opacity-100")})]}),l.jsx(Fc,{active:!!(B&&!M),minDurationMs:300,className:R(ko,"flex-shrink-0"),style:_e,children:Me})]}),l.jsx(LF,{metadata:m,animate:i,showFileIcons:!0,textClassName:It,openDiffLabel:"Open file diff",onFileClick:we?.editor?re:void 0}),typeof U=="number"?l.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-muted-foreground/80",It),"aria-label":"Tool duration",children:l.jsx(Ny,{start:U,end:typeof ue=="number"?ue:void 0,active:!!(B&&typeof ue!="number")})}):null]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"relative h-5 w-3.5 flex-shrink-0 cursor-pointer",onClick:ae=>{ae.stopPropagation(),n(e.id)},children:[l.jsx("div",{className:R("absolute inset-0 flex items-center justify-center transition-opacity",t&&"opacity-0",!t&&"group-hover/tool:opacity-0"),style:ke,children:la(v||e.tool||"")}),l.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",t&&"opacity-100",!t&&"opacity-0 group-hover/tool:opacity-100"),children:t?l.jsx(V,{name:"arrow-down-s",className:"h-3.5 w-3.5"}):l.jsx(V,{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(Fc,{active:!!(B&&!M),minDurationMs:300,className:R(ko,"flex-shrink-0"),style:_e,title:Me,children:Me})})]})}),!ee&&gt?l.jsx("div",{className:R("flex min-w-0 flex-1 items-center",It),style:{color:"var(--tools-description)"},children:l.jsx("span",{className:R("inline-flex min-w-0 max-w-full items-center gap-1 overflow-hidden rounded-md bg-[var(--surface-subtle)] px-1.5 py-0.5",It),children:l.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-hidden",children:[Ze&&l.jsx("span",{className:R("min-w-0 truncate",It),style:{color:"var(--tools-description)",opacity:.8},title:Ze,children:Ze}),!Ze&&v==="lsp"&&Ce?l.jsx($h,{path:Ce,animate:i,grow:!1,showFileIcons:!0}):null,!Ze&&v!=="lsp"&&Ae&&(Ce&&Ae===Ce?l.jsx($h,{path:Ce,animate:i,grow:!1,showFileIcons:!0}):l.jsx(sr,{variant:i?"generate-effect":"static",className:R("min-w-0 truncate",It),style:{color:"var(--tools-description)"},title:Ae,children:Ae})),Ie&&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:["+",Ie.added]}),l.jsx("span",{style:{color:"var(--tools-description)"},children:"/"}),l.jsxs("span",{style:{color:"var(--status-error)"},children:["-",Ie.removed]})]}),fe&&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:["+",fe]})})]})})}):null,!ee&&typeof U=="number"?l.jsx("span",{className:R("ml-auto flex-shrink-0 tabular-nums text-muted-foreground/80",It),"aria-label":"Tool duration",children:l.jsx(Ny,{start:U,end:typeof ue=="number"?ue:void 0,active:!!(B&&typeof ue!="number")})}):null]}),k&&t?l.jsx(AV,{call:b?.call,result:b?.resultExpanded&&b.resultExpanded.length>0?b.resultExpanded:b?.result}):null,Te?l.jsx(OF,{entries:je,isExpanded:t,isMobile:r,output:Y,sessionId:G,onShowPopup:o,input:g,animateTailText:i,isActive:B}):null,!x&&!k?l.jsx("div",{ref:N,"aria-hidden":!t,style:{height:t?"auto":"0px",overflow:t?"visible":"hidden",overflowAnchor:"none"},children:be?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)"}}),f?l.jsx(lb,{part:u,state:f,currentDirectory:y,isExpanded:t,onShowPopup:o}):null]}):null}):null]})};class NV 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:T4,children:la(this.props.toolName)}),l.jsx("span",{className:R(ko,"flex-shrink-0"),style:A4,children:this.props.displayName}),t?l.jsxs("span",{className:R(It,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:t,children:[this.props.errorLabel,": ",t]}):null]})}}const RV=e=>{const t=vs(e.part.tool)||"tool",n=va(t).displayName;return l.jsx(NV,{displayName:n,errorLabel:"Error:",resetKey:e.part,toolName:t,children:l.jsx(LV,{...e})})},PV=h.memo(RV,(e,t)=>Ad([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),db=h.createContext(!1),Py=({disabled:e,children:t})=>l.jsx(db.Provider,{value:e,children:t}),Lm=({children:e,className:t,skipAnimation:n,forceAnimation:r=!1,ignoreContextDisabled:s=!1,respectReducedMotion:o=!1})=>{const i=h.useContext(db),a=o&&typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,c=!!n||!s&&i||a,d=r,u=h.useRef(null);u.current===null&&(u.current=d&&!c);const f=u.current,[p,m]=h.useState(!f);return h.useEffect(()=>{if(!f)return;let g=null;const y=()=>m(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?g=window.requestAnimationFrame(y):y(),()=>{g!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(g)}},[f]),f?l.jsx("div",{className:R("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})},DV=4e3,qs=new Map,ub=e=>{const t=qs.get(e);return t?new Set(t):new Set},OV=(e,t)=>{if(qs.size>=DV&&!qs.has(e)){const n=qs.keys().next().value;typeof n=="string"&&qs.delete(n)}qs.set(e,new Set(t))},HV=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=ub(r);for(const i of s)o.has(i)&&t.add(i)}return t},FV=({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 VV({activities:e}){const t=se(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 y of n)g.set(y.id,y.messageId);return g},[n]),s=h.useMemo(()=>{const g=new Map;for(const y of n){const b=g.get(y.messageId)??new Set;b.add(y.id),g.set(y.messageId,b)}return g},[n]),[o,i]=h.useState(()=>HV(n)),[a,c]=h.useState({open:!1,title:"",content:""}),d=o,u=h.useRef({ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d});u.current={ownerByToolId:r,toolIdsByOwner:s,effectiveExpandedTools:d};const f=h.useCallback(g=>{const y=u.current,b=y.ownerByToolId.get(g);if(!b)return;const k=y.toolIdsByOwner.get(b)??new Set;i(v=>{const x=new Set(v);return x.has(g)?x.delete(g):x.add(g),FV({messageId:b,ownerToolIds:k,nextValue:x,read:ub,write:OV}),x})},[]),p=h.useCallback(g=>{(g.image||g.mermaid)&&(c(g),t(!0))},[t]),m=h.useCallback(g=>{c(y=>({...y,open:g})),t(g)},[t]);return{effectiveExpandedTools:d,popupContent:a,handleToggleTool:f,handleShowPopup:p,handlePopupChange:m}}const BV=ys(()=>mt(()=>import("./ToolOutputDialog-VlS12Xyq.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]))),$V=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}},zV=({activity:e,isLiveTurn:t,activeStreamingMessageId:n,activeStreamingPhase:r})=>t&&n&&e.messageId===n?r??"streaming":"completed",fb=h.memo(({activity:e,animate:t,isExpanded:n,isMobile:r,onContentChange:s,onToggle:o,onShowPopup:i})=>{const a=vs(e.part.tool),c=hF(a)?l.jsx(PV,{part:e.part,isExpanded:n,onToggle:o,isMobile:r,alwaysShowActions:r,onContentChange:s,onShowPopup:i,animateTailText:t}):l.jsx(jH,{toolName:a,activity:e,animateTailText:t});return l.jsx(Lm,{children:l.jsx(eb,{animate:t,children:c})})},(e,t)=>e.activity.id===t.activity.id&&e.activity.messageId===t.activity.messageId&&e.activity.endedAt===t.activity.endedAt&&Ad([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);fb.displayName="TurnToolActivityRow";const UV=({turn:e,isExpanded:t,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s,onContentChange:o})=>{const{isMobile:i}=Rr(),[a,c]=h.useState(BO),d=$V(t),u=h.useRef(o);u.current=o;const f=h.useCallback(I=>{u.current?.(I)},[]),p=e.activityParts,m=h.useMemo(()=>p.reduce((I,E)=>I+(E.kind==="tool"?1:0),0),[p]),g=h.useMemo(()=>zO(p,a),[p,a]),{effectiveExpandedTools:y,popupContent:b,handleToggleTool:k,handleShowPopup:v,handlePopupChange:x}=VV({activities:p}),C=h.useMemo(()=>p.filter(I=>I.kind==="tool").map(I=>I.id),[p]),S=h.useRef({turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set});if(S.current.turnId!==e.turnId&&(S.current={turnId:e.turnId,committed:!1,knownToolIds:new Set,animatedToolIds:new Set}),n&&S.current.committed)for(const I of C)S.current.knownToolIds.has(I)||S.current.animatedToolIds.add(I);h.useEffect(()=>{const I=S.current;for(const E of C)I.knownToolIds.add(E);I.committed=!0},[C]);const w=h.useCallback(()=>{c(I=>Math.min(m,I+$O)),f("structural")},[f,m]),M=h.useCallback(I=>{const E=zV({activity:I,isLiveTurn:n,activeStreamingMessageId:r,activeStreamingPhase:s}),_=S.current.animatedToolIds.has(I.id);return I.kind==="reasoning"?l.jsx(sH,{part:I.part,messageId:I.messageId,streamPhase:E,onContentChange:f,withinActivityRail:!0},I.id):I.kind==="justification"?l.jsx(j4,{part:I.part,messageId:I.messageId,streamPhase:E,onContentChange:f,withinActivityRail:!0},I.id):I.part.type!=="tool"?null:l.jsx(fb,{activity:I,animate:_,isExpanded:y.has(I.id),isMobile:i,onContentChange:f,onToggle:k,onShowPopup:v},I.id)},[r,s,y,v,k,n,i,f]);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:R("relative grid origin-top transition-[grid-template-rows,opacity,transform] duration-200 ease-out motion-reduce:transition-none motion-reduce:transform-none",d.isVisible?"grid-rows-[1fr] translate-y-0 opacity-100":"grid-rows-[0fr] -translate-y-1 opacity-0"),"data-turn-activity-panel":"true","data-turn-activity-visible":d.isVisible?"true":"false",children:[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(Ee,{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:w,children:"Load earlier activity"}):null,l.jsx("div",{className:"min-w-0 space-y-1","data-chat-activity-list":"true",children:g.activities.map(M)})]})]}):null})}),b.open?l.jsx(h.Suspense,{fallback:null,children:l.jsx(BV,{popup:b,onOpenChange:x,isMobile:i})}):null]})},ZV=h.memo(UV),oc=new Map,WV=(e,t)=>{const n=oc.get(e);if(!n)return!1;let r=!1;for(const s of n)r=s(t)||r;return r},qV=(e,t)=>{const n=oc.get(e)??new Set;return n.add(t),oc.set(e,n),()=>{n.delete(t),n.size===0&&oc.delete(e)}},GV=e=>e.filter(r=>r?.type==="text").map(r=>(r.text||r.content||"").trim()).filter(r=>r.length>0).join(`
188
- `).replace(/\n\s*\n+/g,`
189
- `),KV="Authentication failed for this provider. Please re-authenticate and retry.",YV=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},hb=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:
190
- \`${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,u=typeof t.data?.maxAttempts=="number"?t.data.maxAttempts:void 0,f=d&&u?` (${d}/${u})`:"",p=typeof t.data?.message=="string"&&t.data.message.trim()?`
191
- \`${t.data.message.trim()}\``:"";return{text:`Compaction failed temporarily. Retrying${f}...${p}`,variant:"info"}}if(i==="completed"){const d=typeof t.data?.tokensBefore=="number"?t.data.tokensBefore:void 0,u=typeof t.data?.estimatedTokensAfter=="number"?t.data.estimatedTokensAfter:void 0,f=d!==void 0&&u!==void 0?`
192
- ${d.toLocaleString()} → approximately ${u.toLocaleString()} tokens`:"",p=t.data?.willRetry===!0?`
193
- Retrying the interrupted turn.`:"";return{text:`Session compacted${f}${p}`,variant:"info"}}return i==="aborted"?{text:"Compaction stopped.",variant:"info"}:{text:`Compaction failed.${typeof t.data?.message=="string"&&t.data.message.trim()?`
194
- \`${t.data.message.trim()}\``:""}`,variant:"error"}}return YV(o)?{text:KV,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:
195
- \`${o}\``,variant:"error"}}},XV=({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(`
196
-
197
- `);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(`
198
- `):t.filter(a=>a.type==="text").map(a=>(a.text||a.content||"").trim()).filter(a=>a.length>0).join(`
199
- `).replace(/\n\s*\n+/g,`
200
- `)}return n&&n.trim().length>0?n:GV(t)},pb=e=>e.type==="subtask",mb=e=>{const t=e;return t.type==="text"&&typeof t.shellAction=="object"&&t.shellAction!==null},JV=e=>!!(e&&typeof e=="object"&&typeof e.type=="string"),Ld=e=>e.filter(JV),Nm=e=>{const t=e,n=t.text;return typeof n=="string"?n:t.content||t.value||""},gb=e=>{if(e.type!=="text")return!1;const t=Nm(e);return!t||t.trim().length===0},yb=e=>e.type==="text"?!gb(e):pb(e)||mb(e),Rm=e=>e.filter(t=>gb(t)?!1:t.type!=="compaction"),vb=(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)}),QV=(e,t)=>typeof t=="string"&&t.trim().length>0?!0:Rm(e).length>0,Pm=(e,t={})=>{const{includeReasoning:n=!0}=t,r=Ld(e),s=r.some(o=>!o.synthetic);return r.filter(o=>{const a=!!o.synthetic;return a&&o.type==="text"&&Nm(o).includes("<system-reminder>")||a&&s||!n&&o.type==="reasoning"?!1:!(o.type==="patch")})},eB=(e,t)=>{const n=hb(e.info)?.text;if(typeof n=="string"&&n.trim().length>0)return!0;const r=Pm(e.parts),s=vb(r,t,e.info.id);return Rm(s).length>0},Sf=32,Dy=32,tB=({turnId:e,assistantMessages:t,renderMessage:n,deferEarlierMessages:r,activityPartIds:s})=>{const[o,i]=h.useState(Sf),a=t[0],c=h.useMemo(()=>t.filter(v=>eB(v,s)),[s,t]),d=h.useMemo(()=>c.filter(v=>v!==a),[c,a]),u=r&&c.length>Sf,f=u?Math.max(0,o-1):d.length,p=f>=d.length?d:d.slice(-f),m=d.length-p.length;h.useEffect(()=>{i(Sf)},[e]),h.useEffect(()=>qV(e,v=>{if(a?.info.id===v)return!0;const x=d.findIndex(S=>S.info.id===v);if(x<0)return!1;const C=d.length-p.length;return!u||x>=C||i(S=>Math.max(S,d.length-x+1)),!0}),[d,a,u,e,p.length]);const g=h.useCallback(()=>{i(v=>Math.min(d.length+1,v+Dy))},[d.length]),y=h.useCallback(()=>{i(d.length+1)},[d.length]),b=h.useCallback(v=>l.jsx(nB,{message:v,renderMessage:n},v.info.id),[n]);if(!u||m===0)return l.jsxs("div",{className:"relative z-0",children:[a?b(a):null,d.map(b)]});const k=m>Dy;return l.jsxs("div",{className:"relative z-0",children:[a?b(a):null,l.jsxs("div",{className:"chat-message-column flex flex-wrap items-center justify-center gap-2 py-3",children:[l.jsxs(Ee,{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(V,{name:"history",className:"size-3.5"}),"Load earlier response"]}),k?l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:y,"aria-label":"Load full response",className:"rounded-full px-3.5 text-[var(--surface-mutedForeground)]",children:"Load full response"}):null]}),p.map(b)]})},nB=h.memo(function({message:t,renderMessage:n}){return n(t)},(e,t)=>e.message===t.message),rB=h.memo(tB),sB="GitHub issue context (JSON)",oB="GitHub pull request context (JSON)",Mi=e=>!e||typeof e!="object"?!1:!!e.synthetic,iB=e=>!Array.isArray(e)||e.length===0?!1:e.every(t=>Mi(t)),aB=e=>{if(!Array.isArray(e)||e.length===0)return[];const t=e.some(r=>!Mi(r)),n=r=>{if(!Mi(r)||r.type!=="text")return!1;const s=r.text;if(typeof s!="string")return!1;const o=s.trimStart();return o.startsWith(sB)||o.startsWith(oB)};return t&&e.some(s=>Mi(s))?e.filter(s=>!Mi(s)||n(s)):e},lB={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},cB=new Map,xb="\0",dB=new Set(["apply_patch","create","edit","file_write","multiedit","str_replace","str_replace_based_edit_tool","write"]),uB={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"},Oy=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],bb=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},fB=e=>{const t=bb(e);return uB[t]??`using ${t.replaceAll("_"," ")}`},hB=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)},pB=e=>Oy[hB(e)%Oy.length]??"working",Hy=(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=bb(o.tool.name);return{activePartType:dB.has(i)?"editing":"tool",activeToolName:i,statusText:fB(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:pB(n),isGenericStatus:!0}},mB=e=>[e.activePartType??"",e.activeToolName??"",e.statusText,e.isGenericStatus?"1":"0"].join(xb),gB=e=>{const[t,n,r="working",s]=e.split(xb);return{activePartType:t==="text"||t==="tool"||t==="reasoning"||t==="editing"?t:void 0,activeToolName:n||void 0,statusText:r,isGenericStatus:s==="1"}},yB=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 wb(){const e=ve(b=>b.currentSessionId);ve(b=>b.currentSessionDirectory);const t=Dp(e??""),n=h.useMemo(()=>yB(t),[t]),r=n.assistantId,s=Ke(h.useCallback(b=>{const k=`${e??""}:${r??""}`,v=e?b.reducer.bySession.get(e):void 0,x=ea(v)??r,C=x?v?.partOrder.get(x)??[]:[],S=v?Hy(v.parts,C,k):Hy(cB,[],k);return mB(S)},[e,r]),void 0,e?`session:${e}`:"chrome"),o=ve(h.useCallback(b=>e?b.sessionAbortFlags?.get(e)??null:null,[e])),{phase:i,isWorking:a}=Zp(),c=hd(e??""),d=c?.type==="retry"?c.attempt:void 0,u=c?.type==="retry"?c.next:void 0,f=h.useMemo(()=>gB(s),[s]),p=h.useMemo(()=>{const b=!!(o&&!o.acknowledged);return{wasAborted:b,abortActive:b}},[o]),m=h.useMemo(()=>{if(p.wasAborted)return{...lB,wasAborted:!0,abortActive:p.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1,retryInfo:null};const b=a,k=i==="busy",v=!1,x=i==="retry";let C="idle";b&&(f.activePartType==="tool"||f.activePartType==="editing"?C="tooling":C="streaming");const S=x?{attempt:d,next:u}:null;return{activity:C,hasWorkingContext:b,hasActiveTools:f.activePartType==="tool"||f.activePartType==="editing",isWorking:b,isStreaming:k,isCooldown:v,lifecyclePhase:k?"streaming":null,statusText:b?f.statusText:null,isGenericStatus:b?f.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:b,compactionDeadline:null,activePartType:b?f.activePartType:void 0,activeToolName:b?f.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,retryInfo:S}},[i,a,f,p,d,u]),g=h.useMemo(()=>({isActive:a&&f.activePartType==="text",characterCount:0}),[a,f.activePartType]),y=m;return{activeModel:n.model,forming:g,working:y}}const vB=({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,ic=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`},Sb=h.memo(({isWorking:e,startedAt:t,statusText:n})=>{const r=ve(p=>p.currentSessionId),s=Ke(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}=wb(),a=Lv(r??""),c=qe(p=>p.providers),d=h.useMemo(()=>{if(!o)return null;const p=c.find(m=>m.id===o.providerId);return lm(p,o.modelId)||null},[o,c]);if(s?.visible===!1)return null;const u=s?.message?kn(s.message):n??i.statusText,f=s?.message||n?!1:i.isGenericStatus;return l.jsx(Tx,{isWorking:e||i.isWorking,statusText:u,isGenericStatus:f,isWaitingForPermission:i.isWaitingForPermission,retryInfo:i.retryInfo,modelName:d,providerId:o?.providerId??null,startedAt:n?t??a??null:a??t??null})});Sb.displayName="LiveTurnStatus";const xB=({turnId:e,isLiveTurn:t,isWorking:n,isAwaitingRecovery:r=!1,hasActivity:s,isActivityExpanded:o,onToggleActivity:i,startedAt:a,completedAt:c,durationMs:d,liveStatusText:u,wasSteered:f})=>{const p=vB({startedAt:a,completedAt:c,durationMs:d}),m=!t&&r,g=t?"Agent working":m?"Reconnecting · last seen working":p!==null?`Worked for ${ic(p)}${f?" · Steered":""}`:s?"Agent activity":null,y=`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(Sb,{isWorking:n,startedAt:a,statusText:u}):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(Ee,{type:"button",variant:"ghost",size:"icon",className:R("h-6 w-6 shrink-0 rounded-md p-0 text-muted-foreground","hover:bg-interactive-hover hover:text-foreground"),"aria-expanded":o,"aria-controls":y,"aria-label":o?"Collapse activity":"Expand activity","data-turn-activity-toggle":"true",onClick:i,children:l.jsx(V,{name:"arrow-right-s",className:R("size-4 transition-transform duration-200 ease-out motion-reduce:transition-none",o&&"rotate-90"),"aria-hidden":"true"})}):null]})})},bB=h.memo(xB),wB=({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},SB=h.memo(function({userMessage:t,renderMessage:n}){return n(t)},(e,t)=>e.userMessage===t.userMessage),CB=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")},kB=({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(()=>CB(e),[e]),[u,f]=h.useState(()=>r&&c&&!d),p=h.useRef(!1),m=h.useRef(!1),g=h.useRef(e.activityParts.length),y=h.useRef(d);h.useLayoutEffect(()=>{const x=g.current,C=y.current,S=e.activityParts.length>x;g.current=e.activityParts.length,y.current=d;const w=wB({isExpanded:u,userToggled:p.current,wasAutoCollapsed:m.current,hasActivity:c,showWorkingStatus:r,hasFinalText:d,previousHadFinalText:C,hasNewActivity:S});m.current=w.wasAutoCollapsed,w.resetUserToggle&&(p.current=!1),w.isExpanded!==u&&f(w.isExpanded)},[c,d,u,r,e.activityParts.length]);const b=h.useCallback(()=>{p.current=!0,f(x=>!x),a?.("structural")},[a]),k=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(SB,{userMessage:e.userMessage,renderMessage:t}),k?l.jsx(bB,{turnId:e.turnId,isLiveTurn:r,isWorking:r,isAwaitingRecovery:s,hasActivity:c,isActivityExpanded:u,onToggleActivity:b,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(ZV,{turn:e,isExpanded:u,isLiveTurn:r,activeStreamingMessageId:o,activeStreamingPhase:i,onContentChange:a},e.turnId):null,l.jsx(rB,{turnId:e.turnId,assistantMessages:e.assistantMessages,renderMessage:t,deferEarlierMessages:n,activityPartIds:v})]})},MB=h.memo(kB),Gh="#pichamber-skill:",Kh="#pichamber-agent:",IB=e=>`${Gh}${encodeURIComponent(e)}`,_B=e=>`${Kh}${encodeURIComponent(e)}`,EB=e=>{if(!e?.startsWith(Gh))return null;try{return decodeURIComponent(e.slice(Gh.length))}catch{return null}},sq=e=>{if(!e?.startsWith(Kh))return null;try{return decodeURIComponent(e.slice(Kh.length))}catch{return null}},jB=/(^|\s)\/skill:([A-Za-z0-9][A-Za-z0-9_-]*)/g,TB=/(```[\s\S]*?```|~~~[\s\S]*?~~~)/g,AB=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"),Cb=(e,t)=>e.split(TB).map((n,r)=>r%2===1?n:t(n)).join(""),LB=e=>Cb(e,t=>t.replace(/ *\n/g,`
201
- `)),NB=({textContent:e,agentMention:t,skillNames:n})=>{let r=Cb(e,AB);if(t?.token&&r.includes(t.token)){const s=`[${t.token}](${_B(t.name)})`;r=r.replace(t.token,s)}return r=r.replace(jB,(s,o,i)=>n.has(i)?`${o}[/skill:${i}](${IB(i)})`:s),LB(r)},RB=({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,u]=h.useState(!1),f=kr(S=>S.skills),p=xa(),m=!a,g=h.useRef(null),y=h.useMemo(()=>new Map(f.map(S=>[S.name,S])),[f]),b=h.useCallback(S=>{y.has(S)&&R4(S,p)},[p,y]),k=h.useCallback(S=>{if(typeof window>"u")return!1;const w=window.getSelection();if(!w||w.isCollapsed||w.rangeCount===0)return!1;const M=w.getRangeAt(0);return S.contains(M.startContainer)||S.contains(M.endContainer)},[]);h.useEffect(()=>{const S=g.current;if(!S)return;const w=()=>{a||u(S.scrollHeight>S.clientHeight)};w();const M=new ResizeObserver(w);return M.observe(S),()=>M.disconnect()},[i,a]);const v=h.useCallback(S=>{const w=S.target,I=w?.closest("[data-skill-name]")?.dataset.skillName??EB(w?.closest("a[href]")?.getAttribute("href"));if(I){S.preventDefault(),S.stopPropagation(),b(I);return}const E=g.current;E&&(k(E)||!a&&d&&c(!0))},[k,a,d,b]),x=h.useCallback(S=>{S.stopPropagation(),c(!1)},[]),C=h.useMemo(()=>NB({textContent:i,agentMention:n,skillNames:new Set(y.keys())}),[n,y,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(V,{name:"arrow-up-s",className:"h-3.5 w-3.5"})}),l.jsx("div",{className:R("break-words font-sans typography-markdown-body",a&&"pb-3",m&&"line-clamp-2",d&&!a&&"cursor-pointer"),ref:g,onClick:v,children:l.jsx(ya,{content:C,className:R("[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",m&&["[&_.markdown-content>*]:my-0","[&_[data-component='markdown-code']]:my-0","[&_[data-component='markdown-code']]:inline","[&_[data-component='markdown-code']]:border-0","[&_[data-component='markdown-code']]:bg-transparent","[&_[data-component='markdown-code']>*:first-child]:hidden","[&_[data-component='markdown-code']>div]:inline","[&_[data-component='markdown-code']>div]:p-0","[&_[data-component='markdown-code']_pre]:inline","[&_[data-component='markdown-code']_code]:inline","[&_[data-md-code-line]]:!inline","[&_[data-md-code-line-number]]:hidden","[&_[data-md-code-line-break]]:!inline"]),disableLinkSafety:!0,enableFileReferences:!1})})]},e.id||`${t}-user-text`)},PB=h.memo(RB),DB="application/vnd.github.issue-link",OB="application/vnd.github.pull-request-link",kb=e=>e.mime===DB?"issue":e.mime===OB?"pr":null,Mb=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`,HB=e=>{const t=e.split(".");return t.length>1?t[t.length-1].toLowerCase():""},FB=e=>{if(!e)return"Unnamed file";const n=e.replace(/\\/g,"/").split("/");return n[n.length-1]||e},Yh=e=>kb(e)!==null&&typeof e.filename=="string"&&e.filename.trim().length>0?e.filename.trim():FB(e.filename||e.url),Ib=z.memo(({files:e,onShowPopup:t,className:n})=>{const[r,s]=z.useState(!1),[o,i]=z.useState(null),a=z.useRef(null),c=z.useMemo(()=>e.filter(b=>b.type==="file"&&(b.filename||b.mime||b.url)),[e]),d=c.length,u=z.useCallback(()=>{const b=a.current?.closest('[data-slot="dialog-content"], [role="dialog"]');i(b||null)},[]),f=z.useCallback(b=>{se.getState().navigateToDiagram(b),s(!1)},[]);if(d===0)return null;const p=c[0],m=Yh(p),g=Mb(p.size),y=d===1?`${m}${g?` (${g})`:""}`:`${d} attachments`;return l.jsxs(V5,{open:r,onOpenChange:s,children:[l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(B5,{render:l.jsxs("button",{ref:a,type:"button",className:R("inline-flex items-center gap-1.5 rounded-md px-1.5 py-1 text-xs font-medium","text-muted-foreground/80 hover:text-foreground transition-colors cursor-pointer select-none",n),"aria-label":`View ${d} attachment${d!==1?"s":""}`,onPointerDownCapture:u,onFocusCapture:u,children:[l.jsx(V,{name:"attachment-2",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate max-w-[200px]",children:y}),l.jsx(V,{name:r?"arrow-up-s":"arrow-down-s",className:"h-3.5 w-3.5 shrink-0 opacity-60"})]})})}),l.jsx(pt,{side:"top",children:d===1?`Attachment: ${m}`:`View ${d} attachments`})]}),l.jsx($5,{container:o||void 0,children:l.jsx(z5,{side:"top",align:"end",sideOffset:6,collisionPadding:8,children:l.jsxs(U5,{style:Vx,className:R(Fx,"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(V,{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((b,k)=>{const v=b.url||`${Yh(b)}-${k}`;return l.jsx(VB,{file:b,onShowPopup:t,onNavigateToDiagram:f},v)})})]})})})]})}),VB=z.memo(function({file:t,onShowPopup:n,onNavigateToDiagram:r}){const s=Yh(t),o=HB(s),i=Mb(t.size),c=!!(t.mime?.startsWith("image/")&&t.url),d=kb(t),u=t.source,f=typeof u?.type=="string"?u.type:void 0,p=u&&typeof u.path=="string"?u.path:void 0,m=f==="file"&&p?p:t.url||"",g=m&&cx(m),y=z.useCallback(()=>{n&&t.url&&n({open:!0,title:s,content:"",image:{url:t.url,mimeType:t.mime,filename:s,size:t.size}})},[n,t.url,t.mime,t.size,s]),b=z.useCallback(x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),y())},[y]),k=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(),ph(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(V,{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(V,{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:k});const v=t.url;return l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx("div",{role:"button",tabIndex:0,"aria-label":`Preview ${s}`,onClick:y,onKeyDown:b,className:"pt-3 first:pt-0 space-y-2 cursor-pointer rounded-lg",children:k})}),l.jsx(pt,{side:"left",className:R(ux),children:l.jsx(fx,{imageUrl:v,filename:s,metaLine:[o.toUpperCase(),i].filter(Boolean).join(" · ")})})]})});Ib.displayName="UserMessageAttachments";const _b=e=>{if(e==="12h")return!0;if(e==="24h")return!1},BB=(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:_b(t)}):n.fallback??""},oq=(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?_b(t):n.hour12}):""},Eb=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),$B=(e,t)=>{const n=new Date(t);return n.setDate(t.getDate()-1),Eb(e,n)},zB=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),jb=(e,t)=>{if(!zB(e))return"";const n=new Date(e),r=new Date,s=BB(n,t),o="en-US";if(Eb(n,r))return s;if($B(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}`},Dm=h.memo(({sessionId:e,messageId:t,size:n="user",isLatestMessage:r=!1})=>{const s=ve(m=>m.revertToMessage),[o,i]=h.useState(!1),[a,c]=h.useState(()=>{if(!e)return!1;const g=Je().getState().reducer.bySession.get(e);return g?.lifecycle==="busy"||g?.lifecycle==="retry"});h.useEffect(()=>{if(!e){c(!1);return}const m=()=>{const y=Je().getState().reducer.bySession.get(e);c(y?.lifecycle==="busy"||y?.lifecycle==="retry")};return m(),Je().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),Ne.success("Reverted — conversation rewound. Files on disk were not changed.")}catch(y){const b=y instanceof Error?y.message:"Failed to revert conversation";Ne.error(b)}finally{i(!1)}},[o,a,t,s,e]),u=o||a||!e||!t,f=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(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(Ee,{type:"button",variant:"ghost",size:"icon",disabled:u,"aria-label":"Revert conversation to here",className:R(f,"text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",u&&"opacity-50"),onPointerDown:m=>m.stopPropagation(),onClick:d,children:o?l.jsx(V,{name:"loader-4",className:R(p,"animate-spin"),"aria-hidden":"true"}):l.jsx(V,{name:"history",className:p,"aria-hidden":"true"})})}),l.jsx(pt,{sideOffset:6,children:"Revert to here"})]})});Dm.displayName="MessageRevertAction";const Om=h.memo(({sessionId:e,messageId:t,size:n="user"})=>{const r=ve(p=>p.forkFromMessage),[s,o]=h.useState(!1),[i,a]=h.useState(()=>{if(!e)return!1;const m=Je().getState().reducer.bySession.get(e);return m?.lifecycle==="busy"||m?.lifecycle==="retry"});h.useEffect(()=>{if(!e){a(!1);return}const p=()=>{const g=Je().getState().reducer.bySession.get(e);a(g?.lifecycle==="busy"||g?.lifecycle==="retry")};return p(),Je().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),Ne.success("Forked — new session created from this message.")}catch(g){const y=g instanceof Error?g.message:"Failed to fork session";Ne.error(y)}finally{o(!1)}},[s,r,i,t,e]),d=s||i||!e||!t,u=n==="user"?"h-6 w-6":"h-8 w-8",f=n==="user"?"h-3 w-3":"h-3.5 w-3.5";return l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(Ee,{type:"button",variant:"ghost",size:"icon",disabled:d,"aria-label":"Fork conversation from here",className:R(u,"text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",d&&"opacity-50"),onPointerDown:p=>p.stopPropagation(),onClick:c,children:s?l.jsx(V,{name:"loader-4",className:R(f,"animate-spin"),"aria-hidden":"true"}):l.jsx(V,{name:"git-branch",className:f,"aria-hidden":"true"})})}),l.jsx(pt,{sideOffset:6,children:"Fork to new session"})]})});Om.displayName="MessageForkAction";const UB=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}`},ZB=({part:e})=>{const[t,n]=h.useState(!1),r=Vn(),s=ve(m=>m.setCurrentSession),o=xa(),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():"",u=typeof e.taskSessionID=="string"?e.taskSessionID.trim():"",f=UB(e.model),p=h.useCallback(()=>{!r||!u||(s(u,r),o?.closeDrawers?.())},[r,u,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,f?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:f}):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,u?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]})},Fy={background:"transparent",backgroundColor:"transparent"},WB=({part:e})=>{const t=typeof e.shellAction?.output=="string"?e.shellAction.output:"",[n,r]=h.useState(!0),{value:s,show:o}=Sm(!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:R("inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none",a==="error"?"bg-[var(--status-error-background)] text-[var(--status-error)]":"bg-foreground/5 text-muted-foreground"),children:a}):null]}),i?l.jsx("div",{className:"typography-meta mt-1.5 overflow-x-auto font-mono","data-no-drawer-swipe":"true",children:l.jsx(Uc,{language:"bash",code:i,codeStyle:Fy,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(u=>!u),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(V,{name:"check",className:"h-3.5 w-3.5"}):l.jsx(V,{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(Uc,{language:"bash",code:t,codeStyle:Fy,wrap:!0})}):null]}):null]})},qB={contain:"layout",transform:"translateZ(0)"},GB=h.memo(function({sessionId:t,messageId:n,parts:r,messageCreatedAt:s,isLatestMessage:o=!1,isMobile:i,alwaysShowActions:a=i,hasTouchInput:c,hasTextContent:d,onCopyMessage:u,copiedMessage:f,onShowPopup:p,agentMention:m,userActionsMode:g="inline"}){const y=se(F=>F.timeFormatPreference),[b,k]=h.useState(!1),v=h.useRef(null),x=h.useMemo(()=>r.filter(yb),[r]),C=h.useMemo(()=>r.filter(F=>F.type==="file"&&!!(F.filename||F.mime||F.url)),[r]),S=m?.token;let w=!1;const M=!!u,I=!!f,E=!!(c??i),_=!!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)},[]),N=h.useCallback(()=>{!E||!M||!_||typeof window>"u"||(j(),k(!0),v.current=window.setTimeout(()=>{k(!1),v.current=null},1800))},[M,j,_,E]);h.useEffect(()=>{_||(k(!1),j())},[j,_]);const O=h.useCallback(F=>{!u||!_||(F.stopPropagation(),F.preventDefault(),u(),E&&N())},[_,E,u,N]),L=h.useMemo(()=>{if(typeof s!="number"||s<=0)return null;const F=jb(s,y);return F.length>0?F:null},[s,y]),P=i||a,W=A?l.jsx("div",{className:R("group/user-actions",P?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:R("flex items-center justify-start gap-1.5",g==="inline"?"translate-x-5":"translate-x-0",a?"pointer-events-auto opacity-100":"pointer-events-none opacity-0 transition-opacity duration-150 group-hover/message:pointer-events-auto group-hover/message:opacity-100 group-hover/user-actions:pointer-events-auto group-hover/user-actions:opacity-100 group-hover/user-shell:pointer-events-auto group-hover/user-shell:opacity-100"),children:[L?l.jsxs(ft,{children:[l.jsx(ht,{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: ${L}`,children:[l.jsx(V,{name:"time",className:"h-3.5 w-3.5"}),l.jsx("span",{className:"message-footer__label",children:L})]})}),l.jsx(pt,{children:L})]}):null,o?null:l.jsx(Dm,{sessionId:t??null,messageId:n,size:"assistant"}),l.jsx(Om,{sessionId:t??null,messageId:n,size:"assistant"}),M&&_&&l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(Ee,{type:"button",variant:"ghost",size:"icon","data-visible":b||I?"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:F=>F.stopPropagation(),onClick:O,onFocus:()=>k(!0),onBlur:()=>{I||k(!1)},children:I?l.jsx(V,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):l.jsx(V,{name:"file-copy",className:"h-3.5 w-3.5"})})}),l.jsx(pt,{sideOffset:6,children:"Copy message"})]})]}),C.length>0?l.jsx(Ib,{files:C,onShowPopup:p}):null]})}):null;return T?l.jsxs("div",{className:"relative w-full group/message",style:qB,onTouchStart:E&&M&&_?N:void 0,children:[l.jsx("div",{className:R("leading-relaxed text-foreground/90 text-base overflow-x-hidden","overflow-y-hidden"),style:void 0,children:x.map((F,q)=>{if(pb(F))return l.jsx(h.Fragment,{children:l.jsx(ZB,{part:F})},F.id??`user-subtask-${q}`);if(mb(F))return l.jsx(h.Fragment,{children:l.jsx(WB,{part:F})},F.id??`user-shell-${q}`);let K;return m&&S&&!w&&Nm(F).includes(S)&&(K=m,w=!0),l.jsx(h.Fragment,{children:l.jsx(PB,{part:F,messageId:n,isMobile:i,agentMention:K})},F.id??`user-text-${q}`)})}),W]}):l.jsx(l.Fragment,{children:W})}),Vy=8,KB=280,YB=({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),u=h.useRef(null),f=h.useRef(KB),p=h.useRef(null),m=h.useRef(null),g=h.useRef(null),y=h.useRef(!1),b=ve(_=>_.createSession),k=Ge(_=>_.setPendingInputText),v=se(_=>_.isMobile);h.useEffect(()=>{y.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,y.current&&(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),d(!1),n(_=>({..._,show:!1})),s(""),i(""),y.current=!1)},[]),C=h.useCallback(_=>{if(typeof window>"u")return _;const T=window.innerWidth,j=f.current/2,N=Vy+j,O=T-Vy-j;return N>O?T/2:Math.min(Math.max(_,N),O)},[]),S=h.useCallback(()=>{if(!p.current)return;const{plainText:_,markdownText:T,rect:A}=p.current,j=!t.show,N=v?A.left+A.width/2:C(A.left+A.width/2),O=A.top-10;s(_),i(T),n({x:N,y:O,show:!0}),y.current=!0,j&&(d(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{d(!1),m.current=null}))},[C,v,t.show]);h.useLayoutEffect(()=>{if(!t.show||v||!u.current)return;const _=u.current.offsetWidth;!Number.isFinite(_)||_<=0||_===f.current||(f.current=_,n(T=>({...T,x:C(T.x)})))},[C,v,t.show]),h.useEffect(()=>{if(!t.show||v)return;const _=()=>{n(T=>({...T,x:C(T.x)}))};return window.addEventListener("resize",_),()=>{window.removeEventListener("resize",_)}},[C,v,t.show]);const w=h.useCallback(()=>{const _=window.getSelection(),T=e.current;if(!_||!T){a.current||x();return}const A=hn(_.toString());if(!A){a.current||x();return}const j=_.getRangeAt(0);if(!T.contains(j.commonAncestorContainer)){a.current||x();return}const N=j.getBoundingClientRect();p.current={plainText:A,markdownText:G3(j,A),rect:N},a.current||S()},[e,x,S]);h.useEffect(()=>{const _=e.current;if(!_)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 N=window.getSelection();N&&N.toString().trim()?S():x()},10))};document.addEventListener("selectionchange",w),_.addEventListener("mousedown",T),document.addEventListener("mouseup",A);const j=N=>{u.current&&!u.current.contains(N.target)&&!window.getSelection()?.toString().trim()&&x()};return document.addEventListener("mousedown",j),()=>{g.current!==null&&(window.clearTimeout(g.current),g.current=null),document.removeEventListener("selectionchange",w),_.removeEventListener("mousedown",T),document.removeEventListener("mouseup",A),document.removeEventListener("mousedown",j)}},[e,w,x,S]);const M=h.useCallback(()=>{if(!o)return;const _=Xp(o);k(_,"append"),x(),window.getSelection()?.removeAllRanges(),queueMicrotask(()=>{co()})},[o,k,x]),I=h.useCallback(async()=>{if(!r)return;await b(void 0,null,null)&&k(r,"replace"),x(),window.getSelection()?.removeAllRanges()},[r,b,k,x]),E=h.useCallback(async()=>{if(!r)return;const _=await ir(r);_.ok||console.error("Failed to copy:",_.error),x(),window.getSelection()?.removeAllRanges()},[r,x]);return t.show?v?Gi.createPortal(l.jsx("div",{ref:u,className:R("fixed left-3 right-3 bottom-0 z-50 mx-auto max-w-[420px]","rounded-2xl border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] p-2 shadow-lg","safe-area-bottom","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",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:M,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--primary-base)] text-[var(--primary-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Add to current chat",type:"button",children:[l.jsx(V,{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:I,className:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Create new session with selection",type:"button",children:[l.jsx(V,{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:R("flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left","text-sm font-medium leading-tight","bg-[var(--surface-muted)] text-[var(--surface-foreground)]","active:opacity-80","transition-opacity duration-150"),title:"Copy",type:"button",children:[l.jsx(V,{name:"file-copy",className:"h-5 w-5 flex-shrink-0"}),l.jsx("span",{className:"min-w-0 whitespace-normal",children:"Copy"})]})]})}),document.body):Gi.createPortal(l.jsx("div",{ref:u,className:"fixed z-50",style:{left:t.x,top:t.y,transform:"translate(-50%, -100%)"},children:l.jsxs("div",{className:R("flex items-center gap-1 whitespace-nowrap","rounded-lg border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] shadow-none","px-1.5 py-1","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",c?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0"),children:[l.jsxs("button",{onClick:M,className:R("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Add to current chat",type:"button",children:[l.jsx(V,{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:I,className:R("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),title:"Create new session with selection",type:"button",children:[l.jsx(V,{name:"chat-new",className:"h-4 w-4"}),l.jsx("span",{className:"whitespace-nowrap",children:"New session"})]})]})}),document.body):null},jl=[{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 XB(e){if(!e||e==="build")return jl[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)%(jl.length-1);return jl[n]}const JB=h.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,onShareImage:r,sessionId:s,messageId:o,isLatestMessage:i=!1})=>{const a=Ed(),[c,d]=h.useState(!1),{value:u,show:f,clear:p}=Sm(!1,2e3),[m,g]=h.useState(!1),y=h.useRef(null),b=!!n,k=h.useCallback(()=>{y.current!==null&&typeof window<"u"&&(window.clearTimeout(y.current),y.current=null)},[]);h.useEffect(()=>k,[k]),h.useEffect(()=>{(!e||!b)&&(d(!1),k(),p())},[b,k,p,e]);const v=h.useCallback(()=>{!t||!b||!e||typeof window>"u"||(k(),d(!0),y.current=window.setTimeout(()=>{d(!1),y.current=null},1800))},[b,k,e,t]),x=h.useCallback(async S=>{!n||!e||(S.stopPropagation(),S.preventDefault(),await n()===!1)||(f(!0),t&&v())},[e,t,n,v,f]),C=h.useCallback(async S=>{if(S.stopPropagation(),S.preventDefault(),!(m||!e)){g(!0);try{const M=S.currentTarget.closest("[data-message-text-export-root]")?.querySelector("[data-message-text-export-source]")??null;await r(M)}finally{g(!1)}}},[e,m,r]);return l.jsxs(l.Fragment,{children:[s&&o&&!i?l.jsx(Dm,{sessionId:s,messageId:o,size:"assistant"},"message-revert"):null,s&&o?l.jsx(Om,{sessionId:s,messageId:o,size:"assistant"},"message-fork"):null,n&&l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(Ee,{type:"button",variant:"ghost",size:"icon","data-visible":c||u?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!e&&"opacity-50"),disabled:!e,"aria-label":"Copy message text","aria-hidden":!e,onPointerDown:S=>S.stopPropagation(),onClick:S=>{x(S)},onFocus:()=>{e&&d(!0)},onBlur:()=>{u||d(!1)},children:u?l.jsx(V,{name:"check",className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):l.jsx(V,{name:"file-copy",className:"h-3.5 w-3.5"})})}),l.jsx(pt,{sideOffset:6,children:"Copy answer"})]},"message-copy"),a!=="mini-chat"?l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(Ee,{type:"button",size:"icon",variant:"ghost",disabled:m||!e,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",(!e||m)&&"opacity-50"),onPointerDown:S=>S.stopPropagation(),onClick:S=>{C(S)},children:m?l.jsx(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}):l.jsx(V,{name:"image-download",className:"h-4 w-4"})})}),l.jsx(pt,{sideOffset:6,children:m?"Saving image...":"Save as image"})]},"message-share"):null]})});async function QB(e,t){const n=t;if(!n)return;let r=null;try{const{toPng:s}=await mt(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=`
202
- padding: ${d}px;
203
- background-color: ${c};
204
- display: inline-block;
205
- `;const u=o.cloneNode(!0);u.style.cssText=`
206
- ${i.cssText}
207
- transform: none;
208
- contain: none;
209
- `,u.querySelectorAll('[data-message-actions="true"]').forEach(v=>{v.style.display="none"}),u.querySelectorAll('[data-message-action-group="true"]').forEach(v=>{v.style.display="none"});const m=u.querySelectorAll('[aria-label^="Message time:"]'),g=new Set;m.forEach(v=>{const C=v.getAttribute("aria-label")?.replace("Message time:","").trim();if(!C||v.textContent?.includes(C))return;const S=document.createElement("span");S.style.marginLeft="4px",S.textContent=C,v.appendChild(S);const M=v.parentElement?.parentElement;!M||g.has(M)||(M.style.justifyContent="flex-start",g.add(M))}),r.appendChild(u),document.body.appendChild(r);const y=await s(r,{quality:1,pixelRatio:2,backgroundColor:c}),b=`message-${e}.png`,k=await U9({filename:b,mimeType:"image/png",data:y});k==="downloaded"?Ne.success("Image saved"):k==="shared"&&Ne.success("Image shared")}catch(s){console.error("Failed to generate image:",s),Ne.error("Failed to generate image")}finally{r&&r.parentNode&&r.parentNode.removeChild(r)}}function e$({visibleParts:e,isMessageCompleted:t,messageFinish:n,messageCompletedAt:r,messageCreatedAt:s,durationMs:o,turnGroupingContext:i,errorMessage:a,isMobile:c,isMiniChatSurface:d,timeFormatPreference:u}){const f=h.useMemo(()=>e.filter(S=>S.type==="text"),[e]),p=h.useMemo(()=>{if(c||d)return null;for(const S of f){const w=S.text;if(typeof w!="string"||w.length===0)continue;const M=ZI(w)[0];if(M)return M.includes("0.0.0.0")?M.replace("0.0.0.0","127.0.0.1"):M}return null},[f,c,d]),m=i?.isLastAssistantInTurn??!1,g=!!i?.isWorking,y=h.useRef(g),b=y.current&&!g;h.useEffect(()=>{y.current=g},[g]);const k=n==="stop"||t&&!a,v=!t,x=h.useMemo(()=>{if(!m||g)return;if(typeof o=="number"&&o>0)return ic(o);if(typeof r=="number"&&typeof s=="number"&&r>s)return ic(r-s);const S=i?.userMessageCreatedAt;if(typeof S=="number"&&typeof r=="number"&&r>S)return ic(r-S)},[m,g,o,r,s,i?.userMessageCreatedAt]),C=h.useMemo(()=>{const S=typeof r=="number"&&r>0?r:typeof s=="number"&&s>0?s:null;if(S===null)return null;const w=jb(S,u);return w.length>0?w:null},[r,s,u]);return{messagePreviewUrl:p,isLastAssistantInTurn:m,isTurnWorking:g,shouldAnimateTurnFooter:b,hasStopFinish:k,awaitingMessageCompletion:v,turnDurationText:x,footerTimestamp:C}}const t$={contain:"layout",transform:"translateZ(0)"},n$={containerType:"inline-size",containerName:"message-footer"},r$=h.memo(({sessionId:e,messageId:t,parts:n,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,durationMs:a,isLatestMessage:c=!1,isMobile:d,alwaysShowActions:u,hasTouchInput:f,onShowPopup:p,streamPhase:m,onContentChange:g,hasTextContent:y=!1,onCopyMessage:b,turnGroupingContext:k,errorMessage:v,errorVariant:x="error",footerProviderID:C,footerModelName:S,footerAgentName:w,footerVariant:M,isDarkTheme:I=!1})=>{const E=Ed(),_=h.useRef(null),T=h.useRef(null),A=!!(f??d),j=!!(u??d),{src:N,onError:O,hasLogo:L}=om(C??null),P=h.useMemo(()=>Rm(n),[n]),W=E==="mini-chat",F=ve(Ce=>Ce.currentSessionId),q=ve(Ce=>Ce.getDirectoryForSession),K=Vn(),Q=se(Ce=>Ce.timeFormatPreference),D=se(Ce=>Ce.openContextPreview),{messagePreviewUrl:U,isLastAssistantInTurn:Y,isTurnWorking:ne,shouldAnimateTurnFooter:$,hasStopFinish:J,awaitingMessageCompletion:G,turnDurationText:ue,footerTimestamp:B}=e$({visibleParts:P,isMessageCompleted:r,messageFinish:s,messageCompletedAt:o,messageCreatedAt:i,durationMs:a,turnGroupingContext:k,errorMessage:v,isMobile:d,isMiniChatSurface:W,timeFormatPreference:Q}),ie=J?"completed":m,xe=!!y&&!G,de=h.useCallback(async Ce=>{const Ae=Ce??T.current??_.current;await QB(t,Ae)},[t]),Se=!!v,je=x==="info"?"information":"error-warning",Oe=Y&&(y||!!v)&&!ne,Be=h.useMemo(()=>l.jsx(JB,{hasCopyableText:xe,isTouchContext:A,onCopyMessage:b,onShareImage:de,sessionId:e,messageId:t,isLatestMessage:c}),[de,xe,c,A,t,b,e]),Ie=h.useMemo(()=>{const Ce=[];let Ae=0;for(;Ae<P.length;){const Me=P[Ae];if(Me.type!=="text"){Ae++;continue}Ce.push(l.jsx("div",{ref:T,"data-message-text-export-source":"true",children:l.jsx(j4,{part:Me,sessionId:e,messageId:t,streamPhase:ie,onContentChange:g,onShowPopup:p})},`assistant-text-${t}-${Ae}`)),Ae++}return Ce},[t,e,g,p,ie,P]),fe="text-sm text-muted-foreground tabular-nums flex items-center gap-1",ee=!W&&!d,he=l.jsx(l.Fragment,{children:ee&&U?l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsx(Ee,{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:Ce=>Ce.stopPropagation(),onClick:()=>{const Ce=K??(F?q(F):null);Ce&&D(Ce,U)},children:l.jsx(V,{name:"global",className:"h-4 w-4"})})}),l.jsx(pt,{sideOffset:6,children:"Open preview"})]}):null});return l.jsxs("div",{ref:_,"data-message-text-export-root":"true",className:R("relative w-full group/message"),style:t$,children:[l.jsx(YB,{containerRef:_}),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:[Ie,Se&&l.jsx(Lm,{children:l.jsx("div",{className:R("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(V,{name:je,className:R("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(ya,{content:v??"",onShowPopup:p,className:"[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0",enableFileReferences:!1})})]})})},"assistant-error")]}),l.jsx(rm,{files:n,onShowPopup:p}),Oe&&l.jsxs("div",{className:R("mt-2 mb-1 flex flex-wrap items-center justify-start gap-x-3 gap-y-1.5",$&&"message-footer-enter"),style:n$,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:[S?l.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[L&&N?l.jsx("img",{src:N,alt:"",className:"h-3.5 w-3.5 flex-shrink-0",style:{filter:I?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:O}):l.jsx(V,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0",style:{color:`var(${XB(w).var})`}}),l.jsx("span",{className:"truncate",children:S})]}):null,M&&!["default","none"].includes(M.toLowerCase())?l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx(V,{name:"brain-ai-3",className:"h-3.5 w-3.5 flex-shrink-0"}),l.jsx("span",{className:"message-footer__label",children:M[0].toLowerCase()+M.slice(1)})]}):null,w?l.jsxs("span",{className:"flex items-center gap-1",children:[l.jsx(V,{name:"ai-agent",className:"h-3.5 w-3.5 flex-shrink-0"}),l.jsx("span",{className:"message-footer__label",children:w})]}):null,ue?l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsxs("span",{className:"text-sm text-muted-foreground tabular-nums flex items-center gap-1",children:[l.jsx(V,{name:"hourglass",className:"h-3.5 w-3.5"}),l.jsx("span",{className:"message-footer__label",children:ue})]})}),l.jsx(pt,{children:ue})]}):null,B?l.jsxs(ft,{children:[l.jsx(ht,{asChild:!0,children:l.jsxs("span",{className:fe,"aria-label":`Message time: ${B}`,children:[l.jsx(V,{name:"time",className:"h-3.5 w-3.5"}),l.jsx("span",{className:"message-footer__label",children:B})]})}),l.jsx(pt,{children:B})]}):null]}),l.jsxs("div",{className:R("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:[Be,he]})]})]})]})}),Cf=h.memo(({isUser:e,...t})=>e?l.jsx(GB,{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(r$,{...t})),Wc=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}},Tb="GitHub issue context (JSON)",Ab="GitHub pull request context (JSON)",By=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,$y=(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}},s$=e=>{const t=$y(e,Tb);if(t){const r=t.issue,s=r?.number,o=r?.title,i=r?.url;return!By(s)||typeof o!="string"||typeof i!="string"?null:{type:"file",mime:"application/vnd.github.issue-link",filename:`Issue #${s}: ${o}`,url:i}}const n=$y(e,Ab);if(n){const r=n.pr,s=r?.number,o=r?.title,i=r?.url;return!By(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},o$=e=>!!e.trim().startsWith("The following tool was executed by the user"),Hm=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 o$(r)||s.startsWith(Tb)||s.startsWith(Ab)}).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=s$(r);if(o)return o}if(r.startsWith("The following tool was executed by the user"))return{type:"text",text:"/shell"}}return t}),zy=new WeakMap,Lb=e=>{if(!e||!Wc(e.info).isUser)return!1;const t=zy.get(e.parts);if(t!==void 0)return t;const n=Hm(Ld(e.parts)),r=Pm(n,{includeReasoning:!0}).length===0;return zy.set(e.parts,r),r};function kf(e){const[t,n]=h.useState(e);return h.useEffect(()=>{e!=null&&n(e)},[e]),e??t}const un=(e,t)=>{if(typeof e=="object"&&e!==null)return e[t]},Kr=e=>{if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0},Uy=e=>{const t=un(e,"model"),n=typeof t=="object"&&t!==null?t:null;return{providerId:Kr(un(e,"providerID"))??Kr(n?.providerID)??Kr(n?.providerId),modelId:Kr(un(e,"modelID"))??Kr(n?.modelID)??Kr(n?.modelId)}};function i$({message:e,previousMessage:t,isUser:n,sessionId:r,isInActiveTurn:s,turnGroupingContext:o}){const i=qe(A=>A.providers),a=_t(A=>A.getAgentModelForSession),c=_t(A=>A.getSessionModelSelection),d=_t($9(A=>s&&r?A.sessionAgentSelections.get(r)??null:null)),u=h.useMemo(()=>{if(n||!t)return null;const A=un(t.info,"clientRole"),j=un(t.info,"role");if((typeof A=="string"?A:typeof j=="string"?j:void 0)!=="user")return null;const O=un(t.info,"mode"),L=un(t.info,"agent"),P=Uy(t.info),W=un(t.info,"variant"),F=typeof O=="string"&&O.trim().length>0?O:typeof L=="string"&&L.trim().length>0?L:void 0,q=P.providerId,K=P.modelId,Q=typeof W=="string"&&W.trim().length>0?W:void 0;return!F&&!q&&!K&&!Q?null:{agentName:F,providerId:q,modelId:K,variant:Q}},[n,t]),f=h.useMemo(()=>{if(n)return;const A=un(e.info,"mode");if(typeof A=="string"&&A.trim().length>0)return A;const j=un(e.info,"agent");if(typeof j=="string"&&j.trim().length>0)return j;if(u?.agentName)return u.agentName;if(r)return d??void 0},[n,e.info,u,r,d]),p=n?{providerId:void 0,modelId:void 0}:Uy(e.info),m=p.providerId??null,g=p.modelId??null,y=h.useMemo(()=>{if(n||!r)return null;if(u?.providerId&&u?.modelId)return{providerId:u.providerId,modelId:u.modelId};if(f){const j=a(r,f);if(j?.providerId&&j?.modelId)return j}const A=c(r);return A?.providerId&&A?.modelId?A:null},[n,r,f,u,a,c]),b=h.useMemo(()=>n?null:typeof m=="string"&&m.trim().length>0?m:y?.providerId??null,[n,m,y]),k=h.useMemo(()=>n?null:typeof g=="string"&&g.trim().length>0?g:y?.modelId??null,[n,g,y]),v=h.useMemo(()=>{if(n)return;const A=b&&i.length>0?i.find(j=>j.id===b):void 0;return lm(A,k)||void 0},[n,b,k,i]),x=h.useMemo(()=>{if(n||!b||!k)return!1;const A=i.find(O=>O.id===b);if(!A?.models||!Array.isArray(A.models))return!1;const N=A.models.find(O=>O.id===k)?.variants;return!!(N&&Object.keys(N).length>0)},[n,k,b,i]),C=kf(f),S=kf(b??void 0),w=kf(v),M=C??void 0,I=S??null,E=w??void 0,_=n?void 0:Kr(un(e.info,"variant"))??o?.userMessageVariant??u?.variant;return{headerAgentName:M,headerProviderID:I,headerModelName:E,headerVariant:n?void 0:x?_??"Default":_}}class ss{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return ss.instance||(ss.instance=new ss),ss.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 a$({message:e,isUser:t,sessionId:n,streamPhase:r,assistantTextParts:s,shouldCoordinateRendering:o,animationHandlers:i,messageContainerRef:a}){const c=h.useMemo(()=>t||!n?!1:ss.getInstance().shouldAnimateMessage(e.info,n),[e.info,t,n]),d=i??null,u=h.useRef(!1),f=h.useRef(!1),p=h.useRef(!1),m=h.useRef(!1),g=h.useRef(!1);h.useEffect(()=>{u.current=!1,f.current=!1,p.current=!1,m.current=!1,g.current=!1},[e.info.id]);const y=!!un(e.info,"animationSettled"),b=r==="streaming"||r==="cooldown";b&&(g.current=!0);const k=c&&!y&&!b&&!g.current,v=!t&&c&&s.length>0&&!o;h.useEffect(()=>{if(d?.onStreamingCandidate){if(!v){f.current&&(d?.onReservationCancelled&&d.onReservationCancelled(),f.current=!1);return}m.current||(m.current=!0,d.onStreamingCandidate(),f.current=!0)}},[d,v]),h.useEffect(()=>{d?.onAnimationStart&&k&&(p.current||(d.onAnimationStart(),p.current=!0))},[d,k]),h.useEffect(()=>{if(t)return;const x=d?.onAnimatedHeightChange;if(!x||!(k||v))return;const S=a.current;if(!S)return;if(typeof window>"u"||typeof ResizeObserver>"u"){x(S.getBoundingClientRect().height);return}let w=null;const M=E=>{if(typeof window>"u"){x(E);return}w!==null&&window.cancelAnimationFrame(w),w=window.requestAnimationFrame(()=>{x(E)})},I=new ResizeObserver(E=>{const _=E[0];_&&M(_.contentRect.height)});return I.observe(S),M(S.getBoundingClientRect().height),()=>{w!==null&&(window.cancelAnimationFrame(w),w=null),I.disconnect()}},[k,t,d,v,a])}function l$(){const e=se(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 c$=ys(()=>mt(()=>import("./ToolOutputDialog-VlS12Xyq.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]))),d$=({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:u,isTablet:f,hasTouchInput:p}=Rr(),m=u||f,{currentTheme:g}=Fn(),y=h.useRef(null);cs("ui.chat_message.render"),i&&cs("ui.chat_message.render.streaming");const[b,k]=h.useState(!1),x=h.useMemo(()=>Wc(e.info),[e.info]).isUser,C=e.info.sessionID,{headerAgentName:S,headerProviderID:w,headerModelName:M,headerVariant:I}=i$({message:e,previousMessage:t,isUser:x,sessionId:C,isInActiveTurn:i,turnGroupingContext:o}),E=h.useMemo(()=>{const Me=Ld(e.parts);return x?Hm(Me):Me},[x,e.parts]),_=h.useMemo(()=>{const Me=e.info.time;return typeof Me?.completed=="number"?Me.completed:null},[e.info.time]),T=h.useMemo(()=>{const Me=e.info.time;return typeof Me?.created=="number"?Me.created:null},[e.info.time]),A=h.useMemo(()=>x?!0:!!(_&&_>0),[x,_]),j=h.useMemo(()=>{const Me=e.info.finish;return typeof Me=="string"?Me:void 0},[e.info]),N=h.useMemo(()=>Pm(E,{includeReasoning:!0}),[E]),O=h.useMemo(()=>{const Me=new Set;for(const Ze of o?.activityParts??[])Me.add(Ze.id);return Me},[o?.activityParts]),L=h.useMemo(()=>x?N:vb(N,O,e.info.id),[O,x,e.info.id,N]),P=x&&L.some(yb),W=h.useMemo(()=>x?[]:L.filter(Me=>Me.type==="text"),[L,x]),F=h.useMemo(()=>x?[]:N.filter(Me=>Me.type==="tool"),[x,N]),{popupContent:q,handleShowPopup:K,handlePopupChange:Q}=l$(),D=h.useMemo(()=>{if(!x)return;const Me=E.find(re=>re.type==="agent");if(!Me)return;const Ze=Me,gt=typeof Ze.name=="string"?Ze.name:void 0;if(!gt)return;const we=Ze.source&&typeof Ze.source.value=="string"&&Ze.source.value.trim().length>0?Ze.source.value:`@${gt}`;return{name:gt,token:we}},[x,E]),U=x&&L.length===0,Y=!A&&typeof j!="string",ne=h.useMemo(()=>x?!1:W.length===0||F.length===0?Y:!0,[W.length,F.length,Y,x]),$=g?.metadata.variant,J=h.useMemo(()=>$?$==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[$]),G=h.useMemo(()=>n?Wc(n.info):null,[n]),ue=!!o,B=o?.isLastAssistantInTurn??!1,ie=h.useMemo(()=>!x&&Lb(n),[x,n]),xe=h.useMemo(()=>x?!1:ue?!B:G?!G.isUser&&G.role==="assistant":!1,[ue,B,x,G]),de=h.useMemo(()=>A?"completed":i?a??"streaming":"completed",[a,i,A]);a$({message:e,isUser:x,sessionId:C,streamPhase:de,assistantTextParts:W,shouldCoordinateRendering:ne,animationHandlers:s,messageContainerRef:y}),h.useEffect(()=>{!x||!c||d?.(e.info.id)},[c,x,e.info.id,d]);const Se=h.useMemo(()=>{if(!x)return hb(e.info)},[x,e.info]),je=Se?.text,Oe=Se?.variant,Be=h.useMemo(()=>XV({isUser:x,displayParts:L,assistantErrorText:je}),[je,L,x]),Ie=Be.length>0,fe=h.useMemo(()=>x?!1:!QV(L,je),[je,L,x]),ee=h.useCallback(async()=>{let Me;if(x)Me=await ir(Be);else{const{renderMarkdownSync:Ze}=await mt(async()=>{const{renderMarkdownSync:gt}=await import("./markdownCore-B9AuEyYi.js").then(we=>we.m);return{renderMarkdownSync:gt}},__vite__mapDeps([21,8,22,23,24]));Me=await xM(Be,Ze(Be))}return Me.ok?(x&&(k(!0),setTimeout(()=>k(!1),2e3)),!0):!1},[x,Be]);if(U||fe)return null;const he="pt-0",Ce="var(--radius-xl)",Ae={sessionId:e.info.sessionID,messageId:e.info.id,parts:L,isUser:x,isMessageCompleted:A,messageFinish:j,messageCreatedAt:T??void 0,isMobile:u,alwaysShowActions:m,hasTouchInput:p,onShowPopup:K,streamPhase:de,onContentChange:r,hasTextContent:Ie,onCopyMessage:ee,copiedMessage:b,agentMention:D,errorMessage:je,errorVariant:Oe,isLatestMessage:!n};return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:R("group w-full",x?u?"pt-2":"pt-4":he,x?u?"pb-0":"pb-2":xe||ie?"pb-0":"pb-2"),id:`message-${e.info.id}`,"data-message-id":e.info.id,ref:y,children:l.jsx("div",{className:"chat-message-column relative",children:x?L.length===0?null:l.jsx(Lm,{forceAnimation:!0,skipAnimation:!c,ignoreContextDisabled:!0,respectReducedMotion:!0,children:l.jsx("div",{className:R("relative flex justify-end",u?void 0:"group/user-shell"),children:l.jsxs("div",{className:"max-w-[85%]",children:[P?l.jsx("div",{style:{backgroundColor:"var(--chat-user-message-bg)",borderRadius:Ce,borderBottomRightRadius:"var(--radius-sm)"},className:R("shadow-none border border-primary/5",u?"px-3 py-2":"px-5 py-3",!u&&"pb-4"),children:l.jsx(Cf,{...Ae,userActionsMode:"external-content"})}):null,l.jsx(Cf,{...Ae,userActionsMode:"external-actions"})]})})}):l.jsx("div",{className:"relative",children:l.jsx(Cf,{sessionId:e.info.sessionID,messageId:e.info.id,parts:L,isUser:x,isMessageCompleted:A,isLatestMessage:!n,messageFinish:j,messageCompletedAt:_??void 0,messageCreatedAt:T??void 0,durationMs:e.info.durationMs,isMobile:u,alwaysShowActions:m,hasTouchInput:p,onShowPopup:K,streamPhase:de,onContentChange:r,hasTextContent:Ie,onCopyMessage:ee,copiedMessage:b,agentMention:D,turnGroupingContext:o,errorMessage:je,errorVariant:Oe,footerProviderID:w,footerModelName:M,footerAgentName:S,footerVariant:I,isDarkTheme:J})})})}),l.jsx(h.Suspense,{fallback:null,children:l.jsx(c$,{popup:q,onOpenChange:Q,isMobile:u})})]})},u$=h.memo(d$,(e,t)=>D4({info:e.message.info,parts:e.message.parts},{info:t.message.info,parts:t.message.parts})&&Vc(e.previousMessage?{info:e.previousMessage.info,parts:e.previousMessage.parts}:void 0,t.previousMessage?{info:t.previousMessage.info,parts:t.previousMessage.parts}:void 0)&&Vc(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&&O4(e.turnGroupingContext,t.turnGroupingContext,e.message.info.id,Wc(e.message.info).isUser)),f$="pichamber.ui",h$="pichamber.",p$="pichamber-extension-ui",m$=1,g$=new Set(["info","success","warning","error","neutral"]),Jn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:null,Qe=e=>typeof e=="string"?e:void 0,Xh=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Nb=e=>{const t=Qe(e);return t&&g$.has(t)?t:"neutral"},Zy=e=>{if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=Jn(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:Nb(r.tone)}:{}})}return t},y$=128,li=(e,t)=>e.length>t?e.slice(0,t):e,v$=e=>T7(e),Wy=e=>{if(!Array.isArray(e))return;const t=[];for(const n of e.slice(0,8)){const r=Jn(n);if(!r)continue;const s=Qe(r.label),o=Qe(r.command);if(!s||!o||o.includes("/")||o.startsWith("."))continue;const i=Jn(r.promptForArgs),a=i?Qe(i.label):void 0,c=i?Qe(i.placeholder):void 0;t.push({label:li(s,y$),command:o,...Qe(r.args)!==void 0?{args:v$(Qe(r.args))}:{},...r.variant==="outline"||r.variant==="ghost"?{variant:r.variant}:{},...Qe(r.icon)!==void 0?{icon:li(Qe(r.icon)??"",64)}:{},...r.disabled===!0?{disabled:!0}:{},...r.loading===!0?{loading:!0}:{},...Qe(r.confirm)!==void 0?{confirm:li(Qe(r.confirm)??"",500)}:{},...i?{promptForArgs:{...a!==void 0?{label:li(a,256)}:{},...c!==void 0?{placeholder:li(c,256)}:{}}}:{}})}return t.length>0?t:void 0},x$=(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=Zy(t.rows);return n&&n.length>0?{component:"kv",rows:n}:null}case"list":{const n=Zy(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=Xh(t.value);if(n===void 0)return null;const r=Xh(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=Jn(r);if(s){const i=Qe(s.label);return i?{label:i,tone:Nb(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}},qy=(e,t=2e3)=>e.length>t?`${e.slice(0,t)}…`:e,Rb=e=>{const n=e.customType===f$||(e.customType?.startsWith(h$)??!1)?Jn(Jn(e.data)?.ui??null)??Jn(e.data)??Jn(e.details):null;if(n){const s=Qe(n.protocol),o=Xh(n.version);if(!(s&&s!==p$)){if(!(o!==void 0&&o!==m$)){const i=Qe(n.component)??Qe(n.type);if(i){const a=Jn(n.props)??{},c=x$(i,a),d=Wy(n.actions);if(c||d){const u=Qe(n.title);return{kind:"ui",descriptor:{...Qe(n.id)!==void 0?{id:Qe(n.id)?.slice(0,128)}:{},...u!==void 0?{title:u.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=Wy(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(qy(JSON.stringify(e.data,null,2)))}catch{r.push("[unserializable data]")}else if(e.details!==void 0)try{r.push(qy(JSON.stringify(e.details,null,2)))}catch{r.push("[unserializable details]")}return{kind:"fallback",title:e.customType??"Extension",body:r.join(`
210
-
211
- `)}},Gy={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"},b$=e=>typeof e=="string"&&e.length>0&&e in M3,w$=({action:e,variant:t,sessionId:n})=>{const[r,s]=z.useState(!1),[o,i]=z.useState(!1),[a,c]=z.useState(!1),[d,u]=z.useState(""),f=z.useCallback(async b=>{if(!(!n||r)){s(!0);try{await Je().prompt(n,L5(e.command,b),"prompt")}finally{s(!1)}}},[n,r,e.command]),p=z.useCallback(async()=>{if(e.promptForArgs){c(!0),u("");return}await f(e.args)},[e,f]),m=z.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,y=b$(e.icon)?l.jsx(V,{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(Ee,{type:"button",size:"xs",variant:"default",onClick:()=>{i(!1),p()},children:"Continue"}),l.jsx(Ee,{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:b=>{b.preventDefault(),c(!1),f(d)},children:[l.jsx("input",{autoFocus:!0,value:d,onChange:b=>u(b.target.value),placeholder:e.promptForArgs?.placeholder??"","aria-label":e.promptForArgs?.label??e.label,className:"h-6 min-w-0 flex-1 rounded-md border bg-transparent px-2 text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-interactive-focus sm:w-40 sm:flex-none",onKeyDown:b=>{b.key==="Escape"&&(b.stopPropagation(),c(!1))}}),l.jsx(Ee,{type:"submit",size:"xs",variant:"default",disabled:r,children:"Run"}),l.jsx(Ee,{type:"button",size:"xs",variant:"ghost",onClick:()=>c(!1),children:"Cancel"})]}):l.jsxs(Ee,{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"}):y,e.label]})},S$=({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}%`}})})]})},C$=({body:e,messageId:t,text:n})=>{const[r,s]=z.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(ga,{messageId:t,content:n,className:"text-sm text-foreground"}),e&&e!==n&&l.jsxs("div",{children:[l.jsxs(Ee,{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(V,{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})})]})]})},k$=({sessionId:e,messageId:t,customType:n,text:r,data:s,details:o,className:i})=>{const a=z.useMemo(()=>Rb({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,u=a.kind==="ui"?a.descriptor.component:void 0,f=()=>{if(!u)return l.jsx(C$,{body:a.kind==="fallback"?a.body:"",messageId:t,text:r});switch(u.component){case"markdown":return l.jsx(ga,{messageId:t,content:u.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:u.rows.map(p=>l.jsxs(z.Fragment,{children:[l.jsx("dt",{className:"truncate text-muted-foreground",children:p.label}),l.jsx("dd",{className:R("break-words",Gy[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:u.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:u.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:u.rows.map((p,m)=>l.jsx("tr",{children:p.map((g,y)=>l.jsx("td",{className:"border-b px-2 py-1.5 break-words",children:g},y))},m))})]})});case"progress":{const p=u.max??100;return l.jsx(S$,{label:u.label,value:u.value,max:p>0?p:100})}case"badges":return l.jsx("div",{className:"flex flex-wrap gap-1.5",children:u.items.map(p=>l.jsx("span",{className:R("rounded-full px-2 py-0.5 text-xs font-medium",Gy[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:u.code})});default:return null}};return l.jsxs("div",{className:R("my-1 flex flex-col gap-2 rounded-xl border border-border/60 bg-card p-3 text-card-foreground shadow-sm",i),"data-extension-ui":t,children:[(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(w$,{action:p,variant:p.variant??"outline",sessionId:e},`${p.command}:${p.label}`))})]}),f()]})},M$=({messageId:e,customType:t,text:n,data:r,details:s,className:o})=>{const[i,a]=z.useState(!1),c=s!==void 0?s:r,d=c!=null,u=typeof n=="string"&&n.trim().length>0,f=t||"extension",p=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(V,{name:"plug-2",className:"size-3.5","aria-hidden":"true"})}),l.jsx("span",{className:R(ko,"shrink-0"),style:wa,children:"Extension"}),l.jsx("span",{className:R(It,"min-w-0 truncate"),style:{color:"var(--tools-description)"},title:f,children:f})]});return l.jsxs("div",{className:R("py-1",o),"data-extension-ui":e,children:[d?l.jsxs("button",{type:"button",onClick:()=>a(m=>!m),"aria-expanded":i,"aria-label":i?`Hide ${f} details`:`Show ${f} 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:[p,l.jsx(V,{name:"arrow-right-s","aria-hidden":"true",className:R("size-3.5 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] duration-150 group-hover/extension-note:opacity-100 group-focus-visible/extension-note:opacity-100",i&&"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:p}),d&&i&&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(Am,{data:c})})]}),u&&l.jsx("div",{className:"w-full min-w-0 break-words pb-1 pt-1",children:l.jsx(ga,{messageId:e,content:n,variant:"assistant"})})]})},Fm=h.memo(({message:e,previousMessage:t,nextMessage:n,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:c,animationHandlers:d,scrollToBottom:u})=>{const f=e.info;if(f.role==="extension"){const p=Rb({customType:f.customType,data:f.data,details:f.details,text:typeof f.text=="string"?f.text:void 0});return l.jsx("div",{className:"chat-message-column",children:p.kind==="ui"?l.jsx(k$,{sessionId:f.sessionID,messageId:e.info.id,customType:f.customType,text:typeof f.text=="string"?f.text:void 0,data:f.data,details:f.details}):l.jsx(M$,{messageId:e.info.id,customType:f.customType,text:typeof f.text=="string"?f.text:void 0,data:f.data,details:f.details})})}return l.jsx(u$,{message:e,previousMessage:t,nextMessage:n,animateUserOnMount:i,onUserAnimationConsumed:a,onContentChange:c,animationHandlers:d,scrollToBottom:u,turnGroupingContext:r,isInActiveTurn:s,activeStreamingPhase:o})},(e,t)=>{const n=e.turnGroupingContext,r=t.turnGroupingContext;return D4(e.message,t.message)&&Vc(e.previousMessage,t.previousMessage)&&Vc(e.nextMessage,t.nextMessage)&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&e.onContentChange===t.onContentChange&&e.scrollToBottom===t.scrollToBottom&&O4(n,r,e.message.info.id,ms(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});Fm.displayName="MessageRow";const Pb=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:u,activeStreamingMessageId:f,activeStreamingPhase:p})=>{const m=h.useMemo(()=>{const A=[e.userMessage,...e.assistantMessages],j=new Map;return A.forEach((N,O)=>{j.set(N.info.id,O)}),{ordered:A,lookup:j}},[e.assistantMessages,e.userMessage]),g=h.useMemo(()=>fE({activeStreamingMessageId:f,assistantMessages:e.assistantMessages}),[f,e.assistantMessages]),y=e.assistantMessages,b=h.useMemo(()=>{const A=new Map;return y.forEach((j,N)=>{A.set(j.info.id,N)}),A},[y]),k=h.useMemo(()=>yf(e,g),[e,g]),v=yf(e,f),x=t&&s,C=h.useMemo(()=>k&&g?g:y[0]?.info.id,[g,k,y]),S=e.activityParts,w=e.activitySegments,M=h.useMemo(()=>{const A=new Map;for(const j of S){const N=A.get(j.messageId)??[];N.push(j),A.set(j.messageId,N)}return A},[S]),I=h.useMemo(()=>{const A=e.userMessage.info.time?.created,j=e.userMessage.info,N=j?.model?.variant??j?.variant,O=typeof N=="string"&&N.trim().length>0?N:void 0;return{turnId:e.turnId,summaryBody:e.summaryText,activityParts:S,activityGroupSegments:w,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,S,w]),E=h.useCallback(A=>{const N=ms(A)==="user",O=m.lookup.get(A.info.id),L=b.get(A.info.id)??-1,P=L>=0,W=L===0,F=L===y.length-1,K=!!C&&A.info.id===C||W||F,Q=M.get(A.info.id)??[],D=N?void 0:P?W?e.userMessage:void 0:typeof O=="number"&&O>0?m.ordered[O-1]:void 0,U=P&&F?n:void 0,Y=P?{turnId:e.turnId,activityOwnerMessageId:C,isFirstAssistantInTurn:W,isLastAssistantInTurn:F,isLatestTurn:t,isWorking:gE({messageId:A.info.id,activeStreamingMessageId:f,isRetrying:AO(A),isAwaitingRecovery:x&&F}),hasTools:e.hasTools,hasReasoning:e.hasReasoning,...K?{summaryBody:I.summaryBody,activityParts:I.activityParts,activityGroupSegments:I.activityGroupSegments,headerMessageId:I.headerMessageId,diffStats:I.diffStats,changedFiles:I.changedFiles,userMessageCreatedAt:I.userMessageCreatedAt,userMessageVariant:I.userMessageVariant}:{activityParts:Q}}:void 0;return l.jsx(Fm,{message:A,previousMessage:D,nextMessage:U,turnGroupingContext:Y,isInActiveTurn:!!g&&A.info.id===g,activeStreamingPhase:A.info.id===g?p:null,animateUserOnMount:d(A),onUserAnimationConsumed:u,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,I,g,f,p,y,b,C,M,x,d,u]),_=!yf(e,f),T=mE({isLastTurn:t,sessionIsWorking:r,turnIsInActiveStream:e.stream.isStreaming&&v,activeStreamingMessageId:f,isSteering:e.isSteering,awaitingPromptEcho:o});return l.jsx(MB,{turn:e,renderMessage:E,deferEarlierAssistantMessages:_,showWorkingStatus:T,isAwaitingRecovery:x&&!T,activeStreamingMessageId:f,activeStreamingPhase:p,onActivityContentChange:i})});Pb.displayName="TurnBlock";const Db=h.memo(({message:e,previousMessage:t,nextMessage:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,shouldAnimateUserMessage:i,onUserAnimationConsumed:a,activeStreamingMessageId:c,activeStreamingPhase:d})=>l.jsx(Fm,{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}));Db.displayName="UngroupedMessageRow";const I$=new Set(["task"]),_$=e=>typeof e=="string"&&I$.has(e.toLowerCase()),E$=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},Ky=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},j$=e=>{const t=e.info.finish;return typeof t=="string"?t:void 0},T$=e=>e.info.summary===!0,A$=(e,t,n,r)=>({id:n.id??`${t}-part-${r}-${n.type}`,turnId:e,messageId:t,part:n,partIndex:r,endedAt:E$(n)}),L$=e=>{const t=[];let n=!1,r=!1;e.assistantMessages.forEach(g=>{g.parts.forEach(y=>{if(y.type==="tool"){n=!0;return}y.type==="reasoning"&&Ky(y)&&(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,y)=>(g.id??`${e.assistantMessages[i]?.info.id}-part-${y}-${g.type}`)===e.summarySourcePartId)??-1:-1,c=e.assistantMessages.some(g=>g.parts.some(y=>y.type==="tool"||y.type==="reasoning")),d=new Map;let u=null;e.assistantMessages.forEach((g,y)=>{const b=j$(g),k=g.parts.some(x=>x.type==="tool"),v=T$(g);g.parts.forEach((x,C)=>{const S=x.type==="tool",w=x.type==="reasoning"||x.type==="text"?Ky(x):void 0,M=x.id??`${g.info.id}-part-${C}-${x.type}`,I=S?x.tool:void 0,E=S&&_$(I);if(E){const O=M;s.has(O)||(s.set(O,g.info.id),o.push(O)),u=O}const _=x.type==="text"&&typeof w=="string"&&(b==="stop"||typeof b!="string")&&e.summarySourceMessageId===g.info.id&&e.summarySourcePartId===M,T=i>=0&&(y<i||y===i&&a>=0&&C<a);let A=null;if(S?A="tool":x.type==="reasoning"?w&&(A="reasoning"):e.showTextJustificationActivity&&x.type==="text"&&w&&(v||!_&&(k||typeof b=="string"&&b!=="stop"||c||T))&&(A="justification"),!A)return;const j={...A$(e.turnId,g.info.id,x,C),kind:A};if(t.push(j),A==="tool"&&E)return;const N=d.get(u)??[];N.push(j),d.set(u,N)})});const f=[],p=g=>{if(g.length===0)return;const y=new Map;g.forEach(k=>{y.set(k.messageId,(y.get(k.messageId)??0)+1)});let b;for(const k of e.assistantMessages)(y.get(k.info.id)??0)>0&&!b&&(b=k.info.id);return b};return[null,...o].forEach(g=>{const y=d.get(g)??[];if(y.length===0)return;const b=g===null?p(y):s.get(g);b&&f.push({id:`${e.turnId}:${b}:${g??"start"}`,anchorMessageId:b,afterToolPartId:g,parts:y})}),{activityParts:t,activitySegments:f,hasTools:n,hasReasoning:r}},N$=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(u=>{n.set(u,a.turnId),s.add(u),r.set(u,{turnId:a.turnId,messageId:u,userMessageId:a.userMessageId,isUserMessage:!1,isAssistantMessage:!0,isFirstAssistantInTurn:u===c,isLastAssistantInTurn:u===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}},R$=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},P$=e=>e.info.summary===!0,Yy=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!P$(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=R$(o);if(i)return{text:i,sourceMessageId:r.info.id,sourcePartId:o.id??`${r.info.id}-part-${s}-text`}}}},D$=e=>Yy(e,!0)??Yy(e,!1)??{},O$=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}},ac=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},Ob=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},H$=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},F$=e=>{const t=e.info.time?.completed;return typeof t=="number"?t:void 0},V$=e=>{const t=e.info?.summary?.body;return typeof t!="string"?void 0:t.trim().length>0?t:void 0},Mf=(e,t)=>{const n=ac(e);return{messageId:e.info.id,role:n,parentMessageId:Ob(e),message:e,order:t}},B$=(e,t)=>{const n=H$(e);let r,s=!1;t.forEach(i=>{const a=F$(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}},$$={previousProjection:null,showTextJustificationActivity:!1,mergeHiddenUserTurns:void 0},z$=(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},U$=(e,t)=>e.userMessage===t.userMessage&&e.headerMessageId===t.headerMessageId&&z$(e.assistantMessages,t.assistantMessages),Xy=(e,t)=>{e.summary=D$(e.assistantMessages),e.summaryText=e.summary.text??V$(e.userMessage),e.diffStats=O$(e.userMessage),e.changedFiles=void 0;const n=L$({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=B$(e.userMessage,e.assistantMessages),e.startedAt=e.stream.startedAt,e.completedAt=e.stream.completedAt,e.durationMs=e.stream.durationMs,e},Z$=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},W$=(e,t)=>{const n=t.previousProjection;if(!n||n.turns.length===0||e.length===0)return e.map(i=>Xy(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&&U$(c,i)?(s=!0,n.turns[a]!==c&&(r=!1),c):(r=!1,Xy(i,t))});return r&&s?n.turns:o},Hb=(e,t)=>{const n={...$$,...t},r=[],s=new Map,o=new Set,i=n.mergeHiddenUserTurns;e.forEach((u,f)=>{if(ac(u)!=="user")return;const m=r[r.length-1];if(i&&m&&Lb(u)){s.set(u.info.id,m),m.messages.push(Mf(u,f)),o.add(u.info.id);return}const y={turnId:u.info.id,isSteering:!1,userMessageId:u.info.id,userMessage:u,headerMessageId:void 0,messages:[Mf(u,f)],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(y),s.set(y.userMessageId,y),o.add(u.info.id)}),e.forEach((u,f)=>{if(ac(u)!=="assistant")return;const m=Ob(u),g=m?s.get(m):void 0;g&&(g.assistantMessages.push(u),g.assistantMessageIds.push(u.info.id),g.messages.push(Mf(u,f)),g.headerMessageId||(g.headerMessageId=u.info.id),o.add(u.info.id))});const a=Z$(W$(r,n)),c=N$(a),d=new Set;return e.forEach(u=>{ac(u)!=="assistant"&&(o.has(u.info.id)||d.add(u.info.id))}),{...c,ungroupedMessageIds:d}},q$=30,G$=4,br=new Map,Jy=new WeakMap;let Qy=1;const K$=()=>rn()?G$:q$,If=e=>{const t=Jy.get(e);if(t!==void 0)return t;const n=Qy;return Qy+=1,Jy.set(e,n),n},Y$=e=>e.map(t=>{const n=If(t.info),r=If(t.parts),s=t.parts.map(o=>If(o)).join(",");return`${n}:${r}:${s}`}).join(";"),X$=(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,Y$(t),n?"1":"0",r].join("|")},J$=e=>{const t=br.get(e);return t&&(br.delete(e),br.set(e,t)),t},Q$=(e,t)=>{br.delete(e);const n=K$();for(;br.size>=n;){const r=br.keys().next().value;if(typeof r!="string")break;br.delete(r)}br.set(e,t)},ez=(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 u=t.sessionKey??"",f=X$(u,e,t.showTextJustificationActivity,"merge"),p=J$(f);return p?(n.current=p,p):Pl("ui.turns.projection_ms",()=>{const m=Hb(e,{previousProjection:n.current,showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:!0});return n.current=m,Q$(f,m),m})},[e,t.showTextJustificationActivity,t.sessionKey]),c=h.useMemo(()=>{const u=a.turns.length<=1?[]:a.turns.slice(0,-1),f=r.current;if(f.length===u.length){let p=!0;for(let m=0;m<u.length;m+=1)if(f[m]!==u[m]){p=!1;break}if(p)return f}return r.current=u,u},[a.turns]),d=h.useMemo(()=>{const u=a.turns.length===0?void 0:a.turns[a.turns.length-1];return s.current===u?s.current:(s.current=u,u)},[a.turns]);return{projection:a,staticTurns:c,streamingTurn:d}},tz=1.5,nz=({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 u=()=>{if(a||!e)return;const f=i.scrollTop<i.clientHeight*tz,p=i.scrollHeight<=i.clientHeight+1;!f&&!p||(a=!0,s(),r().then(m=>{d&&(a=!1,m&&(c=window.setTimeout(u,0)))}).catch(()=>{d&&(a=!1,o())}))};return i.addEventListener("scroll",u,{passive:!0}),u(),()=>{d=!1,c!==void 0&&window.clearTimeout(c),i.removeEventListener("scroll",u)}},[t,e,r,s,o,n])},e5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},t5=e=>{const t=e.info.time?.created;return typeof t=="number"?t:void 0},rz=(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 u=e.length-1;u>=0;u-=1){const f=t5(e[u]);if(!(s!==void 0&&f!==void 0&&f>s)&&e5(e[u])==="user"){o=u;break}}if(o<0)return e;let i=-1;for(let u=o+1;u<e.length;u+=1){const f=t5(e[u]);if(s!==void 0&&f!==void 0&&f>s)break;e5(e[u])==="assistant"&&(i=u)}if(i>=0)return e.map((u,f)=>f===i?{...u,info:{...u.info,error:r}}:u);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},n5=e=>{const t=e.info;return(typeof t.clientRole=="string"?t.clientRole:null)??(typeof t.role=="string"?t.role:null)??null},sz=(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(n5(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(n5(e[d])==="assistant"){s=d;break}if(s>=0)return e.map((d,u)=>u!==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},r5=[],oz=({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:r5};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=[],u=[];let f=!1;return t.forEach((p,m)=>{if(s&&p.info.id===s){f=!0;return}const g=i.get(p.info.id);if(g){d.push(g);return}!n.has(p.info.id)||p.info.id===c||(f?u: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:u.length>0?u:r5}},Fb=e=>e.parts.some(t=>t?.type==="compaction"),iz=e=>{if(!Fb(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}},az=e=>{const t=Ld(e.parts);return t.length===e.parts.length?e:{...e,parts:t}},s5=new WeakMap,Vb=e=>{const t=s5.get(e);if(t)return t;const n=az(e),r=iz(n),s=aB(r.parts),o=s===r.parts?r:{...r,parts:s};return s5.set(e,o),o},o5=(e,t,n)=>e.info.id!==t||e.parts===n?e:Vb({...e,parts:n}),lz=(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},i5=(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},cz=(e,t)=>{const n=t.activeStreamingMessageId;if(!n)return e;if(e.kind==="ungrouped"){const p=o5(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=o5(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&&lz(o.parts,i.parts)))return{...e,turn:{...e.turn,assistantMessages:s,messages:i5(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],f=Hb(d,{showTextJustificationActivity:t.showTextJustificationActivity,mergeHiddenUserTurns:t.mergeHiddenUserTurns}).turns[0]??{...e.turn,assistantMessages:s,assistantMessageIds:s.map(p=>p.info.id),messages:i5(e.turn,s)};return{...e,turn:f}},a5=e=>!!(e&&e.clientHeight>0),dz=5,uz=[],fz=new Set,hz=16,pz=(e,t)=>e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r]),mz=320,gz=8,yz=16,vz=()=>rn()?yz:gz,xz=30,bz=180,wz=5,Sz=120,Cz=1200,kz=80,Mz=160,l5=1500,Iz=1.5,_z=90,Ez=(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},Xr=new Map,jz=32,Gs=new Map,c5=e=>Gs.get(e)??0,Tz=(e,t)=>{if(Gs.size>=jz&&!Gs.has(e)){const n=Gs.keys().next().value;typeof n=="string"&&Gs.delete(n)}Gs.set(e,t)},Az=(e,t)=>{const n=Xr.get(e);if(n){if(pz(n.keys,t))return n.items;Xr.delete(e)}},Lz=(e,t,n)=>{if(!(!n||t.length===0))for(Xr.delete(e),Xr.set(e,{keys:t.slice(),items:n.takeSnapshot()});Xr.size>hz;){const r=Xr.keys().next().value;if(typeof r!="string")break;Xr.delete(r)}},Tl=e=>{const t=h.useRef(e);return h.useEffect(()=>{t.current=e},[e]),h.useCallback((...n)=>t.current(...n),[])},Nd=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:u,onLoadOlderHistory:f,onLoadAllHistory:p})=>(cs("ui.message_list_entry.render"),e.kind==="ungrouped"?l.jsx(Db,{message:e.message,previousMessage:e.previousMessage,nextMessage:e.nextMessage,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r,shouldAnimateUserMessage:a,onUserAnimationConsumed:c,activeStreamingMessageId:d,activeStreamingPhase:u}):e.kind==="history-gate"?l.jsx(EO,{foldedCount:e.turns.length,onLoadOlder:()=>f?.(e.turns.length),onLoadAll:()=>p?.(e.turns.length)}):l.jsx(Pb,{turn:e.turn,isLastTurn:e.isLastTurn,nextEntryFirstMessage:e.nextEntryFirstMessage,sessionIsWorking:s,sessionAwaitingRecovery:o,awaitingPromptEcho:i,shouldAnimateUserMessage:a,onUserAnimationConsumed:c,activeStreamingMessageId:d,activeStreamingPhase:u,onMessageContentChange:t,getAnimationHandlers:n,scrollToBottom:r})));Nd.displayName="MessageListEntry";const Bb=h.memo(({entries:e,engine:t,contentRef:n,scrollRef:r,registerTanstackVirtualizer:s,virtualizerKey:o,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:c,shouldAnimateUserMessage:d,onUserAnimationConsumed:u,onLoadOlderHistory:f,onLoadAllHistory:p})=>{const m=t==="tanstack",g=h.useRef(!1),y=h.useRef(0),b=h.useRef(null),k=m&&rn();h.useEffect(()=>{if(!k)return;const P=r?.current;if(!P)return;const W=()=>{g.current=!0},F=()=>{g.current=!1},q=()=>{y.current=performance.now()};return P.addEventListener("touchstart",W,{passive:!0}),P.addEventListener("touchend",F,{passive:!0}),P.addEventListener("touchcancel",F,{passive:!0}),P.addEventListener("scroll",q,{passive:!0}),()=>{P.removeEventListener("touchstart",W),P.removeEventListener("touchend",F),P.removeEventListener("touchcancel",F),P.removeEventListener("scroll",q)}},[k,r]);const v=h.useCallback(()=>g.current||performance.now()-y.current<Mz,[]),x=h.useCallback(()=>{const P=r?.current;return P?P.scrollTop<P.clientHeight*Iz:!0},[r]),[C,S]=h.useState(e);let w=C;e!==C?k&&Ez(C,e)&&v()&&!x()&&(b.current===null||performance.now()-b.current<l5)?b.current===null&&(b.current=performance.now()):(b.current=null,S(e),w=e):b.current!==null&&(b.current=null);const[,M]=h.useReducer(P=>P+1,0);h.useEffect(()=>{if(!k)return;const P=window.setInterval(()=>{if(b.current===null)return;const W=performance.now()-b.current>=l5;(!v()||x()||W)&&M()},_z);return()=>window.clearInterval(P)},[k,v,x]);const I=h.useRef(w);I.current=w;const[E]=h.useState(()=>m?Az(o,e.map(P=>P.key)):void 0),_=h.useRef(null),T=h.useRef(mz),[A,j]=h.useState(null);h.useLayoutEffect(()=>{if(!m){j(K=>K===null?K:null);return}let P,W=0;const F=()=>{const K=r?.current??null;return a5(K)?(j(Q=>Q===K?Q:K),!0):!1};if(F())return;const q=r?.current;return q?(P=new ResizeObserver(()=>{F()&&P?.disconnect()}),P.observe(q)):typeof window<"u"&&(W=window.requestAnimationFrame(()=>{if(F())return;const K=r?.current;K&&(P=new ResizeObserver(()=>{F()&&P?.disconnect()}),P.observe(K))})),()=>{W&&window.cancelAnimationFrame(W),P?.disconnect()}},[m,r,o]);const N=m&&a5(A),O=G5({count:w.length,enabled:N,getScrollElement:()=>A,estimateSize:P=>I.current[P]?.kind==="history-gate"?SO:T.current,overscan:vz(),scrollToFn:(P,W,F)=>{const q=_.current;q&&(q.style.height=`${F.getTotalSize()}px`),z9(P,W,F)},getItemKey:P=>I.current[P]?.key??`index:${P}`,anchorTo:"end",initialOffset:()=>Number.MAX_SAFE_INTEGER,initialMeasurementsCache:E});O.shouldAdjustScrollPositionOnItemSizeChange=(P,W,F)=>{if(F.isAtEnd(kz))return!1;const q=F.range?.startIndex;return q!==void 0&&P.index<q},h.useEffect(()=>{if(!m)return;const P=O.itemSizeCache;if(P.size>=wz){let W=0;for(const F of P.values())W+=F;T.current=Math.min(Cz,Math.max(Sz,Math.round(W/P.size)))}}),h.useEffect(()=>{if(N)return s?.(O),()=>{Lz(o,I.current.map(P=>P.key),O),s?.(null)}},[N,s,O,o]);const L=h.useCallback(P=>l.jsx(Nd,{entry:P,onMessageContentChange:i,getAnimationHandlers:a,scrollToBottom:c,sessionIsWorking:!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:u,activeStreamingMessageId:null,activeStreamingPhase:null,onLoadOlderHistory:f,onLoadAllHistory:p},P.key),[a,p,f,i,u,c,d]);if(t==="none"||t==="tanstack"&&!N)return l.jsx("div",{ref:n,className:"relative w-full",children:w.map(P=>l.jsx("div",{"data-turn-entry":P.key,children:L(P)},P.key))});if(t==="tanstack"){const P=O.getVirtualItems(),W=P[0]?.start??0;return l.jsx("div",{ref:_,className:"relative w-full",style:{height:O.getTotalSize()},children:l.jsx("div",{style:{paddingTop:`${W}px`},children:P.map(F=>{const q=w[F.index];return q?l.jsx("div",{"data-index":F.index,ref:O.measureElement,"data-turn-entry":q.key,children:L(q)},q.key):null})})})}return null});Bb.displayName="StaticHistoryList";const $b=({entry:e,sessionId:t,directory:n,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a=!1,awaitingPromptEcho:c=!1,shouldAnimateUserMessage:d,onUserAnimationConsumed:u,activeStreamingMessageId:f,activeStreamingPhase:p})=>{const m=Dk(t,f??"",n),g=h.useMemo(()=>cz(e,{activeStreamingMessageId:f,liveParts:m,showTextJustificationActivity:!0,mergeHiddenUserTurns:!0}),[f,e,m]);return l.jsx(Nd,{entry:g,onMessageContentChange:r,getAnimationHandlers:s,scrollToBottom:o,sessionIsWorking:i,sessionAwaitingRecovery:a,awaitingPromptEcho:c,shouldAnimateUserMessage:d,onUserAnimationConsumed:u,activeStreamingMessageId:f,activeStreamingPhase:p})};$b.displayName="StreamingTailContent";const zb=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:u,scrollToBottom:f,scrollRef:p,directory:m},g)=>{A7("react.message_list_render"),cs("ui.message_list.render");const{hasMoreBefore:y,beforeCursor:b,loadOlder:k}=Wk(e),[v,x]=h.useState(()=>c5(e)),C=h.useRef(null),S=h.useRef(null),w=h.useCallback(()=>{const re=p?.current;if(!re)return null;const ge=re.getBoundingClientRect(),pe=Array.from(re.querySelectorAll("[data-message-id]")).find(ke=>ke.getBoundingClientRect().bottom>ge.top+1);return{top:re.scrollTop,height:re.scrollHeight,anchor:pe?.dataset.messageId?{messageId:pe.dataset.messageId,offsetTop:pe.getBoundingClientRect().top-ge.top}:null}},[p]),M=h.useCallback(re=>{x(ge=>{const pe=typeof re=="function"?re(ge):re;return Tz(e,pe),pe})},[e]),I=h.useCallback(re=>{C.current=w(),M(ge=>IO(ge,re))},[w,M]),E=h.useCallback(re=>{C.current=w(),M(ge=>ge+re)},[w,M]),_=h.useCallback((re,ge,pe)=>{const ke=ge.findIndex(_e=>_e.turnId===re);ke<0||(S.current=re,M(_e=>Math.max(_e,MO(ke,pe))))},[M]);h.useLayoutEffect(()=>{x(c5(e)),S.current=null},[e]);const T=h.useRef({sessionKey:void 0,previousOrder:[],animatedIds:new Set}),A=Tl(u),j=Tl(()=>{f?.()}),N=h.useMemo(()=>Pl("ui.message_list.base_display_ms",()=>{const re=new Set,ge=new Map,pe=[];for(const Te of t){const be=Te.info?.id;typeof be=="string"&&ge.set(be,Te)}for(let Te=0;Te<t.length;Te+=1){const be=t[Te],ae=be.info?.id;if(typeof ae=="string"){if(re.has(ae))continue;re.add(ae)}pe.push(Vb(typeof ae=="string"?ge.get(ae)??be:be))}const ke=[],_e=new Set;for(let Te=0;Te<pe.length;Te+=1){const be=pe[Te],ae=PO(be,_e);(Fb(be)||be.parts.some(oe=>oe.type==="text"&&LO(oe).trim()==="/compact"))&&_e.add(be.info.id);const te=ke.length>0?ke[ke.length-1]:void 0;if(DO(te)){const oe=HO(ae);if(oe.hide){ke[ke.length-1]=FO(te,oe.taskSessionId);continue}}if(_4(te)){const oe=E4(ae,NO(te));if(oe.hide){ke[ke.length-1]=VO(te,oe.details);continue}}ke.push(ae)}return ke}),[t]),O=h.useRef(null),L=h.useCallback(()=>p?.current?p.current:typeof document>"u"?null:document.querySelector('[data-scrollbar="chat"]'),[p]),P=h.useCallback(()=>{C.current=w()},[w]),W=h.useCallback(()=>{C.current=null},[]);nz({hasMoreBefore:y,beforeCursor:b,resolveScrollContainer:L,loadOlder:k,onBeforeLoad:P,onLoadError:W});const F=h.useMemo(()=>Pl("ui.message_list.retry_overlay_ms",()=>{const re=sz(N,{sessionId:a?.sessionId??null,message:a?.message??"Quota limit reached. Retrying automatically.",confirmedAt:a?.confirmedAt,fallbackTimestamp:a?.fallbackTimestamp??0});return rz(re,c?.sessionId??null,c?.compaction??null)}),[N,c,a]),{projection:q,staticTurns:K,streamingTurn:Q}=ez(F,{sessionKey:e,showTextJustificationActivity:!0}),D=q.ungroupedMessageIds.size>0,U=D?F:uz,Y=D?q.ungroupedMessageIds:fz,ne=Q?.userMessage.info.id,{entries:$,trailing:J}=h.useMemo(()=>Pl("ui.message_list.render_entries_ms",()=>oz({staticTurns:K,messages:U,ungroupedMessageIds:Y,lastTurnId:q.lastTurnId,tailUserMessageId:ne})),[q.lastTurnId,U,Y,K,ne]),G=h.useMemo(()=>{if(Q)return{kind:"turn",key:`turn:${Q.turnId}`,turn:Q,isLastTurn:Q.turnId===q.lastTurnId};if(q.ungroupedMessageIds.size===0)return;const re=F[F.length-1];if(!(!re||!q.ungroupedMessageIds.has(re.info.id)))return{kind:"ungrouped",key:`msg:${re.info.id}`,message:re,previousMessage:F.length>1?F[F.length-2]:void 0,nextMessage:void 0}},[F,q.lastTurnId,q.ungroupedMessageIds,Q]);G&&cs("ui.message_list.render.streaming");const ue=G?G.kind==="turn"?G.turn.userMessage:G.message:void 0,B=h.useMemo(()=>{const re=$.map((Te,be)=>{if(Te.kind!=="turn")return Te;const ae=be<$.length-1?(()=>{const te=$[be+1];return te&&te.kind==="turn"?te.turn.userMessage:te?.kind==="ungrouped"?te.message:void 0})():ue;return ae?{...Te,nextEntryFirstMessage:ae}:Te});let ge=0;for(const Te of re)Te.kind==="turn"&&(ge+=1);let pe=-1;const ke=[],_e=[];for(const Te of re){if(Te.kind!=="turn"){_e.push(Te);continue}if(pe+=1,kO(pe,ge,v)){ke.push(Te.turn);continue}_e.push(Te)}return ke.length===0?_e:[{kind:"history-gate",key:"history-gate",turns:ke},..._e]},[v,$,ue]);h.useLayoutEffect(()=>{const re=C.current;if(re){C.current=null;const _e=p?.current;if(_e){const Te=re.anchor?.messageId?_e.querySelector(`[data-message-id="${re.anchor.messageId}"]`):null;if(Te&&re.anchor){const be=_e.getBoundingClientRect(),ae=Te.getBoundingClientRect().top-be.top-re.anchor.offsetTop;ae!==0&&(_e.scrollTop+=ae)}else{const be=_e.scrollHeight-re.height;be>0?_e.scrollTop=re.top+be:_e.scrollTop=re.top}}}const ge=S.current;if(!ge)return;S.current=null,L()?.querySelector(`[data-turn-id="${ge}"]`)?.scrollIntoView({block:"start"})},[B,L,p]);const ie=rn()||B.length>=dz,xe=ie?"tanstack":"none",de=h.useRef(null),Se=h.useCallback(re=>{de.current=re},[]),je=h.useMemo(()=>{const re=G?[...B,G]:B;return J.length>0?[...re,...J]:re},[B,G,J]),Oe=Tl(re=>{d(re)}),Be=Tl(re=>{d(re)}),Ie=h.useMemo(()=>t.filter(re=>ms(re)==="user").map(re=>re.info.id),[t]);{const re=T.current;re.sessionKey!==e&&(re.sessionKey=e,re.previousOrder=Ie,re.animatedIds=new Set);const ge=re.previousOrder;if(Ie.length>ge.length&&ge.every((ke,_e)=>Ie[_e]===ke)&&ek(e))for(let ke=ge.length;ke<Ie.length;ke+=1){const _e=Ie[ke];if(_e&&!re.animatedIds.has(_e)){if(!tk(e))break;re.animatedIds.add(_e)}}re.previousOrder=Ie}const fe=h.useCallback(re=>ms(re)!=="user"?!1:T.current.animatedIds.has(re.info.id),[]),ee=h.useCallback(re=>{T.current.animatedIds.delete(re)},[]),he=h.useMemo(()=>{const re=new Map;return je.forEach((ge,pe)=>{if(ge.kind==="ungrouped"){re.set(ge.message.info.id,pe);return}if(ge.kind==="history-gate"){ge.turns.forEach(ke=>{re.set(ke.userMessage.info.id,pe),ke.assistantMessages.forEach(_e=>{re.set(_e.info.id,pe)})});return}re.set(ge.turn.userMessage.info.id,pe),ge.turn.assistantMessages.forEach(ke=>{re.set(ke.info.id,pe)})}),re},[je]),Ce=h.useMemo(()=>{const re=new Map;return je.forEach((ge,pe)=>{ge.kind==="turn"&&re.set(ge.turn.turnId,pe),ge.kind==="history-gate"&&ge.turns.forEach(ke=>{re.set(ke.turnId,pe)})}),re},[je]),Ae=h.useCallback(re=>{const ge=L();return ge?ge.querySelector(`[data-message-id="${re}"]`):null},[L]),Me=h.useCallback(re=>{if(re<0||re>=B.length||!ie)return!1;const ge=de.current;return ge?(ge.scrollToIndex(re,{align:"start",behavior:"auto"}),!0):!1},[B.length,ie]),Ze=h.useCallback((re,ge="auto")=>{const pe=L();if(!pe)return!1;const ke=Ae(re);if(!ke)return!1;const _e=pe.getBoundingClientRect(),ae=ke.getBoundingClientRect().top-_e.top+pe.scrollTop-50;return pe.scrollTo({top:ae,behavior:ge}),!0},[Ae,L]),gt=h.useCallback((re,ge,pe)=>{if(typeof window>"u")return!1;let ke=0;const _e=()=>{WV(re,ge),!Ze(ge,pe)&&(ke+=1,ke<60&&window.requestAnimationFrame(_e))};return window.requestAnimationFrame(_e),!0},[Ze]);return h.useEffect(()=>{if(!g)return;const re={scrollToTurnId:(pe,ke)=>{const _e=B.find(me=>me.kind==="history-gate");if(_e?.kind==="history-gate"){const me=B.reduce((Re,We)=>We.kind==="turn"?Re+1:Re,0);_(pe,_e.turns,_e.turns.length+me)}const Te=ke?.behavior??"auto",be=Ce.get(pe);if(be===void 0)return!1;const ae=L();if(!ae)return!1;const te=ae.querySelector(`[data-turn-id="${pe}"]`);return te?(te.scrollIntoView({behavior:Te,block:"start"}),!0):G!==void 0&&be>=B.length?!1:Me(be)},scrollToMessageId:(pe,ke)=>{const _e=ke?.behavior??"auto",Te=he.get(pe);if(Te===void 0)return!1;const be=je[Te];if(be?.kind==="history-gate"){const oe=be.turns.find(me=>me.userMessage.info.id===pe||me.assistantMessages.some(Re=>Re.info.id===pe));if(oe){const me=B.reduce((Re,We)=>We.kind==="turn"?Re+1:Re,0);_(oe.turnId,be.turns,be.turns.length+me)}}if(Ze(pe,_e))return!0;G!==void 0&&Te>=B.length||Me(Te);const te=q.indexes.messageToTurnId.get(pe);return te?gt(te,pe,_e):!1},holdViewportAnchor:pe=>{const ke=L();if(!ke||typeof window>"u")return;let _e=0,Te=0,be=!1;const ae=()=>{be=!0,ke.removeEventListener("touchstart",ae),ke.removeEventListener("wheel",ae)};ke.addEventListener("touchstart",ae,{passive:!0}),ke.addEventListener("wheel",ae,{passive:!0});const te=()=>{if(be)return;const oe=Ae(pe.messageId);if(oe){const me=oe.getBoundingClientRect().top-ke.getBoundingClientRect().top-pe.offsetTop;Math.abs(me)>.5?(ke.scrollTop+=me,Te=0):Te+=1}if(_e+=1,Te>=xz||_e>=bz){ke.removeEventListener("touchstart",ae),ke.removeEventListener("wheel",ae);return}window.requestAnimationFrame(te)};window.requestAnimationFrame(te)},isHistoryVirtualized:()=>ie,captureViewportAnchor:()=>{const pe=L();if(!pe)return null;const ke=pe.getBoundingClientRect(),Te=Array.from(pe.querySelectorAll("[data-message-id]")).find(ae=>ae.getBoundingClientRect().bottom>ke.top+1);if(!Te)return null;const be=Te.dataset.messageId;return be?{messageId:be,offsetTop:Te.getBoundingClientRect().top-ke.top}:null},restoreViewportAnchor:pe=>{const ke=L();if(!ke||!he.has(pe.messageId))return!1;const _e=()=>{const Te=Ae(pe.messageId);if(!Te)return!1;const be=ke.getBoundingClientRect(),te=Te.getBoundingClientRect().top-be.top-pe.offsetTop;return te!==0&&(ke.scrollTop+=te),!0};if(!_e()){const Te=he.get(pe.messageId);if(typeof Te=="number"&&Te<B.length)return Me(Te)}return _e()},scrollToBottom:()=>{if(ie&&B.length>0&&de.current){de.current.scrollToEnd();return}const pe=L();pe&&(pe.scrollTop=pe.scrollHeight+4096)}};if(typeof g=="function")return g(re),()=>{g(null)};const ge=g;return ge.current=re,()=>{ge.current=null}},[je,Ae,B,he,q.indexes.messageToTurnId,L,_,gt,Me,Ze,ie,G,Ce,g]),l.jsx("div",{children:l.jsx(Py,{disabled:!1,children:l.jsxs("div",{className:"relative w-full",children:[l.jsx(Py,{disabled:ie,children:l.jsx(Bb,{entries:B,engine:xe,contentRef:O,scrollRef:p,registerTanstackVirtualizer:Se,virtualizerKey:e,onMessageContentChange:Oe,getAnimationHandlers:A,scrollToBottom:j,shouldAnimateUserMessage:fe,onUserAnimationConsumed:ee,onLoadOlderHistory:I,onLoadAllHistory:E},e)}),G?l.jsx($b,{entry:G,sessionId:e??null,directory:m,onMessageContentChange:Be,getAnimationHandlers:A,scrollToBottom:j,sessionIsWorking:n,sessionAwaitingRecovery:r,awaitingPromptEcho:s,shouldAnimateUserMessage:fe,onUserAnimationConsumed:ee,activeStreamingMessageId:o,activeStreamingPhase:i}):null,J.map(re=>l.jsx(Nd,{entry:re,onMessageContentChange:Be,getAnimationHandlers:A,scrollToBottom:j,sessionIsWorking:n,shouldAnimateUserMessage:fe,onUserAnimationConsumed:ee},re.key))]})})})});zb.displayName="MessageList";const Nz=h.memo(zb),Rz=({visible:e,onClick:t})=>l.jsx("div",{className:R("absolute bottom-full left-1/2 -translate-x-1/2 mb-2 transition-all duration-150",e?"opacity-100 translate-y-0 scale-100 pointer-events-auto":"opacity-0 translate-y-2 scale-95 pointer-events-none"),children:l.jsx(Ee,{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(V,{name:"arrow-down",className:"h-4 w-4"})})}),Pz=h.memo(Rz),Dz=.1,Oz=40,Hz=2,d5=1500,u5=2,Ub=350,Fz=300,Vz=600,Bz=8e3,Ii=()=>typeof performance<"u"?performance.now():Date.now(),$z=(e,t)=>{if(e)return Oz;const n=t?.clientHeight??0;return n<=0?96:Math.max(48,n*Dz)},Zb=e=>e.scrollHeight-e.scrollTop-e.clientHeight,ci=e=>e.scrollHeight-e.clientHeight>1,f5=(e,t)=>Zb(e)<=$z(t,e),zz=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return!1;switch(e.key){case"ArrowUp":case"PageUp":case"Home":return!0;default:return!1}},Uz=(e,t)=>{if(!(t instanceof Element))return null;const n=t.closest("[data-scrollable]");return!n||n===e||!(n instanceof HTMLElement)?null:n},h5=(e,t)=>{const n=Uz(e,t);return n?n.scrollTop>0:!1},Zz=100,Wz=48,qz=.1,Gz=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=Math.max(Wz,e.clientHeight*qz),Kz=(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},Yz=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,u,f=!0;const p=new Map;let m=[];const g=()=>{c===void 0&&(c=t(()=>{c=void 0,b()}))},y=()=>{const I=o;if(!I){m=[],f=!1;return}const E=I.getBoundingClientRect().top;m=[...p].map(([_,T])=>({id:_,top:T.getBoundingClientRect().top-E+I.scrollTop})),m.sort((_,T)=>_.top-T.top),f=!1},b=()=>{const I=o;if(!I)return;f&&y();const E=Gz(I)?m[m.length-1]?.id:Kz(m,I.scrollTop+Zz);!E||E===u||(u=E,e.onActive(E))},k=()=>{const I=o;if(I){if(clearTimeout(d),d=void 0,i?.disconnect(),i=void 0,r){i=new r(()=>{clearTimeout(d),d=setTimeout(()=>{f=!0,g()},100)}),i.observe(I);for(const E of p.values())i.observe(E)}if(a?.disconnect(),a=void 0,s){a=new s(()=>{f=!0,g()});const E={subtree:!0,childList:!0};r||(E.characterData=!0,E.characterDataOldValue=!1),a.observe(I,E)}f=!0,g()}},v=I=>{o!==I&&(o=I,u=void 0,k())},x=(I,E)=>{const _=p.get(E);_&&_!==I&&i?.unobserve(_),p.set(E,I),i&&i.observe(I),f=!0,g()},C=I=>{const E=p.get(I);E&&(i?.unobserve(E),p.delete(I),f=!0,g())},S=()=>{f=!0,g()},w=()=>{for(const I of p.values())i?.unobserve(I);p.clear(),m=[],u=void 0,f=!0};return{setContainer:v,register:x,unregister:C,onScroll:g,markDirty:S,clear:w,destroy:()=>{c!==void 0&&n(c),c=void 0,clearTimeout(d),d=void 0,w(),i?.disconnect(),a?.disconnect(),i=void 0,a=void 0,o=void 0},getActiveId:()=>u}};function Xz(e,t){h.useEffect(()=>{if(!t)return;const n=e;if(!n)return;let r=null;const s=Yz({onActive:f=>{f!==r&&(r=f,t(f))}});s.setContainer(n);const o=new Map,i=f=>{const p=f.dataset.turnId;return p?(o.set(p,f),s.register(f,p),!0):!1},a=f=>{const p=f.dataset.turnId;return!p||o.get(p)!==f?!1:(o.delete(p),s.unregister(p),!0)},c=f=>{if(!(f instanceof HTMLElement))return[];const p=[];return f.matches("[data-turn-id]")&&p.push(f),f.querySelectorAll("[data-turn-id]").forEach(m=>p.push(m)),p};n.querySelectorAll("[data-turn-id]").forEach(i),s.markDirty();const d=new MutationObserver(f=>{let p=!1;f.forEach(m=>{m.removedNodes.forEach(g=>{c(g).forEach(y=>{a(y)&&(p=!0)})}),m.addedNodes.forEach(g=>{c(g).forEach(y=>{i(y)&&(p=!0)})})}),p&&s.markDirty()});d.observe(n,{subtree:!0,childList:!0});const u=()=>s.onScroll();return n.addEventListener("scroll",u,{passive:!0}),()=>{n.removeEventListener("scroll",u),d.disconnect(),s.destroy()}},[e,t])}function Jz({containerEl:e,handleScrollEvent:t,releaseFromUserIntent:n,scrollRef:r,stateRef:s,canScroll:o,scrollToBottomNow:i,updateOverflowAndButton:a,keyboardAnimRef:c,animationGuardUntilRef:d,lastScrollTopRef:u}){h.useEffect(()=>{const f=e;if(!f)return;u.current=f.scrollTop;const p=x=>{x.deltaY>=0||h5(f,x.target)||n()};let m=null;const g=x=>{const C=x.touches.item(0);m=C?C.clientY:null},y=x=>{const C=x.touches.item(0);if(!C){m=null;return}const S=m;m=C.clientY,!(S===null||C.clientY-S<=Hz)&&(h5(f,x.target)||n())},b=()=>{m=null},k=x=>{zz(x)&&n()},v=x=>{const C=x.target;C instanceof Element&&C.closest("[data-overlay-scrollbar-thumb]")&&n()};return f.addEventListener("scroll",t,{passive:!0}),f.addEventListener("wheel",p,{passive:!0}),f.addEventListener("touchstart",g,{passive:!0}),f.addEventListener("touchmove",y,{passive:!0}),f.addEventListener("touchend",b,{passive:!0}),f.addEventListener("touchcancel",b,{passive:!0}),f.addEventListener("keydown",k),typeof window<"u"&&window.addEventListener("pointerdown",v,!0),()=>{f.removeEventListener("scroll",t),f.removeEventListener("wheel",p),f.removeEventListener("touchstart",g),f.removeEventListener("touchmove",y),f.removeEventListener("touchend",b),f.removeEventListener("touchcancel",b),f.removeEventListener("keydown",k),typeof window<"u"&&window.removeEventListener("pointerdown",v,!0)}},[e,t,u,n]),h.useEffect(()=>{if(typeof window>"u")return;const f=m=>{const g=m.detail;g&&(c.current=!0,d.current=Ii()+g.durationMs+Ub)},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",f),window.addEventListener("oc:keyboard-settled",p),()=>{window.removeEventListener("oc:keyboard-anim",f),window.removeEventListener("oc:keyboard-settled",p),c.current=!1}},[d,o,c,r,i,s,a])}const Qz=({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),[u,f]=h.useState("following"),[p,m]=h.useState(!1),[g,y]=h.useState(!1),[b,k]=h.useState(!1),v=h.useRef("following"),x=h.useRef(s);x.current=s;const C=h.useRef(r);C.current=r;const S=h.useRef(!1),w=h.useRef(null),M=h.useRef(t);M.current=t;const I=h.useRef(null),E=h.useRef(null),_=h.useRef(null),T=h.useRef(0),A=h.useRef(!1),j=h.useRef(0),N=h.useRef(!1),O=h.useRef(null),L=h.useRef(null),P=h.useRef(0),W=h.useRef(null);h.useLayoutEffect(()=>{i.current!==d.current&&(d.current=i.current,c(i.current))});const F=h.useCallback(()=>C.current||S.current,[]),q=h.useCallback(fe=>{v.current!==fe&&(v.current=fe,f(fe))},[]),K=h.useCallback(fe=>{E.current={top:Math.max(0,fe.scrollHeight-fe.clientHeight),time:Ii()},_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{E.current=null,_.current=null},d5)},[]),Q=h.useCallback(fe=>{const ee=E.current;return ee?Ii()-ee.time>d5?(E.current=null,!1):Math.abs(fe.scrollTop-ee.top)<u5:!1},[]),D=h.useCallback(()=>Ii()<T.current,[]),U=h.useCallback(()=>{N.current=!1,O.current&&(clearTimeout(O.current),O.current=null),L.current&&(clearTimeout(L.current),L.current=null)},[]),Y=h.useCallback(()=>{O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{O.current=null,U()},Vz)},[U]),ne=h.useCallback(()=>{const fe=i.current;fe&&(N.current=!0,P.current=fe.scrollHeight,Y(),L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{L.current=null,U()},Bz))},[Y,U]),$=h.useCallback(()=>{const fe=i.current;if(!fe){m(!1),y(!1);return}const ee=ci(fe);if(m(ee),!ee){y(!1);return}const he=v.current==="released"&&!f5(fe,x.current);y(he)},[]),J=h.useCallback(fe=>{const ee=i.current;if(!ee)return;K(ee);const he=ee.scrollHeight+4096;if(fe==="smooth"){ee.scrollTo({top:he,behavior:fe});return}ee.scrollTop=he},[K]),G=h.useCallback((fe,ee="auto")=>{const he=i.current;!fe&&!F()||(fe&&v.current!=="following"&&q("following"),he&&(!fe&&v.current!=="following"||J(fe?ee:"auto")))},[F,J,q]),ue=h.useCallback(()=>{const fe=i.current;if(fe){if(!ci(fe)){q("following");return}v.current!=="released"&&(q("released"),$())}},[q,$]),B=h.useCallback((fe="instant")=>{G(!0,fe==="smooth"?"smooth":"auto")},[G]),ie=h.useCallback(()=>{G(!0)},[G]),xe=h.useCallback(()=>{q("released"),$()},[q,$]),de=h.useCallback(()=>{U(),ue()},[U,ue]),Se=h.useCallback(async()=>{const fe=M.current;return fe?i.current?(W.current=null,q("following"),G(!0),ne(),$(),!1):(W.current=fe,q("following"),!1):!1},[ne,G,q,$]);h.useEffect(()=>{!e||!t||t===I.current||(I.current=t,ss.getInstance().recordSessionStart(e),E.current=null,W.current&&W.current!==t&&(W.current=null))},[e,t]),h.useEffect(()=>{if(S.current=!1,w.current&&(clearTimeout(w.current),w.current=null),r){v.current==="following"&&G(!0);return}S.current=!0,w.current=setTimeout(()=>{S.current=!1,w.current=null},Fz)},[r,G]),h.useEffect(()=>{k(u==="following"&&r)},[u,r]),h.useLayoutEffect(()=>{a&&W.current&&W.current===t&&Se()},[a,t,Se]);const je=h.useCallback(()=>{const fe=i.current;if(!fe)return;const ee=j.current;j.current=fe.scrollTop;const he=fe.scrollTop>ee+.5;if($(),!ci(fe)){q("following");return}if(f5(fe,x.current)){const Ce=Zb(fe)<=u5;(he||v.current==="following"||Ce)&&q("following");return}if(v.current==="following"&&(Q(fe)||D())){G(!1);return}ue()},[D,Q,G,q,ue,$]);Jz({containerEl:a,handleScrollEvent:je,releaseFromUserIntent:de,scrollRef:i,stateRef:v,canScroll:ci,scrollToBottomNow:J,updateOverflowAndButton:$,keyboardAnimRef:A,animationGuardUntilRef:T,lastScrollTopRef:j}),h.useEffect(()=>{const fe=a;if(!fe||typeof ResizeObserver>"u")return;const ee=new ResizeObserver(()=>{if(A.current){$();return}const Ce=i.current;if(Ce&&!ci(Ce)){q("following"),$();return}if($(),N.current&&Ce){const Ae=Ce.scrollHeight>P.current+1;P.current=Ce.scrollHeight,G(!0),Ae&&Y();return}F()&&v.current==="following"&&G(!1)});ee.observe(fe);const he=fe.firstElementChild;return he instanceof Element&&ee.observe(he),()=>ee.disconnect()},[Y,a,F,G,q,$]),h.useEffect(()=>{$()},[n,$]);const Oe=h.useCallback(fe=>{if(fe==="animation"&&(T.current=Ii()+Ub),$(),N.current){G(!0),Y();return}v.current==="following"&&G(!1)},[Y,G,$]),Be=h.useRef(new Map),Ie=h.useCallback(fe=>{const ee=Be.current.get(fe);if(ee)return ee;const he=()=>{v.current==="following"&&G(!1)},Ce={onChunk:he,onComplete:()=>{$()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:he,onReservationCancelled:()=>{}};return Be.current.set(fe,Ce),Ce},[G,$]);return h.useEffect(()=>()=>{_.current&&(clearTimeout(_.current),_.current=null),w.current&&(clearTimeout(w.current),w.current=null),U()},[U]),Xz(a,o),{scrollRef:i,state:u,isPinned:u==="following",isOverflowing:p,isFollowingProgrammatically:b,showScrollButton:g,notifyContentChange:Oe,getAnimationHandlers:Ie,goToBottom:B,scrollToBottomOnSend:ie,releaseAutoFollow:xe,restoreSnapshot:Se}},Vm=e=>{const t=e.info.clientRole??e.info.role;return typeof t=="string"?t:""},Bm=e=>{const t=e.info.parentID;if(!(typeof t!="string"||t.trim().length===0))return t},p5=e=>{if(!e)return null;const t=Vm(e),n=typeof e.info?.id=="string"?e.info.id:"",r=Bm(e)??"";return`${n}::${t}::${r}`},eU=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}),tU=(e,t,n)=>{if(!e||!t)return null;if(t.length===n.length){let u=-1;for(let f=0;f<n.length;f+=1)if(t[f]!==n[f]){if(u!==-1)return null;u=f}return u===-1?e:u!==n.length-1?null:p5(t[u])===p5(n[u])?e:null}if(n.length!==t.length+1)return null;for(let u=0;u<t.length;u+=1)if(t[u]!==n[u])return null;const r=n[n.length-1];if(!r)return null;const s=Vm(r),o=r.info.id,i=eU(e);if(s==="user"){const u=i.turnIds.length;return i.turnIds.push(o),i.turnMessageStartIndexes.push(n.length-1),i.turnIndexById.set(o,u),i.messageToTurnId.set(o,o),i.messageToTurnIndex.set(o,u),i.turnCount=i.turnIds.length,i}if(s!=="assistant"){const u=i.turnIds.length-1;if(u<0)return null;const f=i.turnIds[u];return f?(i.messageToTurnId.set(o,f),i.messageToTurnIndex.set(o,u),i):null}const a=Bm(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},nU=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 u=Vm(c),f=c.info.id;if(u==="user"){a=t.length,t.push(f),n.push(d),r.set(f,a),i.set(f,a),s.set(f,f),o.set(f,a);return}if(u!=="assistant"){if(a>=0){const y=t[a];y&&(s.set(f,y),o.set(f,a))}return}const p=Bm(c);if(!p)return;const m=i.get(p);if(typeof m!="number"||m<0)return;const g=t[m];g&&(s.set(f,g),o.set(f,m))}),{turnIds:t,turnMessageStartIndexes:n,turnIndexById:r,messageToTurnId:s,messageToTurnIndex:o,turnCount:t.length}},rU=30,sU=1200,oU=1.5,iU=e=>Math.max(sU,e*oU),aU=4,lU=30,cU=250,dU=2e3,uU=2500,Ks=new Map,fU=()=>rn()?aU:rU,hU=e=>rn()?e.length<=lU:!0,m5=(e,t)=>{if(Ks.delete(e),!hU(t.messages))return;const n=fU();for(;Ks.size>=n;){const r=Ks.keys().next().value;if(typeof r!="string")break;Ks.delete(r)}Ks.set(e,t)},pU=e=>!e.sessionId||!e.isPinned||!e.canLoadEarlier||e.isLoadingOlder||e.pendingRevealWork?!1:e.scrollHeight<=e.clientHeight+1,g5=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),mU=20,gU=4,y5=(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-gU&&(e.scrollTop=t),s+=1,s<mU?window.requestAnimationFrame(i):e.removeEventListener("touchstart",o))};window.requestAnimationFrame(i)},v5=(e,t,n)=>!e||!t||t===e?!1:n.some(r=>r.info.id===e);function yU({sessionKey:e,timelineIdentityRef:t,scrollRef:n,messageListRef:r,renderedMessages:s,isPinnedRef:o,goToBottom:i,captureViewportAnchor:a,restoreViewportAnchor:c}){const d=h.useRef(null),u=h.useRef(null);return h.useLayoutEffect(()=>{d.current=null,u.current=null},[e]),h.useLayoutEffect(()=>{const f=n.current;if(!f)return;let p=d.current;const m=u.current,g=s[0]?.info?.id??null,y=s[s.length-1]?.info?.id??null,b=m?g5({previousOldestId:m.oldestId,previousNewestId:m.newestId,currentOldestId:g,currentNewestId:y})||v5(m.oldestId,g,s):!1;p&&p.identity!==t.current&&(d.current=null,p=null);const k=p?g5({previousOldestId:p.oldestId,previousNewestId:p.newestId,currentOldestId:g,currentNewestId:y})||v5(p.oldestId,g,s):!1,v=b||k,x=!!(p&&(b||k)),C=()=>{u.current={oldestId:g,newestId:y,scrollHeight:f.scrollHeight}},S=()=>{const M=d.current;M&&(d.current={...M,height:f.scrollHeight,top:f.scrollTop,anchor:a(),oldestId:g,newestId:y})};if(o.current){v?(d.current=null,i("instant")):p&&S(),C();return}const w=r.current?.isHistoryVirtualized()??!1;if(p&&x){if(d.current=null,w){!p.historyVirtualized&&p.anchor&&c(p.anchor),C();return}const M=f.scrollHeight-p.height,I=()=>M<=0?!1:(f.scrollTop=p.top+M,!0);if(rn()&&M>0){y5(f,p.top+M),C();return}p.anchor&&c(p.anchor)||I()}else if(b&&m&&!w){const M=f.scrollHeight-m.scrollHeight;if(M>0){const I=f.scrollTop+M;rn()?y5(f,I):f.scrollTop=I}}else p&&S();C()},[a,r,s,n,c,i,o,t]),{prePrependScrollRef:d}}const vU=({sessionId:e,sessionKey:t,messages:n,historyMeta:r,scrollRef:s,messageListRef:o,loadMoreMessages:i,goToBottom:a,releaseAutoFollow:c,isPinned:d,showScrollButton:u})=>{const f=h.useRef(null),p=h.useRef(null),m=h.useRef(null),g=h.useMemo(()=>{const ee=t??"";m.current!==t&&(m.current=t,f.current=null,p.current=null);const he=ee?Ks.get(ee):void 0;if(he&&he.messages===n)return m5(ee,he),f.current=he.model,p.current=n,he.model;const Ae=tU(f.current,p.current,n)??nU(n);return f.current=Ae,p.current=n,ee&&n.length>0&&m5(ee,{messages:n,model:Ae}),Ae},[n,t]),[y,b]=h.useState(!1),[k,v]=h.useState(!1),[x,C]=h.useState(null),S=h.useRef(g),w=h.useRef(d),M=h.useRef(y),I=h.useRef(k),E=h.useRef(e),_=h.useRef({key:t});_.current.key!==t&&(_.current={key:t});const T=h.useRef(n),A=h.useRef(r),j=h.useRef(null),N=h.useRef([]),O=h.useRef(null),L=h.useRef(null),P=h.useRef(!1),W=h.useRef(null),F=h.useMemo(()=>{const ee=P2().HISTORICAL_MESSAGES,he=!1,Ce=r?!r.complete:n.length>=ee,Ae=!!r?.loading;return{hasBufferedTurns:he,hasMoreAboveTurns:Ce,historyLoading:Ae,canLoadEarlier:Ce}},[r,n.length]),q=h.useRef(F);S.current=g,w.current=d,M.current=y,I.current=k,q.current=F,E.current=e,T.current=n,A.current=r;const K=h.useCallback(()=>{P.current=!0,W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null)},[]),Q=h.useCallback(()=>{if(typeof window>"u"){P.current=!1;return}W.current!==null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{W.current=null,P.current=!1},dU)},[]);h.useLayoutEffect(()=>{if(j.current===t)return;W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),P.current=!1,j.current=t;const ee=O.current;ee&&ee.identity!==_.current&&(O.current=null,ee.resolve(!1)),b(!1),v(!1),L.current=null,C(null)},[t]),h.useLayoutEffect(()=>{if(!d)return;const ee=g.turnIds[g.turnIds.length-1];ee&&C(he=>he===ee?he:ee)},[d,g.turnIds]);const D=h.useCallback(()=>{const ee=N.current;ee.length!==0&&(N.current=[],ee.forEach(he=>he()))},[]),U=h.useCallback(()=>new Promise(ee=>{if(typeof window>"u"){ee();return}let he=!1;const Ce=()=>{he||(he=!0,window.clearTimeout(Ae),ee())};N.current.push(Ce);const Ae=window.setTimeout(Ce,cU)}),[]),Y=h.useCallback(ee=>{const he=O.current;he&&(O.current=null,he.resolve(ee))},[]),ne=h.useCallback(()=>{const ee=O.current;if(!ee)return;if(ee.identity!==_.current){Y(!1);return}if(ee.kind==="turn"?o.current?.scrollToTurnId(ee.id,{behavior:ee.behavior})??!1:o.current?.scrollToMessageId(ee.id,{behavior:ee.behavior})??!1){ee.turnId&&(L.current={turnId:ee.turnId,expiresAt:Date.now()+uU},C(ee.turnId)),Y(!0);return}typeof(ee.kind==="turn"?S.current.turnIndexById.get(ee.id):S.current.messageToTurnIndex.get(ee.id))=="number"&&Y(!1)},[o,Y]);h.useEffect(()=>()=>{W.current!==null&&typeof window<"u"&&(window.clearTimeout(W.current),W.current=null),D(),Y(!1)},[D,Y]);const $=n;h.useLayoutEffect(()=>{D(),ne()},[ne,$,D]);const J=h.useCallback(()=>o.current?.captureViewportAnchor()??null,[o]),G=h.useCallback(ee=>o.current?.restoreViewportAnchor(ee)??!1,[o]),{prePrependScrollRef:ue}=yU({sessionKey:t,timelineIdentityRef:_,scrollRef:s,messageListRef:o,renderedMessages:$,isPinnedRef:w,goToBottom:a,captureViewportAnchor:J,restoreViewportAnchor:G}),B=h.useCallback(async()=>!1,[]),ie=h.useCallback(async ee=>{if(!E.current||!_.current.key||M.current||!q.current.hasMoreAboveTurns)return!1;const he=E.current,Ce=_.current;if(!he||!Ce.key)return!1;const Ae=()=>{ue.current?.identity===Ce&&(ue.current=null)},Me=s.current,Ze=T.current,gt=Ze.length,we=Ze[0]?.info?.id??null,re=A.current?.limit??P2().HISTORICAL_MESSAGES;ee.preserveViewport&&Me&&(ue.current={identity:Ce,height:Me.scrollHeight,top:Me.scrollTop,anchor:J(),historyVirtualized:o.current?.isHistoryVirtualized()??!1,oldestId:we,newestId:Ze[Ze.length-1]?.info?.id??null}),K(),b(!0);try{let ge=gt,pe=we,ke=re;const _e=S.current.turnCount;for(;;){if(await i(he,"up"),_.current!==Ce||(await U(),_.current!==Ce))return Ae(),!1;const Te=T.current,be=Te.length,ae=Te[0]?.info?.id??null,te=A.current?.limit??ke,oe=be>ge||typeof pe=="string"&&typeof ae=="string"&&pe!==ae||te>ke;if(S.current.turnCount-_e>0)return!0;if(!oe)return Ae(),!1;if(!q.current.hasMoreAboveTurns)return!0;ge=be,pe=ae,ke=te}}catch(ge){throw Ae(),ge}finally{_.current===Ce&&(b(!1),Q())}},[K,J,i,o,ue,s,Q,U]),xe=h.useCallback(async ee=>{const he=_.current;K(),ee?.userInitiated&&c();try{await ie({preserveViewport:!0})}finally{_.current===he&&Q()}},[K,ie,c,Q]),de=h.useCallback(()=>{if(rn())return;const ee=s.current;ee&&(w.current||ee.scrollTop>=iU(ee.clientHeight)||q.current.canLoadEarlier&&(M.current||I.current||xe({userInitiated:!0})))},[xe,s]),Se=h.useCallback(()=>{if(rn()||P.current)return;const ee=s.current;ee&&pU({sessionId:E.current,isPinned:w.current,canLoadEarlier:q.current.canLoadEarlier,isLoadingOlder:M.current,pendingRevealWork:I.current,scrollHeight:ee.scrollHeight,clientHeight:ee.clientHeight})&&xe()},[xe,s]);h.useEffect(()=>{if(typeof window>"u")return;const ee=window.requestAnimationFrame(()=>{Se()});return()=>window.cancelAnimationFrame(ee)},[F.canLoadEarlier,y,d,Se,k,$.length,t]),h.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const ee=s.current;if(!ee)return;let he=null;const Ce=()=>{he===null&&(he=window.requestAnimationFrame(()=>{he=null,Se()}))},Ae=new ResizeObserver(Ce);Ae.observe(ee);const Me=ee.firstElementChild;return Me instanceof Element&&Ae.observe(Me),Ce(),()=>{he!==null&&window.cancelAnimationFrame(he),Ae.disconnect()}},[Se,s,t]);const je=h.useCallback(async(ee,he)=>{if(!ee||!E.current||!_.current.key)return!1;const Ce=_.current;c(),v(!0);try{return _.current!==Ce||typeof S.current.turnIndexById.get(ee)!="number"?!1:!!await new Promise(Ze=>{O.current={identity:Ce,kind:"turn",id:ee,behavior:he?.behavior??"auto",turnId:ee,resolve:Ze},ne()})}finally{_.current===Ce&&v(!1)}},[ne,c]),Oe=h.useCallback(async(ee,he)=>{if(!ee||!E.current||!_.current.key)return!1;const Ce=_.current;c(),v(!0);try{if(_.current!==Ce)return!1;const Ae=S.current.messageToTurnId.get(ee);return typeof S.current.messageToTurnIndex.get(ee)!="number"?!1:!!await new Promise(gt=>{O.current={identity:Ce,kind:"message",id:ee,behavior:he?.behavior??"auto",turnId:Ae??null,resolve:gt},ne()})}finally{_.current===Ce&&v(!1)}},[ne,c]),Be=h.useCallback(async()=>{v(!1),b(!1),a("smooth")},[a]),Ie=h.useCallback(async()=>{v(!1),b(!1),a("instant")},[a]),fe=h.useCallback(ee=>{const he=L.current;if(he){if(ee!==he.turnId&&Date.now()<he.expiresAt)return;L.current=null}C(ee)},[]);return{turnIds:g.turnIds,turnStart:0,renderedMessages:$,historySignals:F,isLoadingOlder:y,pendingRevealWork:k,activeTurnId:x,showScrollToBottom:u&&!k,turnWindowModel:g,loadEarlier:xe,revealBufferedTurns:B,resumeToBottom:Be,resumeToBottomInstant:Ie,scrollToTurn:je,scrollToMessage:Oe,handleHistoryScroll:de,captureViewportAnchor:J,restoreViewportAnchor:G,handleActiveTurnChange:fe}};function Jh(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
212
- `)}function Wb(e,t=80){const r=Jh(e).replace(/\n/g," ");return r.length>t?`${r.slice(0,t)}…`:r}const xU=({open:e,onOpenChange:t,onScrollToMessage:n,onScrollByTurnOffset:r,onResumeToLatest:s,canLoadEarlier:o=!1,isLoadingEarlier:i=!1,onLoadEarlier:a,onRevert:c,onFork:d})=>{const{isMobile:u}=Rr(),f=ve(U=>U.currentSessionId),[p,m]=h.useState(0);h.useEffect(()=>{if(!f){m(0);return}const U=()=>{try{const{getPiSessionStore:Y}=require("@/apps/pi-session-store");m(Y().getState().reducer.bySession.get(f)?.sessionTreeRevision??0)}catch{m(0)}};U();try{const{getPiSessionStore:Y}=require("@/apps/pi-session-store");return Y().subscribe(U,`session:${f}`)}catch{return}},[f]);const[g,y]=h.useState(new Map),b=h.useRef(null);h.useEffect(()=>{if(!e||!f)return;b.current!==f&&(b.current=f,y(new Map));let U=!1;return(async()=>{try{const{getPiSessionStore:Y}=require("@/apps/pi-session-store"),ne=await Y().tree(f);if(U)return;const $=new Map,J=G=>{G.label&&$.set(G.entryId,G.label);for(const ue of G.children)J(ue)};for(const G of ne.nodes)J(G);y($)}catch{}})(),()=>{U=!0}},[f,e,p]);const[k,v]=h.useState(!1);h.useEffect(()=>{if(!f){v(!1);return}const U=()=>{try{const{getPiSessionStore:Y}=require("@/apps/pi-session-store"),ne=Y().getState().reducer.bySession.get(f);v(ne?.lifecycle==="busy"||ne?.lifecycle==="retry")}catch{v(!1)}};U();try{const{getPiSessionStore:Y}=require("@/apps/pi-session-store");return Y().subscribe(U,`session:${f}`)}catch{return}},[f]);const x=pd(f??""),[C,S]=h.useState(""),[w,M]=h.useState(0),I=h.useRef([]),E=h.useRef(null),_=h.useRef(null),T=h.useRef(!1),A=h.useRef(e),j=h.useCallback(U=>new Date(U).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric"}),[]),N=h.useCallback(U=>new Date(U).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),[]),O=h.useMemo(()=>x.filter(U=>U.info.role==="user").map(U=>({message:U})),[x]),L=h.useMemo(()=>{const U=C.trim();if(!U)return O;const Y=U.toLowerCase();return O.filter(({message:ne})=>Jh(ne.parts).toLowerCase().includes(Y))},[O,C]);h.useEffect(()=>{T.current||M(C.trim()?0:Math.max(0,L.length-1))},[L,C]),h.useEffect(()=>{I.current=I.current.slice(0,L.length)},[L.length]),h.useEffect(()=>{T.current||I.current[w]?.scrollIntoView({block:"nearest"})},[w]),h.useEffect(()=>{!T.current||_.current||i||(T.current=!1)},[L.length,i]),h.useLayoutEffect(()=>{const U=A.current;if(A.current=e,!e||U||T.current||C.trim())return;const Y=E.current;Y&&(Y.scrollTop=Y.scrollHeight)},[e,C]),h.useLayoutEffect(()=>{const U=_.current,Y=E.current;if(!U||!Y||i)return;_.current=null;const ne=I.current.find(J=>J?.dataset.timelineMessageId===U.messageId);if(!ne)return;const $=ne.getBoundingClientRect().top-Y.getBoundingClientRect().top;Y.scrollTop+=$-U.top},[L.length,i]);const P=h.useCallback(()=>{const U=E.current;if(U){const Y=U.getBoundingClientRect().top,ne=I.current.find($=>$?$.getBoundingClientRect().bottom>=Y:!1);ne?.dataset.timelineMessageId&&(_.current={messageId:ne.dataset.timelineMessageId,top:ne.getBoundingClientRect().top-Y})}T.current=!0,a?.()},[a]),W=h.useCallback(async U=>{await n?.(U)!==!1&&t(!1)},[t,n]),F=h.useCallback(U=>{const Y=L.length;if(Y!==0){if(U.key==="ArrowDown"){U.preventDefault(),M(ne=>(ne+1)%Y);return}if(U.key==="ArrowUp"){U.preventDefault(),M(ne=>(ne-1+Y)%Y);return}if(U.key==="Enter"){U.preventDefault();const ne=(w%Y+Y)%Y,$=L[ne];$&&W($.message.info.id)}}},[L,W,w]),q=h.useCallback(async()=>{const U=L.length;if(U===0||!c||k)return;const Y=(w%U+U)%U,ne=L[Y];if(ne)try{await c(ne.message.info.id),t(!1)}catch($){Ne.error($ instanceof Error?$.message:"Failed to revert")}},[L,k,c,t,w]),K=h.useCallback(async()=>{const U=L.length;if(U===0||!d||k)return;const Y=(w%U+U)%U,ne=L[Y];if(ne)try{await d(ne.message.info.id),t(!1)}catch($){Ne.error($ instanceof Error?$.message:"Failed to fork")}},[L,k,d,t,w]),Q=h.useCallback(U=>{const Y=L.length;if(Y!==0){if(U.key==="ArrowDown"){U.preventDefault(),M(ne=>(ne+1)%Y);return}if(U.key==="ArrowUp"){U.preventDefault(),M(ne=>(ne-1+Y)%Y);return}if(U.key==="Enter"){U.preventDefault();const ne=(w%Y+Y)%Y,$=L[ne];$&&W($.message.info.id)}}},[L,W,w]);if(h.useEffect(()=>{if(!e||u)return;const U=window.setTimeout(()=>E.current?.focus(),100);return()=>window.clearTimeout(U)},[e,u]),!f)return null;const D=L[(w%Math.max(1,L.length)+Math.max(1,L.length))%Math.max(1,L.length)]?.message??null;return l.jsx(vd,{open:e,onOpenChange:t,children:l.jsxs(xd,{className:R("flex flex-col",u?"max-w-full max-h-[85vh] rounded-t-2xl mt-auto":"max-w-2xl max-h-[70vh]"),children:[l.jsxs(bd,{children:[l.jsxs(wd,{className:"flex items-center gap-2",children:[l.jsx(V,{name:"time",className:"h-5 w-5"}),"Conversation Timeline"]}),l.jsx(Bp,{children:u?"Tap a message, then Revert or Fork":"Arrow keys to move • Enter to jump"})]}),!u&&l.jsxs("div",{className:"relative mt-2",children:[l.jsx(V,{name:"search",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(Ar,{placeholder:"Search messages...",value:C,onChange:U=>S(U.target.value),onKeyDown:F,className:"pl-9 w-full"})]}),o&&a&&l.jsx("div",{className:"flex justify-center py-1",children:l.jsxs(Ee,{type:"button",variant:"link",size:"sm",onClick:P,disabled:i,className:"h-auto px-1 py-0 text-muted-foreground hover:text-foreground",children:[i&&l.jsx(V,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),l.jsx("div",{ref:E,tabIndex:0,onKeyDown:Q,className:"flex-1 overflow-y-auto outline-none focus-visible:ring-1 focus-visible:ring-ring rounded","aria-label":"Message list",children:L.length===0?l.jsx("div",{className:"text-center text-muted-foreground py-8",children:C?"No messages found":"No messages in this session yet"}):L.map(({message:U},Y)=>{const ne=Wb(U.parts),$=U.info.time?.created??0,J=j($),G=L[Y-1],ue=G?j(G.message.info.time?.created??0):null,B=J!==ue,ie=N($),xe=Y===w,de=g.get(U.info.id),Se=C.trim()?wU(Jh(U.parts),C):null;return l.jsxs(h.Fragment,{children:[B&&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:J}),l.jsx("div",{className:"h-px flex-1 bg-border/60"})]}),l.jsxs("div",{ref:je=>{I.current[Y]=je},"data-timeline-message-id":U.info.id,className:R("group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",xe&&"bg-interactive-selection text-interactive-selection-foreground"),onClick:()=>{W(U.info.id)},onMouseEnter:()=>M(Y),children:[l.jsx("span",{className:R("typography-meta w-16 flex-shrink-0 text-right tabular-nums",xe?"text-interactive-selection-foreground/70":"text-muted-foreground"),children:ie}),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:R("flex-1 min-w-0 typography-small truncate",xe?"text-interactive-selection-foreground":"text-foreground"),children:[Se??(ne||"[No text content]"),!Se&&ne&&ne.length>=80&&"…"]})]})]},U.info.id)})}),D&&l.jsxs("div",{className:R("flex gap-2 mt-3",u?"flex-col":"flex-row"),children:[l.jsxs(Ee,{type:"button",variant:u?"default":"outline",size:u?"default":"sm",className:R(u&&"w-full justify-center h-11 text-base"),disabled:k,onClick:()=>{q()},children:[l.jsx(V,{name:"history",className:"h-4 w-4"}),"Revert"]}),l.jsxs(Ee,{type:"button",variant:"outline",size:u?"default":"sm",className:R(u&&"w-full justify-center h-11 text-base"),disabled:k,onClick:()=>{K()},children:[l.jsx(V,{name:"git-branch",className:"h-4 w-4"}),"Fork"]})]})]})})},bU=e=>e.open?l.jsx(xU,{...e}):null;function wU(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 SU=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},CU=(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"}},Al=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)},kU=({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&&Al(`turn-${p}`),r(p,{behavior:m?.behavior})):!1,[r]),d=h.useCallback(async(p,m)=>p?(m?.updateHash!==!1&&Al(`message-${p}`),s(p,{behavior:m?.behavior})):!1,[s]),u=h.useCallback(async(p,m)=>{const g=i.current,y=CU(g,a.current,p);if(y.kind==="noop")return p===0;if(y.kind==="resume"){if(m?.resumePastEnd===!1){const b=g[g.length-1];return b?c(b,{behavior:"auto"}):!1}return Al(null),o(),!0}return c(y.turnId,{behavior:"auto"})},[o,c]),f=h.useCallback(()=>{Al(null),o()},[o]);return h.useEffect(()=>{if(!e||typeof window>"u")return;const p=()=>{const m=SU(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:u,resumeToLatest:f}},MU=[],IU={type:"idle"},x5="pichamber:chat-force-scroll-bottom",_U="Quota limit reached. Retrying automatically.",EU={overflowAnchor:"none",overscrollBehavior:"contain",overscrollBehaviorY:"contain"},_f=e=>R("relative z-10 flex flex-col gap-2 bg-background",e?"flex-1 min-h-0":"shrink-0"),jU=["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(","),TU=e=>e instanceof HTMLElement,$m=e=>TU(e)?!!e.closest(jU):!1,AU=(e,t)=>typeof document>"u"||!e||e===document.body||e===document.documentElement||$m(e)?!0:!t?.contains(e),LU=()=>{const{isCommandPaletteOpen:e,isHelpDialogOpen:t,isImagePreviewOpen:n,isSessionSwitcherOpen:r,isSettingsDialogOpen:s}=se.getState();return e||t||n||r||s},NU=(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)]})},b5=()=>{const e=ve(n=>n.newSessionDraft.selectedProjectId??null),t=it(h.useCallback(n=>YE({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:NU(t?`What are we working on in ${t}?`:"What are we working on?",t)}),l.jsx(e4,{onInsert:n=>{n.ref.type==="text"?Ge.getState().requestStarterTextInsert(n.insertText):Ge.getState().requestStarterInsert(n.promptName)},className:"oc-draft-starters mt-8 max-w-md"})]})},qb=h.memo(()=>{const e=ve(c=>c.currentSessionId),t=ve(h.useCallback(c=>e?c.sessionAbortFlags?.get(e)??null:null,[e])),{activeModel:n,working:r}=wb(),s=Lv(e??""),o=qe(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 lm(c,n.modelId)||null},[n,o]),a=!!(t&&!t.acknowledged);return l.jsx(Ax,{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})});qb.displayName="StatusRowContainer";const RU=160,Ef=28,PU=12,di=6,DU=8,ui=30,fi=12,w5=18,OU=80,Ll=4,HU=10,FU=14,VU=20,Jt=54,S5=4,BU=8,C5=2,$U=160,zU=(e,t)=>e.map(n=>{const r=t.get(n)??[];return{turnId:n,preview:Wb(r,RU)}}),UU=[1,.6,.35,.15],ZU=(e,t,n)=>{const r=n?FU:HU;if(t===null)return r;const s=Math.abs(e-t),o=UU[s]??0;return Math.round(r+(VU-r)*o)};function WU({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:s,isLoadingOlder:o,onLoadEarlier:i}){const a=se(te=>te.isPromptNavigatorPanelOpen),c=se(te=>te.setPromptNavigatorPanelOpen),d=h.useRef(null),u=h.useRef(null),[f,p]=h.useState(null),[m,g]=h.useState(0),[y,b]=h.useState(!1),[k,v]=h.useState(di);h.useEffect(()=>{const te=u.current?.parentElement;if(!te||typeof ResizeObserver>"u")return;const oe=()=>{const We=te.querySelector(".chat-message-column");if(!We){b(!1),v(di);return}const ct=te.getBoundingClientRect(),Lt=We.getBoundingClientRect(),Ut=ct.right-Lt.right-DU-Ef;if(Ut<=di){v(di);const xs=ct.right-di-Ef;b(Lt.right>xs);return}v(Ut),b(!1)};oe();const me=new ResizeObserver(oe);me.observe(te);const Re=te.querySelector(".chat-message-column");return Re&&me.observe(Re),()=>me.disconnect()},[e.length]);const x=h.useMemo(()=>zU(e,t),[t,e]),C=Math.min(x.length,ui),S=Math.max(0,x.length-C),w=Math.min(m,S),M=w+C,I=w>0,E=M<x.length,_="[No text content]",T="Current prompt",A="Load more prompts",j=h.useMemo(()=>n?x.findIndex(te=>te.turnId===n):-1,[n,x]),N=h.useRef(w);N.current=w;const O=h.useRef(x.length);O.current=x.length;const L=h.useRef(null),P=h.useRef(null),W=h.useRef(0),F=h.useCallback(te=>{g(oe=>{const me=O.current,Re=Math.min(me,ui),We=Math.max(0,me-Re),ct=Math.min(oe,We);return te<ct?te:te>=ct+Re?Math.min(We,te-Re+1):ct})},[]),q=h.useRef(x[0]?.turnId),K=h.useRef(x.length);h.useLayoutEffect(()=>{const te=q.current,oe=K.current,me=x.length-oe;me>0&&oe>0&&te&&x[0]?.turnId!==te&&(g(Re=>Re+me),p(Re=>Re===null?null:Re+me)),q.current=x[0]?.turnId,K.current=x.length},[x]),h.useEffect(()=>{if(f!==null)return;const te=j>=0?j:x.length-1;g(()=>{const oe=O.current,me=Math.min(oe,ui),Re=Math.max(0,oe-me);return Math.max(0,Math.min(Re,te-Math.floor(me/2)))})},[j,f,x.length]);const Q=h.useCallback(te=>{const oe=d.current;if(!oe)return null;const me=oe.getBoundingClientRect(),Re=Math.floor((te-me.top)/fi),We=Math.min(O.current,ui);return We===0?null:Math.max(0,Math.min(We-1,Re))},[]),D=h.useCallback(()=>{W.current=0,P.current!==null&&(window.clearInterval(P.current),P.current=null)},[]),U=h.useCallback(()=>{const te=W.current;if(te===0){D();return}const oe=O.current,me=Math.min(oe,ui),Re=Math.max(0,oe-me),We=Math.min(N.current,Re),ct=Math.max(0,Math.min(Re,We+te));if(ct===We){D();return}N.current=ct,g(ct);const Lt=L.current;if(Lt!==null){const Ut=Q(Lt);Ut!==null&&p(Math.min(oe-1,ct+Ut))}},[Q,D]),Y=h.useCallback(te=>{const oe=d.current;if(!oe)return;const me=oe.getBoundingClientRect(),Re=te-me.top;let We=0;if(Re<=w5&&I?We=-1:Re>=me.height-w5&&E&&(We=1),W.current=We,We===0){D();return}P.current===null&&(P.current=window.setInterval(U,OU))},[U,I,E,D]);h.useEffect(()=>()=>{P.current!==null&&window.clearInterval(P.current)},[]);const ne=h.useRef(null),$=h.useCallback(()=>{ne.current!==null&&(window.clearTimeout(ne.current),ne.current=null)},[]),J=h.useCallback(()=>{$(),ne.current=window.setTimeout(()=>{ne.current=null,p(null)},$U)},[$]);h.useEffect(()=>()=>{ne.current!==null&&window.clearTimeout(ne.current)},[]);const G=h.useCallback(te=>{$(),L.current=te.clientY;const oe=Q(te.clientY);oe!==null&&p(Math.min(O.current-1,N.current+oe)),Y(te.clientY)},[$,Q,Y]),ue=h.useCallback(()=>{L.current=null,D(),J()},[J,D]),B=h.useCallback(()=>{c(!1)},[c]),ie=h.useCallback(te=>{if(te===null)return;const oe=x[te];oe&&(r(oe.turnId),D(),p(null),B(),d.current?.blur())},[B,r,x,D]),xe=h.useCallback(te=>{const oe=Q(te.clientY);oe!==null&&ie(Math.min(x.length-1,N.current+oe))},[ie,x.length,Q]);h.useEffect(()=>{if(!a)return;const te=d.current;!te||te===document.activeElement||(te.focus(),p(oe=>{if(oe!==null)return oe;const me=j>=0?j:x.length-1;return F(me),me}))},[j,F,a,x.length]),h.useEffect(()=>()=>{c(!1)},[c]);const de=h.useCallback(te=>{if(x.length===0)return;const oe=f??(j>=0?j:x.length-1),me=Re=>{const We=Math.max(0,Math.min(x.length-1,Re));F(We),p(We)};if(te.key==="ArrowUp"||te.key==="ArrowDown"){te.preventDefault(),me(oe+(te.key==="ArrowUp"?-1:1));return}if(te.key==="Home"){te.preventDefault(),me(0);return}if(te.key==="End"){te.preventDefault(),me(x.length-1);return}if(te.key==="Enter"||te.key===" "){te.preventDefault(),ie(oe);return}te.key==="Escape"&&(te.preventDefault(),p(null),B(),d.current?.blur())},[j,B,F,ie,f,x]),Se=h.useCallback(()=>{D(),p(null),B()},[B,D]),je=h.useRef(null),Oe=h.useRef(f);Oe.current=f;const Be=f!==null,Ie=h.useRef(0);h.useEffect(()=>{const te=je.current;if(!te)return;const oe=me=>{me.preventDefault(),me.stopPropagation(),Ie.current+=me.deltaY;const Re=Math.trunc(Ie.current/Jt);if(Re===0)return;Ie.current-=Re*Jt;const We=Oe.current;if(We===null)return;const ct=Math.max(0,Math.min(O.current-1,We+Re));ct!==We&&(F(ct),p(ct))};return te.addEventListener("wheel",oe,{passive:!1}),()=>te.removeEventListener("wheel",oe)},[F,Be]);const fe=f!==null?x[f]:void 0,ee=Math.min(x.length,BU),he=ee*Jt,Ce=x.length*Jt-he,Ae=te=>Math.max(0,Math.min(Ce,te)),Me=h.useRef(null);let Ze=0;if(f===null)Me.current=null;else if(Me.current===null)Ze=Ae(f*Jt-(he-Jt)/2),Me.current=Ze;else{let te=Me.current;const oe=(f-C5)*Jt,me=(f+1+C5)*Jt-he;te>oe?te=oe:te<me&&(te=me),Ze=Ae(te),Me.current=Ze}const gt=Math.floor(Ze/Jt),we=Math.max(0,gt-Ll),re=Math.min(x.length,gt+ee+Ll),ge=Ze>0,pe=Ze<Ce,ke=ge||pe?`linear-gradient(to bottom, ${ge?"transparent, black 10%":"black"}, ${pe?"black 90%, transparent":"black"})`:void 0,_e=Math.max(0,w-Ll),Te=Math.min(x.length,M+Ll),be=x.slice(_e,Te),ae=I||E?`linear-gradient(to bottom, ${I?"transparent, black 14%":"black"}, ${E?"black 86%, transparent":"black"})`:void 0;return x.length===0?null:l.jsx("nav",{ref:u,"aria-label":"Prompt navigation",className:"pointer-events-none absolute top-1/2 z-20 -translate-y-1/2",style:{right:`${k}px`},children:l.jsxs("div",{className:"pointer-events-auto flex flex-col items-end",children:[s?l.jsx("button",{type:"button",tabIndex:-1,className:R("-mr-px mb-1.5 flex size-5 shrink-0 items-center justify-center rounded-full","text-[var(--surface-mutedForeground)] transition-colors","hover:bg-[var(--interactive-hover)]/60 hover:text-[var(--surface-foreground)]",o?"cursor-wait opacity-70":void 0),"aria-label":A,title:A,disabled:o,onClick:te=>{te.stopPropagation(),o||i()},children:o?l.jsx(V,{name:"loader-4",className:"size-3.5 animate-spin"}):l.jsx(V,{name:"arrow-up-s",className:"size-3.5"})}):null,l.jsxs("div",{ref:d,role:"listbox",tabIndex:-1,"aria-activedescendant":fe?`prompt-rail-tick-${fe.turnId}`:void 0,className:"relative cursor-pointer outline-none",style:{width:`${y?PU:Ef}px`,height:`${C*fi}px`},onMouseMove:G,onMouseLeave:ue,onClick:xe,onKeyDown:de,onBlur:Se,children:[l.jsx("div",{className:"absolute inset-0 overflow-hidden",style:ae?{maskImage:ae,WebkitMaskImage:ae}:void 0,children:l.jsx("div",{className:"absolute inset-x-0 top-0 transition-transform duration-300 ease-out",style:{transform:`translateY(-${w*fi}px)`},children:be.map((te,oe)=>{const me=_e+oe,Re=te.turnId===n,We=f===me,ct=ZU(me,f,Re);return l.jsx("div",{id:`prompt-rail-tick-${te.turnId}`,role:"option","aria-selected":We,"aria-current":Re?"true":void 0,"aria-label":te.preview.trim()||_,className:"pointer-events-none absolute right-1 flex items-center justify-end",style:{top:`${me*fi}px`,height:`${fi}px`},children:l.jsx("span",{"aria-hidden":"true",className:R("block h-0.5 rounded-full transition-all duration-200 ease-out",Re?"bg-[var(--surface-foreground)]":We?"bg-[var(--surface-foreground)]/80":"bg-[var(--surface-foreground)]/30"),style:{width:`${ct}px`}})},te.turnId)})},x[0]?.turnId)}),fe&&f!==null?l.jsx("div",{ref:je,className:R("pointer-events-auto absolute right-full top-1/2 z-30 mr-3 -translate-y-1/2","w-[min(20rem,calc(100vw-6rem))] overflow-hidden rounded-xl","border border-[var(--interactive-border)]/60 bg-[var(--surface-elevated)] py-1 shadow-md"),onMouseEnter:$,onMouseLeave:J,onMouseMove:te=>te.stopPropagation(),onClick:te=>te.stopPropagation(),children:l.jsx("div",{className:"relative overflow-hidden",style:{height:`${ee*Jt}px`,maskImage:ke,WebkitMaskImage:ke},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(we,re).map((te,oe)=>{const me=we+oe,Re=te.turnId===n,We=f===me;return l.jsx("div",{role:"option","aria-selected":We,"aria-current":Re?"true":void 0,title:Re?T:void 0,className:"absolute inset-x-0 cursor-pointer px-1.5",style:{top:`${me*Jt+S5}px`,height:`${Jt-S5*2}px`},onMouseMove:()=>{$(),Oe.current!==me&&(F(me),p(me))},onClick:()=>ie(me),children:l.jsx("div",{className:R("flex h-full items-center rounded-lg border px-2 transition-colors",Re?"border-transparent bg-[var(--interactive-selection)]":We?"border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]":"border-[var(--interactive-border)]/40"),children:l.jsx("span",{className:R("min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] typography-meta",Re?"text-[var(--interactive-selectionForeground)]":"text-[var(--surface-mutedForeground)]"),children:te.preview.trim()||_})})},te.turnId)})})})}):null]})]})})}const Gb=h.memo(({currentSessionId:e,currentSessionKey:t,isDesktopExpandedInput:n,isMobile:r,directory:s,scrollRef:o,messageListRef:i,pendingRevealWork:a,renderedMessages:c,isLoadingOlder:d,sessionIsWorking:u,sessionAwaitingRecovery:f,awaitingPromptEcho:p,streamingMessageId:m,activeStreamingPhase:g,retryOverlay:y,compactionOverlay:b,handleMessageContentChange:k,getAnimationHandlers:v,handleHistoryScroll:x,scrollToBottom:C,isProgrammaticFollowActive:S,showLoadOlderButton:w,onLoadOlder:M,turnIds:I,activeTurnId:E,onSelectTurn:_,showPromptNavigator:T,canLoadEarlierPrompts:A,isLoadingOlderPrompts:j,onLoadEarlierPrompts:N})=>{const O=h.useRef(new Map),L=h.useRef(new WeakMap),P=h.useRef(new Map),W=h.useRef(e);W.current!==e&&(W.current=e,P.current.clear());const F=h.useMemo(()=>{const D=new Map;for(let Y=0;Y<c.length;Y+=1){const ne=c[Y];if(ne.info.role!=="user")continue;if(_4(ne)){const J=TO(c,Y)??"",G=P.current.get(ne.info.id);if(G&&G.command===J)D.set(ne.info.id,G.parts);else{const ue=[{type:"text",text:J?`$ ${J}`:"/shell"}];P.current.set(ne.info.id,{command:J,parts:ue}),D.set(ne.info.id,ue)}continue}if(iB(ne.parts))continue;let $=L.current.get(ne.parts);$||($=Hm(ne.parts),L.current.set(ne.parts,$)),$.length!==0&&D.set(ne.info.id,$)}const U=O.current;if(U.size===D.size){let Y=!0;for(const[ne,$]of D)if(U.get(ne)!==$){Y=!1;break}if(Y)return U}return O.current=D,D},[c]),q=h.useMemo(()=>I.filter(D=>F.has(D)),[F,I]),K=h.useMemo(()=>{if(!E||F.has(E))return E;const D=I.indexOf(E);for(let U=D-1;U>=0;U-=1){const Y=I[U];if(F.has(Y))return Y}return null},[E,F,I]),Q=h.useCallback(D=>{D.defaultPrevented||$m(D.target)||typeof window<"u"&&window.getSelection()?.type==="Range"||o.current?.focus({preventScroll:!0})},[o]);return l.jsx("div",{className:R("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(Cd,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:o,style:EU,observeMutations:!1,hideTopShadow:!1,tabIndex:0,onClick:Q,onScroll:x,"data-scroll-shadow":"true","data-scrollbar":"chat",children:l.jsxs("div",{className:"relative z-0 min-h-full",children:[w&&l.jsx("div",{className:"flex justify-center pt-3 pb-1",children:l.jsxs(Ee,{variant:"secondary",size:"sm",onClick:M,disabled:d,children:[d&&l.jsx(V,{name:"loader-4",className:"size-4 animate-spin"}),"Load older messages"]})}),l.jsx(Nz,{ref:i,sessionKey:e,disableStaging:a,messages:c,sessionIsWorking:u,sessionAwaitingRecovery:f,awaitingPromptEcho:p,activeStreamingMessageId:m,activeStreamingPhase:g,retryOverlay:y,compactionOverlay:b,onMessageContentChange:k,getAnimationHandlers:v,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:s},t),I.length===0&&u?l.jsx("div",{className:"mb-3",children:l.jsx(qb,{})}):I.length===0&&f?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(O3,{containerRef:o,suppressVisibility:S,userIntentOnly:!0,observeMutations:!1}),T&&q.length>=2?l.jsx(WU,{turnIds:q,previewsByTurnId:F,activeTurnId:K,onSelectTurn:_,canLoadEarlier:A,isLoadingOlder:j,onLoadEarlier:N}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.currentSessionKey===t.currentSessionKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.sessionAwaitingRecovery===t.sessionAwaitingRecovery&&e.awaitingPromptEcho===t.awaitingPromptEcho&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.compactionOverlay===t.compactionOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.scrollToBottom===t.scrollToBottom&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&e.onLoadOlder===t.onLoadOlder&&e.turnIds===t.turnIds&&e.activeTurnId===t.activeTurnId&&e.onSelectTurn===t.onSelectTurn&&e.showPromptNavigator===t.showPromptNavigator&&e.canLoadEarlierPrompts===t.canLoadEarlierPrompts&&e.isLoadingOlderPrompts===t.isLoadingOlderPrompts&&e.onLoadEarlierPrompts===t.onLoadEarlierPrompts);Gb.displayName="ChatViewport";const qU={isWorking:!1,isAwaitingRecovery:!1},iq=({active:e=!0,autoOpenDraft:t=!0})=>{const n=ve(oe=>oe.currentSessionId),r=ve(oe=>oe.currentSessionDirectory),s=ve(oe=>oe.openNewSessionDraft),o=ve(oe=>oe.newSessionDraft),i=ve(oe=>oe.sendingNewSessionDraftId),a=g3(o,n,i),c=Mx(),d=Fk(),u=r??d,f=n?JSON.stringify([X(),u,n]):null,p=h.useCallback(oe=>c.ensureSessionRenderable(oe),[c]),m=h.useCallback(async()=>{},[]),g=se(oe=>oe.isExpandedInput),y=se(oe=>oe.isTimelineDialogOpen),b=se(oe=>oe.setTimelineDialogOpen),k=f3(),v=$x(),x=$k(n??""),S=k==="ready"&&!v?x:null,w=S?"streaming":null,M=Zk(n??""),I=p3(n??""),E=pd(n??""),_=n?E:MU,T=Vk(n??""),[A]=h.useState(b_);h.useEffect(()=>{if(!(!e||!f||!I||_.length===0))return A.schedule(f,_.length)},[e,f,A,I,_.length]);const j=hd(n??"")??IU,N=h.useMemo(()=>{if(!n)return qU;const oe=j.type??"idle",me=_[_.length-1]?.info,Re=typeof me?.finish=="string"?me.finish:void 0,We=!!(me&&me.role==="assistant"&&typeof me.time?.completed!="number"&&Re!=="stop"&&Re!=="error");return pE({connection:k,transportUncertain:v,authoritativeWorking:oe==="busy"||oe==="retry",hasPendingAssistant:We,hasRetainedStream:!!x})},[k,n,x,_,j.type,v]),O=N.isWorking,L=N.isAwaitingRecovery,P=zk(n??""),W=h.useMemo(()=>{if(!n||j.type!=="retry")return null;const oe=typeof j.message=="string"?(j.message??"").trim():"";return{sessionId:n,message:oe||_U,confirmedAt:j.confirmedAt}},[n,j]),F=Ok(n??""),q=h.useMemo(()=>n&&F?{sessionId:n,compaction:F}:null,[F,n]),[K,Q]=h.useState(0),D=h.useRef(null);h.useEffect(()=>{if(!W||typeof W.confirmedAt=="number"){D.current=null,Q(0);return}D.current!==W.sessionId&&(D.current=W.sessionId,Q(Date.now()))},[W]);const U=h.useMemo(()=>W?{...W,fallbackTimestamp:K}:null,[W,K]),Y=h.useMemo(()=>n?{limit:_.length,complete:T.complete||!T.cursor,loading:T.status==="loading"}:null,[n,T.complete,T.cursor,T.status,_.length]),{isMobile:ne}=Rr(),$=Ed(),J=!!o?.open,G=ne&&g,ue=ne||$==="mini-chat",B=h.useRef(null);h.useEffect(()=>{o3().sessionId||t&&!n&&!J&&s({automatic:!0})},[t,n,J,s]);const ie=h.useRef(()=>{}),xe=h.useCallback(oe=>{ie.current(oe)},[]),{scrollRef:de,notifyContentChange:Se,getAnimationHandlers:je,goToBottom:Oe,scrollToBottomOnSend:Be,releaseAutoFollow:Ie,restoreSnapshot:fe,isPinned:ee,isFollowingProgrammatically:he,showScrollButton:Ce}=Qz({currentSessionId:n,currentSessionKey:f,sessionMessageCount:M,sessionIsWorking:O,isMobile:ne,onActiveTurnChange:xe}),Me=vU({sessionId:n,sessionKey:f,messages:_,historyMeta:Y,scrollRef:de,messageListRef:B,loadMoreMessages:m,goToBottom:Oe,releaseAutoFollow:Ie,isPinned:ee,showScrollButton:Ce}),Ze=h.useCallback(()=>{Oe("instant")},[Oe]),gt=rn()&&Me.historySignals.canLoadEarlier,we=Me.loadEarlier,re=h.useCallback(()=>{we({userInitiated:!0})},[we]);h.useEffect(()=>{ie.current=Me.handleActiveTurnChange},[Me.handleActiveTurnChange]);const ge=kU({sessionId:n,turnIds:Me.turnIds,activeTurnId:Me.activeTurnId,scrollToTurn:Me.scrollToTurn,scrollToMessage:Me.scrollToMessage,resumeToBottom:Me.resumeToBottomInstant}),pe=h.useCallback(oe=>{ge.scrollToTurnId(oe,{behavior:"smooth"})},[ge]),ke=Me.historySignals.canLoadEarlier,_e=!ne&&!G&&Me.turnIds.length>=2;h.useEffect(()=>{_e||se.getState().setPromptNavigatorPanelOpen(!1)},[_e]),h.useEffect(()=>{if(typeof window>"u"||!n)return;const oe=me=>{const Re=me;Re.detail?.sessionId&&Re.detail.sessionId!==n||Oe("instant")};return window.addEventListener(x5,oe),()=>{window.removeEventListener(x5,oe)}},[n,Oe]),h.useEffect(()=>{if(typeof window>"u"||!n||G)return;const oe=me=>{if(me.defaultPrevented||me.isComposing||me.key!=="ArrowUp"&&me.key!=="ArrowDown"||me.altKey||me.ctrlKey||me.metaKey||me.shiftKey)return;const{activeMainTab:Re}=se.getState();if(Re!=="chat"||LU())return;const We=de.current;if(AU(document.activeElement,We)||$m(me.target))return;me.preventDefault();const ct=me.key==="ArrowUp"?-1:1;ge.scrollByTurnOffset(ct,{resumePastEnd:!1})};return window.addEventListener("keydown",oe),()=>{window.removeEventListener("keydown",oe)}},[n,G,ge,de]),h.useLayoutEffect(()=>{const oe=de.current;if(!oe)return;const me=()=>{oe.style.setProperty("--chat-scroll-height",`${oe.clientHeight}px`)};me();let Re=0;const We=()=>{Re||(Re=requestAnimationFrame(()=>{Re=0,me()}))};if(typeof ResizeObserver>"u")return window.addEventListener("resize",We),()=>{Re&&cancelAnimationFrame(Re),window.removeEventListener("resize",We)};const ct=new ResizeObserver(We);return ct.observe(oe),()=>{Re&&cancelAnimationFrame(Re),ct.disconnect()}},[n,G,de]);const Te=h.useRef(null),ae=!!n&&(!!n&&!I||T.status==="loading"),te=h.useCallback(()=>{!e||!n||c.ensureSessionRenderable(n)},[e,n,c]);return h.useEffect(()=>{if(!e||!n||Te.current===f)return;const oe=typeof window<"u"&&window.location.hash.length>0;if(Te.current=f,oe){Ie();return}const me=()=>{fe()};typeof window>"u"?me():window.requestAnimationFrame(me)},[e,n,f,Ie,fe]),h.useEffect(()=>{!e||!n||I||p(n)},[e,n,p,I]),!n&&!J?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(wO,{isNewSession:!0})}):!n&&J?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:[ue&&!G?l.jsx(b5,{}):null,l.jsx("div",{className:R("relative z-10 flex min-h-0",G?"flex-1 bg-background":ue?"shrink-0 bg-background px-0":"flex-1 items-center justify-center bg-background px-0 pb-[6vh]"),children:l.jsx(ii,{scrollToBottom:Be})})]}):n?ae?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(V,{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(Ee,{variant:"outline",size:"sm",className:"mt-4",onClick:te,children:"Try again"})]})}),l.jsx("div",{className:_f(!1),children:l.jsx(ii,{scrollToBottom:Be})})]}):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:R("relative min-h-0 flex items-center justify-center",G?"absolute inset-0 opacity-0 pointer-events-none":"flex-1"),"aria-hidden":G,children:l.jsxs("div",{className:"flex flex-col items-center gap-3",children:[l.jsx($p,{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:_f(G),children:l.jsx(ii,{scrollToBottom:Be})})]}):_.length===0&&!O&&!L?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:[ue&&!G?l.jsx(b5,{}):null,l.jsx("div",{className:R("relative z-10 flex min-h-0",G?"flex-1 bg-background":ue?"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(Y0,{sessionId:n}),l.jsx(X0,{sessionId:n}),l.jsx(ii,{scrollToBottom:Be})]})}),l.jsx(J0,{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(Gb,{currentSessionId:n,currentSessionKey:f??n,isDesktopExpandedInput:G,isMobile:ne,directory:u,scrollRef:de,messageListRef:B,pendingRevealWork:Me.pendingRevealWork,renderedMessages:Me.renderedMessages,isLoadingOlder:Me.isLoadingOlder,sessionIsWorking:O,sessionAwaitingRecovery:L,awaitingPromptEcho:P,streamingMessageId:S,activeStreamingPhase:w,retryOverlay:U,compactionOverlay:q,handleMessageContentChange:Se,getAnimationHandlers:je,handleHistoryScroll:Me.handleHistoryScroll,scrollToBottom:Ze,isProgrammaticFollowActive:he,showLoadOlderButton:gt,onLoadOlder:re,turnIds:Me.turnIds,activeTurnId:Me.activeTurnId,onSelectTurn:pe,showPromptNavigator:_e,canLoadEarlierPrompts:ke,isLoadingOlderPrompts:Me.isLoadingOlder,onLoadEarlierPrompts:re}),l.jsxs("div",{className:_f(G),children:[!G&&_.length>0&&l.jsx(Pz,{visible:Me.showScrollToBottom,onClick:ge.resumeToLatest}),l.jsx(xO,{sessionId:n}),l.jsx(Y0,{sessionId:n}),l.jsx(X0,{sessionId:n}),l.jsx(ii,{scrollToBottom:Be})]}),l.jsx(J0,{sessionId:n}),l.jsx(bU,{open:y,onOpenChange:b,onScrollToMessage:Me.scrollToMessage,onScrollByTurnOffset:ge.scrollByTurnOffset,onResumeToLatest:Ze,canLoadEarlier:Me.historySignals.canLoadEarlier,isLoadingEarlier:Me.isLoadingOlder,onLoadEarlier:re,onRevert:async oe=>{if(!n)return;const me=oe.includes(":")?oe.split(":")[0]??oe:oe;await ve.getState().revertToMessage(n,me)},onFork:async oe=>{if(!n)return;const me=oe.includes(":")?oe.split(":")[0]??oe:oe;await ve.getState().forkFromMessage(n,me)}})]}):null},GU=e=>typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(100,Math.round(e))),KU=e=>e>=90?"critical":e>=75?"warn":"safe",aq=({percentage:e,size:t=18,stroke:n=3,className:r})=>{const s=GU(e),o=KU(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"})]})},YU=()=>{const e=se(n=>n.uiFont),t=se(n=>n.monoFont);return{uiFont:e,monoFont:t}},lq=h.memo(function({visible:t}){const[n,r]=h.useState(!1);if(z.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(V,{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(V,{name:n?"fullscreen-exit":"checkbox-blank",className:"h-3.5 w-3.5"})}),l.jsx("button",{type:"button",className:R(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(V,{name:"close",className:"h-4 w-4"})})]})}),k5=new Set,jf=new Map,XU=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace("%40","@").replace("%2F","/")}/files/${e.filePrefix}-latin-${t}-normal.woff2`,JU=(e,t)=>{const n=`${e.family}:${t}`;if(k5.has(n))return Promise.resolve();const r=jf.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(${XU(e,t)}) format('woff2')`,{style:"normal",weight:String(t),display:"swap"});document.fonts.add(s);const o=s.load().then(()=>{k5.add(n)}).catch(i=>{document.fonts.delete(s),console.warn(`Failed to load font: ${e.family} ${t}`,i)}).finally(()=>{jf.delete(n)});return jf.set(n,o),o},Kb=e=>e?Promise.all(e.weights.map(t=>JU(e,t))).then(()=>{}):Promise.resolve(),QU=e=>Kb(Nf[e]?.source),eZ=e=>Kb(Rf[e]?.source);function cq(){const{uiFont:e,monoFont:t}=YU();h.useEffect(()=>{if(typeof document>"u")return;const n=document.documentElement,r=Nf[e]?.stack??Nf[L7].stack,s=Rf[t]?.stack??Rf[N7].stack;QU(e),eZ(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{gd as $,Hp as A,Ee as B,Wp as C,bW as D,WZ as E,YU as F,QU as G,qe as H,V as I,$x as J,SW as K,_Z as L,EZ as M,ih as N,cE as O,$p as P,xk as Q,cq as R,M2 as S,TZ as T,qZ as U,dI as V,eW as W,oW as X,GZ as Y,KZ as Z,VZ as _,it as a,IZ as a$,PZ as a0,UZ as a1,DZ as a2,FZ as a3,Rr as a4,Ge as a5,S3 as a6,rr as a7,wx as a8,ft as a9,hO as aA,nW as aB,tW as aC,yt as aD,_t as aE,Ke as aF,wE as aG,xE as aH,aq as aI,Pk as aJ,yZ as aK,pD as aL,kd as aM,bZ as aN,QL as aO,mN as aP,zx as aQ,gN as aR,yN as aS,vN as aT,xN as aU,kW as aV,Sr as aW,w3 as aX,sa as aY,en as aZ,QZ as a_,ht as aa,Sx as ab,pt as ac,Cx as ad,ir as ae,U2 as af,mW as ag,WL as ah,Ar as ai,Hn as aj,vd as ak,xd as al,bd as am,wd as an,Bp as ao,eI as ap,Fn as aq,Sm as ar,h3 as as,pd as at,Wc as au,Uc as av,oq as aw,ys as ax,Id as ay,Zu as az,xS as b,uM as b$,MZ as b0,o3 as b1,ya as b2,Qg as b3,JI as b4,QI as b5,e_ as b6,t_ as b7,iq as b8,jW as b9,z3 as bA,xa as bB,eN as bC,mI as bD,OZ as bE,uZ as bF,Mx as bG,Ap as bH,fZ as bI,lq as bJ,Cr as bK,rc as bL,X8 as bM,kr as bN,vZ as bO,pZ as bP,AW as bQ,hN as bR,GU as bS,KU as bT,Dp as bU,co as bV,_E as bW,$j as bX,kZ as bY,ea as bZ,nk as b_,TW as ba,VA as bb,am as bc,Co as bd,sT as be,FA as bf,xv as bg,XZ as bh,Q_ as bi,YZ as bj,X_ as bk,JZ as bl,DC as bm,Wf as bn,ME as bo,Mp as bp,xZ as bq,sm as br,UT as bs,WT as bt,XL as bu,qf as bv,J3 as bw,SZ as bx,sn as by,On as bz,Ji as c,DN as c$,pM as c0,r3 as c1,CZ as c2,NZ as c3,Rp as c4,BW as c5,ZZ as c6,BI as c7,zI as c8,oN as c9,L2 as cA,O3 as cB,qL as cC,GL as cD,KL as cE,tN as cF,nN as cG,kE as cH,er as cI,pW as cJ,gW as cK,yW as cL,vW as cM,Lv as cN,mZ as cO,H4 as cP,MW as cQ,IW as cR,uf as cS,_W as cT,om as cU,hp as cV,Qc as cW,Dt as cX,w8 as cY,nv as cZ,EW as c_,$t as ca,_d as cb,aH as cc,df as cd,ba as ce,HF as cf,Lm as cg,JW as ch,Cd as ci,cx as cj,lx as ck,aW as cl,pT as cm,lW as cn,cW as co,dW as cp,iH as cq,uW as cr,CW as cs,Rx as ct,fW as cu,hW as cv,E2 as cw,T2 as cx,j2 as cy,A2 as cz,MS as d,ON as d0,Mj as d1,Gl as d2,L3 as d3,BZ as d4,MI as d5,t2 as d6,n2 as d7,Du as d8,$Z as d9,LW as dA,NW as dB,QW as dC,oV as dD,Ey as dE,hV as dF,eq as dG,tq as dH,nq as dI,rq as dJ,dV as dK,$H as dL,ob as dM,PW as dN,Hb as dO,wW as dP,hZ as dQ,wZ as dR,RZ as dS,sW as dT,iW as dU,xW as dV,zZ as da,BB as db,HD as dc,DH as dd,uy as de,sq as df,EB as dg,$F as dh,GW as di,KW as dj,VW as dk,OW as dl,HW as dm,FW as dn,RW as dp,sV as dq,zW as dr,UW as ds,ZW as dt,$W as du,YW as dv,DW as dw,qW as dx,WW as dy,XW as dz,XI as e,jZ as f,Je as g,ve as h,AZ as i,ES as j,gZ as k,oo as l,LZ as m,So as n,ph as o,Vn as p,ma as q,Fp as r,pa as s,Ne as t,rd as u,rW as v,bE as w,yd as x,HZ as y,_k as z};